Background Lesson
Lesson on how the background.md file works
🎮 Scrolling Background Lesson (Beginner-Friendly)
Welcome! This notebook will teach you how to create a scrolling background for a game step by step.
At the end of each step, you will answer a checkpoint question to test your understanding.
Step 1: Drawing the Background
Before we can make our background move, we need to understand how to draw images on the canvas.
In HTML games, this is done with the special method drawImage. This method lets us tell the computer which image to use, where to place it, and how big it should be.
The general format looks like this:
ctx.drawImage(image, x, y, width, height);
Checkpoint: Type the code to draw the background at the top-left corner of the canvas.
```python
# ⬇️ Type your answer below for Step 1
answer1 = "" # Example: "ctx.drawImage(background, 0, 0);"
# Checkpoint 1
correct1 = ["ctx.drawImage(background, 0, 0);"]
if answer1 in correct1:
print("✅ Correct! You drew the background.")
else:
print("❌ Try again.")
Step 2: Moving the Background
Now that we know how to draw the background, let’s make it move.
Movement in games happens by changing the position of objects a little bit each frame.
For our background, the important value is the x position.
- If we make the x position smaller each frame, the image will look like it’s sliding to the left.
- If we make the x position larger each frame, it will slide to the right.
This is how scrolling backgrounds are created — the position keeps changing, which makes the image look like it’s moving.
Here’s a simple example:
// each frame, shift the background 2 pixels left
backgroundX -= 2;
Checkpoint: Type the code to move the background left by 2 pixels.
```python
# ⬇️ Type your answer below for Step 2
answer2 = "" # Example: "backgroundX -= 2;"
# Checkpoint 2
correct2 = ["backgroundX -= 2;", "backgroundX=backgroundX-2;"]
if answer2 in correct2:
print("✅ Correct! The background now scrolls.")
else:
print("❌ Try again.")
Step 3: Resetting the Background
If we only move the background to the left, eventually the image will scroll all the way off the screen — and then the screen will just look blank.
To fix this, we need to make the background loop forever.
This means that when the first image moves off the screen, we reset its position so it starts over again.
That way, the player always sees a background, and it feels endless.
We can do this using an if statement:
if (backgroundX <= -canvas.width) backgroundX = 0;
Checkpoint: Type the code to reset the background when it goes off screen.
```python
# ⬇️ Type your answer below for Step 3
answer3 = "if (backgroundX <= -canvas.width) backgroundX = 0;" # Example: "if (backgroundX <= -canvas.width) backgroundX = 0;"
# Checkpoint 3
correct3 = ["if (backgroundX <= -canvas.width) backgroundX = 0;"]
if answer3 in correct3:
print("✅ Correct! The background loops forever 🚀")
else:
print("❌ Try again.")
✅ Correct! The background loops forever 🚀