井字游戏赢逻辑N×N个板 [英] TicTacToe win logic for NxN board
本文介绍了井字游戏赢逻辑N×N个板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当前逻辑正常工作与3x3的董事会,因为它是静态的。 我怎样才能将其转换成N×N的逻辑是什么?
Current logic works fine with 3x3 board because it is static. How can I convert it into NxN logic?
运逻辑的工作通过将行和列的正方形。
Win logic works by adding the row and column squares.
/*
* To determine a win condition, each square is "tagged" from left
* to right, top to bottom, with successive powers of 2. Each cell
* thus represents an individual bit in a 9-bit string, and a
* player's squares at any given time can be represented as a
* unique 9-bit value. A winner can thus be easily determined by
* checking whether the player's current 9 bits have covered any
* of the eight "three-in-a-row" combinations.
*
* 273 84
* \ /
* 1 | 2 | 4 = 7
* -----+-----+-----
* 8 | 16 | 32 = 56
* -----+-----+-----
* 64 | 128 | 256 = 448
* =================
* 73 146 292
*
*/
wins = [7, 56, 448, 73, 146, 292, 273, 84],
/*
* Returns whether the given score is a winning score.
*/
win = function (score) {
for (var i = 0; i < wins.length; i += 1) {
if ((wins[i] & score) === wins[i]) {
return true;
}
}
return false;
},
我的小提琴是这里
推荐答案
因此,以编程方式做到这一点,你可以使用类来跟踪哪些设置每个单元是,即ROW1或COL1:
So, to do it programatically, you can use classes to keep track of what "set" each cell is in, i.e. "row1" or "col1":
在我
/ Ĵ
创建循环:
cell.addClass('col' + j); // The cell is in column j
cell.addClass('row' + i); // The cell is in row i
if (i == j) {
cell.addClass('dia0'); // The cell is in the down/right diagonal
}
if (j == SIZE - i - 1) {
cell.addClass('dia1'); // The cell is in the up/right diagonal
}
然后,在赢()
,传中的最后一个单元格点击。对于每个类的小区属于,检查是否细胞与含有类数 X
(或 0
)是等于表大小:
Then, in win()
, pass in the last cell clicked. For each class the cell belongs to, check if the number of cells with that class containing X
(or O
) is equal to the table size:
win = function (clicked) {
// Get all of the classes this cell belongs to
var memberOf = clicked[0].className.split(/\s+/);
// Check elements with the same class, and see if they contain "turn", i.e. X or O
for (var i=0; i<memberOf.length; i++) {
var testClass = '.'+memberOf[i];
// If the number of elements containing "turn" == SIZE,
// we have a winning condition
if( $('#tictactoe').find(testClass+':contains('+turn+')').length == SIZE) {
return true;
}
}
return false;
},
这篇关于井字游戏赢逻辑N×N个板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文