Skip to content

Commit

Permalink
Pve (#170)
Browse files Browse the repository at this point in the history
* feat-single

* single battle

* feat-single

* single battle

* wip

* pull develop

* fix

* fix

* feat PveSystem

* single play

* fix

* fix ui

* feat rank

* fix

* fix getRandomNumberInGame

* fix _gameId

* add errCount

* feat how to play

* add PveBotSystem

* fix _getHeroIdx

* fix _getHeroIdx

* add todo

* fix randomAddressBytes

* fix getBotAddress

* fix getBotAddress

* fix _getHeroIdx

* fix rank
  • Loading branch information
aLIEzsss4 authored Sep 12, 2023
1 parent c39f92c commit 705884b
Show file tree
Hide file tree
Showing 33 changed files with 764 additions and 183 deletions.
Binary file added packages/client/public/assets/chess.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added packages/client/public/assets/createRoom.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added packages/client/public/assets/gameBar.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added packages/client/public/assets/shop.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 7 additions & 0 deletions packages/client/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useRef, useState } from "react";
import { useComponentValue } from "@latticexyz/react";
import { useMUD } from "./MUDContext";
import AutoChess from "./ui/ChessMain";
Expand All @@ -6,6 +7,8 @@ import "./index.css";
import { SelectNetwork } from "./ui/SelectNetwork";
import Feedback from "./ui/Feedback";
import usePreload from "./hooks/usePreload";
import { Tour } from "antd";
import type { TourProps } from "antd";

export const App = () => {
const {
Expand All @@ -16,6 +19,10 @@ export const App = () => {

usePreload();

const ref1 = useRef(null);
const ref2 = useRef(null);
const ref3 = useRef(null);

const playerObj = useComponentValue(PlayerGlobal, playerEntity);

const isPlay = playerObj?.status == 1;
Expand Down
8 changes: 7 additions & 1 deletion packages/client/src/hooks/useAutoBattle.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import dayjs from "dayjs";
import { useEffect, useState } from "react";
import { useEffect, useState, useRef } 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);
const errorCountRef = useRef(0);

useEffect(() => {
if (shouldRun) {
Expand All @@ -21,8 +22,13 @@ export function useAutoBattle() {
autoBattleFn()
.then(() => {
setIsRunning(false);
errorCountRef.current = 0;
})
.catch((e) => {
errorCountRef.current++;
if (errorCountRef.current < 3) {
setIsRunning(false);
}
setIsRunning(false);
console.error(e);
});
Expand Down
2 changes: 1 addition & 1 deletion packages/client/src/hooks/useAutoBattleFn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export function useAutoBattleFn() {
}
await autoBattle(_playerGlobal.gameId, localAccount);
return true;
}, [_playerGlobal, autoBattle, localAccount]);
}, [_playerGlobal?.gameId, autoBattle, localAccount]);

return { autoBattleFn };
}
65 changes: 39 additions & 26 deletions packages/client/src/hooks/useChessboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export interface boardInterface {
}

export interface HeroBaseAttr {
[x: string]: number | string;
race: HeroRace;
class: HeroClass;
attack: number;
Expand Down Expand Up @@ -84,6 +85,15 @@ const useChessboard = () => {
return srcObj.perUrl + heroIdString + ".png";
};

const creatureMap = new Map(
useEntityQuery([Has(Creature)])
?.map((row) => ({
...getComponentValueStrict(Creature, row),
key: row,
}))
.map((c) => [Number(c.key), c])
);

const BattlePieceList = useMemo(() => {
if (PieceInBattleList.length > 0) {
const battlePieces: any[] = [];
Expand All @@ -93,21 +103,20 @@ const useChessboard = () => {
const isEnemy = BoardList?.enemyPieces.includes(piece.key);

if (isOwner || isEnemy) {
const creature = getComponentValue(
Creature,
piece.creatureId as unknown as Entity
);
const creature = creatureMap.get(Number(piece.creatureId));

if (!creature) {
return;
}

const { tier } = decodeHero(creature as unknown as bigint);
const decodeHeroData = decodeHero(
piece.creatureId as unknown as bigint
);

battlePieces.push({
enemy: isEnemy,
image: getHeroImg(piece.creatureId),
tier: tier,
...decodeHeroData,
...creature,
...piece,
maxHealth: creature?.health,
Expand All @@ -118,28 +127,31 @@ const useChessboard = () => {
return battlePieces;
}
return [];
}, [BoardList, PieceInBattleList]);
}, [BoardList, PieceInBattleList, creatureMap]);

const PiecesList = playerObj?.heroes.map((row, _index: any) => {
const hero = getComponentValueStrict(
Hero,
encodeEntity({ id: "bytes32" }, { id: numberToHex(row, { size: 32 }) })
);
const creature = getComponentValue(
Creature,
encodeCreatureEntity(hero.creatureId)
);

const { tier } = decodeHero(hero.creatureId);
return {
...hero,
...creature,
key: row,
_index,
tier: tier,
image: getHeroImg(hero.creatureId),
maxHealth: creature?.health,
};
try {
const hero = getComponentValueStrict(
Hero,
encodeEntity({ id: "bytes32" }, { id: numberToHex(row, { size: 32 }) })
);
const creature = getComponentValue(
Creature,
encodeCreatureEntity(hero.creatureId)
);

const decodeHeroData = decodeHero(hero.creatureId);

return {
...hero,
...creature,
key: row,
_index,
...decodeHeroData,
image: getHeroImg(hero.creatureId),
maxHealth: creature?.health,
};
} catch (error) {}
});

const playerListData = currentGame?.players?.map((_player: string) => {
Expand Down Expand Up @@ -168,6 +180,7 @@ const useChessboard = () => {
currentRoundStartTime: currentGame?.startFrom,
startFrom: currentGame?.startFrom,
currentGameStatus: currentGame?.status,
isSinglePlay: currentGame?.single,
playerListData,
localAccount,
playerObj,
Expand Down
1 change: 1 addition & 0 deletions packages/client/src/hooks/useHeroAttr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export function useHeroesAttr(arr: bigint[]): HeroBaseAttr[] {

if (creature) {
return {
...item,
cost: item.rarity,
lv: item.tier,
url: srcObj.perUrl + item.heroIdString + ".png",
Expand Down
3 changes: 2 additions & 1 deletion packages/client/src/hooks/useTick.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const useTick = () => {
const roundInterval = _GameConfig?.roundInterval;
const expUpgrade = _GameConfig?.expUpgrade;
const currentRoundStartTime = currentGame?.startFrom;
const finishedBoard = currentGame?.finishedBoard;

const { currentBoardStatus } = useBoardStatus();

Expand Down Expand Up @@ -78,7 +79,7 @@ const useTick = () => {
setTimeLeft(0);
setWidth(0);
}
}, [currentBoardStatus, roundInterval, currentRoundStartTime]);
}, [currentBoardStatus, roundInterval, currentRoundStartTime, finishedBoard]);

useEffect(() => {
if (
Expand Down
2 changes: 1 addition & 1 deletion packages/client/src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@
width: 100vw;
height: 100vh;
overflow: hidden;
background: url(./assets/bg.svg);
background: url(/assets/bg.svg);
background-size: 240px;
background-repeat: repeat;
background-position: top right;
Expand Down
6 changes: 4 additions & 2 deletions packages/client/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,10 @@ function shortenAddress(address: string) {
return "";
}

const firstPart = address.substring(0, 6);
const lastPart = address.substring(address.length - 4);
const checksumAddress =address.length>42?'0x'+address.substring(address.length - 40):address

const firstPart = checksumAddress.substring(0, 6);
const lastPart = checksumAddress.substring(checksumAddress.length - 4);

return `${firstPart}.....${lastPart}`;
}
Expand Down
6 changes: 6 additions & 0 deletions packages/client/src/mud/createSystemCalls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ export function createSystemCalls(
await waitForTransaction(tx);
};

const singlePlay = async () => {
const tx = await worldContract.write.singlePlay();
await waitForTransaction(tx);
};

const leaveRoom = async (gameId: `0x${string}`, index: bigint) => {
const tx = await worldContract.write.leaveRoom([gameId, index]);
await waitForTransaction(tx);
Expand Down Expand Up @@ -187,6 +192,7 @@ export function createSystemCalls(
joinPrivateRoom,
leaveRoom,
startGame,
singlePlay,
surrender,
buyRefreshHero,
buyHero,
Expand Down
50 changes: 43 additions & 7 deletions packages/client/src/ui/ChessMain.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,16 @@ import { useDrop } from "ahooks";
import useChessboard, { HeroBaseAttr } from "@/hooks/useChessboard";
import usePreload from "@/hooks/usePreload";

import { Button, Popconfirm } from "antd";
import { Button, Popconfirm, Tour } from "antd";
import type { TourProps } from "antd";

import { Inventory } from "./Inventory";
import HeroInfo from "./HeroInfo";
import { shallowEqual } from "@/lib/utils";
import { Synergy } from "./Synergy";

import shopPic from "/assets/shop.jpg";
import gameBarPic from "/assets/gameBar.jpg";
import chessPic from "/assets/chess.jpg";

export interface boardInterface {
creatureId?: any;
Expand Down Expand Up @@ -44,8 +49,6 @@ const Game = () => {

const [acHero, setAcHero] = useState<HeroBaseAttr | null>(null);

// const [isDrag, setisDrag] = useState(second)

useEffect(() => {
let calculateInterval: any;

Expand Down Expand Up @@ -103,9 +106,43 @@ const Game = () => {
}
};

const ref1 = useRef(null);
const ref2 = useRef(null);
const ref3 = useRef(null);

const [open, setOpen] = useState<boolean>(false);

const steps: TourProps["steps"] = [
{
title: "Open Shop",
description: "Buy and refresh heroes.",
cover: <img alt="tour.png" src={shopPic} />,
target: () => ref1.current,
},
{
title: "Game Status",
description: "",
cover: <img alt="tour.png" src={gameBarPic} />,
target: () => ref2.current,
},
{
title: "Chessboard",
description: "Click for details.",
cover: <img alt="tour.png" src={chessPic} />,
target: () => ref3.current,
},
];

return (
<div className=" text-white relative">
<GameStatusBar showModal={showModal} />
<Tour open={open} onClose={() => setOpen(false)} steps={steps} />

<div className="fixed left-4 bottom-40">
<Button type="primary" onClick={() => setOpen(true)}>
How To Play
</Button>
</div>
<GameStatusBar customRef={ref1} customRef2={ref2} showModal={showModal} />
<div className="fixed left-2 top-36 align-text-bottom grid text-white">
<Button className="my-4 text-white-wrap" onClick={autoBattleFn}>
Manual Battle
Expand All @@ -121,10 +158,9 @@ const Game = () => {
</Popconfirm>
</div>
<ShopCom isModalOpen={isModalOpen} handleCancel={handleCancel} />
<div className="handle-area">
<div className="handle-area ">
<div>
<Chessboard setAcHeroFn={setAcHeroFn} />
<Synergy />
<Inventory setAcHeroFn={setAcHeroFn} />
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion packages/client/src/ui/Chessboard.css
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@

.hero-info-box {
width: 131px;
height: 327px;
/* height: 327px; */
background: #323846;
border: 1px solid #2c84a8;
border-radius: 9px;
Expand Down
Loading

0 comments on commit 705884b

Please sign in to comment.