How to Quickly Deploy TON Game with Cocos Creator in Five Minutes (Part One)

Industry Express
2024-08-30 15:53:15
Collection
Cocos Creator, as a mainstream game editor, is being adopted by more and more developers.

The TON ecosystem is heating up in the gaming sector, attracting a large number of developers. However, from a technical perspective, issues such as EVM compatibility and programming languages still present a high barrier for many developers looking to build gaming applications on the TON underlying layer. Zypher Network, as the most advanced blockchain game development engine currently, supports the expansion of Web2 games into dApps, has developed numerous plugins, and allows developers to quickly deploy games developed with CocosCreator within the Telegram ecosystem, significantly lowering the barrier for developers to create games on the TON network.

Developer Documentation

A New Hotspot in On-chain Gaming: The TON Ecosystem

TON (The Open Network) is becoming one of the hottest public chains recently, attracting a lot of attention in a short time through its deep integration with Telegram, a social platform backed by 900 million users. Applications developed by developers based on the TON underlying layer can be seamlessly integrated into Telegram as "mini-programs," allowing users to access and use various TON ecosystem dApps directly through Telegram, greatly reducing the user access barrier.

At this stage, the TON ecosystem is becoming a new hotspot for on-chain mini-games. In addition to low development costs and overall low transaction costs on the TON chain, on-chain games can fully utilize Telegram's massive traffic pool for user conversion and viral growth. Moreover, the "mini-program applications" within Telegram can naturally combine with gaming products to enrich and expand functionalities, seamlessly supporting data storage, interactive gaming, and transaction payments. Based on this, on-chain game projects can leverage these features to provide diverse gameplay and economic models.

In fact, the popularity of some mini-games supports the above viewpoint. For example, the click game based on Telegram has become a sensation, with the popular representative Notcoin attracting over 35 million users by rewarding users for clicking the screen. Hamster Kombat publicly stated that its cumulative user count has reached 200 million. The cat-themed task mini-game Catizen has over 20 million users, with more than 500,000 paying users. Even the subscription followers of Notcoin's imitation Yescoin have already surpassed 6 million users.

The relationship between on-chain mini-games and the TON ecosystem is mutually beneficial. From user data, since the beginning of 2024, driven by a series of popular mini-games, the TON ecosystem has emerged strongly, with over 12 million active on-chain wallets as of mid-August (compared to about 1 million in January), and the number of active wallets per month is 4.2 million (about 300,000 in January).

Currently, the TON ecosystem has also attracted a large number of Web2 and Web3 game developers, who hope to capture early benefits from the massive attention system.

Technical Barriers of the TON Network

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

Therefore, whether for Web2 developers or Web3 developers, facing the TON underlying layer, there will be a certain development threshold to some extent.

Zypher Network

Zypher Network is a next-generation game engine solution centered around zero-knowledge proof technology, which helps developers more easily enter the blockchain field and deeply expand on-chain functionalities in a modular and pluggable manner, significantly lowering the barriers for developers to build blockchain games. At the same time, Zypher Network further constructs a set of underlying game facilities that can serve on-chain games based on existing on-chain infrastructure, providing perfect support for the decentralized operation of games.

Currently, Zypher Network has launched a Services SDK toolkit for developers, allowing them to directly utilize "inherent" zero-knowledge functionalities such as Shuffle and Rollup in a pluggable manner, without needing to understand the complexities of zero-knowledge circuits. This user-friendly approach can be implemented immediately, greatly simplifying the development process. Additionally, the toolkit provides various tools and circuits, allowing developers to "assemble" with minimal coding effort, similar to building with LEGO blocks. The modular approach enables the creation of custom circuit logic to meet specific requirements. Developers can start with basic operations and gradually build more complex logic to meet their needs.

Furthermore, to adapt to the vast majority of chain standards, the framework also supports third-party domain-specific languages (DSL) and zero-knowledge virtual machines (ZKVM) for game logic writing, providing customized on-chain verification SDKs for these systems to offer more flexibility and customization options.

Based on the aforementioned development toolkit, developers can deploy applications on different chains with low barriers using 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 and deployed on-chain using the engine.

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

  • From the miners' perspective, the Zypher Network will delegate zkp tasks (helping games in the network perform zero-knowledge verification and upload to the corresponding chain). Completing zero-knowledge verification work will earn rewards. The more Zypher tokens miners stake, the stronger their ability to process zero-knowledge tasks in parallel, and the higher the rewards for each task.
  • From the players' perspective, by staking Zypher tokens, they can participate in high-quality on-chain games for free. The more tokens staked, the faster the proof generation for the game, the better the gaming experience, and the more rewards they may receive.

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

Currently, Zypher Network has already enabled developers to use Cocos Creator to develop games and quickly deploy them on the TON chain. The following is the first part of the deployment tutorial, which explains how to rapidly deploy games developed with Cocos Creator onto Telegram.

Beginner's Guide: Deploying TON Games with Cocos Creator in Five Minutes (Part One)

1. Understanding Cocos Creator

Official Website

Documentation Links

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

Forum Links

  • Cocos Official Forum: https://forum.cocos.org/

2. Cocos Creator Version Overview (1.x is mostly unusable, most are 2.x, and 3.x has more 3D games)

Cocos Creator is a complete game development solution that provides an integrated development environment supporting both 2D and 3D game development. Cocos Creator adopts a component-based and data-driven workflow, simplifying the complexity of game development. It is based on the Cocos 2d-x engine and has strong extensibility and flexibility.

Main 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 editors, animation editors, particle editors, code editors, etc.
  • Script support: Mainly uses JavaScript and TypeScript to write game logic.

Main Versions of Cocos Creator and Their Differences

Cocos Creator 1.x Series

Cocos Creator 1.x is the earliest version of Cocos Creator, with main features including:

  • Basic functionality: Basic scene editing, component system, animation editor.
  • JavaScript support: Mainly uses JavaScript as the scripting language.
  • Basic plugin system: Allows developers to extend editor functionalities.
  • Web and native platform support: Can export to Web and native platforms (iOS and Android).

Cocos Creator 2.x Series

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

  • Performance optimization: Improved engine performance, especially on mobile devices.
  • TypeScript support: Introduced TypeScript support, enhancing code maintainability and type safety.
  • Physics engine integration: Built-in Box2D and Chipmunk physics engines, supporting 2D physics effects.
  • Resource management optimization: Improved resource management system for more efficient resource loading and management.
  • Enhanced UI system: Enhanced UI components and layout system, providing more powerful UI editing capabilities.

Cocos Creator 3.x Series

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

  • 3D support: Fully supports 3D game development, providing rich 3D functionalities and editor tools.
  • Unified engine architecture: Integrates 2D and 3D engines, providing a consistent API and workflow.
  • Rendering engine update: Introduced a new rendering engine that supports PBR (Physically Based Rendering), global illumination, shadows, and other advanced effects.
  • Enhanced animation system: Provides more powerful animation editing and playback features, supporting complex animation effects.
  • Optimized cross-platform support: Further optimized the export and publishing process, supporting more platforms and devices.
  • Enhanced editor: Provides richer editor plugins and extension mechanisms, enhancing developer productivity.

3. Starting the Source Code Project (Refer to the documentation for specific details if you purchased the source code)

1. Install Cocos Creator

If you haven't installed Cocos Creator yet, please visit the Cocos Official Website to download and install the latest version.

2. Open Cocos Creator

After installation, launch the Cocos Creator editor.

3. Open the Project

  1. Import Project:
  • In the Cocos Creator startup interface, click the Open Project button.
  • Browse to the folder of the Cocos Creator project source code you obtained, select that folder, and click Select Folder.
  1. Check Project Configuration:
  • After the project opens successfully, check the assets folder in the project to ensure all resource files are in the correct location.
  • Check Project -> Project Settings to ensure the project's resolution and other settings meet your needs.

4. Run the Project

  1. Select Scene:
  • In the assets folder, find your main scene file (usually ending with .fire or .scene).
  • Double-click the main scene file to open it in the editor.
  1. Run the Project:
  • Click the Play button (green triangle button) at the top of the editor to preview and run the project in the editor.
  • If the project runs normally, 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 top menu bar of the editor, select Project -> Build.
  1. Select Platform:
  • In the build panel, select Web Mobile as the target platform.
  1. Set Build Options:
  • Build Path: Set the folder path for the build output.
  • Start Scene: Choose the scene to load when the game starts.
  • Main Bundle Compression Type: Choose the compression type (e.g., None, Zip, JPG, etc.).
  • Zip Compression Level: If you selected Zip compression type, you can set the compression level.
  • MD5 Cache: Enable MD5 caching to add MD5 hash values to all resource files for version control and cache management.
  • Source Maps: Generate Source Maps files for easier debugging.
  • Debug Mode: Enable debug mode to retain debug information and log output in the published code.
  • Inline all Sprite Frames: Inline all sprite frames into one file.
  • Merge all JSON Files: Merge all JSON files into one file.
  1. Build the Project:
  • Click the Build button to start building the project.
  • After the build is complete, the build output files will be generated in the specified build path.
  1. Publish the 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 for easier debugging of the published code.
  • After publishing, you can use Source Maps in the browser's developer tools to debug the code.
  1. Enable MD5 Cache:
  • Enable the MD5 Cache option in the build panel to add MD5 hash values to all resource files.
  • This ensures that users do not load old resources due to caching issues when updating the game.
  1. Debug Mode:
  • Enable the Debug Mode option in the build panel to retain debug information and log output.
  • If debugging is needed during the publishing process, you can enable this option in the build panel.

7. Test the Project

  1. Local Testing:
  • Test the build output files on a local server to ensure the game performs and is compatible across different browsers.
  • You can use the Live Server plugin for VS Code or other local server tools for testing.
  1. Online Testing:
  • After uploading the build output files to the server, test the online version to ensure all functionalities are working correctly.

By following 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 debugging mode, MD5 caching, and other publishing attributes.

4. Example of Protect Trump: Backend Go Code Deployment Instructions

Protect Trump is a mini-game developed in collaboration between Zypher Network and a third-party development team, deployed on TON through the Zypher Network's underlying engine.

1. Create a new scene, create a node in the scene, and attach the script GameLanch.ts.

(I also included the background image for the main interface here for preloading, which is optional.)

  1. GameLanch.ts.

Configure page information in the UIConfig.ts file

Control the UI using the ui Manager interface

3. Fetching tg data

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

Also include the relevant imports in the game script for debugging mode

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

4. Briefly discuss rank

Add the UIRank.ts script to the rank page
After UIRank inherits from UIView, it can be managed through uiManager

5. Briefly discuss reward

The interface mainly has 3 scripts attached

Refer to the script for specific content

Share code:

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

Mainly modify index.html and application.js

Added a background image and progress bar

7. Publish 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, publishing is done manually, but later it can be published via command line. Don't forget the MD5 when officially launching.

Five, Explanation of the Backend Go Code for Protect Trump

1. Overview

The Protect Trump game is a backend application based on the Go language and GORM framework, primarily used to handle user login, game interaction, and reward collection for Telegram Web app users. The application communicates with the frontend through multiple RESTful API interfaces and uses a PostgreSQL database to store and manage user data, bodyguards, buff effects, and reward information.

2. Directory Structure

|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | ├── handlers # Functions for handling HTTP requests ├── middlewares # Middleware for validating Telegram data ├── models # Database model definitions ├── tasks # Scheduled tasks, such as leaderboard updates and cleanup tasks ├── utils # Utility functions, such as extracting Telegram user data └── main.go # Entry point of the application |

3. Environment Configuration

|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | DBHOST = localhost DBUSER = yourdbuser DBPASSWORD = yourdbpassword DBNAME = yourdbname DBPORT = 5432 DBSSLMODE = disable DBTIMEZONE = Asia/Shangha DBBOTTOKEN = yourtelegrambottoken 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 effects associated with the bodyguard.
  • CoinRecord: Coin records.
  • InvitedUser: Information about invited users.

In the main.go file, the following code connects to and migrates the database:

5. Scheduled Tasks

The application includes two scheduled tasks:

  1. Cleanup Task: Runs every 5 minutes to clean up invalid or expired data.
  2. Leaderboard Update Task: Runs every minute to update the user's coin leaderboard.

|-----------------------------------------------------------------------------------------------------------------| | tasks.StartCleanupTask(db, time.Minute5) tasks.StartLeaderboardUpdateTask(db, time.Minute1) |

6. Middleware

1. AuthMiddleware

  • Description: Used to validate whether the Telegram initialization data in the request is valid.
  • Parameters:
  • next: The next handler
  • bot Token: The Telegram bot's token

Six, Detailed Steps to Create a Telegram Bot and Web App

1. Create a Bot

  1. Search for BotFather
  • Open Telegram and search for BotFather, which is the official bot management tool of Telegram.
  1. Start a Conversation
  • Type /start to initiate a conversation with BotFather.
  1. Create a New Bot
  • Type /newbot to create a new bot.
  1. Enter Bot Name
  • Choose a name and enter protectRump.
  1. Enter Bot Username
  • The username must end with Bot or _bot. For example: protectRumpBot.
  1. Save the Token
  • After successful creation, BotFather will generate an API Token. Note this token for future steps.

2. Create a Web App

  1. Start Web App Creation
  • In BotFather, type /newapp to create a new Web App.
  1. Select Bot
  • Choose the bot you just created, for example, protectRumpBot.
  1. Enter Web App Name
  • Enter the name of your Web App.
  • description: Modify the description of the web app, i.e., the content of "What can this bot do?"
  1. Upload Image
  • Upload an image of 640*360 as the icon for the Web App.
  • botpic: Modify the avatar.
  1. Upload GIF
  • Upload a GIF file. If you don't have one, you can type /empty to skip this step.
  1. Enter Web App URL
  • Enter your game address, for example, https://protect-rump.zypher.game/.
  1. Enter Short Name
  • Choose a short name for the Web App link, for example, protectRump.
  1. Complete Creation
  • After successful creation, you will receive your Web App link, for example, me/protectRumpBot/protectRump.

By following these steps, you have successfully created a Telegram Bot and Web App. Next, you can integrate the game into your Web App and use the Telegram Web App interface for interaction.

3. Test Environment Configuration

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

(Not finished)

Conclusion

Cocos Creator, as a mainstream game editor, is being adopted by more and more developers. Its powerful features, familiar programming languages, flexible development environment, and extensive cross-platform support make it highly favored in the game development field. Zypher Network, through its compatibility with Cocos Creator and integration with the TON network, is significantly lowering the barriers for game developers to deploy and migrate applications to the TON network, further simplifying complex issues. After successful deployment of games, it provides support for smoother and lower-cost operation based on zero-knowledge proof solutions.

As Zypher Network expands to more on-chain ecosystems, it will also become one of the most important game infrastructure facilities in the Web3 era.

ChainCatcher reminds readers to view blockchain rationally, enhance risk awareness, and be cautious of various virtual token issuances and speculations. All content on this site is solely market information or related party opinions, and does not constitute any form of investment advice. If you find sensitive information in the content, please click "Report", and we will handle it promptly.
banner
ChainCatcher Building the Web3 world with innovators