gpt4 book ai didi

更改背景颜色会使程序出错? (诅咒)

转载 作者:太空宇宙 更新时间:2023-11-04 04:39:42 25 4
gpt4 key购买 nike

所以我有一个用 ncurses 制作的基本“贪吃蛇”游戏。

添加时

start_color();
init_color(COLOR_BLUE, 0, 0, 0);
init_pair(1, COLOR_WHITE, COLOR_BLUE);
bkgd(COLOR_PAIR(1));

为了改变背景颜色,程序进入无限循环。调试告诉我程序在生成食物时停止。这是代码:

void generate_food(food *food, int nrows, int ncols, snake *snake) {
srand(time(NULL));
int validLocation = 0;

do {
food->x = rand() % nrows;
food->y = rand() % ncols;
if ( mvinch(food->x, food->y) == ' ' )
validLocation = 1;
}
while (!validLocation);
move(food->x, food->y);
addch('*');
}

它检查随机位置是否为空 (== ' '),如果是,则在其中放置一个 '*'。

在我更改 bkgd 之前工作完美。它停在 do-while 处,就好像窗口中没有空白空间一样。知道为什么吗?

最佳答案

ncurses中,mvinch不只是返回字符,它返回一个chtype,其中包含字符信息,还有属性和颜色信息。这意味着为了将它与字符进行比较,您必须从 chtype 中提取字符信息。

为此,ncurses 提供了几个位掩码。从联机帮助页:

   Attributes       The following bit-masks may be AND-ed with characters returned by winch.       A_CHARTEXT     Bit-mask to extract character       A_ATTRIBUTES   Bit-mask to extract attributes       A_COLOR        Bit-mask to extract color-pair field information

In short, if you set a background color to your window, mvinch will never return ' '. Instead, you could use:

if (mvinch(food->x, food->y) & A_CHARTEXT == ' ')

另见 man mvinch

关于更改背景颜色会使程序出错? (诅咒),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27549591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com