game.jsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import React, { useState } from "react";
  2. import {
  3. PRE_GAME,
  4. PRE_ROUND,
  5. IN_ROUND,
  6. POST_ROUND,
  7. POST_GAME,
  8. ERROR,
  9. } from "./game-state.enum";
  10. import PreGameContainer from '../pre-game.component';
  11. import PreRound from '../pre-round.component';
  12. import GamePanelContainer from "../game-panel.component";
  13. import RoundSummary from '../round-summary.component';
  14. import PlayerScoresContainer from "../player-scores.component";
  15. const initialState = {
  16. gameState: PRE_GAME,
  17. gameId: null,
  18. playerName: null,
  19. lastRound: null,
  20. }
  21. const Game = () => {
  22. const [ state, rawSetState ] = useState(initialState);
  23. const setGameState = gameState => rawSetState({ ...state, gameState });
  24. const setGameStateAnd = (gameState, updates) => rawSetState({ ...state, gameState, ...updates });
  25. switch (state.gameState) {
  26. case PRE_GAME:
  27. return <PreGameContainer
  28. playerName={state.playerName}
  29. onGameJoined={({ gameId, playerName }) => setGameStateAnd(PRE_ROUND, { gameId, playerName })}
  30. />
  31. case PRE_ROUND:
  32. return <PreRound
  33. gameId={state.gameId}
  34. playerName={state.playerName}
  35. onStart={() => setGameState(IN_ROUND)}
  36. />
  37. case IN_ROUND:
  38. return <GamePanelContainer
  39. gameId={state.gameId}
  40. playerName={state.playerName}
  41. onRoundEnd={lastRound => setGameStateAnd(POST_ROUND, { lastRound })}
  42. onGameEnd={() => setGameState(POST_GAME)}
  43. />
  44. case POST_ROUND:
  45. return <RoundSummary
  46. round={state.lastRound}
  47. onNext={() => setGameState(IN_ROUND)}
  48. />
  49. case POST_GAME:
  50. return <PlayerScoresContainer
  51. gameId={state.gameId}
  52. onReturnToStart={() => setGameState(PRE_GAME)}
  53. />
  54. case ERROR:
  55. // TODO - would be nice to hook this into the sub-components, maybe with a HOC?
  56. return <p>Application encountered unrecoverable error, please refresh the page.</p>
  57. default:
  58. setGameState(ERROR);
  59. return <p>Application state is inconsistent, please refresh and rejoin your previous game.</p>
  60. }
  61. }
  62. export default Game;