Creating your first HTML5 spaceship game for the Android* OS on Intel® Architecture

Introduction

I'm certain most of us have some insane or not so insane video game plans in mind. The majority of these thoughts are never acted on as many people think game coding is exceptionally hard to do. Indeed that is true to a degree, but it is not as hard as you may think.

If you have a fundamental understanding of HTML, CSS, and JavaScript*, you have all the requisites to start a straightforward project.

Adding a Canvas element to a web page

One of the most exciting features of HTML5 is the <canvas> element that can be used to draw vector graphics and engender astonishing effects, interactive games, and animations The web defines canvas, as a rectangular area that allows for dynamic, scriptable rendering of 2D shapes and bitmap images. The HTML5 Canvas is perfect for creating great visual results that augment UIs, diagrams, photo albums, charts, graphs, animations, and embedded drawing applications. HTML5 Canvas works with JavaScript libraries and CSS3 enabling you to create interactive web-based games and animations.

The elementary code for using and setting a canvas looks like this:

<body onload="spaceShipGame()">
    <h1>
      SpaceShipGame
    </h1>
    <canvas id="spaceCanvas" width="300" height="300">
    </canvas>
 </body>

This looks very similar to the <img> element, the difference being that it doesn't have the src and alt attributes. The <canvas> element has only two characteristics, width and height. If your renderings seem inaccurate, try designating your width and height attributes explicitly in the <canvas> attributes, instead of CSS. The width and height attributes default to 300 and 300, respectively. The id will be acclimated to initialize the canvas using JavaScript, and the text next to the equal to sign will be used as a call back when the mobile browser doesn’t support it.

Drawing the background and spaceship for a game using HTML5 canvas and JavaScript

canvas = document.getElementById("spaceCanvas");
ctx = canvas.getContext("2d");

The variable canvas creates the canvas that we need to draw graphics objects, and ctx holds the rendering context. In this case it is a 2d graphics object.

This context contains the elementary methods for drawing on the canvas such as arc(), lineto(), and fill().

Next we paint the background black, place shiny asteroids on it, and draw the spaceship using the context object.


// Paint it black
          ctx.fillStyle = "black";
          ctx.rect(0, 0, 300, 300);
          ctx.fill();

         // Draw 100 stars.
         for (i = 0; i <= 100; i++) {
         // Get random positions for stars.
         var x = Math.floor(Math.random() * 299)
         var y = Math.floor(Math.random() * 299)

          // Make the stars white
          ctx.fillStyle = "white";

          // Give the spaceship some room.
          if (x < 20 || y < 20) ctx.fillStyle = "black";

          // Draw an individual star.
          ctx.beginPath();
          ctx.arc(x, y, 3, 0, Math.PI * 2, true);
          ctx.closePath();
          ctx.fill();
        }

//drawing the spaceship
       ctx.beginPath();
        ctx.moveTo(28.4, 16.9);
        ctx.bezierCurveTo(28.4, 19.7, 22.9, 22.0, 16.0, 22.0);
        ctx.bezierCurveTo(9.1, 22.0, 3.6, 19.7, 3.6, 16.9);
        ctx.bezierCurveTo(3.6, 14.1, 9.1, 11.8, 16.0, 11.8);
        ctx.bezierCurveTo(22.9, 11.8, 28.4, 14.1, 28.4, 16.9);
        ctx.closePath();
        ctx.fillStyle = "rgb(0, 0, 255)";
        ctx.fill();
        ctx.beginPath();
        ctx.moveTo(22.3, 12.0);
        ctx.bezierCurveTo(22.3, 13.3, 19.4, 14.3, 15.9, 14.3);
        ctx.bezierCurveTo(12.4, 14.3, 9.6, 13.3, 9.6, 12.0);
        ctx.bezierCurveTo(9.6, 10.8, 12.4, 9.7, 15.9, 9.7);
        ctx.bezierCurveTo(19.4, 9.7, 22.3, 10.8, 22.3, 12.0);
        ctx.closePath();
        ctx.fillStyle = "rgb(255, 0, 0)";
        ctx.fill();
When we execute the code, our screen looks like the picture shown in Figure 1.


Figure 1

Next we are going to move the spaceship in our game using HTML5 canvas and JavaScript. The code sample is composed with HTML5 and JavaScript and demonstrates how to move the spaceship over the star field. Canvas uses quick mode to create this moving image. Two steps are used to execute this in the game application. We should redraw the image every time we move it. Then we should re-establish the groundwork (background) that was destroyed when we drew the spaceship over it.

The code below demonstrates how we can delete the image of the spaceship as it moves and draw another one at the new location. It shows how to spare and restore previews of the spaceship and the background. Canvas does not memorize the trajectory regarding where the pixels are drawn, so the example demonstrates the best practices to keep the trajectory for each pixel as it is recovered, eradicated, moved, and restored in our code.

Let’s look at declaring some of the variables:

var newBackground = new Image(); // This variable will be used to store the new background.

var oldBackground = new Image(); // This variable will be used to store the old background.
var ship = new Image(); // This variable captures the spaceship image

      var spaceShipX = 0; // The current X position of the spaceship
      var spaceShipY = 0; // The current Y position of the spaceship
      var old_SpaceShipX = 0; // The old X position of the spaceship
      var old_SpaceShipY = 0; // The old Y position of the spaceship

Setting up a game loop to process the main game events

Loopgame()
{

The code below stores the old background so we can erase the ship and then draw the spaceship at the new position. This looks as if the ship has moved.

        ctx.putImageData(oldBack, old_ShipX, old_ShipY);
        ctx.putImageData(spaceShip, spaceShipX, spaceShipY);
}

To get the image information for every pixel of a rectangular range on the canvas, we can get the image data object with the getimagedata() strategy for the canvas setting and afterward access the pixel information from the information property. Each pixel in the picture information holds four parts: a red, green, blue, and alpha part.

To play the game, we need to call the Loopgame() method. We do this by calling the setInterval method. The setInterval() method requests a function or assesses an expression at definite intervals. This LoopGame is called in 20-millisecond loops, which are very common in games because they accomplish basic animation tasks at fixed intervals.

setInterval(Loopgame, 20);

Animation in Canvas

The <canvas> tag in HTML can accomplish animation in two ways.

  1. The usual way and the one used for most animation is where the screen is totally redrawn for every movement. This works better when you have a modest canvas drawing surface and a faster processor. It is not suggested for bigger or more unpredictable animation.
  2. The second way Canvas makes movements is the one we used in this article’s code sample. This technique is suggested when you have a bigger, more complex Canvas animation and is the recommended technique to use. In spite of the fact that it takes more code to set it up, it runs much faster than the more normal style of activity.

Because this round circle refreshes every 20 milliseconds, the human eye does not see that the spaceship is erased; the spaceship just looks like it’s moving. This diminishes the danger of eye damage from screen flickering between every move since just a little part of the screen is drawn every time.

We set up the addEventListner to handle the touch events and capture the new X and Y positions and place our spaceship accordingly.

document.addEventListener("touchstart", movespaceShip, true);

When a user touches/moves a finger on the phone screen, the movespaceShip() event is triggered right away.

function startMoveDrawing (event)
{ event.preventDefault();//To prevent default behavior
var eventTouch, x, y;
eventTouch = event.changedTouches[0];// Array to store previous touch cords,0 is the initial one.
x = eventTouch.pageX;//The touch for x co-ordinate
 y = eventTouch.pageY;// The touch for y co-ordinate
}

So far we have seen how to draw/change the background and spaceship for our game. If we hit an asteroid, our spaceship will explode. So to get back securely to home base, we should stay away from asteroids or blow them up before we collide with them. To do this, we can use canvas to retain a record of each pixel on the screen.

The first stage is to yield a depiction (snapshot) of the screen at the point where the spaceship is about to move. This location has already been calculated using eventTouch.pageX and eventTouch.pageY;.

The next stage is to test the snapshot data. We hunt for a red value (255) in a chunk of 4 bytes. If we find it, an asteroid is present. We say in a chunk of 4 bytes because each pixel is assigned a color value that consists of four parts: red, green, blue, and alpha. Alpha denotes the amount of pellucidity (transparency). For example, a black pixel is made up of 0% red, 0% green, 0% blue, and 0% alpha.

Using the above mentioned technique and code, we know you’ll be able to turn this code snippet in to a full-fledged spaceship game in no time.

HTML5 is a future trend in the world of app development, Intel believes it is important to help experienced developers transition to this cross-platform approach and aid new developers to quickly get up to speed with this exciting new approach so that they can deploy their apps & games on nearly all modern computing platforms. Visit Intel HTML5  and Intel Android page to get more resources for your projects.

 

Intel and the Intel logo are trademarks of Intel Corporation in the U.S. and/or other countries.

Copyright © 2013 Intel Corporation. All rights reserved.

*Other names and brands may be claimed as the property of others.