import pygame
import sys
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())
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()