import { Constants } from "../constants"; import { DirectionEnum } from "./directionEnum"; class Shot { constructor(shotManager, direction, x, y) { this.image = ShotVisualElement.createShot(direction); this.shotManager = shotManager; this.direction = direction; this.x = x; this.y = y; this.speed = Constants.SHOT_SPEED.getValue(); this.size = Constants.SHOT_SIZE.getValue(); } move() { switch (this.direction) { case DirectionEnum.Up: if (!this.shotManager.checkCollision(this.x, this.x + this.size, this.y - this.speed, this.y + this.size - this.speed)) this.y -= this.speed; else this.shotManager.destroyShot(); break; case DirectionEnum.Left: if (!this.shotManager.checkCollision(this.x - this.speed, this.x + this.size - this.speed, this.y, this.y + this.size)) this.x -= this.speed; else this.shotManager.destroyShot(); break; case DirectionEnum.Right: if (!this.shotManager.checkCollision(this.x + this.speed, this.x + this.size + this.speed, this.y, this.y + this.size)) this.x += this.speed; else this.shotManager.destroyShot(); break; case DirectionEnum.Down: if (!this.shotManager.checkCollision(this.x, this.x + this.size, this.y + this.speed, this.y + this.size + this.speed)) this.y += this.speed; else this.shotManager.destroyShot(); break; } } } export class ShotManager { constructor(collisionManager, tank) { this.collisionManager = collisionManager; this.tank = tank; this.shot = null; } tryShot(direction, x, y) { if (!this.shot) { this.shot = new Shot(this, direction, x, y); } } checkCollision(minX, maxX, minY, maxY) { return this.collisionManager.checkCollisionForShots(minX, maxX, minY, maxY, this.shot.direction, this.tank); } destroyShot() { this.shot = null; } draw(ctx) { if (this.shot) this.shot.move(); if (this.shot) ctx.drawImage(this.shot.image, this.shot.x, this.shot.y); } } class ShotVisualElement { static createShot(direction) { let canvas = document.createElement("canvas"); canvas.width = 4; canvas.height = 4; let ctx = canvas.getContext("2d"); ctx.fillStyle = "BLACK"; ctx.fillRect(0, 0, 4, 4); ctx.fillStyle = "GREY"; switch (direction) { case DirectionEnum.Up: ctx.fillRect(0, 1, 4, 3); ctx.fillRect(1, 0, 2, 1); break; case DirectionEnum.Left: ctx.fillRect(1, 0, 3, 4); ctx.fillRect(0, 1, 1, 2); break; case DirectionEnum.Down: ctx.fillRect(0, 0, 4, 3); ctx.fillRect(1, 3, 2, 1); break; case DirectionEnum.Right: ctx.fillRect(0, 0, 3, 4); ctx.fillRect(3, 1, 1, 2); break; } let img = new Image(); img.src = canvas.toDataURL("image/png"); return img; } }