Last active
March 12, 2018 00:04
-
-
Save Tiny-Giant/f9d3f31c208328a97c9e3d16d32f958a to your computer and use it in GitHub Desktop.
A prompt/confirm tic-tac-toe game using ES6
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
(() => { | |
"use strict"; | |
const game = () => { | |
let done; | |
const solutions = [ | |
[ 0, 1, 2 ], [ 0, 3, 6 ], [ 0, 4, 8 ], | |
[ 1, 4, 7 ], [ 2, 4, 6 ], [ 2, 5, 8 ], | |
[ 3, 4, 5 ], [ 6, 7, 8 ] | |
]; | |
const check = abc => abc.filter(e => board[e] !== ' ' | |
&& board[e] === board[abc[0]]) | |
.length === 3; | |
const win = (...args) => { | |
done = args; | |
}; | |
const board = new Proxy([...' '], { | |
set: (t, k, v) => { | |
if (t[k] === ' ') { | |
t[k] = v; | |
} else { | |
return false; | |
} | |
const correct = solutions.filter(e => e.includes(+k) && check(e)); | |
if (correct.length > 0) win(k, v, correct); | |
return true; | |
}, | |
get: (t, k) => { return t[k]; }, | |
}); | |
const render = message => { | |
const b = board; | |
return ` | |
${ message } | |
0: ${ b[0] } | 1: ${ b[1] } | 2: ${ b[2] } | |
3: ${ b[3] } | 4: ${ b[4] } | 5: ${ b[5] } | |
6: ${ b[6] } | 7: ${ b[7] } | 8: ${ b[8] }`; | |
}; | |
const play = (() => { | |
let turn = 0; | |
return () => { | |
if(done) { | |
const [k, v, correct] = done; | |
if(confirm(render(`${ v } won! play again?`))) { | |
game(); | |
} | |
return false; | |
} | |
if(turn > 8) { | |
if(confirm(render(`Game over, play again?`))) { | |
game(); | |
} | |
return false; | |
} | |
const value = ['X', 'O'][turn++ % 2]; | |
const index = prompt(render(`Player ${ value }, choose a space:`)); | |
if(index === null) { | |
if(confirm(render(`${ value } forfeit the game, play again?`))) { | |
game(); | |
} | |
return false; | |
} | |
if(!(index in board)) { | |
if(confirm(render(`${ index } is an invalid index, try again?`))) { | |
play(--turn); | |
} | |
return false; | |
} | |
try { | |
board[+index] = value; | |
play(); | |
} catch(e) { | |
if(confirm(render(`${ index } is occupied, choose again?`))) { | |
play(--turn); | |
} | |
} | |
}; | |
})(); | |
return play(); | |
}; | |
game(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment