Skip to content

Commit c27844b

Browse files
html.game
0 parents  commit c27844b

File tree

3 files changed

+79
-0
lines changed

3 files changed

+79
-0
lines changed

game.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// Select Canvas and set up
2+
const canvas = document.getElementById('gameCanvas');
3+
const ctx = canvas.getContext('2d');
4+
5+
// Player properties
6+
const player = {
7+
x: 50,
8+
y: 50,
9+
width: 50,
10+
height: 50,
11+
color: 'blue',
12+
speed: 5,
13+
};
14+
15+
// Movement keys
16+
const keys = {};
17+
18+
// Event listeners for key presses
19+
window.addEventListener('keydown', (e) => {
20+
keys[e.key] = true;
21+
});
22+
window.addEventListener('keyup', (e) => {
23+
keys[e.key] = false;
24+
});
25+
26+
// Update game state
27+
function update() {
28+
if (keys['ArrowUp']) player.y -= player.speed;
29+
if (keys['ArrowDown']) player.y += player.speed;
30+
if (keys['ArrowLeft']) player.x -= player.speed;
31+
if (keys['ArrowRight']) player.x += player.speed;
32+
33+
// Keep player within bounds
34+
player.x = Math.max(0, Math.min(canvas.width - player.width, player.x));
35+
player.y = Math.max(0, Math.min(canvas.height - player.height, player.y));
36+
}
37+
38+
// Draw everything
39+
function draw() {
40+
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear canvas
41+
ctx.fillStyle = player.color;
42+
ctx.fillRect(player.x, player.y, player.width, player.height); // Draw player
43+
}
44+
45+
// Game loop
46+
function gameLoop() {
47+
update();
48+
draw();
49+
requestAnimationFrame(gameLoop); // Loop the game
50+
}
51+
52+
// Start the game
53+
gameLoop();

index.html

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6+
<title>Simple HTML Game</title>
7+
<link rel="stylesheet" href="style.css">
8+
</head>
9+
<body>
10+
<canvas id="gameCanvas" width="800" height="600"></canvas>
11+
<script src="game.js"></script>
12+
</body>
13+
</html>

style.css

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
body {
2+
display: flex;
3+
justify-content: center;
4+
align-items: center;
5+
height: 100vh;
6+
margin: 0;
7+
background-color: #f0f0f0;
8+
}
9+
10+
canvas {
11+
border: 2px solid #000;
12+
background-color: #fff;
13+
}

0 commit comments

Comments
 (0)