Last active
September 19, 2015 20:56
-
-
Save kevincolten/1064ab287ca7e6f984fc to your computer and use it in GitHub Desktop.
Tic Tac Toe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var prompt = require('prompt'); | |
prompt.start(); | |
var board = [ | |
[' ', ' ', ' '], | |
[' ', ' ', ' '], | |
[' ', ' ', ' '], | |
[' ', ' ', ' '] | |
]; | |
var playerTurn = 'X'; | |
function printBoard() { | |
console.log(board[0].join(' | ')); | |
console.log('---------'); | |
console.log(board[1].join(' | ')); | |
console.log('---------'); | |
console.log(board[2].join(' | ')); | |
} | |
function horizontalWin() { | |
return (board[0][0] === playerTurn && board[0][1] === playerTurn && board[0][2] === playerTurn) || | |
(board[1][0] === playerTurn && board[1][1] === playerTurn && board[1][2] === playerTurn) || | |
(board[2][0] === playerTurn && board[2][1] === playerTurn && board[2][2] === playerTurn); | |
} | |
function verticalWin() { | |
return (board[0][0] === playerTurn && board[1][0] === playerTurn && board[2][0] === playerTurn) || | |
(board[0][1] === playerTurn && board[1][1] === playerTurn && board[2][1] === playerTurn) || | |
(board[0][2] === playerTurn && board[1][2] === playerTurn && board[2][2] === playerTurn); | |
} | |
function diagonalWin() { | |
return (board[0][0] === playerTurn && board[1][1] === playerTurn && board[2][2] === playerTurn) || | |
(board[2][0] === playerTurn && board[1][1] === playerTurn && board[0][2] === playerTurn); | |
} | |
function checkForWin() { | |
if ( horizontalWin() || verticalWin() || diagonalWin() ) { | |
console.log('Player ' + playerTurn + ' Won!'); // announce to the world | |
printBoard(); // show the board for bragging rights | |
return true; | |
} | |
return false; | |
} | |
function placeMark(row, column) { | |
board[row][column] = playerTurn; | |
} | |
function getPrompt() { | |
printBoard(); | |
console.log("It's Player " + playerTurn + "'s turn."); | |
prompt.get(['row', 'column'], function (error, result) { | |
placeMark(parseInt(result.row, 10), parseInt(result.column, 10)); | |
if (checkForWin()) { | |
return; | |
} | |
playerTurn = playerTurn === 'X' ? 'O' : 'X'; | |
getPrompt(); | |
}); | |
} | |
getPrompt(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment