Skip to content

Commit

Permalink
fix: front end tick rate (#141)
Browse files Browse the repository at this point in the history
* fix: front end tick rate

* fix: await tick tx
  • Loading branch information
noyyyy authored Aug 24, 2023
1 parent 079d1f5 commit 0a4e5d2
Show file tree
Hide file tree
Showing 7 changed files with 111 additions and 36 deletions.
52 changes: 52 additions & 0 deletions packages/client/src/hooks/useAutoBattle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import dayjs from "dayjs";
import { useEffect, useState } from "react";
import { useAutoBattleFn } from "./useAutoBattleFn";

export function useAutoBattle() {
const { autoBattleFn } = useAutoBattleFn();
const [shouldRun, setShouldRun] = useState<boolean>(false);
const [isRunning, setIsRunning] = useState<boolean>(false);
const [runningStart, setRunningStart] = useState<number>(0);

useEffect(() => {
if (shouldRun) {
if (!isRunning) {
// set to now
setRunningStart(dayjs().unix());
setIsRunning(true);

// delay 0.5s to avoid on-chain fail and minimal tick interval
setTimeout(() => {
// run auto battle
autoBattleFn()
.then(() => {
setIsRunning(false);
})
.catch((e) => {
setIsRunning(false);
console.error(e);
});
}, 500);
}
}
}, [shouldRun, isRunning, setIsRunning, autoBattleFn, setRunningStart]);

// check timeout
useEffect(() => {
if (shouldRun) {
const interval = setInterval(() => {
// running timeout 10s
if (dayjs().unix() - runningStart > 10) {
setIsRunning(false);
console.log("running tick timeout");
}
// check every seconds:
}, 1000);
return () => {
clearInterval(interval);
};
}
}, [runningStart, shouldRun]);

return { setShouldRun, shouldRun, isRunning };
}
24 changes: 24 additions & 0 deletions packages/client/src/hooks/useAutoBattleFn.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { useMUD } from "@/MUDContext";
import { useComponentValue } from "@latticexyz/react";
import { useCallback } from "react";

export function useAutoBattleFn() {
const {
components: { PlayerGlobal },
systemCalls: { autoBattle },
network: { localAccount, playerEntity },
} = useMUD();

const _playerGlobal = useComponentValue(PlayerGlobal, playerEntity);

const autoBattleFn = useCallback(async () => {
if (!_playerGlobal) {
console.log("unknown player");
return false;
}
await autoBattle(_playerGlobal.gameId, localAccount);
return true;
}, [_playerGlobal, autoBattle, localAccount]);

return { autoBattleFn };
}
19 changes: 19 additions & 0 deletions packages/client/src/hooks/useBoardStatus.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { useMUD } from "@/MUDContext";
import { useComponentValue } from "@latticexyz/react";
import { useEffect, useState } from "react";

export function useBoardStatus() {
const {
components: { Board },
network: { playerEntity },
} = useMUD();

const BoardList = useComponentValue(Board, playerEntity);

const [currentBoardStatus, setCurrentBoardStatus] = useState(0);
useEffect(() => {
setCurrentBoardStatus(BoardList?.status || 0);
}, [BoardList, BoardList?.status]);

return { currentBoardStatus };
}
8 changes: 1 addition & 7 deletions packages/client/src/hooks/useChessboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ const srcObj = {
const useChessboard = () => {
const {
components: { Board, Player, PlayerGlobal },
systemCalls: { autoBattle, placeToBoard, changeHeroCoordinate },
systemCalls: { placeToBoard, changeHeroCoordinate },
network: { localAccount, playerEntity, storeCache, getCurrentBlockNumber },
} = useMUD();

Expand Down Expand Up @@ -202,10 +202,6 @@ const useChessboard = () => {

const { heroAltar, inventory } = playerObj!;

const autoBattleFn = async () => {
await autoBattle(_playerlayerGlobal!.gameId, localAccount);
};

const heroList = useMemo(() => {
return (tierPrice && decodeHeroFn(heroAltar)) ?? [];
}, [tierPrice, heroAltar]);
Expand All @@ -220,7 +216,6 @@ const useChessboard = () => {
PiecesList,
BattlePieceList,
BoardList,
currentBoardStatus: BoardList?.status,
srcObj,
heroList,
inventoryList,
Expand All @@ -234,7 +229,6 @@ const useChessboard = () => {
getCurrentBlockNumber,
roundInterval: GameConfig?.value.roundInterval,
expUpgrade: GameConfig?.value.expUpgrade,
autoBattleFn,
};
};

Expand Down
39 changes: 13 additions & 26 deletions packages/client/src/hooks/useTick.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { useState, useEffect } from "react";
import useChessboard from "./useChessboard";
import dayjs from "dayjs";
import { useAutoBattle } from "./useAutoBattle";
import { useBoardStatus } from "./useBoardStatus";

// const BoardStatus = ["PREPARING", "INBATTLE", "FINISHED"];
const BoardStatus = ["Preparing", "In Progress", "Awaiting Opponent"];
Expand All @@ -12,13 +14,14 @@ const useTick = () => {
startFrom,
autoBattleFn,
currentRoundStartTime,
currentBoardStatus = 0,
expUpgrade,
} = useChessboard();
const { currentBoardStatus } = useBoardStatus();

// console.log(status, "status", currentGameStatus);
const [width, setWidth] = useState(100);
const [timeLeft, setTimeLeft] = useState<number>(Infinity);
const { shouldRun, setShouldRun, isRunning } = useAutoBattle();

// reduce progress bar and time
useEffect(() => {
Expand Down Expand Up @@ -51,31 +54,15 @@ const useTick = () => {
}, [currentBoardStatus, roundInterval, currentRoundStartTime]);

useEffect(() => {
const interval = setInterval(async () => {
const number = await getCurrentBlockNumber();
const startTime = Number(startFrom);

if (timeLeft <= 0 && currentBoardStatus == 0) {
// First tick
console.log("first tick");
await autoBattleFn();
} else if (currentBoardStatus == 1) {
// Running tick
console.log("Running tick");
await autoBattleFn();
}
}, 1000);
return () => {
clearInterval(interval);
};
}, [
startFrom,
roundInterval,
getCurrentBlockNumber,
currentBoardStatus,
timeLeft,
autoBattleFn,
]);
if (
(timeLeft <= 0 && currentBoardStatus === 0) ||
currentBoardStatus === 1
) {
setShouldRun(true);
} else {
setShouldRun(false);
}
}, [timeLeft, currentBoardStatus, setShouldRun]);

return {
roundInterval,
Expand Down
3 changes: 1 addition & 2 deletions packages/client/src/mud/createSystemCalls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,14 @@ export type SystemCalls = ReturnType<typeof createSystemCalls>;
export function createSystemCalls({
worldSend,
txReduced$,
singletonEntity,
}: SetupNetworkResult) {
// { Board, Game, Piece, Creatures, CreatureConfig, Player, ShopConfig, GameConfig }: ClientComponents
const autoBattle = async (
gameId: PromiseOrValue<BigNumberish>,
player: PromiseOrValue<string>
) => {
const tx = await worldSend("tick", [gameId, player]);
await awaitStreamValue(txReduced$, (txHash) => txHash === tx.hash);
awaitStreamValue(txReduced$, (txHash) => txHash === tx.hash);
};

const createRoom = async (
Expand Down
2 changes: 1 addition & 1 deletion packages/client/src/mud/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export type SetupResult = Awaited<ReturnType<typeof setup>>;
export async function setup() {
const network = await setupNetwork();
const components = createClientComponents(network);
const systemCalls = createSystemCalls(network, components);
const systemCalls = createSystemCalls(network);
return {
network,
components,
Expand Down

0 comments on commit 0a4e5d2

Please sign in to comment.