Creating a Simple Windows 8 Game with JavaScript: Windows 8 App Basics

Share this article

“Shall We Make a Game?”

This is the first in a series of four posts over four weeks that will show you how to create a (very) simple Windows 8 game. We’ll be using HTML5, JavaScript, WinJS, and some helpful libraries from CreateJS along the way. The game is based on the XNA sample game “Catapult Wars Lab”. We’ll reuse the assets from that game as we develop a new version for Windows 8 that’s based on web technologies. Catapult Wars This game focuses on simplicity, so there are a number of intermediate techniques that aren’t used in this sample. For more comprehensive samples, see “Further Reading” at the end of this post. Let’s get started. In this post, we’ll focus on the basics of a Windows 8 project.

Setting Up

To develop this game (or any Windows 8 Metro style application) you need to have both Windows 8 and Visual Studio 2012. Download and install these before moving on. We won’t cover that here because it’s explained well online.

Creating the Project

Start Visual Studio 2012 and choose FILE -> New Project (or CTRL + SHIFT + N). We’ll be using JavaScript, so choose that node under Templates. We’ll be relying on HTML5 canvas for UI so we only need the “Blank App” template (other templates have common Metro style layout and controls built in): screen shot of Blank App template Name the project “CatapultGame” and click OK to reate the project. There is some guidance about the Blank App template, but I’ll give you a quick tour now.

Understanding the Project

So, what did we get? Open some files in Solution Explorer and take a look around. If you expand all of the folders, you’ll see something like this: screen shot of Solution Explorer Here are the main parts to focus on:
  • /References/Windows Library for JavaScript – This is “WinJS”, the layer of JavaScript and CSS that helps us develop JavaScript Metro style apps for Windows 8. You can’t modify these files, but I recommend you take a look through them (later).
  • /css/default.css – Starter CSS, including basics for handling screen changes via media queries. We’ll also build on this later.
  • /js/default.js – Has some starter JavaScript logic. We’ll add our own here soon.
  • default.html – The root HTML page for our game
  • package.appxmanifest – Contains many settings that help you personalize the application.  It’s XML, but if you double-click to open you’ll get a friendly interface for changing settings.
Also, the “images” folder has some default content used by the app for logos and a splash screen.  You’ll want to add your own.

Running the Game… well, the Empty Project

So, let’s run the project to see what we get.  First, there are some options for running the project: screen shot of Local Machine settings Using the local machine is the default, but it’s also easy to connect to another machine with Remote Machine so you can run and use the project on the target machine, while debugging on your local machine.  Simulator lets you test various screen sizes/resolutions, simulate touch input, adjust location, and more. For now, let’s run with Local Machine (click the button, press F5, or choose DEBUG -> Start Debugging). screen shot of the empty project A fun game, indeed!

Getting Started

So, where did that “Content goes here” text come from?  Open default.html, and here’s what you should see:
 <!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8" /> 
<title>CatapultGame</title> 
 
<!-- WinJS references --> 
<link href="//Microsoft.WinJS.1.0.RC/css/ui-dark.css" rel="stylesheet" /> 
<script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script> 
<script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script> 
 
<!-- CatapultGame references --> 
<link href="/css/default.css" rel="stylesheet" /> 
<script src="/js/default.js"></script> 
</head> 
<body> 
<p>Content goes here</p> 
</body> 
</html> 
What’s going on here?
  • Line 1 – Says we’re targeting HTML5
  • Lines 7-10 – Referencing WinJS’s CSS & JavaScript
  • Lines 12-14 – Other references, including the default JS and CSS files. We’ll be adding others here later.
  • Lines 16-18 – The body of our HTML page
As you can see, it’s just basic HTML.  Go ahead and have a little fun changing the HTML in the <body> and running again.

Where CSS Fits In

We’ve seen the default.html file, providing references and base content for the project, but HTML is only part of the story.  Web applications use HTML for content, JavaScript to make things happen, and CSS (Cascading Style Sheets) to affect design & appearance in a maintainable way. CSS styles work by identifying (selecting) target elements and applying effects – color, shadow, text, transitions, transforms, layout… the list goes on.  CSS has so many features to help us create amazing effects, it would be ridiculous to attempt an overview here.  Just know that Visual Studio 2012 has many features to help you create and modify styles, and the more CSS you know, the more effective you’ll be. Take a look at /css/default.css:
body { 
  } 
 
@media screen and (-ms-view-state: fullscreen-landscape) { 
  } 
 
@media screen and (-ms-view-state: filled) { 
  } 
 
@media screen and (-ms-view-state: snapped) { 
  } 
 
@media screen and (-ms-view-state: fullscreen-portrait) { 
  } 
By default, no styles are being applied, but what is this for?
  • Lines 1 & 2 – This selects the <body> tag of any page that references this file and will apply to that content any style rules we add.
  • Lines 4-14 – These are CSS Media Queries, incredibly useful for adapting layout based on how the content is being displayed.  In this case, there are states in which Metro style apps can run – full screen landscape, filled, snapped, and full screen portrait – and these map to the four regions.  You can use this approach to customize your game to best utilize the available screen space.
We’ll add to this later.  Stay tuned.

JavaScript, the Action Hero

We’ve seen HTML content & CSS styles, but how do things come to life?  How can the game “know” what’s going on? Let’s switch over to the js/default.js file and take a look:
 // For an introduction to the Blank template, see the following documentation: 
// http://go.microsoft.com/fwlink/?LinkId=232509 
(function () { 
  "use strict"; 
 
  var app = WinJS.Application; 
  var activation = Windows.ApplicationModel.Activation; 
  WinJS.strictProcessing();
 
  app.onactivated = function (args) { 
    if (args.detail.kind === activation.ActivationKind.launch) { 
      if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
      // TODO: This application has been newly launched. Initialize 
      // your application here. 
      } else { 
        // TODO: This application has been reactivated from suspension. 
        // Restore application state here. 
        } 
      args.setPromise(WinJS.IU.processAll()); 
      } 
    }; 
 
  app.oncheckpoint = function (args) { 
    // TODO: This application is about to be suspended. Save any state 
    // that needs to persist across suspension here. You might use the 
    // WinJS.Application.sessionState object, which is automatically 
    // saved and restored across suspension. If you need to complete an 
    // asynchronous operation before your application is suspended, call 
    // args.setPromise(). 
  }; 
 
  app.start(); 
  })(); 
It may look like a lot, but it’s pretty straightforward, just there to help us get started:
  • Lines 3-33 – Haven’t seen a JavaScript function like this before? It’s an “Immediately-Invoked Function Expression” or IIFE (pronounced “iffy”). Short version, it keeps variables and functions tidy without affecting the global namespace. Medium version, read section 4 of Addy Osmani’s Essential JavaScript Namespacing Patterns. Longer version, I’m a fan of Ben Allman’s IIFE post.
  • Lines 6-7 – Variables for the frequently-used Application and Activation classes.
  • Line 8 – Calling WinJS.strictProcessing enables strict declarative processing (helping to detect errors more easily)
  • Lines 10-21 – Activation code. First TODO is when the app is newly launched, second TODO is where we can load saved state when the app returns from being suspended by Windows.
  • Lines 23-30 – A chance to save state before the app is suspended. Particularly important because suspension can be followed by termination, and if the game’s state isn’t saved here, the player has to start over when he/she returns to the game.
This is where we’ll soon add the game’s logic.  From code to load images, managing the game world, and various helper functions, to the game loop to control updating state and displaying content. By the way, in this sample we’re going to do the simple thing by adding code only to default.js, but well-factored applications will generally have multiple JavaScript files, for example to create classes around game elements – player, planet, item, world, etc.  For some excellent recommendations and practices, see “JavaScript Game Code Organization” by Greg Smith.

What’s Next?

That was a brief overview of the basic gears and pulleys behind a Metro style application.  Next week, we’ll start creating the game by bringing in content from the “Catapult Wars” starter project and getting the game’s basic structure in place.

Further Reading

Again, this series focuses on ease of learning and simplicity, so for a more comprehensive game sample, see the “JavaScript and HTML5 touch game sample” and related tutorial on MSDN.

Frequently Asked Questions (FAQs) about Creating a Simple Windows 8 Game with JavaScript

How can I start developing apps for Windows 8?

To start developing apps for Windows 8, you need to have a basic understanding of programming languages like JavaScript, HTML, and CSS. You also need to install Visual Studio, which is the development environment for Windows apps. Once you have these prerequisites, you can start creating your app by setting up a new project in Visual Studio, designing your app’s interface, and writing the code for your app’s functionality. Remember to test your app regularly during the development process to ensure it works as expected.

What are the basics of creating a game with JavaScript for Windows 8?

Creating a game with JavaScript for Windows 8 involves several steps. First, you need to set up your development environment, which includes installing Visual Studio and creating a new project. Next, you need to design your game’s interface using HTML and CSS. After that, you can start writing the game logic using JavaScript. This includes defining the game’s rules, creating game objects, and handling user input. Finally, you need to test your game to ensure it works correctly.

How can I create a 2D game using pure JavaScript?

Creating a 2D game using pure JavaScript involves several steps. First, you need to define the game’s objects, such as the player character, enemies, and items. Next, you need to write the game logic, which includes handling user input, updating the game state, and rendering the game objects. You also need to create a game loop that updates and renders the game at a consistent rate. Finally, you need to test your game to ensure it works correctly.

What are some good JavaScript games for beginners to develop?

Some good JavaScript games for beginners to develop include simple 2D games like Pong, Snake, and Breakout. These games have simple rules and mechanics, making them ideal for beginners to learn the basics of game development. They also require minimal graphics and sound, allowing beginners to focus on the programming aspects of game development.

How can I publish my Windows 8 app?

To publish your Windows 8 app, you need to create an app package using Visual Studio and then submit it to the Microsoft Store. The submission process involves providing details about your app, such as its name, description, and screenshots, and specifying its pricing and availability. Once your app is submitted, it will be reviewed by Microsoft before it is published on the Microsoft Store.

How can I debug my JavaScript game?

Debugging your JavaScript game involves identifying and fixing errors in your code. You can use the debugging tools in Visual Studio to help with this. These tools allow you to step through your code, inspect variables, and set breakpoints. You can also use console.log statements in your code to output debug information.

How can I handle user input in my JavaScript game?

Handling user input in your JavaScript game involves listening for input events, such as key presses and mouse clicks, and then updating your game state based on these events. You can use the addEventListener function in JavaScript to listen for these events.

How can I create game objects in JavaScript?

Creating game objects in JavaScript involves defining a class for each type of game object. Each class should define the properties and methods of the game object, such as its position, size, and behavior. You can then create instances of these classes to represent the actual game objects in your game.

How can I render game objects in my JavaScript game?

Rendering game objects in your JavaScript game involves drawing them on the screen. You can use the Canvas API in JavaScript to do this. The Canvas API provides functions for drawing shapes, images, and text, allowing you to create a wide range of game objects.

How can I create a game loop in JavaScript?

Creating a game loop in JavaScript involves setting up a function that updates and renders your game at a consistent rate. You can use the requestAnimationFrame function in JavaScript to do this. This function calls your game loop function once per frame, ensuring your game runs smoothly.

Chris BowenChris Bowen
View Author

Chris Bowen is a Principal Technical Evangelist with Microsoft, based in the Boston area and specializing in Windows 8 development. An architect and developer with over 19 years in the industry, he joined Microsoft after holding senior technical positions at companies including Monster.com, VistaPrint, and Staples. He is coauthor of two books (with Addison-Wesley and WROX) and holds an M.S. in Computer Science and a B.S. in Management Information Systems, both from Worcester Polytechnic Institute.

HTML5 Dev CenterHTML5 Tutorials & Articles
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week