Python 8个箱子开宝箱游戏,随机炸弹,点击获得金币
以下是使用Python语言编写的一段代码,实现了打开箱子的游戏逻辑:
import random
import pygame
# 初始化游戏界面
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('打开箱子')
clock = pygame.time.Clock()
# 加载图片
box_image = pygame.image.load('zsPic/box.png')
gold_image = pygame.image.load('zsPic/gold.png')
bomb_image = pygame.image.load('zsPic/bomb3.png')
# 设置游戏状态
GAME_OVER = False
GOT_BOMB = False
total_gold = 0
# 生成随机的炸弹位置
bomb_index = random.randint(0, 7)
# 游戏主循环
while not GAME_OVER:
clock.tick(60)
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
GAME_OVER = True
# 绘制界面
screen.fill((255, 255, 255))
# 绘制箱子
for i in range(8):
if i == bomb_index:
screen.blit(bomb_image, (100 + 80 * i, 200))
else:
screen.blit(box_image, (100 + 80 * i, 200))
# 判断是否打开箱子
mouse_x, mouse_y = pygame.mouse.get_pos()
if 100 <= mouse_x <= 780 and 200 <= mouse_y <= 380:
box_index = (mouse_x - 100) // 80
if box_index == bomb_index:
GOT_BOMB = True
else:
total_gold += 1
screen.blit(gold_image, (100 + 80 * box_index, 200))
# 判断游戏结束条件
if GOT_BOMB:
GAME_OVER = True
pygame.display.flip()
# 游戏结束,显示结果
screen.fill((255, 255, 255))
if GOT_BOMB:
text = pygame.font.SysFont(None, 48).render('你踩到炸弹了!', True, (0, 0, 0))
else:
text = pygame.font.SysFont(None, 48).render('你获得了{}个金币'.format(total_gold), True, (0, 0, 0))
screen.blit(text, (300, 250))
pygame.display.flip()
# 等待关闭窗口
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
运行以上代码后,会弹出一个窗口,窗口中有8个箱子,其中一个箱子内装有炸弹,其余7个箱子内装有金币。点击鼠标左键打开箱子,如果打开的箱子内是金币,则获得金币,如果打开的箱子内是炸弹,则游戏结束,损失之前获得的金币。最后会在窗口中显示游戏结果。
原文地址: https://www.cveoy.top/t/topic/o9au 著作权归作者所有。请勿转载和采集!