【发布时间】:2015-01-24 05:51:29
【问题描述】:
标题非常具有描述性。基本上,我在 C++ 的控制台窗口中制作 Space Invaders,它被称为 ASCII Invaders。除了一个主要问题,我似乎让游戏中的所有内容都运行良好,_getch 正在暂停程序。我调用 _kbhit 检查玩家是否正在输入玩家输入,如果是,我使用 _getch 获取密钥并正确操作。玩家左/右移动就好了,但是当玩家按下“空格”或射击时,程序会暂停,直到你再次按下“空格”,此时它也会射击。
显然玩家不希望在游戏中出现这种情况。所以很想知道如何解决它。这里是它的名字:
/***************************************/
/* move_player(); */
/* Calculates player movement */
/*Returns weather or not toQuitTheGame */
/***************************************/
bool move_player()
{
bool ret = false;
//If a key is pressed
if (_kbhit())
{
//Get key
_getch();
int key = _getch();
//Check is the player moves left
if (key == LEFT && object_handle.player_obj.x > 0)
{
//Move left
object_handle.player_obj.x -= 1;
}
//Check is the player moves right
if (key == RIGHT && object_handle.player_obj.x < 79)
{
//Move right
object_handle.player_obj.x += 1;
}
//Check is the player is shooting
if (key == SHOOT)
{
//shoot by creating the bullet above the player
object_handle.bullet_obj.x = object_handle.player_obj.x;
object_handle.bullet_obj.y = object_handle.player_obj.y - 1;
object_handle.bullet_obj.active = true;
}
//Weather or not to kill the program
if (key == VK_ESCAPE)
{
ret = true;
}
else
{
ret = false;
}
}
return ret;
}
作为旁注,如果您只是滚动浏览并思考“这是很多代码......我不想处理这个。” (我有时会这样做 - 不是在挑剔你)请注意这不是很多,我只是使用了很多 cmets 和很多空白。
如果你想知道,这里是整个“main”函数。
int main()
{
bool quit = false;
object_handle.set_info();
//Display main manu
menu();
//Main game loop
while(!quit)
{
//Update past object variables
object_handle.xy_update();
//Calculate player movements
quit = move_player();
//Calculate bullet movements
handle_objects();
//Finally, update the screen
screen_update();
//DEBUG CODE
debug();
//Display score/stats
stats();
//Wait a given time before continuing the loop
Sleep(INTERVAL);
}
cout << "\n\n\n\n\nBye" << endl;
Sleep(1000);
return 0;
}
我已经包含了所有正确的库,没有编译错误。
哦,是的,在我忘记之前。以下是常量:
/******************CONSTANTS********************/
const int ENEMY_COUNT = 15;
const int INTERVAL = 250;
const int LEFT = 75;
const int RIGHT = 77;
const int SHOOT = VK_SPACE;
const int BULLET_SPEED = 8;
/***********************************************/
非常感谢任何帮助!
【问题讨论】:
-
你为什么要调用 _getch() 两次?
-
您必须调用它两次才能接收箭头键,但您可以检测到它并且只能有条件地执行此操作。如in this question/answer 所述,使用 ReadConsoleInput 可能会更好。