简体   繁体   English

Javascript Connect 4游戏,检查获胜者

[英]Javascript Connect 4 game, checking a winner

I am trying to make a Connect 4 game using Javascript. 我正在尝试使用Javascript制作Connect 4游戏。 So I began trying to search the horizontal for 4 in a row and made up this: 因此,我开始尝试在水平方向连续搜索4个,并进行以下补充:

for (var y = 0; y < Column - 1; y++)
  for (var x = 0; x < Row - 1; x++)
    if (myArray1[y][x] == 1){
           Win1++;
           if (Win1 == 4){
              alert("Won");
              }
        } else {Win1 = 0}

I got it working when only checking 1 row, but when I added a second for loop to also check the columns it stopped working. 当我只检查1行时,我就开始工作了,但是当我添加了第二个for循环来也检查了它停止工作时,它就工作了。

My intention is to run this (And code for checking vertical and diagonal) everytime I place down a piece. 我的意图是每次我放下一块时都运行此代码(以及用于检查垂直和对角线的代码)。

As pointed out by @LuanNico in the comments, you need to reset your counter variable Win1 before each row or column. 正如@LuanNico在评论中指出的那样,您需要在每一行或每一列之前重置计数器变量Win1

If your Column and Row variables hold the number of columns and rows, you might also have a one-off error by stopping your loop iteration one row or column too early. 如果您的ColumnRow变量保存了列和行的数量,则过早停止循环迭代一行或一列,可能还会出现一次性错误。

I recommend to fix and reorganize your code a little bit as follows: 我建议对代码进行一些修复和重组,如下所示:

 function checkColums(board, columns, rows) { for (var y = 0; y < columns; y++) { var consecutive = 0; for (var x = 0; x < rows; x++) { if (board[y][x] == 1) { consecutive++; if (consecutive == 4) { return true; } } } } return false; } function checkRows(board, columns, rows) { for (var x = 0; x < rows; x++) { var consecutive = 0; for (var y = 0; y < columns; y++) { if (board[y][x] == 1) { consecutive++; if (consecutive == 4) { return true; } } } } return false; } // Example: var board = [ [1, 0, 1, 0], [0, 1, 1, 0], [1, 0, 1, 1], [1, 1, 1, 0] ]; console.log(checkColums(board, 4, 4)); // false console.log(checkRows(board, 4, 4)); // true 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM