require("Paddle"); require("Ball"); class Game { engine = null; paddles = {}; gameActive = true; constructor() { this.paddles['left'] = new Paddle('left'); this.paddles['right'] = new Paddle('right'); this.ball = new Ball(); } init(engine) { this.engine = engine; this.rounds = 11; for(let index in this.paddles) { this.paddles[index].init(this); } this.ball.init(this); this.gameActive = true; this.winner = ""; this.finalScore = 0; } update(delta) { if(this.ball.isDead() && this.rounds <= 0) { this.gameActive = false; this.finalScore = 0; this.winner = ""; for(let index in this.paddles) { let paddleScore = this.paddles[index].getScore(); if(paddleScore > this.finalScore) { this.finalScore = paddleScore; this.winner = index; } } return; } for(let index in this.paddles) { this.paddles[index].update(delta); } this.ball.update(delta); if(this.ball.isDead()) { this.rounds--; if(this.rounds > 0) { this.ball.init(this); } } } draw(context) { if(!this.gameActive) { context.fillStyle = "#000000"; context.beginPath(); context.rect(0, 0, this.getWidth(), this.getHeight()); context.fill(); context.fillStyle = "#FFFFFF"; context.textAlign = "center"; context.font = "18px Arial"; context.fillText("winner:", this.getWidth() / 2, this.getHeight() * 0.2); context.font = "30px Arial"; context.fillText(this.winner, this.getWidth() / 2, this.getHeight() * 0.4); context.font = "48px Arial"; context.fillText(this.finalScore, this.getWidth() / 2, this.getHeight() * 0.7); return; } context.fillStyle = "#000000"; context.textAlign = "center"; context.font = "14px Arial"; for(let index in this.paddles) { context.fillText(this.paddles[index].getScore(), this.paddles[index].getPosition().x, 10); this.paddles[index].draw(context); } this.ball.draw(context); } collideSide(collisionBox) { let collisionSide = ""; for(let side in collisionBox) { let collider = collisionBox[side]; if(side == "top" || side == "left") { if(collider < 0) { return side; } } if(side == "bottom" && collider > this.getHeight()) { return side; } if(side == "right" && collider > this.getWidth()) { return side; } } } getWidth() { return this.engine.viewport.w; } getHeight() { return this.engine.viewport.h; } getBallPosition() { return {x: this.ball.position.x, y: this.ball.position.y}; } getPaddle(side) { return this.paddles[side]; } }