连接4 - 通过遍历数组

时间:2017-07-01 17:18:49

标签: javascript

我正在写一个连接4游戏,我正在尝试实现代码以检查是否有人赢了。

我有一个这样的数组,但是更长,总共42个元素。它表示Connect 4网格的坐标和颜色。

var arr = [{xcoordinate:60, ycoordinate:55, color:"W"}]; // W is white, R is Red and Y is Yellow

此数组包含可以获胜的所有列,行和对角线(如果连续4种颜色或更多颜色,我们仍需要计数器计数):

var wins = new Array();
wins[0]  = new Array(0, 7,  14, 21, 28, 35);
wins[1]  = new Array(1, 8,  15, 22, 29, 36);
wins[2]  = new Array(2, 9,  16, 23, 30, 37);
wins[3]  = new Array(3, 10, 17, 24, 31, 38);
wins[4]  = new Array(4, 11, 18, 25, 32, 39);
wins[5]  = new Array(5, 12, 19, 26, 33, 40);
wins[6]  = new Array(6, 13, 20, 27, 34, 41);
wins[7]  = new Array(0,   1,  2,  3,  4,  5,  6);
wins[8]  = new Array(7,   8,  9, 10, 11, 12, 13);
wins[9]  = new Array(14, 15, 16, 17, 18, 19, 20);
wins[10] = new Array(21, 22, 23, 24, 25, 26, 27);
wins[11] = new Array(28, 29, 30, 31, 32, 33, 34);
wins[12] = new Array(35, 36, 37, 38, 39, 40, 41);
wins[13] = new Array(14, 22, 30, 28);
wins[14] = new Array(7, 15, 23, 31, 39);
wins[15] = new Array(0, 8, 16, 24, 32, 40);
wins[16] = new Array(1, 9, 17, 25, 33, 41);
wins[17] = new Array(2, 10, 18, 26, 34);
wins[18] = new Array(3, 11, 19, 27);
wins[19] = new Array(20, 26, 32, 38);
wins[20] = new Array(13, 19, 25, 31, 37);
wins[21] = new Array(6,  12, 18, 24, 30, 36);
wins[22] = new Array(5,  11, 17, 23, 29, 35);
wins[23] = new Array(4,  10, 16, 22, 28);
wins[24] = new Array(3,   9, 15, 21);

我遍历wins数组的方式是否存在任何问题。我得到了一些不可预测的行为......"未捕获的类型错误:无法读取属性' c'未定义"

    var currentColor = "Y" // This is currently yellow but would change after each turn
    var counter = 0;

    // Outer array
    for(i=0; i<wins.length; i++)
    {
        // Inner array
        for(j=0; j<wins[j].length; j++)
        {
                // Inner array starting at a different point each time
                for(k=j; k<wins[j].length; k++)
                {   
                    if((arr[wins[i][k]].color)===currentColor)
                    {
                        counter++;
                        if(counter==4)
                        {
                            alert(currentColor + " has won");
                        }
                        break;
                    }
                    else
                    {
                        counter=0;
                        break;
                    }
                }
        }
    }

0 个答案:

没有答案