编辑代码

# coding:utf-8
import pygame
import sys

# 初始化 Pygame
pygame.init()

# 游戏常量
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
TILE_SIZE = 32
PLAYER_SPEED = 3

# 颜色定义
BLACK = (0, 0, 0)
GRASS_GREEN = (46, 139, 87)
WATER_BLUE = (0, 105, 148)

# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("像素冒险游戏")

# 玩家类
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((TILE_SIZE, TILE_SIZE))
        self.image.fill((255, 0, 0))  # 简单红色方块表示玩家
        self.rect = self.image.get_rect()
        self.rect.center = (SCREEN_WIDTH//2, SCREEN_HEIGHT//2)
    
    def move(self, dx, dy):
        # 移动并检查碰撞
        self.rect.x += dx
        self.rect.y += dy
        self.rect.clamp_ip(screen.get_rect())

# 地图数据 (0: 草地, 1: 水域)
game_map = [
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 1, 1, 0, 0, 0, 0, 0],
    [0, 0, 0, 1, 1, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 1, 1, 0],
    [0, 0, 0, 0, 0, 0, 0, 1, 1, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]

def draw_map():
    for y, row in enumerate(game_map):
        for x, tile in enumerate(row):
            rect = pygame.Rect(x*TILE_SIZE, y*TILE_SIZE, TILE_SIZE, TILE_SIZE)
            if tile == 0:
                pygame.draw.rect(screen, GRASS_GREEN, rect)
            elif tile == 1:
                pygame.draw.rect(screen, WATER_BLUE, rect)

# 创建玩家和精灵组
player = Player()
all_sprites = pygame.sprite.Group()
all_sprites.add(player)

# 游戏主循环
clock = pygame.time.Clock()
running = True

while running:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 获取键盘输入
    keys = pygame.key.get_pressed()
    dx, dy = 0, 0
    
    if keys[pygame.K_a]:
        dx = -PLAYER_SPEED
    if keys[pygame.K_d]:
        dx = PLAYER_SPEED
    if keys[pygame.K_w]:
        dy = -PLAYER_SPEED
    if keys[pygame.K_s]:
        dy = PLAYER_SPEED
    
    player.move(dx, dy)

    # 绘制游戏
    screen.fill(BLACK)
    draw_map()
    all_sprites.draw(screen)
    
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
sys.exit()