在連接4中檢查4行的最佳方法是什麼?在javascript中連接4個算法
我不會複製代碼的陣列,但它基本上是長度42的陣列,每個陣列元件將X,Y位置圖和彩色
var board_array = [{x:60, y:55, c:"Red"}, // ... and so on
和看起來像這樣:
起初,我採取這種方式。這裏有所有不同的可能的方式有人可以贏得比賽。這還不是全部在一排位置的可能4,但所有的不同的方式的人可以贏得垂直,水平和垂直方向 - 你仍然需要使用某種形式的嵌套的循環
// Winning vertically
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);
// Winning horizontally
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);
// Winning diagonally, left to right
wins[13] = new Array(14, 22, 30, 38);
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);
//Winning diagonally, right to left
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);
檢查如果你覺得board_array作爲這個:
//0 1 2 3 4 5 6
//7 8 9 10 11 12 13
//14 15 16 17 18 19 20
//21 22 23 24 25 26 27
//28 29 30 31 32 33 34
//35 36 37 38 39 40 41
我用了3層for循環和一個計數器來檢查wins陣列反對board_array但無濟於事。我只是想知道是否有更簡單的方法。
我的方法是通過放置令牌循環。對於每一個令牌,我都向左邊3,右邊3,上邊3,下邊3以及每個方向的對角線3看。我會檢查它們是否都是相同的顏色。 –
如果你得到的數組超出界限類型的錯誤 – jimbo123
你將不得不檢查出界。從簡單的事情開始,例如只檢查是否有垂直勝利。然後將該邏輯應用於水平。然後對角線。 –