Basic PC game code
Basic PC game code
https://build-magic-weaver.lovable.app
code:
// HTML: <canvas id="game" width="400" height="600"></canvas>
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
let car = { x: 180, y: 500, width: 40, height: 70 };
let obstacles = [];
let gameOver = false;
// Track mouse movement
canvas.addEventListener('mousemove', (e) => {
const rect = canvas.getBoundingClientRect();
car.x = e.clientX - rect.left - car.width / 2;
});
// Create obstacles
function spawnObstacle() {
obstacles.push({ x: Math.random() * 360, y: 0, width: 40, height: 40 });
}
// Game loop
function update() {
if (gameOver) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw car
ctx.fillStyle = 'blue';
ctx.fillRect(car.x, car.y, car.width, car.height);
// Move and draw obstacles
ctx.fillStyle = 'red';
for (let i = 0; i < obstacles.length; i++) {
obstacles[i].y += 5;
ctx.fillRect(obstacles[i].x, obstacles[i].y, obstacles[i].width, obstacles[i].height);
// Check collision
if (
car.x < obstacles[i].x + obstacles[i].width &&
car.x + car.width > obstacles[i].x &&
car.y < obstacles[i].y + obstacles[i].height &&
car.y + car.height > obstacles[i].y
) {
gameOver = true;
alert('💥 Game Over! Reload to play again.');
}
}
requestAnimationFrame(update);
}
// Spawn obstacles every second
setInterval(spawnObstacle, 1000);
update();
-------------------------
Explanation:
Absolutely! Let’s go step by step through this code so you fully understand how it works. I’ll break it down carefully.
1️⃣ HTML Canvas Element
<canvas id="game" width="400" height="600"></canvas>
- This creates a drawing area in your webpage called a canvas.
-
id="game"→ This is the name we use to reference it in JavaScript. -
width="400" height="600"→ Sets the size of the canvas: 400 pixels wide and 600 pixels tall. - Think of it like a piece of paper where we will draw the car and obstacles.
2️⃣ Getting the Canvas and Context
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
-
document.getElementById('game')→ Selects the canvas element from the HTML. -
canvas.getContext('2d')→ Gives us a 2D drawing context, calledctx.- This is what we use to draw rectangles, circles, text, and images on the canvas.
3️⃣ Defining the Car and Obstacles
let car = { x: 180, y: 500, width: 40, height: 70 };
let obstacles = [];
let gameOver = false;
-
car→ an object representing the player’s car:-
x→ horizontal position (left side). -
y→ vertical position (top). -
widthandheight→ size of the car.
-
-
obstacles→ an array that will store all obstacles currently on the screen. -
gameOver→ a flag that stops the game if the car hits an obstacle.
4️⃣ Tracking Mouse Movement
canvas.addEventListener('mousemove', (e) => {
const rect = canvas.getBoundingClientRect();
car.x = e.clientX - rect.left - car.width / 2;
});
-
canvas.addEventListener('mousemove', ...)→ Runs code whenever the mouse moves over the canvas. -
rect = canvas.getBoundingClientRect()→ Gets the canvas position relative to the page. -
e.clientX→ The horizontal position of the mouse. -
car.x = e.clientX - rect.left - car.width / 2→ Moves the car horizontally to match the mouse, centering it under the cursor.
5️⃣ Creating Obstacles
function spawnObstacle() {
obstacles.push({ x: Math.random() * 360, y: 0, width: 40, height: 40 });
}
-
Math.random() * 360→ Generates a random horizontal position for the obstacle (360 = canvas width minus obstacle width). -
y: 0→ Starts at the top of the canvas. -
widthandheight→ Size of the obstacle. -
obstacles.push(...)→ Adds the new obstacle to theobstaclesarray.
This makes obstacles appear at random positions at the top of the screen.
6️⃣ Game Loop
function update() {
if (gameOver) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
-
function update()→ This is the main game loop that runs over and over. -
if (gameOver) return;→ Stops the game if the car crashed. -
ctx.clearRect(0, 0, canvas.width, canvas.height)→ Clears the canvas each frame so we can redraw everything.
7️⃣ Drawing the Car
ctx.fillStyle = 'blue';
ctx.fillRect(car.x, car.y, car.width, car.height);
-
ctx.fillStyle = 'blue'→ Sets the color for the next shape. -
ctx.fillRect(...)→ Draws a rectangle at the car’s position.
8️⃣ Moving and Drawing Obstacles
ctx.fillStyle = 'red';
for (let i = 0; i < obstacles.length; i++) {
obstacles[i].y += 5;
ctx.fillRect(obstacles[i].x, obstacles[i].y, obstacles[i].width, obstacles[i].height);
-
ctx.fillStyle = 'red'→ Obstacles are red. -
Loop through each obstacle:
-
obstacles[i].y += 5→ Moves the obstacle downwards 5 pixels per frame. -
ctx.fillRect(...)→ Draws the obstacle on the canvas.
-
9️⃣ Collision Detection
if (
car.x < obstacles[i].x + obstacles[i].width &&
car.x + car.width > obstacles[i].x &&
car.y < obstacles[i].y + obstacles[i].height &&
car.y + car.height > obstacles[i].y
) {
gameOver = true;
alert('💥 Game Over! Reload to play again.');
}
- This checks if the car rectangle overlaps with any obstacle rectangle.
-
If so:
-
gameOver = true→ stops the game loop. - Shows a Game Over alert.
-
10️⃣ Repeat the Loop
requestAnimationFrame(update);
-
requestAnimationFrame(update)→ Tells the browser: “Call theupdatefunction again before the next screen repaint.” - This makes the game smooth and continuous.
11️⃣ Spawning Obstacles Every Second
setInterval(spawnObstacle, 1000);
update();
-
setInterval(spawnObstacle, 1000)→ CallsspawnObstacle()every 1000 milliseconds (1 second). -
update();→ Starts the game loop immediately.
✅ Summary of Flow
- Car is drawn and follows the mouse.
- Obstacles are randomly generated at the top.
- Obstacles move downward each frame.
- Collision is checked: if car hits → Game over.
-
The loop repeats every frame using
requestAnimationFrame.

Comments
Post a Comment