python +pygame 制作五子连珠小游戏

python +pygame 制作五子连珠小游戏

学习python半年了,今天分享一个利用pygame制作的五子连珠游戏。
一、代码:
1.球类,ball.py

"""
球类
"""
import pygame
from pygame.sprite import Sprite
from settings import Settings
import time
from music import iMusic

class Ball(Sprite):

    def __init__(self,id,screen,image_id,preantRect):
        super().__init__()
        """
        初始化球
        :param screen: 屏幕
        :param image: 球的着色
        :param preantRect:所在区域 
        """
        self.ai_settings=Settings
        self.images=self.ai_settings.images
        self.id=id
        self.image_id=image_id
        self.image=self.images[self.image_id]
        self.rect=self.image.get_rect()
        self.rect.center=preantRect.center
        self.screen=screen
        self.x=float(self.rect.x)
        self.y=float(self.rect.y)
        self.music=iMusic('Dou')
        self.draw()


    def draw(self):
        self.screen.blit(self.image,self.rect)



    def move(self,firsti,firstj,endi,endj):

        length=self.ai_settings.length
        endid=endj*10+endi

        # print('firstid:',firstid,'endid:',endid)

        if firsti>endi:
            # self.rect.move(-50,0)
            self.x-=length
            self.rect.x=self.x

            # print('从{0}移动到{1}成功:'.format(firstid, endid))
        elif firsti<endi:
            # self.rect.move(50, 0)
            self.x += length
            self.rect.x = self.x
            # print('从{0}移动到{1}成功:'.format(firstid, endid))
        elif firstj > endj:
            self.y -= length
            self.rect.y = self.y
            # self.rect.move(0,-50)
            # print('从{0}移动到{1}成功:'.format(firstid, endid))
        elif firstj < endj:
            self.y += length
            self.rect.y = self.y
            # print('从{0}移动到{1}成功:'.format(firstid, endid))
        self.id=endid
        # print('id:',self.id,self.rect)
        self.draw()
        self.music.play()
        time.sleep(self.ai_settings.speed)


2.按钮类,button.py

import pygame.font
"""
v2.0
创建内置按钮


"""
class Button():
    def __init__(self,screen,msg):
        """
        初始化按钮
        :param ai_settings: 设置类
        :param screen: 屏幕类
        :param msg: 文字
        
        """
        self.screen=screen
        self.screen_rect=screen.get_rect()
    #   设置按钮的尺寸和其他属性
        self.width=200
        self.height=50
        self.button_color=(0,255,0)
        self.text_color=(255,255,255)
        self.font=pygame.font.SysFont('kaiti',48)
    #     设置按钮的rect属性,并让其居中
        self.rect=pygame.Rect(0,0,self.width,self.height)
        self.rect.center=self.screen_rect.center
    #     按钮的标签只需创建一次
        self.prep_msg(msg)
    def prep_msg(self,msg):
        """
        将msg渲染为图像,并使其在按钮上居中
        :param msg: 要显示的文本
        :return: None
        """
        self.msg_image=self.font.render(
            msg,True,self.text_color,self.button_color)
        self.msg_image_rect=self.msg_image.get_rect()
        self.msg_image_rect.center=self.rect.center
    def draw_button(self):
    #     绘制一个用颜色填充的按钮,再绘制文本
        self.screen.fill(self.button_color,self.rect)
        self.screen.blit(self.msg_image,self.msg_image_rect)

3.主函数类,是游戏的精华所在,game_function.py

"""
主函数类
"""
from ball import Ball
from settings import Settings
# from score import Score

# from pygame.mixer import music
from configobj import ConfigObj

from music import iMusic

import pygame
import pygame.gfxdraw
import random

import time

class Function():
    def __init__(self):
        self.ai_settings = Settings
        pygame.display.set_caption('五子连珠'+self.ai_settings.version)
        self.screen = pygame.display.set_mode(
            (self.ai_settings.screen_height,self.ai_settings.screen_width))
        self.screen.fill(self.ai_settings.background_color)
        # 难度控制
        self.difficulty = self.ai_settings.difficulty
        # 游戏区的设置
        # 1.网格长度
        self.length=self.ai_settings.length
        # 2.设置游戏区的范围
        self.rect=pygame.Rect(20,20,self.length*10,self.length*10)
        # 3.存储网格位置列表
        self.rect_list = []
        # 4.存储网格背景色列表
        self.color_list = []
        # 游戏主数据列
        # 1.存储球移动路径的列表
        self.ball_list=[]
        # 2.存储没有球的区域列表
        self.surplus_ball_list=[]
        # 3.存储各个球所在位置的列表
        self.main_ball_list=[]
        # 4.存储Ball类的列表
        self.balls=pygame.sprite.Group()
        # 5.存储ball_move_list列表
        self.ball_move_list=[]
        # 6.判断是否要移动球
        self.isMove=False

        # 6.1判断球是否被选中
        self.isChoose=False
        # 7.存储移动前后的id
        self.ball_first_id=-1
        self.ball_end_id=-1

        # 8.存储可删除球的id
        self.remove_ball_list=[]
        # 设置文字
        self.font=pygame.font.SysFont('kaiti',30)

        # 初始总分
        self.Main_score=0

        # 最高分
        self.Max_score=0
        # 显示屏幕
        self.screen_draw()
        # 显示球列表
        self.images = ['r','g','b', 'y', 'p','o','w']

        self.Move_music=iMusic('Move')
        self.Great_music=iMusic('Great')
        self.Fantastic_music = iMusic('Fantastic')
        self.Dou_music=iMusic('Dou')

    #     next
        self.next_ball_list=[]

        self.next_rect=[]

        self.file_list = []


    def read_maxscore_file(self):

        inifile=ConfigObj('data.ini',encoding='UTF8')


        temp_high_score=inifile['data']['hihg_score']
        # print(tempdata)

        self.Max_score=eval(temp_high_score)

    def write_maxscore_file(self):

        inifile=ConfigObj('data.ini',encoding='UTF8')


        inifile['data']['hihg_score']=self.Max_score
        # print(tempdata)

        # self.Max_score=temp_high_score
        inifile.write()

    def read_ball_scro_file(self):

        inifile = ConfigObj('data.ini', encoding='UTF8')

        temp_ball_list = inifile['Main']['ball_list']
        print(temp_ball_list)
        temp_ball_list=list(map(int,temp_ball_list))
        print(temp_ball_list)

        temp_score=int(inifile['Main']['score'])
        # temp_high_score = inifile['hihg_score'][hihg_score]
        # print(tempdata)
        if len(temp_ball_list)!=0 and temp_score!=0:
            self.main_ball_list = temp_ball_list
            self.Main_score=temp_score
        # self.Max_score = temp_high_score

    def write_ball_scro_file(self):

        inifile = ConfigObj('data.ini', encoding='UTF8')

        if not self.game_over():
            print(self.main_ball_list)
            inifile['Main']['ball_list']=self.main_ball_list

            inifile['Main']['score']=self.Main_score
            inifile.write()
        # temp_high_score = inifile['hihg_score'][hihg_score]
        # print(tempdata)

            # self.Max_score = temp_high_score

    def game_over(self):
        isgameover=False
        if len(self.surplus_ball_list)==0:
            isgameover=True
            print('游戏结束了!')
        return isgameover

    def show_next_ball(self):

        for i in range(3):
            if i==1:
                temp_color=self.ai_settings.foreground_color
            else:
                temp_color=self.ai_settings.high_color

            temp_rect=pygame.Rect(660+i*self.length,230,self.length,self.length)

            self.next_rect[i]=temp_rect

            self.screen.fill(temp_color,temp_rect)


            next_ball=self.next_ball_list[i][1]

            images = self.ai_settings.images

            image_index=self.images[next_ball]

            # print(image_index)

            temp_image=images[image_index]
            temp_image.set_alpha(255)




            temp_image_rect=temp_image.get_rect()

            temp_image_rect.center=temp_rect.center

            self.screen.blit(temp_image, temp_image_rect)


            if self.ai_settings.is_show_next_in_game:

                image_in_game = images[image_index]
                rect_image_in_game=image_in_game.get_rect()
                image_in_game.set_alpha(80)
                temp_rect_in_game=self.rect_list[self.next_ball_list[i][0]]
                rect_image_in_game.center=temp_rect_in_game.center
                self.screen.blit(image_in_game, rect_image_in_game)
                image_in_game.set_alpha(255)






        # print(self.next_rect)

    def screen_draw(self):
        # 显示屏幕

        self.screen.fill(self.ai_settings.face_color, self.rect)

        self.game_draw()

    def game_draw(self):
        # 绘制游戏区
        self.rect_list = []
        self.color_list = []
        self.temp_color = (0, 0, 0)
        for i in range(10):
            for j in range(10):
                t = (i + j) % 2
                if t:
                    self.temp_color = self.ai_settings.foreground_color
                else:
                    self.temp_color = self.ai_settings.high_color
                self.temp_rect = pygame.Rect(j * self.length + 20, i * self.length + 20,
                                             self.length, self.length)
                self.rect_list.append(self.temp_rect)

                self.color_list.append(self.temp_color)

                self.screen.fill(self.temp_color, self.temp_rect)
        pygame.gfxdraw.rectangle(self.screen,
                                 self.ai_settings.game_rect,
                                 self.ai_settings.angle_color)

    def Event(self):
        # music_time=music.get_pos
        # # loop,start=divmod(music_time,300)
        # tMusic = music.load(r'music\BGM.mp3')
        # music.play(-1)

        # 鼠标事件控制
        self.events = pygame.event.get()
        for event in self.events:
            # 退出游戏
            if event.type == pygame.QUIT:
                self.write_ball_scro_file()

                # song=iMusic('Over')
                quit()
            if event.type==pygame.MOUSEBUTTONDOWN:
                # 按下鼠标

                if self.rect.collidepoint(pygame.mouse.get_pos()):
                    # 检测鼠标位置是否在某个单元格
                    self.mouse_down_event()
            if event.type==pygame.MOUSEMOTION:
                # 检测鼠标移动时所显示的鼠标样式
                self.mouse_motion_event()


    def mouse_motion_event(self):
        # 鼠标移动事件
        if self.rect.collidepoint(pygame.mouse.get_pos()):
            temp_pos = pygame.mouse.get_pos()
            rect = self.xy_to_rect(temp_pos[0], temp_pos[1])
            id = self.rect_to_int(rect)
            if self.main_ball_list[id] != -9:
                pygame.mouse.set_system_cursor(pygame.SYSTEM_CURSOR_HAND)

            elif self.ball_list[id] == -1 and not self.isMove:
                pygame.mouse.set_system_cursor(pygame.SYSTEM_CURSOR_NO)
            else:
                pygame.mouse.set_system_cursor(pygame.SYSTEM_CURSOR_ARROW)
        else:
            pygame.mouse.set_system_cursor(pygame.SYSTEM_CURSOR_ARROW)

    def mouse_down_event(self):
        # 鼠标按下事件
        # 1.先进行屏幕绘制初始化
        self.screen_draw()
        # 2.如果球列表里有球存在,则在屏幕上显示所有的球
        if len(self.balls)!=0:
            self.balls.draw(self.screen)
        # 3.获取鼠标位置
        temp_pos=pygame.mouse.get_pos()
        # 4.将鼠标位置转化为rect
        rect=self.xy_to_rect(temp_pos[0],temp_pos[1])
        # 5.将rect转化为id
        id=self.rect_to_int(rect)
        # 高亮显示选中的单元格
        self.hight_choose_rect(rect)
        # 6.如果主列表中的list中有球的时候,则屏幕rect上有球
        if self.main_ball_list[id]!=-9:
            self.Dou_music.play()
            # 7.可移动为:否

            self.isMove=False
        #   球处于选中状态
            self.isChoose=True
        else:
            if self.ball_list[id]!=-1 and self.isChoose==True:
                # 8.主列表中没有球,并且该位置有可移动的数字时,可移动为:是
                self.isMove = True
            # self.isChoose = False
        # if self.isChoose:
        #     self.isMove=True

        if self.isMove and self.isChoose:
            # 如果可移动,
            # 1.获取移动后的id位置
            self.ball_end_id=id
            # 2.移动开始
            self.ball_move(self.ball_first_id,self.ball_end_id)

            self.Move_music.play()
            # tMusic=music.load('music\Move.mp3')
            # music.play(0,3,100)

            end_rect=self.id_to_rect(self.ball_end_id)
            self.hight_choose_rect(end_rect)
            # 检查可消除list
            # self.check_remove_ball_list(self.ball_end_id)
            # 删除连成五子的棋子
            isRemove=self.remove_ball(self.ball_end_id)


            # isRemove为True,False为删除成功与否
            # 1.对可移动数字列表进行置空,此时有球的位置不为空
            self.ball_list_empty()
            if isRemove:


                # tMusic = music.load(r'music\reMove.mp3')
                # music.play(0, 2, 100)


                self.screen.fill(self.ai_settings.background_color)

                # 删除后刷新屏幕
                self.screen_draw()
                self.balls.draw(self.screen)
                # 记录总分
                self.Max_score = max(self.Max_score, self.Main_score)
                self.write_maxscore_file()
                self.print_score()
                # pygame.display.flip()+


            else:
                # 选中状态为否
                self.isChoose=False
                # 2.随机设置球色及位置
                self.show_random_ball()

            # 移动后可移动为:否
            # self.isMove=False
        elif not self.isMove and self.isChoose:
            # 如果可移动为:否,选中状态为是
            # 1.对可移动数字列表进行置空,此时有球的位置不为空
            self.ball_list_empty()
            # # 2.随机设置球色及位置
            # self.set_random_ball()
            # 3.设置球所在的位置的ball_list值为0
            self.ball_list[id] = 0
            for n in range(100):
                self.chcek_ball_list(n)
                # 4.设置ball_list列表,每个位置都显示从开始到本位置所有的步数
            self.print_ball_list()
            # 5.显示ball_list列表
            self.ball_first_id=id
            # 6.设置起始位置id

        self.show_next_ball()
        self.balls.draw(self.screen)

    def set_difficulty(self):

        if self.Main_score in range(0,2000):
            self.difficulty=1
        elif self.Main_score in range(2000,6000):
            self.difficulty=2
        elif self.Main_score in range(6000,10000):
            self.difficulty=3
        elif self.Main_score in range(10000,30000):
            self.difficulty=4
        elif self.Main_score in range(30000,60000):
            self.difficulty=5
        elif self.Main_score in range(60000,100000):
            self.difficulty=6
        else:
            self.difficulty=7

    def get_difficulty_name(self):
        d_name=['一级入门魂士','二级初级魂师','三级中级魂宗',
                '四级高级魂王','五级超级魂帝','六级顶级魂斗罗',
                '至尊封号斗罗']
        index=self.difficulty-1
        return d_name[index]

    def print_score(self):
        self.set_difficulty()
        self.get_difficulty_name()
        self.prep_msg(self.get_difficulty_name(),
                      self.ai_settings.rect_score.move(0,50))

        self.prep_msg(str(self.Main_score),
                      self.ai_settings.rect_score)

        self.prep_msg(str(self.Main_score),
                      self.ai_settings.rect_score)

        self.prep_msg('最高分:'+str(self.Max_score),
                      self.ai_settings.rect_score.move(0, 100))
        self.prep_msg('下一次',
                      self.ai_settings.rect_score.move(0, 150))

    def hight_choose_rect(self,rect):
        pygame.draw.rect(self.screen, self.ai_settings.choose_color, rect)

    def chcek_ball_list(self,num):
        # 检查ball_list列表
        # num 代表列表中的某个数字
        if num in self.ball_list:
            # 1.置空临时列表
            temp_list=[]

            for id in range(100):
                # 2.把所在数字为num的id加载到临时列表中
                if self.ball_list[id]==num:
                    temp_list.append(id)
            for m in temp_list:
                # 3.对临时列表里进行处理,将符合num的ID进行转化
                # 4.

                ij=self.id_to_ij(m)
                i,j=ij[0],ij[1]
                self.check_pass(i,j)
            # print(self.ball_list)

    def check_pass(self, i, j):

        id = self.ij_to_id(i, j)
        if self.ball_list[id]<-1:
            return
        num = self.ball_list[id] + 1
        # print(num)
        if i + 1 in range(10) and j in range(10):
            id1 = self.ij_to_id(i + 1, j)
            if self.ball_list[id1] == -1 or self.ball_list[id1] >= num:
                self.ball_list[id1] = num

        if i in range(10) and j - 1 in range(10):
            id4 = self.ij_to_id(i, j - 1)
            if self.ball_list[id4] == -1 or self.ball_list[id4] >= num:
                self.ball_list[id4] = num

        if i - 1 in range(10) and j in range(10):
            id2 = self.ij_to_id(i - 1, j)
            if self.ball_list[id2] == -1 or self.ball_list[id2] >= num:
                self.ball_list[id2] = num

        if i in range(10) and j + 1 in range(10):
            id3 = self.ij_to_id(i, j + 1)
            if self.ball_list[id3] == -1 or self.ball_list[id3] >= num:
                self.ball_list[id3] = num

    def print_ball_list(self):
        # for i in range(100):
        #     self.prep_msg('',self.id_to_rect(i))
        # self.screen_draw()
        for j in range(100):
            if not self.ball_list[j]==-1:
                self.prep_msg(self.ball_list[j],self.id_to_rect(j))
        # pygame.display.flip()
                # self.print_ball(j)

    def show_main_ball_list_ball(self):
        tid=0
        for i in self.main_ball_list:
            tid += 1
            if i==-9:
                continue
            rect=self.rect_list[tid-1]
            image=self.images[-i-2]
            b1=Ball(tid-1,self.screen,image,rect)
            self.balls.add(b1)
            self.screen_draw()
            self.balls.draw(self.screen)

    def print_ball(self,id):
        temp=-self.main_ball_list[id]-2
        # print(temp)
        if  temp in range(self.difficulty):
            rect=self.rect_list[id]
            image=self.images[temp]
            if self.get_ball(id)!=None:
                return
            #

            b1=Ball(id,self.screen,image,rect)
            # self.balls[id]=b1
            self.balls.add(b1)
            isRemove=self.remove_ball(id)
            if isRemove:
                self.screen_draw()
                self.balls.draw(self.screen)

    def dell_ball(self,id):
        for ball in self.balls:
            # print('balls_group可用')
            temp_id=ball.id
            print(temp_id)
            if temp_id==id:
                self.balls.remove(ball)
                # print('删除ball:',temp_id)
                # print('self.balls_group_len',len(self.balls))
            pygame.display.update()

    def set_random_ball(self):
        # self.next_ball_list.clear()
        for t in range(3):
            self.surplus_ball_list.clear()
            for m in range(100):
                if self.main_ball_list[m] == -9:
                    self.surplus_ball_list.append(m)
            s=len(self.surplus_ball_list)
            # print(self.surplus_ball_list)
            if s>0:
                n=random.randrange(s)
                r=self.surplus_ball_list[n]
                # print(r)
                # if self.main_ball_list[r] !=-9:
                #     self.set_random_ball()
                i=random.randrange(self.difficulty)
                self.next_ball_list[t]=[r,i]
                # print(i)

                # self.ball_list[r]=-(i+2)
                # rect=self.rect_list[r]
                # b1=Ball(self.screen,self.images[i],rect)
            else:
                break
        print(self.next_ball_list)

    def show_random_ball(self):
        for t in range(3):
            self.surplus_ball_list.clear()
            for m in range(100):
                if self.main_ball_list[m] == -9:
                    self.surplus_ball_list.append(m)
            s=len(self.surplus_ball_list)
            # print(self.surplus_ball_list)
            if s>0:
                n=random.randrange(s)
                temp_r=self.surplus_ball_list[n]
                # print(r)
                # if self.main_ball_list[r] !=-9:
                #     self.set_random_ball()

                i=self.next_ball_list[t][1]

                r=self.next_ball_list[t][0]
                if not r in self.surplus_ball_list:
                    r=temp_r

                self.main_ball_list[r]=-(i+2)
                self.ball_list[r]=-(i+2)
                self.print_ball(r)
                # self.ball_list[r]=-(i+2)
                # rect=self.rect_list[r]
                # b1=Ball(self.screen,self.images[i],rect)
            else:
                break
        self.set_random_ball()

    def set_ground(self):
        self.main_ball_list=[]
        self.rect_list = []
        self.color_list = []
        self.temp_color = (0, 0, 0)
        for i in range(10):
            for j in range(10):
                t = (i + j) % 2
                if t:
                    self.temp_color = self.ai_settings.foreground_color
                else:
                    self.temp_color = self.ai_settings.high_color
                self.temp_rect = pygame.Rect(j * self.length + 20, i * self.length + 20,
                                             self.length, self.length)
                self.rect_list.append(self.temp_rect)

                self.color_list.append(self.temp_color)

                self.main_ball_list.append(-9)

                self.ball_list.append(-1)
                self.screen.fill(self.temp_color, self.temp_rect)
            if i<3:
                self.next_ball_list.append(None)
                self.next_rect.append(None)

        self.read_ball_scro_file()
        self.ball_list_empty()
        self.show_main_ball_list_ball()

        self.read_maxscore_file()

        self.set_random_ball()
        self.show_random_ball()
        self.show_next_ball()
        # score=Score(self.screen,self.Main_score,self.ai_settings.rect_score)
        # self.prep_msg(self.Main_score,self.ai_settings.rect_score)

    def prep_msg(self, msg, rect):
        pygame.font.init()


        temp_image = self.font.render(str(msg), True, self.ai_settings.text_color,
                                      None)
        temp_rect = temp_image.get_rect()
        temp_rect.center = rect.center

        self.screen.blit(temp_image, temp_rect)

    def ij_to_rect(self, i, j):
        id=self.ij_to_id(i,j)
        return self.rect_list[id]

    def rect_to_int(self, rect):
        for i in range(100):
            if self.rect_list[i].colliderect(rect):
                return i

    def ij_to_ground_color(self, i, j):
        id=self.ij_to_id(i,j)
        return self.temp_color[id]

    def xy_to_rect(self, x, y):
        for rect in self.rect_list:
            if rect.collidepoint(x, y):
                return rect

    def id_to_ij(self,id):

        j,i=divmod(id,10)
        return i,j

    def ij_to_id(self,i,j):
        return j*10+i

    def id_to_rect(self,id):
        i,j=self.id_to_ij(id)
        return self.ij_to_rect(i,j)

    def ball_list_empty(self):
        # 清空ball_list列表
        self.ball_list.clear()
        for i in range(100):
            self.ball_list.append(-1)
        for j in range(100):
            if self.main_ball_list[j]!=-9:
                self.ball_list[j]=self.main_ball_list[j]

    def ball_move(self,firstid,endid):
        self.get_ball_move_list(firstid,endid)
        for i in range(1,len(self.ball_move_list)):
            fid=self.ball_move_list[i-1]
            fi,fj=self.id_to_ij(fid)
            eid=self.ball_move_list[i]
            ei,ej=self.id_to_ij(eid)
            for ball in self.balls:
                if ball.id==fid:
                    ball.move(fi,fj,ei,ej)
                    self.screen_draw()
                    self.balls.draw(self.screen)
                    self.main_ball_list[eid]=self.main_ball_list[fid]
                    self.main_ball_list[fid]=-9

            pygame.display.update()

    def get_ball_move_list(self,firstid,endid):
        i=0
        self.ball_move_list.clear()
        temp_list=[]
        endnum=self.ball_list[endid]

        while endnum>0 :
            temp_list.append(endid)
            # i+=1
            # print(i,' endnum:', endnum)
            endnum-=1
            endid=self.get_next_id(endid,endnum)
        temp_list.reverse()
        self.ball_move_list.append(firstid)
        self.ball_move_list.extend(temp_list)
        # print(self.ball_move_list)

    def get_next_id(self,id,nextnum):

        if id in range(100):
            ij = self.id_to_ij(id)
            i, j = ij[0], ij[1]
        else:
            # print('错误:',id)
            return

        if i+1 in range(10) and j in range(10):
            id1=self.ij_to_id(i+1,j)
            if self.ball_list[id1]==nextnum:
                return id1
        if i-1 in range(10) and j in range(10):
            id2=self.ij_to_id(i-1,j)
            if self.ball_list[id2]==nextnum:
                return id2
        if i in range(10) and j+1 in range(10):
            id3=self.ij_to_id(i,j+1)
            if self.ball_list[id3]==nextnum:
                return id3
        if i in range(10) and j-1 in range(10):
            id4=self.ij_to_id(i,j-1)
            if self.ball_list[id4]==nextnum:
                return id4

    def remove_ball(self,id):
        # id 为最后一个加载的序号
        canRemove=self.check_remove_ball_list(id)
        # 判断能不能删除
        if not canRemove:
            return canRemove
        num_remove_ball=len(self.remove_ball_list)
        # 删除可消除球
        leve = num_remove_ball - 4
        self.Main_score += num_remove_ball * 20 * leve

        for ball in self.balls:
            tid=ball.id
            if tid in self.remove_ball_list:
                #

                # print('ball.id',tid)
                # print(self.remove_ball_list)

                self.balls.remove(ball)
                # 将主球列表相应位置置空

                self.main_ball_list[tid]=-9
                time.sleep(0.06)
        if len(self.remove_ball_list)>6:
            self.Fantastic_music.play()
        else:
            self.Great_music.play()

        return canRemove

    def check_remove_ball_list(self,id):
        canRemove=False

        Mij=self.id_to_ij(id)
        Mi,Mj=Mij
        main_ball=self.get_ball(id)
        if main_ball==None:
            return
        # 获取balls指定id的主ball
        # 将删除列表置空
        self.remove_ball_list.clear()

        # 设置四个方向的列表
        # 1.左右↔
        RL_list=[]
        # 2.上下↕
        UD_list=[]
        # 3.左上右下↖↘
        LU_RD_list=[]
        # 4.左下右上↙↗
        LD_RU_list=[]


        # 5.临时合并列表
        temp_sum_list=[]

        # 对四个方向进行统计
        # 1.左右
        # 1.1向右加载→
        for i in range(10-Mi):
            Ri=i+Mi
            Rid=self.ij_to_id(Ri,Mj)
            rBall=self.get_ball(Rid)
            if rBall ==None:
                break
            if rBall.image_id==main_ball.image_id:
                RL_list.append(Rid)
            else:
                break
        # 1.2向左加载←
        for i in range(Mi+1):
            Li=Mi-i
            Lid=self.ij_to_id(Li,Mj)
            lBall=self.get_ball(Lid)
            if lBall==None:
                break
            if lBall.image_id==main_ball.image_id:
                RL_list.append(Lid)
            else:
                break
        RL_list=list(set(RL_list))
        print ('RL_list1:',RL_list)
        if len(RL_list)<5:
            RL_list.clear()
        print('RL_list2:', RL_list)

        # 2.上下加载↕
        # 2.1向下↓
        for j in range(10 - Mj):
            Dj = j + Mj
            Did = self.ij_to_id(Mi, Dj)
            dBall = self.get_ball(Did)
            if dBall == None:
                break
            if dBall.image_id == main_ball.image_id:
                UD_list.append(Did)
            else:
                break
        # 2.2向上↑
        for j in range(Mj + 1):
            Uj = Mj - j
            Uid = self.ij_to_id(Mi, Uj)
            uBall = self.get_ball(Uid)
            if uBall == None:
                break
            if uBall.image_id == main_ball.image_id:
                UD_list.append(Uid)
            else:
                break
        UD_list = list(set(UD_list))
        print('UD_list1:', UD_list)
        if len(UD_list) < 5:
            UD_list.clear()
        print('UD_list2:', UD_list)
        # 3.左上右下加载
        # 3.1左上↖
        Mini=min(Mi,Mj)
        for i in range(Mini+1):
            LUj = Mj - i
            LUi=Mi-i
            LUid = self.ij_to_id(LUi, LUj)

            luBall = self.get_ball(LUid)
            if luBall == None:
                break
            if luBall.image_id == main_ball.image_id:
                LU_RD_list.append(LUid)
            else:
                break
        # 3.2右下↘
        minJ=min(10-Mi,10-Mj)
        for j in range(minJ):
            RDi=Mi+j
            RDj=Mj+j

            RDid = self.ij_to_id(RDi, RDj)
            rdBall = self.get_ball(RDid)
            if rdBall == None:
                break
            if rdBall.image_id == main_ball.image_id:
                LU_RD_list.append(RDid)
            else:
                break
        LU_RD_list = list(set(LU_RD_list))
        print('LU_RD_list1:', LU_RD_list)
        if len(LU_RD_list) < 5:
            LU_RD_list.clear()
        print('LU_RD_list2:', LU_RD_list)
        # 4.左下右上加载
        # 4.1左下↙
        MinI = min(Mi+1, 10-Mj)
        for i in range(MinI):
            LDi = Mi - i
            LDj = Mj + i
            LDid = self.ij_to_id(LDi, LDj)

            ldBall = self.get_ball(LDid)
            if ldBall == None:
                break
            if ldBall.image_id == main_ball.image_id:
                LD_RU_list.append(LDid)
            else:
                break
        # 4.2右下↘
        minJ = min(10 - Mi, Mj+1)
        for j in range(minJ):
            RUi = Mi + j
            RUj = Mj - j

            RUid = self.ij_to_id(RUi, RUj)
            ruBall = self.get_ball(RUid)
            if ruBall == None:
                break
            if ruBall.image_id == main_ball.image_id:
                LD_RU_list.append(RUid)
            else:
                break
        LD_RU_list= list(set(LD_RU_list))
        print('LD_RU_list1:', LD_RU_list)
        if len(LD_RU_list) < 5:
            LD_RU_list.clear()
        print('LD_RU_list2:', LD_RU_list)


        #
        temp_sum_list=RL_list+UD_list+LU_RD_list+LD_RU_list

        # 将四个方向的列表值加载到一个列表中,再传递到删除列表中
        # list(set(temp_sum_list))删除重复值
        self.remove_ball_list=list(set(temp_sum_list))
        print('temp_sum_list:',temp_sum_list)

        if len(self.remove_ball_list)!=0:
            canRemove=True

        return canRemove



        pass

    def get_ball(self,id):
        """       
        :param id: 位置id
        :return:ball 
        """
        for ball in self.balls:
            if ball.id==id:
                return ball
        return None

4.音乐类,music.py

"""
音乐类
"""
import pygame
# from pygame.mixer import music
from PyQt5 import QtMultimedia
from PyQt5.QtMultimedia import QMediaPlayer
from PyQt5.QtCore import QUrl

class iMusic():
    def __init__(self,song):
        self.songs={
            'BGM':'music\BGM.mp3',
            'Move':'music\Move.mp3',
            'Fantastic':'music\Fantastic.mp3',
            # 'Over': music.load(r'D:\study\ball\music\Move.wma'),
            'Great': 'music\Great.mp3',
            'Dou':'music\Dou.mp3'

        }
        self.player = QMediaPlayer()
        file = QUrl.fromLocalFile(self.songs[song])  # 音频文件路径
        content = QtMultimedia.QMediaContent(file)
        self.player.setMedia(content)
        self.player.setVolume(50.0)
        self.player.loops=1000
        # player.play()
        # self.song=music.load(self.songs[song])
        # self.loops=loops
        # self.play()
        # file = QUrl.fromLocalFile(wav_file) # 音频文件路径
        # content = QtMultimedia.QMediaContent(file)
        # player.setMedia(content)
        # player.setVolume(50.0)
        # player.play()

    def play(self):
        # print('音乐 ')

        self.player.play()

    pass


5.记分板,score.py

"""
记分板
"""
import pygame
from settings import Settings

class Score():
    def __init__(self,screen, msg, rect):
        self.font=pygame.font.SysFont(None,48)
        self.ai_settings = Settings()
        self.screen = screen
        self.preant_rect=rect
        self.msg=msg
        pass
    def prep_msg(self):
        self.font.init()

        temp_image = self.font.render(str(self.msg), True,
                                 self.ai_settings.text_color,
                                      None)
        temp_rect = temp_image.get_rect()
        temp_rect.center = self.preant_rect.center

        self.screen.blit(temp_image, temp_rect)

6.设置类,settings.py

"""
设置类
"""
import pygame
class Settings():
   # 屏幕设置

   screen_height=900
   screen_width =600



   #  颜色设置
   face_color       =   (85, 90, 92)
   background_color =   (39, 40, 34)
   foreground_color =   (168, 179, 172)
   high_color       =   (138, 149, 142)
   text_color       =   (130, 130, 138)
   choose_color     =   (255,100,103)

   angle_color      =   (23,210,200)


   # 游戏区设置

   # 游戏区Rect
   game_rect=(20,20,550,550)
   # 网格长度length
   length=55

   # 游戏移动速度
   speed=0.15

   # 设置版本号
   version = 'v3.1'

   # 难度设置1-7
   difficulty = 1


   # 图片路径加载
   images = {
       'w': pygame.image.load('images/balls/white.png'),
       'g': pygame.image.load('images/balls/green.png'),
       'b': pygame.image.load('images/balls/blue.png'),
       'p': pygame.image.load('images/balls/pink.png'),
       'r': pygame.image.load('images/balls/red.png'),
       'o': pygame.image.load('images/balls/orange.png'),
       'y': pygame.image.load('images/balls/yellow.png')
   }
   #    展示板设置
   #     1.记分板rect
   rect_score=pygame.Rect(680,20,125,60)
   #  2.下一个显示屏rect
   rect_next=pygame.Rect(680,220,150,50)
   #  3.是否在游戏区显示提示球
   is_show_next_in_game=True

7.主程序,ball_game.py


import pygame
from game_function import Function

# from music import iMusic

class GameMain():
    def __init__(self):
        pygame.init()
        self.gf=Function()
    def Game_run(self):
        # pygame.init()
        # self.gf.balls_init()
        # music = iMusic('BGM')
        pygame.mixer.music.load(r'music\BGM.mp3')
        pygame.mixer.music.play(-1)
        self.gf.set_ground()
        self.gf.print_score()
        self.gf.ball_list_empty()
        while True:
            self.gf.Event()
            pygame.display.flip()
if __name__ == "__main__":
    main = GameMain()
    main.Game_run()


二、相关素材(发邮箱可以免费获取)
1.图像素材
2.音乐素材
三、效果图:
游戏分为游戏区和显示区。
python +pygame 制作五子连珠小游戏_第1张图片

你可能感兴趣的:(python,pygame)