Monday, 26 October 2015

Collectibles - Simplegamelib Part Nine

This is the ninth part in an ongoing series where we will look at the package I am currently writing called simplegamelib. Development is usually a little ahead of the current blog post. The projects homepage is located here. There's been some refactoring going on, documentation being updated and general bug fixing. I have also started a Space Invaders/Galaxian game using the library though too soon to share!

This time we are looking at picking up items. A Collectible is a specialisation of the Sprite class that stores some extra information - the points and health delta (collectible items can have both a positive and negative effect!). The collectibles are added to the game by the createCollectibles function and the picking up in the collectibleDemo function.

If the Player's health or points change, we need to broadcast this message in order to update the game display. The function updateScorePanel is called by the Player class when one of these properties changes.

import 'dart:html';
import 'package:simplegamelib/simplegamelib.dart';

Sprite player;
AudioBank sounds = new AudioBank();
Game game = new Game("My Game", '#surface');

void main() {
  sounds.load('test', 'sounds/coin.mp3');
  player = game.createSprite('images/ninjadude.png', 48, 48);

    ..player = new Player.withNotifications(updateScorePanel)
    ..player.sprite = player


    ..position = new Point(0, 30)
    ..movement = new Point(0, 0);

  game.customUpdate = collectibleDemo;

  print('starting game...');

void collectibleDemo() {
  List pickUps = game.collectiblesGroup.detectCollision(player);

  pickUps.forEach((Sprite pickup) {
    pickup.alive = false;

void createCollectibles() {
  Collectible heart = new Collectible.fromFilename('images/heart.png', 24, 24);
    ..position = new Point(100, 100)
    ..healthDelta = 15;


  Collectible diamond =
      new Collectible.fromFilename('images/diamond.png', 24, 24);
    ..position = new Point(175, 100)
    ..scoreDelta = 1000;


void updateScorePanel(Player p1) {
  DivElement statusPanel = querySelector("#gameStatus");
  statusPanel.innerHtml =
      "Health : ${}      Score : ${p1.score}";

Click here to see it in action. Use the cursor keys to pick up the objects.

Next time, we will look at Sprite's being hit by projectiles and expiring. Yikes!