gpt4 book ai didi

C++控制台游戏输入&&刷新函数

转载 作者:搜寻专家 更新时间:2023-10-31 00:21:51 25 4
gpt4 key购买 nike

我正在编写一个小型主机冒险游戏,但遇到了一些问题。
1. 输入有点滞后,我正在使用 while 循环 ( while(getch() == 'w') )。第一次按下某个键后,什么也没有发生(你必须按下它 2 次)并且如果你切换方向(按下 A/D/S 键)它在第一次也没有反应。如果你拿着 key ,它工作正常。这怎么能解决?
2.这是我用来刷新游戏的功能(按下按键时渲染游戏场景):

    void refresh(char map[Y][X])
{
system("cls");
for (int i = 0; i<UP; i++)
{
cout<<endl;
}
for (int i = 0; i<Y; i++)
{
for (int k = 0; k<LEFT; k++)
{
cout<<" ";
}
for (int j = 0; j<X; j++)
{
cout<<map[i][j];
}
cout<<endl;
}
}

当我使用这个功能一次时,没问题,但是当他们多次按下或按住这些键时 - 游戏区域开始闪烁。我认为我只需要重绘该字段的一部分(进行更改/完成移动的位置),而不是整个字段。你能提供任何想法如何做到这一点吗?

输入示例代码:

while(getch() == 'w')
{
if (map[y-1][x]!= WALL)
{
map[y-1][x] = CHARACTER;
map [y][x] = ' ';
y--;
refresh(map);
Sleep(SPEED); // this is unnecessary, SPEED is 0, I just kept it for tests
}
}

基本上,主要功能如下所示:

int main()
{
(...) Variables (...)
generateMap(FROM FILE);
refresh(); // First initialization of the field
while (getch() != 'q') // While not quitting
{
while(getch() == 'w')
{
if (THE FIELD ABOVE IS NOT OCCUPIED)
{
setSomeVariables();
refresh(THE GAMEFIELD);
}
}
}
while(getch() == 's')
{
if (THE FIELD BELOW IS NOT OCCUPIED)
{
setSomeVariables();
refresh(THE GAMEFIELD);
}
}
}
while(getch() == 'a')
{
if (THE FIELD ON THE LEFT IS NOT OCCUPIED)
{
setSomeVariables();
refresh(THE GAMEFIELD);
}
}
}
while(getch() == 'd')
{
if (THE FIELD ON THE RIGHT IS NOT OCCUPIED)
{
setSomeVariables();
refresh(THE GAMEFIELD);
}
}
}
return 0;
}

最佳答案

不要使用 system("cls"),它真的很慢,而是使用以下代码将光标设置在屏幕的开头:

COORD cur = {0, 0};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cur);

您应该在循环中只调用一次 getch(),如下所示:

char key;

do
{
key = getch();

if(key == 'w')
{
//do something
}

//the other if statements

}while(key != 'q');

关于C++控制台游戏输入&&刷新函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4041308/

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