A Tiny RPG

by Sam Fereday

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/2.6.2/custom/phaser-arcade-physics.min.js"></script>
<div id="phaser-example"></div>

JavaScript

/*
- Rock paper-scissors battle system
- Walk around, find the key to unlock the door
- Convert to es6

Will need:
1 Hero
1 Villain
1 Tiny inventory
1 Map

*/

const identity = x => x;

const compose = (...funcs) => {
  if (funcs.length === 0) {
    return identity
  }

  if (funcs.length === 1) {
    return funcs[0]
  }

  return funcs.reduce((a, b) => (...args) => a(b(...args)))
}

const TYPES = {
  NPC: 0
};

/// Helpers
let mix = (superclass) => new MixinBuilder(superclass);

class MixinBuilder {
  constructor(superclass) {
    this.superclass = superclass;
  }

  with(...mixins) {
    return mixins.reduce((c, mixin) => mixin(c), this.superclass);
  }
}

/// Components (class-likes)
let UserControlled = (superclass) => class extends superclass {

  initCursors() {

    this.cursors = this.game.input.keyboard.createCursorKeys();

  }

  initInteractionKeys(cb) {

    this.interactionKey = this.game.input.keyboard.addKey(Phaser.Keyboard.E);

    if (cb)
      this.interactionKey.onDown.add(cb, this);

  }

  inputDirection() {

    return {
      x: this.cursors.left.isDown || this.cursors.right.isDown ? (this.cursors.left.isDown ? -1 : 1) : 0,
      y: this.cursors.up.isDown || this.cursors.down.isDown ? (this.cursors.up.isDown ? -1 : 1) : 0
    }

  }

};

/// Entities
class Hero extends mix(Phaser.Sprite).with(UserControlled) {

  constructor(game, x, y, name) {

    // Phaser requires all of these to happen
    super(game, x, y, name);

    game.add.existing(this);
    game.physics.arcade.enable(this);

    // Custom stats and things
    this.stats = {
      hp: 4,
      maxHp: 4
    }

    this.config = {
      movementSpeed: 200
    }

    // Component initializers
    this.initCursors(game);
    this.initInteractionKeys(this.onInteractKey);

  }

  update() {

    // As pure as I can think of right now.
    let dir = this.inputDirection();

    this.body.velocity.x = dir.x * this.config.movementSpeed;
    this.body.velocity.y = dir.y *...