I am currently working on a simple snake game in C using the curses library. However, when I compile and execute the code to test if the snake marked 'S' would move, the terminal only displays a blank screen. I'm not sure what is causing this issue and I would like to fix it first.
So here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
#include <unistd.h>
/* Define constants for height and width of the rectangle */
#define HEIGHT 20
#define WIDTH 60
/* Variables */
int gameover, x, y, fruitx, fruity, flag;
/* Function to position the fruit */
void position()
{
gameover = 0;
x = HEIGHT/2;
y = WIDTH/2;
fruitx = rand() % HEIGHT;
fruity = rand() % WIDTH;
}
/* Function to draw a rectangle with specified height and width */
void boundary(int h, int w)
{
int i, j;
for (i = 0; i <= h; i++) /* Rows */
{
for (j = 0; j <= w; j++) /* Columns */
{
if (i == 0 || i == h || j == 0 || j == w)
{
printf("#");
}
else
{
if (i == x && j == y)
{
printf("S");
}
else if (i == fruitx && j == fruity)
{
printf("F");
}
else
{
printf(" ");
}
}
}
printf("\n");
}
}
/* Set movement */
void keyboard()
{
int ch;
switch(getch())
{
case KEY_UP:
flag = 1;
break;
case KEY_DOWN:
flag = 2;
break;
case KEY_RIGHT:
flag = 3;
break;
case KEY_LEFT:
flag = 4;
break;
}
if (x < 0 || x >= HEIGHT || y < 0 || y >= WIDTH)
{
gameover = 1;
}
}
/* Commands and logic of the program */
void logic()
{
switch(flag)
{
case 1:
y--;
break;
case 2:
y++;
break;
case 3:
x++;
break;
case 4:
x--;
break;
}
}
int main() {
// Initialize curses
initscr();
raw();
keypad(stdscr, TRUE);
noecho();
curs_set(FALSE);
// Game loop
while (!gameover)
{
clear(); // Clear the screen
boundary(HEIGHT, WIDTH); // Draw the game boundary and snake
keyboard(); // Handle keyboard input
logic(); // Update snake position
refresh(); // Refresh the screen
// Add a small delay for smooth movement
//usleep(100000);
}
// Clean up curses
endwin();
return 0;
}
I compiled it using:
gcc snake.c -o snake -lncurses
What could be causing the blank terminal screen issue when running my C code with the curses library? Are there any common mistakes or additional steps I need to take to properly display the snake game?
Any insights, suggestions, or guidance would be greatly appreciated. Thank you in advance for your help!