Sitemap
Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

How to Build a Simple 2D Game in Python with Pygame

5 min readNov 21, 2024

--

# !pip install pygame

import pygame
import sys

pygame.init()

WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Simple 2D Game")

player_color = (0, 255, 0)
player_width, player_height = 50, 50
player_x, player_y = WIDTH // 2 - player_width // 2, HEIGHT // 2 - player_height // 2
player_speed = 5

running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

keys = pygame.key.get_pressed()

if keys[pygame.K_LEFT]:
player_x -= player_speed
if keys[pygame.K_RIGHT]:
player_x += player_speed
if keys[pygame.K_UP]:
player_y -= player_speed
if keys[pygame.K_DOWN]:
player_y += player_speed

player_x = max(0, min(WIDTH - player_width, player_x))
player_y = max(0, min(HEIGHT - player_height, player_y))

screen.fill((0, 0, 0))

pygame.draw.rect(screen, player_color, (player_x, player_y, player_width, player_height))
pygame.display.flip()

pygame.time.Clock().tick(60)

pygame.quit()
sys.exit()

Setting Up the Environment for Your Game

Before diving into the code, let’s ensure you’re all set up to run the program.

Install Pygame

To start working with Pygame, you need to install it first. Open your terminal and run the following command:

pip install pygame

This will download and install the Pygame library, which is essential for building games in Python. Pygame provides easy access to game-related functionality, including graphical rendering, user input handling, sound, and more.

Importing the Required Libraries

In any Python program, importing libraries is essential to access their built-in functions. In this case, we are importing two libraries: pygame and sys.

import pygame
import sys
  • pygame: This is the library we use to create games. It includes functionality for handling graphics, sounds, events, and more.
  • sys: The sys module allows you to interact with the Python runtime environment. It’s used here to exit the program gracefully.

Initializing Pygame

Next, we need to initialize the Pygame library to ensure it is ready for use.

pygame.init()

This line initializes all the necessary modules within Pygame. Without it, you won’t be able to use any of Pygame’s functions, like rendering graphics or handling events.

Setting Up the Screen

For any game, a screen is necessary where the action will take place. Let’s set up the window where our game will be displayed.

WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Simple 2D Game")
  • WIDTH and HEIGHT: These variables define the dimensions of the game window (800px width by 600px height).
  • pygame.display.set_mode((WIDTH, HEIGHT)): This creates a window with the dimensions defined above.
  • pygame.display.set_caption(“Simple 2D Game”): This sets the title of the game window to “Simple 2D Game.”

Setting Up the Player

Now that the window is set up, we need to define our player character. In this game, the player will be a simple green rectangle that we can move around the screen.

player_color = (0, 255, 0) # Green Color
player_width, player_height = 50, 50
  • player_color: This defines the color of the player character. The RGB value (0, 255, 0) corresponds to green.
  • player_width and player_height: These variables define the dimensions of the player (50px by 50px).

Now, let’s define the player’s starting position and movement speed.

player_x, player_y = WIDTH // 2 - player_width // 2, HEIGHT // 2 - player_height // 2
player_speed = 5
  • player_x and player_y: These define the player’s initial position. We use integer division (//) to center the player in the middle of the screen.
  • player_speed: This controls how fast the player can move. The value 5 means the player will move by 5 pixels per frame.

Game Loop

The heart of any game is the game loop, which continuously runs and updates the game state (e.g., player movement, screen refresh, event handling). In this case, we’re using a while loop to keep the game running until the user closes the window.

running = True
while running:

This starts the game loop. The variable running controls whether the game is still active. As long as it’s True, the game continues.

Handling Events

In every game, there are events that the game must handle. These can include things like closing the window, pressing keys, or clicking buttons. Let’s add event handling to our game.

for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
  • pygame.event.get(): This function retrieves all the events that are currently in the event queue.
  • pygame.QUIT: This event is triggered when the user clicks the close button on the window. When this event is detected, we set running = False, which ends the game loop.

Moving the Player

Now that we have basic event handling, let’s add the ability for the player to move around the screen using the arrow keys.

keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_x -= player_speed

if keys[pygame.K_RIGHT]:
player_x += player_speed

if keys[pygame.K_UP]:
player_y -= player_speed

if keys[pygame.K_DOWN]:
player_y += player_speed
  • pygame.key.get_pressed(): This function returns a list of all the keys currently being pressed.
  • pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, and pygame.K_DOWN: These represent the left, right, up, and down arrow keys, respectively. When any of these keys are pressed, the player moves in the corresponding direction by player_speed pixels.

Keeping the Player Inside the Screen

To prevent the player from moving off-screen, we need to make sure their position stays within the screen boundaries. Here’s how we do that:

player_x = max(0, min(WIDTH - player_width, player_x))
player_y = max(0, min(HEIGHT - player_height, player_y))
  • max(0, min(WIDTH — player_width, player_x)): This line ensures the player’s x position stays within the left and right boundaries of the screen.
  • max(0, min(HEIGHT — player_height, player_y)): Similarly, this ensures the player’s y position stays within the top and bottom boundaries.

Drawing the Player and Updating the Screen

Once we’ve handled input and updated the player’s position, we need to draw the player on the screen and refresh the display.

screen.fill((0, 0, 0)) # Fill the screen with black
pygame.draw.rect(screen, player_color, (player_x, player_y, player_width, player_height))
pygame.display.flip()
  • screen.fill((0, 0, 0)): This fills the screen with a black background. Each time the game loop runs, we clear the screen to prevent the previous frame from lingering.
  • pygame.draw.rect(screen, player_color, (player_x, player_y, player_width, player_height)): This draws the player as a green rectangle at the updated x and y positions.
  • pygame.display.flip(): This updates the display, showing the new frame with the updated player position.

Setting the Frame Rate

To ensure the game runs at a consistent speed, we need to control the frame rate. We can set this using pygame.time.Clock().

pygame.time.Clock().tick(60)

This ensures the game runs at 60 frames per second (FPS). The tick() method pauses the game loop as necessary to maintain the frame rate.

Exiting the Game

Finally, after the game loop ends (i.e., when the user closes the window), we need to clean up and exit the program gracefully.

pygame.quit()
sys.exit()
  • pygame.quit(): This shuts down all Pygame modules and frees up resources.
  • sys.exit(): This exits the program.

Program Output

When you run this program, you’ll see a simple game window with a green rectangle in the center. You can move the rectangle around using the arrow keys. The game will continue running until you close the window.

Conclusion

In this tutorial, we’ve built a simple 2D game using Python and Pygame. We’ve covered how to set up the game window, handle player input, and manage the game loop. By following these basic steps, you can start building more complex games by adding features like enemies, obstacles, scoring, and more!

Get Someone’s stories in your inbox

Join Medium for free to get updates from this writer.

Feel free to check out the code on my GitHub and follow me on Twitter to stay updated with my learning journey:

--

--

Dev Genius
Dev Genius

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development