我正在尝试创建一个矩阵来表示可伸缩棋盘游戏中的对角线选项,其中行数和列数由玩家定义。游戏的目标是击败你的对手连接一个由玩家定义的可变长度的一串。
我创建了水平和垂直矩阵来表示电路板,使用循环将行推入相应的矩阵,但是,我无法动态创建对角线规则。
这些对角线阵列的目的是检查胜利条件。即X,X,X,X。我已经在数组中给出了垂直数组中索引值的元素,用于检测。
以下是我需要的4 X 4电路板的示例;
verticalArray = [
['0,0', '1,0', '2,0', '3,0'],
['0,1', '1,1', '2,1', '3,1'],
['0,2', '1,2', '2,2', '3,2'],
['0,3', '1,3', '2,3', '3,3']
];
diagonalArray = [
['2,0', '3,1'],
['1,0', '2,1', '3,2'],
['0,0', '1,1', '2,2', '3,3'],
['0,1', '1,2', '2,3'],
['0,1', '1,3']
];
此时我只能使用Javascript / jQuery。
答案 0 :(得分:0)
做你的大脑会做什么:选择一个起点(在这种情况下是7或10)并按照对角线。 (我猜你想要从右上角到左下角,但这是家庭作业。)
var verticalArray = [
['A1', 'B1', 'C1', 'D1'],
['A2', 'B2', 'C2', 'D2'],
['A3', 'B3', 'C3', 'D3'],
['A4', 'B4', 'C4', 'D4']
];
var W = verticalArray[0].length;
var H = verticalArray.length;
// Starting points (coordinates, not values)
var starts = [];
// Top line: A1-D1
for (var i=0; i<W; i++) {
starts.push([i, 0]);
}
// Left line: A2-A4 (already have A1)
for (var i=1; i<H; i++) {
starts.push([0, i]);
}
// Right line: D2-D4 (already have D1)
// @todo
console.log(starts);
// [[0,0], [1,0], [2,0], [3,0], [0,1], [0,2], [0,3]]
var validCoord = function(C) {
return C[0] >= 0 && C[0] < W && C[1] < H;
};
var getDiag = function(start, dx) {
var C = [start[0], start[1]]; // copy
var diag = [];
// Keep moving until coord isn't valid anymore (ie. outside grid)
while (validCoord(C)) {
diag.push(verticalArray[C[1]][C[0]]);
C[0] += dx; // One to the left/right
C[1] += 1; // One down
}
return diag;
};
var diagonalArray = [];
starts.forEach(function(start) {
var diag;
// For this starting point, move down+right as far as possible
diag = getDiag(start, 1);
diag.length > 1 && diagonalArray.push(diag);
// For this starting point, move down+left as far as possible
diag = getDiag(start, -1);
diag.length > 1 && diagonalArray.push(diag);
});
console.log(diagonalArray);
// [["A1","B2","C3","D4"], ["B1","C2","D3"], ["B1","A2"], ["C1","D2"], ["C1","B2","A3"], ["D1","C2","B3","A4"], ["A2","B3","C4"], ["A3","B4"]]
更多解释
getDiag()
跟随对角线,左侧或右侧(dx
为delta x
表示左侧(-1
)或右侧(1
)) dx
中的starts.forEach
@todo
并更新了所有评论。[x, y]
数组,它可能会变得更具可读性,因为C[0] >= 0 && C[0] < W && C[1] < H
几乎不像C.x >= 0 && C.x < W && C.y < H
IMO那样可读