Skip to content

Commit

Permalink
Update
Browse files Browse the repository at this point in the history
  • Loading branch information
Phinetwork committed Dec 14, 2024
1 parent 4eef874 commit 65aed34
Showing 1 changed file with 142 additions and 105 deletions.
247 changes: 142 additions & 105 deletions frontend/src/components/Game.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,93 +4,90 @@ import "./Game.css";
// Simulate backend APIs
const fetchUserProfile = async () => ({
name: "Player One",
streak: Math.floor(Math.random() * 10) + 1,
streak: 5,
skillStats: {
timeManagement: Math.floor(Math.random() * 100),
problemSolving: Math.floor(Math.random() * 100),
mindfulness: Math.floor(Math.random() * 100),
timeManagement: 60,
problemSolving: 40,
mindfulness: 50,
},
});

const fetchLeaderboard = async () => [
{ name: "Alice", score: Math.floor(Math.random() * 300) + 200 },
{ name: "Bob", score: Math.floor(Math.random() * 300) + 200 },
{ name: "Player One", score: Math.floor(Math.random() * 300) + 100 },
{ name: "Alice", score: 120 },
{ name: "Bob", score: 100 },
{ name: "Player One", score: 80 },
];

const generateRandomSequence = (length) => {
const colors = ["Red", "Blue", "Green", "Yellow", "Orange", "Purple"];
return Array.from({ length }, () => colors[Math.floor(Math.random() * colors.length)]);
};
const fetchMiniGames = () => [
{
id: "memory",
title: "Memory Blitz",
description: "Remember this sequence: Red, Blue, Green, Yellow. Repeat it.",
options: [
{ text: "Red, Blue, Green, Yellow", correct: true },
{ text: "Red, Green, Blue, Yellow", correct: false },
{ text: "Yellow, Blue, Red, Green", correct: false },
],
},
{
id: "logic",
title: "Logical Puzzle",
description: "A train leaves Station A at 6:00 PM and travels at 60 mph. How far does it go in 2 hours?",
options: [
{ text: "60 miles", correct: false },
{ text: "120 miles", correct: true },
{ text: "90 miles", correct: false },
],
},
{
id: "reaction",
title: "Reaction Challenge",
description: "Tap the button as quickly as you can when it appears!",
isReaction: true,
},
{
id: "calculation",
title: "Quick Math",
description: "Solve this: 12 + 15 = ?",
options: [
{ text: "27", correct: true },
{ text: "28", correct: false },
{ text: "26", correct: false },
],
},
];

const generateDynamicScenario = (userStats) => {
const templates = [
const generateDynamicScenario = (level, userStats) => {
const baseScenarios = [
{
title: "Time Crunch",
description: "You have multiple tasks. How do you prioritize?",
description: "You have 3 tasks due at the same time. How do you prioritize?",
options: [
{ text: "Focus on urgent tasks", skill: "timeManagement" },
{ text: "Delegate to others", skill: "problemSolving" },
{ text: "Take a break", skill: "mindfulness" },
{ text: "Finish the easiest task first", score: 5, skill: "timeManagement" },
{ text: "Complete the hardest task first", score: 10, skill: "problemSolving" },
{ text: "Delegate to your team", score: 8, skill: "timeManagement" },
],
},
{
title: "Financial Decision",
description: "You have unexpected expenses. What do you do?",
title: "Mindfulness Break",
description: "You’re feeling overwhelmed. What do you do?",
options: [
{ text: "Save the money", skill: "mindfulness" },
{ text: "Invest in a project", skill: "problemSolving" },
{ text: "Spend it carefully", skill: "timeManagement" },
{ text: "Meditate for 5 minutes", score: 10, skill: "mindfulness" },
{ text: "Take a quick walk", score: 8, skill: "mindfulness" },
{ text: "Power through and ignore it", score: 3, skill: "timeManagement" },
],
},
];

return templates.map((template) => {
const options = template.options.map((option) => ({
return baseScenarios.map((scenario) => {
const updatedOptions = scenario.options.map((option) => ({
...option,
text: `${option.text} (${Math.floor(Math.random() * 100)} points)`,
score: Math.floor(Math.random() * 20) + 5 + Math.floor(userStats[option.skill] / 10),
score: option.score + Math.floor(userStats[option.skill] / 10),
}));

return {
title: template.title,
description: template.description,
options,
};
return { ...scenario, options: updatedOptions };
});
};

const generateDynamicMiniGames = () => [
{
id: "memory",
title: "Memory Blitz",
description: "Memorize the sequence and repeat it.",
levels: Array.from({ length: 3 }, (_, i) => ({
sequence: generateRandomSequence(i + 3),
points: (i + 1) * 10,
})),
},
{
id: "reaction",
title: "Reaction Challenge",
description: "Tap the button as quickly as you can when it appears!",
difficulty: Array.from({ length: 3 }, (_, i) => ({
delayRange: [300 + i * 200, 1000 - i * 200],
points: (i + 1) * 10,
})),
},
{
id: "logic",
title: "Logical Puzzle",
description: "Solve multi-step challenges.",
levels: Array.from({ length: 3 }, (_, i) => ({
question: `What is ${(i + 1) * 10} + ${(i + 2) * 5}?`,
answer: `${(i + 1) * 10 + (i + 2) * 5}`,
points: (i + 1) * 15,
})),
},
];

function Game() {
const [userProfile, setUserProfile] = useState(null);
const [scenarios, setScenarios] = useState([]);
Expand All @@ -99,24 +96,25 @@ function Game() {
const [score, setScore] = useState(0);
const [progress, setProgress] = useState(0);
const [currentScenarioIndex, setCurrentScenarioIndex] = useState(0);
const [feedback, setFeedback] = useState("");
const [gameOver, setGameOver] = useState(false);
const [miniGameActive, setMiniGameActive] = useState(false);
const [currentMiniGame, setCurrentMiniGame] = useState(null);
const [miniGameLevel, setMiniGameLevel] = useState(0);
const [feedback, setFeedback] = useState("");
const [reactionTime, setReactionTime] = useState(null);

useEffect(() => {
const initializeGame = async () => {
const profile = await fetchUserProfile();
setUserProfile(profile);

const scenarios = generateDynamicScenario(profile.skillStats);
setScenarios(scenarios);
const dynamicScenarios = generateDynamicScenario(1, profile.skillStats);
setScenarios(dynamicScenarios);

const leaderboard = await fetchLeaderboard();
setLeaderboard(leaderboard);
const leaderboardData = await fetchLeaderboard();
setLeaderboard(leaderboardData);

const miniGames = generateDynamicMiniGames();
setMiniGames(miniGames);
const games = fetchMiniGames();
setMiniGames(games);
};
initializeGame();
}, []);
Expand All @@ -126,39 +124,54 @@ function Game() {
setFeedback(`You earned ${option.score} points!`);
setProgress(progress + 1);

// Proceed to the next scenario
if (currentScenarioIndex + 1 < scenarios.length) {
setCurrentScenarioIndex(currentScenarioIndex + 1);
} else {
setFeedback("You've completed all scenarios!");
setGameOver(true);
}
};

const startMiniGame = () => {
const randomGame = miniGames[Math.floor(Math.random() * miniGames.length)];
setCurrentMiniGame(randomGame);
setMiniGameActive(true);
setMiniGameLevel(0);

// Set reaction game timing
if (randomGame.isReaction) {
setTimeout(() => {
setReactionTime(Date.now());
}, Math.random() * 2000 + 1000); // Random delay between 1-3 seconds
}
};

const handleMiniGameSubmit = (answer) => {
const game = currentMiniGame;
const level = game.levels ? game.levels[miniGameLevel] : null;
const correct = level?.sequence ? answer === level.sequence.join(", ") : answer === level?.answer;

if (correct) {
setScore(score + level.points);
setFeedback(`Correct! You earned ${level.points} points!`);
if (miniGameLevel + 1 < (game.levels?.length || 0)) {
setMiniGameLevel(miniGameLevel + 1);
} else {
setMiniGameActive(false);
}
const handleMiniGameSubmit = (option) => {
if (currentMiniGame.isReaction) {
const timeTaken = Date.now() - reactionTime;
setScore(score + Math.max(0, 1000 - timeTaken));
setFeedback(`Reaction Time: ${timeTaken}ms. You earned ${Math.max(0, 1000 - timeTaken)} points!`);
} else if (option.correct) {
setScore(score + 20);
setFeedback("Correct! Bonus 20 points!");
} else {
setFeedback("Oops! That was incorrect.");
setMiniGameActive(false);
}
setMiniGameActive(false);
setReactionTime(null);
};

const restartGame = () => {
setScore(0);
setProgress(0);
setCurrentScenarioIndex(0);
setFeedback("");
setGameOver(false);
setMiniGameActive(false);
setCurrentMiniGame(null);
};

const currentScenario = scenarios[currentScenarioIndex];

return (
<div className="game-container">
<header className="game-header">
Expand All @@ -170,12 +183,12 @@ function Game() {
</div>
</header>
<main className="game-area">
{!miniGameActive ? (
{!miniGameActive && !gameOver && currentScenario ? (
<>
<h2>{scenarios[currentScenarioIndex]?.title}</h2>
<p>{scenarios[currentScenarioIndex]?.description}</p>
<h2>{currentScenario.title}</h2>
<p>{currentScenario.description}</p>
<div className="options">
{scenarios[currentScenarioIndex]?.options.map((option, index) => (
{currentScenario.options.map((option, index) => (
<button
key={index}
className="option-button"
Expand All @@ -185,39 +198,63 @@ function Game() {
</button>
))}
</div>
{feedback && <p className="feedback">{feedback}</p>}
<button className="mini-game-button" onClick={startMiniGame}>
Play Mini-Game for Bonus Points
</button>
</>
) : (
) : miniGameActive && currentMiniGame ? (
<div className="mini-game">
<h2>{currentMiniGame.title}</h2>
<p>{currentMiniGame.description}</p>
{currentMiniGame.levels && currentMiniGame.levels[miniGameLevel]?.sequence ? (
{!currentMiniGame.isReaction ? (
<div className="options">
{currentMiniGame.levels[miniGameLevel].sequence.map((seq, index) => (
{currentMiniGame.options.map((option, index) => (
<button
key={index}
className="option-button"
onClick={() => handleMiniGameSubmit(seq)}
onClick={() => handleMiniGameSubmit(option)}
>
{seq}
{option.text}
</button>
))}
</div>
) : (
<input
type="text"
placeholder="Enter your answer"
onKeyDown={(e) => {
if (e.key === "Enter") handleMiniGameSubmit(e.target.value);
}}
/>
<button
className="reaction-button"
onClick={() => handleMiniGameSubmit()}
disabled={!reactionTime}
>
Tap Here!
</button>
)}
</div>
)}
{feedback && <p className="feedback">{feedback}</p>}
) : gameOver ? (
<div className="game-over">
<h2>Game Over!</h2>
<p>Your final score: {score}</p>
<h3>Leaderboard</h3>
<ul>
{leaderboard.map((entry, index) => (
<li key={index}>
{entry.name}: {entry.score} points
</li>
))}
</ul>
<button className="restart-button" onClick={restartGame}>
Play Again
</button>
</div>
) : null}
</main>
<footer className="game-footer">
<div className="progress-bar-container">
<div
className="progress-bar"
style={{ width: `${(progress / scenarios.length) * 100}%` }}
></div>
</div>
</footer>
</div>
);
}
Expand Down

0 comments on commit 65aed34

Please sign in to comment.