Skip to content

Commit

Permalink
feat: remove player's data transform to merkel tree
Browse files Browse the repository at this point in the history
  • Loading branch information
Vivomo committed Oct 4, 2023
1 parent 883b952 commit dc2edb8
Show file tree
Hide file tree
Showing 11 changed files with 3,879 additions and 379 deletions.
441 changes: 441 additions & 0 deletions packages/client/abi/Mississippi.json

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions packages/client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,14 @@
"@latticexyz/store-sync": "2.0.0-next.4",
"@latticexyz/utils": "2.0.0-next.4",
"@latticexyz/world": "2.0.0-next.4",
"@openzeppelin/contracts": "^4.9.3",
"@types/node": "^18.15.11",
"antd": "^5.9.2",
"buffer": "^6.0.3",
"contracts": "workspace:*",
"ethers": "^5.7.2",
"keccak256": "^1.0.6",
"merkletreejs": "^0.3.10",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.16.0",
Expand All @@ -33,8 +37,10 @@
"viem": "1.6.0"
},
"devDependencies": {
"@nomicfoundation/hardhat-toolbox": "^3.0.0",
"@types/react": "^18.0.11",
"@types/react-dom": "^18.0.11",
"hardhat": "^2.17.4",
"vite": "^4.2.1",
"wait-port": "^1.0.4"
}
Expand Down
1 change: 1 addition & 0 deletions packages/client/src/components/AvatarSelector/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const AvatarSelector = (props: IProps) => {
Avatars.map((avatar) => {
return (
<li
key={avatar}
className={`avatar-item avatar-box avatar-${avatar}`}
onClick={() => {
setAvatar(avatar);
Expand Down
8 changes: 5 additions & 3 deletions packages/client/src/components/Map/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { IPlayer } from '../Player';
import MapCell, { ICellClassCache, ICoordinate } from '../MapCell';
import './styles.scss';
import { bfs, simplifyMapData } from '@/utils/map';
import useMerkel from '@/hooks/useMerkel';

interface IProps {
width: number;
Expand All @@ -14,7 +15,7 @@ interface IProps {
x: number,
y: number,
};
onPlayerMove: (paths: ICoordinate[]) => void;
onPlayerMove: (paths: ICoordinate[], simpleMapData: number[][]) => void;
}

const Map = (props: IProps) => {
Expand All @@ -29,6 +30,8 @@ const Map = (props: IProps) => {
return simplifyMapData(data);
}, [data]);

const formatMovePath = useMerkel(simpleMapData);

const playerData = useMemo(() => {
const obj = {};
players.forEach((player) => {
Expand All @@ -40,10 +43,9 @@ const Map = (props: IProps) => {
const cellClassCache = useRef<ICellClassCache>({});

const onMoveTo = (coordinate) => {
console.log(coordinate);
const { x, y} = players.find((player) => player.id === curId);
const paths = bfs(simpleMapData, { x, y }, coordinate);
onPlayerMove(paths);
onPlayerMove(paths, formatMovePath(paths));
console.log(paths, { x, y }, coordinate);
}

Expand Down
69 changes: 69 additions & 0 deletions packages/client/src/hooks/useMerkel.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import React, { useEffect, useRef } from 'react';
import { MerkleTree } from 'merkletreejs';
import { solidityKeccak256, keccak256 } from 'ethers/lib/utils';
import { Buffer } from 'buffer';


const useMerkel = (mapData) => {

const convertToLeafs = (mapData) => {
const result = [];
for (let x = 0; x < mapData.length; x++) {
for (let y = 0; y < mapData[x].length; y++) {
result.push({ x, y, value: mapData[x][y] });
}
}
return result;
}

const merkel = useRef({
leafs: convertToLeafs(mapData),
merkleTree: null
});

const getProof = (x, y) => {
const leaf = generateLeaf(x, y, 1);
return merkel.current.merkleTree.getHexProof(leaf);
}

// 通过本函数将地图初始化为默克尔树节点的字符串数组,每个字符串的格式为"x,y-value"
// 其中value为0或1,表示该位置是否可以走,默认0不可走,1以及以后数字可以约定分别代表不同的可行性
const generateLeaf = (x, y, value) => {

return Buffer.from(
solidityKeccak256(
["uint16", "string", "uint16", "string", "uint8"],
[x, ",", y, ",", value]
).slice(2),
"hex"
);
}

const formatMovePath = (paths) => {
const steps = paths.map(({ x, y }) => [x, y]);
const result = [];
for (let i = 0; i < steps.length; i++) {
const proof = getProof(steps[i][0], steps[i][1]);
result.push([steps[i][0], steps[i][1], proof]);
}
return result;
}

useEffect(() => {
if (mapData.length === 0) {
return;
}
merkel.current.leafs = convertToLeafs(mapData);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
merkel.current.merkleTree = new MerkleTree(
merkel.current.leafs.map((info) => generateLeaf(info.x, info.y, info.value)),
keccak256,
{ sortPairs: true }
);
}, [mapData]);

return formatMovePath;
}

export default useMerkel;
5 changes: 4 additions & 1 deletion packages/client/src/pages/game/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import './styles.scss';
import Rank from '@/components/Rank';
import { CurIdMockData, PlayersMockData, RankMockData } from '@/mock/data';
import { IPlayer } from '@/components/Player';
import { uploadUserMove } from '@/service/user';

const Game = () => {
const [renderMapData, setRenderMapData] = useState([]);
Expand Down Expand Up @@ -47,7 +48,7 @@ const Game = () => {
});
};

const movePlayer = (paths) => {
const movePlayer = (paths, merkelData) => {
let pathIndex = 1;
const curPlayerIndex = players.findIndex(item => item.id === curPlayer!.id);
const interval = setInterval(() => {
Expand All @@ -58,6 +59,8 @@ const Game = () => {
clearInterval(interval);
}
}, 300);
console.log(merkelData);
uploadUserMove(players[curPlayerIndex].x, players[curPlayerIndex].y, merkelData);
}

useEffect(() => {
Expand Down
7 changes: 7 additions & 0 deletions packages/client/src/pages/home/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Col, Row, Button, Input, message } from 'antd';
import './styles.scss';
import { useNavigate } from 'react-router-dom';
import AvatarSelector from '@/components/AvatarSelector';
import { connect } from '@/service/connection';

const Home = () => {

Expand Down Expand Up @@ -33,6 +34,7 @@ const Home = () => {
});
}


return (
<div className="mi-home-page">
<div className="home-content">
Expand Down Expand Up @@ -61,6 +63,11 @@ const Home = () => {
<AvatarSelector onChange={(value) => setAvatar(value)}/>
</Col>
</Row>
<Row>
<Col>
<Button onClick={connect}>Connect</Button>
</Col>
</Row>
</div>
</div>
);
Expand Down
14 changes: 14 additions & 0 deletions packages/client/src/service/connection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { ethers } from 'ethers';

export const connect = async () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const provider = new ethers.providers.Web3Provider(window.ethereum)

await provider.send("eth_requestAccounts", []);

const signer = provider.getSigner();

const addr = await signer.getAddress();
console.log('connected', addr);
}
19 changes: 19 additions & 0 deletions packages/client/src/service/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { ethers } from 'ethers';
import Mississippi from '../../abi/Mississippi.json';

export const uploadUserMove = async (x, y, steps) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const provider = new ethers.providers.Web3Provider(window.ethereum)

await provider.send("eth_requestAccounts", []);
const signer = provider.getSigner();

const miss = new ethers.Contract('0xc86c785620e9d9a14374ea203b34b6312bce6d03', Mississippi, signer);

const transaction = await miss.connect(signer).move([x, y, steps]);
const tx = await transaction.wait(1);

console.log(tx.events)

}
4 changes: 2 additions & 2 deletions packages/client/src/utils/map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ export const bfs = (mapData: number[][], from: ICoordinate, to: ICoordinate) =>
const nextX = last.x + dX;
const nextY = last.y + dY;

if (data[nextY][nextX] === 0) {
if (data[nextY][nextX] === 1) {
newPaths.push([...path, { x: nextX, y: nextY}]);
data[nextY][nextX] = 1;
}
Expand All @@ -276,5 +276,5 @@ export const simplifyMapData = (mapData: number[][]) => {
if (mapData.length === 0) {
return mapData;
}
return mapData.map((row) => row.map(type => isMovable(type) ? 0 : 1));
return mapData.map((row) => row.map(type => isMovable(type) ? 1 : 0));
}
Loading

0 comments on commit dc2edb8

Please sign in to comment.