Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React from "react";
- import ReactDOM from "react-dom";
- import { store } from "./store";
- import { useEffect } from "react";
- import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
- const render = ReactDOM.render(<App />, document.getElementById("root"));
- store.suscribe(render);
- render();
- // App.js
- function App() {
- useEffect(() => {
- //this is printed on every click on the "shuffle" from the Game component button.
- console.log("heyyy from App");
- });
- return (
- <div className="App">
- <Router>
- <Switch>
- <Route path="/game">
- <Game />
- </Route>
- <Route path="/">
- <Main />
- </Route>
- </Switch>
- </Router>
- </div>
- );
- }
- // Game.js
- const NUM_OF_CARDS = 52;
- const MAX_CARD_VALUE = 13;
- function Game() {
- //shuffle cards with Fisher Yates algorithm
- const shuffle = (array) => {
- for (let i = array.length - 1; i > 0; i--) {
- let j = Math.floor(Math.random() * (i + 1));
- [array[i], array[j]] = [array[j], array[i]];
- }
- };
- const initGame = {
- type: "INIT_GAME",
- payload: (state) => {
- // creates an array of size 52 filled with 1..13 four times
- const cards = Array(NUM_OF_CARDS / MAX_CARD_VALUE)
- .fill(
- Array(13)
- .fill()
- .map((_, i) => i + 1)
- )
- .flat();
- shuffle(cards);
- return {
- ...state,
- cards,
- // distributes cards evenly
- computer: {
- ...state.computer,
- cards: cards.slice(0, NUM_OF_CARDS / 2),
- },
- player: { ...state.player, cards: cards.slice(NUM_OF_CARDS / 2) },
- };
- },
- };
- useEffect(() => {
- store.dispatch(initGame);
- }, []);
- const shuffleCards = () => {
- const cards = [...store.getState().player.cards];
- shuffle(cards);
- store.dispatch({
- type: "SHUFFLE",
- payload: (state) => {
- return {
- ...state,
- player: { ...state.player, cards },
- };
- },
- });
- };
- return (
- <div>
- {store.getState().player.cards?.map((card) => (
- <div>{card}</div>
- ))}
- <div>----------------</div>
- {store.getState().computer.cards?.map((card) => (
- <div>{card}</div>
- ))}
- <button onClick={shuffleCards}>shuffle</button>
- </div>
- );
- }
- export default Game;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement