Answer the question
In order to leave comments, you need to log in
Faced a difficulty in the process of describing the game of tic-tac-toe in JavaScript: how to implement a check for winning?
1. Created a two-dimensional array startPosition
var startPosition = [
['','',''],
['','',''],
['','','']
];
, 2. Introduced the concept of priority positionsvar advantagePosition = [
[3,2,3],
[2,4,2],
[3,2,3]
];
, var player = 1;
var move = function(j,k){
if(startPosition[j][k] !== ''){
console.log('ячейка уже занята!');
}
else if(player++ % 2){
startPosition[j][k] = 'X';
}
else{
startPosition[j][k] = 'O';
}
return true;
};
var render = function(){
for(var i=0; i<3; i++){
console.log(startPosition[i]);
}
};
(function(){
render();
move(1,1); //первый ход
render();
move(0,0); //второй ход
move(0,0); //сообщение об ошибке
move(0,0); //сообщение об ошибке
render();
move(2,2);
render();
})();
["", "", ""]
["", "", ""]
["", "", ""]
["", "", ""]
["", "X", ""]
["", "", ""]
"ячейка уже занята!"
"ячейка уже занята!"
["O", "", ""]
["", "X", ""]
["", "", ""]
["O", "", ""]
["", "X", ""]
["", "", "X"]
Answer the question
In order to leave comments, you need to log in
for(i=0; i<3; i++) /* проверка строк */
if(matrix[i][0]==matrix[i][1] &&
matrix[i][0]==matrix[i][2]) return matrix[i][0];
for(i=0; i<3; i++) /* проверка столбцов */
if(matrix[0][i]==matrix[1][i] &&
matrix[0][i]==matrix[2][i]) return matrix[0][i];
/* проверка диагоналей */
if(matrix[0][0]==matrix[1][1] &&
matrix[1][1]==matrix[2][2])
return matrix[0][0];
if(matrix[0][2]==matrix[1][1] &&
matrix[1][1]==matrix[2][0])
return matrix[0][2];
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question