top of page
Writer's pictureSoham Pingat

Turn Based Game using DynamoDB and Cognito.

Updated: Dec 13, 2021

Learn to create a Turn Based Game using DynamoDB and Cognito.


Tutorial Objectives:

1. To create a turn based game using DynamoDB and Cognito.


Prerequisite:

1. Download the zip from here.


Step 1: Set up your AWS Cloud9 IDE

Navigate to the AWS Management Console, choose Services at the top of the page, and then choose Cloud9 under Developer Tools.

Choose Create environment.

Type Turn-based game in the Name box. Leave the Description box empty.

Choose Next step.

Leave the Environment settings at their defaults to create a new t2.micro EC2 instance, which will be hibernated after 30 minutes of inactivity. Click on next step.

Review the environment name and settings, and choose Create environment. Your environment will be provisioned and prepared after several minutes.

Congratulations you have successfully created your Cloud9 Environment.


Step 2: Download the supporting code

Download the necessary code from the given link: here, onto your local device.

Drag and drop the zip file in your Cloud9 environment.


cd ~/environment
unzip Turn_Based_Game.zip

You should see two directories in the AWS Cloud9 file explorer:

Application: The application directory contains an example code for the turn-based game application. This code is similar to the code you would have in your real turn-based game application backend.

Scripts: The scripts directory contains administrator-level scripts, such as for creating AWS resources or loading data into your database.

Run the following command in your AWS Cloud9 terminal to install the dependencies for both directories.

npm install --prefix scripts/ && npm install --prefix application
npm audit fix

Run the following command in your AWS Cloud9 terminal to set your AWS Region in an environment file. Change the highlighted text with the region you are using your Cloud 9 environment.

echo "export AWS_REGION=us-east-1" >> env.sh && source env.sh

You use the env.sh file to store environment variables of resources and other parameters you need in this lab. If you take a break during this lab and then start a new session in your AWS Cloud9 environment, be sure to reload your environment variables by executing the following command in your terminal:

source env.sh

Congratulations you have successfully downloaded all the necessary material.


Step 3: Provision an Amazon DynamoDB database

In the scripts/ directory, there is a file called create-table.sh that creates your DynamoDB table using the AWS Command Line Interface (AWS CLI)

Run the following command to create your DynamoDB Database.

bash scripts/create-table.sh

You can check if the created table on your AWS Management Console by navigating to DynamoDB Service.

Now that your database is successfully created we will now create a demo game to test other functionalities of the game.

To create a game run the following commands in your cloud9 terminal window.

node scripts/createGame.js

You should see the following output in your terminal:

Game added successfully!

Note: If you run the command too quickly, you may get an error that the table is not yet available. Wait one minute, then try the command again.


You can check if the game is created or not by looking at your AWS Management Console DynamoDB Service.

Congratulations, you have successfully created your game.


Now to update the entries in the database. Run the following command.

node scripts/performMove.js

Congratulations, you have successfully updated the entries in your database.


Note: If you run the command one more time it will give an error because it is a turn based game which means that next move must be done by other user and not the same user.


Step 4: Set up Email notification.

There is a sendMessage.js code in your script that is similar to a function you have in your application. It takes an SNS Topic ARN and publishes a message to that topic.


a. Create an SNS Topic.

Open SNS on your AWS management console and click on create topic.

Give a name to your topic ex. Turn_Based_Game.

Under Access Policy select everyone to who can publish and subscribe to the topic.

Click on create topic to create the topic.


b. Create a subscriber for that topic using the email service.

Select the topic you have just created and click on create subscriber.

Under Protocol select Email and enter your email in the Endpoint and click on create subscriber.


Similarly, create another subscriber for player 2.


c. Edit the sendMessage.js script and add your Topic ARN.


Open the sendMessage.js script in the scripts folder. Copy the ARN of your SNS topic, also change the region to your region.

Paste your ARN in the sendMessage.js script.

Similarly past the SNS topic ARN and replace the region in the sendMessage.js script in the application/data folder.


Run the following command to test your notification.

node scripts/sendMessage.js

Congratulations, you have successfully set you your notification.



Step 5: Setting up AWS Cognito to create user authentication.


a. Create an Amazon Cognito user pool.

In the scripts/ directory, there is a file called create-user-pool.sh.

You can create your user pool by executing the script with the following command:

bash scripts/create-user-pool.sh

b. Create a user pool client.


There is a file in the scripts/ directory called create-user-pool-client.sh for creating a user pool client. The contents of the file are as follows:

bash scripts/create-user-pool-client.sh

You can check the Cognito User Pool using the AWS Management Console Cognito Service.


Step 6: Deployment of Application on Lambda.


In the scripts/ directory, there is a file called create-lambda.sh. This script does four things:


Zips up the contents of the application/ directory for use in your Lambda function.


Creates an IAM role to be assumed by your Lambda function.


Adds an IAM policy to your IAM role that allows your Lambda function to access your

DynamoDB table and publish messages to Amazon SNS.


Creates the Lambda function by uploading your zip file.


If you want to see the AWS CLI commands used to run these steps, open the scripts/create-lambda.sh file in your file explorer.


To execute the script, run the following command in your terminal:

bash scripts/create-lambda.sh

Step 7: Creating a REST API.

In your scripts/ directory, there is a file called create-rest-api.sh that provisions an API Gateway REST API and connects it to your Lambda function. This script handles a number of things, including:


Creates a REST API in API Gateway.


Configures a proxy resource and method in the REST API to send all incoming request paths and methods to a single Lambda function.


Adds the permissions for the REST API to trigger your Lambda function.


API Gateway has a lot of configuration options, and this tutorial cannot cover all of the details. For additional detail, see Amazon API Gateway Concepts.

Run the following command in your terminal to execute the script and configure your REST

API:

bash scripts/create-rest-api.sh

You’ve now configured your REST API to connect to your Lambda function. The end of the output included the base URL to access your REST API.

The value of your base URL was added to the env.sh file. Source that file now to set the BASE_URL environment variable in your terminal.

source env.sh

Step 8: Testing your REST API.

Let’s test your endpoint by fetching the game you created in an earlier module. This request goes through API Gateway to your Lambda function, which then makes a request to DynamoDB and returns the results.

Run the following command in your terminal:

curl -X GET ${BASE_URL}/games/5b5ee7d8

You should see the following output in your terminal:


{"heap2":4,"heap1":3,"heap3":5,"gameId":"5b5ee7d8","user2":"theseconduser","user1":"myfirstuser","lastMoveBy":"theseconduser"}


Step 9: Test your Application.

a. Register a new user

To register a new user run the following command:

curl -X POST ${BASE_URL}/users \
  -H 'Content-Type: application/json' \
  -d '{
        "username": "myfirstuser",
        "password": "Password1",
        "phoneNumber": "+911234567890",
        "email": "test@email.com"
}'

Note: You can change the username, password, phoneNumber and email as per your game.


You should see the following output in your terminal:

{"username":"myfirstuser","email":"test@email.com","phoneNumber":"+911234567890"}

Great! You’ve successfully created your user. Now, create a second user so that you can simulate playing a game.

Run the following command in your terminal:

curl -X POST ${BASE_URL}/users \
  -H 'Content-Type: application/json' \
  -d '{
        "username": "theseconduser",
        "password": "Password1",
        "phoneNumber": "+910000000000",
        "email": "test@email.com"
}'

You should see the following output in your terminal:

{"username":"theseconduser","email":"test@email.com","phoneNumber":"+910000000000"}

b. Login to fetch user credentials

Let’s test it out with your first created user. Run the following command in your terminal:

curl -X POST ${BASE_URL}/login \
  -H 'Content-Type: application/json' \
  -d '{
        "username": "myfirstuser",
        "password": "Password1"
}'

You should see a response with an idToken property in your terminal:

{"idToken":"eyJraWQiO…."}

This ID Token is used in subsequent requests to authorize a user. Save the value of the ID token in your shell by copying the value of the token between the quotations, then running the following command:

export FIRST_ID_TOKEN=<idToken>

Do the same steps to login with your second user. Execute the following command in your terminal:

curl -X POST ${BASE_URL}/login \
  -H 'Content-Type: application/json' \
  -d '{
        "username": "theseconduser",
        "password": "Password1"
}'

You should see a response with an idToken property in your terminal:

{"idToken":"eyJraWQiOiI...."}

Again, copy the quoted value of the ID token and save it as an environment variable with the following command:

export SECOND_ID_TOKEN=<idToken>

Note: These identity tokens are temporary credentials that will expire over time. If you return to this tutorial after a period of time, you may need to re-run the steps above to generate new tokens.


c. Create a new game

The createGame function generates a unique game id and saves the basic game details into DynamoDB. Then, it sends a message to the opponent to alert them that a new game has started and it is their turn to play.


Let’s try using this endpoint. Run the following command in your terminal:


curl -X POST ${BASE_URL}/games \
 -H 'Content-Type: application/json' \
  -H "Authorization: ${FIRST_ID_TOKEN}" \
  -d '{
        "opponent": "theseconduser"
}'

Note that you’re passing the ID token of the first user in the Authorization header with your request.

You should see the following output in your terminal:

{"gameId":"433334d0","user1":"myfirstuser","user2":"theseconduser","heap1":5,"heap2":4,"heap3":5,"lastMoveBy":"myfirstuser"}

A new game has been created! You should receive an SMS message on the phone number you registered for the second user.


Save the value of the game Id to your terminal using the following command:

(Make sure you substitute the value of your game Id for <yourGameId>.)

export GAME_ID=<yourGameId>

To know the current status of the game type the following command.

curl -X GET ${BASE_URL}/games/${GAME_ID}

You should see the following output in your terminal:

{"heap2":4,"heap1":5,"heap3":5,"gameId":"32597bd8","user2":"theseconduser","user1":"myfirstuser","lastMoveBy":"myfirstuser"}

Now to complete the game you can perform consecutive moves one by one and complete the game of Nim.

Type to following commands to complete the game.


curl -X POST ${BASE_URL}/games/${GAME_ID} \
  -H "Authorization: ${SECOND_ID_TOKEN}" \
  -H 'Content-Type: application/json' \
  -d '{
        "changedHeap": "heap1",
        "changedHeapValue": 0
}'
curl -X POST ${BASE_URL}/games/${GAME_ID} \
  -H "Authorization: ${FIRST_ID_TOKEN}" \
  -H 'Content-Type: application/json' \
  -d '{
        "changedHeap": "heap2",
        "changedHeapValue": 0
}'
curl -X POST ${BASE_URL}/games/${GAME_ID} \
  -H "Authorization: ${SECOND_ID_TOKEN}" \
  -H 'Content-Type: application/json' \
  -d '{
        "changedHeap": "heap3",
        "changedHeapValue": 0
}'

You should see the following output in your terminal:

{"heap2":0,"heap1":0,"heap3":0,"gameId":"32597bd8","user2":"theseconduser","user1":"myfirstuser","lastMoveBy":"theseconduser"}

This ends the game, which triggers the end-of-game notifications for both users.

Note: You will receive an email notification for every move performed in the game.


Step10. Delete AWS Lambda, Amazon API Gateway, Amazon DynamoDB, and Amazon Cognito resources


First, delete your application resources.


In the scripts/ folder, there is a file called delete-resources.sh. This script deletes your Lambda function, your API Gateway REST API, your function’s IAM role, your DynamoDB table, and your Amazon Cognito user pool.


Execute this script with the following command in your terminal:

bash scripts/delete-resources.sh

Finally, delete the AWS Cloud9 environment that you used in this lab:

Navigate to the AWS Cloud9 console.

Choose the Turn-based game environment and choose Delete.

In dialog box, type Delete and choose Delete.

Congratulations, you have successfully created and played a Turn Based Game using AWS.


Was this document helpful? How can we make this document better? Please provide your insights. You can download PDF version for reference.

We provide the best AWS training from Pune, India.

For aws certification contact us now.

179 views0 comments

Comentarios


bottom of page