antiyoy.js/Tile.js

104 lines
3.4 KiB
JavaScript
Raw Normal View History

2019-04-08 19:54:07 +00:00
class Tile {
constructor(game, element, x, y) {
this.game = game;
this.element = element;
this.pos = {x: x, y: y};
this.claimedBy = null;
this.object = null;
this.addClickListener();
}
addClickListener() {
this.element.addEventListener('click', () => this.clickHandler());
}
clickHandler() {
// Checks whether there is an object selected at the moment and if it belongs to the human player
if (!!this.game.selectedObject && this.game.selectedObject.civilization.player === player) {
// Checks whether this tile is a possible destination for the object based on the object type
if (this.game.selectedObject instanceof Warrior) {
this.game.selectedObject.move(this.pos.x, this.pos.y);
return;
}
if (this.game.selectedObject.type === 'new') {
const obj = this.game.selectedObject;
const allowMoveAfterCreation = this.claimedBy === obj.civilization && this.object === null;
const result = this.game[obj.function](this.pos.x, this.pos.y, obj.civilization, obj.class);
if (!result) {
this.game.deselectObject();
return;
}
if (!allowMoveAfterCreation) {
this.object.setNeedsAction(false);
}
} else {
this.object = this.game.selectedObject;
}
this.object.x = this.pos.x;
this.object.y = this.pos.y;
this.game.deselectObject();
this.object.update();
} else if(this.object instanceof Warrior) {
this.object.onClick();
}
this.game.selectCivilization(this.claimedBy);
}
getAdjacentTiles() {
const surroundings = [
[-1, 0],
[0, -1],
[0, 1],
[1, 0],
];
if (this.pos.y % 2 === 0) {
surroundings.push([-1, -1], [-1, 1]);
} else {
surroundings.push([1, -1], [1, 1]);
}
const adjacentTiles = [];
surroundings.forEach(modification => {
const x = this.pos.x + modification[0];
const y = this.pos.y + modification[1];
if (x >= 0 && x < this.game.fieldSize.x && y >= 0 && y < this.game.fieldSize.y)
adjacentTiles.push(this.game.field[x][y]);
});
return adjacentTiles;
}
getAdjacentCivilizationTiles(civilization, excluded = []) {
const surroundings = this.getAdjacentTiles().filter(tile => !excluded.includes(tile));
const matches = [];
surroundings.forEach(tile => {
if(!!tile.claimedBy && tile.claimedBy.uuid === civilization.uuid) {
matches.push(tile);
matches.push(...tile.getAdjacentCivilizationTiles(civilization, [this, ...surroundings, ...matches, ...excluded]));
}
});
return matches;
}
getAvailableAdjacentTiles() {
return this.getAdjacentTiles().filter(tile => !tile.object);
}
overtake(civilization) {
const prevColor = this.getColor();
this.claimedBy = civilization;
this.element.childNodes[0].classList.remove(prevColor);
this.element.childNodes[0].classList.add(this.getColor());
}
getColor() {
return this.claimedBy != null ? this.claimedBy.color : 'grey';
}
}