Created
July 15, 2018 12:03
-
-
Save M3kH/87df17bc56fe28e2b1f95aa540186c41 to your computer and use it in GitHub Desktop.
TicTacToe
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
<html> | |
<head> | |
<title>Tic Tac Toe!</title> | |
</head> | |
<body> | |
<div> | |
<span> | |
<input name="" type="text" value="-" size="1"/> | |
</span> | |
<span> | |
<input name="" type="text" value="-" size="1"/> | |
</span> | |
<span> | |
<input name="" type="text" value="-" size="1"/> | |
</span> | |
</div> | |
<div> | |
<span> | |
<input name="" type="text" value="-" size="1"/> | |
</span> | |
<span> | |
<input name="" type="text" value="-" size="1"/> | |
</span> | |
<span> | |
<input name="" type="text" value="-" size="1"/> | |
</span> | |
</div> | |
<div> | |
<span> | |
<input name="" type="text" value="-" size="1"/> | |
</span> | |
<span> | |
<input name="" type="text" value="-" size="1"/> | |
</span> | |
<span> | |
<input name="" type="text" value="-" size="1"/> | |
</span> | |
</div> | |
<script> | |
const gameLogicValidation = [ | |
[0, 1, 2], | |
[3, 4, 5], | |
[6, 7, 8], | |
[0, 3, 6], | |
[1, 4, 7], | |
[2, 5, 8], | |
[0, 4, 8], | |
[2, 4, 6] | |
] | |
function validateGame(game) { | |
if ( Array.isArray(game) === false || game.length !== 9) { | |
console.log('This is not a valid game'); | |
return; | |
} | |
for (let k = 0; k < gameLogicValidation.length; k++) { | |
let currentRule = gameLogicValidation[k]; | |
if( game[currentRule[0]] === 1 && | |
game[currentRule[1]] === 1 && | |
game[currentRule[2]] === 1 ) { | |
return 1; | |
} | |
if( game[currentRule[0]] === 2 && | |
game[currentRule[1]] === 2 && | |
game[currentRule[2]] === 2 ) { | |
return 2; | |
} | |
} | |
return 0; | |
} | |
const inputs = document.querySelectorAll('input'); | |
function getStatusGame() { | |
const board = []; | |
for(let i = 0; i < inputs.length; i++) { | |
if (inputs[i].value === '-') board.push(0); | |
if (inputs[i].value === 'X') board.push(1); | |
if (inputs[i].value === 'O') board.push(2); | |
} | |
return board; | |
} | |
for(let i = 0; i < inputs.length; i++) { | |
const input = inputs[i]; | |
input.addEventListener('change', function() { | |
console.log('Something Change', input.value); | |
if ( input.value === 'X' || input.value === 'O' ) { | |
input.setAttribute('disable', 'disable'); | |
const statusGame = getStatusGame(); | |
const status = validateGame(statusGame); | |
if (status) { | |
console.log('Game is finish'); | |
console.log(`Winner is player ${status}`); | |
return; | |
} | |
} else { | |
input.value = '-'; | |
} | |
}); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment