【发布时间】:2021-12-04 07:39:19
【问题描述】:
我正在用 c (windows) 制作一个 ASCII 艺术游戏,但由于某种原因,当我玩它时,它总是以明显随机的间隔闪烁,而且大部分时间我什么都看不到。谁能解释为什么或如何解决它?
这是我的代码:
const int WIDTH = 20, HEIGTH = 5;
const int AREA = (WIDTH) * HEIGTH;
const int gl = HEIGTH - 2; //Ground level
const float delta = 0.1f; //Frame rate
char scr[AREA]; //String for displaying stuff
char input;
int posx = 10, posy = gl - 1; //Player position
int vel = 0; //player velocity
while(1)
{
//TODO: player input
for(i = 0; i < AREA; i++) //Rendering part
{
if(i % WIDTH == 0 && i != 0)
{
scr[i] = '\n';
continue;
}
if(floor(i / WIDTH) >= gl) //i is on ground
{
scr[i] = '.';
continue;
}
scr[i] = ' ';
}
//Set player position
scr[posy * WIDTH + posx + 1] = '@';
scr[(posy + 1) * WIDTH + posx + 1] = '@';
system("cls");// Clear terminal
printf(scr);// Print screen
usleep(delta * 1000);//Sleep
}
输出:
@
..........@........
...................►↓@
它可以工作,但它会闪烁......
【问题讨论】:
-
如果您希望其他人能够重现您的问题,您可能需要考虑提供minimal reproducible example,其中包括函数
main和所有#include指令。 -
我猜用户将能够在
scr上写他的名字(或其他一些东西),所以请不要printf(scr);,这是一种不好的做法,因为它不安全。用户可以使用"%n"泄漏地址甚至写入他不应该写入的内存。我会使用puts或者如果您坚持使用printf_s... -
您可以考虑使用Console Functions API 或Console Virtual Terminal Sequences,而不是使用
system("cls");。请注意,后者需要最新的 Windows 10 或 11,它不适用于 Windows 7。 -
或者另一种选择是终端功能库;在 Windows 上有 pdcurses。