【问题标题】:Declared enum and IF on its elements在其元素上声明枚举和 IF
【发布时间】:2024-04-13 05:15:05
【问题描述】:

我正在开发 Snake 游戏。虽然我有一点小问题。我创建了带有可能方向的枚举:

    enum Direction{
    n = 0, // north
    e = 1, // east
    s = 2, // south
    w = 3 // west
};

然后我创建了一个 ChangeDirection() 函数,它会根据之前的方向改变它。 (比如往右/东,不能切换到左/西):

void ChangeDirection(char key){
    switch (key){
    case 'w':
        if (Direction != 2)
            Direction = 0;
        break;
    case 'd':
        if (Direction != 3)
            Direction = 1;
        break;
    case 's':
        if (Direction != 0)
            Direction = 2;
        break;
    case 'a':
        if (Direction != 1)
            Direction = 3;
        break;
    }

但我的 if 显然行不通;出现以下错误:

'!=' 标记之前的预期主表达式

有人可以帮忙吗?我怎样才能重新安排它工作?为什么它不起作用?谢谢!

【问题讨论】:

  • 您的Direction 实例在哪里?
  • Direction类型名称 而不是变量。您需要一个Direction 类型的变量
  • 我已经创建了变量Direction dir;,然后将dir 插入到ifs,但还是不行。好像我不知道如何使用枚举,但我觉得我在这里需要它们:(

标签: c++ if-statement enums comparison


【解决方案1】:
Direction CurrentDir = e; // somewhere in the code

// ....

//another place in the code, so on..

CurrentDir = s; 

//....



void ChangeDirection(char key){
    switch (key){
    case 'w':
        if (CurrentDir != s)
            CurrentDir = n;
        break;
    case 'd':
        if (CurrentDir != w)
            CurrentDir = e;
        break;
   // so on ..
    }

【讨论】: