HTML 5 Game Development - Tutorial step 3

In this step we will first clean up a bit the code; I've moved all the "drawing" function to drawUtil.dart. I've changed nothing at all, just copy and paste so let's skip that.

Let's point to step3 game

import 'dart_03/game.dart';

void main() {
  //launch the game
  HTML5Game game = new HTML5Game();

Let's move the monster around, instead. We assume that the monster knows the previous position of the player and "how" fast is moving (not the final destination...too easy in that case).

This would be the most important part in a real game. The calibration of the difficulty and AI would make the difference between a good game and a bad one. In this case, since it's a demo, I don't care and we go for the easiest solution.

class Monster extends Character {
  followHero(int posX, int posY, int numberOfMovement) {
    if(numberOfMovement == 0) {
      //are you crazy?? run!! If the Player stand still the Monster will move notheless
      numberOfMovement = 1;
    double angleToTarget = atan2(posY - y, posX - x); 
    x += numberOfMovement*(cos(angleToTarget).round());
    y += numberOfMovement*(sin(angleToTarget).round());
    print("moving monster to :(${x.toString()},${y.toString()})");

Ok, now we have the monster AI. Let's call that and decrement the monster time to live a little every loop

  update() {
    //the monster should try to follow the hero
    m.followHero(p.x, p.y, lastComands.length);
    //it will die eventually

Finally let's modify the main loop to print the win/lose messages or continue the game
   * Game loop.
   * Each loop:
   * 1) the game will calculate the new properties for the characters of the game (position, ammo, health etc)
   * 2) draw the update value
  mainGame() {
    //still alive, keep playing
    if(m.ttl > 0 && > 0) {
    //either you won or lose
    else if(m.ttl <= 0) {
    else if( <= 0) {

Let's try it out. Go around for a while and you'll see the Win message. Demo

We're still missing the monster-touching-hero-do-something part. Let's do it in step4

Theme Sponsored by: Roller Blinds, Cyprus Holidays, Walk in Baths