Cointime

Download App
iOS & Android

AO-Autonomous-Pet v1.0 | AO 极速入门(二)

Validated Project

在 AO 上实现自治宠物游戏。


作者:李大狗

审阅:Lemon

来源:内容公会 - 新闻


从本篇开始,将以一个链上宠物游戏为例, Step by Step 讲述如何基于 AO 进行游戏开发。

仓库: https://github.com/rootMUD/ao-autonomous-pet/

Process Code Online:

https://www.ao.link/#/entity/oMIa9Ea8dWESVZJ3iDX62mbTNFdm9zwFtV-5th6f5zs

0x00 架构设计

和其他区块链应用一致,AO-Autonomous-Pet 同样遵循「轻链上,重链下」、「抽象链上、具象链下」的原则。

在这种原则下,我们这样设计应用的架构:

在链上,我们设计出抽象层面的 Pet 以及必要的 Create/Read/Write 等方法,在 AO Process 中实现。

在链下,我们把抽象层面的 Pet 通过渲染(Renderer)模块渲染为具体的 Pet;通过 Pet Getter 对 AO Process 中的数据进行读取。通过 Pet Feeder 对 Pet 的等级进行提升。

0x01 Pet.lua 的实现与部署

  在 AO-Counter | AO 极速入门(一) 中,我们使用的是原生存储方式。在本次实践中,我们通过 AOS-SQLite 来实现我们的存储,SQLite是非常流行的文件式关系型数据库。  

  

1.1 代码加载

AOS-SQLite Repo: https://github.com/permaweb/aos-sqlite

在 AOS-SQLite Repo 中查看 ao-sqlite module id 的当前版本。

在 process 中加载 lua 脚本。

   

1.2 初始化 MySQL

加载 DB,然后执行 exec 脚本。

在这里,我们创建了一个表,里面包含如下字段:

  • 自增 id
  • Pet 名字
  • Pet 描述
  • Pet 等级
  • Pet 类型
  • Pet 拥有人地址
  • 上次更新时间戳

   

1.3 关于 Pet 的 CRW

CRWCreate-Read-Write 的缩写。通常,我们认为传统计算机中的基本操作是 CRUD —— Create, Read, Update and Delete。在区块链架构中,由于区块链不可篡改的基本特性,所以基本操作转变为 CRW —— Create, Read and Write

  

1.3.1 initPet

通过一个 Handler 和 一个 Function,我们实现了 initPet

  • stmt

stmt:step() 是 SQLite 中用于执行准备好的语句的函数。在 SQLite 的上下文中,准备好的语句是一个预编译的 SQL 语句,它可以用来提高效率和安全性。

当你调用 stmt:step() 时,它会执行准备好的 SQL 语句。如果 SQL 语句返回结果(例如 SELECT 查询),那么 stmt:step() 会将语句的执行状态移动到结果集中的下一行。对于其他类型的 SQL 语句(如 INSERTUPDATEDELETE),stmt:step() 会实际执行这些操作。

如果 stmt:step() 返回 sqlite3.ROW,这意味着还有更多的行可以处理。如果返回 sqlite3.DONE,这意味着语句已经完成执行,结果集已经完全遍历或者操作已经执行完毕。

  • 简单随机数

在计算机编程中,随机数会具备两种属性:可预测性可验证性

💡https://blog.chain.link/verifiable-random-function-vrf-zh/

不同的使用场景对随机数有不同的需求。例如,在initPet中,我们希望生成一个宠物类型,但这个随机数没有验证公平性的需求,所以我们可以直接使用 lua 自带的 math.random() 函数。

如果需要随机数可验证的话,会使用 AO 自带的 crypto.cipher.issac.getRandom(),这个在本系列的后续中再予以阐述。

  • 时间戳

在 Handler 中,msg 默认携带时间戳,我们把 msg 中的时间戳作为变量传入函数即可。

  

1.3.2 getPet & getPets

  • getPet,通过 Address 作为 Key 来获取 Pet。
  • getPets,获取所有 Pets
  • json 处理

我们通过json.encode将 pets 转换为 string 进行回复,主要要在文件头引入 json package -- local json = require("json")

  

1.3.3 UpdateLevel

updatePetLevel函数中,我们设置了基于时间的升级机制,升级后会需要一个小时的冷却时间。

  

1.3.4 调用 Handler 的 AO 指令

  • initPet
  • getPet
  • getPets
  • updateLevel

 0x02 番外:关于 GPT 编写代码的极简指南

本篇阐述一个额外的重要话题,如何利用 GPT 来辅助编写代码?

我们来一个一句话的极简指南:

💡把已有的代码或模板放在 Prompt 的最前面,然后再问问题 ——

抽象来看就是:

  以 .lua的编写为例,我们将 https://github.com/iamgamelover/ao-twitter 作为起始模板用 AI 进行代码编写。  

  

2.1 Sqlite 交互代码生成

Prompt:

local json = require("json")local sqlite3 = require("lsqlite3")DB = DB or sqlite3.open_memory()DB:exec [[ CREATE TABLE IF NOT EXISTS stories (   id TEXT PRIMARY KEY,   address TEXT,   post TEXT,   range TEXT,   category TEXT,   likes INT,   replies INT,   coins INT,   time INT );]]DB:exec [[ CREATE TABLE IF NOT EXISTS replies (   id TEXT PRIMARY KEY,   post_id TEXT,   address TEXT,   post TEXT,   likes INT,   replies INT,   coins INT,   time INT );]]DB:exec [[ CREATE TABLE IF NOT EXISTS likes (   id TEXT,   address TEXT,   time INT );]]DB:exec [[ CREATE TABLE IF NOT EXISTS txids (   id TEXT PRIMARY KEY,   txid TEXT );]]Give me the code about ao-pets.lua, which includes follow fields: name, description, lastUpdated, level, type, address which is unique and id which is increased automatically.

Answer:

Here's an example of the ao-pets.lua script that includes the specified fields (name, description, lastUpdated, level, type, address, id which is unique and automatically incremented):

In this script:

  • The ao_pets table is created with fields id, name, description, lastUpdated, level, type, and address.
  • The id field is set as the primary key and will automatically increment.
  • The address field is unique.
  • The add_pet function inserts a new pet into the ao_pets table.
  • The get_all_pets function retrieves and prints all pets in the table.

You can modify the script further based on your specific needs.

  

2.2 Handler 代码生成

Prompt:

Handlers.add( "AddNew", Handlers.utils.hasMatchingTag("Action", "AddNew"), function (msg)   table.insert(Players, msg.Data)   count = #Players   Handlers.utils.reply("bizz buzz")(msg) end)

Here is a handler example, impl Action "GetAllPets".

Answer:

Here's an example of a handler for the Action "GetAllPets" that retrieves all pets from the ao_pets table and sends them back as a response:

In this handler:

  • The GetAllPets action is defined and will be triggered when a message with the Action "GetAllPets" is received.
  • The handler function retrieves all rows from the ao_pets table and stores them in a pets table.
  • A response table is created with the Action "GetAllPetsResponse" and the retrieved pets data.
  • The response is sent back using Handlers.utils.reply.

This will ensure that when the "GetAllPets" action is received, the handler will retrieve all pets from the database and send them back in the response.


 🏆 “捉虫”有奖:在本文发现错字、病句、描述有误,点我报告,可得激励。

免责声明:本文不代表 PermaDAO 的观点或立场。PermaDAO 不提供投资建议,亦不为任何项目背书。请读者遵守所在国法律,合规进行 Web3 活动。

🔗 关于 PermaDAO:Website | Twitter | Telegram | Discord | MediumYoutube

Comments

All Comments

Recommended for you

  • Putin: Russia "supports" Harris, calls her smile "contagious"

    According to foreign media such as TASS and Russia's Sputnik News, Jinse Finance reported that on the afternoon of September 5th local time, Russian President Putin said at the plenary session of the Eastern Economic Forum 2024 that Russia will "support" the US Democratic Party presidential candidate and vice president Harris as recommended by the US President Biden in the upcoming US presidential election. When asked how he viewed the 2024 US election, Putin said it was the choice of the American people. The new US president will be elected by the American people, and Russia will respect the choice of the American people. Putin also said that just as Biden suggested his supporters to support Harris, "we will do the same, we will support her." The report said that Putin also joked that Harris' laughter is "expressive and infectious," which shows that "she is doing everything well." He added that this may mean that she will avoid further sanctions against Russia.

  • An ETH whale repurchased 5,153 ETH with 12.23 million USDT 20 minutes ago

    A certain high-frequency trading ETH whale monitored by on-chain analyst Yu Jin bought 5,153 ETH with 12.23 million USDT 20 minutes ago.

  • CFTC: Uniswap Labs has actively cooperated with the investigation and only needs to pay a fine of US$175,000

    The CFTC has filed a lawsuit against Uniswap Labs and reached a settlement. It was found that Uniswap Labs illegally provided leveraged or margined retail commodity transactions of digital assets through a decentralized digital asset trading protocol. Uniswap Labs was required to pay a civil penalty of $175,000 and cease violations of the Commodity Exchange Act (CEA). The CFTC acknowledged that Uniswap Labs actively cooperated with law enforcement agencies in the investigation and reduced the civil penalty.

  • Federal Reserve Beige Book: Respondents generally expect economic activity to remain stable or improve

    The Federal Reserve's Beige Book pointed out that economic activity in three regions has slightly increased, while the number of regions reporting flat or declining economic activity has increased from five in the previous quarter to nine in this quarter. Overall employment levels remain stable, although some reports indicate that companies are only filling necessary positions, reducing working hours and shifts, or reducing overall employment levels through natural attrition. However, reports of layoffs are still rare. Generally speaking, wage growth is moderate, and the growth rate of labor input costs and sales prices ranges from slight to moderate. Consumer spending has declined in most regions, while in the previous reporting period, consumer spending remained stable overall.

  • Puffpaw Completes $6 Million Seed Round with Lemniscap Ventures as Participant

    Puffpaw has announced the completion of a $6 million seed round of financing, with participation from Lemniscap Ventures. The Puffpaw project plans to launch a blockchain-enabled electronic cigarette aimed at helping users reduce nicotine intake through token incentives. The project encourages users to quit smoking by recording their smoking habits and rewarding them with tokens. Puffpaw's token economics aims to cover 30% of the cost of users' first month of using their product and provide social rewards. The project also considers possible system abuse, but the issue of users potentially reporting smoking habits dishonestly is not yet clear.

  • Affected by Ethervista and others, Ethereum Gas temporarily rose to 33gwei

    According to Etherscan, due to the influence of contracts such as Ethervista, Ethereum Gas has temporarily risen to 33gwei, with the top three being EthervistaRouter, UniswapRouter, and BananaGun.

  • The probability of the Fed cutting interest rates by 25 basis points in September is 55%.

    The probability of the Federal Reserve cutting interest rates by 25 basis points in September is 55.0%, while the probability of a 50 basis point cut is 45.0%. The probability of the Federal Reserve cutting interest rates by a cumulative 50 basis points by November is 32.1%, by 75 basis points is 49.2%, and by 100 basis points is 18.8%.

  • Nvidia: No subpoena received from the US Department of Justice

    Nvidia (NVDA.O) stated that it has not received a subpoena from the US Department of Justice.

  • US SEC again postpones decision on environmentally friendly Bitcoin ETF listing application

    The US Securities and Exchange Commission (SEC) has once again postponed its final decision on the New York Stock Exchange (NYSE) Arca's application for a carbon offset Bitcoin ETF. According to a document dated September 4th, the decision has been extended to November 21st. The ETF aims to provide a Bitcoin investment exposure in an environmentally friendly way by offsetting carbon emissions, tracking an investment portfolio composed of 80% Bitcoin and 20% carbon credit futures. Tidal Investments submitted the fund registration application in December 2023, while NYSE Arca submitted the initial application in March. Concerns have been raised about the environmental impact of Bitcoin mining, with the International Monetary Fund (IMF) reporting that cryptocurrency mining accounts for 1% of global greenhouse gas emissions. The delay in this decision also includes the postponement of approval for the Nasdaq One-Stop Cryptocurrency Investment Portfolio ETF.

  • Pudgy Penguins CEO:何为消费级加密货币应用

    加密货币行业中的一些 builder 努力地重复造轮。如今,一些突破性的消费级产品,若是能基于区块链打造并利用好加密货币的激励机制,其规模可能是现在的 10 倍。与其试图重新创建一种模式,不如利用现有的模式进行加密化改造。我认为,许多尚未面世的消费级加密货币应用在 Web2 中都有对应的产品,它们正等待着通过加密货币释放巨大的增长潜力。