aboutsummaryrefslogtreecommitdiff
path: root/src/Tile/Tile.ts
blob: 2e6f2ba8707cfe106690a3eacb670c9f0375dda8 (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
import _ from 'lodash';

export enum Direction {
  North,
  East,
  South,
  West
}
export interface Attachment {
  attachTo: Tile;
  edge: Direction;
  tile: Tile;
  orientation: number;
}

export default class Tile {
  center: string;
  private _edges: string;
  shield?: boolean;

  private _orientation: number; // Clockwise rotation of a tile
  position: {
    x: number;
    y: number;
  }

  public constructor(
    center: string,
    edges: string,
    shield = false,
    position = { x: 0, y: 0 },
    orientation = 0
  ) {
    this.center = center;
    this._edges = edges;
    this.shield = shield;
    this.position = position;
    this.orientation = orientation;
  }

  public set orientation(orientation) {
    this._orientation = ((orientation % 4) + 4) % 4;
  }

  public get orientation() {
    return this._orientation;
  }

  public get edges() {
    return _.repeat(this._edges, 2).slice(4 - this.orientation, 8 - this.orientation);
  }

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

  getAttachments(tile: Tile): Attachment[] {
    return _.flatten(_.map(this.edges, (feature, edge) => {
      const oppositeEdge = (edge + 2) % 4;

      return _
        .map(tile.edges, (candidate, index) => candidate === feature ? index : -1)
        .filter(index => index !== -1)
        .map(index => ({
          edge,
          orientation: (((oppositeEdge - index) % 4) + 4) % 4,
          attachTo: this,
          tile,
        }));
    }));
  }
}