用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - python代码库

躲避方块(英文版) 小游戏

2022-04-03 作者: mikeKil举报

[python]代码库

'''
作者:mikeKil
游戏名:躲避方块(英文版)
注:如果发现BUG或有疑问可以到作者的留言板留言
(如果想导入背景音乐可以去掉196~199,670和66~67行的注释)
'''
#模块导入
import pygame
import sys
import random
import time
import tkinter as tk
from tkinter import filedialog, messagebox
import easygui as gui
import win32gui
import win32api

#pygame初始化
pygame.init()
pygame.mixer.init()
#隐藏tkinter窗口
root = tk.Tk()
root.withdraw()

#窗口宽高
windowWIDTH = 600 ; windowHEIGHT = 450
#颜色加载
BLUE = (0, 0, 255) ; LIGHTBLUE = (0,245,255)
WHITE = (255, 255, 255) ; PURPLE = (148,0,211)
LIGHTPURPLE = (160,32,240) ; GREEN = (50,205,50)
LIGHTGREEN = (0,255,127) ; ORANGE = (255,140,0)
RED = (255,0,0) ; PINK = (255,192,203)
LIGHTYELLOW = (255,222,173) ; YELLOW = (255,255,0)
colors = [BLUE,WHITE,PURPLE,GREEN,ORANGE,LIGHTYELLOW,
          RED,LIGHTBLUE,LIGHTPURPLE,PINK,LIGHTGREEN,YELLOW]
#音乐名设置
fileName = "The Way I Still Love You"
#窗口标题
window_title = u'躲避方块(英文版)  Avoid obstacles(English version)'
#大号字体和小号字体
BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
BASICFONT_M = pygame.font.Font('freesansbold.ttf', 30)
BASICFONT_B = pygame.font.Font('freesansbold.ttf', 55)
#是否继续更新推进
IsPlus = True ; IsWrite = True ; IsAgain = True
#状态
STATES = {"START": 1, "RUNNING1": 2, "GAME_OVER": 3,"SETUP": 4, "RUNNING2": 5}
state = STATES["START"]
#方块列表
enemies = []
Senemies = []
#分数列表
secondsList = []
#开始的时间
TIMELATER = 0
#上次的时间和等待的时间
lastTime = 0
interval = 0.7
lastTime_m2 = 0
interval_m2 = 0.5

#窗口加载和标题命名
canvas = pygame.display.set_mode((windowWIDTH,windowHEIGHT))
pygame.display.set_caption("躲避方块(英文版)  Avoid obstacles(English version)")
#音乐加载并播放音乐
# track = pygame.mixer.music.load(filePath)
# pygame.mixer.music.play()
#line(Surface, color, start_pos, end_pos, width=1)

#创建Enemy类
class Enemy():
    def __init__(self,width,color,steep,type,
                 start_posX,start_posY,end_posX,end_posY):
        #宽度
        self.width = width
        #开始坐标和结束坐标
        self.start_posX = start_posX
        self.start_posY = start_posY
        self.end_posX = end_posX
        self.end_posY = end_posY
        #颜色,速度,类型等属性
        self.color = color
        self.steep = steep
        self.type = type
        self.WIDTH = self.start_posX - self.end_posX
    #绘制方法
    def draw(self):
        pygame.draw.line(canvas, self.color,(self.start_posX,self.start_posY),
                         (self.end_posX,self.end_posY), self.width)
    #移动方法
    def move(self):
        if self.type == 1:
            self.start_posY += self.steep
            self.end_posY += self.steep
        elif self.type == 2:
            self.start_posX += self.steep
            self.end_posX += self.steep
        elif self.type == 3:
            self.start_posY -= self.steep
            self.end_posY -= self.steep
        elif self.type == 4:
            self.start_posX -= self.steep
            self.end_posX -= self.steep
    #越界方法
    def outOfBounds(self):
        return self.start_posX > 700 or\
             self.start_posY > 700 or\
             self.start_posX < -100 or\
             self.start_posY < -100
    #碰撞方法
    def hit(self, x, y):
        if self.type == 1 or self.type == 3:
            return x >= self.start_posX and\
                 x <= self.end_posX and\
                  y >= self.start_posY and\
                   y <= self.start_posY + self.width
        elif self.type == 2 or self.type == 4:
            return x >= self.start_posX and\
                 x <= self.start_posX + self.width and\
                  y >= self.start_posY and\
                   y <= self.end_posY
    
#调用
Enemy(5,WHITE,7,1,0,0,40,40)

#事件检测方法
def handleEvent():
    global state,TIMELATER,IsPlus,IsWrite,IsAgain
    #循环事件
    for event in pygame.event.get():
        #退出
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        #鼠标左键按下
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            mouseX = event.pos[0]
            mouseY = event.pos[1]
            if state == STATES["START"]:
                #鼠标位置获取
                if 35 <= mouseX <= 100 and 390 <= mouseY <= 420:
                    state = STATES["SETUP"]
                elif 140 <= mouseX <= 250 and 270 <= mouseY <= 320:
                    #设置开始时间
                    TIMELATER = time.time()
                    #状态跳转
                    state = STATES["RUNNING1"]
                elif 340 <= mouseX <= 450 and 270 <= mouseY <= 320:
                    #设置开始时间
                    TIMELATER = time.time()
                    #状态跳转
                    state = STATES["RUNNING2"]
                else:
                    pass
            elif state == STATES["SETUP"]:
                if windowWIDTH - 110 <= mouseX <= windowWIDTH - 40 and 35 <= mouseY <= 60:
                    findMusic()
                elif windowWIDTH - 110 <= mouseX <= windowWIDTH - 40 and 65 <= mouseY <= 90:
                    changeInterval()
                elif windowWIDTH - 110 <= mouseX <= windowWIDTH - 40 and 95 <= mouseY <= 130:
                    changeSInterval()
                else:
                    #状态跳转
                    state = STATES["START"]
        #鼠标移动,判断出界
        if event.type == pygame.MOUSEMOTION:
            mouseX = event.pos[0]
            mouseY = event.pos[1]
            #isMouseOut方法
            if isMouseOut(mouseX, mouseY):
                if state == STATES["RUNNING1"] or state == STATES["RUNNING2"]:
                    secondsList.append(timeLater())
                    state = STATES["GAME_OVER"]
        #键盘按下
        if event.type == pygame.KEYDOWN:
            #Esc键
            if event.key == pygame.K_ESCAPE:
                #返回主页
                if state == STATES["RUNNING1"] or state == STATES["RUNNING2"]:
                    state = STATES["START"]
                    IsAgain = True
                #退出
                elif state == STATES["START"] or state == STATES["GAME_OVER"]:
                    pygame.quit()
                    sys.exit()
            #R键重开
            elif event.key == pygame.K_r:
                if state == STATES["GAME_OVER"]:
                    state = STATES["START"]
                    #重新设置
                    IsPlus = True
                    IsWrite = True
                    IsAgain = True
                    
#音乐检测方法
# def handleMusic():
#     #检查是否正在播放音乐
#     if pygame.mixer.music.get_busy() == False:
#         pygame.mixer.music.play() 

#工具方法-寻找指定窗口
def findTitle(window_title):
    '''
    查找指定标题窗口句柄
    @param window_title: 标题名
    @return: 窗口句柄
    '''
    hWndList = []
    # 函数功能:该函数枚举所有屏幕上的顶层窗口,办法是先将句柄传给每一个窗口,然后再传送给应用程序定义的回调函数。
    win32gui.EnumWindows(lambda hWnd, param: param.append(hWnd), hWndList)
    for hwnd in hWndList:
        # 函数功能:该函数获得指定窗口所属的类的类名。
        # clsname = win32gui.GetClassName(hwnd)
        # 函数功能:该函数将指定窗口的标题条文本(如果存在)拷贝到一个缓存区内
        title = win32gui.GetWindowText(hwnd)
        if (title == window_title):
            break
    #返回参数
    return hwnd
 
hwnd = findTitle(window_title)
def Get_coordinates():               #工具方法-获取鼠标坐标
    #全局设置
    global pos_x,pos_y
    #获取鼠标坐标
    p = win32api.GetCursorPos()
    #  GetWindowRect 获得整个窗口的范围矩形,窗口的边框、标题栏、滚动条及菜单等都在这个矩形内 
    x,y,w,h = win32gui.GetWindowRect(hwnd)
    # 鼠标坐标减去指定窗口坐标为鼠标在窗口中的坐标值
    pos_x = p[0] - x
    pos_y = p[1] - y
            
def isActionTime(lastTime, interval):#工具方法-判断时间间隔是否到了
    if lastTime == 0:
        return True
    currentTime = time.time()
    return currentTime - lastTime >= interval

def isMouseOut(x, y):                #工具方法-判断鼠标是否越界
    if x >= 570 or x <= 30 or y > 430 or y <= 30:
        return True
    else:
        return False
    
def findNumValue(list=[]):           #工具方法-寻找最大的分数值
    for i in range(len(list)-1):
        for j in range(len(list)-1-i):
            if list[j]>list[j+1]:
                temp=list[j]
                list[j]=list[j+1]
                list[j+1]=temp
    #返回参数
    return list[len(list)-1]

def findMusic():                     #工具方法-打开音乐列表并选择播放音乐
    global filePath,fileName
    #这里借用了tkinter的filedialog模块
    #initialdir是指定打开路径,filetypes筛选了MP3,WAV,PCM三个格式的文件
    filePath = filedialog.askopenfilename(title = "choose a Music",
                                          initialdir = "C:/",
                                          filetypes=[("MP3","mp3"),
                                                     ("WAV","wav"),
                                                     ("PCM","pcm")])
    if len(filePath) != 0:
        #加载音乐并播放
        track = pygame.mixer.music.load(filePath)
        pygame.mixer.music.play()
        #修改音乐名,split为字符串分割方法
        fileName = filePath.split("-")[1].split(".")[0]
    
def changeInterval():                #工具方法-修改MODE1的参数
    global interval
    try:
        #输入参数
        interval = float(gui.enterbox("Please input a float about the Interval:\n(>= 0.2 and <= 2.1):"))
        #参数不合格
        while interval < 0.2 or interval >= 2.1:
            if interval >= 2.1:
                interval = float(gui.enterbox("The value is too large.\nPlease input a float about the Interval:\n(>= 0.2 and <= 2.1)"))
            else:
                interval = float(gui.enterbox("The value is too small.\nPlease input a float about the Interval:\n(>= 0.2 and <= 2.1)"))
    except:
        #没有输入
        interval = 0.7
        
def changeSInterval():               #工具方法-修改MODE2的参数
    global interval_m2
    try:
        #输入参数
        interval_m2 = float(gui.enterbox("Please input a float about the Interval:\n(>= 0.3 and <= 1):"))
        #参数不合格
        while interval_m2 < 0.3 or interval_m2 > 1:
            if interval_m2 > 1:
                interval_m2 = float(gui.enterbox("The value is too large.\nPlease input a float about the Interval:\n(>= 0.3 and <= 1)"))
            else:
                interval_m2 = float(gui.enterbox("The value is too small.\nPlease input a float about the Interval:\n(>= 0.3 and <= 1)"))
    except:
        #没有输入
        interval_m2 = 0.5
    
def timeLater():                     #工具方法-游戏时间获取
    global TimeLater,TIMELATER
    TimeLater = time.time()
    Time = TimeLater - TIMELATER
    Time = int(Time)
    #返回参数
    return Time

def drawLinesBounds():      #边界绘制方法
    WID_1 = pygame.draw.line(canvas, BLUE, (30, 30), (windowWIDTH-30, 30), 7)
    HEI_1 = pygame.draw.line(canvas, BLUE, (30, 30), (30, windowHEIGHT-30), 7)
    HEI_2 = pygame.draw.line(canvas, BLUE, (windowWIDTH-30, windowHEIGHT-30), 
                             (windowWIDTH-30, 30), 7)
    WID_2 = pygame.draw.line(canvas, BLUE, (windowWIDTH-30, 
                                            windowHEIGHT-30), 
                             (30, windowHEIGHT-30), 7)
    
def writeWords():           #文字方法-游戏开始提示
    pressKeySurf = BASICFONT.render("Press a mouse in 'MODE' to play.", True, WHITE)
    pressKeyRect = pressKeySurf.get_rect()
    pressKeyRect.topleft = (windowWIDTH - 290, windowHEIGHT - 20)
    canvas.blit(pressKeySurf, pressKeyRect)
    pressKeySurf1 = BASICFONT_M.render('MODE 1', True, WHITE)
    pressKeyRect1 = pressKeySurf1.get_rect()
    pressKeyRect1.topleft = (140,270)
    canvas.blit(pressKeySurf1, pressKeyRect1)
    pressKeySurf2 = BASICFONT_M.render('MODE 2', True, WHITE)
    pressKeyRect2 = pressKeySurf2.get_rect()
    pressKeyRect2.topleft = (340,270)
    canvas.blit(pressKeySurf2, pressKeyRect2)
    
def writeStart():           #文字方法-START状态游戏界面文字书写
    global pressKeySurf3
    #游戏标题
    pressKeySurf1 = BASICFONT_B.render('Avoid obstacles', True, WHITE)
    pressKeyRect1 = pressKeySurf1.get_rect()
    pressKeyRect1.topleft = (90, 150)
    canvas.blit(pressKeySurf1, pressKeyRect1)
    #鼠标位置提示
    pressKeySurf2 = BASICFONT.render('Please move the mouse into the blue box',
                                      True, WHITE)
    pressKeyRect2 = pressKeySurf2.get_rect()
    pressKeyRect2.topleft = (170, 220)
    canvas.blit(pressKeySurf2, pressKeyRect2)
    #最大分数
    if len(secondsList) == 0:
        pressKeySurf3 = BASICFONT.render('Best score:0', True, WHITE)
    else:
        score = findNumValue(secondsList)
        pressKeySurf3 = BASICFONT.render('Best score:' + str(score), True, WHITE)
    pressKeyRect3 = pressKeySurf3.get_rect()
    pressKeyRect3.topleft = (90, 130)
    canvas.blit(pressKeySurf3, pressKeyRect3)
    
def writeTip():             #文字方法-书写RUNNING状态的提示
    #提示游戏已经开始
    pressKeySurf1 = BASICFONT.render('Game Already Started', True, WHITE)
    pressKeyRect1 = pressKeySurf1.get_rect()
    pressKeyRect1.topleft = (windowWIDTH - 210, windowHEIGHT - 20)
    canvas.blit(pressKeySurf1, pressKeyRect1)
    #时间
    pressKeySurf2 = BASICFONT.render('Time:' + str(timeLater()), True, WHITE)
    pressKeyRect2 = pressKeySurf2.get_rect()
    pressKeyRect2.topleft = (5, 5)
    canvas.blit(pressKeySurf2, pressKeyRect2)
    #等级
    if timeLater() <= 15:
        pressKeySurf = BASICFONT.render('Grade:Bad', True, WHITE)
    elif timeLater() <= 25:
        pressKeySurf = BASICFONT.render('Grade:Commonly', True, WHITE)
    elif timeLater() <= 40:
        pressKeySurf = BASICFONT.render('Grade:Good', True, LIGHTYELLOW)
    elif timeLater() <= 50:
        pressKeySurf = BASICFONT.render('Grade:Nice', True, LIGHTYELLOW)
    elif timeLater() <= 60:
        pressKeySurf = BASICFONT.render('Grade:Great!', True, YELLOW)
    elif timeLater() <= 80:
        pressKeySurf = BASICFONT.render('Grade:Against The Sky!', True, YELLOW)
    elif timeLater() <= 100:
        pressKeySurf = BASICFONT.render('Grade:Legend!', True, ORANGE)
    else:
        pressKeySurf = BASICFONT.render('Grade:Invincible!!', True, ORANGE)
    pressKeyRect = pressKeySurf.get_rect()
    pressKeyRect.topleft = (125, 5)
    canvas.blit(pressKeySurf, pressKeyRect)
    
def writeTip_EXIT():        #文字方法-退出提示
    pressKeySurf1 = BASICFONT.render('Press a Esc to exit.', True, WHITE)
    pressKeyRect1 = pressKeySurf1.get_rect()
    pressKeyRect1.topleft = (5, windowHEIGHT - 20)
    canvas.blit(pressKeySurf1, pressKeyRect1)
    
def writeTip_EXIT_Reopen(): #文字方法-重开和退出提示
    pressKeySurf1 = BASICFONT.render('Press a Esc to exit.', True, WHITE)
    pressKeyRect1 = pressKeySurf1.get_rect()
    pressKeyRect1.topleft = (5, windowHEIGHT - 20)
    canvas.blit(pressKeySurf1, pressKeyRect1)
    #提示按R重开
    pressKeySurf2 = BASICFONT.render('Press a key R to Reopen.', True, WHITE)
    pressKeyRect2 = pressKeySurf2.get_rect()
    pressKeyRect2.topleft = (windowWIDTH - 230, windowHEIGHT - 20)
    canvas.blit(pressKeySurf2, pressKeyRect2)
    
def writeLose():            #文字方法-游戏失败提示
    pressKeySurf2 = BASICFONT_B.render('You failed!', True, WHITE)
    pressKeyRect2 = pressKeySurf2.get_rect()
    pressKeyRect2.topleft = (150, 200)
    canvas.blit(pressKeySurf2, pressKeyRect2)
    
def writeLoseTime():        #文字方法-书写存活时间
    global IsPlus,c
    if IsPlus:
        content = timeLater()
        if content <= 1:
            pressKeySurf = BASICFONT.render('You survived ' + str(content) + " second", True, WHITE)
        else:
            pressKeySurf = BASICFONT.render('You survived ' + str(content) + " seconds", True, WHITE)
        pressKeyRect = pressKeySurf.get_rect()
        pressKeyRect.topleft = (154, 180)
        canvas.blit(pressKeySurf, pressKeyRect)
        c = content
        IsPlus = False
    else:
        if c <= 1:
            pressKeySurf = BASICFONT.render('You survived ' + str(c) + " second", True, WHITE)
        else:
            pressKeySurf = BASICFONT.render('You survived ' + str(c) + " seconds", True, WHITE)
        pressKeyRect = pressKeySurf.get_rect()
        pressKeyRect.topleft = (150, 180)
        canvas.blit(pressKeySurf, pressKeyRect)
        
def writeLoseEncourage():   #文字方法-鼓励文字提示
    pressKeySurf = BASICFONT.render("Don't give up,keep working hard!", True, WHITE)
    pressKeyRect = pressKeySurf.get_rect()
    pressKeyRect.topleft = (154, 275)
    canvas.blit(pressKeySurf, pressKeyRect)
        
def writeLoseGrade():       #文字方法-等级文字提示
    global IsWrite,SpressKeySurf
    if IsWrite:
        if timeLater() <= 15:
            SpressKeySurf = BASICFONT.render('Grade:Bad', True, WHITE)
        elif timeLater() <= 25:
            SpressKeySurf = BASICFONT.render('Grade:Commonly', True, WHITE)
        elif timeLater() <= 40:
            SpressKeySurf = BASICFONT.render('Grade:Good', True, LIGHTYELLOW)
        elif timeLater() <= 50:
            SpressKeySurf = BASICFONT.render('Grade:Nice', True, LIGHTYELLOW)
        elif timeLater() <= 60:
            SpressKeySurf = BASICFONT.render('Grade:Great!', True, YELLOW)
        elif timeLater() <= 80:
            SpressKeySurf = BASICFONT.render('Grade:Against The Sky!', True, YELLOW)
        elif timeLater() <= 100:
            SpressKeySurf = BASICFONT.render('Grade:Legend!', True, ORANGE)
        else:
            SpressKeySurf = BASICFONT.render('Grade:Invincible!!', True, ORANGE)
        SpressKeyRect = SpressKeySurf.get_rect()
        SpressKeyRect.topleft = (154, 255)
        canvas.blit(SpressKeySurf, SpressKeyRect)
        IsWrite = False
    else:
        SpressKeyRect = SpressKeySurf.get_rect()
        SpressKeyRect.topleft = (154, 255)
        canvas.blit(SpressKeySurf, SpressKeyRect)
        
def writeBeyondRecord():    #文字方法-新纪录提示
    if len(secondsList) > 0:
        timeNow = timeLater()
        timeAgo = findNumValue(secondsList)
        if timeNow > timeAgo:
            pressKeySurf = BASICFONT.render("Beyond Record!", True, ORANGE)
            pressKeyRect = pressKeySurf.get_rect()
            pressKeyRect.topleft = (375, 5)
            canvas.blit(pressKeySurf, pressKeyRect)
            
def writeSet_up():          #文字方法-设置
    pressKeySurf = BASICFONT.render("Set Up", True, WHITE)
    pressKeyRect = pressKeySurf.get_rect()
    pressKeyRect.topleft = (38, windowHEIGHT - 53)
    canvas.blit(pressKeySurf, pressKeyRect)
    
def writeSetContent():
    pressKeySurf1 = BASICFONT.render("background music:"+fileName, True, WHITE)
    pressKeyRect1 = pressKeySurf1.get_rect()
    pressKeyRect1.topleft = (40,40)
    canvas.blit(pressKeySurf1, pressKeyRect1)
    surf1change = BASICFONT.render("Change", True, WHITE)
    rect1change = surf1change.get_rect()
    rect1change.topleft = (windowWIDTH - 110,40)
    canvas.blit(surf1change, rect1change)
    pressKeySurf2 = BASICFONT.render("MODE 1 Block update time:"+str(interval), True, WHITE)
    pressKeyRect2 = pressKeySurf2.get_rect()
    pressKeyRect2.topleft = (40,70)
    canvas.blit(pressKeySurf2, pressKeyRect2)
    surf2change = BASICFONT.render("Change", True, WHITE)
    rect2change = surf2change.get_rect()
    rect2change.topleft = (windowWIDTH - 110,70)
    canvas.blit(surf2change, rect2change)
    pressKeySurf3 = BASICFONT.render("MODE 2 Block update time:"+str(interval_m2), True, WHITE)
    pressKeyRect3 = pressKeySurf3.get_rect()
    pressKeyRect3.topleft = (40,100)
    canvas.blit(pressKeySurf3, pressKeyRect3)
    surf3change = BASICFONT.render("Change", True, WHITE)
    rect3change = surf3change.get_rect()
    rect3change.topleft = (windowWIDTH - 110,100)
    canvas.blit(surf3change, rect3change)
    
def deleteComponent():      #组件删除方法
    for i in range(len(enemies) - 1, -1, -1):
        x = enemies[i]
        if x.outOfBounds():
            enemies.remove(x)
            
def paint():                #MODE1组件绘制方法
    for i in enemies:
        i.draw()
        
def Spaint():               #MODE2组件绘制方法
    for i in Senemies:
        i.draw()
        
def move():                 #MODE1组件移动方法
    for i in enemies:
        i.move()
        
def Smove():                #MODE2组件移动方法
    for i in Senemies:
        i.move()
            
def enterComponent():       #MODE1组件更新方法
    global lastTime
    # 判断是否到了产生的时间
    if not isActionTime(lastTime, interval):
        return
    lastTime = time.time()
    #随机生成属性
    steep = random.randint(3,10)
    type = random.randint(1,4)
    width = random.randint(30,40)
    color = colors[random.randint(0,11)]
    #将属性和位置一一插入方块列表
    if type == 1:
        sX = random.randint(30,570)
        eX = random.randint(30,570)
        while sX >= eX:
            sX = random.randint(30,570)
            eX = random.randint(30,570)
        enemies.append(Enemy(width,color,steep,type,sX,-50,eX,-50))
    elif type == 2:
        sY = random.randint(30,420)
        eY = random.randint(30,420)
        while sY >= eY:
            sY = random.randint(30,420)
            eY = random.randint(30,420)
        enemies.append(Enemy(width,color,steep,type,-30,sY,-30,eY))
    elif type == 3:
        sX = random.randint(30,570)
        eX = random.randint(30,570)
        while sX >= eX:
            sX = random.randint(30,570)
            eX = random.randint(30,570)
        enemies.append(Enemy(width,color,steep,type,sX,500,eX,500))
    elif type == 4:
        sY = random.randint(30,420)
        eY = random.randint(30,420)
        while sY >= eY:
            sY = random.randint(30,420)
            eY = random.randint(30,420)
        enemies.append(Enemy(width,color,steep,type,630,sY,630,eY))
        
def ComponentUpdate():      #MODE2组件更新方法
    global lastTime_m2,Scolor,IsAgain
    # 判断是否到了产生的时间
    if not isActionTime(lastTime_m2, interval_m2):
        return
    lastTime_m2 = time.time()
    width = random.randint(30,40)
    if timeLater() <= 30: Space_between = random.randint(70,200)
    elif timeLater() <= 40: Space_between = random.randint(50,150)
    elif timeLater() <= 60: Space_between = random.randint(35,100)
    elif timeLater() <= 80: Space_between = random.randint(25,75)
    else: Space_between = random.randint(25,50)
    eY = random.randint(80,370)
    sY = eY + Space_between
    if IsAgain:
        Scolor = colors[random.randint(0,11)]
        IsAgain = False
    Senemies.append(Enemy(width,Scolor,5,4,630,30,630,eY))
    Senemies.append(Enemy(width,Scolor,5,4,630,sY,630,windowHEIGHT - 30))
    
        
#碰撞检测方法

def checkHit(x,y):          #检测组件与鼠标之间的碰撞
    global state
#     x,y = pag.position() #返回鼠标的坐标
#     print(x,y)
    for enemy in enemies:
        if enemy.hit(x , y):
            state = STATES["GAME_OVER"]
            #插入分数值
            secondsList.append(timeLater())
    for enemy in Senemies:
        if enemy.hit(x , y):
            state = STATES["GAME_OVER"]
            #插入分数值
            secondsList.append(timeLater())
    
#状态和方法的总控制
def contralState():
    #开始
    if state == STATES["START"]:
        #绘制边界
        drawLinesBounds()
        #书写提示
        writeTip_EXIT()
        writeWords()
        writeStart()
        writeSet_up()
    #运行
    elif state == STATES["RUNNING1"]:
        #绘制边界
        drawLinesBounds()
        #书写提示
        writeTip_EXIT()
        writeTip()
        writeBeyondRecord()
        #组件方法
        enterComponent()
        paint()
        move()
        checkHit(pos_x,pos_y)
    #运行
    elif state == STATES["RUNNING2"]:
        #绘制边界
        drawLinesBounds()
        #书写提示
        writeTip_EXIT()
        writeTip()
        writeBeyondRecord()
        #组件方法
        ComponentUpdate()
        Spaint()
        Smove()
        checkHit(pos_x,pos_y)
    #结束
    elif state == STATES["GAME_OVER"]:
        #绘制边界
        drawLinesBounds()
        #书写提示
        writeTip_EXIT_Reopen()
        writeLose()
        writeLoseTime()
        writeLoseGrade()
        writeLoseEncourage()
        #组件方法(用于清空界面)
        move()
        Smove()
    #设置
    elif state == STATES["SETUP"]:
        #绘制边界
        drawLinesBounds()
        writeSetContent()
        
def MAINLOOP():
    #实时获取鼠标坐标
    Get_coordinates()
    #事件监测方法
    handleEvent()
    #音乐监测方法
    #handleMusic()
    #绘制黑色背景
    canvas.fill((0, 0, 0))
    #状态方法调用
    contralState()
    #屏幕更新和刷新
    pygame.display.update()
    #等待0.01秒后再进行下一次循环
    pygame.time.delay(15)
        
#循环调用控制运行

while True:
    MAINLOOP()

[代码运行效果截图]


躲避方块(英文版) 小游戏


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...