recursal/MDN huggingface dataset:
Techniques for game development
===============================

This page lists essential core techniques for anyone wanting to develop games using open web technologies.

Using async scripts for asm.js

Especially when creating medium to large-sized games, async scripts are an essential technique to take advantage of, so that your game's JavaScript can be compiled off the main thread and be cached for future game running, resulting in a significant performance improvement for your users. This article explains how.

Optimizing startup performance

How to make sure your game starts up quickly, smoothly, and without appearing to lock up the user's browser or device.

Using WebRTC peer-to-peer data channels

In addition to providing support for audio and video communication, WebRTC lets you set up peer-to-peer data channels to exchange text or binary data actively between your players. This article explains what this can do for you, and shows how to use libraries that make this easy.

Audio for Web Games

Audio is an important part of any game — it adds feedback and atmosphere. Web-based audio is maturing fast, but there are still many browser differences to negotiate. This article provides a detailed guide to implementing audio for web games, looking at what works currently across as wide a range of platforms as possible.

2D collision detection

A concise introduction to collision detection in 2D games.

Tilemaps

Tiles are a very popular technique in 2D games for building the game world. These articles provide an introduction to tilemaps and how to implement them with the Canvas API.
Async scripts for asm.js
========================

Every medium or large game should compile asm.js code as part of an async script to give the browser the maximum flexibility to optimize the compilation process. In Gecko, async compilation allows the JavaScript engine to compile the asm.js off the main thread when the game is loading and cache the generated machine code so that the game doesn't need to be compiled on subsequent loads (starting in Firefox 28). To see the difference, toggle `javascript.options.parallel_parsing` in `about:config`.

Putting async into action
-------------------------

Getting async compilation is easy: when writing your JavaScript, just use the `async` attribute like so:


```html
<script async src="file.js"></script>
```


or, to do the same thing via script:


```js
const script = document.createElement("script");
script.src = "file.js";
document.body.appendChild(script);
```


(Scripts created from script default to `async`.) The default HTML shell Emscripten generates produces the latter.

When is async not async?
------------------------

Two common situations in which a script is \*not\* async (as defined by the HTML spec) are:


```html
<script async>
 code();
</script>
```


and


```js
const script = document.createElement("script");
script.textContent = "code()";
document.body.appendChild(script);
```


Both are counted as 'inline' scripts and get compiled and then run immediately.

What if your code is in a JS string? Instead of using `eval` or `innerHTML`, both of which trigger synchronous compilation, you should use a Blob with an object URL:


```js
const blob = new Blob([codeString]);
const script = document.createElement("script");
const url = URL.createObjectURL(blob);
script.onload = script.onerror = () => URL.revokeObjectURL(url);
script.src = url;
document.body.appendChild(script);
```


The setting of `src` rather than `innerHTML` is what makes this script async.
WebRTC data channels
====================

The WebRTC (Web Real-Time Communications) API is primarily known for its support for audio and video communications; however, it also offers peer-to-peer data channels. This article explains more about this, and shows you how to use libraries to implement data channels in your game.

What is a data channel?
-----------------------

A WebRTC data channel lets you send text or binary data over an active connection to a peer. In the context of a game, this lets players send data to each other, whether text chat or game status information. Data channels come in two flavors.

**Reliable channels** guarantee that messages you send arrive at the other peer and in the same order in which they're sent. This is analogous to a TCP socket.

**Unreliable channels** make no such guarantees; messages aren't guaranteed to arrive in any particular order and, in fact, aren't guaranteed to arrive at all. This is analogous to a UDP socket.

We have documentation for using WebRTC. This article, however, will take advantage of some libraries that can help trivialize the work, and will demonstrate ways to use abstraction to work around implementation differences between browsers. Hopefully, of course, those differences will fade away in time.

Using the p2p library
---------------------

One library you can use is the p2p library. This library provides a simple API for creating peer connections and setting up streams and data channels. There's also a broker server component and a hosted broker you can use instead of having to set one up for yourself.

**Note:** We will continue to add content here soon; there are some organizational issues to sort out.

Original Document Information
-----------------------------

* Author(s): Alan Kligman
* Source Article: WebRTC Data Channels for Great Multiplayer
* Other Contributors: Robert Nyman
* Copyright Information: Alan Kligman, 2013
Building up a basic demo with PlayCanvas
========================================

**PlayCanvas** is a popular 3D WebGL game engine, originally created by Will Eastcott and Dave Evans. It is open sourced on GitHub, with an editor available online and good documentation. The online editor is free for public projects with up to two team members, but there are also paid plans if you'd like to run a commercial private project with more developers.

![PlayCanvas website.](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/playcanvas-cover.png)

Games and demos
---------------

PlayCanvas has a few well-known demos published that showcase its possibilities.

* Tanx is a multiplayer tank game where you can drive your tank around, shooting at other players as you go.
* Swooop is a flying game where you pilot your plane around a magical island, collecting jewels and fuel as you go.
* Visualizations like the Star Lord and BMW i8 also take advantage of the engine and showcase what's possible.

![A list of PlayCanvas demos: Tanx, Swooop, Star Lord, BMW i8.](/en-US/docs/Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_PlayCanvas/playcanvas-demos.png)

**Note:** Check out the list of featured demos to find more examples.

Engine vs. editor
-----------------

The engine itself can be used as a standard library by including its JavaScript file directly in your HTML, so you can start coding right away; in addition the PlayCanvas toolset comes with an online editor that you can use to drag and drop components onto the scene — a great way to create games and other apps requiring scenes if you're more of a designer than a coder. Those approaches are different but work equally well regarding achieving end goals.

PlayCanvas engine
-----------------

Built for modern browsers, PlayCanvas is a fully-featured 3D game engine with resource loading, an entity and component system, advanced graphics manipulation, collision and physics engine (built with ammo.js), audio, and facilities to handle control inputs from various devices (including gamepads). That's quite an impressive list of features — let's see some in action, check out the Building up a basic demo with PlayCanvas engine for details.

PlayCanvas editor
-----------------

Instead of coding everything from the beginning you can also use the online editor. This can be a more pleasant working environment if you are not someone who likes to code. See the Building up a basic demo with PlayCanvas editor for details.

Summary
-------

Of course, it depends on your approach — designers may favor the online editor while programmers will prefer having the full control over the coding environment and will probably use the engine's source files. The good thing is that you have a choice and can pick whatever tools suit you best.
asm.js
======

**Warning:** The asm.js specification is considered **deprecated**.
 Developers may look to WebAssembly as an alternative to asm.js for running high-performance code in the browser.


Asm.js is a specification defining a subset of JavaScript that is highly optimizable. This article looks at exactly what is permitted in the asm.js subset, what improvements it confers, where and how you can make use of it, and further resources and examples.

What is asm.js, exactly?
------------------------

It is a very small, strict subset of JavaScript that only allows things like `while`, `if`, numbers, top-level named functions, and other simple constructs. It does not allow objects, strings, closures, and basically anything that requires heap allocation. Asm.js code resembles C in many ways, but it's still completely valid JavaScript that will run in all current engines. It pushes JS engines to optimize this kind of code, and gives compilers like Emscripten a clear definition of what kind of code to generate. We will show what asm.js code looks like and explain how it helps and how you can use it.

This subset of JavaScript is already highly optimized in many JavaScript engines using fancy Just-In-Time (JIT) compiling techniques. However, by defining an explicit standard we can work on optimizing this kind of code even more and getting as much performance as we can out of it. It makes it easier to collaborate across multiple JS engines because it's easy to talk about and benchmark. The idea is that this kind of code **should** run very fast in each engine, and if it doesn't, it's a bug and there's a clear spec that engines should optimize for.

It also makes it easy for people writing compilers that want to generate high-performant code on the web. They can consult the asm.js spec and know that it will run fast if they adhere to asm.js patterns. Emscripten, a C/C++ to JavaScript compiler, emits asm.js code to make it run with near native performance on several browsers.

Additionally, if an engine chooses to specially recognize asm.js code, there even more optimizations that can be made. Firefox is the only browser to do this right now.

asm.js language summary
-----------------------

asm.js is an intermediate programming language. asm.js has a very predictable performance rate because it is limited to an extremely restricted subset of JavaScript that provides only strictly-typed integers, floats, arithmetic, function calls, and heap accesses. The performance characteristics are closer to native code than that of standard JavaScript. Using a subset of JavaScript asm.js is already supported by major web browsers. Since asm.js runs in a browser it depends heavily on the browser and the hardware.
Touch Event Horizon
===================

This article is for Touch Event Horizon and A Game Related To It

Touch Gestures and Events
-------------------------

Link

The example game
----------------

![Box with the text touch to start](/en-US/docs/Games/Tutorials/Touch_Event_Horizon/touch-to-start.png)

![Two circles placed side-by-side, one bigger than the other. The size of the circle represents a player's score. The scores are written above each circle.](/en-US/docs/Games/Tutorials/Touch_Event_Horizon/tapping.png)

GitHub repository

Live demo

### Setting up the canvas

### Counting the taps

touchstart, touchend

### Collecting the bonus

touchmove

Future developments
-------------------

Summary
-------

This tutorial shows how to use Touch Events to create a game on a <canvas>. This is a multiplayer game relying on the Tap and Drag gestures.
2D breakout game using pure JavaScript
======================================

* Next »

In this step-by-step tutorial we create a simple **MDN Breakout** game written entirely in pure JavaScript and rendered on HTML `<canvas>`.

Every step has editable, live samples available to play with so you can see what the intermediate stages should look like. You will learn the basics of using the `<canvas>` element to implement fundamental game mechanics like rendering and moving images, collision detection, control mechanisms, and winning and losing states.

To get the most out of this series of articles you should already have basic to intermediate JavaScript knowledge. After working through this tutorial you should be able to build your own simple Web games.

![Gameplay screen from the game MDN Breakout where you can use your paddle to bounce the ball and destroy the brick field, with keeping the score and lives.](/en-US/docs/Games/Tutorials/2D_Breakout_game_pure_JavaScript/mdn-breakout-gameplay.png)

Lesson details
--------------

All the lessons — and the different versions of the MDN Breakout game we are building together — are available on GitHub:

1. Create the Canvas and draw on it
2. Move the ball
3. Bounce off the walls
4. Paddle and keyboard controls
5. Game over
6. Build the brick field
7. Collision detection
8. Track the score and win
9. Mouse controls
10. Finishing up

Starting with pure JavaScript is the best way to get a solid knowledge of web game development. After that, you can pick any framework you like and use it for your projects. Frameworks are just tools built with the JavaScript language; so even if you plan on working with them, it's good to learn about the language itself first to know what exactly is going on under the hood. Frameworks speed up development time and help take care of boring parts of the game, but if something is not working as expected, you can always try to debug that or just write your own solutions in pure JavaScript.

**Note:** If you are interested in learning about 2D web game development using a game library, consult this series' counterpart, 2D breakout game using Phaser.

**Note:** This series of articles can be used as material for hands-on game development workshops. You can also make use of the Gamedev Canvas Content Kit based on this tutorial if you want to give a talk about game development in general.

Next steps
----------

Ok, let's get started! Head to the first chapter— Create the Canvas and draw on it.

* Next »
2D breakout game using Phaser
=============================

* Next »

In this step-by-step tutorial, we create a simple mobile **MDN Breakout** game written in JavaScript, using the Phaser framework.

Every step has editable, live samples available to play with, so you can see what the intermediate stages should look like. You will learn the basics of using the Phaser framework to implement fundamental game mechanics like rendering and moving images, collision detection, control mechanisms, framework-specific helper functions, animations and tweens, and winning and losing states.

To get the most out of this series of articles you should already have basic to intermediate JavaScript knowledge. After working through this tutorial, you should be able to build your own simple Web games with Phaser.

![Gameplay screen from the game MDN Breakout created with Phaser where you can use your paddle to bounce the ball and destroy the brick field, with keeping the points and lives.](/en-US/docs/Games/Tutorials/2D_breakout_game_Phaser/mdn-breakout-phaser.png)

Lesson details
--------------

All the lessons — and the different versions of the MDN Breakout game we are building together — are available on GitHub:

1. Initialize the framework
2. Scaling
3. Load the assets and print them on screen
4. Move the ball
5. Physics
6. Bounce off the walls
7. Player paddle and controls
8. Game over
9. Build the brickfield
10. Collision detection
11. The score
12. Win the game
13. Extra lives
14. Animations and tweens
15. Buttons
16. Randomizing gameplay

As a note on learning paths — starting with pure JavaScript is the best way to get a solid knowledge of web game development. If you are not already familiar with pure JavaScript game development, we would suggest that you first work through this series' counterpart, 2D breakout game using pure JavaScript.

After that, you can pick any framework you like and use it for your projects; we have chosen Phaser as it is a good solid framework, with a good support and community available, and a good set of plugins. Frameworks speed up development time and help take care of the boring parts, allowing you to concentrate on the fun stuff. However, frameworks are not always perfect, so if something unexpected happens or you want to write some functionality that the framework does not provide, you will need some pure JavaScript knowledge.

**Note:** This series of articles can be used as material for hands-on game development workshops. You can also make use of the Gamedev Phaser Content Kit based on this tutorial if you want to give a talk about game development with Phaser.

Next steps
----------

Ok, let us get started! Head to the first part of the series — Initialize the framework.

* Next »
Mouse controls
==============

* « Previous
* Next »

This is the **9th step** out of 10 of the Gamedev Canvas tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Canvas-workshop/lesson9.html.

The game itself is actually finished, so let's work on polishing it up. We have already added keyboard controls, but we could easily add mouse controls too.

Listening for mouse movement
----------------------------

Listening for mouse movement is even easier than listening for key presses: all we need is the listener for the `mousemove` event. Add the following line in the same place as the other event listeners, just below the `keyup event`:


```js
document.addEventListener("mousemove", mouseMoveHandler, false);
```

Anchoring the paddle movement to the mouse movement
---------------------------------------------------

We can update the paddle position based on the pointer coordinates — the following handler function will do exactly that. Add the following function to your code, below the previous line you added:


```js
function mouseMoveHandler(e) {
  const relativeX = e.clientX - canvas.offsetLeft;
  if (relativeX > 0 && relativeX < canvas.width) {
    paddleX = relativeX - paddleWidth / 2;
  }
}
```


In this function we first work out a `relativeX` value, which is equal to the horizontal mouse position in the viewport (`e.clientX`) minus the distance between the left edge of the canvas and left edge of the viewport (`canvas.offsetLeft`) — effectively this is equal to the distance between the canvas left edge and the mouse pointer. If the relative X pointer position is greater than zero and lower than the Canvas width, the pointer is within the Canvas boundaries, and the `paddleX` position (anchored on the left edge of the paddle) is set to the `relativeX` value minus half the width of the paddle, so that the movement will actually be relative to the middle of the paddle.

The paddle will now follow the position of the mouse cursor, but since we're restricting the movement to the size of the Canvas, it won't disappear completely off either side.

Compare your code
-----------------

This is the latest state of the code to compare against:

**Note:** Try adjusting the boundaries of the paddle movement, so the whole paddle will be visible on both edges of the Canvas instead of only half of it.

Next steps
----------

Now we've got a complete game we'll finish our series of lessons with some more small tweaks — Finishing up.

* « Previous
* Next »
Game over
=========

* « Previous
* Next »

This is the **5th step** out of 10 of the Gamedev Canvas tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Canvas-workshop/lesson5.html.

It's fun to watch the ball bouncing off the walls and be able to move the paddle around, but other than that the game does nothing and doesn't have any progression or end goal. It would be good from the gameplay point of view to be able to lose. The logic behind losing in breakout is simple. If you miss the ball with the paddle and let it reach the bottom edge of the screen, then it's game over.

Implementing game over
----------------------

Let's try to implement game over in our game. Here's the piece of code from the third lesson where we made the ball bounce off the walls:


```js
if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
  dx = -dx;
}

if (y + dy > canvas.height - ballRadius || y + dy < ballRadius) {
  dy = -dy;
}
```


Instead of allowing the ball to bounce off all four walls, let's only allow three now — left, top and right. Hitting the bottom wall will end the game. We'll edit the second if block so it's an if else block that will trigger our "game over" state upon the ball colliding with the bottom edge of the canvas. For now we'll keep it simple, showing an alert message and restarting the game by reloading the page.

First, replace where you initially called `setInterval()`


```js
setInterval(draw, 10);
```


with:


```js
const interval = setInterval(draw, 10);
```


Then replace the second if statement with the following:


```js
if (y + dy < ballRadius) {
  dy = -dy;
} else if (y + dy > canvas.height - ballRadius) {
  alert("GAME OVER");
  document.location.reload();
  clearInterval(interval); // Needed for Chrome to end game
}
```

Letting the paddle hit the ball
-------------------------------

The last thing to do in this lesson is to create some kind of collision detection between the ball and the paddle, so it can bounce off it and get back into the play area. The easiest thing to do is to check whether the center of the ball is between the left and right edges of the paddle. Update the last bit of code you modified again, to the following:


```js
if (y + dy < ballRadius) {
  dy = -dy;
} else if (y + dy > canvas.height - ballRadius) {
  if (x > paddleX && x < paddleX + paddleWidth) {
    dy = -dy;
  } else {
    alert("GAME OVER");
    document.location.reload();
    clearInterval(interval);
  }
}
```


If the ball hits the bottom edge of the Canvas we need to check whether it hits the paddle. If so, then it bounces off just like you'd expect; if not, then the game is over as before.

Compare your code
-----------------

Here's the working code for you to compare yours against:

**Note:** Try making the ball move faster when it hits the paddle.

Next steps
----------

We're doing quite well so far and our game is starting to feel a lot more worth playing now that you can lose! But it is still missing something. Let's move on to the sixth chapter — Build the brick field — and create some bricks for the ball to destroy.

* « Previous
* Next »