Welcome to this comprehensive guide on pygame coding. In this tutorial, we will delve deep into the wonders of the pygame library, a popular module for Python programming that allows for game development. We have designed this tutorial to be engaging and beginner-friendly, providing multiple examples that revolve around fun and simple game mechanics.
Table of contents
What is Pygame?
Pygame is an open-source library designed for making video games using the Python programming language. Fun and easy to use, it allows you to create a wide variety of games, from simple 2D games to complex 3D ones.
We’ll be using it to learn how to create engaging games while also understanding how Python works. If you’ve wanted to create your own game or just understand how coding a game works, this tutorial will prove to be invaluable.
The Pygame module is an excellent starting point for those wanting to dip their toes into game development. It’s powerful yet easy to learn, and since it’s based on Python, it allows you to dive into game creating without the need to learn a more complex language.
In short, Python and Pygame together provide a way to learn coding and game development in an engaging, fun way. Let’s get started!
Setting Up Pygame
Our first task is to install the pygame library. Open your command prompt and type:
pip install pygame
After installation, you can verify it by typing python on the command prompt, then:
If you don’t see any error, that means pygame module has been successfully installed.
Creating Our First Game Window
Let’s create a basic game window using pygame. To do this, we need to initialise the game, create a screen object and create a game loop to keep the game window running.
import pygame pygame.init() gameWindow = pygame.display.set_mode((800, 600)) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit()
This code will open a game window of 800×600 pixels until the user decides to close the window.
Moving Our Game Forward
Now, let’s explore how Pygame lets you create moving graphics to simulate game environments. We will create a simple moving square to see how this works:
import pygame pygame.init() gameWindow = pygame.display.set_mode((800, 600)) pygame.display.set_caption('Moving Square') square= pygame.image.load('square.png') def drawSquare(x,y): gameWindow.blit(square, (x, y)) running = True x = 50 y = 50 while running: pygame.time.delay(100) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False x += 5 if x > 800: x = 50 gameWindow.fill((0,0,0)) drawSquare(x,y) pygame.display.update() pygame.quit()
This code will move the square image across the game window, restarting when it reaches the end of the screen.
Adding User Controls
Finally, we can make our game interactive by adding some user controls. We’ll modify our square to move based on the arrow keys:
import pygame pygame.init() gameWindow = pygame.display.set_mode((800, 600)) pygame.display.set_caption('Controlled Square') square = pygame.image.load('square.png') def drawSquare(x,y): gameWindow.blit(square, (x, y)) running = True x = 50 y = 50 speed = 0.1 while running: pygame.time.delay(100) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: x -= speed if keys[pygame.K_RIGHT]: x += speed if keys[pygame.K_UP]: y -= speed if keys[pygame.K_DOWN]: y += speed gameWindow.fill((0,0,0)) drawSquare(x,y) pygame.display.update() pygame.quit()
This code lets you control the square with the arrow keys, letting you move it around the game window.
Bringing It All Together – Simple Game
Let’s combine the basics we’ve learned and build a simple ‘collect the item’ game. We need a moving sprite (the player), and an item to collect, which will randomly appear in different locations. Our score will increment each time we collect an item.
import pygame import random pygame.init() screenWidth = 800 screenHeight = 600 gameScreen = pygame.display.set_mode((screenWidth, screenHeight)) pygame.display.set_caption('Item Collector Game') playerImg = pygame.image.load('player.png') playerX = screenWidth / 2 playerY = screenHeight / 2 playerSpeed = 3 itemImg = pygame.image.load('item.png') itemX = random.randint(0, screenWidth) itemY = random.randint(0, screenHeight) score = 0 def drawPlayer(x, y): gameScreen.blit(playerImg, (x, y)) def drawItem(x, y): gameScreen.blit(itemImg, (x, y)) def collectItem(playerX, playerY, itemX, itemY): distance = ((itemX - playerX)**2 + (itemY - playerY)**2)**0.5 if distance < 27: return True else: return False gameRunning = True while gameRunning: pygame.time.delay(100) gameScreen.fill((0, 0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: gameRunning = False keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: playerX -= playerSpeed if keys[pygame.K_RIGHT]: playerX += playerSpeed if keys[pygame.K_UP]: playerY -= playerSpeed if keys[pygame.K_DOWN]: playerY += playerSpeed itemCollection = collectItem(playerX, playerY, itemX, itemY) if itemCollection: score += 1 print(score) itemX = random.randint(0, screenWidth) itemY = random.randint(0, screenHeight) drawPlayer(playerX, playerY) drawItem(itemX, itemY) pygame.display.update() pygame.quit()
There you have it! Our first simple game made entirely with pygame. By implementing collisions and scoring, we’ve made our game a bit more engaging and interactive for the player.
The possibilities with pygame are endless. Let’s stick with the basics for now, though, and ensure we understand everything about pygame fundamentals before moving on to more complex concepts. Happy coding!
Adding Sound and Music to Our Game
Adding sound and music can bring our game to life. Pygame makes it simple to add sound effects and background music. Let’s add some sound effects to our game:
import pygame import random pygame.init() screenWidth = 800 screenHeight = 600 gameScreen = pygame.display.set_mode((screenWidth, screenHeight)) pygame.display.set_caption('Sound Effects Game') sound = pygame.mixer.Sound('sound.wav') bg_music = pygame.mixer.music.load('bgmusic.mp3') pygame.mixer.music.play(-1) #-1 will ensure the music loops indefinitely. ..... itemCollection = collectItem(playerX, playerY, itemX, itemY) if itemCollection: sound.play() #plays the sound score += 1 .....
This new code will play the sound effect when the player collects an item and will continuously play the background music.
Adding Multiple Players to Our Game
Games can be more fun when more than one player is involved. Pygame allows us to easily add multiple entities:
def drawPlayer2(x, y): gameScreen.blit(player2Img, (x, y)) .... player2Img = pygame.image.load('player2.png') player2X = screenWidth / 3 player2Y = screenHeight / 3 drawPlayer2(player2X, player2Y)
We’ve added a second player to our game, with just a few lines of code.
Now, let’s make our game a bit more challenging by adding an enemy that moves randomly on the screen:
enemyImg = pygame.image.load('enemy.png') enemyX = random.randint(0, screenWidth) enemyY = random.randint(0, screenHeight) def drawEnemy(x, y): gameScreen.blit(enemyImg, (x, y)) ... drawEnemy(enemyX, enemyY)
The enemy will appear at a random location on the screen.
Next, let’s make our enemy move:
enemySpeedX = 0.5 enemySpeedY = 0.5 ... while gameRunning: enemyX += enemySpeedX enemyY += enemySpeedY if enemyX = screenWidth: enemySpeedX *= -1 if enemyY = screenHeight: enemySpeedY *= -1
This will make the enemy bounce back and forth within the boundaries of our game screen.
Collision with Enemy
Finally, let’s add a penalty when our player collides with the enemy:
def collisionWithEnemy(playerX, playerY, enemyX, enemyY): distance = ((enemyX - playerX)**2 + (enemyY - playerY)**2)**0.5 if distance < 27: return True else: return False ... enemyCollision = collisionWithEnemy(playerX, playerY, enemyX, enemyY) if enemyCollision: score -= 1
Now the player’s score will decrease by 1 every time they collide with the enemy. This adds a challenge by incentivizing the player to avoid the enemy.
This concludes our tutorial on building a simple game using pygame. By utilizing these techniques and approaches, you have the keys to code more complex and personalized games. Keep practicing, and happy coding!
Continuing Your Learning Journey
Congratulations on taking the first steps into your game development journey with pygame! But don’t stop here. There is so much more to learn and explore!
We welcome you to boost your coding skills further with our Python Mini-Degree. This comprehensive course collection covers coding basics, algorithms, object-oriented programming, game development, and app development – all in Python. The content is designed for learners of all levels, with step-by-step projects that allow you to create your own games and apps. It’s a flexible offering that you can access 24/7, and receive a certificate upon completion.
If you are looking for more specific or advanced Python courses, you can check out our Python courses. We have over 250 supported courses that can assist beginners, intermediates, and even experts in furthering their programming knowledge. Remember, learning is a never-ending journey. Stick with it, and you will be amazed by what you can achieve.
From setting up pygame to creating a basic game with user controls and audio support, we’ve covered a lot in this tutorial. Pygame is a terrific library to begin your journey into game development and Python programming; its simplicity and versatility make it an excellent choice for programmers at all levels, especially beginners.
At Zenva, our mission is to provide the highest quality learning material to help upskill passionate learners and create opportunities for all. If you enjoyed this tutorial and are interested in diving deeper into Python and game development, or if you’re just starting your coding journey, we invite you to explore our Python Mini-Degree. With us, you’ll take your coding skills to new heights and possibly discover a passion that might shape your career. See you in another learning journey!
FINAL DAYS: Unlock coding courses in Unity, Unreal, Python, Godot and more.