Make your first Pygame 🎮
h
jajoosam (669)

Make games the easy way, and forget about the setup 😌

Demo + Code ⏯️ 👨‍💻

I've heard coding in python is quite delightful! And I agreed once I made my first python app that didn't just run on the terminal - a game made with Pygame.

You'd usually have to spend a while getting set up, installing Pygame, dependencies and then have to spend time compiling an executable before sharing your game. But with replit's new GFX system - there's absolutely no need for that ✌️

This is a tutorial to get started with Pygame, and make a simple game within 30 minutes!

🛠️ Getting our environment running

Head over to repl.it and once you're logged in, hit new repl → Pygame to create the repl where we're going to be making our game.

That's it 😉

🎲 Understanding the game

Before we start coding, let's understand what we're making 🛠️

Our game concept is pretty straightforward - there's a paddle - a simple rectangle that moves left or right in the screen, attempting to catch balls falling from the top of the screen.

A higher score is more number of balls caught ⚾

👨‍💻 Initializing pygame

You can go right ahead and paste this code in your repl!

# adding libraries we're going to use
import pygame
from random import randint

pygame.init()

# initializing variables to account for the number of balls caught, and total dropped
score = 0
total = 0

myfont = pygame.font.SysFont('monospace', 50) # creating a font to write the score in

# Making dictionaries with settings for everything.

display = {
    "width": 800,
    "height": 600
}

paddle = {
    "width": 200,
    "height": 20,
    "x": 300,
    "y": 580,
    "velocity": 10
}

ball = {
    "radius": 15,
    "y": 30,
    "x": randint(0, display["width"]),
    "velocity": 20
}

# creating a window, and launching our game
win = pygame.display.set_mode((display["width"], display["height"])) # 800 width, 600 height

I've added comments to explain what each line does 😄

Make sure to paste in the dictionaries too, they'll be super useful soon!

👾 The paddle

Our paddle is going to be just a little rectangle that moves when we hit the arrow keys. Before we can start making it, we need to create the main loop. Pygame will run the code inside this loop continuously, to update the screen based on inputs.

Paste all this in!

while True:
    pygame.time.delay(100)
    win.fill((255, 255, 255))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            break

    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT]:
        paddle["x"] -= paddle["velocity"]

    if keys[pygame.K_RIGHT]:
        paddle["x"] += paddle["velocity"]

    pygame.draw.rect(win, (255, 0, 0), (paddle["x"], paddle["y"], paddle["width"], paddle["height"]))
    pygame.display.update()

pygame.quit()

Don't worry, I'm not just going to leave you like that xD

Let's break this up into smaller blocks to explain what everything does! Let's talk about everything inside the while loop, which will run forever - since True will always remain True 😮

pygame.time.delay(100)
win.fill((255, 255, 255))

We're adding the delay so that the loop doesn't run too often, and there's some gap between each cycle - keeping our repl from crashing. 100 is delay in milliseconds, causing the loop to run 10 times a second. win.fill() takes a color in RGB as it's argument - and 255, 255, 255 represents white, filling our window with white before we draw anything onto it 🖌️

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        break

This piece of code goes over all events that pygame gives us, and breaks the loop if Pygame has been quit. When the loop breaks, we go to the line which says pygame.quit()- you know what that does 😛

keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT]:
        paddle["x"] -= paddle["velocity"]

    if keys[pygame.K_RIGHT]:
        paddle["x"] += paddle["velocity"]

To get this - lets first clear out our understanding about the coordinate grid - it doesn't start at the center in pygame! In fact, the top left corner is 0, 0 and x increases as you go right, while y increases as you move down.

This block of code gets all currently pressed keys, and checks whether the left or right keys are pressed. If they are, it changes the x coordinates of the paddle - reducing if ⬅️ is pressed, and increasing if ➡️ is pressed by the velocity we set in the paddle dictionary. Try changing the velocity to see what happens 🤔

pygame.draw.rect(win, (255, 0, 0), (paddle["x"], paddle["y"], paddle["width"], paddle["height"]))
pygame.display.update()

This is where we actually draw our paddle to the screen - in the window called win, red in color (255, 0, 0 RGB) - at paddle[x] on the x axis, and paddle[y] on the y axis. We've also set the width and height in the paddle dictionary, feel free to mess around with it!

Finally, pygame.display.update() updates the entire screen with what we've drawn in this cycle of the loop!

Try running the code, and hitting the left and right arrow keys! You should see a little rectangle moving around 👇

⚽ Generating falling circles

Let's bring up the ball dictionary up again 👇

ball = {
    "radius": 15,
    "y": 30,
    "x": randint(0, display["width"]),
    "velocity": 20
}

What does the "x" line do?

We're selecting a random x co-ordinate between 0 and display["width"] (currently 800) - using the randint function we imported right at the start of our code.

Add this inside your while loop, right before you draw the paddle to the screen:

ball["y"] += ball["velocity"]
pygame.draw.circle(win, (0, 0, 255), (ball["x"], ball["y"]), ball["radius"])

We're increasing the y co-ordinate of the ball by its velocity and drawing the ball again in every cycle of the loop.

🏆 When do you actually score a point, though?

The final part of our game would be checking if the ball hits the paddle when it's at the bottom of the screen. Collision detection is going to be essential to most of the games you're going to make in the future, so let's go over it here!

if ball["y"] + ball["radius"] >= paddle["y"]:
        if ball["x"] > paddle["x"] and ball["x"] < paddle["x"] + paddle["width"]:
            score += 1
        total += 1
        ball["y"] = 0
        ball["x"] = randint(0, display["width"])

First up, we're learning if the ball has hit the level of the paddle - by checking if the ball's radius + it's position on the y axis is equal to the position of the paddle.

if ball["x"] > paddle["x"] and ball["x"] < paddle["x"] + paddle["width"]

With this long condition, we're testing if

  • The ball's position on the X axis is greater than the paddle's position on the X axis

AND

  • The ball's position on the X axis is lesser than the sum of the paddle's position on the X axis and its width

If this condition is true, it means that the ball has landed on the paddle, and we increase the score 🙌

Maybe this image helps a bit 🤞

After this, regardless of whether a point has beens scored or not, we add one to the total number of balls landed - and reset the ball's position, setting the ball's y co-ordinate to 0, and generate a random position for the X axis.

Lastly, we're going to write the score on the screen 🏅

textsurface = myfont.render("score: {0}/{1}".format(score, total), False, (0, 0, 0))
win.blit(textsurface, (10, 10))

We create a new surface where we write the text using python's format function, replacing {0} with the socre, and {1} with the total. We're writing this in black (0, 0, 0 RGB).

win.blit(textsurface, (10, 10)) merges the text with the main window, at co-ordinates 10, 10.

And that's the game - the full thing 🤯

🔮 Things to try

  • Changing the contents of the dictionary and seeing what happens ❓
  • Make multiple balls fall at the same time 🔴 🔵 ⚫
  • Make the paddle move up and down too 🚀
  • Adding poison balls - the game stops when your paddle hits one 😵

Be sure to put down any questions or improvements down in the comments 💬

And here's all the code for you to go over again - I highly recommend going through this to help you understand the flow of the program, and the sequencing of everything if you were even a little confused by this guide 😅

https://repl.it/@jajoosam/paddleBasket

You are viewing a single comment. View All
John2515 (0)

Really helpful, would you like to submit this on http://letsfindcourse.com/python