用python制作了一款迷宫游戏

下面是一个简单的迷宫游戏的Python代码示例。在这个游戏中,玩家需要使用键盘上的上下左右键来控制一个表示玩家的小方块在迷宫中移动,并尽可能地收集迷宫中的所有金币。

python复制代码
import pygame
import random
# 初始化pygame
pygame.init()
# 设置屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置颜色
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)
# 设置迷宫和金币大小
maze_width = 20
maze_height = 20
coin_size = 20
# 创建迷宫和金币
maze = [[0 for _ in range(maze_width)] for _ in range(maze_height)]
coins = []
for _ in range(10):
x = random.randint(0, maze_width - 1)
y = random.randint(0, maze_height - 1)
coins.append((x, y))
# 创建玩家
player_x = screen_width // 2
player_y = screen_height - 30
player_color = GREEN
player_rect = pygame.Rect(player_x, player_y, 10, 10)
player_pos = [player_x, player_y]
# 游戏主循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
new_pos = [player_pos[0], player_pos[1] - 10]
if maze[new_pos[1]][new_pos[0]] != 0: # 不在迷宫边界上且不是墙壁或金币
player_pos = new_pos[:]
elif event.key == pygame.K_DOWN:
new_pos = [player_pos[0], player_pos[1] + 10]
if maze[new_pos[1]][new_pos[0]] != 0: # 不在迷宫边界上且不是墙壁或金币
player_pos = new_pos[:]
elif event.key == pygame.K_LEFT:
new_pos = [player_pos[0] - 10, player_pos[1]]
if maze[new_pos[1]][new_pos[0]] != 0: # 不在迷宫边界上且不是墙壁或金币
player_pos = new_pos[:]
elif event.key == pygame.K_RIGHT:
new_pos = [player_pos[0] + 10, player_pos[1]]
if maze[new_pos[1]][new_pos[0]] != 0: # 不在迷宫边界上且不是墙壁或金币
player_pos = new_pos[:]
elif event.type == pygame.MOUSEBUTTONDOWN: # 如果点击了鼠标左键,将玩家移动到鼠标位置(作为起点)
mouse_x, mouse_y = pygame.mouse.get_pos()
if player_x == mouse_x and player_y == mouse_y: # 如果玩家在起点位置上,则移动玩家到鼠标位置(作为终点)
new_x = mouse_x - player_rect.width // 2 - player_rect.x + player_rect.width // 2 + player_rect.x//2 -

你可能感兴趣的:(pygame,python,开发语言)