HTML and CSS Reference
In-Depth Information
Listing 20-1. An Example of Dart
main() { // This is where the app starts executing.
print(new Fibonacci(10)); // Print a new object's value.
}
class Fibonacci { // Define a class.
int original, fibo; // Declare variables with (optional) types.
String toString() => '$fibo'; // Define a method using shorthand syntax.
Fibonacci(int value) : // Define a constructor with list initializer.
original = value, fibo = fib(value) {
}
static int fib(int n) { // Define a class method.
if (n < 2) { // Control flow and expressions.
return n;
} else {
return fib(n-1) + fib(n-2); // Arithmetic operators.
}
}
}
// Want terser code? Write a one-line function instead:
// fib(n) => n < 2 ? n : (fib(n - 1) + fib(n - 2));
Dart provides a familiar but modern syntax. Contrary to JavaScript, Dart has first-class support for classes and
allows for (optional) type annotations, which are used only during development to catch programmer errors early.
game_loop
The sample code provided in this chapter is part of the game_loop package available via Dart's package management
tool, pub . If you decide to write your next game in Dart, you can use the code directly. However, if you decide to use a
different language, it should be trivial to port the code from Dart to your language of choice.
The easiest way to get game_loop is to add it as a dependency in your project's pubspec.yaml . You can always
find the source code for the latest version of game_loop in its GitHub repository at http://github.com/johnmccutchan/
game_loop .
Interfacing with the Browser
Before discussing main loops in detail, it is important to understand that the browser is in control of the main loop.
The browser places constraints on the main loop because it is in control of when the loop executes and provides the
inputs (time, render signal, and user input) needed to make progress. An example of the browser controlling the
main loop is requestAnimationFrame , which dictates when the main loop must render the game into the page
for compositing. This is the display synchronization point. You request to receive this event by registering a frame
callback with requestAnimationFrame . The next time your game should draw itself to the screen, the frame callback
will be executed. It is important to understand that the browser tells you when to render, not the other way around.
This example demonstrates how, in general, the browser is in control of the main loop.
 
Search WWH ::




Custom Search