Skip to content

Commit

Permalink
single play
Browse files Browse the repository at this point in the history
  • Loading branch information
aLIEzsss4 committed Sep 12, 2023
1 parent bbb1f21 commit 693019b
Show file tree
Hide file tree
Showing 14 changed files with 192 additions and 47 deletions.
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
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
5 changes: 4 additions & 1 deletion packages/client/src/ui/Chessboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,11 @@ const Chessboard = ({ setAcHeroFn }: { setAcHeroFn: (any) => void }) => {
placeToBoard,
changeHeroCoordinate,
currentBoardStatus = 0,
BoardList,
} = useChessboard();

const turn = (BoardList?.turn as number) || 0;

const dropRef = useRef(null);

const [dragIng, setDragIng] = useState(false);
Expand Down Expand Up @@ -134,7 +137,7 @@ const Chessboard = ({ setAcHeroFn }: { setAcHeroFn: (any) => void }) => {
BattlePieceList?.length > 0 ? `HP ${squares[i]?.["health"]}` : null;
// `HP ${squares[i]?.["maxHealth"]}`;

const dynamicKey = i + "key" + squares[i]?.["health"];
const dynamicKey = i + "key" + squares[i]?.["health"] + turn;

return (
<div key={dynamicKey} className={`${className} square `} data-index={i}>
Expand Down
75 changes: 61 additions & 14 deletions packages/client/src/ui/JoinGame.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"use client";
import { useState } from "react";
import { useEffect } from "react";
import { useEffect, useState, useRef } from "react";
import { useMUD } from "../MUDContext";
import { useComponentValue, useEntityQuery } from "@latticexyz/react";
import { Entity, getComponentValueStrict, Has } from "@latticexyz/recs";
Expand All @@ -12,8 +11,9 @@ import {
sha256,
toUtf8Bytes,
} from "ethers/lib/utils";
import { Input, Button, Table, Modal, message, Tooltip } from "antd";
import { Input, Button, Table, Modal, message, Tooltip, Tour } from "antd";
import type { ColumnsType } from "antd/es/table";
import type { TourProps } from "antd";
import { BigNumberish } from "ethers";
import { shortenAddress } from "../lib/utils";
import { Hex, numberToHex, stringToHex, toHex } from "viem";
Expand Down Expand Up @@ -67,6 +67,12 @@ const JoinGame = (/**{}: JoinGameProps */) => {
network: { playerEntity, localAccount },
} = useMUD();

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

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

const params = new URLSearchParams(window.location.search);

const roomId = params?.get("roomId");
Expand All @@ -81,11 +87,13 @@ const JoinGame = (/**{}: JoinGameProps */) => {
joinRoom: boolean;
leaveRoom: boolean;
startGame: boolean;
singlePlay: boolean;
}>({
createRoom: false,
joinRoom: false,
leaveRoom: false,
startGame: false,
singlePlay: false,
});

const playerObj = useComponentValue(PlayerGlobal, playerEntity);
Expand Down Expand Up @@ -249,6 +257,30 @@ const JoinGame = (/**{}: JoinGameProps */) => {
parseBytes32String(playerObj?.roomId as BytesLike) != ""
);

const steps: TourProps["steps"] = [
{
title: "Create Room",
description: "Put your files here.",
cover: (
<img
alt="tour.png"
src="https://user-images.githubusercontent.com/5378891/197385811-55df8480-7ff4-44bd-9d43-a7dade598d70.png"
/>
),
target: () => ref1.current,
},
{
title: "Save",
description: "Save your changes.",
target: () => ref2.current,
},
{
title: "Other Actions",
description: "Click to see other actions.",
target: () => ref3.current,
},
];

const columns: ColumnsType<DataType> = [
{
title: "RoomName",
Expand Down Expand Up @@ -399,6 +431,13 @@ const JoinGame = (/**{}: JoinGameProps */) => {
return (
<>
{contextHolder}
<Tour open={open} onClose={() => setOpen(false)} steps={steps} />
<div className="fixed left-10 top-10">
<Button type="primary" onClick={() => setOpen(true)}>
How To Play
</Button>
</div>

<div className="JoinGame bg-indigo-100">
<div className="grid justify-items-center h-20 bg-transparent absolute top-20 left-0 right-0 z-10 ">
{/* <h1 className="text-5xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-pink-500 to-blue-500">
Expand All @@ -410,22 +449,30 @@ const JoinGame = (/**{}: JoinGameProps */) => {
<div className="mt-[40px] w-8 h-8 bg-gradient-to-br from-indigo-500 via-indigo-600 to-indigo-700 animate-spin"></div>
<div className=" flex flex-col items-center justify-center">
<div className="flex justify-center mt-20">
<Button
className="cursor-pointer btn bg-blue-500 text-white font-bold px-4 rounded"
onClick={showModal}
disabled={disabled}
loading={loading.createRoom}
type="primary"
>
➕ Create Room
</Button>
<div>
<Button
className="cursor-pointer btn bg-blue-500 text-white font-bold px-4 rounded"
onClick={showModal}
disabled={disabled}
loading={loading.createRoom}
type="primary"
ref={ref1}
>
➕ Create Room
</Button>
</div>

<Button
className="cursor-pointer ml-[20px] btn bg-blue-500 text-white font-bold px-4 rounded"
onClick={() => singlePlay()}
onClick={() => {
setLoading({ singlePlay: true });
singlePlay().finally(() => {
setLoading({ singlePlay: false });
});
}}
disabled={disabled}
type="primary"
loading={loading.createRoom}
loading={loading.singlePlay}
>
👾 Single Play
</Button>
Expand Down
4 changes: 2 additions & 2 deletions packages/client/src/ui/Shop.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,11 @@ const Shop: React.FC<IShopProps> = ({ isModalOpen, handleCancel }) => {
<div className="flex felx-row">
<img
className="w-[30px] h-[30px] mx-1"
src={getRaceImage(hero.race)}
src={getRaceImage(hero.race as number)}
></img>
<img
className="w-[30px] h-[30px] mx-1"
src={getClassImage(hero.class)}
src={getClassImage(hero.class as number)}
></img>
</div>
</div>
Expand Down
9 changes: 9 additions & 0 deletions packages/contracts/mud.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,15 @@ export default mudConfig({
passwordHash: "bytes32",
},
},
Rank: {
keySchema: {
addr: "address",
},
schema: {
createdAtBlock: "uint32",
score: "uint32",
},
},
GameRecord: {
keySchema: {
index: "uint32",
Expand Down
2 changes: 1 addition & 1 deletion packages/contracts/script/ConfigInitializer.sol
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ library ConfigInitializer {
0, // creature index
4, // length
8, // width
10, // round interval second
60, // round interval second
0, // revenue
0, // revenueGrowthPeriod
6, // inventory slot num
Expand Down
19 changes: 17 additions & 2 deletions packages/contracts/src/library/Utils.sol
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
PlayerGlobal,
Player,
GameConfig,
ShopConfig,
Hero,
Piece,
Creature,
Expand Down Expand Up @@ -232,8 +233,22 @@ library Utils {
function getBotAddress(address _player) internal returns (address randomAddr) {
bytes32 randomBytes = keccak256(abi.encodePacked(_player));

bytes20 randomAddressBytes = bytes20(randomBytes << (12));
bytes20 randomAddressBytes = bytes20(randomBytes << (12 * 8));

randomAddr = address(randomAddressBytes);
randomAddr = address(uint160(uint256(randomBytes)));
}

function getRandomValues(uint256 count) internal returns (uint256[] memory) {
uint256[] memory values = new uint[](count);

uint256 seed = uint256(keccak256(abi.encode(blockhash(block.number - 1), block.number, gasleft())));

for (uint256 i = 0; i < count; i++) {
uint256 newSeed = uint256(keccak256(abi.encodePacked(seed)));
values[i] = uint256(keccak256(abi.encodePacked(newSeed)));
seed = values[i];
}

return values;
}
}
16 changes: 14 additions & 2 deletions packages/contracts/src/systems/AutoBattleSystem.sol
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ import {Board, BoardData} from "../codegen/Tables.sol";
import {Hero, HeroData} from "../codegen/Tables.sol";
import {Piece, PieceData} from "../codegen/Tables.sol";
import {GameRecord, Game, GameData} from "../codegen/Tables.sol";
import {PlayerGlobal, Player} from "../codegen/Tables.sol";
import {PlayerGlobal, Player, Rank} from "../codegen/Tables.sol";
import {GameStatus, BoardStatus, PlayerStatus} from "../codegen/Types.sol";
// import {Rank, RankData} from "../codegen/Types.sol";
import {Coordinate as Coord} from "cement/utils/Coordinate.sol";
import {RTPiece} from "../library/RunTimePiece.sol";
import {Utils} from "../library/Utils.sol";
Expand Down Expand Up @@ -185,8 +186,19 @@ contract AutoBattleSystem is System {
}

function _updateWhenGameFinished(uint32 _gameId) internal {
// push winner into GameRecord
address[] memory players = Game.getPlayers(_gameId);

bool isSinglePlay = Game.getSingle(_gameId);
if (isSinglePlay) {
uint32 turn = Board.getTurn(players[0]);
uint32 score = Rank.getScore(players[0]);

if (turn > score) {
// Rank.set(players[0], uint32(block.timestamp), turn);
}
}

// push winner into GameRecord
uint256 num = players.length;
assert(num < 2);
if (num == 1) {
Expand Down
18 changes: 11 additions & 7 deletions packages/contracts/src/systems/MatchingSystem.sol
Original file line number Diff line number Diff line change
Expand Up @@ -162,13 +162,17 @@ contract MatchingSystem is System {

uint24[] memory inventory = new uint24[](GameConfig.getInventorySlotNum(0));

uint256 num = _players.length;
for (uint256 i; i < num; ++i) {
address player = _players[i];
PlayerGlobal.set(player, bytes32(0), gameIndex, PlayerStatus.INGAME);
Player.setHealth(player, 30);
Player.setInventory(player, inventory);
}
address player = _players[0];
PlayerGlobal.set(player, bytes32(0), gameIndex, PlayerStatus.INGAME);
Player.setHealth(player, 4);
Player.setInventory(player, inventory);

// set bot
address _bot = _players[1];
PlayerGlobal.set(_bot, bytes32(0), gameIndex, PlayerStatus.INGAME);
Player.setHealth(_bot, 30);
Player.setCoin(_bot, 1000);
Player.setInventory(_bot, inventory);

// init round 0 for each player
IWorld(_world()).settleRound(gameIndex);
Expand Down
4 changes: 4 additions & 0 deletions packages/contracts/src/systems/PlaceSystem.sol
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,10 @@ contract PlaceSystem is System {
Player.setHeroOrderIdx(player, i);
}

// function getHeroIdxPublic(address player) public returns (bytes32 idx) {
// idx = _getHeroIdx(player);
// }

modifier onlyWhenGamePreparing() {
_checkGamePreparing();
_;
Expand Down
Loading

0 comments on commit 693019b

Please sign in to comment.