C ++如果其他两个语句在不应该执行时执行

时间:2019-04-22 18:39:05

标签: c++

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

#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;
}

我希望其他箭头会像使用箭头键时那样被跳过,但是我无法一生搞清楚为什么它会执行两个语句。我敢肯定解决方案很简单,但任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:0)

我设法通过将_getch()替换为_getwch()来解决此问题。显然_getwch()可以返回更多不同的值,因此似乎可以解决我遇到的问题。

答案 1 :(得分:0)

在您的主要活动中,您有一个if循环,包含3种可能的条件。 1,按键是控制键。 2,键是作弊键。 3,否则。最后,您无需检查它是否为退出键,因此在退出键上始终会打印“ Invalid Key”。