class SpaceInvadersGame { constructor(ctx) { this.new_game(); this.ctx = ctx } new_game() { this.width = 600; this.height = 600; this.enemies = []; for(let i = 75; i < 550 ; i += 50) { for( let j = 75; j < 250; j+= 50) { this.enemies.push({x: i, y:j}); } } this.spaceship = {x:300, y: 600}; this.spanceship_direction = 0; this.enemies_x_position = 5; this.enemies_move_orientation = 1; this.game_started = false; } check_game_end() { for (let enemy of this.enemies) { if (enemy.y > this.spaceship.y - 27 ) { return true; } } return false; } tick() { if (this.game_started) { if(this.check_game_end()) { alert("You lose"); this.new_game(); } // Move the spaceship this.spaceship.x += this.spanceship_direction * 5; this.spanceship_direction = 0; // move the enemies this.enemies_x_position += this.enemies_move_orientation; let offset_x = this.enemies_move_orientation * 10; let offset_y = 0; if (this.enemies_x_position === 0) { this.enemies_move_orientation = 1; offset_y = 20; } else if (this.enemies_x_position === 10) { this.enemies_move_orientation = -1; offset_y = 20; } for (let enemy of this.enemies) { enemy.x += offset_x; enemy.y += offset_y; } } } draw() { this.ctx.clearRect(0, 0, this.width, this.height); this.ctx.fillStyle = "black"; this.ctx.strokeStyle = "black 2px solid"; this.ctx.fillRect(0, 0, this.width, this.height); this.ctx.fillStyle = "red"; this.ctx.strokeStyle = "red 2px solid"; for (let enemy of this.enemies) { this.ctx.fillRect(enemy.x-12, enemy.y-12, 25, 15); } this.ctx.fillStyle = "blue"; this.ctx.strokeStyle = "blue 2px solid"; this.ctx.fillRect(this.spaceship.x - 25, this.spaceship.y -15, 50, 15) } keypress(event) { this.spanceship_direction = { 37: -1, // Left 39: 1, // Right }[event.keyCode] || 0; this.game_started = { 13: true, 27: true }[event.keyCode] ? !this.game_started: this.game_started; } }