Let's move - Sui 猜大小游戏前端设计

  • stom698
  • 更新于 2024-03-28 16:24
  • 阅读 1040

本文转自本人微信公众号的文章,所以带有wx水印,希望大家能理解一下。后续新文会自己留存不带水印。

1.1 前言

上一篇已经简单的做了一个有了基本可玩性的框架,本文尝试在其基础上进行后端合约优化并且设计前端。

**1.2 前端设计

**

根据上一篇猜大小游戏合约也尝试先设计一个基础的前端交互界面**。

**

先创建个链接钱包的模板

#创建模板
pnpm create @mysten/dapp --template react-client-dapp
#安装依赖
pnpm install @mysten/sui.js @mysten/dapp-kit @tanstack/react-query

img

然后新建constants.ts文件,新增packageid

export const SICBOGAME_PACKAGE_ID = "0x4047ca9d7990e25abe3dea249e54eb5ed079212dd976f1ccc30700a96d01608f";

然后创建前端交互creategame.tsx文件,通过猜小和猜大按钮来发起交易然后通过queryEvents来获取交易返回信息

import {
    useSignAndExecuteTransactionBlock,
    useSuiClient,
  } from "@mysten/dapp-kit";
import { TransactionBlock } from "@mysten/sui.js/transactions";
import { Button, Flex, Heading } from "@radix-ui/themes";
import { SICBOGAME_PACKAGE_ID } from "./constants";  

export function Creategame({ 
    onCreated,
}:{
    onCreated: (id: string) => void;
 }) {
    const { mutate: signAndExecute } = useSignAndExecuteTransactionBlock();
    const client = useSuiClient();
​
    const executeMoveCall = (method: "small" | "large") => {
        const txb = new TransactionBlock();
​
        if (method === "small") {
        txb.moveCall({
            arguments: [txb.pure.u64(0)],
            target: `${SICBOGAME_PACKAGE_ID}::sicbogame::create_game`,
        });
        } else {
        txb.moveCall({
            arguments: [txb.pure.u64(1)],
            target: `${SICBOGAME_PACKAGE_ID}::sicbogame::create_game`,
        });
        }
​
        signAndExecute(
        {
            transactionBlock: txb,
            options: {
            showEffects: true,
            showObjectChanges: true,
            },
        },
        {
            onSuccess: (tx) => {
                client.
                    queryEvents({
                        query:{Transaction:tx.digest}
                    }).then(PaginatedEvents=> {
                        const events = JSON.stringify(PaginatedEvents.data[0].parsedJson);
                        const result = JSON.parse(events)['msg'];

                        if (result.length > 0) {
                          onCreated(result)
                        } else {
                          onCreated('No events found for the given criteria.');
                        }
                      })
                      .catch(error => { 
                        console.error('Error querying events:', error);
                      });
            },
        },
        );
    };
​

​
    return (
        <>
        <Heading size="3">Game Start</Heading>
​
        <Flex direction="column" gap="2">
            <Flex direction="row" gap="2">
            <Button onClick={() => executeMoveCall("small")}>
                猜小
            </Button>
            <Button onClick={() => executeMoveCall("large")}>
                猜大
            </Button>
            </Flex>
        </Flex>
        </>
    );
}
​

然后修改新建QueryDigest.tsx,返回猜选的结果

export function QueryDigest({ id }: { id: string }) {
​
  // 展示本次交易obeject中的内容。
  return (
    <div>
      <h3>Game Result:</h3>
      <ul>
        { id }
      </ul>
    </div>
  );
}

修改一下App.tsx文件

import { ConnectButton, useCurrentAccount } from "@mysten/dapp-kit";
import { Box, Container, Flex, Heading } from "@radix-ui/themes";
import { WalletStatus } from "./WalletStatus";
import { useState } from "react";
import { isValidSuiObjectId } from "@mysten/sui.js/utils";
import { QueryDigest } from "./QueryDigest";
import { Creategame } from "./creategame";
​
function App() {
  const currentAccount = useCurrentAccount();
  const [counterId, setCounter] = useState(() => {
    const hash = window.location.hash.slice(1);
    return isValidSuiObjectId(hash) ? hash : null;
  });
  return (
    <>
      <Flex
        position="sticky"
        px="4"
        py="2"
        justify="between"
        style={{
          borderBottom: "1px solid var(--gray-a2)",
        }}
      >
        <Box>
          <Heading>SICBOGAME</Heading>
        </Box>
​
        <Box>
          <ConnectButton />
        </Box>
      </Flex>
      <Container>
        <Container
          mt="5"
          pt="2"
          px="4"
          style={{ background: "var(--gray-a2)", minHeight: 500 }}
        >
          <WalletStatus />
          {currentAccount ? (
            counterId ? (
              <QueryDigest id={counterId} />
            ) : (
              <Creategame
                onCreated={(id) => {
                  window.location.hash = id;
                  setCounter(id);
                }}
              />
            )
          ) : (
            <Heading>Please connect your wallet</Heading>
          )}
        </Container>
      </Container>
    </>
  );
}
​
export default App;
​

然后运行

npm run dev

浏览器访问

img

点击猜小,然后返回结果

img

本文源码:

https://github.com/baicaiyihao/sui_dappkit/tree/main/sicbogame

Sui move_cn社交账号

telegram: https://t.me/move_cn

X(twitter): https://twitter.com/move_cn

QQ群: 79489587

微信公众号:Move中文

Sui中文开发群: https://t.me/sui_dev_cn

  • 原创
  • 学分: 5
  • 分类: Sui
  • 标签:
点赞 1
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。
5 订阅 9 篇文章

0 条评论

请先 登录 后评论
stom698
stom698
0x06CC...099B
努力提升