×
Community Blog ROS CDK Guide: Build Your Game World (TypeScript)

ROS CDK Guide: Build Your Game World (TypeScript)

This article instructs you to learn how to use ROS CDK and ECS to deploy 2048 games and enjoy cloud-based games.

1. Introduction

In the world of virtual games, digitalization composes the shared memories of numerous players. In this world full of creativity and adventure, your goal is to combine a unique gaming experience with various technical knowledge to create something unforgettable. To realize this goal, you may wonder how to deploy a simple and interesting game to the cloud so that more players can share the fun.

Don't worry. You now have a tool, that is, the Cloud Development Kit (CDK) provided by Alibaba Cloud Resource Orchestration Service (ROS). With this powerful tool, you can easily create and manage cloud resources and securely and quickly deploy your 2048 games to the cloud.

In the following article, we will guide you through the process of deploying the 2048 game to an Alibaba Cloud instance using ROS CDK, providing a solid cloud foundation for your game. To help you avoid complicated configurations and tedious operations, we will guide you through the simplest steps to deploy your game, achieving a seamless migration from local to cloud.

2. Background

2.1 What is ROS CDK?

Imagine you are a game designer with a brand-new game world to build. In the traditional development process, you may need to build each element step by step and repeatedly test and optimize them, which is time-consuming and laborious and needs to handle a large number of technical details. However, with the Alibaba Cloud Resource Orchestration Service (ROS) Cloud Development Kit (CDK), you can easily generate the entire architecture of your game through a short piece of code.

ROS CDK is a powerful development framework that allows you to define, build, and deploy cloud resources with familiar programming languages. ROS CDK allows you to convert infrastructure into code (Infrastructure as Code, IaC) and create and configure cloud resources as easily as writing game logic.

This framework helps you write intuitive code that describes the overall structure of the game instead of configuring each component individually. These codes are then converted to specific cloud resource configurations, such as Elastic Compute Service (ECS), Object Storage Service (OSS), and database services, and quickly deployed on the cloud. This streamlined process makes the entire development process more efficient and repeatable, helping developers easily collaborate and share resources across teams.

Infrastructure as code reduces the risk of human error and makes cloud service management as easy as playing games. ROS CDK provides great convenience for the rapid development, upgrading, and scaling of game applications so that you can devote more energy to creativity and design rather than being plagued by tedious operations. In short, ROS CDK gives you endless possibilities to build the game world on the cloud, allowing your creativity to be realized in this digital world.

2.2 What is ECS?

In the vast domain of cloud computing, you are a developer in pursuit of knowledge and capability, eager to create a multitude of diverse applications and services. On this journey, you need a powerful supporter to provide continuous computing resources for your projects, that is, ECS.

ECS has numerous flexible and scalable instances, each of which provides powerful computing capabilities and can be combined to meet any of your needs. Whether for lightweight applications or complex computing tasks, ECS can respond quickly.

Deploying your applications on ECS is like setting up a permanent and reliable hosting environment for them. No matter what happens, ECS provides you with highly reliable computing power to ensure that every idea can be turned into reality in an instant, supporting the continuous development of your applications.

Like an assistant, ECS guides you to flexibly deploy and manage computing resources. Its intelligent monitoring and auto-scaling capabilities enable you to fully control the flow of demand without worrying about the shortage and waste of resources. Robust security features, such as network isolation and access control, protect your applications from external intrusion, ensuring that your development and creative work can thrive in a secure environment.

In Alibaba Cloud, ECS has become the best partner for every developer to realize their creative visions and explore endless possibilities. No matter how grand your dreams or how challenging the tasks are, ECS will always be a reliable platform where you can fully unleash your wisdom and creativity on the cloud. Therefore, as you prepare to plan your future on the cloud, ECS will be an indispensable tool, helping you to achieve greater success.

3. Preparations

3.1 Language Requirements

Before entering the IaC world, we still need some preparations. To install ROS CDK, Node.js and TypeScript of the following versions are used:

Node.js: 14.17.0 or later

TypeScript: 3.8 or later

3.2 Initialize the Project

First, install ROS CDK.

Note: Please make sure that the version of ros-cdk-cli you install is 1.0.50 or later. You can confirm it by running npm list -g.

In your practice, whenever you plan to start a new project, you need to make some preparations in your programming environment. You need to ensure you have a project framework, configurations, and access credentials for the cloud platform.

Initializing the project is like laying out a blueprint in your programming environment with the basic outline of the project to be completed. On your computer, this means creating a new directory containing the necessary file structure, giving the developers a place to code.

Configuring credential information is to obtain an AccessKey, which grants you the authority to control resources and manage data on the cloud. In the Alibaba Cloud world, this means that you need to configure the AccessKey ID and Secret AccessKey for authentication in the local environment. In this way, when you use ROS CDK, it ensures that you are an authorized developer with the rights to manage these cloud resources, rather than an unintentional intruder.

Before we proceed with more advanced tasks, let's first set up the environment.

1.  Run the following command to create a project directory and initialize the project:

mkdir demo
cd demo
ros-cdk init --language=typescript --generate-only=true

2.  Run the following command to configure an Alibaba Cloud credential:

ros-cdk config

3.  Set the credential parameters:

endpoint(optional, default:https://ros.aliyuncs.com):
defaultRegionId(optional, default:cn-hangzhou):

[1] AK
[2] StsToken
[3] RamRoleArn
[4] EcsRamRole
[0] CANCEL

Authenticate mode [1...4 / 0]: 1
accessKeyId:************************
accessKeySecret:******************************

✅ Your cdk configuration has been saved successfully!

Parameter description:

endpoint: the endpoint of ROS. Default value: https://ros.aliyuncs.com

defaultRegionId: the ID of the region where you want to deploy the ROS stack. Default value: cn-hangzhou.

Authenticate mode: the authentication method. In this example, an AccessKey pair is used for authentication. In this case, you must specify the AccessKey ID and the AccessKey Secret. For more information about how to obtain an AccessKey pair, see Configure a credential in interactive mode (fast).

With everything ready, let us begin our journey with ROS CDK.

4. Best Practice: Deploy 2048 Games in the Cloud

In this part, we will use a best practice case to demonstrate how to deploy 2048 games on a cloud server.

Before performing the following steps, make sure that you have completed all necessary preparations, including environment configuration and project initialization.

4.1 Install Dependencies

First, we need to install the dependencies required for developing the CDK project.

Enter the project initialized in the "Preparations" step and modify the contents of the package.json file as follows:

{
  "name": "demo",
  "version": "0.1.0",
  "bin": {
    "demo": "bin/demo.js"
  },
  "scripts": {
    "build": "tsc",
    "test": "jest"
  },
  "devDependencies": {
    "@types/jest": "^25.2.1",
    "@types/node": "10.17.5",
    "typescript": "^3.9.7",
    "jest": "^25.5.0",
    "ts-jest": "^25.3.1",
    "ts-node": "^8.1.0",
    "babel-jest": "^26.6.3",
    "@babel/core": "^7.12.9",
    "@babel/preset-env": "7.12.7",
    "@babel/preset-typescript": "^7.12.7",
    "@alicloud/ros-cdk-assert": "^1.1.0"
  },
  "dependencies": {
    "@alicloud/ros-cdk-core": "^1.1.0",
    "@alicloud/ros-cdk-ecs": "^1.1.0"
  }
}

After the modification is complete, run the following command to install dependencies:

npm install

4.2 Add Resources

In this part, we will add resources to the project. The resources involved in this example include:

ALIYUN::ECS::SecurityGroup

ALIYUN::ECS::SecurityGroupIngress

ALIYUN::ECS::Instance

ALIYUN::ECS::VPC

ALIYUN::ECS::VSwitch

ALIYUN::ECS::RunCommand

The billable items involved in this project include:

ECS: pay-as-you-go

Go to the project directory and modify the contents of lib/demo-stack.ts as follows:

import * as ros from '@alicloud/ros-cdk-core';
import * as ecs from '@alicloud/ros-cdk-ecs';

export class DemoStack extends ros.Stack {
  constructor(scope: ros.Construct, id: string, props?: ros.StackProps) {
    super(scope, id, props);
    new ros.RosInfo(this, ros.RosInfo.description, "Deploy 2048 game through ROS CDK.");

    const zoneId = new ros.RosParameter(this, 'ZoneId', {
      type: ros.RosParameterType.STRING
    });

    const vpc = new ecs.Vpc(this, 'Vpc', {
      cidrBlock: '192.168.0.0/16'
    });

    const sg = new ecs.SecurityGroup(this, 'SecurityGroup', {
      vpcId: vpc.ref
    });

    const vsw = new ecs.VSwitch(this, 'VSwitch', {
      cidrBlock: '192.168.0.0/24',
      zoneId: zoneId,
      vpcId: vpc.ref
    })

    const instance = new ecs.Instance(this, 'Instance', {
      vpcId: vpc.ref,
      vSwitchId: vsw.ref,
      securityGroupId: sg.ref,
      zoneId: zoneId,
      instanceType: 'ecs.c6e.large',
      imageId: 'centos_7_8',
      systemDiskCategory: 'cloud_essd',
      ioOptimized: 'optimized'
    });

    const sgIngress = new ecs.SecurityGroupIngress(this, 'SecurityGroupIngress', {
      ipProtocol: 'tcp',
      portRange: '80/80',
      sourceCidrIp: '0.0.0.0/0',
      securityGroupId: sg.ref,
      nicType: 'intranet'
    });

    const runCommand = new ecs.RunCommand(this, 'RunCommand', {
      instanceIds: [instance.ref],
      type: 'RunShellScript',
      sync: true,
      timeout: 3600,
      commandContent: `yum install -y httpd wget\nsystemctl start httpd\nwget 'https://computenest-artifacts-cn-hangzhou.oss-cn-hangzhou-internal.aliyuncs.com/1853370294850618/cn-beijing/1697533575326/2048.tgz' -O 2048.tgz\ntar xvf 2048.tgz\nmv 2048/* /var/www/html && rm -rf 2048`
    });
    runCommand.addDependency(sgIngress);

    new ros.RosOutput(this, 'Url', {
      value: `http://${instance.attrPublicIp}:80`
    });
  }
}

4.3 Deploy the Stack

Run the following command to deploy the stack:

ros-cdk deploy --parameters ZoneId=cn-hangzhou-i --sync=true

--sync=true synchronizes the stack information and displays it in the terminal. Upon success, the command-line terminal returns the following information:

Create bucket(cdk-tcbgaxxxx-assets-cn-hangzhou) successfully!
Upload file(./cdk.out/DemoStack.template.json) to bucket(cdk-tcbgaxxxx-assets-cn-hangzhou) successfully!
DemoStack: deploying...
|DemoStack               |2024-09-09T08:56:47 | CREATE_COMPLETE      | ALIYUN::ECS::SecurityGroup | sg-bp121z2wd687mdxxxxxx | SecurityGroup

|DemoStack               |2024-09-09T08:56:47 | CREATE_COMPLETE      | ALIYUN::ECS::SecurityGroupIngress | sg-bp121z2wd687mdxxxxxx | SecurityGroupIngress

|DemoStack               |2024-09-09T08:56:47 | CREATE_COMPLETE      | ALIYUN::ECS::Instance   | i-bp16t9mt9b0uscixxxxx | Instance

|DemoStack               |2024-09-09T08:56:47 | CREATE_COMPLETE      | ALIYUN::ECS::VPC        | vpc-bp10y18ke2x6v0bjxxxxx | Vpc

|DemoStack               |2024-09-09T08:56:47 | CREATE_COMPLETE      | ALIYUN::ECS::VSwitch    | vsw-bp1qfb9u90cuyu69xxxxx | VSwitch

|DemoStack               |2024-09-09T08:56:47 | CREATE_COMPLETE      | ALIYUN::ECS::RunCommand | t-hz04w6ckiuxxxxx | RunCommand


Outputs:

 Key: Url  Value: http://121.40.xxx.xx:80 Description: No description given

 ✅ The deployment(sync create stack) has completed!
Status: CREATE_COMPLETE
StatusReason: Stack CREATE completed successfully
StackId: 40c92773-33fb-4249-bd46-3ab6xxxxxxxx

After the deployment is complete, copy the link in Outputs and open it in your browser to play 2048!

1

4.4 Delete the Stack

Run the following command to delete the stack:

ros-cdk destroy --sync=true 

CDK reconfirms the stack to be deleted:

The following stack(s) will be destroyed(Only deployed stacks will be displayed).

DemoStack

Please confirm.(Y/N)

Enter y and press the Enter key. After deletion, the following information is displayed:

✅ The task(sync destroy stack) has finished!
status: DELETE_COMPLETE
StatusReason: Stack DELETE completed successfully
StackId: 40c92773-33fb-4249-bd46-3ab6xxxxxxxx

Disclaimer: The views expressed herein are for reference only and don't necessarily represent the official views of Alibaba Cloud.

0 0 0
Share on

Alibaba Cloud Community

1,075 posts | 263 followers

You may also like

Comments

Alibaba Cloud Community

1,075 posts | 263 followers

Related Products