gpt4 book ai didi

C++ If Else 两个语句都在不应该执行的时候执行

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:38:57 24 4
gpt4 key购买 nike

<分区>

所以我正在尝试用 C++ 创建一个贪吃蛇游戏。大多数情况下都有效,但是我正在尝试实现作弊模式,当激活时蛇会缩小到其原始大小并且不会因撞墙等而失去游戏。我遇到的问题是当按下作弊键时它正确地执行了“else if”,但随后也直接执行了“else”。当按下箭头键时,else 会被正确跳过,只有当按下作弊键时才会出现这种情况。

#include <iostream> 
#include <iomanip>
#include <conio.h>
#include <cassert>
#include <string>
#include <sstream>
#include <vector>
using namespace std;

//constants
const int UP(72); //up arrow
const int DOWN(80); //down arrow
const int RIGHT(77); //right arrow
const int LEFT(75); //left arrow
const char QUIT('Q'); //to end the game
const char CHEAT('C'); //to activate cheat mode

int main()
{
//protoypes
bool isArrowKey(const int k);
bool isCheatKey(const int k);
bool wantsToQuit(const int k);
int getKeyPress();

string message = "";

//body
system("CLS");
int key; //current key selected by player
do {
key = getKeyPress(); //read in selected key: arrow or letter command
if (isArrowKey(key))
{
}
else if (isCheatKey(key))
{
message = "cheat on";
}
else
{
message = "INVALID KEY!"; //set 'Invalid key' message
}
} while (!wantsToQuit(key)); //while user does not want to quit
return 0;
}

// additional needed functions
int getKeyPress()
{ //get key or command selected by user
//KEEP THIS FUNCTION AS GIVEN
int keyPressed;
keyPressed = _getch(); //read in the selected arrow key or command letter
while (keyPressed == 224) //ignore symbol following cursor key
keyPressed = _getch();
return keyPressed;
}

bool isArrowKey(const int key)
{
return (key == LEFT) || (key == RIGHT) || (key == UP) || (key == DOWN);
}

bool isCheatKey(const int key)
{ //check if the user wants to cheat (when key is 'C' or 'c')
return toupper(key) == CHEAT;
}

bool wantsToQuit(const int key)
{ //check if the user wants to quit (when key is 'Q' or 'q')
return toupper(key) == QUIT;
}

我希望 else 像使用箭头键时那样被跳过,但我终究无法弄清楚为什么它会执行这两个语句。我确信解决此问题的方法非常简单,但我们将不胜感激。

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