Created
July 16, 2015 22:16
-
-
Save alex-wilmer/39fa2e267e6416df177e to your computer and use it in GitHub Desktop.
Tic Tac Toe Click Event Scope: State
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
clicks.onValue((() => { | |
let states = [ init ] | |
$(`reset`).click(() => { | |
states = [ init ] | |
$(`cell, message`).html(``) | |
}) | |
return event => { // observe click stream | |
const cell = event.target.dataset // clicked cell | |
if (!states[states.length - 1][+cell.x][+cell.y]) { | |
states.push( // push modified state | |
states[states.length - 1].map((row, index) => { | |
if (index === +cell.x) { | |
return changeListValue( | |
row, +cell.y, switchPlayer(total(states[states.length - 1])) | |
) | |
} | |
else return row | |
}) | |
) | |
// draw X or O | |
$(`[data-x='${cell.x}'][data-y='${cell.y}']`).html( | |
`<div class="center"> | |
${!total(states[states.length - 1]) ? `O` : `X`} | |
</div>` | |
) | |
if (states.length > 5) { // minimum number of moves to win | |
const last = states[states.length - 1] | |
if (Math.abs(sumDiagonalLR(last)) === 3 | |
|| Math.abs(sumDiagonalRL(last)) === 3 | |
|| mapReduceSum(last).some(n => Math.abs(n) === 3) | |
|| sumVertical(last).some(n => Math.abs(n) === 3)) { | |
$(`message`).html( | |
`<div> | |
${!total(last) ? `O wins!` : `X wins!`} | |
</div>` | |
) | |
} | |
else if (states.length === 10) { | |
$(`message`).html( | |
`<div>Cat's game!</div>` | |
) | |
} | |
} | |
} | |
} | |
}())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment