game.jsx 2.3 KB

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