시가총액: $2.2006T 0.82%
거래량(24시간): $38.5475B -31.41%
  • 시가총액: $2.2006T 0.82%
  • 거래량(24시간): $38.5475B -31.41%
  • 공포와 탐욕 지수:
  • 시가총액: $2.2006T 0.82%
암호화
주제
암호화
소식
cryptostopics
비디오
최고의 뉴스
암호화
주제
암호화
소식
cryptostopics
비디오
bitcoin
bitcoin

$87959.907984 USD

1.34%

ethereum
ethereum

$2920.497338 USD

3.04%

tether
tether

$0.999775 USD

0.00%

xrp
xrp

$2.237324 USD

8.12%

bnb
bnb

$860.243768 USD

0.90%

solana
solana

$138.089498 USD

5.43%

usd-coin
usd-coin

$0.999807 USD

0.01%

tron
tron

$0.272801 USD

-1.53%

dogecoin
dogecoin

$0.150904 USD

2.96%

cardano
cardano

$0.421635 USD

1.97%

hyperliquid
hyperliquid

$32.152445 USD

2.23%

bitcoin-cash
bitcoin-cash

$533.301069 USD

-1.94%

chainlink
chainlink

$12.953417 USD

2.68%

unus-sed-leo
unus-sed-leo

$9.535951 USD

0.73%

zcash
zcash

$521.483386 USD

-2.87%

암호화폐 뉴스 기사

비트코인 SV 블록체인에서 풀스택 분산형 Tic-Tac-Toe Dapp 구축: 최고의 가이드

2024/04/09 17:00

"이 기사는 비트코인 ​​SV 블록체인에서 풀 스택 분산형 앱을 개발하기 위한 Web3 기술 스택에 대한 포괄적인 개요를 제공합니다. 기술 스택에는 sCrypt Frameworks, Yours Wallet 및 React가 포함됩니다. 풀 스택 분산형 tic-tac-toe를 구축하는 프로세스 게임은 스마트 계약 작성, 계약 배포, 프런트 엔드 통합(React 사용), 지갑 통합 등을 포함하여 자세히 설명되어 있습니다. 가이드를 따르면 독자는 비트코인 ​​SV에서 완전한 기능을 갖춘 분산형 앱을 구축하는 방법을 이해할 수 있습니다. 블록체인."

비트코인 SV 블록체인에서 풀스택 분산형 Tic-Tac-Toe Dapp 구축: 최고의 가이드

Build a Full-Stack Decentralized Tic-Tac-Toe App on the Bitcoin SV Blockchain: A Comprehensive Guide

비트코인 SV 블록체인에서 전체 스택 분산형 Tic-Tac-Toe 앱 구축: 종합 가이드

Introduction

소개

In this detailed guide, we will guide you through the process of building a complete full-stack decentralized Tic-Tac-Toe application on the Bitcoin SV (BSV) blockchain. This comprehensive journey will cover the creation of a smart contract, deploying it, integrating a front-end using React, and connecting to a user's wallet. By the end, you will possess a fully functional Tic-Tac-Toe application running seamlessly on the BSV blockchain.

이 세부 가이드에서는 비트코인 ​​SV(BSV) 블록체인에 완전한 풀스택 분산형 Tic-Tac-Toe 애플리케이션을 구축하는 과정을 안내합니다. 이 포괄적인 여정에서는 스마트 계약 생성, 배포, React를 사용한 프런트 엔드 통합, 사용자 지갑 연결 등을 다룹니다. 결국, 귀하는 BSV 블록체인에서 원활하게 실행되는 완전한 기능을 갖춘 Tic-Tac-Toe 애플리케이션을 보유하게 될 것입니다.

Prerequisites

전제조건

To embark on this adventure, you will need the following prerequisites:

이 모험을 시작하려면 다음 전제 조건이 필요합니다.

  • Node.js (version 16 or higher)
  • npm
  • Git
  • Yours Wallet Chrome extension
  • sCrypt CLI (installed using npm install -g scrypt-cli)

Technology Stack

Node.js(버전 16 이상)npmGitYours Wallet Chrome 확장Crypt CLI(npm install -g scrypt-cli를 사용하여 설치)기술 스택

Our tech stack consists of the following key components:

우리의 기술 스택은 다음과 같은 주요 구성 요소로 구성됩니다.

  • sCrypt Framework: TypeScript framework for developing BSV smart contracts.
  • Yours Wallet: Open-source digital wallet for BSV that enables interaction with decentralized applications built on BSV.
  • React: JavaScript library for building user interfaces.

Designing the Contract

sCrypt 프레임워크: BSV 스마트 계약 개발을 위한 TypeScript 프레임워크.Yours Wallet: BSV에 구축된 분산 애플리케이션과 상호 작용할 수 있는 BSV용 오픈 소스 디지털 지갑.React: 사용자 인터페이스 구축을 위한 JavaScript 라이브러리.계약 설계

Let's define the blueprint of our game. The Tic-Tac-Toe contract will be initialized with the Bitcoin addresses of two players, Alice and Bob. They will wager the same amount and lock their bets in the contract. The winner claims the entire pot, while a draw results in an equal split between both players.

게임의 청사진을 정의해 봅시다. Tic-Tac-Toe 계약은 Alice와 Bob이라는 두 플레이어의 비트코인 ​​주소로 초기화됩니다. 그들은 동일한 금액을 베팅하고 계약에 베팅을 고정합니다. 승자가 전체 팟을 차지하며, 무승부로 인해 두 플레이어가 균등하게 분배됩니다.

Creating the Contract

계약 생성

Using the sCrypt framework, we will create the contract in TypeScript in the src/contracts/tictactoe.ts file:

sCrypt 프레임워크를 사용하여 src/contracts/tictactoe.ts 파일에 TypeScript로 계약을 생성합니다.

import {

수입 {

prop,

소품,

method,

방법,

SmartContract,

스마트계약,

PubKey,

퍼브키,

FixedArray,

고정배열,

assert,

주장하다,

Sig,

말하다,

Utils,

유틸리티,

toByteString,

toByteString,

hash160,

해시160,

hash256,

해시256,

fill,

채우다,

ContractTransaction,

계약거래,

MethodCallOptions,

MethodCall옵션,

bsv

bsv

} from "scrypt-ts";

} "scrypt-ts"에서;

export class TicTacToe extends SmartContract {

내보내기 클래스 TicTacToe는 SmartContract를 확장합니다.

@prop()

@소품()

alice: PubKey;

앨리스: PubKey;

@prop()

@소품()

bob: PubKey;

밥: PubKey;

@prop(true)

@prop(참)

isAliceTurn: boolean;

isAliceTurn: 부울;

@prop(true)

@prop(참)

board: FixedArray;

보드:FixedArray;

static readonly EMPTY: bigint = 0n;

정적 읽기 전용 비어 있음: bigint = 0n;

static readonly ALICE: bigint = 1n;

정적 읽기 전용 ALICE: bigint = 1n;

static readonly BOB: bigint = 2n;

정적 읽기 전용 BOB: bigint = 2n;

constructor(alice: PubKey, bob: PubKey) {

constructor(alice: PubKey, bob: PubKey) {

super(...arguments);

super(...인수);

this.alice = alice;

this.alice = 앨리스;

this.bob = bob;

this.bob = 밥;

this.isAliceTurn = true;

this.isAliceTurn = true;

this.board = fill(TicTacToe.EMPTY, 9);

this.board = fill(TicTacToe.EMPTY, 9);

}

}

@method()

@방법()

public move(n: bigint, sig: Sig) {

공개 이동(n: bigint, sig: Sig) {

// check position `n`

// 위치 `n` 확인

assert(n >= 0n && n < 9n);

주장(n >= 0n && n < 9n);

// check signature `sig`

// 서명 확인 `sig`

let player: PubKey = this.isAliceTurn ? this.alice : this.bob;

플레이어에게: PubKey = this.isAliceTurn ? this.alice : this.bob;

assert(this.checkSig(sig, player), `checkSig failed, pubkey: ${player}`);

주장(this.checkSig(sig, player), `checkSig failed, pubkey: ${player}`);

// update stateful properties to make the move

// 이동을 위해 상태 저장 속성을 업데이트합니다.

assert(this.board[Number(n)] === TicTacToe.EMPTY, `board at position ${n} is not empty: ${this.board[Number(n)]}`);

주장(this.board[Number(n)] === TicTacToe.EMPTY, `${n} 위치의 보드가 비어 있지 않습니다: ${this.board[Number(n)]}`);

let play = this.isAliceTurn ? TicTacToe.ALICE : TicTacToe.BOB;

플레이하자 = this.isAliceTurn ? TicTacToe.ALICE : TicTacToe.BOB;

this.board[Number(n)] = play;

this.board[Number(n)] = 플레이;

this.isAliceTurn = !this.isAliceTurn;

this.isAliceTurn = !this.isAliceTurn;

// build the transation outputs

// 트랜잭션 출력을 빌드합니다.

let outputs = toByteString('');

출력 = toByteString('');

if (this.won(play)) {

if (this.won(play)) {

outputs = Utils.buildPublicKeyHashOutput(hash160(player), this.ctx.utxo.value);

출력 = Utils.buildPublicKeyHashOutput(hash160(player), this.ctx.utxo.value);

}

}

}

else if (this.full()) { const halfAmount = this.ctx.utxo.value / 2n;

const halfAmount = this.ctx.utxo.value / 2n;

const aliceOutput = Utils.buildPublicKeyHashOutput(hash160(this.alice), halfAmount);

const aliceOutput = Utils.buildPublicKeyHashOutput(hash160(this.alice), halfAmount);

const bobOutput = Utils.buildPublicKeyHashOutput(hash160(this.bob), halfAmount);

const bobOutput = Utils.buildPublicKeyHashOutput(hash160(this.bob), halfAmount);

outputs = aliceOutput + bobOutput;

출력 = aliceOutput + bobOutput;

}

}

}

else { // build a output that contains latest contract state.

// 최신 계약 상태가 포함된 출력을 작성합니다.

outputs = this.buildStateOutput(this.ctx.utxo.value);

출력 = this.buildStateOutput(this.ctx.utxo.value);

}

}

}

if (this.changeAmount > 0n) {

if (this.changeAmount > 0n) {

outputs += this.buildChangeOutput();

출력 += this.buildChangeOutput();

}

}

}

// make sure the transaction contains the expected outputs built above

// 위에서 빌드한 예상 출력이 트랜잭션에 포함되어 있는지 확인합니다.

assert(this.ctx.hashOutputs === hash256(outputs), "check hashOutputs failed");

주장(this.ctx.hashOutputs === hash256(outputs), "check hashOutputs 실패");

}

}

@method()

@방법()

won(play: bigint): boolean {

won(play: bigint): 부울 {

let lines: FixedArray, 8> = [

라인을 보자: FixArray = [

[0n, 1n, 2n],

[0n, 1n, 2n],

[3n, 4n, 5n],

[3n, 4n, 5n],

[6n, 7n, 8n],

[6n, 7n, 8n],

[0n, 3n, 6n],

[0n, 3n, 6n],

[1n, 4n, 7n],

[1n, 4n, 7n],

[2n, 5n, 8n],

[2n, 5n, 8n],

[0n, 4n, 8n],

[0n, 4n, 8n],

[2n, 4n, 6n]

[2n, 4n, 6n]

];

];

let anyLine = false;

anyLine = false로 두십시오.

for (let i = 0; i < 8; i++) {

for (let i = 0; i < 8; i++) {

let line = true;

라인 = true;

for (let j = 0; j < 3; j++) {

for (j = 0; j < 3; j++) {

line = line && this.board[Number(lines[i][j])] === play;

line = line && this.board[Number(lines[i][j])] === play;

}

}

}

}

anyLine = anyLine || line;

anyLine = anyLine || 선;

}

}

}

return anyLine;

anyLine을 반환합니다.

}

}

@method()

@방법()

full(): boolean {

전체(): 부울 {

let full = true;

전체 = 사실로 두십시오;

for (let i = 0; i < 9; i++) {

for (let i = 0; i < 9; i++) {

full = full && this.board[i] !== TicTacToe.EMPTY;

전체 = 전체 && this.board[i] !== TicTacToe.EMPTY;

}

}

}

return full;

가득 차서 돌아오다;

}

}

}

Integrating the Front-End with React

}React와 프런트엔드 통합

Time to connect our contract with the user interface. After compiling the contract and generating the artifact file, we will use it to initialize the contract in the front-end:

계약을 사용자 인터페이스와 연결할 시간입니다. 계약을 컴파일하고 아티팩트 파일을 생성한 후 이를 사용하여 프런트엔드에서 계약을 초기화합니다.

import {

수입 {

TicTacToe } from './contracts/tictactoe'; import artifact from '../artifacts/tictactoe.json';

'../artifacts/tictactoe.json'에서 아티팩트 가져오기;

TicTacToe.loadArtifact(artifact);

Connect to the Wallet

TicTacToe.loadArtifact(artifact);지갑에 연결

We will use Yours Wallet to connect to the BSV network and interact with our contract.

우리는 Yours Wallet을 사용하여 BSV 네트워크에 연결하고 계약과 상호 작용합니다.

Call the Contract

계약서 호출

Now, we can enable users to play the game. Each move triggers a contract call, updating its state:

이제 사용자가 게임을 플레이할 수 있게 되었습니다. 각 이동은 계약 호출을 트리거하여 상태를 업데이트합니다.

const { tx: callTx } = await p2pkh.methods.unlock(

const { tx: callTx } = p2pkh.methods.unlock을 기다립니다(

(sigResponses: SignatureResponse[]) => findSig(sigResponses, $publickey),

(sigResponses: SignatureResponse[]) => findSig(sigResponses, $publickey),

$publickey,

$공개키,

{

{

pubKeyOrAddrToSign: $publickey.toAddress()

pubKeyOrAddrToSign: $publickey.toAddress()

}

}

as MethodCallOptions );

Conclusion

);결론

Congratulations! You have successfully created a fully functional Tic-Tac-Toe dApp on the BSV blockchain. This adventure has showcased the power of this cutting-edge technology stack.

축하해요! 귀하는 BSV 블록체인에서 완전한 기능을 갖춘 Tic-Tac-Toe dApp을 성공적으로 생성했습니다. 이 모험은 최첨단 기술 스택의 힘을 보여주었습니다.

Additional Resources

추가 리소스

  • Explore the code: https://github.com/[repo URL]
  • Learn more about sCrypt: https://github.com/moneybutton/sCrypt/blob/master/README.md
  • Access the Yours Wallet: https://yours.bitcoin.com/
  • Discover more about Bitcoin SV: https://www.bitcoinsv.io/
  • Join the sCrypt Hackathon 2024 (March 17, 2024): [registration link]

May this comprehensive guide inspire you to build more innovative and engaging decentralized applications on the BSV blockchain.

코드 탐색: https://github.com/[repo URL]sCrypt에 대해 자세히 알아보기: https://github.com/moneybutton/sCrypt/blob/master/README.mdYours 지갑에 액세스: https://yours. bitcoin.com/비트코인 SV에 대해 자세히 알아보세요: https://www.bitcoinsv.io/sCrypt Hackathon 2024 참여(2024년 3월 17일): [등록 링크] 이 종합 가이드가 귀하가 더욱 혁신적이고 매력적인 분산형 애플리케이션을 구축하는 데 영감을 주기를 바랍니다 BSV 블록체인에서.

부인 성명:info@kdj.com

제공된 정보는 거래 조언이 아닙니다. kdj.com은 이 기사에 제공된 정보를 기반으로 이루어진 투자에 대해 어떠한 책임도 지지 않습니다. 암호화폐는 변동성이 매우 높으므로 철저한 조사 후 신중하게 투자하는 것이 좋습니다!

본 웹사이트에 사용된 내용이 귀하의 저작권을 침해한다고 판단되는 경우, 즉시 당사(info@kdj.com)로 연락주시면 즉시 삭제하도록 하겠습니다.

2026年07月27日 에 게재된 다른 기사