Spiral 1 – drawing the board

The app starts with main() in educ_memory_game.dart:

library memory;

import 'dart:html';
import 'dart:async';

part 'board.dart';

void main() {
  // Get a reference to the canvas.
  CanvasElement canvas = querySelector('#canvas'),          (1)
  new Board(canvas);                                        (2)
}

Note

For code files of this section refer to chapter 7educ_memory_gamespiralss01 in the code bundle.

As we did in Chapter 5, Handling the DOM in a New Way, we'll draw a board on a canvas element. So, we need a reference that is given in line (1). The Board view is represented in code as its own Board class in the board.dart file. Since everything happens on this board, we construct its object with canvas as argument (line (2)). Our game board is periodically drawn as a rectangle in line (4) by using the animationFrame method from the Window class in line (3):

part of memory;

class Board {
  // The board is drawn every INTERVAL in ms.
  static const int INTERVAL = 8;

  CanvasElement canvas;
  CanvasRenderingContext2D context;
  num width, height;

  Board(this.canvas) {
    context = canvas.getContext('2d'),
    width = canvas.width;
    height = canvas.height;
    // Draw every INTERVAL in ms.
    window.animationFrame.then(gameLoop);                     (3)
  }

  void gameLoop(num delta) {
    draw();
    window.animationFrame.then(gameLoop);
  }

  void draw() {
    clear();
    border();
  }

  void clear() {
    context.clearRect(0, 0, width, height);
  }

  void border() {
    context..rect(0, 0, width, height)..stroke();             (4)
  }
}

And this is our first result:

Spiral 1 – drawing the board

The game board

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.85.135