0% found this document useful (0 votes)
6 views2 pages

!DOCTYPE HTML - TXT Gun Game

The document is an HTML file for a simple gun game featuring a player and a bullet. It includes a canvas element where the player can shoot bullets using the spacebar. The game updates the position of the bullet and redraws the player and bullet on each frame.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

!DOCTYPE HTML - TXT Gun Game

The document is an HTML file for a simple gun game featuring a player and a bullet. It includes a canvas element where the player can shoot bullets using the spacebar. The game updates the position of the bullet and redraws the player and bullet on each frame.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

<!

DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gun Game</title>
<style>
canvas {
border: 1px solid black;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="400"></canvas>
<script>
// Define the canvas and context
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// Player object
const player = {
x: 50,
y: canvas.height / 2,
width: 50,
height: 30,
color: 'blue',
speed: 5
};

// Bullet object
const bullet = {
x: 0,
y: 0,
width: 10,
height: 5,
speed: 10,
color: 'red',
fire: false
};

// Event listener for key presses


document.addEventListener('keydown', function(event) {
if(event.code === 'Space') {
bullet.fire = true;
bullet.x = player.x + player.width;
bullet.y = player.y + player.height / 2;
}
});

// Update function
function update() {
// Move bullet
if(bullet.fire) {
bullet.x += bullet.speed;
if(bullet.x > canvas.width) {
bullet.fire = false;
}
}

// Draw everything
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPlayer();
drawBullet();

// Request new frame


requestAnimationFrame(update);
}

// Draw player function


function drawPlayer() {
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.width, player.height);
}

// Draw bullet function


function drawBullet() {
if(bullet.fire) {
ctx.fillStyle = bullet.color;
ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
}
}

// Start the game


update();
</script>
</body>
</html>.html

You might also like