Fancy learning the basics and getting your first game up and running on your Azure Web Services, well this guide will show you have to build a game with Web technologies.
Building a web based game is the perfect Hour of Code and the aim if for you to have the game live within one hour. This blog covers the basic game design and screen layout, controls and sprites and includes an artificial intelligence (AI) as a simple opponent.
Step 1. Tools and Technologies
Download Visual Studio Community or Visual Studio code from www.dreamspark.com
I will be using Visual Studio Community and the Microsoft Azure SDK.If you have a Mac or Linux user, Visual Studio Code is available cross-platform and perfect for building web sites.
Create your DreamSpark Azure Subscription which give you FREE web apps see http://blogs.msdn.com/b/uk_faculty_connection/archive/2015/09/14/accessing-microsoft-dreamspark-azure-account-if-you-have-onthehub-dreamspark-premium.aspx
This app will require no server code, so I start by creating a new, empty Web page project in Visual Studio.
Step 2. Creating a ASP.Net Web Site
I’ll use the empty C# template for a Web site by selecting the Visual C# option after selecting File | New | ASP.NET Empty Web Site.
Select an Empty ASP.Net Web Site
If you already have your Azure account setup up you will be promoted to configure your Microsoft Azure Web App Settings for publishing
If you have got this configured see http://docs.asp.net/en/latest/tutorials/publish-to-azure-webapp-using-vs.html or see my previous blog http://blogs.msdn.com/b/uk_faculty_connection/archive/2015/07/19/using-visual-studio-2015-and-deploying-your-first-web-app-to-your-free-azure-subscription.aspx
To create these new files right click on the new create web app in the solution explorer and select Add
Step 3. So what is the game
This game is based on Pong, except that either player grabs the ball when it comes to them and can then fire the ball back either directly or at an angle up or down. It’s often best to draw how you would like the game to look before you build it. For this game, the overall layout I want to see is shown below.
Once I’ve developed the game design layout, it’s just a matter of adding each element to HTML to build the game. One thing to note, though, is I’ll group the scoreboard and controls to ensure they sit together. So one by one, you can see I’ve added the elements, as shown below:
Step 4. Styling the Game using CSS
If you were to load this page, you wouldn’t see anything because there’s no style applied. I’ve already set up a link to a main.css file in my HTML,
We now need to create main.css.
The first thing I’ll do is position everything on the screen. The body of the page needs to take up the whole screen, so I’ll set that up first:
Second, I need to have the arena fill the whole screen with the arena background image (see image below) applied:
I want the scoreboard to appear top and centre, over the other elements.
The command position: absolute lets me place it wherever I want and left: 50% places it halfway across the top of the window, but starting at the leftmost side of the scoreboard element. To ensure it’s perfectly centered, I use the transform property and the z-index property ensures it’s always at the top:
I also want the text font to be used, Most modern browsers let you include actual fonts.
I found the appropriate Press Start 2P font from codeman38 www.zone38.net
To add the font to the scoreboard, you have to create a new font face in the style.css
The scores are in an h1 tag of index.html, so I can set the font for all h1 tags. Just in case the font is missing,
To do this simply add the following to style.css
For the player, ball and control icons I will be use a simply sprite sheet
I have a single sprite sheet that contains all the images I need for the game in one file sprites.png
As you can see I have two different colour players ball and control arrows
We now need to assign the sprite class element to style.css
Then, for each element, I’ll use background-position to define what part of the sprite sheet I want to show:
Next, I’ll add the sprite class to all elements that will use the sprite sheet.
To do this I simply need to add all the element into the <div> section of <body> in index.html
Add the following back to your index.html
Now I need to indicate the positions of each sprite on the sheet for each element. Again, I’ll do this using background-position in Style.css
There are four control elements (buttons the user can press to move the player about),. I’ll also add a margin so they have a little space around them:
After adding this class, the game has much better looking controls:
Edit index.html and add
The last thing I need to do is position the controls so they’re by the user’s thumbs when the page is running on a mobile device. I’ll stick them to the bottom corners:
so edit style.css
One nice thing about this design is everything is set with relative positions.
This means the screen can be a number of different sizes while still making the game look good so this game will support mobile, desktop and tablet devices.
Step 5. Making the Game Work
We now need to create ping.js
I’m going to make objects for the ball and each of the players, but I’ll use the factory pattern for the objects.
This is a simple concept. The Ball function creates a new ball when you call it. The following pattern reduces some of the confusion around the this variable by clarifying the available object properties. And because we only have an hour to make this game, I need to minimize any confusing concepts.
The structure of this pattern, as I make the simple Ball class:
To create a new ball, I simply call this function I’ve defined:
var ball = Ball();
Now I want to make the ball move and bounce around the screen.
First, I need to call the update function at some interval to create an animation of the ball.
Modern browsers provide a function meant for this purpose called requestAnimationFrame.
This takes a function as an argument, and will call that passed-in function the next time it runs its animation cycle. This lets the ball move around in smooth steps when the browser is ready for an update. When it calls the passed-in function, it will give it the time in seconds since the page was loaded. This is critical for ensuring animations are consistent over time. In the game, the use of requestAnimationFrame appears as follows:
In Ping.js add the following at the top of the file
Because I know the speed of the ball (velocity) and the time since its last update, I can do some simple physics to move the ball forward:
Try running the code and you’ll see the ball move at an angle and off the screen. This is fun for a second, but once the ball goes off the edge of the screen, the fun stops.
So the next step is to make the ball bounce off the edges of the screen,
Add this code and running the app will show a continuously bouncing ball.
Step 6. Creating Player Objects
Now it’s time to make the Player objects.
The first step in fleshing out the player class will be to make the move function change the position of the player. The side variable will indicate which side of the court the player will reside, which will dictate how to position the player horizontally. The y value, passed into the move function, will be how much up or down the player will move:
We can then lay out player movement, stopping the motion if the player sprite reaches the top or bottom of the window.
The height of the player is 128 pixels, so stop it before any part of the player extends off the screen.
If the player is meant to stick to the right side, set the player position to the right edge of the screen.
Finally, update the player's position on the page.
I can now create two players and have them move to their appropriate side of the screen:
So in theory you can move the player, but it won’t move without instruction. Add some controls to the player on the left.
You want two ways to control that player: using the keyboard (on PCs) and tapping the controls (on tablets and phones).
To ensure consistency between touch inputs and mouse inputs on various platforms, I’ll use the great unifying framework hand.minified there are others like https://github.com/jquery/PEP
First, I’ll add the script to HTML in the head section:
I’ll then use Hand.js and jQuery to control the player when you press keyboard keys A and Z, or when you tap the controls.
In ping.css add the following at the top where you declare variables
Add the following section for controls
This code converts the keyCode (a number) from the event to an uppercaseletter to make the switch statement easier to read.
Step 7. Adding Functions
As the ball bounces around, I want to let players catch it. When it’s caught, the ball has an owner, and it follows the motion of that owner. I’ll add functionality to the ball’s move method, allowing for an owner, which the ball will then follow:
If there is an owner, move the ball to match the owner's position.
Otherwise, move the ball using physics. Note the horizontal bouncing has been removed -- ball should pass by a player if it isn't caught.
If the ball hits the top or bottom, reverse the vertical speed.
Currently, there’s no way to get the position of a Player object, so I’ll add the getPosition and getSide accessors to the Player object:
Now, if the ball has an owner, it will follow that owner around. But how do I determine the owner? Somebody has to catch the ball. Let’s determine when one of the player sprites touches the ball. When that happens, I’ll set the owner of the ball to that player.
First the motion of the ball is handled.
The ball is under control of a player, no need to update.
First, check if the ball is about to be grabbed by the player.
Then by the opponent...
If you try playing the game now, you’ll find the ball bounces off the top of the screen, and you can move the player to catch it.
Now, how do you throw it?
That’s what the right-hand controls are for—aiming the ball.
Let’s add a “fire” function to the player, as well as an aim property.
Add supporting for Aiming
The fire function
Safety check: if the ball doesn't have an owner, don't not mess with it.
Depending on the side the player is on, different directions will be thrown.The ball should move at the same speed, regardless of direction -- with some math you can determine that moving .707 pixels on the x and y directions is the same speed as moving one pixel in just one direction.
Release control of the ball.
The rest of the Ball definition code goes here...
We can then augment the keyboard function to set the player’s aim and fire functions.
Aiming will work slightly differently. When the aiming key is released, the aim will return to straightforward.
The final addition will be touch support on all controls.
I’ll make the controls on the right change the aim of the player. I’ll also make it so touching on your player fires the ball additionally you need to touch-action:none; in the style.css to all of #up #down ‘'#left #right #player
Step 8. Keep Score
When the ball passes a player, I want to change the score and give the ball to that player. I’ll use custom events so I can separate scoring from any of the existing objects.
The update function is getting long, so I’ll add a new private function called checkScored:
Now when the ball makes it past your opponent (which isn’t that difficult, as the opponent doesn’t move) your score will go up, and the ball will be handed to the opponent. However, the opponent will just hold onto the ball.
Step 9. Adding an AI
You almost have a game.
The last step is adding the opponent with simple AI.
The opponent will try to stay parallel with the ball as it moves about. If the opponent catches the ball, it will move randomly and fire the ball in a random direction.
To make the AI feel a little more human, we will add delays in everything done.
The opponent AI has three possible states: following, aiming/shooting and waiting. I’ll be the state between following actions to add a more human element. Start with just that for the AI object:
Depending on the state of the AI, I’ll want it to do a different action. Just like the ball, I’ll make an update function I can call in requestAnimationFrame to have the AI act according to its state:
Do something to follow the ball.
Do something to wait.
Do Something to Aiming
The FOLLOWING state is straightforward. The opponent moves in the vertical direction of the ball, and the AI transitions to the WAITING state to inject some slowed reaction time. The code below shows these two states:
The AI alternates between having to follow the ball and wait a split second. Now add the code to the game-wide update function:
When you run the game, you’ll see the opponent follow the ball’s movements,
So thats a nice little AI in less than 30 lines of code.
Of course, if the opponent catches the ball, it won’t do anything.
So we now need to handle the actions for the AIMING state.
I want the AI to move randomly a few times and then fire the ball in a random direction. Let’s add a private function that does just that.
Adding the aimAndFire function to the AIMING case statement makes a fully functional AI against which to play.
Repeat the motion action 5 to 10 times.
Finally, set the state to FOLLOWING.
Thanks you have completed the tutorial
All you need to do now is your publish your game to your Azure subscription.
Simply select Web site under the solution explorer right click and select publish
You can download the entire source to the project at https://github.com/leestott/Pong-Game---HTML-JS-Web-Game
Step 10. Testing your web site
This code is interoperable with modern browsers like Chrome, Firefox, and Microsoft Edge, it’s always a best practice to double-check.
You can also scan your existing web sites and apps for out-of-date libraries, layout issues, and accessibility
And you can even now test you site Remotely for Microsoft Edge Support
There are loads of free great coding resources
More free cross-platform tools & resources for the Web Platform:
More advanced resources
Woah, I can test Edge & IE on a Mac & Linux! (from Rey Bango)
The Edge Rendering Engine that makes the Web just work (from Jacob Rossi)