How to quickly deploy TON games using Cocos Creator in five minutes (Part 1)

This article is machine translated
Show original

The popularity of TON ecosystem in the gaming field has attracted a large number of developers, but from a technical perspective, there are still high barriers for many developers to build game applications based on TON due to issues such as EVM compatibility and development language. Zypher Network, as the most advanced blockchain game development engine, supports the expansion of Web2 games into dApps, has developed a large number of plug-ins, and supports developers to quickly deploy games developed based on CocosCreator in the Telegram ecosystem, greatly reducing the threshold for developers to develop games based on the TON network.

Developer documentation: https://docs.zypher.network/blog/cocos-tg/

The new hot spot in the field of on-chain games: TON ecosystem

TON (The Open Network) is becoming one of the most popular public chains in recent times. It has attracted a lot of attention in a short period of time through its deep integration with Telegram, a social platform with 900 million users. Applications developed based on TON's underlying platform can be seamlessly integrated into Telegram in the form of "applets". Users can directly use Telegram as an entry point to access and use various dAPPs in the TON ecosystem, which greatly reduces the user's access threshold.

At this stage, the TON ecosystem is becoming a new hotspot for on-chain mini-games. In addition to low development costs and low overall transaction costs on the TON chain, on-chain games can make full use of Telegram's huge traffic pool to convert and fission users, and the Telegram "Mini Program Application" can naturally be combined with game products to enrich and expand functions, and seamlessly support data storage, interactive games, and transaction payments. Based on this, on-chain game projects can use these functions to provide diverse gameplay and economic models.

In fact, the popularity of some small games also confirms the above view. For example, the popularity of click games based on Telegram. The popular representative Notcoin has attracted more than 35 million users by rewarding users for clicking the screen. Hamster Kombat has disclosed user data and said that its cumulative users have reached 200 million. Catizen, a cat-themed task game, has more than 20 million users and more than 500,000 paying users. Even Notcoin's imitation Yescoin has already exceeded 6 million subscribers.

The on-chain mini-games and TON ecosystem also complement each other. Judging from user data, since the beginning of 2024, the TON ecosystem has emerged as a dark horse driven by a series of popular mini-games. As of mid-August, more than 12 million on-chain wallets have been activated (about 1 million in January), and the number of active wallets per month is 4.2 million (about 300,000 in January).

At present, the TON ecosystem has also attracted a large number of Web2 and Web3 game developers to join in, hoping to capture early dividends from the huge attention system.

Technical barriers of the TON network

In fact, TON uses a virtual machine called TVM (TON Virtual Machine), which supports smart contract programming languages mainly Fun C and TVM instruction set (although Fun C looks a lot like C language, it is generally not known or respected). These languages and virtual machine architectures are quite different from Ethereum's EVM and Solidity programming languages. At the same time, TON's design includes a multi-threaded blockchain architecture that allows different shard chains to run in parallel. This architectural design can improve network performance, but it also increases the complexity of development. Developers need to understand how to effectively coordinate data and logic between multiple shards, which is more challenging than the traditional single-chain architecture.

Therefore, whether it is Web2 developers or Web3 developers, they will more or less face certain development thresholds when facing the underlying layer of TON.

Zypher Network

Zypher Network is a new generation game engine solution with zero-knowledge proof technology as its core. It can help developers enter the blockchain field more easily and expand the on-chain functions in a modular and pluggable way, so as to greatly reduce the threshold for developers to build blockchain games. At the same time, Zypher Network further builds a set of underlying game facilities that can serve blockchain games based on the existing on-chain facilities, and provides perfect support for the decentralized operation of games.

At this stage, Zypher Network has launched a Services SDK toolkit for developers, where developers can directly use "inherent" zero-knowledge functions such as Shuffle, Rollup, etc. in a plug-and-play manner for development without having to understand the complexity of zero-knowledge circuits. This user-friendly approach can be implemented immediately, greatly simplifying the development process. At the same time, the toolkit provides a variety of gadgets and circuits that developers can "assemble" with minimal coding effort, similar to building with Lego bricks. The modular approach makes it possible to create customized circuit logic to meet specific requirements. Developers can start with basic operations and gradually build more complex logic to meet their needs.

In addition, in order to adapt to the vast majority of chain standards, the framework further supports third-party domain-specific languages (DSL) and zero-knowledge virtual machines (ZKVM) for game logic writing, and provides on-chain verification SDKs customized for these systems to provide more flexibility and customization options.

Based on the above development toolkit, developers can deploy applications on different chains with low barriers based on their familiar languages, and ensure efficient and low-cost operation of games based on Zypher Network's zk technology solution. Some Web2 games can even be directly expanded into dApps based on the engine and deployed on the chain.

At the same time, in order to provide users with a product-level zk experience, Zypher launched an economic model centered on token "staking", that is, players and on-chain verifiers (network miners) can capture resources from the network by staking Zypher tokens.

  • From the perspective of miners, the Zypher Network will delegate zkp tasks to them (helping games in the network to perform zero-knowledge verification and upload them to the corresponding chain), and they will be rewarded for completing zero-knowledge verification work. The more Zypher tokens miners stake, the stronger their ability to process zero-knowledge tasks in parallel, and the higher the reward for a single task.
  • From the perspective of players, by staking Zypher tokens, you can participate in high-quality on-chain games for free. The more tokens you stake, the faster the game's proofs are generated, the better the gaming experience, and the more rewards you may receive.

Based on the incentivized staking economic model, more validators are mobilized to participate in the operation of the network, further improving the efficiency of network operation. Players can also actively participate in different games due to the incentive bonus provided by staking, thus capturing active users on a large scale for high-quality games.

Currently, Zypher Network can support developers to develop games using Cocos Creator and quickly deploy them to the TON chain. The following is the first part of the deployment tutorial, which is how to quickly deploy games developed based on Cocos Creator to Telegram.

Beginner's Guide: Quickly deploy TON games with Cocos Creator in five minutes (Part 1)

1. Understand Cocoscreator

Official Website

Document address

  • Cocos Creator documentation: https://docs.cocos.com/creator/manual/en/
  • Cocos Creator API Reference: https://docs.cocos.com/creator/api/en/

Forum Address

  • Cocos official forum: https://forum.cocos.org/

2. Introduction to Cocoscreator versions (1. x is basically unusable, most of them are 2. x, 3. x 3D games are more common)

Cocos Creator is a complete game development solution that provides an integrated development environment and supports 2D and 3D game development. Cocos Creator uses component-based and data-driven workflows to simplify the complexity of game development. It is based on the Cocos 2D-X engine and has strong scalability and flexibility.

Key features include:

  • Component-based design: Developers can quickly build game logic by dragging and dropping components.
  • Cross-platform support: Supports exporting to multiple platforms, including Web, iOS, Android, Windows, Mac, etc.
  • Rich editing tools: Provides scene editor, animation editor, particle editor, code editor, etc.
  • Script support: Game logic is mainly written in JavaScript and TypeScript.

Cocos Creator main versions and their differences

Cocos Creator 1.x series

Cocos Creator 1.x is the earliest version of Cocos Creator, and its main features include:

  • Basic functions: basic scene editing, component system, animation editor.
  • JavaScript support: JavaScript is mainly used as the scripting language.
  • Basic plugin system: allows developers to extend editor functionality.
  • Web and Native Platform Support: You can export to the web and native platforms (iOS and Android).

Cocos Creator 2.x Series

Cocos Creator 2.x series introduces many improvements and new features:

  • Performance Optimization: Improved engine performance, especially on mobile devices.
  • TypeScript support: TypeScript support is introduced to enhance the maintainability and type safety of the code.
  • Physics engine integration: Built-in Box2D and Chipmunk physics engines, supporting 2D physics effects.
  • Resource Management Optimization: The resource management system has been improved to make resource loading and management more efficient.
  • UI system enhancement: The UI components and layout system have been enhanced to provide more powerful UI editing capabilities.

Cocos Creator 3.x Series

Cocos Creator 3.x series is a major version update, with the following main features:

  • 3D support: Fully supports 3D game development and provides rich 3D functions and editor tools.
  • Unified engine architecture: Integrates 2D and 3D engines, providing consistent APIs and workflows.
  • Rendering engine update: A new rendering engine has been introduced, which supports advanced effects such as PBR (physically based rendering), global illumination, and shadows.
  • Enhanced animation system: provides more powerful animation editing and playback functions, and supports complex animation effects.
  • Improved cross-platform support: The export and publishing process has been further optimized to support more platforms and devices.
  • Editor enhancement: Provides richer editor plug-ins and extension mechanisms to enhance developer productivity.

3. Start the source code project (if you bought a copy of the source code) See the document for details

1. Install Cocos Creator

If you haven't installed Cocos Creator yet, go to Download and install the latest version from the Cocos official website .

2. Open Cocos Creator

After the installation is complete, launch the Cocos Creator editor.

3. Open the project

  1. Import the project :
    • In the Cocos Creator startup interface, click the Open Project button.
    • Browse to the source code folder of the Cocos Creator project you obtained, select the folder, and then click Select Folder.
  2. Check the project configuration :
    • After the project is successfully opened, check the assets folder in the project to make sure all resource files are in the correct location.
    • Check Project -> Project Settings to make sure the resolution and other settings of your project are what you want.

4. Run the project

  1. Select a scene :
    • In the assets folder, find your main scene file (usually the file ending in .fire or .scene).
    • Double-click the main scene file to open it in the editor.
  2. Run the project :
    • Click the Play button (the green triangle button) at the top of the editor to preview and run the project in the editor.
    • If the project runs correctly, you will see the game screen in the editor's game window.

5. Build and publish the project to Web Mobile

  1. Open the Build panel :
    • In the editor top menu bar, select Project -> Build.
  2. Select Platform :
    • In the Build panel, select Web Mobile as the target platform.
  3. Set build options :
    • Build Path : Set the folder path for the build output.
    • Start Scene : Select the scene to load when the game starts.
    • Main Bundle Compression Type : Select the compression type (such as None, Zip, JPG, etc.).
    • Zip Compression Level : If you select the Zip compression type, you can set the compression level.
    • MD5 Cache : Enable MD5 cache and add MD5 hash values to all resource files for version control and cache management.
    • Source Maps : Generate Source Maps files for easy debugging.
    • Debug Mode : Enable debug mode to preserve debug information and log output in published code.
    • Inline all Sprite Frames : Inline all sprite frames into one file.
    • Merge all JSON Files : Merge all JSON files into one file.
  4. Build the project :
    • Click the Build button to start building the project.
    • After the build is complete, the build output files are generated in the set build path.
  5. Release Project :
    • Upload the generated build output files to a server that supports HTTPS. You can use GitHub Pages, Netlify, Vercel, or other static website hosting services.

6. Debugging and Optimization

  1. Enable Source Maps :
    • Enable the Source Maps option in the build panel to generate Source Maps files, which makes it easier to debug the released code.
    • After publishing, you can use Source Maps to debug your code in your browser's developer tools.
  2. Enable MD5 caching :
    • Enable the MD5 Cache option in the Build panel to add MD5 hashes to all asset files.
    • This ensures that when users update the game they will not be loading old assets due to caching issues.
  3. Debug mode :
    • Enable the Debug Mode option in the Build panel to preserve debug information and log output.
    • During release, if debugging is required, you can enable this option in the build panel.

7. Test items

  1. Local testing :
    • Test the build output files on a local server to ensure the performance and compatibility of the game on different browsers.
    • You can use the Live Server plugin for VS Code or other local server tools for testing.
  2. Online test :
    • After uploading the build output files to the server, test the online version to ensure that all functions are running normally.

Through these steps, you can successfully start and publish a Cocos Creator project source code to the Web platform, and understand the configuration and use of publishing properties such as debug mode and MD5 cache.

4. Taking Protect Trump as an example, the backend go code deployment instructions

Protect Trump is a small game developed by Zypher Network in collaboration with a third-party development team. The game is deployed on TON through the Zypher Network underlying engine.

1. Create a new scene, create a new node in the scene, and mount the script GameLanch.ts.
(I also put the background image of the main interface here, so that you can load it in advance, but you don’t have to put it.)


2.GameLanch.ts.

Configure page information in UIConfig.ts file and use UI Manager's interface to control UI

uiManager . open ( UIID . UILoading );

3.tg data acquisition

Add the import in the template folder build-teleplates/web-mobile/index.html

script async src="https://telegram.org/js/telegram-web-app.js"> script >

Related imports are also included in the game script. Convenient for use in debug mode

// Create and insert the script for the Telegram Web App SDK

loadTelegramSDK () {

// this . url . string = ' loadTelegramSDK '

return new Promise (( resolve , reject ) => {

if ( window [' Telegram '] && window [' Telegram ']. WebApp ) {

// Telegram SDK has been loaded

console . log (' Telegram SDK has been loaded:', window [' Telegram ']);

window [' Telegram ']. WebApp . ready ();

resolve ();

return ;

}

const script = document . createElement (' script ');

script .src = 'https://telegram.org/js/telegram-web-app.js';

script . onload = () => {

console . log (' SDK loaded successfully:', window [' Telegram ']);

window [' Telegram ']. WebApp . ready ();

// SDK loaded successfully

resolve ();

};

script . on error = error => {

console . log (' SDK loading failed:', error );

// SDK loading failed

reject ( error );

};

document . head . appendChild ( script );

});

}

processInitData() {

const initData = window [' Telegram ']?. WebApp ?. initData;

if ( initData ) {

const searchParams = new URLSearchParams ( initData );

const WebAppData = {};

for ( const [ key , value ] of searchParams . entries ()) {

WebAppData [ key ] = value ;

}

console .log (' WebAppData :', WebAppData );

// Get user information

const user = window [' Telegram ']. WebApp . initDataUnsafe;

console .log (' User :', user );

// this . WebAppData = WebAppData ;

// Handle window size changes

window [' Telegram ']. WebApp . onEvent (' resize ', function () {

// Update the UI

console . log ('Update UI:');

});

this .tgInitData = initData;

} else {

console . warn (' Telegram WebApp initData is not available .');

}

}

async initTelegram () {

try {

await this .loadTelegramSDK ();

this . processInitData ();

} catch ( error ) {

console . error (' Failed to load Telegram SDK :', error );

}

}

Send the obtained window ['Telegram']?.WebApp?.initData; to the server for verification

4. Briefly explain rank

Add UIRank . ts script to the rank page
After UIRank inherits the UIView class, you can manage the page through uiManager

export default class UIRank extends UIView
//Get the ranking data
let ranksRes = await Http . getAllCoinsRank ( PlayerModel . inst . tgInitData );

this . list . refreshData ( ranks ); //Display to the component

5. Briefly explain reward

The interface mainly hangs 3 scripts

UIReward.ts //The page script mainly controls the reward and invitation list pages
RewardTabCtrl . ts //Control the display content of rewards and invitations
InviteTabCtrl . ts //Control the display of the invitation list

See the script for details

Share code:

onCopy () {
le t l in k Url = PlayerModel . in st . l in k ?. in vi te _ l in k ;
t his . tg _ l in k . str in g = l in k Url;
// Copy invitation link to clipboard t his . copy T oClipboard ( l in k Url + " Hey t he re ! I jus t found t his aweso me T elegram ga me called Pro t ec t T - RUMP ! Jo in me in defend in g T rump from various t hrea ts dur in gt he campaign . We can hire and t ra in bodyguards , comp le te exci t in g mission s , and team up with friends to keep T rump safe . Click now to earn even more rewards ! �✨");
uiManager . open (UII D. CopySuccess );
}

onInvi te() {
le t l in k Url = PlayerModel . in st . l in k ?. in vi te _ l in k ;
// Copy the invitation link to the clipboard t his . copy T oClipboard ( link Url );
t his .onShareBu tton Click ( l in k Url ,' Hey t he re ! I jus t found t his aweso me T elegram ga me called Pro t ec t T - RUMP ! Jo in me in defend in g T rump from various t hrea ts dur in gt he campaign . We can hire and t ra in bodyguards , comp le te exci t in g missions , and t eam up with th friends to keep T rump safe . Click now to earn even more rewards ! �✨')
}

onShareBu tton Click ( url , t ex t = '') {
cons t share Url = ' htt ps :// t . me / share / url ? url =' + encodeUR I Componen t ( url ) + '& t ex t =' + encodeUR I Componen t ( t ex t );
w in dow. open ( share Url , '_ blank ');
}

6. Modify the startup page. Modify the startup page in the template.

Mainly modify index.html and application.js

Added a background image and progress bar

7. Release the game

https://docs.cocos.com/creator/3.8/manual/zh/editor/publish/publish-web.html

https://docs.cocos.com/creator/3.8/manual/zh/editor/publish/custom-project-build-template.html

Refer to these two documents. Currently, they are published manually. Later, they can be published by command line. Don't forget to use md5 when it is officially launched.

5. Protect Trump backend go code description

1. Overview

As a backend application based on the Go language and GORM framework, the Protect Trump game is mainly used to handle the login, game interaction, and reward collection functions of Telegram Web application users. The application communicates with the front end through multiple RESTful API interfaces, and uses the PostgreSQL database to store and manage user data, bodyguards, buffs, and reward information.

2. Directory Structure

.
├── handlers # Functions that handle HTTP requests ├── middlewares # Middlewares for verifying Telegram data ├── models # Database model definition ├── tasks # Scheduled tasks, such as leaderboard updates and cleanup tasks ├── utils # Utility functions, such as extracting Telegram user data └── main . go # Application entry

3. Environment Configuration

DB_HOST = localhost
DB_USER = your_db_user
DB_PASSWORD = your_db_password
DB_NAME = your_db_name
DB_PORT =5432
DB_SSLMODE = disable
DB_TIMEZONE=Asia/Shanghai
TG_BOT_TOKEN = your_telegram_bot_token
PORT =8080

4. Database configuration and migration

The application uses GORM for database operations and will automatically migrate the following data models at startup:

  • User: User information, including Telegram ID, username, coins, etc.
  • Bodyguard: Bodyguard information, associated with the user.
  • Buff: Buff effect (Buff), associated with bodyguard.
  • CoinRecord: Gold coin record.
  • InvitedUser : Invited user information.

In the main.go file, connect and migrate the database using the following code:

dsn := " h os t =" + os . Geten v (" DB _ HOST ") +
" user =" + os . Geten v (" DB _ USER ") +
" password =" + os . Geten v (" DB _ PASSWORD ") +
" db name =" + os . Geten v (" DB _ NAME ") +
" port =" + os . Geten v (" DB _ PORT ") +
" sslmode =" + os . Geten v (" DB _ SSLMODE ") +
" TimeZone =" + os . Geten v (" DB _ TIMEZONE ")

db , err := gorm . Open (p os tgres. Open ( dsn ), & gorm . Config {})
if err != nil {
log . Fatalf (" Failed to connect to the database : % v ", err )
}

db .Au to Migrate(& models . User {}, & models . Bodyguard {}, & models . Buff {}, & models . CoinRecord {}, & models .In v ited User {})

5. Scheduled tasks

The application contains two scheduled tasks:

  1. Cleanup task : runs every 5 minutes to clean up invalid or expired data.
  2. Ranking update task : runs once every minute to update the user's gold coin ranking

tasks . StartCleanupTask ( db , time . Minute *5)
tasks . StartLeaderboardUpdateTask ( db , time . Minute *1)

6. Middleware

1. AuthMiddleware

  • Description : Used to verify whether the Telegram initialization data in the request is valid.
  • parameter :
    • next : next handler
    • bot Token: Telegram robot token

func AuthMiddle ware ( next http . Handle r Func , botToken st r ing ) http . Handle r Func {
r etu rn func ( w http . ResponseW r ite r , r * http . Request ) {
body , err := io . ReadAll ( r . Body )
if err != nil {
http .Error ( w , "Invalid request body", http .StatusBad Request )
r etu rn
}
deferr . Body . Close ()

va r r eq st r uct {
Teleg r amInitData st r ing ` json :"teleg r am_ init _ data "`
}
if err := json .Unma r shal( body , & r eq); err != nil {
http .Error ( w , "Invalid request body", http .StatusBad Request )
r etu rn
}

if !validateTeleg r amData( r eq.Teleg r amInitData, botToken ) {
http .Error ( w , "Invalid Telegram data", http .StatusUnnautized)
r etu rn
}

r . Body = io .Nop Close r ( bytes .Ne w Buffe r ( body ))
next .ServeHTTP( w , r )
}
}

6. Detailed steps to create Telegram Bot and Web App

1. Create a Bot

  1. Search for BotFather
    • Open Telegram and search for Bot Father, which is Telegram's official Bot management tool.
  2. Start a conversation
    • Type /start to start a conversation with BotFather.
  3. Create a new Bot
    • Type /newbot to create a new Bot.
  4. Enter Bot Name
    • Choose a name and enter protectRump.
  5. Enter Bot Username
    • Username must end with Bot or _bot. For example: protectRump Bot.
  6. Save Token
    • After successful creation, BotFather will generate an API Token. Note this Token for subsequent steps.

2. Create a Web App

  1. Start Web App Creation
    • Type /newapp in BotFather to create a new Web App.
  2. Select Bot
    • Select the Bot you just created, for example protectRump Bot.
  3. Enter the Web App name
    • Enter a name for your Web App.
    • description Modify the description of the webapp. That is, the content of What can this bot do?
  4. Upload pictures
    • Enter a 640*360 picture as the icon of the Web App.
    • botpic modify avatar
  5. Upload GIF
    • Enter a GIF file. If you don't have one, you can skip this step by typing /empty.
  6. Enter the Web App URL
    • Enter your game address, for example https://protect-rump.zypher.game/.
  7. Enter short name
    • Give it a short name to be used in the Web App link, such as protectRump.
  8. Complete creation
    • After successful creation, you will get your Web App link, such as me/protectRump Bot/protectRump.

Through the above steps, you have successfully created a Telegram Bot and Web App. Next, you can integrate the game in your Web App and interact with it using Telegram's Web App interface.

3. Test environment configuration

https://core.telegram.org/bots/webapps #us-in-g-bots-in-the-test-environment

(To be continued)

Summarize

As the current mainstream game editor, Cocos Creator is being adopted by more and more developers. Its powerful functions, familiar programming process, flexible development environment and wide cross-platform support make it popular in the field of game development. Zypher Network is significantly reducing the threshold for game developers to deploy and migrate applications to the TON network through compatibility with Cocos Creator and integration with the TON network, further simplifying complex issues. After the game is successfully deployed, it provides support for smoother and lower-cost operation of the game based on the zero-knowledge proof solution.

As Zypher Network expands to more on-chain ecosystems, it will become the most important gaming infrastructure in the Web3 era.

Source
Disclaimer: The content above is only the author's opinion which does not represent any position of Followin, and is not intended as, and shall not be understood or construed as, investment advice from Followin.
Like
Add to Favorites
Comments