SoFunction
Updated on 2025-04-10

Using Python to implement the complete code of Bomb Man game

1. Introduction

Bomb Man Game is a classic game. In this article, we will explore in-depth how to use Python's Pygame library to implement a Bomb Man game and optimize it in many aspects, including adding enemy AI, scoring systems, health points, and game ending logic to bring players a more complete and rich gaming experience.

2. Game initialization and settings

(I) Pygame initialization and window settings

First, we import the necessary librariespygamerandomandsys, andpygamePerform initialization operation.

import pygame
import random
import sys

# Initialize pygame()

# Set the game window sizeSCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
BOMB_TIMER = 10  # Bomb explosion time
# Set colorWHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)

# Set fontsFONT = ('Arial', 24)

# Game Windowscreen = .set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
.set_caption('Bomber Man')

Here we set the size of the game window800x600The explosion time of the bomb is10Each unit of time, and at the same time, it defines the various colors and font styles that will be used in the game, and creates a game window and sets the window title asBomber Man

(II) Initial settings of players, enemies and bombs

Next, we make initial settings for the main elements in the game - players, enemies and bombs.

# Player settingsplayer_size = 30
player_pos = [SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2]
player_speed = 5
player_bombs = 3
player_lives = 3

# Enemy settingsenemy_size = 30
enemy_pos = [(0, SCREEN_WIDTH - enemy_size), (0, SCREEN_HEIGHT - enemy_size)]
enemy_speed = 3
enemy_list = [{'pos': enemy_pos, 'speed': enemy_speed}]

# Bomb Settingsbomb_size = 20
bomb_list = []
bomb_timer = 0

For players, we set its initial size to30The pixel, the initial position is in the center of the window, the movement speed is5Pixels/Unit time, initially owned3Bomb with health3. For enemies, their initial size is also30The pixel, the initial position is randomly generated in the window, and the movement speed is3Pixels/unit time and store their information inenemy_listin the list. The bomb sets the initial size and creates an empty bomb listbomb_listUsed to store bomb information and initialize the bomb timer as0

(III) Map Settings

Finally, we set up the map.

# Map Settingsmap_width = 20
map_height = 15
map_grid = [['1' for _ in range(map_width)] for _ in range(map_height)]

A created here20x15Map gridmap_grid,in'1'For walls that indicate that they cannot pass, the map can be modified according to the bomb explosion and other situations in the future.

3. Game element drawing function

(I) Draw a map grid function

def draw_grid():
    for y in range(map_height):
        for x in range(map_width):
            rect = (x * 40, y * 40, 40, 40)
            (screen, BLACK if map_grid[y][x] == '1' else WHITE, rect, 0 if map_grid[y][x] == '0' else 1)

This function is used to draw a grid of game maps. By traversing each grid in the map grid, according to the value of the grid ('1'It is a black wall,'0'It is a white passable area) draws the corresponding rectangle and decides whether to draw the border according to the grid type.

(II) Draw the player function

def draw_player():
    (screen, RED, (player_pos[0], player_pos[1], player_size, player_size))

This function simply draws a red rectangle at the player's current position to represent the player.

(III) Draw enemy functions

def draw_enemy():
    for enemy in enemy_list:
        (screen, BLUE, (enemy['pos'][0], enemy['pos'][1], enemy_size, enemy_size))

This function traverses the enemy listenemy_list, draw a blue rectangle at each enemy's position to represent the enemy.

4. Game element movement and operation functions

(I) Player Movement Function

def move_player(keys):
    if keys[pygame.K_LEFT] and player_pos[0] > 0:
        player_pos[0] -= player_speed
    if keys[pygame.K_RIGHT] and player_pos[0] < SCREEN_WIDTH - player_size:
        player_pos[0] += player_speed
    if keys[pygame.K_UP] and player_pos[1] > 0:
        player_pos[1] -= player_speed
    if keys[pygame.K_DOWN] and player_pos[1] < SCREEN_HEIGHT - player_size:
        player_pos[1] += player_speed

Get keyboard key statuskeys, When the player presses the left, right, up and down direction keys, and the player's position is within the window boundary, the player's position coordinates are changed accordingly to realize the player's movement operation.

(II) Enemy Movement Function

def move_enemy():
    for enemy in enemy_list:
        if () &lt; 0.1:  # Random movement            if () &lt; 0.5:
                enemy['pos'][0] += enemy['speed']
            else:
                enemy['pos'][0] -= enemy['speed']
            if () &lt; 0.5:
                enemy['pos'][1] += enemy['speed']
            else:
                enemy['pos'][1] -= enemy['speed']
        # Keep the enemy in the window        enemy['pos'][0] = max(0, min(enemy['pos'][0], SCREEN_WIDTH - enemy_size))
        enemy['pos'][1] = max(0, min(enemy['pos'][1], SCREEN_HEIGHT - enemy_size))

Enemies move with a simple random movement strategy. In each cycle, there10%The probability of the enemy will move, the movement direction is randomly selected from the four directions: up, down, left and right, and the movement speed isenemy_speed. At the same time, make sure that the enemy's position is always in the game window.

(III) Place the bomb function

def place_bomb():
    global bomb_timer
    if bomb_timer == 0 and player_bombs > 0:
        bomb_list.append({'pos': [player_pos[0] // 40, player_pos[1] // 40], 'timer': BOMB_TIMER})
        bomb_timer = BOMB_TIMER
        player_bombs -= 1

When the bomb timer is0When the player has a bomb, create a bomb information at the map grid coordinates corresponding to the player's current position and add it tobomb_list, and update the bomb timer and reduce the number of bombs for players.

(IV) Bomb explosion function

def explode_bombs():
    for bomb in bomb_list[:]:
        x, y = bomb['pos']
        if bomb['timer'] == 0:
            bomb_list.remove(bomb)
            if map_grid[y][x] == '1':
                map_grid[y][x] = '0'
                for dx in [-1, 0, 1]:
                    for dy in [-1, 0, 1]:
                        if dx!= 0 or dy!= 0:
                            nx, ny = x + dx, y + dy
                            if 0 <= nx < map_width and 0 <= ny < map_height and map_grid[ny][nx] == '1':
                                map_grid[ny][nx] = '0'
        else:
            bomb['timer'] -= 1

This function traverses the bomb listbomb_list, When the bomb timer returns to zero, the bomb explodes. If the explosion location is a wall ('1'), then turn it into a passable area ('0'), and traverse the grids around the explosion (except the center grid within the nine-cage grid range), and turn them into a passable area if it is a wall. If the bomb timer is not reset to zero, reduce it1

(V) Collision detection function

def check_collision():
    global player_lives
    for enemy in enemy_list[:]:
        if (enemy['pos'][0] >= player_pos[0] and enemy['pos'][0] <= player_pos[0] + player_size) and \
           (enemy['pos'][1] >= player_pos[1] and enemy['pos'][1] <= player_pos[1] + player_size):
            player_lives -= 1
            enemy_list.remove(enemy)
            if player_lives <= 0:
                return True
    return False

This function is used to detect collisions between players and enemies. Iterate through the enemy list, and if an enemy overlaps with the player's position, reduce the player's health and remove the enemy. If the player's health is less than or equal to0, then the game ends and returnsTrue, otherwise returnFalse

5. The main loop of the game

def game_loop():
    running = True
    clock = ()
    score = 0
    while running:
        for event in ():
            if  == :
                running = False

        keys = .get_pressed()
        move_player(keys)
        if keys[pygame.K_SPACE] and player_bombs > 0:
            place_bomb()

        move_enemy()
        explode_bombs()

        (BLACK)
        draw_grid()
        draw_player()
        draw_enemy()
        for bomb in bomb_list:
            (screen, (255, 255, 0), (bomb['pos'][0] * 40, bomb['pos'][1] * 40, 40, 40))

        if check_collision():
            running = False

        score_text = (f'Score: {score}', True, GREEN)
        lives_text = (f'Lives: {player_lives}', True, GREEN)
        (score_text, (10, 10))
        (lives_text, (SCREEN_WIDTH - 150, 10))

        ()
        (30)

    ()
    ()

Game main loopgame_loopIn the first place, the game exit event is handled. Then get the keyboard key status and perform player movement and bomb placement operations. Then move the enemy and deal with the bomb explosion logic. Then draw elements such as game background, map, players, enemies and bombs. Confirmation detection is performed again, and if the game is over, the loop will be jumped out. Finally, draw the score and health information, and update the screen display to control the game frame rate to30Frames/second.

6. Game entrance

if __name__ == "__main__":
    game_loop()

existif __name__ == "__main__"Called in a statement blockgame_loopFunction, start the game.

7. Optimization content summary

  • Enemy AI: Through a simple random movement strategy, the enemy has a certain degree of autonomy, which increases the challenge of the game.
  • Scoring system: Although the scoring increase logic is not shown in detail in the code (the score can be increased when the bomb is placed, etc.), the scoring variable has been reservedscore, providing a foundation for subsequent improvement of the scoring system.
  • Health value: The player has health, and the health is reduced when the collision with the enemy, and when the health is0When the game ends, it makes the game more reasonable and tense.
  • Game end logic: The conditions for the end of the game are clarified, that is, the player's health is exhausted, so that the game has a complete start and end process.

8. Subsequent expansion direction

This optimized code has provided a relatively complete Bomb Man game framework. You can further expand and optimize this game as needed, such as adding more enemy types, with different types of enemies having different movement strategies and attack methods; improving map generation logic to generate more complex and interesting maps; adding more game elements, such as props, traps, etc. to enrich gameplay and improve the fun and playability of the game.

Through the above detailed analysis of Bomb Man game code, I hope it can help readers better understand the logical construction and functional implementation in the game development process, so as to make greater progress in the learning and practice of game development.

This is the end of this article about using Python to implement Bomb Man Games. For more related content on Python to implement Bomb Man Games, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!