Lösung für die Aufgabe 8 - Raketen-Spiel Code
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mein erstes Spiel!</title>
<style>
canvas {
background-color: black;
}
</style>
</head>
<body onload="startGame()">
<canvas id="canvas" width="720" height="480"></canvas>
<script src="game.js"></script>
</body>
</html>
game.js:
let KEY_SPACE = false;
let KEY_UP = false;
let KEY_DOWN = false;
let backgroundImage = new Image;
let canvas;
let ctx;
let rocket = {
x: 50,
y: 250,
width: 95,
heigth: 60,
src: "rocket.png"
};
let ufos = [];
let shots = [];
document.onkeydown = function(e) {
if (e.key == " ") {
KEY_SPACE = true;
}
if (e.key == "ArrowUp") {
KEY_UP = true;
}
if (e.key == "ArrowDown") {
KEY_DOWN = true;
}
}
document.onkeyup = function(e) {
if (e.key == " ") {
KEY_SPACE = false;
}
if (e.key == "ArrowUp") {
KEY_UP = false;
}
if (e.key == "ArrowDown") {
KEY_DOWN = false;
}
}
function startGame() {
loadImages();
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
setInterval(update, 1000 / 25);
setInterval(createUfos, 5000);
setInterval(checkForCollision, 1000/25);
setInterval(checkForShots, 1000 / 10);
draw();
}
function checkForShots() {
if (KEY_SPACE) {
let shot = {
x: rocket.x + 110,
y: rocket.y + 22,
width: 20,
heigth: 4,
src: 'laser.png',
img: new Image()
};
shot.img.src = shot.src;
shots.push(shot);
}
}
function checkForCollision() {
ufos.forEach(function(ufo) {
if (rocket.x + rocket.width > ufo.x &&
rocket.y + rocket.heigth > ufo.y &&
rocket.x < ufo.x &&
rocket.y < ufo.y + ufo.heigth
) {
rocket.img.src = 'boom.png';
ufos = [];
alert("GAME OVER!");
}
shots.forEach(function(shot) {
if (shot.x + shot.width > ufo.x &&
shot.y + shot.heigth > ufo.y &&
shot.x < ufo.x &&
shot.y < ufo.y + ufo.heigth
) {
ufo.hit = true;
ufo.img.src = 'boom.png';
setTimeout(() => {
ufos = ufos.filter(u => u != ufo);
}, 2000);
}
});
});
}
function createUfos() {
let ufo = {
x: 800,
y: Math.random() * 500,
width: 100,
heigth: 70,
src: "ufo.png",
img: new Image()
};
ufo.img.src = ufo.src;
ufos.push(ufo);
}
function draw() {
ctx.drawImage(backgroundImage, 0, 0, 720, 480);
ctx.drawImage(rocket.img, rocket.x, rocket.y, rocket.width, rocket.heigth);
ufos.forEach(function(ufo){
ctx.drawImage(ufo.img, ufo.x, ufo.y, ufo.width, ufo.heigth);
});
shots.forEach(function(shot) {
ctx.drawImage(shot.img, shot.x, shot.y, shot.width, shot.heigth);
});
requestAnimationFrame(draw);
}
function loadImages() {
backgroundImage.src = "space.png"
rocket.img = new Image;
rocket.img.src = rocket.src;
}
function update() {
if(KEY_UP) {
rocket.y = rocket.y - 4;
}
if(KEY_DOWN) {
rocket.y = rocket.y + 4;
}
ufos.forEach(function(ufo) {
if (!ufo.hit) {
ufo.x -= 5;
}
});
shots.forEach(function(shot) {
shot.x += 15;
});
}
Zuletzt geändert: Donnerstag, 25. Mai 2023, 14:32