summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTinWoodman92 <chrhodgden@gmail.com>2024-01-14 20:53:20 -0600
committerTinWoodman92 <chrhodgden@gmail.com>2024-01-14 20:53:20 -0600
commit3abed3973308c7cb7f2258d4b5633a41527b4d00 (patch)
tree403addc36742a9d21d490fbada89d1f61f599fdb
parente4816e7eeee4f498e358a0c5e0ca5b286c63b6ba (diff)
added vitory check
-rw-r--r--app.js49
-rw-r--r--index.html1
2 files changed, 49 insertions, 1 deletions
diff --git a/app.js b/app.js
index b804185..29fd993 100644
--- a/app.js
+++ b/app.js
@@ -6,6 +6,47 @@ const boardTurn = function() {
console.log('clicked', this.id, this.bitBoard);
};
+const checkVictory = function() {
+ let checkSum = 0;
+ let victory = false;
+ const rows = [
+ //rows
+ [0, 1, 2],
+ [3, 4, 5],
+ [6, 7, 8],
+ //columns
+ [0, 3, 6],
+ [1, 4, 7],
+ [2, 5, 8],
+ //diagonals
+ [0, 4, 8],
+ [2, 4, 6]
+ ];
+ const xBoard = this.bitBoard.slice(0, 9);
+ const oBoard = this.bitBoard.slice(9, 18);
+ let checkRow = [];
+
+ rows.forEach(row => {
+ checkRow = xBoard.filter((_, index) => row.includes(index));
+ checkSum = checkRow.reduce((acc, value) => acc + value, 0);
+ if (checkSum == 3) {
+ victory = true;
+ board.victory_row = row;
+ };
+ checkRow = oBoard.filter((_, index) => row.includes(index));
+ checkSum = checkRow.reduce((acc, value) => acc + value, 0);
+ if (checkSum == 3) {
+ victory = true;
+ board.victory_row = row;
+ };
+ });
+ board.victory = victory;
+ if (victory) {
+ board.victor = board.turn;
+ };
+ return(victory);
+};
+
const squareClick = function() {
console.log('clicked', this.id, this.innerText, this.position);
if (this.innerText == '') {
@@ -15,6 +56,11 @@ const squareClick = function() {
let pos = 9 * (this.board.turn==turns[false]);
pos += this.position - 1
this.board.bitBoard[pos] = 1;
+ //check victory
+ this.board.checkVictory();
+ if (this.board.victory) {
+ console.log(`${this.board.victor} wins!!!`);
+ };
//Switch player turn
this.board.turn = turns[this.board.turn==turns[false]]
};
@@ -31,8 +77,9 @@ const initBoard = function(board) {
board.addEventListener('click', boardTurn);
board.turn = turns[true];
board.bitBoard = Array(18).fill(0);
+ board.checkVictory = checkVictory;
};
const board = document.getElementById('board');
-initBoard(board); \ No newline at end of file
+initBoard(board);
diff --git a/index.html b/index.html
index c11b476..b124bd9 100644
--- a/index.html
+++ b/index.html
@@ -4,6 +4,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tit Tac Toe</title>
<link rel="stylesheet" href="style.css">
+ <script src="https://cdn.jsdelivr.net/npm/mathjs@9.0.0/lib/browser/math.js"></script>
<script defer src="app.js"></script>
</head>
<body>