3 回答

TA贡献1852条经验 获得超1个赞
int[][] winner = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}};
当有赢家时,这都是所有可能的情况。前 3 个是水平的,接下来的 3 个是垂直的,最后 2 个是对角的,其中的数字是这样定义的,在前面的代码中表示:
0 | 1 | 2
---+---+---
3 | 4 | 5
---+---+---
6 | 7 | 8
那么我们来分析一下核心代码:
for (int[] columnWinner : winner) { // traverses all cases
if ( // if there is a case satisfied
// for a specified case for example {0, 1, 2}
playerChoices[columnWinner[0]] == playerChoices[columnWinner[1]] && // check if choice at 0 is the same as choice at 1
playerChoices[columnWinner[1]] == playerChoices[columnWinner[2]] && // check if choice at 1 is the same as choice at 2
// then choice at 0 1 2 are the same
playerChoices[columnWinner[0]] != Player.NO // and this "the same" is not "they are all empty"
) {
// then there is a winner

TA贡献1803条经验 获得超6个赞
我假设您正在询问 for each 循环:
for (int[] columnWinner : winner) {
该循环称为 for each 循环,它创建一个变量并为循环中的每次迭代赋予一个值。
在这种情况下,循环为井字棋棋盘上每个可能的行、列和对角线创建一个名为 columnWinner 的长度为 3 的数组。
每次循环时,它都会检查该人是否赢得了验证 columnWinner 数组中的所有三个元素是否相同:
if (playerChoices[columnWinner[0]] == playerChoices[columnWinner[1]] && playerChoices[columnWinner[1]] == playerChoices[columnWinner[2]]
然后检查以确保它们已填写,而不是空的。
&& playerChoices[columnWinner[0]] != Player.NO) {

TA贡献1820条经验 获得超9个赞
3 x 3 板由一维数组表示(相当奇怪)。所有获胜位置都是手动确定的,并winner
以三倍的形式列在数组中,因为在井字游戏中占据一个获胜位置需要 3 个标记。
您指示的循环依次检查每个获胜位置。
例如,考虑获胜位置{1, 4, 7}
。if 语句检查棋盘位置 1、4、7 的值是否相同,并且不等于表示没有人在那里玩过的“NO”值。
实际winners
数据结构为(3 元素)数组的数组;因此 for 循环一次获取每个 3 元素数组并使用它来驱动“if”语句。例如,when columnWinner
is {1, 4, 7}
thencolumnWinner[0]
是 4,因此playerChoices[columnWinner[0]]
正在查看playerChoices[4]
。
添加回答
举报