Skip to content

Instantly share code, notes, and snippets.

@JJTech0130
Created July 29, 2021 12:52
Show Gist options
  • Save JJTech0130/f82f0ca551dce5c733a547fa3bd9ffdb to your computer and use it in GitHub Desktop.
Save JJTech0130/f82f0ca551dce5c733a547fa3bd9ffdb to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>
Tic-Tac-Toe
</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}
.row div {
padding: 10px;
border: 1px solid black;
height: 30px;
width: 30px;
float: left;
}
.row {
clear: both;
}
</style>
</head>
<body>
<h1>Tic-Tac-Toe</h1>
<div>
<div class="row">
<div id="0_0" onclick="place(this)"></div>
<div id="1_0" onclick="place(this)"></div>
<div id="2_0" onclick="place(this)"></div>
</div>
<div class="row">
<div id="0_1" onclick="place(this)"></div>
<div id="1_1" onclick="place(this)"></div>
<div id="2_1" onclick="place(this)"></div>
</div>
<div class="row">
<div id="0_2" onclick="place(this)"></div>
<div id="1_2" onclick="place(this)"></div>
<div id="2_2" onclick="place(this)"></div>
</div>
</div>
<script>
var currentPlayer = "O";
var won = false;
function place(box) {
if (box.innerText != "" || won) return;
box.innerText = currentPlayer;
checkGameBoard();
currentPlayer == "O" ? currentPlayer = "X" : currentPlayer = "O";
}
function checkGameBoard() {
for (let i = 0; i <= 2; i++) {
checkWinner(getDiv("0_" + i),
getDiv("1_" + i),
getDiv("2_" + i));
checkWinner(getDiv(i + "_0"),
getDiv(i + "_1"),
getDiv(i + "_2"));
}
checkWinner(getDiv("0_0"),
getDiv("1_1"),
getDiv("2_2"));
checkWinner(getDiv("0_2"),
getDiv("1_1"),
getDiv("2_0"));
}
function getDiv(id) {
return document.getElementById(id).innerText;
}
function checkWinner(first, second, third) {
if (first != "" && first == second && first == third) {
win();
}
}
function win() {
won = true;
alert("Winner: " + currentPlayer);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment