aboutsummaryrefslogtreecommitdiff
path: root/src/Tile/Tile.ts
blob: 4eee263e2629331ccc8799bcf20f1b2384b007e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import _ from 'lodash';
import Debug, { Debugger } from 'debug';

const debug = Debug('cell');

export enum Direction {
  North,
  East,
  South,
  West
}

export enum Feature {
  Empty = " ",
  Road = "R",
  Town = "T",
  River = "I",
  Church = "C",
}

export interface Attachment {
  attachTo: Tile;
  side: Direction;
  cell: Tile;
  rotation: number; // Clockwise rotation of a cell
}


export default class Tile {
  center: Feature;
  private sides: [Feature, Feature, Feature, Feature];
  neighbors: [Tile, Tile, Tile, Tile];
  private orientation: number // amount of 90-degree counter-clockwise rotations from original orientation
  shield?: boolean;

  debug: Debugger;

  public constructor(center: Feature, sides: [Feature, Feature, Feature, Feature], orientation = 0, shield = false) {
    this.center = center;
    this.sides = sides;
    this.shield = shield;
    this.orientation = orientation;
  }

  print() {
    console.log( ` ${this.getSide(Direction.North)} \n${this.getSide(Direction.West)}${this.center}${this.getSide(Direction.East)}\n ${this.getSide(Direction.South)} `);
  }

  getSide(direction: Direction) {
    return this.sides[(((this.orientation + direction) % 4) + 4) % 4];
  }

  rotate(rotation = 1) {
    debug(`Rotating ${rotation} clockwise`)
    this.orientation = this.orientation - rotation;
  }

  getAttachments(cell: Tile) {
    return _.flatten([0, 1, 2, 3].map(side => {
      const item = this.getSide(side);
      return [0, 1, 2, 3]
        .filter(rotation => cell.getSide(side - rotation + 2) === item)
        .map(rotation => ({
          cell,
          rotation,
          side,
          attachTo: this as Tile
        }))
    }));
  }

  attach(cell: Tile, side: Direction) {
    if (this.neighbors[side]) throw new Error('There is something already attached to this side!');
    this.neighbors[side] = cell;
  }
}