add basic animation

This commit is contained in:
Halit Aksoy 2022-05-12 23:41:24 +03:00
parent fdfb69c7e6
commit 290a1f5b6a
4 changed files with 284 additions and 151 deletions

View File

@ -14,7 +14,7 @@
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"mancala.js": "^0.0.2-beta.0", "mancala.js": "^0.0.2-beta.1",
"react": "^17.0.2", "react": "^17.0.2",
"react-dom": "^17.0.2" "react-dom": "^17.0.2"
}, },

View File

@ -1,143 +1,198 @@
import * as React from 'react'; import * as React from "react";
import { FunctionComponent, useState } from 'react'; import { FunctionComponent, useEffect, useState } from "react";
import BoardView from './components/BoardView'; import BoardView from "./components/BoardView";
import { context } from './context' import { context } from "./context";
import { RTMTWS } from './rtmt/rtmt_websocket'; import { RTMTWS } from "./rtmt/rtmt_websocket";
import { channel_game_move, channel_leave_game, channel_on_game_update, channel_on_game_user_leave } from './channel_names'; import {
import Button from './components/Button'; channel_game_move,
import InfoPanel from './components/InfoPanel'; channel_leave_game,
import { CommonMancalaGame, MancalaGame, Pit } from 'mancala.js' channel_on_game_update,
import { GameMove } from './models/GameMove'; channel_on_game_user_leave,
} from "./channel_names";
import Button from "./components/Button";
import InfoPanel from "./components/InfoPanel";
import { CommonMancalaGame, MancalaGame, Pit } from "mancala.js";
import { GameMove } from "./models/GameMove";
type ConnectionState = "connecting" | "error" | "connected" | "reconnecting" type ConnectionState = "connecting" | "error" | "connected" | "reconnecting";
const Home: FunctionComponent<{ initial?: number }> = ({ initial = 0 }) => { const Home: FunctionComponent<{ initial?: number }> = ({ initial = 0 }) => {
const [userKey, setUserKey] = useState(undefined); const [userKey, setUserKey] = useState(undefined);
const [connectionState, setConnetionState] = useState<ConnectionState>("connecting") const [connectionState, setConnetionState] =
useState<ConnectionState>("connecting");
const [searchingOpponent, setSearchingOpponent] = useState<boolean>(false) const [searchingOpponent, setSearchingOpponent] = useState<boolean>(false);
const [game, setGame] = useState<CommonMancalaGame>(undefined) const [game, setGame] = useState<CommonMancalaGame>(undefined);
const gameRef = React.useRef<CommonMancalaGame>(game);
const [crashMessage, setCrashMessage] = useState<string>(undefined) const [crashMessage, setCrashMessage] = useState<string>(undefined);
const [userKeyWhoLeave, setUserKeyWhoLeave] = useState<string>(undefined) const [userKeyWhoLeave, setUserKeyWhoLeave] = useState<string>(undefined);
const [animationPitIndex, setAnimationPitIndex] = useState<number>(-1);
const [intervalId, setIntervalId] = useState<number>(-1);
useEffect(() => {
gameRef.current = game;
});
const onConnectionDone = () => { const onConnectionDone = () => {
setConnetionState("connected") setConnetionState("connected");
} };
const onConnectionLost = () => { const onConnectionLost = () => {
connectToServer("reconnecting") connectToServer("reconnecting");
} };
const onConnectionError = (event: Event) => { const onConnectionError = (event: Event) => {
setConnetionState("error") setConnetionState("error");
} };
const connectToServer = (connectionState: ConnectionState) => { const connectToServer = (connectionState: ConnectionState) => {
setConnetionState(connectionState) setConnetionState(connectionState);
context.userKeyStore.getUserKey((userKey: string) => { context.userKeyStore.getUserKey((userKey: string) => {
setUserKey(userKey) setUserKey(userKey);
const rtmtws = context.rtmt as RTMTWS const rtmtws = context.rtmt as RTMTWS;
if (rtmtws) { if (rtmtws) {
rtmtws.initWebSocket(userKey, onConnectionDone, onConnectionLost, onConnectionError) rtmtws.initWebSocket(
userKey,
onConnectionDone,
onConnectionLost,
onConnectionError
);
} else { } else {
console.error("context.rtmt is not RTMTWS"); console.error("context.rtmt is not RTMTWS");
} }
}) });
} };
const listenMessages = () => { const listenMessages = () => {
context.rtmt.listenMessage(channel_on_game_update, (message: Object) => { context.rtmt.listenMessage(channel_on_game_update, (message: Object) => {
const newGame: CommonMancalaGame = message as CommonMancalaGame; const newGame: CommonMancalaGame = message as CommonMancalaGame;
setGame(MancalaGame.createFromMancalaGame(newGame)) const mancalaGame = MancalaGame.createFromMancalaGame(newGame);
}) if (gameRef.current && mancalaGame.history.length > 0) {
const lastHistoryItem =
mancalaGame.history[mancalaGame.history.length - 1];
if (lastHistoryItem.gameSteps.length > 0) {
let stepIndex = 0;
if (intervalId) {
clearInterval(intervalId);
}
const id = setInterval(() => {
if (stepIndex === lastHistoryItem.gameSteps.length) {
clearInterval(id);
setAnimationPitIndex(-1);
setGame(mancalaGame);
} else {
const gameStep = lastHistoryItem.gameSteps[stepIndex];
const index = mancalaGame.board.getPitIndexCircularly(
gameStep.index
);
setAnimationPitIndex(index);
}
stepIndex++;
}, 250);
setIntervalId(intervalId);
}
}
});
context.rtmt.listenMessage("on_game_start", (message: Object) => { context.rtmt.listenMessage("on_game_start", (message: Object) => {
const newGame: CommonMancalaGame = message as CommonMancalaGame; const newGame: CommonMancalaGame = message as CommonMancalaGame;
setSearchingOpponent(false) setSearchingOpponent(false);
setGame(MancalaGame.createFromMancalaGame(newGame)) setGame(MancalaGame.createFromMancalaGame(newGame));
}) });
context.rtmt.listenMessage("on_game_crashed", (message: any) => { context.rtmt.listenMessage("on_game_crashed", (message: any) => {
const newCrashMessage = message as string const newCrashMessage = message as string;
console.error("on_game_crash"); console.error("on_game_crash");
console.error(newCrashMessage); console.error(newCrashMessage);
setCrashMessage(newCrashMessage) setCrashMessage(newCrashMessage);
}) });
context.rtmt.listenMessage(channel_on_game_user_leave, (message: any) => { context.rtmt.listenMessage(channel_on_game_user_leave, (message: any) => {
const userKeyWhoLeave = message; const userKeyWhoLeave = message;
setUserKeyWhoLeave(userKeyWhoLeave) setUserKeyWhoLeave(userKeyWhoLeave);
}) });
} };
React.useEffect(() => { React.useEffect(() => {
listenMessages() listenMessages();
connectToServer("connecting") connectToServer("connecting");
}, []) }, []);
const resetGameState = () => { const resetGameState = () => {
setGame(undefined) setGame(undefined);
setCrashMessage(undefined) setCrashMessage(undefined);
setUserKeyWhoLeave(undefined) setUserKeyWhoLeave(undefined);
} };
const newGameClick = () => { const newGameClick = () => {
resetGameState() resetGameState();
setSearchingOpponent(true) setSearchingOpponent(true);
context.rtmt.sendMessage("new_game", {}) context.rtmt.sendMessage("new_game", {});
} };
const leaveGame = () => { const leaveGame = () => {
context.rtmt.sendMessage(channel_leave_game, {}) context.rtmt.sendMessage(channel_leave_game, {});
} };
const onHoleSelect = (index: number, hole: Pit) => { const onHoleSelect = (index: number, hole: Pit) => {
const gameMove: GameMove = { index: index } const gameMove: GameMove = { index: index };
context.rtmt.sendMessage(channel_game_move, gameMove) context.rtmt.sendMessage(channel_game_move, gameMove);
} };
const showConnectionState = connectionState != "connected" const showConnectionState = connectionState != "connected";
const connectionStateText = () => { const connectionStateText = () => {
let map: { [key: string]: string } = { let map: { [key: string]: string } = {
"connecting": context.texts.Connecting, connecting: context.texts.Connecting,
"connected": context.texts.Connected, connected: context.texts.Connected,
"error": context.texts.CannotConnect, error: context.texts.CannotConnect,
"reconnecting": context.texts.ConnectingAgain reconnecting: context.texts.ConnectingAgain,
}; };
return map[connectionState] return map[connectionState];
} };
const renderNewGameButton = () => { const renderNewGameButton = () => {
const newGame = <Button text={context.texts.NewGame} color="#005f73" onClick={newGameClick} /> const newGame = (
<Button
text={context.texts.NewGame}
color="#005f73"
onClick={newGameClick}
/>
);
if (userKeyWhoLeave) { if (userKeyWhoLeave) {
return newGame return newGame;
} }
if (crashMessage) { if (crashMessage) {
return newGame return newGame;
} }
if (!game) { if (!game) {
return newGame return newGame;
} else if (game.state == "ended") { } else if (game.state == "ended") {
return newGame return newGame;
}
return <></>
} }
return <></>;
};
return <div style={{ return (
<div
style={{
display: "flex", display: "flex",
flexDirection: "column", flexDirection: "column",
alignItems: "center", alignItems: "center",
background: "#EEEEEE", background: "#EEEEEE",
flex: "1", flex: "1",
}}> }}
{showConnectionState && >
<div style={{ {showConnectionState && (
<div
style={{
position: "absolute", position: "absolute",
bottom: "0px", bottom: "0px",
left: "0px", left: "0px",
@ -147,33 +202,54 @@ const Home: FunctionComponent<{ initial?: number }> = ({ initial = 0 }) => {
minHeight: "1vw", minHeight: "1vw",
background: "#2F2504", background: "#2F2504",
color: "white", color: "white",
}}> }}
>
{connectionStateText()} {connectionStateText()}
</div>} </div>
<div style={{ )}
<div
style={{
padding: "0px 50px", padding: "0px 50px",
background: "rgb(228, 228, 228)", background: "rgb(228, 228, 228)",
display: 'flex', display: "flex",
flexDirection: "row", flexDirection: "row",
alignItems: "center", alignItems: "center",
justifyContent: "space-between", justifyContent: "space-between",
alignSelf: "stretch" alignSelf: "stretch",
}}> }}
>
<h1 style={{ margin: "10px 0px" }}>{context.texts.Mancala}</h1> <h1 style={{ margin: "10px 0px" }}>{context.texts.Mancala}</h1>
<div> <div>
{renderNewGameButton()} {renderNewGameButton()}
{game && !userKeyWhoLeave && !crashMessage && (game?.state === "playing" || game?.state === "initial") && < Button color="#005f73" text={context.texts.Leave} onClick={leaveGame} />} {game &&
!userKeyWhoLeave &&
!crashMessage &&
(game?.state === "playing" || game?.state === "initial") && (
<Button
color="#005f73"
text={context.texts.Leave}
onClick={leaveGame}
/>
)}
</div> </div>
</div> </div>
<InfoPanel <InfoPanel
game={game} game={game}
crashMessage={crashMessage} crashMessage={crashMessage}
userKey={userKey} userKey={userKey}
userKeyWhoLeave={userKeyWhoLeave} userKeyWhoLeave={userKeyWhoLeave}
searchingOpponent={searchingOpponent} /> searchingOpponent={searchingOpponent}
{game && <BoardView userKey={userKey} game={game} onHoleSelect={onHoleSelect} />} />
{game && (
<BoardView
userKey={userKey}
game={game}
onHoleSelect={onHoleSelect}
animationPitIndex={animationPitIndex}
/>
)}
</div> </div>
} );
};
export default Home export default Home;

View File

@ -10,6 +10,8 @@ type Theme = {
storeColorWhenPlayerTurn: string; storeColorWhenPlayerTurn: string;
holeColor: string; holeColor: string;
ballColor: string; ballColor: string;
ballLightColor: string;
holeAnimateColor: string;
}; };
const theme: Theme = { const theme: Theme = {
@ -20,6 +22,8 @@ const theme: Theme = {
storeColorWhenPlayerTurn: "#6cab94", storeColorWhenPlayerTurn: "#6cab94",
holeColor: "#D3D4D8", holeColor: "#D3D4D8",
ballColor: "#393E46", ballColor: "#393E46",
ballLightColor: "#393E46",
holeAnimateColor: "#afb3a4",
}; };
const BallView: FunctionComponent<{ color: string }> = ({ color }) => { const BallView: FunctionComponent<{ color: string }> = ({ color }) => {
@ -44,13 +48,34 @@ function range(size: number) {
return ans; return ans;
} }
const PitContainer: FunctionComponent<{
pit: Pit;
isAnimating: boolean;
onClick: () => void;
}> = ({ pit, isAnimating, onClick }) => {
if (isAnimating) {
pit.stoneCount += 1;
}
return (
<>
<HoleView
hole={pit}
color={isAnimating ? theme.holeAnimateColor : theme.holeColor}
stoneColor={isAnimating ? theme.ballLightColor : theme.ballColor}
onClick={onClick}
/>
</>
);
};
const HoleView: FunctionComponent<{ const HoleView: FunctionComponent<{
hole: Pit; hole: Pit;
color: string; color: string;
stoneColor: string;
onClick: () => void; onClick: () => void;
}> = ({ hole, color, onClick }) => { }> = ({ hole, color, stoneColor, onClick }) => {
const balls = [...range(hole.stoneCount)].map((i) => ( const balls = [...range(hole.stoneCount)].map((i) => (
<BallView color={theme.ballColor} /> <BallView color={stoneColor} />
)); ));
return ( return (
@ -77,11 +102,12 @@ const HoleView: FunctionComponent<{
const StoreView: FunctionComponent<{ const StoreView: FunctionComponent<{
store: Bank; store: Bank;
color: string; color: string;
stoneColor: string;
gridColumn: string; gridColumn: string;
gridRow: string; gridRow: string;
}> = ({ store, color, gridColumn, gridRow }) => { }> = ({ store, color, stoneColor, gridColumn, gridRow }) => {
const balls = [...range(store.stoneCount)].map((i) => ( const balls = [...range(store.stoneCount)].map((i) => (
<BallView color={theme.ballColor} /> <BallView color={stoneColor} />
)); ));
return ( return (
<div <div
@ -107,35 +133,62 @@ const BoardView: FunctionComponent<{
game?: MancalaGame; game?: MancalaGame;
userKey: string; userKey: string;
onHoleSelect: (index: number, hole: Pit) => void; onHoleSelect: (index: number, hole: Pit) => void;
}> = ({ game, userKey, onHoleSelect }) => { animationPitIndex: number;
const player1Pits = game?.board.player1Pits.map((hole) => ( }> = ({ game, userKey, onHoleSelect, animationPitIndex }) => {
<HoleView const player1Pits = game?.board.player1Pits.map((pit) => {
hole={hole} const isAnimating = pit.index === animationPitIndex;
color={theme.holeColor} return (
<PitContainer
pit={pit}
isAnimating={isAnimating}
onClick={() => { onClick={() => {
if (game.turnPlayerId === game.player1Id) if (game.turnPlayerId === game.player1Id)
onHoleSelect(game.board.player1Pits.indexOf(hole), hole); onHoleSelect(game.board.player1Pits.indexOf(pit), pit);
}} }}
/> />
)); );
});
const player2Pits = game!!.board.player2Pits.map((hole) => ( const player2Pits = game!!.board.player2Pits.map((pit) => {
<HoleView const isAnimating = pit.index === animationPitIndex;
hole={hole} return (
color={theme.holeColor} <PitContainer
pit={pit}
isAnimating={isAnimating}
onClick={() => { onClick={() => {
if (game.turnPlayerId === game.player2Id) if (game.turnPlayerId === game.player2Id)
onHoleSelect(game.board.player2Pits.indexOf(hole), hole); onHoleSelect(game.board.player2Pits.indexOf(pit), pit);
}} }}
/> />
)); );
});
const isUserTurn = game.checkIsPlayerTurn(userKey); const isUserTurn = game.checkIsPlayerTurn(userKey);
const storeColor = isUserTurn const animatingPlayer1Bank =
game.board.player1Bank.index === animationPitIndex;
const animatingPlayer2Bank =
game.board.player2Bank.index === animationPitIndex;
const storeColorPlayer1 = animatingPlayer1Bank
? theme.holeAnimateColor
: isUserTurn
? theme.storeColor ? theme.storeColor
: theme.storeColorWhenPlayerTurn; : theme.storeColorWhenPlayerTurn;
const storeStoneColorPlayer1 = animatingPlayer1Bank
? theme.ballLightColor
: theme.ballColor;
const storeColorPlayer2 = animatingPlayer2Bank
? theme.holeAnimateColor
: isUserTurn
? theme.storeColor
: theme.storeColorWhenPlayerTurn;
const storeStoneColorPlayer2 = animatingPlayer2Bank
? theme.ballLightColor
: theme.ballColor;
return ( return (
<div <div
style={{ style={{
@ -154,13 +207,15 @@ const BoardView: FunctionComponent<{
<> <>
<StoreView <StoreView
store={game!!.board.player1Bank} store={game!!.board.player1Bank}
color={storeColor} color={storeColorPlayer1}
stoneColor={storeStoneColorPlayer1}
gridColumn="1 / 2" gridColumn="1 / 2"
gridRow="1 / 3" gridRow="1 / 3"
/> />
<StoreView <StoreView
store={game!!.board.player2Bank} store={game!!.board.player2Bank}
color={storeColor} color={storeColorPlayer2}
stoneColor={storeStoneColorPlayer2}
gridColumn="8 / 9" gridColumn="8 / 9"
gridRow="1 / 3" gridRow="1 / 3"
/> />
@ -171,13 +226,15 @@ const BoardView: FunctionComponent<{
<> <>
<StoreView <StoreView
store={game!!.board.player2Bank} store={game!!.board.player2Bank}
color={storeColor} color={storeColorPlayer2}
stoneColor={storeStoneColorPlayer2}
gridColumn="1 / 2" gridColumn="1 / 2"
gridRow="1 / 3" gridRow="1 / 3"
/> />
<StoreView <StoreView
store={game!!.board.player1Bank} store={game!!.board.player1Bank}
color={storeColor} color={storeColorPlayer1}
stoneColor={storeStoneColorPlayer1}
gridColumn="8 / 9" gridColumn="8 / 9"
gridRow="1 / 3" gridRow="1 / 3"
/> />

View File

@ -3373,10 +3373,10 @@ magic-string@^0.22.4:
dependencies: dependencies:
vlq "^0.2.2" vlq "^0.2.2"
mancala.js@^0.0.2-beta.0: mancala.js@^0.0.2-beta.1:
version "0.0.2-beta.0" version "0.0.2-beta.1"
resolved "https://registry.yarnpkg.com/mancala.js/-/mancala.js-0.0.2-beta.0.tgz#360cd909b6ee743a3e3cbea203457c82917d6fcb" resolved "https://registry.yarnpkg.com/mancala.js/-/mancala.js-0.0.2-beta.1.tgz#333d613b349e743a00141d231e1f49ab1f99b4fe"
integrity sha512-3UOo94K81GmqhQ8m2vFoU608yMyDWbn+EI7OfPjcmQJHf+n8+bu1Ju/bUYNMP5qoFU0rQnxaXKU+Z1hK3hw/Rg== integrity sha512-RS5DFYOjcKMONqZ4DsZudscN+2OhcRBJV2fX3KjqGBvREgMjCxDZVjFMhdZxnP5HFXdRSbUeMivyisGGGQbJ/A==
map-cache@^0.2.2: map-cache@^0.2.2:
version "0.2.2" version "0.2.2"