One of the key elements of a great video game is the presence of enemies. Whether they're zombies, aliens, or other players, enemies can make a game more challenging and exciting.

In PyGame, you can easily program a variety of enemy movement behaviors, like following the player, moving randomly, or taking specific paths.

Creating a Simple Game

Start by creating a simple game where a player will move horizontally and vertically. If the player touches the enemy, the player will die.

You can find the complete code in this GitHub repo.

Begin by importing the necessary PyGame module and initializing it.

 import pygame

pygame.init()

Next, set up the screen and create the player and enemy objects using the pygame.Rect() function.

 # Set up the screen
screen = pygame.display.set_mode((800, 600))

# Set up the colors
black = (0, 0, 0)
white = (255, 255, 255)

# Set up the player rectangle and the enemy object
player = pygame.Rect(350, 500, 50, 50)
enemy = pygame.Rect(350, 0, 50, 50)

After that, create a game loop that runs until the player either collides with the enemy or exits the game. Also, check for collision between the player and the enemy, and draw the game objects on the screen.

 # Set up the game loop
running = True

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

    # Fill the screen with white
    screen.fill(white)

    # Move the player rectangle
    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT]:
        player.x -= 5

    if keys[pygame.K_RIGHT]:
        player.x += 5

   if keys[pygame.K_UP]:
       player.y -= 5

   if keys[pygame.K_DOWN]:
       player.y += 5

    # Check for collision between player and enemy
    if player.colliderect(enemy):
        running = False

    # Draw the player rectangle and the enemy object on the screen
    pygame.draw.rect(screen, black, player)
    pygame.draw.rect(screen, black, enemy)

    # Update the screen
    pygame.display.update()

# Quit the game
pygame.quit()

Direct Enemies Toward the Player

To move the enemy toward the player, you need to calculate the distance between the two, which you can do using the Pythagorean theorem. You can then use this distance to determine the enemy's movement speed and direction toward the player.

To implement this, create a speed variable and use it to update the enemy's position toward the player.

 # Calculate the distance between the enemy and the player
distance_x = player.x - enemy.x
distance_y = player.y - enemy.y
distance = (distance_x ** 2 + distance_y ** 2) ** 0.5

# Move the enemy toward the player
speed = 2

if distance != 0:
    enemy.x += speed * distance_x / distance
    enemy.y += speed * distance_y / distance

Randomize Enemy Movement on Screen

You can also make the enemy move randomly on the screen to make the game more challenging.

To do this, generate a random direction for the enemy to move using the random module in Python. Use the choice() function to select a random direction from a list of directions that the enemy can move in. Then update the enemy's position based on the chosen direction.

 import random

# Move the enemy randomly on the screen
direction = random.choice(['left', 'right', 'up', 'down'])

if direction == 'left':
    enemy.x -= 5
elif direction == 'right':
    enemy.x += 5
elif direction == 'up':
    enemy.y -= 5
elif direction == 'down':
    enemy.y += 5

Proximity-Based Enemy Movement

In some games, the enemy moves only when the player is close to them. You can achieve this by calculating the distance between the enemy and the player.

If the distance is less than a certain value, make the enemy move toward the player. This makes the game more strategic and forces the player to be more careful in their movements.

 # Move the enemy toward the player if the player is close
speed = 2

if distance < 300:
    if distance != 0:
        enemy.x += speed * distance_x / distance
        enemy.y += speed * distance_y / distance

Enemy Evades Player Attacks

You can also make the enemy dodge the player's movement. The enemy will try to avoid the player by moving perpendicular to the player's position.

To achieve this, calculate the unit vector toward the player using the distance_x and distance_y calculated earlier. Then, calculate the perpendicular vector to move the enemy perpendicular to the unit vector. Finally, calculate the dot product of the perpendicular vector and the unit vector to determine the direction of enemy movement.

To implement this, add the code snippet below after the distance calculation.

 speed = 2

if distance < 400:
    if distance != 0:
        # Calculate the unit vector toward the player
        unit_vector_x = distance_x / distance
        unit_vector_y = distance_y / distance

        # Calculate the perpendicular vector
        perpendicular_vector_x = -unit_vector_y
        perpendicular_vector_y = unit_vector_x

        # Calculate the dot product of the perpendicular vector and the
        # unit vector
        dot_product = perpendicular_vector_x * unit_vector_x
           + perpendicular_vector_y * unit_vector_y

        # Move the enemy perpendicular to the unit vector
        if dot_product > 0:
            enemy.x += speed * perpendicular_vector_x
            enemy.y += speed * perpendicular_vector_y
        else:
            enemy.x -= speed * perpendicular_vector_x
            enemy.y -= speed * perpendicular_vector_y

With these modifications, the enemy will try to avoid getting too close to the player. This makes the game more challenging and fun to play.

Adding Extra Features

You can also add more features in your game to make it more challenging. For example, you can add multiple enemies that move randomly on the screen, obstacles that the player needs to avoid while moving, power-ups that enhance the player's abilities, and so on.

You can use the Clock module to set the frame rate of your game and make it run more smoothly. Below is the implementation:

 # Add multiple enemies that move randomly on the screen
enemies = []

for i in range(5):
    enemy = pygame.Rect(random.randint(0, 750), random.randint(0, 550), 50,
       50)

    enemies.append(enemy)

# Add obstacles that the player needs to avoid
obstacle = pygame.Rect(200, 250, 50, 50)

# Set up the game loop
clock = pygame.time.Clock()
running = True

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

    # Fill the screen with white
    screen.fill(white)

    # Move the player rectangle
    keys = pygame.key.get_pressed()

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

    # Move the enemies randomly on the screen
    for enemy in enemies:
        direction = random.choice(['left', 'right', 'up', 'down'])

        if direction == 'left':
            enemy.x -= 5
        elif direction == 'right':
            enemy.x += 5
        elif direction == 'up':
            enemy.y -= 5
        elif direction == 'down':
            enemy.y += 5

        # Check for collision between player and enemy
        if player.colliderect(enemy):
            running = False

    # Draw the player rectangle, the enemy objects, and the obstacle on
   # the screen
    pygame.draw.rect(screen, black, player)

    for enemy in enemies:
        pygame.draw.rect(screen, black, enemy)

    pygame.draw.rect(screen, black, obstacle)

    # Update the screen
    pygame.display.update()

    # Set the frame rate of the game
    clock.tick(60)

# Quit the game
pygame.quit()

Enhance Your Gaming Experience With Enemies

By adding enemies with unique movements, behaviors, and abilities, you can make your games more engaging and challenging for players. Players will need to strategize and adapt their gameplay to overcome different types of enemies. This can increase engagement, improve replay value, and keep players coming back for more.