Created
May 4, 2014 17:38
-
-
Save sjkillen/5d6e856664de9c5e9f76 to your computer and use it in GitHub Desktop.
Tic Tac Toe
This file contains hidden or 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
<script> | |
"use strict"; | |
this.TicTacToe=(function(){ | |
var Error=(function(){ | |
var errors=new Map([ | |
["error-not-found",new (function errorNotFound(){message:"error not found!"})] | |
["value-input",new TypeError(["Invalid GridSquare value"])], | |
["square-not-empty",new TypeError(["Square full"])] | |
]); | |
return function(string){ | |
if (!errors.has(string)){ | |
throw errors.get('error-not-found'); | |
} | |
return errors.get(string); | |
} | |
}()); | |
var GridSquare=(function(){ | |
function f(){ | |
this.value=" "; | |
} | |
f.prototype.fill=function(v){ | |
var lowerV; | |
if (this.value!==" "){ | |
throw new Error('square-not-empty'); | |
} | |
else if ((lowerV=v.toLowerCase())!=='x' && lowerV!=='o'){ | |
throw new Error('value-input'); | |
} | |
else{ | |
this.value=lowerV; | |
} | |
} | |
return f; | |
}()); | |
var grid; | |
var reset=function(){ | |
grid=[ | |
[new GridSquare,new GridSquare,new GridSquare], | |
[new GridSquare,new GridSquare,new GridSquare], | |
[new GridSquare,new GridSquare,new GridSquare], | |
]; | |
}; | |
var turn; | |
var randomTurn=function(){ | |
if (Math.random()>.5) {turn="x";} | |
else {turn='o';} | |
} | |
reset(); | |
randomTurn(); | |
return { | |
newGame:function(){ | |
reset(); | |
randomTurn(); | |
console.info(turn.toUpperCase()+"'s turn"); | |
}, | |
go:function(x,y){ | |
grid[x-1][y-1].fill(turn); | |
this.print(); | |
if (turn='x') {turn='o';} | |
else {turn='x';} | |
}, | |
print:function(){ | |
console.log('['+grid[0][0].value+']['+grid[0][1].value+']['+grid[0][2].value+']'); | |
console.log('['+grid[1][0].value+']['+grid[1][1].value+']['+grid[1][2].value+']'); | |
console.log('['+grid[2][0].value+']['+grid[2][1].value+']['+grid[2][2].value+']'); | |
console.info(turn.toUpperCase()+"'s turn"); | |
}, | |
whosTurn:function(){console.info(turn.toUpperCase()+"'s turn");} | |
}; | |
}()); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment