游戏逻辑问题

发布于 2024-07-16 04:12:50 字数 408 浏览 6 评论 0原文

我正在制作一个圈和十字游戏(井字游戏),在我的逻辑类中,我用一个二维数组表示游戏的状态,但这就是问题所在,我像这样检查数组,

 if(gameModel[0][0] == gameModel[1][1] && gameModel[0][0] == gameModel[2][2]){
     return true;
    }
 if(gameModel[2][0] == gameModel[1][1] && gameModel[2][0] == gameModel[0][2]){
     return true;
    }

以此类推检查所有 8 个条件,但是,该数组在开始时使用所有值 0 进行初始化,因此它总是找到三个匹配的值,我如何解决这个问题而不必更改整个代码

谢谢

i am making a noughts and crosses game (tic tac toe) and in my logic class i represent the state of the game with a 2d array, but this is the problem, im checking the array like so

 if(gameModel[0][0] == gameModel[1][1] && gameModel[0][0] == gameModel[2][2]){
     return true;
    }
 if(gameModel[2][0] == gameModel[1][1] && gameModel[2][0] == gameModel[0][2]){
     return true;
    }

and so on for all 8 conditions, however, the array is initialised with all values of 0 at the beginning, so it always finds three matching values, how can i get round this problem without having to change the whole of my code

thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

宛菡 2024-07-23 04:12:50

在这种情况下,您只需添加一个检查是否设置了值:

if (   gameModel[0][0] == gameModel[1][1] 
    && gameModel[0][0] == gameModel[2][2] 
    && gameModel[0][0] != 0) {
 return true;
}

In that case you just have to add a check if a value is set:

if (   gameModel[0][0] == gameModel[1][1] 
    && gameModel[0][0] == gameModel[2][2] 
    && gameModel[0][0] != 0) {
 return true;
}
惯饮孤独 2024-07-23 04:12:50

让我惊讶的一件事是......为什么你使用整数而不是类来表示这个? 确实,这是一个简单的游戏,但 Piece 类似乎是一个相当明显的类。

另外,对于 int 你确实有 3 个状态,大概是这样的:

0 = empty
1 = X
2 = Y

所以你应该在费心检查它们是否相同的值之前检查 0 (空),它会更快(谁真正在乎,这不需要更快),并更具逻辑意义(正方形是空的吗?如果是,则不必费心检查正方形是否具有相同的值)。

即使是像这样简单的事情,尤其是当你刚刚开始时,也要尝试拥抱 OOP,这是一种不同的思维方式,并且需要练习,所以尽可能多地练习!

One thing that jumps out at me with this is... why are you using ints instead of a class to represent this? True this is a simple game, but a Piece class seems to jump out as a fairly obvious class to have.

Also, with int you really have 3 states, presumably something like:

0 = empty
1 = X
2 = Y

So you should check for 0 (empty) before bothering to check for if they are the same value, it will be quicker (who really cares though, this doesn't need to be fast), and make more logical sense (is the square empty? if so then do not bother checking if the squares hold the same values).

Even for simple things like this, especially when you are just starting out, try to embrace OOP, it is a different way of thinking, and it takes practice, so practice as much as you can!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文