Lesson 4: Enhancing Game Play and Performance 🎮🚀
Objective 🧐🗿
Take your game to the next level by adding a scoring system, setting up timers, and fine-tuning the cannon's movements. Learn how to keep the action smooth and fast-paced with frame rate control. Let's make this game an unforgettable experience!
Step 1. Ending the Game 🚫👾
Open up the file we made in our Setup section.
Before we continue with the score system, we need to stop the game whenever one of the aliens makes it to the bottom!
# ...
# Game loop
alien_timer = 0
game_running = True
while game_running:
# ...
# Move all aliens
for alien in aliens:
alien.forward(ALIEN_SPEED)
# Check for game over
if alien.ycor() < FLOOR_LEVEL:
game_running = False
break
window.update()
turtle.done()
By using an if statement to check the alien's y-coordinate, we can end the game whenever it is triggered.
Let's add a game over text on the screen!
# ...
# Game loop
alien_timer = 0
game_running = True
while game_running:
# ...
window.update()
splash_text = turtle.Turtle()
splash_text.hideturtle()
splash_text.color(1, 1, 1)
splash_text.write("GAME OVER", font=("Courier", 40, "bold"), align="center")
turtle.done()
By using write()
, we can display cool messages like "GAME OVER" when the game ends! 🛑📝
Step 2. Create a Timer ⏰
Now let's make a timer for a thrilling, action-packed game!
# ...
# Create laser cannon
cannon = turtle.Turtle()
cannon.penup()
cannon.color(1, 1, 1)
cannon.shape("square")
cannon.setposition(0, FLOOR_LEVEL)
# Create turtle for writing text
text = turtle.Turtle()
text.penup()
text.hideturtle()
text.setposition(LEFT * 0.8, TOP * 0.8)
text.color(1, 1, 1)
# ...
# Game loop
alien_timer = 0
game_timer = time.time()
game_running = True
while game_running:
time_elapsed = time.time() - game_timer
text.clear()
text.write(
f"Time: {time_elapsed:5.1f}s",
font=("Courier", 20, "bold"),
)
# ...
By using write()
, we can display the time and keep the player on the clock! 🕒⏳
Step 3. Add the Score 🏆
Let's rack up points for each alien you zap—aim for the high score!
# ...
# Game loop
alien_timer = 0
game_timer = time.time()
score = 0
game_running = True
while game_running:
time_elapsed = time.time() - game_timer
text.clear()
text.write(
f"Time: {time_elapsed:5.1f}s\nScore: {score:5}",
font=("Courier", 20, "bold"),
)
# ...
# Check for collision with aliens
for alien in aliens.copy():
if laser.distance(alien) < 20:
remove_sprite(laser, lasers)
remove_sprite(alien, aliens)
score += 1
break
# ...
We created a variable to keep track of how many aliens we blasted! We then display it in the game loop so we can constantly see our score. 🔢👾
Step 4. Enhance Movement Controls 🚀🕹️
Time to make our cannon glide like a spaceship with new control tricks.
import random
import time
import turtle
CANNON_STEP = 3
# ...
# Create laser cannon
cannon = turtle.Turtle()
cannon.penup()
cannon.color(1, 1, 1)
cannon.shape("square")
cannon.setposition(0, FLOOR_LEVEL)
cannon.cannon_movement = 0 # -1, 0 or 1 for left, stationary, right
# ...
def move_left():
cannon.cannon_movement = -1
def move_right():
cannon.cannon_movement = 1
# ...
# Game loop
alien_timer = 0
game_timer = time.time()
score = 0
game_running = True
while game_running:
time_elapsed = time.time() - game_timer
text.clear()
text.write(
f"Time: {time_elapsed:5.1f}s\nScore: {score:5}",
font=("Courier", 20, "bold"),
)
# Move cannon
new_x = cannon.xcor() + CANNON_STEP * cannon.cannon_movement
if LEFT + GUTTER <= new_x <= RIGHT - GUTTER:
cannon.setx(new_x)
draw_cannon()
# ...
After reworking our cannon logic by creating a new function, we now have a super-enhanced cannon! 🚀🔫
One last thing we need to do!
# ...
def move_left():
cannon.cannon_movement = -1
def move_right():
cannon.cannon_movement = 1
def stop_cannon_movement():
cannon.cannon_movement = 0
# ...
# Key bindings
window.onkeypress(move_left, "Left")
window.onkeypress(move_right, "Right")
window.onkeyrelease(stop_cannon_movement, "Left")
window.onkeyrelease(stop_cannon_movement, "Right")
window.onkeypress(create_laser, "space")
window.onkeypress(turtle.bye, "q")
window.listen()
# ...
By using onkeyrelease
, we can stop the cannon from moving uncontrollably and put our cannon right back on track! 🛑🎮
Step 5. Frame Rate Control 🖥️⚙️
We need to keep our game running smoother than a hoverboard on a space station. First, we need to create some variables!
import random
import time
import turtle
FRAME_RATE = 30 # Frames per second
TIME_FOR_1_FRAME = 1 / FRAME_RATE # Seconds
# ...
Next, measure the time it takes to run one iteration of the while loop. If this time is shorter than the time required for one frame, pause the game until you reach the required time for one frame. The loop can then proceed with the next iteration. As long as the time it takes to run the while loop is shorter than the time required for one frame, every frame will take the same amount of time once the pause is completed:
Imagine your game loop is like a race car driving around a track, and each time the car goes around the track, it completes one lap. You want each lap to take the same amount of time to ensure the race looks smooth and doesn't speed up or slow down unpredictably. To achieve this, you start by measuring how long it takes for your race car (game loop) to complete one lap. This is like using a stopwatch to time the lap.
Next, you compare the actual lap time to your target lap time, which might be something like 0.05 seconds (50 milliseconds) per lap. If your car finishes the lap too quickly, taking less than the target 0.05 seconds, you need to make it wait at the finish line until the full 0.05 seconds have passed. This pause ensures that each lap takes exactly the same amount of time, even if the car (game loop) is capable of going faster.
Once the full 0.05 seconds are up, the car can start the next lap, maintaining a consistent pace. By doing this, you keep the game running at a steady, smooth speed, making it more enjoyable to play. This method ensures that each iteration of your game loop takes the same amount of time, resulting in a well-paced and visually smooth gaming experience. 🚗🏁
Now is the time to change any parameters to make the game feel smooth.
You are almost done! 🎉🎮