From 31010bd69aa28afeec580d93fba14303d75cfd96 Mon Sep 17 00:00:00 2001 From: Sri Kailash Choudhary Date: Mon, 21 Oct 2024 19:45:53 +0530 Subject: [PATCH] Added Game History Feature --- paras/src/Game.js | 42 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/paras/src/Game.js b/paras/src/Game.js index b56cfeb..a204a9a 100644 --- a/paras/src/Game.js +++ b/paras/src/Game.js @@ -2,6 +2,7 @@ import React, { useState, useEffect } from 'react'; import './App.css'; import Sparkle from './Sparkle'; // If Sparkle is not used, you can remove this import. import { Link } from 'react-router-dom'; + const initialBoard = Array(9).fill(null); const App = () => { @@ -16,7 +17,8 @@ const App = () => { const [highestScorePlayerX, setHighestScorePlayerX] = useState(0); const [highestScorePlayerO, setHighestScorePlayerO] = useState(0); const [gameMode, setGameMode] = useState(null); - + const [gameHistory, setGameHistory] = useState([]); // Added game history state + // Handle click on a cell const handleCellClick = (index) => { if (board[index] || winner || draw) return; @@ -65,8 +67,20 @@ const App = () => { } }; + // Update game history + const updateGameHistory = (board) => { + let updatedHistory = [...gameHistory, board]; + if (updatedHistory.length > 3) { + updatedHistory = updatedHistory.slice(1); // Keep only the last 3 games + } + setGameHistory(updatedHistory); + }; + // Reset the game but keep the scores intact const resetGame = () => { + if (winner || draw) { + updateGameHistory(board); // Store the finished game in history + } setBoard(initialBoard); setCurrentPlayer('X'); setWinner(null); @@ -108,6 +122,22 @@ const App = () => { ); }; + // Render game history + const renderHistory = () => { + return gameHistory.map((pastGame, index) => ( +
+

Game {index + 1}

+
+ {pastGame.map((cell, cellIndex) => ( +
+ {cell} +
+ ))} +
+
+ )); + }; + // Game Mode selection const handleBackButton = () => { setGameMode(null); @@ -185,8 +215,16 @@ const App = () => { )} + + {/* Game History Section */} + {gameMode === 'multiplayer' && ( +
+

Game History (Last 3 Games)

+ {renderHistory()} +
+ )} ); }; -export default App; +export default App; \ No newline at end of file