K
K
krll-k2015-01-29 20:35:58
JavaScript
krll-k, 2015-01-29 20:35:58

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 positions
var advantagePosition = [
  [3,2,3],
  [2,4,2],
  [3,2,3]
];
,
3. Described the alternation of moves (later I added a check for the possibility of a move)
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]);
  }
};

4. Tested
(function(){
  render();
  move(1,1); //первый ход
  render();
  move(0,0); //второй ход
  move(0,0); //сообщение об ошибке
  move(0,0); //сообщение об ошибке
  render();
  move(2,2);
  render();
})();

Happened
["", "", ""]
["", "", ""]
["", "", ""]
["", "", ""]
["", "X", ""]
["", "", ""]
"ячейка уже занята!"
"ячейка уже занята!"
["O", "", ""]
["", "X", ""]
["", "", ""]
["O", "", ""]
["", "X", ""]
["", "", "X"]

5. I don’t know how to describe the victory, can someone tell me?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
krll-k, 2015-01-29
@krll-k

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 question

Ask a Question

731 491 924 answers to any question