Skip to content

Commit

Permalink
Merge pull request #326 from riddhij0804/fixing_aiplay
Browse files Browse the repository at this point in the history
Fixed Play Against Ai Functionality
  • Loading branch information
iamparas0 authored Oct 29, 2024
2 parents ebecc22 + d45bf09 commit 975fe03
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 31 additions & 1 deletion paras/src/Game.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,36 @@ const App = () => {
newBoard[index] = currentPlayer;
setBoard(newBoard);
checkWinner(newBoard, currentPlayer);
setCurrentPlayer(currentPlayer === 'X' ? 'O' : 'X');

if(gameMode==='multiplayer')
{
setCurrentPlayer(currentPlayer === 'X'?'O':'X');
}

if(gameMode==='ai')
{
setTimeout(()=>{
aiTurn(newBoard);
},400);
}

};

const aiTurn=(currentBoard) => {
const availableMoves=currentBoard
.map((cell, index) => (cell===null? index : null))
.filter((index) => index !== null);

if (availableMoves.length===0)
{
return;
}
const aiMove = availableMoves[Math.floor(Math.random()*availableMoves.length)];
const newBoard = [...currentBoard];
newBoard[aiMove]='O';
setBoard(newBoard);
checkWinner(newBoard,'O');
setCurrentPlayer('X');
};

// Check if there's a winner
Expand All @@ -40,6 +69,7 @@ const App = () => {
if (board[a] === player && board[b] === player && board[c] === player) {
setWinner(player);
updateScoreAndHighestScore(player);
setDraw(false);
return;
}
}
Expand Down

0 comments on commit 975fe03

Please sign in to comment.