current position:Home>Blockchain game development and deployment

Blockchain game development and deployment

2022-02-02 09:58:12 awf133

Blockchain development has developed rapidly in the past few years , It is now being adopted in various fields of software development . From decentralized applications (DApps) To decentralized Finance (DeFi) Software , Until then NFTs, Until then DAOs, Blockchain technology has penetrated into a wide range of industries and served many use cases .

In this tutorial , We will explore emerging trends in blockchain game development . Blockchain based games are also called chain games . Once you understand the basic structure involved in writing smart contracts and deploying them to blockchains , You can use the tools available in the encrypted space to build the game .

We will build a lottery game to demonstrate how game development on the blockchain works . We will also review the basic structure of transactions in blockchain games . then , We deploy it to the test network .

What is a blockchain ?

The underlying data structure of the blockchain is a chain of linked lists , Or the only “ block ”. Each block added to the chain will be automatically linked to the previous added block , And the previous block also points to its previous block .

The chain itself is a transaction list . The process of agreeing on these blocks before adding them to the list data structure lays the key innovation that the blockchain has given us : agreement . This protocol helps the network decide how to add blocks to the chain .

This decision-making process gives birth to the decentralized nature of blockchain . Proof of workload (PoW)、 Evidence proves that (PoS) And authority (PoA) It's a decentralized mechanism , Through these mechanisms , These decisions can be made and agreed before adding blocks to the chain .

Cryptocurrency through these blockchains is a means to encourage people to run software to protect the network security around these blockchains .

NEAR And other blockchain platforms provide an encryption security platform , Used to store information using smart contracts 、 Update and delete data in the blockchain .

Web3 Game development

In the context of blockchain ,Web3 It refers to decentralized applications running on the blockchain . These applications allow anyone to participate , Without monetizing their personal data . With an in-depth understanding of the programming languages supported by these blockchains , We can start writing smart contracts , Build the game application as a... On the blockchain DApp.

With the development of blockchain ecosystem , A new paradigm has emerged . from De-Fi Draw inspiration from the ecosystem , The blockchain game ecosystem has also evolved into GameFi.GameFi, Also known as “ play game ”, By turning ordinary users into the leading force behind major decisions in the game industry , Introduced a new way of playing .

When trading valuables and generating additional income through tokens and irreplaceable tokens ,GameFi Promote the player owned economy . This means building communities around specific games , Users of these games can earn cryptocurrency or assets , These cryptocurrencies or assets are in the meta space of the game ( And outside the game ) It's all very valuable .

stay NEAR Write smart contracts on the blockchain

In this tutorial , We will demonstrate how to build a sample game project in NEAR Build games on the blockchain .

In this game , We will explore how to set up the code base structure and write in Near The programming language required by the smart contract running on the blockchain . After completion , We will test our application in a local environment , Then deploy our smart contract to the test network .

We will clone a starter kit code base . This repository provides a basic template , When we build the various functions of the game , You can write more smart contract code on it .

git clone https : //github.com/I

kehAkinyemi/lottery-smart-contract.git

After successfully executing the above command , Change directory to folder . You can open it in any text editor ; In this tutorial , We will use Visual Studio Code.lottery-smart-contract

Run the commands in the folder directory from the terminal .code .

Ikeh Akinyemi He is a software engineer based in river state of Nigeria . He is keen on learning pure mathematics and applied mathematics concepts 、 Open source and software engineering .

Blockchain Game Development Guide

2021 year 11 month 12 Japan 8 Minutes reading

Blockchain development has developed rapidly in the past few years , It is now being adopted in various fields of software development . From decentralized applications (DApps) To decentralized Finance (DeFi) Software , Until then NFTs, Until then DAOs, Blockchain technology has penetrated into a wide range of industries and served many use cases .

In this tutorial , We will explore emerging trends in blockchain game development . Blockchain based games are also called chain games . Once you understand the basic structure involved in writing smart contracts and deploying them to blockchains , You can use the tools available in the encrypted space to build the game .

We will build a lottery game to demonstrate how game development on the blockchain works . We will also review the basic structure of transactions in blockchain games . then , We deploy it to the test network .

What is a blockchain ?

The underlying data structure of the blockchain is a chain of linked lists , Or the only “ block ”. Each block added to the chain will be automatically linked to the previous added block , And the previous block also points to its previous block .

The chain itself is a transaction list . The process of agreeing on these blocks before adding them to the list data structure lays the key innovation that the blockchain has given us : agreement . This protocol helps the network decide how to add blocks to the chain .

This decision-making process gives birth to the decentralized nature of blockchain . Proof of workload (PoW)、 Evidence proves that (PoS) And authority (PoA) It's a decentralized mechanism , Through these mechanisms , These decisions can be made and agreed before adding blocks to the chain .

Cryptocurrency through these blockchains is a means to encourage people to run software to protect the network security around these blockchains .

NEAR And other blockchain platforms provide an encryption security platform , Used to store information using smart contracts 、 Update and delete data in the blockchain .

Web3 Game development

In the context of blockchain ,Web3 It refers to decentralized applications running on the blockchain . These applications allow anyone to participate , Without monetizing their personal data . With an in-depth understanding of the programming languages supported by these blockchains , We can start writing smart contracts , Build the game application as a... On the blockchain DApp.

With the development of blockchain ecosystem , A new paradigm has emerged . from De-Fi Draw inspiration from the ecosystem , The blockchain game ecosystem has also evolved into GameFi.GameFi, Also known as “ Play a game ”, By turning ordinary users into the leading force behind major decisions in the game industry , Introduced a new way of playing .

When trading valuables and generating additional income through tokens and irreplaceable tokens ,GameFi Promote the player owned economy . This means building communities around specific games , Users of these games can earn cryptocurrency or assets , These cryptocurrencies or assets are in the meta space of the game ( And outside the game ) It's all very valuable .

stay NEAR Write smart contracts on the blockchain

In this tutorial , We will demonstrate how to build a sample game project in NEAR Build games on the blockchain .

In this game , We will explore how to set up the code base structure and write in Near The programming language required by the smart contract running on the blockchain . After completion , We will test our application in a local environment , Then deploy our smart contract to the test network .

We will clone a starter kit code base . This repository provides a basic template , When we build the various functions of the game , You can write more smart contract code on it .

git clone https : //github.com/IkehAkinyemi/lottery-smart-contract.git

After successfully executing the above command , Change directory to folder . You can open it in any text editor ; In this tutorial , We will use Visual Studio Code.lottery-smart-contract

Run the commands in the folder directory from the terminal .code .

Folder structure starter kit

The figure above shows NEAR The basic folder structure of the project , Use AssemblyScript As its smart contract .

The script The folder contains information for compiling smart contracts and deploying them to blockchains shell Source file . The src contain lottery Folder , Inside, there are , We will write the code required for our smart contract .

The remaining files are AssemblyScript You need to understand Near Some types of configuration files defined on . The library is used in AssemblyScript In the development NEAR A collection of smart contract packages .near-sdk-as

How to be in NEAR Build lottery games on the blockchain

Through this game , We will explore the use of AssemblyScript stay Near Some basic concepts of writing smart contracts on the blockchain .

function yarn installornpm install Command to install the library and any necessary dependencies .near-sdk-as

Next , Create a file called assembly. In this folder , Create two files : and . This file contains the different object types that we will use throughout the code in this file . The file contains the following :index.tsmodel.tsmodel.tsindex.tsmodel.ts

import { RNG } from "near-sdk-as";

@nearBindgen
export class Lottery {
private luckyNum: u32 = 3;

constructor() {
const randGen = new RNG<u32>(1, u32.MAX_VALUE);
this.id = "LO-" + randGen.next().toString();
}
}

Use this play function , Any player can call it to use the RNG Object generates a random number . then , We imported logging object , This allows us to access the output values on the local console —— This is our local machine terminal .

The play The function returns a bool value , The true or false Value is the result of comparison pickedNum To determine whether the number of guesses is equal to that defined in the lottery game .this.luckyNumluckyNum

Next , We will define reset function . seeing the name of a thing one thinks of its function , This will enable us to Reset to new random number :this.luckyNum

import { RNG, logging } from "near-sdk-as";

@nearBindgen
export class Lottery {
...

play(): bool {
const randGen = new RNG<u32>(1, u32.MAX_VALUE);
const pickNum = randGen.next();

logging.log("You picked: " + pickedNum.toString());

return pickedNum === this.luckyNum
}
}

In the code above , We generated another new random number . Use this assert function , We compared it with the current value .this.luckyNum

If the comparison is true, The rest of the function will continue to execute . If not , Then the function stops at this point and returns the assertion message .Rerun this function to generate a new random luckyNum

When assert To true , We assign variables to the newly generated numbers .this.luckyNumrandNum

Definition Player object

For every player in the lottery game , We will define a basic type structure . This structure presents players in our game .

Update the file with the following code :model.ts

...
@nearBindgen
export class Lottery {
...

reset(): string {
const randGen = new RNG<u32>(1, u32.MAX_VALUE);
const randNum = randGen.next();
assert(randNum !== this.luckyNum, "Rerun this function to generate a new random luckyNum");

this.luckyNum = randNum;
return "The luckyNum has been reset to another number";
}
}

layer The object type contains two interfaces : The variable , It's a type , also , This is an array of Boolean values .this.idAccountIDthis.guesses

The PersistentVector The data structure is the data type of the array . During initialization , We use Context Object obtains the caller of the current smart contract through the function . then , We assign it to .Context.senderthis.id

about , We initialize a new object and assign it to . then , Use Function interfaces available on , We will a new Boolean value , Attach to variable .this.guessesPersistentVectorthis.guessespushPersistorVectorisRightthis.guesses

Let's define other types and variables that will be used when defining the core function in the next section :

...
exsport const TxFee = u128.from("500000000000000000000000");
export const WinningPrize = u128.from("100000000000000000000000");
export const Gas: u64 = 20_000_000_000_000;

...

export const players = new PersistentMap<AccountID, Player>("p")
...

Define core game features

Create a file in the folder . Here we will define the core functions of the game .index.tsassembly

In the file , Define a function , Here's the picture :index.tspickANum

import { RNG, logging, PersistentVector, Context } from "near-sdk-as";

export type AccountID = string;

@nearBindgen
export class Lottery {
...
}

@nearBindgen
export class Player {
id: AccountId;
guesses: PersistentVector<bool>;

constructor(isRight: bool) {
this.id = Context.sender;
this.guesses = new PersistorVector<bool>("g"); // choose a unique prefix per account

this.guesses.push(isRight);
}
}

In the above function , We are verifying 0.5 NEAR Token deposits , Then any player of the lottery game can call any call to play the game on the smart contract . such , Our players pay a certain amount of money before playing the game . Besides , Once the player starts the game , We will update the player's profile in the player's data structure .

Next , Let's define a function , This function will be generated randomly equal to The correct number to process the payment to the winning player luckyNum

import { TxFee, Lottery, Player, players, Gas, WinningPrize } from "./model";
import { Context, u128, ContractPromiseBatch, logging } from "near-sdk-as";

function on_payout_complete(): string {
logging.log("This winner has successfully been paid");
}

export function payout(): void {
const player = players.get(Context.sender) as Player;

for (let x = 0; x < players.guesses.length; x++) {
if (player.guesses[x] === true) {
const to_winner = ContractPromiseBatch.create(Context.sender);
const self = Context.contractName;

to_winner.transfer(WinningPrize);
to_winner
.then(self)
.function_call("on_payout_complete", "{}", u128.Zero, Gas)
}
}
}

The above functions help us transfer money to lottery winners . Use this ContractPromiseBatch object , We create and set up a transfer transaction to us as create The address passed in by the method parameter . then , Use this transfer function , We will WinningPrize The token passed to it for transaction .

Use this function_call function , We then schedule function calls when the transaction is successfully sent . For this game , We intend to call when the transaction is successful on_payout_complete Functions are functions .

For the purposes of this tutorial , We won't focus on setting up NEAR Test network or test network Wallet , But I encourage you to check the link to learn about NEAR More information about the various networks that exist in the ecosystem .

In this demonstration , We will build our lottery game to generate files in binary format , Then use this command to deploy the smart contract ..wasmnear dev-deploy

Build and deploy smart contracts

We will first use the following asb Command to build smart contracts :yarn asb

This is an alias for the command , Define... In a file located in the root directory .yarn asb --verbose --nologopackage.json

After we successfully generated build After the folder containing the files in the folder , We can deploy it by running the following command :lottery.wasmbuild/release/

near dev-deploy ./build/release/lottery.wasm

This will deploy the smart contract and provide us with the contract name or ID, We can use them on the front end or through shell The file interacts with it .

$ near dev-deploy ./lottery.wasm
Starting deployment. Account id: dev-1635968803538-35727285470528, node: https://rpc.testnet.near.org, helper: https://helper.testnet.near.org, file: ./lottery.wasm
Transaction Id 4TWTTnLEx7hpPsVMfK31DDX3gVmG4dsqoMy7sA7ypHdo
To see the transaction in the transaction explorer, please open this url in your browser


Done deploying to dev-1635968803538-35727285470528

Test our blockchain game

I've written two unit tests to confirm that our application is actually runnable . These two simple tests will create a lottery game , And will luckyNum Reset the variable to a new random number .

This folder contains test files . Run the test suite with the following command :/src/lottery/__test__

$ yarn test:unit
[Describe]: Checks for creating account

 [Success]:  creates a new game
 [Success]:  create and reset the luckyNum of a new game

    [File]: src/lottery/__tests__/index.unit.spec.ts
  [Groups]: 2 pass, 2 total
  [Result]:  PASS
[Snapshot]: 0 total, 0 added, 0 removed, 0 different
 [Summary]: 2 pass,  0 fail, 2 total
    [Time]: 19.905ms
[Result]:  PASS
   [Files]: 1 total
  [Groups]: 2 count, 2 pass
   [Tests]: 2 pass, 0 fail, 2 total
    [Time]: 13907.01ms
Done in 14.90s.

In this tutorial , We demonstrated how to create game applications on the blockchain platform . Blockchain based games can be used as multiplayer games or single player games .

You can also extend the concept of blockchain games , To include a meta section around your game ( A digital world ).Metaverse A player can form a team 、 Create a world of governance and even money as a means of value exchange . You can cast... In the world of digital games NFT Or form DAO.

 

copyright notice
author[awf133],Please bring the original link to reprint, thank you.
https://en.netfreeman.com/2022/02/202202020958100115.html

Random recommended