"use strict"; var canvasWidth = 1280; var canvasHeight = 650; var c = undefined var ctx = undefined var game = { level: 1, speed: 1, gameOver: false, frames: 0, timer: 0, } var keys = { up: false, down: false, left: false, right: false, fire: false } var playerShipImg = new Image(); playerShipImg.src = 'img/pixelShip.png' window.onload = function () { init() } function init() { c = document.getElementById("canvas"); ctx = c.getContext('2d'); document.addEventListener('keydown', keyDownPressed, false); document.addEventListener('keyup', keyUpPressed, false); gameLoop(); } function keyDownPressed(e) { if (e.keyCode == 87) { keys.up = true; } else if (e.keyCode == 83) { keys.down = true } if (e.keyCode == 65) { keys.left = true; } if (e.keyCode == 68) { keys.right = true; } if (e.keyCode == 32) { keys.fire = true; alert("fire"); } } function keyUpPressed(e) { if (e.keyCode == 87) { keys.up = false; } else if (e.keyCode == 83) { keys.down = false; } if (e.keyCode == 65) { keys.left = false; } if (e.keyCode == 68) { keys.right = false; } if (e.keyCode == 32) { keys.fire = false; } } function clearGame() { ctx.clearRect(0, 0, canvasWidth, canvasHeight); } function updateGame() { player1.update(); game.frames++; } function drawGame(){ player1.draw(); drawNewText('Score: ' +player1.score, 30, 610, 'white'); drawNewText('Player Lives: ' +player1.lives, 1100, 610, 'white'); } function gameLoop(timestamp){ clearGame(); updateGame(); drawGame(); window.requestAnimationFrame(gameLoop); } class PlayerObject{ constructor(x, y){ this.x = x; this.y = y; this.width = 170; this.height = 105; this.image = playerShipImg; this.speed = 8; this.lives = 3; this.score = 0; this.health = 100; } draw(){ ctx.save(); ctx.drawImage(this.image, this.x, this.y, this.width, this.height); ctx.restore(); } update(){ if (keys.up) { if(this.y > 0){ this.y -= this.speed; } } else if (keys.down) { if (this.x < canvasWidth - this.width) { this.y += this.speed; } } if (keys.right) { if (this.x < canvasWidth - this.width) { this.x += this.speed; } } if (keys.left) { if (this.x > 10) { this.x -= this.speed; } } } } let player1 = new PlayerObject(100, 100); function drawNewText(txt, x, y, color){ ctx.font = "20px Arial"; ctx.fillStyle = color; ctx.fillText(txt, x, y); }