游戏逻辑问题
我正在制作一个圈和十字游戏(井字游戏),在我的逻辑类中,我用一个二维数组表示游戏的状态,但这就是问题所在,我像这样检查数组,
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,您只需添加一个检查是否设置了值:
In that case you just have to add a check if a value is set:
让我惊讶的一件事是......为什么你使用整数而不是类来表示这个? 确实,这是一个简单的游戏,但 Piece 类似乎是一个相当明显的类。
另外,对于 int 你确实有 3 个状态,大概是这样的:
所以你应该在费心检查它们是否相同的值之前检查 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:
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!