首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >连接四个游戏检查Wins JS

连接四个游戏检查Wins JS
EN

Stack Overflow用户
提问于 2015-10-17 00:22:05
回答 2查看 8.5K关注 0票数 3

我正在忙着我的第一个完整的程序,两个星期的编程在我的腰带下,已经遇到了一个路障,我似乎无法弄清楚。我正在制作一个连接4游戏,并且已经开始在JavaScript中构建逻辑,然后再推进到DOM。我已经开始使用构造函数创建的单元格对象,然后将其以2D数组的形式推入游戏对象中。我已经成功地创建了一个函数,每次播放,并使用一个2天数组在该列的最低点更改单元格的值。然而,我不知道如何得到我的检查,以确保wins功能的运作。

到目前为止,我的逻辑是,对于2D数组中的每个点,您可以按行、列和对角进行检查。我理解如何检查win的逻辑,但不知道如何按行和列遍历数组。在下面的示例中,this.cellsArray是理事会构造函数中的单元对象数组。该数组有7个列数组,每列6行,因为我翻转了典型的行列逻辑,以说明Connect 4的基于列的性质。但是,我不能像this.cellsArraycol那样访问数组,因为没有定义col和row,我也不知道如何定义索引值?任何帮助都将不胜感激!

连接4

示例:

代码语言:javascript
复制
//array location is equal to an instance of this.cellsArray[col][row]
Board.prototype.checkRowRight = function (arrayLocation) {

    if ((arrayLocation[i+1][i].value === arrayLocation.value) && (arrayLocation[i+2][i]=== arrayLocation.value)  && (arrayLocation[i+3][i].value === arraylocation.value)){
        this.winner = this.currentPlayer;
        this.winnerFound = true;
        console.log('Winner has been found!')
    }
};
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-10-17 03:59:13

引用我找到的这里的逻辑并重构获胜的行检测代码,可以很容易地将其转换为Javascript,如下所示:

代码语言:javascript
复制
function chkLine(a,b,c,d) {
    // Check first cell non-zero and all cells match
    return ((a != 0) && (a ==b) && (a == c) && (a == d));
}

function chkWinner(bd) {
    // Check down
    for (r = 0; r < 3; r++)
        for (c = 0; c < 7; c++)
            if (chkLine(bd[r][c], bd[r+1][c], bd[r+2][c], bd[r+3][c]))
                return bd[r][c];

    // Check right
    for (r = 0; r < 6; r++)
        for (c = 0; c < 4; c++)
            if (chkLine(bd[r][c], bd[r][c+1], bd[r][c+2], bd[r][c+3]))
                return bd[r][c];

    // Check down-right
    for (r = 0; r < 3; r++)
        for (c = 0; c < 4; c++)
            if (chkLine(bd[r][c], bd[r+1][c+1], bd[r+2][c+2], bd[r+3][c+3]))
                return bd[r][c];

    // Check down-left
    for (r = 3; r < 6; r++)
        for (c = 0; c < 4; c++)
            if (chkLine(bd[r][c], bd[r-1][c+1], bd[r-2][c+2], bd[r-3][c+3]))
                return bd[r][c];

    return 0;
}

还有一个测试电话:

代码语言:javascript
复制
x =[ [0, 0, 0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0, 0, 0],
     [0, 0, 0, 1, 1, 0, 0],
     [0, 0, 0, 1, 1, 0, 0],
     [0, 0, 1, 2, 2, 2, 0],
     [0, 1, 2, 2, 1, 2, 0] ];
alert(chkWinner(x));

当与董事会一起调用时,chkWinner函数将返回第一个(并且仅假设每个移动只改变一个单元格,并且在每次移动之后检查)获胜的玩家。

这样做的目的基本上是把支票限制在那些有意义的地方。例如,当检查右边的单元格(请参见第二个循环)时,只需检查从最左边的四列0-6中的每一列开始的每一行0-3

这是因为从其他地方开始,在找到一个可能的胜利之前,会从董事会的右边跑掉。换句话说,列集{0,1,2,3}{1,2,3,4}{2,3,4,5}{3,4,5,6}将是有效的,但{4,5,6,7}不会(这七个有效的列是0-6)。

票数 6
EN

Stack Overflow用户

发布于 2020-08-17 07:10:22

这是一个旧的线程,但我将把我的解决方案放到混合中,因为这将显示为“如何计算connect4 win javascript”的顶级搜索结果。

我通过使用矩阵加法来解决这个问题。

假设您的游戏板作为2D数组存储在内存中,如下所示:

代码语言:javascript
复制
   [ [0, 0, 0, 0, 0, 0, 0],
     [0, 0, Y, 0, 0, 0, 0],
     [0, 0, Y, 0, 0, 0, 0],
     [0, 0, R, 0, 0, 0, 0],
     [0, 0, Y, 0, 0, 0, 0],
     [0, 0, R, R, R, 0, 0] ];

在每个“硬币掉头”上,您应该调用一个传递硬币x/y位置的函数。

这就是你计算用户是否赢了比赛的地方。

代码语言:javascript
复制
let directionsMatrix = {
  vertical: { south: [1, 0], north: [-1, 0] },
  horizontal: { east: [0, 1], west: [0, -1] },
  backward: { southEast: [1, 1], northWest: [-1, -1] },
  forward: { southWest: [1, -1], northEast: [-1, 1] },
};

注:矩阵符号中的"South“是[1,0],意思是"Down 1单元格,右0单元格”

现在,我们可以循环遍历每个Axis/Direction,以检查一行中是否有4。

代码语言:javascript
复制
  const playerHasWon = (colnum, rowNum, playerColor, newGrid) => {
    //For each [North/South, East/West, NorthEast/Northwest, SouthEast/Southwest]
    for (let axis in directionsMatrix) {
      // We difine this variable here so that "East" and "West" share the same count,
      // This allows a coin to be dropped in a middle cell
      let numMatches = 1;

      // For each [North, South]
      for (let direction in directionsMatrix[axis]) {
        // Get X/Y co-ordinates of our dropped coin
        let cellReference = [rowNum, colnum];

        // Add co-ordinates of 1 cell in test direction (eg "North")
        let testCell = newGrid[cellReference[0]][cellReference[1]];

        // Count how many matching color cells are in that direction
        while (testCell == playerColor) {
          try {
            // Add co-ordinates of 1 cell in test direction (eg "North")
            cellReference[0] += directionsMatrix[axis][direction][0];
            cellReference[1] += directionsMatrix[axis][direction][1];
            testCell = newGrid[cellReference[0]][cellReference[1]];

            // Test if cell is matching color
            if (testCell == playerColor) {
              numMatches += 1;

              // If our count reaches 4, the player has won the game
              if (numMatches >= 4) {
                return true;
              }
            }
          } catch (error) {
            // Exceptions are to be expected here.
            // We wrap this in a try/catch to ignore the array overflow exceptions
            // console.error(error);
            break;
          }
        }
        // console.log(`direction: ${direction}, numMatches: ${numMatches}`);

        // If our count reaches 4, the player has won the game
        if (numMatches >= 4) {
          return true;
        }
      }
    }

    // If we reach this statement: they have NOT won the game
    return false;
  };

如果您希望看到完整的代码,这里有一个指向github回购的链接。

这里有一个指向现场演示的链接

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33181356

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档