pygame勇闯黑暗迷宫.py

"""勇闯黑暗迷宫.py,一个迷宫创意小游戏,本程序运行后操作一只小猫闯过迷宫,
不能碰到迷宫的墙壁,当走到一半路程时会停电,这时玩家只能靠记忆了。
本程序来源于李兴球曾经制作的scratch同名小游戏。
"""
__author__ = "李兴球"
__date__ = "2018年7月"

import pygame
from pygame.locals import *
import time

gametitle = "勇闯黑暗迷宫"
pygame.init()
screenWidth,screenHeight=480,360
screen = pygame.display.set_mode((screenWidth,screenHeight))
pygame.display.set_caption(gametitle + ",作者:李兴球,406273900@qq.com")
icon = "李兴球.ico"
pygame.display.set_icon(pygame.image.load(icon))

ballimage = pygame.image.load("cat.png").convert_alpha()
# 以下是列表导出加载迷宫的每一张图片
mazeimages = [ pygame.image.load("迷宫" + str(i) + ".gif").convert_alpha() for  i in range(1,7) ]

停电音 = pygame.mixer.Sound("停电灭灯.wav")
碰到音 = pygame.mixer.Sound("Meow.wav")
开始音 = pygame.mixer.Sound("勇闯.wav")
通关音 = pygame.mixer.Sound("通关.wav")
过关音 = pygame.mixer.Sound("过关.wav")
失败音 = pygame.mixer.Sound("闯关失败.wav")

class Ball(pygame.sprite.Sprite):
    def __init__(self,image,x,y):
        pygame.sprite.Sprite.__init__(self)
        self.image = image
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.mask = pygame.mask.from_surface(self.image)
        self.xspeed = 0
        self.yspeed = 0
        
    def move(self,maze):
        
        self.rect.move_ip(self.xspeed,self.yspeed)
        point = pygame.sprite.collide_mask(maze,self)
        if point:  self.xspeed = -self.xspeed  ;self.yspeed = -self.yspeed ; self.rect.move_ip(self.xspeed,self.yspeed)
        return point
        
    def draw(self):
        screen.blit(self.image,self.rect)
    
class Maze(pygame.sprite.Sprite):
    def __init__(self,image):
        pygame.sprite.Sprite.__init__(self)
        self.image = image
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.image)
        self.start_time = time.time()            #记录开始时间,给停电设计用
    def draw(self):
        screen.blit(self.image,self.rect)
        
def display_cover():
    """显示封面图像,单击鼠标退出循环"""
    cover = pygame.image.load("封面设计.png")
    运行  = True
    exit_flag = False
    while 运行 :
        for event in pygame.event.get():
            if event.type == MOUSEBUTTONDOWN :
               运行  = False
            if event.type==KEYDOWN:
                if event.key ==K_SPACE:运行 = False
            if event.type ==QUIT:exit_flag = True
        screen.blit(cover,(0,0))
        pygame.display.update()
        if exit_flag == True :break
    if exit_flag == True :
        pygame.quit()
        return False
    else:
        return True
    
                    
def main():
        
    闯关结果= None
    ball = Ball(ballimage,60,313)
    mazeindex = 0
    maze = Maze(mazeimages[mazeindex])
    # 每关的过关条件
    exit_condition=["ball.rect.y<0","ball.rect.x>480","ball.rect.x<0","ball.rect.x>480","ball.rect.x>480","ball.rect.x>480"]
    level_amount = len(exit_condition)
    point=None
    clock = pygame.time.Clock()
    running = True

    # 每关的停电时间
    darktime = [6,7,7,7,7,10]  # 以秒为单位,第一关到了第6秒就会变黑,同时给Maze增加了start_time属性
    
    # 停电音是否播放限制表
    停电音播放了吗=[0,0,0,0,0,0]# 为0表示此关没有播放,播放后把它的值设为1,这样就能限制播放的次数
    
    while running:   
        for event in pygame.event.get():
            if event.type==QUIT:pygame.quit()  
       
        screen.fill((128,0,0))
        # 停电设计,不重画maze,那么就是黑乎乎的,相当于停电
        逝去的时间 = time.time() - maze.start_time
        if 逝去的时间 < darktime[mazeindex]:
            maze.draw()                       # 重画迷宫
        else:
            # 播放停电音,渲染气氛,但只能播放一次
            if 停电音播放了吗[mazeindex]==0:
                停电音.play()
                停电音播放了吗[mazeindex]=1
        
        mx,my = ball.rect.x,ball.rect.y       # 改为显示球的坐标,因为显示鼠标坐标意义不大
        keys  = pygame.key.get_pressed()
     
        if  keys[K_LEFT] :ball.xspeed =  -2  ; ball.yspeed=0      
        if  keys[K_RIGHT] : ball.xspeed =2 ; ball.yspeed=0    
        if  keys[K_UP] : ball.yspeed =  -2 ; ball.xspeed=0    
        if  keys[K_DOWN] : ball.yspeed =  2; ball.xspeed=0    
        if  keys[K_SPACE] : ball.yspeed =  0 ; ball.xspeed =0
        
        point = ball.move(maze) 
        if point : 闯关结果 = "失败" ; running = False ; 碰到音.play()
        pygame.display.set_caption(gametitle + ", 碰撞点:" + str(point) + ",(" + str(mx) + "," + str(my) + "),关卡号:" + str(mazeindex + 1))        
        ball.draw()
        ispassed = eval(exit_condition[mazeindex])               # 计算每关是否通关
        if ispassed :
            if  mazeindex< (level_amount-1):
                mazeindex = mazeindex + 1
                maze = Maze(mazeimages[mazeindex])
                ball.yspeed =  0 ;  ball.xspeed =0
                ball.rect.x  = 60 ; ball.rect.y = 313
                过关音.play()
            else:                
                闯关结果 = "成功"
                running = False            
            
        pygame.display.update()
        clock.tick(30)
    return 闯关结果

def play_background_music():
    """播放背景音乐"""
    pygame.mixer.music.load("OcularNebula_Geometry Dash - Stay Inside Me [mp3clan.com].wav")
    pygame.mixer.music.play(-1,0)
    
if __name__=="__main__":

    pygame.mixer.init()                 # 初始化混音器
    开始音.play()
    play_background_music()             # 播放背景音乐 
    ret = display_cover()               # 显示封面
    
    if ret == True :
        结果= main()                        # 游戏主程序

        pygame.display.set_caption(gametitle + ",游戏结束.作者:李兴球 406273900@qq.com ")
        
        if 结果 == "成功":
            print("通关了")
            end_image = pygame.image.load("通关图像.png")
            通关音.play()
        else:
            print("闯关失败")
            end_image = pygame.image.load("失败图像.png")
            失败音.play()
            
        # 以下是显示游戏结束画面        
        running = True
        while running:
            for event in pygame.event.get():
                if event.type in (MOUSEBUTTONDOWN,KEYDOWN):running = False    # 按鼠标键或任意键结束
                if event.type==QUIT:running=False                             # 按关闭按钮退出pygame
            screen.blit(end_image,(0,0))                                      # 渲染图像
            pygame.display.update()                                           # 更新显示
        pygame.quit()