Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Space Invaders Game</title>
- <style>
- body {
- margin: 0;
- overflow: hidden;
- font-family: Arial, sans-serif;
- }
- canvas {
- display: block;
- }
- </style>
- </head>
- <body>
- <canvas id="gameCanvas" width="800" height="600"></canvas>
- <script>
- const canvas = document.getElementById("gameCanvas");
- const ctx = canvas.getContext("2d");
- // Player spaceship
- const player = {
- x: canvas.width / 2,
- y: canvas.height - 50,
- width: 50,
- height: 50,
- color: "#00F"
- };
- // Falling objects
- const objects = [];
- function drawPlayer() {
- ctx.fillStyle = player.color;
- ctx.fillRect(player.x - player.width / 2, player.y - player.height / 2, player.width, player.height);
- }
- function drawObjects() {
- for (const object of objects) {
- ctx.fillStyle = object.color;
- ctx.fillRect(object.x - object.width / 2, object.y - object.height / 2, object.width, object.height);
- }
- }
- function update() {
- // Move player with arrow keys
- window.addEventListener('keydown', function(e) {
- if (e.key === 'ArrowLeft' && player.x > player.width / 2) {
- player.x -= 10;
- } else if (e.key === 'ArrowRight' && player.x < canvas.width - player.width / 2) {
- player.x += 10;
- }
- });
- // Move falling objects
- for (const object of objects) {
- object.y += 5;
- // Check collision with player
- if (
- object.x + object.width / 2 > player.x - player.width / 2 &&
- object.x - object.width / 2 < player.x + player.width / 2 &&
- object.y + object.height / 2 > player.y - player.height / 2 &&
- object.y - object.height / 2 < player.y + player.height / 2
- ) {
- alert("Game Over! You got hit!");
- document.location.reload();
- }
- }
- // Remove objects that are out of the canvas
- objects.forEach((object, index) => {
- if (object.y > canvas.height) {
- objects.splice(index, 1);
- }
- });
- // Add a new falling object randomly
- if (Math.random() < 0.02) {
- const newObject = {
- x: Math.random() * canvas.width,
- y: 0,
- width: 30,
- height: 30,
- color: "#F00"
- };
- objects.push(newObject);
- }
- }
- function draw() {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- drawPlayer();
- drawObjects();
- }
- function gameLoop() {
- update();
- draw();
- requestAnimationFrame(gameLoop);
- }
- gameLoop();
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement