From 6f23323aa256dfb2138659c873bb38d15acbbb6a Mon Sep 17 00:00:00 2001 From: atchutchi <> Date: Tue, 16 May 2023 14:10:36 +0000 Subject: [PATCH] Add in function computer move so that machine look choose winning move --- assets/js/scripts.js | 47 +++++++++++++++++++++++++------------------- 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/assets/js/scripts.js b/assets/js/scripts.js index 1bf4170..f7c8d48 100644 --- a/assets/js/scripts.js +++ b/assets/js/scripts.js @@ -80,32 +80,39 @@ function handleCellClick(event) { // Adapted from code by lando464 on CodePen: https://codepen.io/lando464/pen/BPGEKO function computerMove() { - var emptyCells = []; - var random; + var emptyCells = []; + var random; - for (var i = 0; i < board.length; i++) { - if (board[i] == '') { - emptyCells.push(i); + for (var i = 0; i < board.length; i++) { + if (board[i] == '') { + emptyCells.push(i); + } } + +// Check for winning moves +for (var i = 0; i < winningCombinations.length; i++) { + var combination = winningCombinations[i]; + var foundWinner = true; + for (var j = 0; j < combination.length; j++) { + if (board[combination[j]] != currentPlayer) { + foundWinner = false; + break; + } } - - random = Math.floor(Math.random() * emptyCells.length); - board[emptyCells[random]] = currentPlayer; - document.getElementById(`cell${emptyCells[random] + 1}`).textContent = currentPlayer; - - // Check if computer won - if (checkWin(currentPlayer)) { - playerOScore++; - updateScores(); - if (currentRound === 5) { - endGame(); - } else { - startNextRound(); + if (foundWinner) { + // The computer has a winning move + board[combination[0]] = currentPlayer; + document.getElementById(`cell${combination[0] + 1}`).textContent = currentPlayer; + return; } - } else { - currentPlayer = "X"; } + +// No winning moves found, so select a random empty cell +random = Math.floor(Math.random() * emptyCells.length); +board[emptyCells[random]] = currentPlayer; +document.getElementById(`cell${emptyCells[random] + 1}`).textContent = currentPlayer; } + // Function to determine whether a player won function checkWin(player) {