battle-city-js/src/Tanks/aiTankManager.js
2021-06-05 18:07:51 +02:00

94 lines
2.3 KiB
JavaScript

import { Constants } from "../constants";
import { CollisionManager } from "../GameLogic/collisionManager";
import { AITank } from "./aiTank"
export class AITankManager {
/**
*
* @param {CollisionManager} collisionManager
*/
constructor(collisionManager) {
this.maxTanks = Constants.MAX_ACTIVE_TANKS_ON_LEVEL.getValue();
this._count = null;
this._collision = collisionManager;
this._canSpawn = false;
this._activeTanks = [];
this._lastSpawn = 0;
}
drawAllTanks(tileset, ctx) {
for (let tank of this._activeTanks) {
tank.move(null);
tank.shot();
tank.draw(tileset, ctx);
}
this.tick();
}
tick() {
this.destroyKilledTanks();
if (this.checkIfCanSpawn()){
this._count--;
let tank = this.spawn();
this._collision.addNewAITank(tank);
}
if (this._activeTanks.length >= this.maxTanks)
this._canSpawn = false;
}
destroyKilledTanks() {
this._activeTanks.filter((e) => e.canBeErased()).forEach((e) => this.destroy(e));
}
destroy(tank) {
this._activeTanks = this._activeTanks.filter(t => tank.x != t.x || tank.y != t.y);
this._collision.deleteFromAITank(tank);
this._canSpawn = true;
}
setCount(count) {
this._count = count;
this._canSpawn = true;
}
checkIfCanSpawn() {
return this._canSpawn && this._count != 0;
}
isAllTanksDied() {
return this._count == 0 && this._activeTanks.length == 0;
}
getCount() {
return this._count;
}
getAllActiveTanks() {
return this._activeTanks;
}
spawn() {
const map = this._collision._map;
const tilesize = Constants.TILE_SIZE.getValue();
let tank = new AITank(200, 0, 0, this._collision);
for (let x = tilesize*this._activeTanks.length; x < tilesize*map.width; x+=tilesize) {
tank.x = x;
if (!this._collision.checkCollisionForTank(x, x + tilesize-1, 0, tilesize-1, tank) && this._lastSpawn != x) {
this._activeTanks.push(tank);
this._lastSpawn = x;
return tank;
}
}
return null;
}
}