以下是一个使用Python和`pygame`库创建的简单类似马里奥的游戏示例代码,该游戏有窗口、滚轴效果、重力、惯性以及怪物元素。 ```python import pygame import sys # 初始化pygame pygame.init() # 设置窗口尺寸 WIDTH, HEIGHT = 800, 600 win = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Simple Mario-like Game") # 颜色定义 WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) # 玩家设置 player_x = 50 player_y = HEIGHT - 50 player_width = 50 player_height = 50 player_vel_x = 0 player_vel_y = 0 player_jump = False jump_height = 15 gravity = 0.5 inertia = 0.9 # 怪物设置 monster_x = 700 monster_y = HEIGHT - 50 monster_width = 50 monster_height = 50 monster_vel_x = -2 # 滚动相机设置 camera_x = 0 clock = pygame.time.Clock() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: player_vel_x = -5 if event.key == pygame.K_RIGHT: player_vel_x = 5 if event.key == pygame.K_UP and not player_jump: player_jump = True player_vel_y = -jump_height if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: player_vel_x = 0 # 应用惯性 player_vel_x *= inertia # 应用重力 player_vel_y += gravity # 更新玩家位置 player_x += player_vel_x player_y += player_vel_y # 防止玩家掉出屏幕底部 if player_y >= HEIGHT - player_height: player_y = HEIGHT - player_height player_vel_y = 0 player_jump = False # 更新怪物位置 monster_x += monster_vel_x # 怪物碰到边界反弹 if monster_x <= 0 or monster_x >= WIDTH - monster_width: monster_vel_x = -monster_vel_x # 滚动相机 if player_x > WIDTH // 2 and player_vel_x > 0: camera_x -= player_vel_x elif player_x < WIDTH // 2 and player_vel_x < 0: camera_x -= player_vel_x # 绘制 win.fill(WHITE) # 绘制玩家 pygame.draw.rect(win, BLACK, (player_x - camera_x, player_y, player_width, player_height)) # 绘制怪物 pygame.draw.rect(win, RED, (monster_x - camera_x, monster_y, monster_width, monster_height)) pygame.display.update() clock.tick(60) ``` 代码解释 1. 初始化部分:初始化`pygame`库,设置窗口大小、颜色、玩家和怪物的初始位置、速度等参数。 2. 主循环部分:处理用户输入事件,根据按键更新玩家的速度和位置。应用惯性和重力,更新玩家和怪物的位置。 3. 绘制部分:绘制、玩家和怪物,使用滚动相机实现滚轴效果。 额外注意的逻辑点 1. 边界处理:要确保玩家和怪物不会超出游戏窗口的边界,避免出现异常情况。 2. 碰撞检测:可以添加玩家和怪物的碰撞检测逻辑,当玩家碰到怪物时游戏结束或者玩家损失生命值。 3. 性能优化:在处理大量元素时,要注意性能问题,避免出现卡顿现象。可以考虑使用精灵组等方式优化代码。 [2025-06-13 19:11:12 | AI写代码神器 | 964点数解答]