请你用python编一个闯关游戏要求:有图像
以下是一个简单的用Python编写的闯关游戏示例,使用了pygame库来实现图像显示和交互。游戏中包含了两个关卡,玩家需要控制一个小球通过障碍物到达终点。
import pygame
import sys
# 初始化pygame
pygame.init()
# 窗口大小
WIDTH = 800
HEIGHT = 600
# 颜色定义
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 创建窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("闯关游戏")
# 加载图片
ball_image = pygame.image.load("ball.png")
obstacle_image = pygame.image.load("obstacle.png")
finish_image = pygame.image.load("finish.png")
# 设置初始位置
ball_x = 50
ball_y = HEIGHT // 2
# 设置初始速度
ball_dx = 0
ball_dy = 0
# 设置终点位置
finish_x = WIDTH - 100
finish_y = HEIGHT // 2
# 设置障碍物位置
obstacle_x = WIDTH // 2
obstacle_y = HEIGHT // 2
# 游戏结束标志
game_over = False
# 游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
ball_dy = -5
elif event.key == pygame.K_DOWN:
ball_dy = 5
elif event.key == pygame.K_LEFT:
ball_dx = -5
elif event.key == pygame.K_RIGHT:
ball_dx = 5
elif event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
ball_dy = 0
elif event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
ball_dx = 0
# 更新小球位置
ball_x += ball_dx
ball_y += ball_dy
# 碰撞检测
if ball_x < 0 or ball_x > WIDTH or ball_y < 0 or ball_y > HEIGHT:
game_over = True
if abs(ball_x - obstacle_x) < 50 and abs(ball_y - obstacle_y) < 50:
game_over = True
if abs(ball_x - finish_x) < 50 and abs(ball_y - finish_y) < 50:
game_over = True
# 绘制背景
screen.fill(WHITE)
# 绘制小球
ball_rect = ball_image.get_rect()
ball_rect.center = (ball_x, ball_y)
screen.blit(ball_image, ball_rect)
# 绘制障碍物
obstacle_rect = obstacle_image.get_rect()
obstacle_rect.center = (obstacle_x, obstacle_y)
screen.blit(obstacle_image, obstacle_rect)
# 绘制终点
finish_rect = finish_image.get_rect()
finish_rect.center = (finish_x, finish_y)
screen.blit(finish_image, finish_rect)
# 更新屏幕
pygame.display.flip()
# 游戏结束,退出pygame
pygame.quit()
请注意,该示例中使用到了三个图片文件:ball.png、obstacle.png和finish.png。你需要自行准备这些图片文件,并与代码放在同一目录下才能正常运行。该示例仅提供了基本的游戏框架,你可以根据需要进行扩展和修改
原文地址: http://www.cveoy.top/t/topic/hQze 著作权归作者所有。请勿转载和采集!