Creating a Basic Tic Tac Toe Game with AngularJS in JavaScript

Posted by

Simple Tic Tac Toe Game using AngularJS in JavaScript

Simple Tic Tac Toe Game using AngularJS in JavaScript

{{ cell }}

{{ ctrl.message }}

angular.module(‘ticTacToeApp’, [])
.controller(‘ticTacToeController’, function() {
var ctrl = this;

ctrl.board = [
[”, ”, ”],
[”, ”, ”],
[”, ”, ”]
];

ctrl.currentPlayer = ‘X’;
ctrl.message = ‘Player ‘ + ctrl.currentPlayer + ”s turn’;

ctrl.makeMove = function(row, col) {
if (ctrl.board[row][col] === ”) {
ctrl.board[row][col] = ctrl.currentPlayer;
if (ctrl.checkWin(row, col)) {
ctrl.message = ‘Player ‘ + ctrl.currentPlayer + ‘ wins!’;
} else if (ctrl.checkDraw()) {
ctrl.message = ‘It’s a draw!’;
} else {
ctrl.currentPlayer = (ctrl.currentPlayer === ‘X’ ? ‘O’ : ‘X’);
ctrl.message = ‘Player ‘ + ctrl.currentPlayer + ”s turn’;
}
}
};

ctrl.checkWin = function(row, col) {
var symbols = [‘X’, ‘O’];
for (var i = 0; i < symbols.length; i++) {
var symbol = symbols[i];
var rowWin = true;
var colWin = true;
var diag1Win = true;
var diag2Win = true;
for (var j = 0; j < 3; j++) {
if (ctrl.board[row][j] !== symbol) {
rowWin = false;
}
if (ctrl.board[j][col] !== symbol) {
colWin = false;
}
if (ctrl.board[j][j] !== symbol) {
diag1Win = false;
}
if (ctrl.board[j][2 – j] !== symbol) {
diag2Win = false;
}
}
if (rowWin || colWin || diag1Win || diag2Win) {
return true;
}
}
return false;
};

ctrl.checkDraw = function() {
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
if (ctrl.board[i][j] === '') {
return false;
}
}
}
return true;
};

ctrl.resetGame = function() {
ctrl.board = [
['', '', ''],
['', '', ''],
['', '', '']
];
ctrl.currentPlayer = 'X';
ctrl.message = 'Player ' + ctrl.currentPlayer + ''s turn';
};
});