python写一个有可视化界面的推箱子游戏代码
时间: 2024-02-04 18:02:04 浏览: 138
好的,以下是一个带有可视化界面的推箱子游戏的 Python 代码:
```python
import pygame
# 定义地图
map = [
"#####",
"# #",
"#O #",
"# #",
"#####"
]
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 定义格子大小
TILE_SIZE = 50
# 初始化 Pygame
pygame.init()
# 设置窗口大小
WINDOW_SIZE = (len(map[0]) * TILE_SIZE, len(map) * TILE_SIZE)
screen = pygame.display.set_mode(WINDOW_SIZE)
# 加载图片
player_image = pygame.image.load("player.png").convert_alpha()
box_image = pygame.image.load("box.png").convert_alpha()
# 定义玩家初始位置
player_x = 1
player_y = 1
# 定义箱子初始位置
box_x = 2
box_y = 2
# 绘制地图
def draw_map():
for y in range(len(map)):
for x in range(len(map[0])):
if map[y][x] == "#":
pygame.draw.rect(screen, BLACK, [x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE])
elif map[y][x] == "O":
screen.blit(box_image, (x * TILE_SIZE, y * TILE_SIZE))
elif map[y][x] == "X":
pygame.draw.rect(screen, GREEN, [x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE])
# 绘制玩家
def draw_player():
screen.blit(player_image, (player_x * TILE_SIZE, player_y * TILE_SIZE))
# 游戏主循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# 玩家移动
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
if map[player_y - 1][player_x] == " ":
player_y -= 1
elif map[player_y - 1][player_x] == "O" and map[player_y - 2][player_x] == " ":
player_y -= 1
box_y -= 1
elif event.key == pygame.K_DOWN:
if map[player_y + 1][player_x] == " ":
player_y += 1
elif map[player_y + 1][player_x] == "O" and map[player_y + 2][player_x] == " ":
player_y += 1
box_y += 1
elif event.key == pygame.K_LEFT:
if map[player_y][player_x - 1] == " ":
player_x -= 1
elif map[player_y][player_x - 1] == "O" and map[player_y][player_x - 2] == " ":
player_x -= 1
box_x -= 1
elif event.key == pygame.K_RIGHT:
if map[player_y][player_x + 1] == " ":
player_x += 1
elif map[player_y][player_x + 1] == "O" and map[player_y][player_x + 2] == " ":
player_x += 1
box_x += 1
# 绘制背景
screen.fill(WHITE)
# 绘制地图
draw_map()
# 绘制玩家
draw_player()
# 判断是否胜利
if map[box_y][box_x] == "X":
font = pygame.font.Font(None, 64)
text = font.render("You win!", True, BLUE)
text_rect = text.get_rect(center=(WINDOW_SIZE[0]/2, WINDOW_SIZE[1]/2))
screen.blit(text, text_rect)
pygame.display.update()
pygame.time.wait(2000)
pygame.quit()
exit()
# 移动箱子
map[box_y] = map[box_y][:box_x] + "O" + map[box_y][box_x + 1:]
map[box_y - 1] = map[box_y - 1][:box_x] + " " + map[box_y - 1][box_x + 1:]
# 更新屏幕
pygame.display.update()
```
需要注意的是,这里使用了 Pygame 库来进行可视化界面的开发,需要提前安装 Pygame 库。另外,这个实现也只是一个非常简单的实现,还有很多可以改进和优化的地方。
阅读全文