From 029569a66a9232ef6e5d22fe3dad150af6ea6a32 Mon Sep 17 00:00:00 2001 From: Antoine M Date: Tue, 13 Feb 2024 19:30:01 +0100 Subject: [PATCH] updating GameContext --- src/context/GameContext.js | 96 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 src/context/GameContext.js diff --git a/src/context/GameContext.js b/src/context/GameContext.js new file mode 100644 index 0000000..fb8d490 --- /dev/null +++ b/src/context/GameContext.js @@ -0,0 +1,96 @@ +import { createContext, useContext, useEffect, useState } from "react"; +import chantierAtmopshere from "../assets/sounds/chantier_1.mp3"; +import GameAnswerExplanation from "../components/game/GameAnswerExplanation.jsx"; +import { useGame } from "../hooks/useGame.jsx"; +import { useUser } from "../hooks/useUser.jsx"; +import { calculateScore } from "../utils/gameFunctions.js"; + +export const GameContext = createContext(); + +export function GameContextProvider({ children }) { + const { language, country } = useUser(); + + // ##### DATA ##### + const [contextGameDatas, setContextGameDatas] = useState(null); + + // ##### GAME ##### + const [answers, setAnswers] = useState(null); + const [score, setScore] = useState(null); + + // ##### INTERFACE ##### + const [hasCheckedTutorial, setHasCheckedTutorial] = useState(false); + const [currentGameModal, setCurrentGameModal] = useState(null); + const [isSoundOn, setIsSoundOn] = useState(true); + + // ##### STATUS ##### + const [isTimeRuning, setIsTimeRuning] = useState(false); + const [isGameComplete, setIsGameComplete] = useState(false); + + // INIT DATAS + useEffect(() => { + if (!contextGameDatas) return; + initAnswers(); + }, [contextGameDatas]); + + function initAnswers() { + const answersArray = contextGameDatas.gameObjects.map((object, key) => { + return { + correctAnswer: object.attrs.behaviourType ? object.attrs.behaviourType : "unsafe", + userAnswer: null, + userAnsweredCorrectly: null, + }; + }); + setAnswers(answersArray); + } + + function answerQuestion(answerKey, answer) { + if (!answer || answerKey === null) return; + const newAnswers = [...answers]; + newAnswers[answerKey].userAnswer = answer; + newAnswers[answerKey].userAnsweredCorrectly = answer === newAnswers[answerKey].correctAnswer; + setAnswers(newAnswers); + + const newScore = calculateScore(answers); + setScore(newScore); + setCurrentGameModal(); + } + + function checkIfGameIsComplete() { + const isGameFinished = answers.every((answer) => answer.userAnswer !== null); + if (!isGameFinished) return; + console.warn(answers); + alert("Game is complete"); + setIsTimeRuning(false); + setIsGameComplete(true); + } + + function resetGame() { + isGameComplete(false); + setIsTimeRuning(false); + } + + return ( + + {children} + + ); +}