Skip to content

Commit

Permalink
update:
Browse files Browse the repository at this point in the history
  • Loading branch information
TiyoSheng committed Oct 30, 2023
2 parents 3252bb1 + cddf60a commit 623906c
Show file tree
Hide file tree
Showing 15 changed files with 342 additions and 7,632 deletions.
269 changes: 179 additions & 90 deletions packages/client/src/components/Battle/index.tsx

Large diffs are not rendered by default.

16 changes: 14 additions & 2 deletions packages/client/src/components/Map/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { bfs, simplifyMapData } from '@/utils/map';
import useMerkel from '@/hooks/useMerkel';
import { ITreasureChest } from '@/components/TreasureChest';
import GameContext from '@/context';
import { main } from '../../utils/createMerkelTree';

interface IProps {
width: number;
Expand Down Expand Up @@ -57,10 +58,21 @@ const Map = (props: IProps) => {
const cellClassCache = useRef<ICellClassCache>({});

const onMoveTo = (coordinate) => {
console.log(players, coordinate, 'onMoveTo')
const { x, y} = players.find((player) => player.addr === curId);
console.log(players, coordinate, 'onMoveTo', curId)
const { x, y} = players.find((player) => player.addr.toLocaleLowerCase() === curId.toLocaleLowerCase());
const paths = bfs(simpleMapData, { x, y }, coordinate).slice(1);
onPlayerMove(paths, formatMovePath(paths));
// 全是1的地图
// const player = players.find((e) => e.addr.toLocaleLowerCase() === curId.toLocaleLowerCase());
// let from = {x: player.x, y: player.y}
// let to = coordinate
// let map_info = [];
// let line = Array.from({ length: 100 }, () => 1);
// for (let i = 0; i < 10; i++) {
// map_info.push(line);
// }
// let {merkelData, paths} = main(from, to);
// onPlayerMove(paths, merkelData);
}


Expand Down
111 changes: 73 additions & 38 deletions packages/client/src/pages/game/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useRef, useState } from "react";
import React, { useEffect, useRef, useState, useMemo } from "react";
import { useComponentValue, useEntityQuery } from "@latticexyz/react";
import { Has, getComponentValue } from '@latticexyz/recs';
import { decodeEntity } from "@latticexyz/store-sync/recs";
Expand All @@ -20,11 +20,15 @@ import UserInfoDialog from '@/components/UserInfoDialog';
import { DELIVERY } from '@/config/map';
import { updatePlayerPosition } from '@/utils/player';
import { triggerVertexUpdate } from '@/utils/map';
import { bfs, simplifyMapData } from '@/utils/map';
import useMerkel from '@/hooks/useMerkel';

let boxId = ''

const Game = () => {
const {
components: { Player, GameConfig, BattleList, BoxList, GlobalConfig },
systemCalls: { move, getPosition },
systemCalls: { move, openBox, revealBox, getCollections, battleInvitation },
network,
} = useMUD();

Expand All @@ -34,16 +38,20 @@ const Game = () => {
y: 0,
});

const [players, setPlayers] = useState([]);
const simpleMapData = useMemo(() => {
return simplifyMapData(renderMapData);
}, [renderMapData]);

const formatMovePath = useMerkel(simpleMapData);

const [targetPlayer, setTargetPlayer] = useState(null);
const [userInfoPlayer, setUserInfoPlayer] = useState<IPlayer>();
const [treasureChest, setTreasureChest] = useState(TreasureChestMockData);
const curId = CurIdMockData;

const [startBattleData, setStartBattleData] = useState(false);
const [userInfoVisible, setUserInfoVisible] = useState(false);

const { account } = network;
const curId = account;

const { Modal, open, close, setContent } = useModal();

Expand All @@ -58,7 +66,7 @@ const Game = () => {
head,
} = location.state ?? {};

const mudPlayers = useEntityQuery([Has(Player)]).map((entity) => {
const players = useEntityQuery([Has(Player)]).map((entity) => {
const address = decodeEntity({ addr: "address" }, entity)?.addr?.toLocaleLowerCase() || ''
const player = getComponentValue(Player, entity);
player.addr = address
Expand All @@ -68,13 +76,44 @@ const Game = () => {
handheld,
head,
}
player.username = username;
}
return player;
});

const curPlayer = mudPlayers.find(player => player.addr.toLocaleLowerCase() == account.toLocaleLowerCase());
const curPlayer = players.find(player => player.addr.toLocaleLowerCase() == account.toLocaleLowerCase());

const getCollectionsFun = (box: any) => {
setContent(
<div className={'mi-modal-content-wrapper'}>
<div className="mi-modal-content">
Congrats,you got {box.oreBalance} gems!

<div className="mi-treasure-chest-wrapper">
<TreasureChest/>
</div>
</div>
<div className="mi-modal-footer">
<button className="mi-btn" onClick={async () => {
await getCollections(box.id, box.oreBalance, box.treasureBalance);
boxId = ''
close();
}}>OK</button>
</div>
</div>
);
open();
}

const boxs = useEntityQuery([Has(BoxList)]).map((entity) => {
let id = decodeEntity({ boxId: "uint256" }, entity);
let box:any = getComponentValue(BoxList, entity)
box.id = id.boxId.toString()
return box;
});

const treasureChest = boxs.filter((item) => !item.opened);

console.log(curPlayer, 'curPlayer')
useEffect(() => {
loadMapData().then((csv) => {
setRenderMapData(csv);
Expand All @@ -83,8 +122,11 @@ const Game = () => {
}, []);

useEffect(() => {
setPlayers(mudPlayers);
}, []);
if (boxId) {
const box = boxs.find((item) => item.id === boxId);
getCollectionsFun(box);
}
}, [boxs]);


const finishBattle = (e: any) => {
Expand Down Expand Up @@ -119,7 +161,6 @@ const Game = () => {
setVertexCoordinate(triggerVertexUpdate(paths[pathIndex], curPlayer, mapDataRef.current, vertexCoordinate));
updatePlayerPosition(curPlayer, paths[pathIndex]);
pathIndex++;
setPlayers([...players]);
if (pathIndex === paths.length) {
clearInterval(moveInterval.current);
const target = paths[pathIndex - 1];
Expand Down Expand Up @@ -166,39 +207,33 @@ const Game = () => {
}, 1000);
}

const setStartBattle = (player) => {
const setStartBattle = async (player) => {
console.log(player)
const paths = bfs(simpleMapData, { x: curPlayer.x, y: curPlayer.y }, {x: player.x, y: player.y}).slice(1);
// await battleInvitation(player.addr, formatMovePath(paths));
// console.log(formatMovePath(paths))
setTargetPlayer(player);
setStartBattleData(true);
}

const openTreasureChest = (id) => {
const openTreasureChest = async (id) => {
console.log(id);
const targetIndex = treasureChest.findIndex(item => item.id === id);
treasureChest[targetIndex].opening = true;
setTreasureChest([...treasureChest]);

setTimeout(() => {
curPlayer.gem += treasureChest[targetIndex].gem;
setPlayers([...players]);
setContent(
<div className={'mi-modal-content-wrapper'}>
<div className="mi-modal-content">
Congrats,you got {treasureChest[targetIndex].gem} gems!

<div className="mi-treasure-chest-wrapper">
<TreasureChest/>
</div>
</div>
<div className="mi-modal-footer">
<button className="mi-btn" onClick={() => {
treasureChest.splice(targetIndex, 1);
setTreasureChest([...treasureChest]);
close();
}}>OK</button>
</div>
</div>
);
open();
}, 3000);
await openBox(id);

let blockNumber = await network.publicClient.getBlockNumber()
// 每隔1s获取一次getBlockNumber
let interval = setInterval(async () => {
let currentBlockNumber = await network.publicClient.getBlockNumber()
console.log(currentBlockNumber, blockNumber, 'currentBlockNumber')
if (currentBlockNumber - blockNumber >= 2) {
clearInterval(interval)
await revealBox(id)

boxId = id
}
}, 1000)
}

const getWinTreasureChest = (gem = 1) => {
Expand Down
10 changes: 2 additions & 8 deletions packages/client/src/pages/test/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,12 +109,6 @@ const Test = () => {
return battle;
});
console.log(battles, 'battles')
battles.forEach(async item => {
if (item.attackerState == 2 && item.defenderState == 2) {
let hp = await getBattlePlayerHp(item.id, account)
console.log(hp, 'hp')
}
})

const boxs = useEntityQuery([Has(BoxList)]).map((entity) => {
let id = decodeEntity({ boxId: "uint256" }, entity);
Expand Down Expand Up @@ -230,7 +224,7 @@ const Test = () => {
let player = players.find(item => item.isMe);
let from = {x: player.x, y: player.y}
let to = {x: stepData[0], y: stepData[1]}
let merkelData = main(from, to);
let { merkelData } = main(from, to);
move(merkelData);
}

Expand Down Expand Up @@ -345,7 +339,7 @@ const Test = () => {
</div>
<div className="hd">
{
boxs.map((item, index) => (<div key={index}>
boxs.map((item, index) => (<div key={index} style={{marginBottom: '20px'}}>
<h6>宝箱信息</h6>
<div style={{ marginTop: '8px' }}>id: {item.id}</div>
<div style={{ marginTop: '8px' }}>opened: {item.opened.toString()}</div>
Expand Down
1 change: 1 addition & 0 deletions packages/client/src/pages/test/index.scss
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
align-items: flex-start;
justify-content: space-between;
min-height: 67px;
flex-wrap: wrap;
}

.main {
Expand Down
2 changes: 1 addition & 1 deletion packages/client/src/utils/createMerkelTree.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export const main = (from, to) => {
console.log("总移动步数", steps_arr.length);
let steps_list = move(steps_arr);
console.log("生成的传入文件", steps_list);
return steps_list
return {merkelData: steps_list, paths: steps}
}


24 changes: 24 additions & 0 deletions packages/contracts/mud.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,30 @@ export default mudConfig({
owner: "address",
}
},
LootList1:{
keySchema:{
addr: "address",
},
schema:{
weapon:"string",
chest:"string",
head:"string",
waist:"string",
foot:"string",
}

},
LootList2:{
keySchema:{
addr: "address",
},
schema:{
hand:"string",
neck:"string",
ring:"string"
}

},
GlobalConfig: {
dataStruct: false,
schema: {
Expand Down
2 changes: 1 addition & 1 deletion packages/contracts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
"build:typechain": "rimraf types && typechain --target=ethers-v5 out/IWorld.sol/IWorld.json",
"deploy:local": "pnpm run build && mud deploy",
"deploy:testnet": "pnpm run build && mud deploy --profile=lattice-testnet",
"dev-before": "pnpm mud dev-contracts",
"dev": "pnpm mud dev-contracts --rpc http://127.0.0.1:8545",
"dev-old": "pnpm mud dev-contracts --rpc http://127.0.0.1:8545",
"lint": "pnpm run prettier && pnpm run solhint",
"prettier": "prettier --write 'src/**/*.sol'",
"solhint": "solhint --config ./.solhint.json 'src/**/*.sol' --fix",
Expand Down
4 changes: 2 additions & 2 deletions packages/contracts/script/GameConfigInit.sol
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import { GAME_CONFIG_KEY } from "../src/Constants.sol";
library GameConfigInit {
function initGameConfig(IWorld _world) internal {
console.log(" ========= initGameConfig");
// bytes32 merkleRoot = 0x5df91eca63323dbb115087ef262075c5bcea99b8eaf95f520efb8d48ff447499;
bytes32 merkleRoot = 0xa969691ad8c2e97e3d516e08f5b10ee4decd5f278a5f03ac4fa3532be181c854;
bytes32 merkleRoot = 0x5df91eca63323dbb115087ef262075c5bcea99b8eaf95f520efb8d48ff447499;
// bytes32 merkleRoot = 0xa969691ad8c2e97e3d516e08f5b10ee4decd5f278a5f03ac4fa3532be181c854;
GameConfig.set(
_world,
GAME_CONFIG_KEY, //key
Expand Down
34 changes: 26 additions & 8 deletions packages/contracts/src/other/Loot.sol
Original file line number Diff line number Diff line change
Expand Up @@ -241,13 +241,31 @@ contract MLoot is Suit, ERC721,MRandom {
function getStructInfo(uint256 _tokenId) external view returns(string memory,string memory,string memory,string memory,string memory,string memory,string memory,string memory){
Loot memory loot = lootList[_tokenId];
require(loot.state == RandomState.Confirmed,"User not exists");
return(loot.Weapon,
loot.Chest,
loot.Head,
loot.Waist,
loot.Foot,
loot.Hand,
loot.Neck,
loot.Ring);
return(
loot.Weapon,
loot.Chest,
loot.Head,
loot.Waist,
loot.Foot,
loot.Hand,
loot.Neck,
loot.Ring
);
}

function getUserTokenIdList() view external returns(uint256[] memory){
uint256 balance = balanceOf(msg.sender);
uint256[] memory tokenIds = new uint256[](balance);
uint256 index;
for(uint256 i;i<tokenId;i++){
if(ownerOf(i) == msg.sender){
tokenIds[index] = i;
index++;
if(index == balance){
break;
}
}
}
return tokenIds;
}
}
19 changes: 17 additions & 2 deletions packages/contracts/src/systems/PlayerSystem.sol
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
pragma solidity >=0.8.0;

import { System } from "@latticexyz/world/src/System.sol";
import { Player, GlobalConfig } from "@codegen/Tables.sol";
import { Player, GlobalConfig, LootList1,LootList2 } from "@codegen/Tables.sol";
import {PlayerState } from "@codegen/Types.sol";

import { GLOBAL_CONFIG_KEY, PLAYER_KEY } from "../Constants.sol";
Expand Down Expand Up @@ -52,9 +52,24 @@ contract PlayerSystem is System {
Player.setStrength(sender, strength);
Player.setSpace(sender, space);
}
function selectLootNFT(uint256 _tokenId) external {
address lootAddress = GlobalConfig.getUserContract(GLOBAL_CONFIG_KEY);
Loot loot = Loot(lootAddress);
address _sender = _msgSender();
require(loot.ownerOf(_tokenId) == _msgSender(), "You are not the owner of this NFT");
(string memory Weapon,string memory Chest,string memory Head,string memory Waist,string memory Foot,string memory Hand,string memory Neck,string memory Ring) = loot.getStructInfo(_tokenId);
LootList1.setWeapon(_sender,Weapon);
LootList1.setChest(_sender,Chest);
LootList1.setHead(_sender,Head);
LootList1.setWaist(_sender,Waist);
LootList1.setFoot(_sender,Foot);
LootList2.setHand(_sender,Hand);
LootList2.setNeck(_sender,Neck);
LootList2.setRing(_sender,Ring);
}

function getUserInfo(uint256 tokenId) public view returns (uint256,uint256,uint256,uint256,uint256,uint256) {
address userAddress = GlobalConfig.getUserContract(GLOBAL_CONFIG_KEY);
address userAddress = GlobalConfig.getUserContract(GLOBAL_CONFIG_KEY);
User user = User(userAddress);
return user.getStructInfo(tokenId);
}
Expand Down
Loading

0 comments on commit 623906c

Please sign in to comment.