Code in the CompanionSample Project

The CompanionSample project contains the code for the device side of the SmartGlass experience for Snake Battle Arena. This project uses the companion approach for creating the device side of a SmartGlass experience, in which you provide web content that you serve over the Internet, which the user views in the context of the Xbox SmartGlass app that they install on their device. To create a companion, you use the SmartGlass Hosted Companion SDK.

The CompanionSample project consists of the following files:

Index.html

The Index.html file is the web page that displays the user interface elements for the companion. In the case of Snake Battle Arena, this page is the interface through which the user joins a game of Snake Battle Arena that is running on an Xbox One console.

The <head> section of this HTML file includes several lines that are specific to the function of the companion.

<head>
    [...]
    <script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.js" 
        type="text/javascript"></script>
    <script src="//sg.xboxlive.com/march2014-1/Xbc.js" type="text/javascript">
        </script>
    <script src="SnakeControl.js" type="text/javascript"></script>
    <link href="default.css" rel="stylesheet" />
</head>  

The elements in the previous example perform the following functions:

The first element in the <body> section of the Index.html file includes a script from the SmartGlass companion demo that you can launch from http://sgsapinext.dfhosted.net in SmartGlass Studio. It includes a Log button in the web page that you can tap to display the SmartGlass log files, and provides functions for writing to the SmartGlass log file.

<!-- The log widget needs to go here so that when log 
functions run, a body exists for the functions to append bew entries to.-->>
<script src="//sgsapinext.dfhosted.net/Scripts/LogWidget.js" 
    type="text/javascript"></script>  

The remainder of the <body> section of the HTML file includes three <div> sections that define three different interfaces that the companion displays to the user at different times.

The first <div> section has an identifier of mainDiv and defines the main interface that user sees when the user starts the companion. If consists of two text boxes where the user specifies a name and color for the snake, and two buttons which allow the user to choose to use either the accelerometer on their device to control the movement of the snake, or buttons on the HTML page of the companion to control the movement of the snake.

<div id="mainDiv">
    <input type="text" id="txtSnakeName" value="Name Your Snake" />
    <br />
    <input type="text" id="txtSnakeColor" value="Blue" />
    <br />
    <button id="btnShowAccelerometer">Use Accelerometer</button>
    <button id="btnShowController">Use Controller Buttons</button>
</div>  

The second <div> section has an identifier of acclerometerDiv and defines the interface that the companion displays on the SmartGlass-enabled device after the user taps Use Accelerometer on the main interface and begins to play the game. It consists of text that indicates that the user chose to use the accelerometer on their device to control the snake, and a button that the user can tap to return to the main interface.

<div id="accelerometerDiv">
    Using Accelerometer
    <br />
    <button class="btnHome">Companion Home</button>
</div>  

The final <div> section has an identifier of controllerDiv and defines the interface that the companion displays on the SmartGlass-enabled device after the user taps Use Controller Buttons on the main interface and begins to play the game. It consists of four buttons to move the snake up, down, right, or left, and a fifth button to return to the main interface.

<div id="controllerDiv">
    <table>
        <tr>
            <td>&nbsp;</td>
             <td>
                 <button id="btnUp">Up</button>
            </td>
            <td>&nbsp;</td>
        </tr>
        <tr>
              <td>
                 <button id="btnLeft">Left</button>
             </td>
             <td>
                 <button class="btnHome">Companion Home</button>
             </td>
             <td>
                 <button id="btnRight">Right</button>
             </td>
        </tr>
        <tr>
             <td>&nbsp;</td>
             <td>
                 <button id="btnDown">Down</button>
             </td>
             <td>&nbsp;</td>
        </tr>
    </table>
</div>  

SnakeControl.js

The SnakeControl.js script contains the code that switches between the different interfaces on the Default.hmlt page and the code that calls the SmartGlass Device JavaScript API to communicate with the Snake Battle Arena game that runs on the Xbox One console.

The majority of the code in the SnakeControl.js is part of a function that is specified as a handler for the jQuery .ready event for the document. This function runs when the document object model (DOM) for the document for the Index.html file is fully loaded. The remainder of the script consists of additonal functions that are called from within that event handler.

Initializing the Interface

The first lines of the code in the SnakeControl.js file create variables that represent the three <div> sections in the Default.js file, and hide the accelerometerDiv and controllerDiv sections so that only the main interface is visible initially.

$(document).ready(function () 
{

    var mainDiv = $("#mainDiv");
    var accelerometerDiv = $("#accelerometerDiv");
    var controllerDiv = $("#controllerDiv");

    accelerometerDiv.hide();
    controllerDiv.hide();

    // This $(document).ready handler continues in the next example.  

Specifying Handlers for SmartGlass Events

The next section of the code begins to make calls to the SmartGlass Device JavaScript API. These statements call the Xbc.on function that you use to specify the functions that you want to run when different SmartGlass events occur. The first statement specifies a function to run when the SmartGlass loaded event occurs. The first call to the SmartGlass Device JavaScript API that any SmartGlass companion should make is to call Xbc.on to handle the loaded event. If you call other functions in the SmartGlass Device JavaScript API before you specify a handler for the loaded event, those calls may not work. For more information about calling Xbc.on to handle the loaded event, see “Initializing the SmartGlass Platform in a SmartGlass Companion” in the SmartGlass Hosted Companion SDK documentation.

    // This code continues the previous example.

    // After the host application handshakes with the browser, the Xbc.js script 
    // fires a loaded event. Insert application specific intialization here.
    Xbc.on("loaded", function (state) 
    {
        Log("Loaded");
    });

    // The $(document).ready handler continues in the next example.  

The second time that the SnakeControl.js script calls the Xbc.on function, the script specifies a function to run when the received event occurs. The received event occurs when the SmartGlass-enabled device receives a message from the game that runs on the console. One of the primary means that the Xbox One console and SmartGlass-enabled device use to communicate is to send messages that consist of objects in JavaScript Object Notation (JSON) to each other.

    // This code continues the previous example.

    // Fired when device receives a message from the console.
    Xbc.on("received", function (msg) 
    {
        Log("Received " + JSON.stringify(msg));
    });

    // The $(document).ready handler continues in the example after the next example.  

For more information about receiving messages in a SmartGlass companion, see “Receiving Messages from an Xbox One Console in a SmartGlass Companion” in the SmartGlass Hosted Companion SDK documentation.

For information about how the game in the Snake Battle Arena sample sends messages to the SmartGlass companion, see Sending a Message to a SmartGlass-enabled Device.

For both the loaded and received events, the event handler function just calls the Log function defined later in the SnakeControl.js file to write information to the log file. The Log function does this by calling the AddLogMessage function for the log widget that the Index.html includes on the web page at the beginning of the <body> section of the page.

// This code occurs outside the $(document).ready handler.

// The logWidget displays a button to display a log window that you can use 
// during development and testing of the companion.
function Log(s) {
    logWidget.AddLogMessage(s);
}  

Adding a Player Using the Accelerometer to the Game

The next section of code specifies a function to run when the user taps the Use Accelerometer button to specify that they want to control their snake by tilting their device and to start playing the game. This anonymous function performs the follwing tasks:

    // This code continues the example before the previous example.

    // Fired when user taps the Use Accelerometer button.
    $("#btnShowAccelerometer").click(function () 
    {
        // Indicate that the user wants to use the accelerometer.
        Log("Using the accelerometer to control the snake.");

        // Send the name and color fo the snake to the game.
        SendSnakeDetails();

        // Hide the main interface.
        mainDiv.hide();

        // Show the accelerometer interface.
        accelerometerDiv.show();

        // Start sending accelerometer reading to the Xbox One console.
        Xbc.Accelerometer.start(250, false, true, 0);
    });

    // The $(document).ready handler continues in the example after the next example.  

For more information on how to use the acclerometer in a SmartGlass companion, see “Using the Accelerometer in a SmartGlass Companion” in the SmartGlass Hosted Companion SDK documentation.

For information about how the game in the Snake Battle Arena sample receives accelerometer data from the SmartGlass companion, see Receiving Accelerometer Data from a SmartGlass-enabled Device.

The SendSnakeDetails function that sends the name and color of the snake to the game on the Xbox One console uses the Messagine object of the SmartGlass Device JavaScript API to send this information. The SendSnakeDetails function gets the values that the user entered for the name and color on the Index.html page, and creates a JSON object for each of these characteristics. This function then makes two calls to the Messaging.sendMessage method to send each of these objects as a message to the game on the console.

// This code occurs outside the $(document).ready handler.
function SendSnakeDetails() 
{
    // Get the snake name and color
    var snakeName = { name: $("#txtSnakeName").val() };
    var snakeColor = { color: $("#txtSnakeColor").val() };
    Log("About to send snake details: " + snakeName + " / " + snakeColor);

    // Be sure the game gets the name of our snake.
    Xbc.Messaging.sendMessage(snakeName).then(function (success) 
    {
        Log("Telling the game that our snake name is " + snakeName.name);
    }, function (error) 
    {
        Log("Failed to tell the game the name of our snake, error: " + 
            JSON.stringify(error));
    });

    // Be sure the game gets the color of our snake.
    Xbc.Messaging.sendMessage(snakeColor).then(function (success) 
    {
        Log("Telling the game that our snake color is " + snakeColor.color);
    }, function (error) 
    {
        Log("Failed to tell the game the name of our snake, error: " + 
            JSON.stringify(error));
    });
}  

For more information about how to send messages from a SmartGlass companion to the Xbox One console, see “Sending Messages from a SmartGlass Companion to an Xbox One Console” in the SmartGlass Hosted Companion SDK documentation.

For information about how the game in the Snake Battle Arena sample receives the messages that the SmartGlass companion sends, see Receiving a Messsage from a SmartGlass-enabled Device.

Adding a Player Using the Controller Buttons to the Game

The next section of code specifies a function to run when the user taps the Use Controller Buttons button to specify that they want to control their snake by tapping buttons on the web page that the companion displays on their device and to start playing the game. This anonymous function performs the follwing tasks:

    // This code continues the example before the previous example.

    // Fired when user taps the Use Controller Buttons button.
    $("#btnShowController").click(function () 
    {
        // Indicate that the user is  going to use the controller buttons.
        Log("Using the controller buttons to control the snake.");

        // Send the name and color of the snake to the game.
        SendSnakeDetails();

        // Hide the main interface.
        mainDiv.hide();

        // Show the controller interface.
        controllerDiv.show();
    });

    // The $(document).ready handler continues in the next example.  

Returning to the Main Interface for the Companion

The next section of code specifies a function to run when either the accelerometer or controller buttons interface is visible and the user taps the Companion Home button to indicate that they want to return to the main page of the companion. This anonymous function performs the follwing tasks:

    // This code continues the previous example.

    // Fired when the user taps the Companion Home button.
    $(".btnHome").click(function () 
    {
        Log("Go back to companion home.");

        // Hide the other interfaces.
        accelerometerDiv.hide();
        controllerDiv.hide();

        // Stop the accelerometer.
        Xbc.Accelerometer.stop();

        // Show the main interface.
        mainDiv.show();
    });

    // The $(document).ready handler continues in the next example.  

Handling Events from the Controller Buttons

The last section of code in the function that is called when then document is ready specifies functions to run when the user taps the buttons to change the direction of the snake in the controller buttons interface. Each of these functions calls a ChangeDirection function defined later in the SnakeControl.js file with a string that indicates the direction as a parameter.

    // This code continues the previous example.

    // Fired when the user pushes the Up button.
    $("#btnUp").click(function () 
    {
        ChangeDirection("up"); 
    });

    // Fired when the user pushes the Down button.
    $("#btnDown").click(function () 
    { 
        ChangeDirection("down"); 
    });

    // Fired when the user pushes the Left button.
    $("#btnLeft").click(function () 
    { 
        ChangeDirection("left"); 
    });

    // Fired when the user pushes the Right button.
    $("#btnRight").click(function () 
    { 
        ChangeDirection("right"); });
    });
});  

// This code concludes the $(document).ready handler.  

The ChangeDirection function sends the information that the user specified by tapping the controller buttons about how they want to change the direction of the snake to the game on the Xbox One console by sending a message to the Xbox One console. The process for sending this message is the same as the process described in the Adding a Player Using the Accelerometer to the Game section earlier in this document. The script creates a JSON object with the information about the direction that the user specified, and calls the Messaging.sendMessage method to send the object as a message.

// This code occurs outside the $(document).ready handler.

// Change the direction of the snake.
function ChangeDirection(dir) 
{
    Log("Tell snake to head" + dir);
    var direction = { d: dir };
    Xbc.Messaging.sendMessage(direction).then(function (success) 
    {
        Log("Told Snake to head " + direction.d);
    }, function (error) 
    {
        Log("Failed to tell snake to head " + direction.d + "; error: " + 
            JSON.stringify(error));
    });
}  

See also

Exploring an End-to-End Sample for a SmartGlass Experience: Snake Battle Arena

Code in the SBA Project

Overview of the SmartGlass Platform