I gave up after I realised that the way I was doing it would make it almost impossible to figure out when someone had got 3 in a row.
Feel free to use any of this code for anything. It's in the Public Domain now.
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>TickTackToe</title> | |
<link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet"> | |
<style> | |
html { | |
height: 100%; | |
} | |
body { | |
margin: 0 auto; | |
max-width: 30em; | |
background-color: #efefef; | |
height: 90%; | |
font-family: 'Ubuntu', 'IBM Plex Sans', 'Helvetica', sans-serif; | |
} | |
div#grid { | |
width: 100%; | |
height: 100%; | |
} | |
div#grid button { | |
text-align: center; | |
width: 30%; | |
height: calc(100% - 85%); | |
padding: 1%; | |
margin: 1%; | |
color: #000; | |
background-color: #fff; | |
border: 1px solid #000; | |
font-size: 3em; | |
} | |
div#grid button:hover { | |
background-color: #000; | |
color: #fff; | |
} | |
.x { | |
color: blue !important; | |
} | |
.o { | |
color: red !important; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>TickTackToe</h1> | |
<p><span id="turn"><span class="x">X</span></span>'s turn.</p> | |
<div id="grid"> | |
<button id="b1-1"> </button><button id="b1-2"> </button><button id="b1-3"> </button> | |
<button id="b2-1"> </button><button id="b2-2"> </button><button id="b2-3"> </button> | |
<button id="b3-1"> </button><button id="b3-2"> </button><button id="b3-3"> </button> | |
</div> | |
<script src="ttt.js"></script> | |
</body> | |
</html> |
let turn = 0; | |
document.getElementById('grid').addEventListener('click', function(ev) { | |
if (ev.target.id.indexOf('b') !== -1) { | |
buttonClick(ev.target.id); | |
} | |
}); | |
function buttonClick(id) { | |
const e = document.getElementById(id); | |
if (e.innerHTML == ' ') { | |
if (turn == 0) { | |
e.className += 'x'; | |
e.innerHTML = 'X'; | |
turn = 1; | |
} else if (turn == 1) { | |
e.className += 'o'; | |
e.innerHTML = 'O'; | |
turn = 0; | |
} | |
} | |
upTurn(); | |
} | |
function upTurn() { | |
const te = document.getElementById('turn'); | |
if (turn == 0) { | |
te.innerHTML = '<span class="x">X</span>'; | |
} else if (turn == 1) { | |
te.innerHTML = '<span class="o">O</span>'; | |
} | |
} |