8-bit game using pygame


Pygame is an open-source Python library used for making games. Pygame library provides various functions and tools for creating games, sound processing, and graphics.pygame library can be used to create games on any operating system like Windows, Linux, and macOS as pygame is a cross-platform library.

What is an 8-bit Game?

The 8-bit game was very popular in the 1980s. The 8-bit video games included graphics and sound that were created using 8-bit technology i.e a limited color palette and sound range that fall within the 8-bit range were used to create such video games. In this article, we will create an 8-bit game using the pygame library in Python with minimal graphics.

Before creating an 8-bit game using pygame we need to install pygame by pip command in Python as

pip install pygame

Creating 8-bit Game

Creating our Window for the Game

Once the pygame library is installed we can use it to create our game. To create the game we need to first create a window of a certain size on which the game will be displayed or played. To create a window we have to −

  • Specify the width and height of the window

  • Create a window using pygame.display.set_mode() function and pass the width and height to it.

  • Create the window name that will be displayed on the top of the game window as the Game begins. Use display.set_caption() function to set the window name.

Example

import pygame

pygame.init()
width = 640
height = 480
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("My 8-bit Game")

Creating 8-bit Sprite

After creating our window for the game we will be creating the 8-bit sprite.Sprites are basic building blocks of the 8-bit game. Sprite are objects that move around the screen with help of a computer or the player can move the object. We can create a sprite in the 8-bit game by −

  • Use the pygame.sprite.Sprite() class

  • Create a player class that inherits from sprite class

  • Define the attributes and function of the class

Example

class Player(pygame.sprite.Sprite):
   def __init__(self, x, y):
      super().__init__()
      self.image = pygame.Surface((16, 16))
      self.image.fill((255, 255, 255))
      self.rect = self.image.get_rect()
      self.rect.x = x
      self.rect.y = y

player = Player(0, 0)

Create Enemies in the Game

To make the game more engaging we can create some enemies for the player which when colliding with the player will damage the player. We can create enemies by creating a new enemies class by inheriting from the pygame.sprite.Sprite() class which will be similar to the player class.

Here we will −

  • Create enemies class similar to player class using pygame.sprite.Sprite() class

  • Create the enemies in red color

  • Move the enemies horizontally

  • Create an update function which sets the speed of the moving enemies.

# Define the Enemy class
class Enemy(pygame.sprite.Sprite):
   def __init__(self, x, y):
      super().__init__()
      self.image = pygame.Surface((32, 32))
      self.image.fill((0, 0, 255))
      self.rect = self.image.get_rect()
      self.rect.x = x
      self.rect.y = y
      self.speed = 2

   def update(self):
      self.rect.x += self.speed
      if self.rect.left > WIDTH:
      self.rect.right = 0

Add power-ups

We can create power-ups for the player which will increase the power or speed of the player when the player collides with the power-ups. We can create a new powerup class that is inherited from pygame.sprite.Sprite() class and will be similar to the player and enemies class.

Here we will −

  • Create a powerup class similar to player and enemies class and it will have a power or speed attribute

  • The powerup objects will be green in color

# Define the PowerUp class
class PowerUp(pygame.sprite.Sprite):
   def __init__(self, x, y, power):
      super().__init__()
      self.image = pygame.Surface((16, 16))
      self.image.fill((0, 255, 0))
      self.rect = self.image.get_rect()
      self.rect.x = x
      self.rect.y = y
      self.power = power

   def update(self):
      pass

Create Player and Enemies Groups and Instances

Create groups for players, enemies, and power-ups so that we can create multiple instances of these to make the game more interactive. Here in this game, we will −

  • Create 5 instances of the Enemy class and add them to the enemies group

  • Create 3 instances of the PowerUp class and add them to the powerups group

# Create the player and enemy groups
all_sprites = pygame.sprite.Group()
enemies = pygame.sprite.Group()
powerups = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
```

```
# Create 5 instances of the Enemy class and add them to the enemies group
for i in range(5):
   enemy = Enemy(random.randint(0, WIDTH), random.randint(0, HEIGHT))
   enemies.add(enemy)
   all_sprites.add(enemy)

# Create 3 instances of the PowerUp class and add them to the powerups group
for i in range(3):
   power = random.choice(['health', 'speed'])
   powerup = PowerUp(random.randint(0, WIDTH), random.randint(0, HEIGHT), power)
   powerups.add(powerup)
   all_sprites.add(powerup)

Create the Game Loop

We can add movement to our game using the keyboard inputs We can handle keyboard inputs in our game using the pygame.key.get_pressed() function which returns a boolean value indicating which key is currently pressed.

Here −

  • We will create an infinite loop to continuously listen for events

  • If the user closes the window we exit the game using pygame.quit() and sys.exit() functions.

  • Get the currently pressed key using pygame.key.get_pressed() function

  • If the left arrow key is pressed we move the player back by subtracting 5 from the x-coordinate and if the right arrow key is pressed we move the player forward by adding 5 to the x-coordinate of the player position and similarly for UP and DOWN arrow key

  • Check for collisions with enemies by pygame.sprite.spritecollide() function

  • Check the collision with powerup by using pygame.sprite.spritecollide() function

  • Update the enemies when the enemies collide with the player.

  • Fill the screen with black color using screen.fill() function

  • Display the player on the screen using screen.blit() function

  • Update the display using the pygame.display.flip() function.

# Game loop
while True:
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         pygame.quit()
         sys.exit()

   keys = pygame.key.get_pressed()

   if keys[pygame.K_LEFT]:
      player.rect.x -= player.speed
   elif keys[pygame.K_RIGHT]:
      player.rect.x += player.speed
   elif keys[pygame.K_UP]:
      player.rect.y -= player.speed
   elif keys[pygame.K_DOWN]:
      player.rect.y += player.speed

   # Check for collisions with enemies
   if pygame.sprite.spritecollide(player, enemies, True):
      player.health -= 10

   # Check for collisions with power-ups
   powerups_collected = pygame.sprite.spritecollide(player, powerups, True)
   for powerup in powerups_collected:
      if powerup.power == 'health':
         player.health += 20
      elif powerup.power == 'speed':
         player.speed += 1
    
   # Update the enemies
   enemies.update()

   # Draw the sprites on the screen
   screen.fill((0, 0, 0))
   screen.blit(player.image, player.rect)
   enemies.draw(screen)
   powerups.draw(screen)

   pygame.display.flip()

The Full Code of the Game is given below −

import pygame
import sys
import random


# Initialize Pygame
pygame.init()


# Set up the display
WIDTH = 800
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('8-Bit Game')


# Set up the clock
clock = pygame.time.Clock()


# Define the Player class
class Player(pygame.sprite.Sprite):
   def __init__(self):
      super().__init__()
      self.image = pygame.Surface((32, 32))
      self.image.fill((255, 0, 0))
      self.rect = self.image.get_rect()
      self.rect.x = WIDTH // 2
      self.rect.y = HEIGHT // 2
      self.speed = 5
      self.health = 100


   def update(self):
      pass


# Define the Enemy class
class Enemy(pygame.sprite.Sprite):
   def __init__(self, x, y):
      super().__init__()
      self.image = pygame.Surface((32, 32))
      self.image.fill((0, 0, 255))
      self.rect = self.image.get_rect()
      self.rect.x = x
      self.rect.y = y
      self.speed = 2


   def update(self):
      self.rect.x += self.speed
      if self.rect.left > WIDTH:
         self.rect.right = 0


# Define the PowerUp class
class PowerUp(pygame.sprite.Sprite):
   def __init__(self, x, y, power):
      super().__init__()
      self.image = pygame.Surface((16, 16))
      self.image.fill((0, 255, 0))
      self.rect = self.image.get_rect()
      self.rect.x = x
      self.rect.y = y
      self.power = power


   def update(self):
      pass


# Create the player and enemy groups
all_sprites = pygame.sprite.Group()
enemies = pygame.sprite.Group()
powerups = pygame.sprite.Group()
player = Player()
all_sprites.add(player)


# Create 5 instances of the Enemy class and add them to the enemies group
for i in range(5):
   enemy = Enemy(random.randint(0, WIDTH), random.randint(0, HEIGHT))
   enemies.add(enemy)
   all_sprites.add(enemy)


# Create 3 instances of the PowerUp class and add them to the powerups group
for i in range(3):
   power = random.choice(['health', 'speed'])
   powerup = PowerUp(random.randint(0, WIDTH), random.randint(0, HEIGHT), power)
   powerups.add(powerup)
   all_sprites.add(powerup)


# Game loop
while True:
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         pygame.quit()
         sys.exit()


   keys = pygame.key.get_pressed()


   if keys[pygame.K_LEFT]:
      player.rect.x -= player.speed
   elif keys[pygame.K_RIGHT]:
      player.rect.x += player.speed
   elif keys[pygame.K_UP]:
      player.rect.y -= player.speed
   elif keys[pygame.K_DOWN]:
      player.rect.y += player.speed


   # Check for collisions with enemies
   if pygame.sprite.spritecollide(player, enemies, True):
      player.health -= 10


   # Check for collisions with power-ups
   powerups_collected = pygame.sprite.spritecollide(player, powerups, True)
   for powerup in powerups_collected:
      if powerup.power == 'health':
         player.health += 20
      elif powerup.power == 'speed':
         player.speed += 1
    
   # Update the enemies
   enemies.update()


   # Draw the sprites on the screen
   screen.fill((0, 0, 0))
   screen.blit(player.image, player.rect)
   enemies.draw(screen)
   powerups.draw(screen)


   pygame.display.flip()

Output

Conclusion

In this article we explored the pygame library by creating an 8-bit game with players, enemies, and powerups to make the game more interesting. Pygame library can be used to add more functionality and sound to the game which can make the code more complex.

Updated on: 17-Apr-2023

895 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements