运行基于诅咒的贪吃蛇游戏时出现空白终端屏幕

问题描述 投票:0回答:1

我目前正在使用 Curses 库用 C 语言开发一个简单的蛇游戏。然而,当我编译并执行代码来测试标记为“S”的蛇是否会移动时,终端仅显示空白屏幕。我不确定是什么导致了这个问题,我想先解决它。
所以这是代码:

#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;
}

我使用以下方法编译它:

gcc snake.c -o snake -lncurses

使用curses 库运行我的C 代码时,可能会导致空白终端屏幕问题的原因是什么?是否有任何常见错误或需要采取额外步骤才能正确显示贪吃蛇游戏?

任何见解、建议或指导将不胜感激。预先感谢您的帮助!

c ncurses
1个回答
0
投票

一般来说,你不应该将 stdio (

printf()
) 与诅咒混合在一起。如果将 printf 调用更改为
printw()
,将渲染正方形。 (我还建议将
usleep()
延迟(如果未注释)替换为对 Curses 自己的
napms()
函数的等效调用(只需将参数除以 1000)。)

© www.soinside.com 2019 - 2024. All rights reserved.