推箱子是一种经典的益智游戏,玩家需要操作角色推动箱子到目标位置。以下是一个简单的推箱子 Python 代码实现:

# 导入必要的库
import pygame
import sys

# 定义常量
WIDTH = 800
HEIGHT = 600
FPS = 60
BLOCK_SIZE = 50
ROWS = HEIGHT // BLOCK_SIZE
COLS = WIDTH // BLOCK_SIZE

# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

# 定义游戏状态
GAME_OVER = 0
PLAYING = 1
WIN = 2

# 定义游戏地图
MAP = [
    '##########',
    '#        #',
    '#        #',
    '#  P     #',
    '#        #',
    '#   B    #',
    '#        #',
    '#        #',
    '#        #',
    '##########'
]

# 初始化pygame
pygame.init()

# 设置窗口大小和标题
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Push Box')

# 加载游戏资源
player_img = pygame.image.load('player.png').convert_alpha()
box_img = pygame.image.load('box.png').convert_alpha()
wall_img = pygame.image.load('wall.png').convert_alpha()
target_img = pygame.image.load('target.png').convert_alpha()

# 定义游戏对象类
class GameObject:
    def __init__(self, row, col, img):
        self.row = row
        self.col = col
        self.img = img
    
    def draw(self):
        x = self.col * BLOCK_SIZE
        y = self.row * BLOCK_SIZE
        screen.blit(self.img, (x, y))

# 定义角色类
class Player(GameObject):
    def __init__(self, row, col):
        super().__init__(row, col, player_img)
    
    def move(self, dx, dy):
        new_row = self.row + dy
        new_col = self.col + dx
        if 0 <= new_row < ROWS and 0 <= new_col < COLS:
            if game_map[new_row][new_col] != '#':
                self.row = new_row
                self.col = new_col
                return True
        return False

# 定义箱子类
class Box(GameObject):
    def __init__(self, row, col):
        super().__init__(row, col, box_img)

    def move(self, dx, dy):
        new_row = self.row + dy
        new_col = self.col + dx
        if 0 <= new_row < ROWS and 0 <= new_col < COLS:
            if game_map[new_row][new_col] != '#' and not is_box(new_row, new_col):
                self.row = new_row
                self.col = new_col
                return True
        return False

# 定义游戏地图
game_map = []
player = None
boxes = []
targets = []
for row in range(ROWS):
    game_map.append([])
    for col in range(COLS):
        char = MAP[row][col]
        if char == '#':
            game_map[row].append('#')
            wall = GameObject(row, col, wall_img)
        elif char == 'P':
            game_map[row].append('.')
            player = Player(row, col)
        elif char == 'B':
            game_map[row].append('.')
            box = Box(row, col)
            boxes.append(box)
        elif char == ' ':  # 空格
            game_map[row].append('.')
        elif char == 'T':
            game_map[row].append('.')
            target = GameObject(row, col, target_img)
            targets.append(target)

# 判断一个位置是否有箱子
def is_box(row, col):
    for box in boxes:
        if box.row == row and box.col == col:
            return True
    return False

# 判断游戏是否胜利
def is_win():
    for target in targets:
        is_covered = False
        for box in boxes:
            if box.row == target.row and box.col == target.col:
                is_covered = True
                break
        if not is_covered:
            return False
    return True

# 游戏循环
state = PLAYING
clock = pygame.time.Clock()
while True:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                if player.move(0, -1):
                    for box in boxes:
                        if player.row == box.row and player.col == box.col:
                            box.move(0, -1)
                            break
            elif event.key == pygame.K_DOWN:
                if player.move(0, 1):
                    for box in boxes:
                        if player.row == box.row and player.col == box.col:
                            box.move(0, 1)
                            break
            elif event.key == pygame.K_LEFT:
                if player.move(-1, 0):
                    for box in boxes:
                        if player.row == box.row and player.col == box.col:
                            box.move(-1, 0)
                            break
            elif event.key == pygame.K_RIGHT:
                if player.move(1, 0):
                    for box in boxes:
                        if player.row == box.row and player.col == box.col:
                            box.move(1, 0)
                            break
    
    # 更新游戏状态
    if is_win():
        state = WIN
    elif state != GAME_OVER and not any([box.row == player.row and box.col == player.col for box in boxes]):
        state = GAME_OVER

    # 绘制游戏界面
    screen.fill(WHITE)
    for row in range(ROWS):
        for col in range(COLS):
            if game_map[row][col] == '#':
                wall = GameObject(row, col, wall_img)
                wall.draw()
            elif game_map[row][col] == '.':
                target = GameObject(row, col, target_img)
                target.draw()
    for box in boxes:
        box.draw()
    player.draw()
    
    # 绘制游戏状态
    if state == GAME_OVER:
        font = pygame.font.SysFont(None, 64)
        text = font.render('Game Over', True, RED)
        screen.blit(text, (WIDTH//2 - text.get_width()//2, HEIGHT//2 - text.get_height()//2))
    elif state == WIN:
        font = pygame.font.SysFont(None, 64)
        text = font.render('You Win!', True, GREEN)
        screen.blit(text, (WIDTH//2 - text.get_width()//2, HEIGHT//2 - text.get_height()//2))
    
    # 更新屏幕
    pygame.display.update()
    clock.tick(FPS)

这个代码实现了一个简单的推箱子游戏,玩家可以使用方向键控制角色移动,并推动箱子到目标位置。游戏界面使用了 pygame 库来实现,游戏地图使用了一个字符串列表来表示。这个代码仅仅是一个基础实现,可以添加更多的关卡、难度等元素来丰富游戏内容。

如何运行代码

  1. 确保你已经安装了 pygame 库:pip install pygame
  2. 将代码保存为 .py 文件 (例如 pushbox.py)
  3. 在代码同一目录下,创建 player.png, box.png, wall.png, target.png 图片文件
  4. 运行代码:python pushbox.py

代码说明

  • 游戏状态
    • GAME_OVER: 游戏结束
    • PLAYING: 游戏进行中
    • WIN: 游戏胜利
  • 游戏地图
    • 使用字符串列表表示游戏地图,字符含义如下:
      • '#' - 墙壁
      • 'P' - 角色
      • 'B' - 箱子
      • 'T' - 目标
      • ' ' - 空格
  • 游戏对象
    • GameObject 是所有游戏对象的基类
    • Player 类表示角色
    • Box 类表示箱子
  • 游戏逻辑
    • 使用 move() 方法控制角色和箱子移动
    • 使用 is_win() 方法判断游戏是否胜利
    • 使用 is_box() 方法判断一个位置是否有箱子
  • 游戏界面
    • 使用 pygame 库绘制游戏界面
    • 使用 screen.blit() 函数绘制游戏对象

扩展思路

  • 添加更多关卡
  • 增加难度(例如增加箱子数量、墙壁数量等)
  • 添加游戏音效和背景音乐
  • 添加计时功能
  • 添加分数统计功能
  • 使用图形界面设计工具 (例如 Tkinter) 创建游戏菜单和设置界面
  • 将游戏打包成可执行文件

希望这个代码能够帮助你开始你的推箱子游戏之旅!

Python 推箱子游戏代码实现 - 经典益智游戏编程

原文地址: https://www.cveoy.top/t/topic/lBui 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录