130 lines
2.2 KiB
JavaScript
130 lines
2.2 KiB
JavaScript
"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
|
|
}
|
|
|
|
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 == 81) {
|
|
keys.up = true;
|
|
} else if (e.keyCode == 65) {
|
|
keys.down = true
|
|
}
|
|
|
|
if (e.keyCode == 79) {
|
|
keys.left = true;
|
|
}
|
|
|
|
if (e.keyCode == 80) {
|
|
keys.right = true;
|
|
}
|
|
|
|
if (e.keyCode == 32) {
|
|
keys.fire = true;
|
|
alert("fire");
|
|
}
|
|
}
|
|
|
|
|
|
|
|
function keyUpPressed(e) {
|
|
if (e.keyCode == 81) {
|
|
keys.up = false;
|
|
} else if (e.keyCode == 65) {
|
|
keys.down = false;
|
|
}
|
|
|
|
if (e.keyCode == 79) {
|
|
keys.left = false;
|
|
}
|
|
|
|
if (e.keyCode == 80) {
|
|
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();
|
|
}
|
|
|
|
function gameLoop(timestamp){
|
|
clearGame();
|
|
updateGame();
|
|
drawGame();
|
|
window.requestAnimationFrame(gameLoop);
|
|
}
|
|
|
|
class PlayerObject{
|
|
constructor(x,y){
|
|
this.x = x;
|
|
this.y = y;
|
|
this.width = 200;
|
|
this.height = 150;
|
|
this.color = 'blue';
|
|
this.speed = 10;
|
|
this.lives = 3;
|
|
this.score = 0;
|
|
this.health = 100;
|
|
}
|
|
draw(){
|
|
ctx.save();
|
|
ctx.fillStyle = this.color;
|
|
ctx.fillRect(this.x, this.y, this.width, this.height);
|
|
ctx.fill();
|
|
ctx.restore();
|
|
}
|
|
update(){
|
|
if(keys.up){
|
|
this.y -= this.speed;
|
|
}
|
|
|
|
else if (keys.down){
|
|
this.y += this.speed;
|
|
}
|
|
}
|
|
}
|
|
|
|
let player1 = new PlayerObject(100.100); |