mancala/src/components/board/BoardView.tsx
2022-07-14 13:23:15 +03:00

73 lines
2.5 KiB
TypeScript

import * as React from "react";
import { MancalaGame, Pit } from "mancala.js";
import { FunctionComponent } from "react";
import { Context } from "../../context";
import BoardViewModel from "../../viewmodel/BoardViewModel";
import PitViewModel from "../../viewmodel/PitViewModel";
import PitView from "./PitView";
import StoreView from "./StoreView";
const BoardView: FunctionComponent<{
game: MancalaGame;
context: Context;
boardId: string;
boardViewModel: BoardViewModel;
userKey: string;
onPitSelect: (index: number, pit: Pit) => void;
}> = ({ game, context, boardId, boardViewModel, userKey, onPitSelect: onPitSelect }) => {
const createPitView = (key: any, pitViewModel: PitViewModel, onClick: () => void) => {
return <PitView key={key} pitViewModel={pitViewModel} onClick={onClick} />;
};
const player1Pits = game?.board.player1Pits.map((pit, index) => {
const pitViewModel = boardViewModel.pits[pit.index];
return createPitView(index, pitViewModel, () => {
if (game.turnPlayerId === game.player1Id && userKey === game.player1Id)
onPitSelect(game.board.player1Pits.indexOf(pit), pit);
});
});
const player2Pits = game?.board.player2Pits.map((pit, index) => {
const pitViewModel = boardViewModel.pits[pit.index];
return createPitView(index, pitViewModel, () => {
if (game.turnPlayerId === game.player2Id && userKey === game.player2Id)
onPitSelect(game.board.player2Pits.indexOf(pit), pit);
});
});
const theme = context.themeManager.theme;
const player1BankViewModel =
boardViewModel.pits[game.board.player1BankIndex()];
const player2BankViewModel =
boardViewModel.pits[game.board.player2BankIndex()];
const isPlayer2 = userKey === game?.player2Id;
return (
<div
style={{
margin: "1vw",
padding: "2vw",
display: "grid",
gridTemplateColumns: "repeat(8, 11vw)",
gridTemplateRows: "repeat(2, 11vw)",
borderRadius: "3vw",
transition: "background-color 0.5s",
background: theme.boardColor,
}}
>
<StoreView
context={context}
pitViewModel={isPlayer2 ? player2BankViewModel : player1BankViewModel}
gridColumn="8 / 9"
gridRow="1 / 3"
/>
<StoreView
context={context}
pitViewModel={isPlayer2 ? player1BankViewModel : player2BankViewModel}
gridColumn="1 / 2"
gridRow="1 / 3"
/>
{isPlayer2 ? player1Pits?.reverse() : player2Pits?.reverse()}
{isPlayer2 ? player2Pits : player1Pits}
</div>
);
};
export default BoardView;