TIC TAC TOE WIN条件检查具有可变网格大小的检查
对于TIC-TAC-toe游戏,我有一个2D的可变长度。数组中的每个条目都对应于网格中的正方形,并且可以具有0(空)1(x)或2(o)的值。
我正在写一种方法来检查任何一个播放器是否有一个并返回true,如果是的,但无法弄清楚该怎么做。当前的实现将所有内容与“锚点”进行了比较,该“锚点”对于行,列和对角线略有不同。
这是我当前的方法(仅检查行):
public static boolean hasWon(int[][] gridStatus){
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
if (gridStatus[row][col]!=gridStatus[row][0]){
}
}
}
任何帮助将不胜感激。
I have a 2d array of variable length for a tic-tac-toe game. Each entry in the array corresponds to a square in the grid and can have a value of 0 (empty) 1(X) or 2(O).
I'm writing a method to check if EITHER player has one and return true if so but can't figure out how to do so. The current implementation compares everything to an "anchor point" that is slightly different for rows, columns, and diagonals.
here is my current method (only checks rows):
public static boolean hasWon(int[][] gridStatus){
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
if (gridStatus[row][col]!=gridStatus[row][0]){
}
}
}
any help would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我最近做了一个3x3 TIC TAC TOE,但是我的
Haswon()
方法是通用的,在您的情况下应该有效。我的演示的codesandbox链接:
I recently made a 3x3 Tic Tac Toe but my
hasWon()
method is generic and should work in your case.Codesandbox Link for my Demo : Tic Tac Toe Demo
我假设在您的网格中,1表示X,2表示O和0表示没有人。
我想到的是tic tac脚趾,所以让我们把这个想法纳入程序。这是一条行,让您可以将播放器处于任何位置:
现在我们可以编写返回行,列和对角线的实现行实现的方法。
这是一种将所有线路列入网格中的方法:
一种看谁赢得一线赢的方法:
最后,很容易找出谁在抽奖的情况下赢了,或者如果没有人赢,则零。
I am assuming that in your grid, 1 means X, 2 means O and 0 means nobody.
I think of tic tac toe in terms of lines, so let's put that idea into the program. Here is a line that let's you get the player at any position:
Now we can write methods that return Line implementations for rows, columns and diagonals.
and a method to get all the lines in the grid:
And a method to see who won in a line:
Then finally it is easy to find out who won in the case of a draw, or zero if nobody won.
我认为您可以通过控制每种可能的获胜方式和他们的结果来检查玩家是否赢了。另外,我将传递您的检查方法,以确定玩家是否赢了。
通过使用流,您可以大大减少代码长度并使其更具可读性。
这是一个示例项目,用于测试上述代码:
https://www.jdoodle.com/iembed /v0/rv3
I think you could check if a player has won or not by controlling each possible way of winning and the OR-ing their result. Also, I would pass to your checking method the player's value to establish if the player has won or not.
By using streams, you can drastically reduce the code length and make it much more readable.
Here is a sample project to test the code above:
https://www.jdoodle.com/iembed/v0/rv3