HTML and CSS Reference
In-Depth Information
Chapter 20
Implementing a Main Loop in Dart
John McCutchan, Software Engineer, Google
At the heart of your favorite games is the game loop. At the core of the game loop is control over the game clock.
In each frame the game does some or all of the following: updates the game state, triggers timers, processes user inputs,
renders graphics, and plays audio. Each of these operations must be synchronized using a virtual clock controlled by
the game loop. This chapter explains how to implement a deterministic and efficient main loop for any type of game
designed from the ground up to run in the browser.
This chapter uses the Dart programming language ( www.dartlang.org/ ) for reference code but the focus of this
chapter is not on Dart. Dart should be familiar to programmers coming from languages like Java or C#, and the code does
not make use of any of Dart's higher-level features. All DOM calls can be easily mapped to their JavaScript equivalents.
Implementing a main loop must be done with respect to the browser's execution model. The Dart program
cannot execute endlessly; it must yield control back to the browser every frame. User inputs are delivered via
asynchronous event callbacks and the rendering is synchronized with the browser by performing rendering in the
frame callback.
User inputs are delivered as discrete events through callbacks registered with the browser. The browser delivers a
different input event per device type. For example, there are four separate event sources for key down, key up, mouse
button down, and mouse button up. The main loop should record all user inputs into a single stream of input events
between frames, allowing input code to process all inputs in one location. Processing complex user inputs like chords
or sequences will be covered as well.
When you finish this chapter you will be able to build a robust, reusable, main loop upon which you can build games.
Sample Code
The source code included with this chapter is written in Dart. Dart is an object-oriented programming language that
can run in any browser by being compiled to JavaScript or run in a version of Chromium that includes the Dart virtual
machine (VM). Even though the source code is written in Dart, the focus of this chapter is on the main loop for games,
and the concepts, design, and algorithms discussed in this chapter do not depend on Dart functionality.
Dart
Dart is an object-oriented programming language designed to be familiar to programmers coming from
object-oriented languages like Java or C#. The Dart language is stricter than JavaScript and, in turn, programs written
in Dart can run significantly faster than programs written in JavaScript. An example of Dart is shown in Listing 20-1.
 
Search WWH ::




Custom Search