Building the Button Blaster example in Amazon GameSparks - GameSparks

Amazon GameSparks is currently in preview. Changes might be made to this service and to this documentation. We don't recommend using this service for production workloads.

Building the Button Blaster example in Amazon GameSparks

In this topic you'll create a Button Blaster game in the Amazon GameSparks backend. The game records the clicks made by the player by incrementing a counter in the player data. You'll create the event raised by the click and a notification that results from the event. You'll also create a request that the client can make to get the count.

Note

Set up GameSparks before proceeding.

Create a GameSparks game

To create a GameSparks game
  1. In the GameSparks navigation pane, select Games.

  2. Choose Create Game.

  3. For Game name enter ButtonBlaster.

  4. Choose Create and use new roles for each stage.

  5. Choose Create.


           Create game
Important

When you create your messages, make sure that you use exactly the same names given below for the messages and fields. Otherwise the game won't function because the generated code in the game client won't match the cloud code in the backend.

Create an event

As players play your game, the GameSparks backend handles the events that occur. Events can occur for anything you want: a portal is opened, an artifact is acquired, a team wins a battle, a player wins their 100th game. An event is one kind of message that your game client raises to the backend. After sending the event, the client continues to the next instruction; no response is expected.

To try a simple example, you'll create an event that occurs when the player chooses a button.

To create an event
  1. In the navigation pane, select Dev, expand Configuration, and then choose Cloud code.

  2. Choose Create message.

    The Create message dialog box appears.

  3. Choose Event

  4. In the Name box, enter ButtonPressed.

  5. (Optional) enter a description.

  6. Choose Create

    The ButtonPressed message appears.

You just added an event to your game configuration. To make your event have an effect in your game, you add one or more handlers. In each handler you add cloud code to implement your game logic.

To add code to an event
  1. Select Player.

  2. Choose Add event handler

    The Add event handler dialog box appears.

  3. For the name, enter ButtonPressHandler.

  4. (Optional) Add a description.

  5. Insert the following code into ButtonPressHandler.

    GameSparks().Logging().Debug("Inside ButtonPress event handler"); // Retrieve player data GameSparks().Logging().Debug("Retrieving player data"); let data = GameSparks().CurrentPlayer().GetData(["ButtonPressed"]); // Handle initial case with no data if (data.ButtonPressed === undefined) { data.ButtonPressed = 0; } // Increment the counter GameSparks().Logging().Debug("Incrementing button press counter"); data.ButtonPressed++; GameSparks().Logging().Info("Setting a value of button press count"); // Store player data GameSparks().CurrentPlayer().SetData(data);
  6. Choose Save.

Create a notification

Create a notification that the backend sends to the client when the button is pressed.

To create a notification
  1. In the console on the Cloud code page, choose Create message, and then choose Notification.

    The Create message dialog box appears.

  2. Enter the name ButtonPressedNotification.

  3. (Optional) Add a description.

  4. Choose Create.

  5. In the notification fields, for Field name enter buttonPressCount, for Shape select Integer, and for Required select Yes.

  6. Choose Save.

You're ready to enable triggering of this notification by your ButtonPressed event.

To enable triggering of a notification
  1. Choose the ButtonPressed event in the Messages pane.

  2. Choose Add event handler and name it NotificationHandler.

  3. Insert the following code into NotificationHandler.

    GameSparks().Logging().Debug( "Inside ButtonPressed Notification dispatch handler"); let data = GameSparks().CurrentPlayer().GetData(["ButtonPressed"]); // Handle initial case with no data if (data.ButtonPressed === undefined) data.ButtonPressed = 0; GameSparks().Logging().Debug("Sending notification: " + data.ButtonPressed); GameSparks().CurrentPlayer().SendNotification( "Custom.Game.ButtonPressedNotification", { "buttonPressCount": parseInt(data.ButtonPressed) });
  4. Choose Save.

Your ButtonPressed event now triggers two outcomes defined in the code of two event handlers. The ButtonPressHandler increments the counter. The NotificationHandler alerts the game client.

Create a request

In addition to the notification above, create a request so the client can get the count when needed.

To create a request
  1. In the GameSparks console, on the Cloud code page, choose Create Message.

    The Create message dialog box appears.

  2. Choose Request, and enter GetButtonPressCount as the name.

  3. (Optional) Enter a description.

  4. Choose Create.

  5. Select Player.

  6. Add a response field named buttonPressCount, choose a Shape of Integer, and for Required choose Yes.

  7. Add the following cloud code in the request handler

    GameSparks().Logging().Debug( "Inside GetButtonPressCount request handler"); let data = GameSparks().CurrentPlayer() .GetData(["ButtonPressed"]); // Handle initial case with no data if (data.ButtonPressed === undefined) data.ButtonPressed = 0; return GameSparks().Messaging().Response( { "buttonPressCount": parseInt(data.ButtonPressed) } );
  8. Choose Save.

Deploy your changes

You must deploy the game configuration in order to test your changes from the test harness or from the game client.

To deploy your changes
  1. In the GameSparks navigation pane, select Dev.

  2. Choose Deploy as new snapshot.

    
                 Create game

    The Deploy as new snapshot dialog box appears.

  3. Enter a description that will help you remember the changes you made. For example: Added messages to implement button press event. Client gets data via notification and request.

  4. Choose Save.

A banner appears: Saving snapshot and deploying updates…. After the snapshot has been saved and deployed, its number appears in the form Snapshot_<timestamp> along with your description.


           Create game

Refresh your browser to get the Dev stage key to appear. Later you'll use this key to connect from the client to this stage of your game.

You just created a snapshot of your configuration, which includes the cloud code you wrote. You also deployed the snapshot to the dev stage of the backend so that your game clients can connect to it. The snapshot is also exportable, importable, and part of the history of your game.

Test your messages

With the test harness you can iterate much more quickly to develop and test your messages.

Note

If some of your events or requests don't appear, go back to the Cloud code page and make sure that Player is selected for each of your messages.

Your ButtonPressed event does two things. It increments the score and it sends a ButtonPressedNotification to the client. To test these:

To test your messages
  1. In the GameSparks navigation pane, select Test harness.

  2. Wait until the Player card is Connected.

  3. Select the ButtonPressed message.

  4. Choose Populate example.

  5. Choose Send message.

  6. The ButtonPressed event appears in the Log inspector

    ⓘ Event sent

    Id: 1a071196-4f76-421a-90ee-d9a5ee8ba220
      Type: Custom.Game.ButtonPressed
      Category: Event
      
      {}
  7. You will receive a ButtonPressedNotification with a payload like {"buttonPressCount":1}.

    ✓ Notification received

    Id: d81c89cc-5fac-4392-91ad-4b71b97a6b97
      Type: Custom.Game.ButtonPressedNotification
      Category: Notification
      
      {"buttonPressCount":1}
  8. You can choose Send message a few times to increment the score.

Your GetButtonPressCount request enables the client to request the score whenever it needs it. To test this request, choose GetButtonPressCount, choose Populate example, and then choose Send message.

Import the Button Blaster sample

Note

Make sure you've set up the client SDK in your Unity game before proceeding.

For this tutorial, your client code comes from a sample that is built into the GameSparks SDK.

To import the sample
  1. In Unity, create a 3D project named ButtonBlaster.

  2. In the Unity editor window, from the Window menu, choose Package Manager.

  3. Import the sample.

    1. In Package Manager, choose Amazon GameSparks.

    2. Expand Samples

    3. Next to ButtonBlaster choose Import.

    
                  Choose Amazon GameSparks and then choose Import
  4. Save your Unity project.

Add the game key to your project

Your GameSparks game accepts a connection only if the game client provides the game key.

To add the game key to your Unity project
  1. In GameSparks, navigate to the Dev page, and copy the key to your clipboard.

    Note

    If you don't see the key, make sure that you have chosen Deploy as new snapshot and refreshed the page.

  2. In the Unity project pane, browse to and select the Connection asset in /Assets/Samples/Amazon GameSparks/0.0.3/Button Blaster/UsingScriptableObjects/Assets/Connection.

  3. In the Inspector pane, paste the key into the Game Key box.

Open the UsingScriptableObjects scene

In the Unity project pane, browse to and double-click the UsingScriptableObjects scene in /Assets/Samples/Amazon GameSparks/0.0.3/Button Blaster/UsingScriptableObjects/Assets/Scenes.

Connect the client to GameSparks

To connect the client to GameSparks
  1. In Unity, if the console is not already displayed, from the Window menu, choose General, Console.

  2. From the Edit menu, choose Play.

  3. In the Console, observe how the game connects by searching for key words in the search box.

Search for… See a log entry like…

gameKey or playerId

Connecting using gameKey:
  aBcDeFgHiJkLmNoPqRsTUvWxYz-aBcDeFgHiJkLmNoP and playerId:
  0a0b0c0d-1e1f-2g2h-3i3j-4k4l4m4n4o4p

authToken

received GetConnectionInfo response for player [playerId: 0a0b0c0d-1e1f-2g2h-3i3j-4k4l4m4n4o4p
  authToken: <authentication token string>, now connected

Press the button

Choose the button to increment the score.

Note

To enlarge the view, near the top of the Unity window, drag the Scale slider to the right.


           Button with 48 on top and ButtonPressCount: 48 on bottom of scoreboard

The data in the bottom of the scoreboard panel comes from the notification. The data in top of the panel comes from the response to the request.

The table below provides a simplified explanation of how the game works.

Behavior Sequence

The user presses the button in the client, which raises the event.

  • Client

    • The User chooses the button.

    • OnMouseUp() event calls SendButtonPress(). It also subscribes OnButtonPressed() to notifications.

    • SendButtonPress() queues a ButtonPressed() event.

    • EnqueueButtonPressed() raises the ButtonPressed event.

  • Backend

    • The Backend receives the ButtonPressed event.

    • ButtonPressHandler increments the count by 1.

    • NotificationHandler sends a ButtonPressedNotification to the client.

The client receives the notification that results from an event.

  • The client receives ButtonPressedNotification from the backend.

  • OnButtonPressed() stores the score in achievement as { "buttonPressCount": n }.

  • The achievement value is displayed in the bottom of the scoreboard.

The client makes a request.

  • Client

    • UpdateButtonPressCount() runs every 5 seconds.

    • SyncButtonPresses() queues a GetButtonPressCountRequest() request.

    • EnqueueGetButtonPressCountRequest() makes the request.

  • Backend

    • Receives the request, gets the count, and sends a response to the client.

  • Client

    • HandleGetButtonPressCountResponse() stores the score in pressCountString as n.

    • pressCountString value is displayed in the top of the scoreboard.

You can browse deeper into the code mentioned above in /Assets/Samples/Amazon GameSparks/0.0.3/Button Blaster/UsingScriptableObjects/Scripts/Player.cs.

The lower-level code is in /Assets/Samples/Amazon GameSparks/0.0.3/Button Blaster/Scripts/Generated/ButtonBlasterOperations.cs. This file was generated from the backend to enable writing strongly-typed code to match the message shapes in the cloud code. To learn about generating code, see Part 2: Unity game client .

If you prefer to use code directly (instead of with a ScriptableObject), see /Assets/Samples/Amazon GameSparks/0.0.3/Button Blaster/UsingCode/Scripts/Player.cs.