import pygame
import sys

# 初始化 Pygame
pygame.init()

# 设置游戏窗口
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Super Mario")

# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 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

# 时钟设置
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_SPACE 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_x += player_vel_x
    player_y += player_vel_y

    # 处理跳跃
    if player_jump:
        player_vel_y += 0.5
        if player_y >= height - 50:
            player_y = height - 50
            player_jump = False
            player_vel_y = 0

    # 边界检测
    if player_x < 0:
        player_x = 0
    elif player_x > width - player_width:
        player_x = width - player_width

    # 填充背景色
    screen.fill(WHITE)

    # 绘制玩家
    pygame.draw.rect(screen, BLACK, (player_x, player_y, player_width, player_height))

    # 更新显示
    pygame.display.flip()

    # 控制帧率
    clock.tick(60)    

代码说明

  1. 初始化部分:对 Pygame 进行初始化,设置游戏窗口的大小和标题,同时定义了一些颜色常量。
  2. 玩家设置:对玩家的初始位置、尺寸、速度等属性进行设置。
  3. 游戏主循环:在这个循环里,处理用户的输入事件,像按键操作等。依据用户的输入来更新玩家的位置,同时进行边界检测和跳跃处理。
  4. 绘制和更新:将背景填充为白色,绘制玩家矩形,最后更新显示。
  5. 帧率控制:借助 clock.tick(60) 把游戏的帧率控制在 60 帧每秒。
    你可以将上述代码保存为一个 .py 文件,然后运行它来体验这个简单的超级玛丽游戏。

Python最棒
12 声望0 粉丝

码农一枚