Today I will show a simple source code with two functions.
This source code will try to read from a file named level.txt a string like this: 101010100000011111101110101010101 and show empty spaces and square ASCII based on this string.
You can compile this source code from a file named screen.c like this:
1 2 | [mythcat@fedora GUI]$ gcc -o screen screen.c -lncurses [mythcat@fedora GUI]$ ./screen |
Let’s see the source code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | #include <ncurses.h> #include <stdio.h> #include <limits.h> // Get number of chars on terminal int get_max_chars() { int max_chars = COLS * LINES; if (max_chars < 0) { max_chars = INT_MAX; } return max_chars; } // Get the area of terminal int get_square_ascii() { int max_chars = get_max_chars(); if (max_chars >= 255) { // Full block character for large terminals return 219; } else { // Medium shade block character for smaller terminals return 178; } } int main() { FILE *file = fopen("level.txt", "rb"); if (file == NULL) { fprintf(stderr, "Failed to open file\n"); return 1; } // Initialize ncurses initscr(); // Hide the cursor curs_set(0); // Init values and variables int y = 0; int x = 0; int value; int max_chars = get_max_chars(); int square_ascii = get_square_ascii(); while ((value = fgetc(file)) != EOF && x < max_chars) { if (value == '0') { // Display a space for 0 value mvprintw(y, x, " "); } else if (value == '1') { // Display the appropriate square character for 1 value, use tty terminal // else you will see something like this: � � � � mvaddch(y, x, square_ascii); } // Increement values for all area of terminal with x and y x++; if (x >= COLS) { x = 0; y++; } } // Close the file fclose(file); // Update the screen refresh(); // Wait for user input getch(); // Clean up ncurses endwin(); return 0; } |