Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { createContext, useContext, useState, useEffect, useRef } from 'react';
- import DeckService from '../services/DeckAPIService';
- import Hand from '../models/Hand';
- import {determineOutcome, GameOutcome} from "../utils/gameLogic";
- export interface GameContextType {
- playerHand: Hand;
- houseHand: Hand;
- handleHit: () => Promise<void>;
- handleStand: () => void;
- resetGame: () => void;
- gameStatus: string | null;
- }
- const GameContext = createContext<GameContextType | undefined>(undefined);
- export function useGame() {
- const context = useContext(GameContext);
- if (!context) {
- throw new Error('useGame must be used within a GameProvider');
- }
- return context;
- }
- function GameProvider({ children }: { children: React.ReactNode }) {
- const [playerHand, setPlayerHand] = useState(new Hand());
- const [houseHand, setHouseHand] = useState(new Hand());
- const [gameStatus, setGameStatus] = useState<string | null>(null);
- const [deckService, setDeckService] = useState(new DeckService());
- const hasInitialized = useRef(false);
- useEffect(() => {
- if (!hasInitialized.current) {
- hasInitialized.current = true;
- setupGame();
- }
- }, []);
- async function setupGame() {
- await deckService.createDeck();
- const playerCards = await deckService.drawCard(2);
- const houseCards = await deckService.drawCard(2);
- const newPlayerHand = new Hand();
- const newHouseHand = new Hand();
- newPlayerHand.addCards(playerCards);
- newHouseHand.addCards(houseCards);
- setPlayerHand(newPlayerHand);
- setHouseHand(newHouseHand);
- setGameStatus(null);
- }
- async function handleHit() {
- const newCards = await deckService.drawCard(1);
- playerHand.addCard(newCards[0]);
- setPlayerHand(new Hand([...playerHand.cards]));
- if (playerHand.isBusted()) {
- endRound();
- }
- }
- function handleStand() {
- endRound();
- }
- function endRound() {
- const outcome = determineOutcome(playerHand, houseHand);
- if (outcome !== GameOutcome.CONTINUE_GAME) {
- setGameStatus(outcome);
- }
- }
- function resetGame() {
- setupGame();
- }
- const value: GameContextType = {
- playerHand,
- houseHand,
- handleHit,
- handleStand,
- resetGame,
- gameStatus
- };
- return (
- <GameContext.Provider value={value}>
- {children}
- </GameContext.Provider>
- );
- }
- export default GameProvider;
Advertisement
Add Comment
Please, Sign In to add comment