Skip to content

Commit

Permalink
Allow hexes to store content
Browse files Browse the repository at this point in the history
  • Loading branch information
butzopower committed Jan 1, 2022
1 parent 6a50a38 commit 545512a
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 9 deletions.
42 changes: 42 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"@types/chai": "^4.3.0",
"@types/mocha": "^9.0.0",
"chai": "^4.3.4",
"fast-check": "^2.20.0",
"mocha": "^9.1.3",
"ts-node": "^10.4.0",
"typescript": "^4.5.4"
Expand Down
17 changes: 9 additions & 8 deletions src/hexgrid.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,34 @@
export class Hex {
private readonly parent: HexGrid;
export class Hex<T = void> {
private readonly parent: HexGrid<T>;
private readonly x: number;
private readonly y: number;
content: T | undefined;

constructor(parent: HexGrid, x: number, y: number) {
constructor(parent: HexGrid<T>, x: number, y: number) {
this.parent = parent;
this.x = x;
this.y = y;
}

get neighbors(): Hex[] {
get neighbors(): Hex<T>[] {
return this.parent.neighborsOf(this.x, this.y);
}
}

export class HexGrid {
private readonly hexArray: Hex[][]
export class HexGrid<T = void> {
private readonly hexArray: Hex<T>[][]

constructor(width: number, height: number) {
this.hexArray = Array.from(new Array(height))
.map((_, y) => Array.from(new Array(width))
.map((_, x) => new Hex(this, x, y)));
}

at(x: number, y: number): Hex {
at(x: number, y: number): Hex<T> {
return this.hexArray[y][x];
}

neighborsOf(x: number, y: number): Hex[] {
neighborsOf(x: number, y: number): Hex<T>[] {
const above = y - 1
const below = y + 1
const left = x - 1;
Expand Down
15 changes: 14 additions & 1 deletion tests/hexgrid.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { beforeEach, describe, it } from "mocha";
import { expect } from "chai";
import * as fc from "fast-check";
import { HexGrid } from "../src/hexgrid";

describe('a hex grid', () => {
Expand Down Expand Up @@ -149,4 +150,16 @@ describe('a hex grid', () => {
]);
});
});
});
});

describe('a hex', () => {
it('can store content', () => {
fc.assert(fc.property(fc.anything(), thing => {
const grid = new HexGrid<unknown>(1, 1);
const hex = grid.at(0, 0);

hex.content = thing;
expect(grid.at(0, 0).content).to.eql(thing);
}));
});
})

0 comments on commit 545512a

Please sign in to comment.