【Python】pygame弹球游戏实现

弹球游戏实现

游戏源码:

import pygame,pygame_os,random,math
"""
砖块设定:80*30 一个砖块 其中 70*20是有颜色的,边缘的5*5(四周)是白色--为了区分块与块之间
        总块数在10*13=130块,第一行是(0,0)-(0,9);第二行是(1,0)-(1,9)如此类推,用random函数进行随机放置方块
"""

# 查找数组元素
def find(list, num):
    try:
        index = list.index(num)
    except:
        return -1
    else:
        return index

# 初始变量
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
yellow = (255, 255, 0)
font_file = "IPix中文像素字体.ttf"
win_width, win_height, bg_color, caption_title = (800, 600, white, "弹球游戏")
clock = pygame.time.Clock()

if __name__ == '__main__':
    # 程序死循环
    while 1:
        # 初始游戏窗口
        window_init = pygame_os.Start_Name(win_width, win_height, bg_color, caption_title)
        window = pygame_os.Start_Name.start_init(window_init)

        # 初始游戏开始界面
        pygame_os.Font.set_font(window, font_file, 45, "欢迎来到弹球游戏", (255, 0, 0),"top")
        for i in range(3):
            button_pos = ((win_width - 200)/2, 200 + 100 * i)
            button_name = ["简单难度", "普通难度", "困难难度"]
            locals()[f"button_{i}"] = pygame_os.Button(window, (255, 0, 0), button_pos, 200, 50, font_file, 30, white, button_name[i])
            pygame_os.Button.set_button(locals()[f"button_{i}"])


        #游戏选择难度while循环
        Start_bool = True
        difficulty = None
        tem_bool = True # 控制只执行一次的按钮if判断
        while Start_bool:
            for event in pygame.event.get():
                # 当按钮经过时:
                if event.type == pygame.MOUSEMOTION:
                    # 简单难度按钮
                    if (win_width - 200)/2 <= event.pos[0] <= (win_width + 200)/2 and 200 <= event.pos[1] <=250:
                        if tem_bool == True:
                            pygame_os.Button.button_MOUSEMOTION(button_0)
                            tem_bool = False
                    # 普通难度按钮
                    elif (win_width - 200)/2 <= event.pos[0] <= (win_width + 200)/2 and 300 <= event.pos[1] <=350:
                        if tem_bool == True:
                            pygame_os.Button.button_MOUSEMOTION(button_1)
                            tem_bool = False
                    # 困难难度按钮
                    elif (win_width - 200)/2 <= event.pos[0] <= (win_width + 200)/2 and 400 <= event.pos[1] <=450:
                        if tem_bool == True:
                            pygame_os.Button.button_MOUSEMOTION(button_2)
                            tem_bool = False
                    #重画
                    else:
                        pygame_os.Button.button_MOUSEMOTION_end(button_0)
                        pygame_os.Button.button_MOUSEMOTION_end(button_1)
                        pygame_os.Button.button_MOUSEMOTION_end(button_2)
                        tem_bool = True

                # 当按钮按下时:
                if event.type == pygame.MOUSEBUTTONDOWN:
                    # 简单难度按钮
                    if (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 200 <= event.pos[1] <= 250:
                            pygame_os.Button.button_MOUSEDOWN(button_0)
                            difficulty = 0
                    # 普通难度按钮
                    elif (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 300 <= event.pos[1] <= 350:
                            pygame_os.Button.button_MOUSEDOWN(button_1)
                            difficulty = 1
                    # 困难难度按钮
                    elif (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 400 <= event.pos[1] <= 450:
                            pygame_os.Button.button_MOUSEDOWN(button_2)
                            difficulty = 2
                # 当按钮松开时:
                if event.type == pygame.MOUSEBUTTONUP:
                    # 简单难度按钮
                    if (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 200 <= event.pos[1] <= 250:
                            pygame_os.Button.button_MOUSEUP(button_0)
                            Start_bool = False
                            break
                    # 普通难度按钮
                    elif (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 300 <= event.pos[1] <= 350:
                            pygame_os.Button.button_MOUSEUP(button_1)
                            Start_bool = False
                            break
                    # 困难难度按钮
                    elif (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 400 <= event.pos[1] <= 450:
                            pygame_os.Button.button_MOUSEUP(button_2)
                            Start_bool = False
                            break

                # 退出游戏代码
                if event.type == pygame.QUIT:exit()

        # 清屏
        pygame.draw.rect(window, white, (0, 0, win_width, win_height))
        pygame.display.update()

        # 画长板以及小球
        plank_size = 25 + 50 * (3 - difficulty)
        pygame.draw.rect(window, red, ((win_width - plank_size) / 2, 500, plank_size, 10))
        pygame.draw.circle(window, green, (win_width / 2, 490), 10)
        pygame.display.update()

        # 游戏开始设置开关
        Start_bool = True

        last_x, last_y, last_plank_x = win_width / 2, 490, (win_width - plank_size) / 2
        while Start_bool:
            for event in pygame.event.get():
                # 长板随着鼠标移动而移动
                if event.type == pygame.MOUSEMOTION:
                    if event.pos[1] >= 500:
                        pygame.draw.rect(window, white, (0, 500, win_width, 10))
                        pygame.draw.rect(window, red, (event.pos[0] - plank_size/2, 500, plank_size, 10))
                        pygame.draw.rect(window, white, (0, 480, win_width, 20))
                        last_x, last_y, last_plank_x = event.pos[0], 490, event.pos[0] - plank_size/2
                        pygame.draw.circle(window, green, (last_x, last_y), 10)
                        pygame.display.update()
                if event.type == pygame.MOUSEBUTTONUP:
                    angle = random.choice(range(20,60))
                    x_speed = math.cos(math.radians(angle)) * (difficulty * 3 + 5)
                    y_speed = - math.sin(math.radians(angle)) * (difficulty * 3 + 5)
                    Start_bool = False
                    break
                # 退出游戏代码
                if event.type == pygame.QUIT:exit()

        # 砖块放置函数
        brick_list = []
        def set_brick(difficulty):
            global brick_list, last_x, last_y
            brick_list = []
            tem_list = []
            # 设立砖块数列
            for row in range(10):
                for column in range(13):
                    brick_list.append([row, column, False])
            brick_num = random.choice(range(50 + 20 * difficulty, 80 + 20 * difficulty))
            # 删除球附近的砖块
            index = find(brick_list, [int((last_x-10)/80),int((last_y-10)/30), False])
            if index != -1:
                del brick_list[index]

            index = find(brick_list, [int((last_x + 10) / 80), int((last_y - 10) / 30), False])
            if index != -1:
                del brick_list[index]

            index = find(brick_list, [int((last_x - 10) / 80), int((last_y + 10) / 30), False])
            if index != -1:
                del brick_list[index]

            index = find(brick_list, [int((last_x + 10) / 80), int((last_y + 10) / 30), False])
            if index != -1:
                del brick_list[index]

            # 随机砖块数列
            for i in range(len(brick_list)):
                tem_list.append(i)
            for num in range(brick_num):
                random_num = random.choice(range(len(tem_list)))
                brick_list[tem_list[random_num]][2] = True
                del tem_list[random_num]
            # 构建被抽中砖块
            for num in range(len(brick_list)):
                if brick_list[num][2] == True:
                    random_color = (
                        random.choice(range(50, 200)),
                        random.choice(range(50, 200)),
                        random.choice(range(50, 200))
                    )
                    x = 80*brick_list[num][0]+5
                    y = 30*brick_list[num][1]+5
                    pygame.draw.rect(window, random_color, (x, y, 70, 20))



        # 游戏正式开始
        game_score = 0
        while True:
            # 刷新分数
            pygame.draw.rect(window, white, (0, 530, win_width, win_height - 530))
            pygame_os.Font.set_font(window, font_file, 30, "目前得分:{0}".format(game_score), (0, 0, 0), (0, 550))
            # 无尽模式砖块打完刷新
            Start_bool = False
            tem_num = 0
            for brick in brick_list:
                if brick[2] == True:
                    tem_num += 1
            if tem_num >= 5:
                Start_bool = True
            if Start_bool == False:
                pygame.draw.rect(window, white, (0, 0, win_width, 490))
                set_brick(difficulty)

            # 画球的运动轨迹
            pygame.draw.circle(window, white, (last_x, last_y), 10)
            last_x += x_speed
            last_y += y_speed
            pygame.draw.circle(window, green, (last_x , last_y), 10)
            # 碰到边缘反弹
            if last_x + 10 >= win_width or last_x - 10 <= 0:
                x_speed = -x_speed
            if (last_y <= 500 <= last_y + 10 and last_plank_x <= last_x <= last_plank_x + plank_size) or last_y - 10 <= 0:
                y_speed = -y_speed

            # 画边缘线
            pygame.draw.line(window, (0, 0, 0), (0, 0), (win_width, 0), 2)
            pygame.draw.line(window, (0, 0, 0), (0, 0), (0, 498), 2)
            pygame.draw.line(window, (0, 0, 0), (win_width - 2, 0), (win_width - 2, 498), 2)
            pygame.draw.line(window, (0, 0, 0), (0, 498), (win_width, 498), 2)

            # 画长板
            pygame.draw.rect(window, red, (last_plank_x, 500, plank_size, 10))

            # 判断砖块碰撞消失
                # 碰撞删除砖块
            def clean_break(window, pos_x, pos_y, ball_last_x, ball_last_y):
                global white
                x = 80 * pos_x + 5
                y = 30 * pos_y + 5
                pygame.draw.rect(window, white, (x, y, 70, 20))
                # 重新画球
                pygame.draw.circle(window, green, (last_x, last_y), 10)
                pygame.display.update()

                # 从砖块左边碰撞
            judge_x = int((last_x+10)/80)
            judge_y = int(last_y/30)
            index = find(brick_list, [judge_x, judge_y, True])
            if index != -1 and x_speed > 0:
                brick_list[index][2] = False
                game_score += 1
                x_speed = -x_speed
                clean_break(window, judge_x, judge_y, last_x, last_y)

                # 从砖块右边碰撞
            judge_x = int((last_x-10)/80)
            judge_y = int(last_y/30)
            index = find(brick_list, [judge_x, judge_y, True])
            if index != -1 and x_speed < 0:
                brick_list[index][2] = False
                game_score += 1
                x_speed = -x_speed
                clean_break(window, judge_x, judge_y, last_x, last_y)

                # 从砖块上边碰撞
            judge_x = int(last_x/80)
            judge_y = int((last_y+10)/30)
            index = find(brick_list, [judge_x, judge_y, True])
            if index != -1 and y_speed > 0:
                brick_list[index][2] = False
                game_score += 1
                y_speed = -y_speed
                clean_break(window, judge_x, judge_y, last_x, last_y)

                # 从砖块下边碰撞
            judge_x = int(last_x/80)
            judge_y = int((last_y-10)/30)
            index = find(brick_list, [judge_x, judge_y, True])
            if index != -1 and y_speed < 0:
                brick_list[index][2] = False
                game_score += 1
                y_speed = -y_speed
                clean_break(window, judge_x, judge_y, last_x, last_y)

            pygame.display.update()

            # 判断Gameover
            if last_y > 525:
                pygame.draw.circle(window, white, (last_x, last_y), 10)
                pygame.draw.rect(window, red, (last_plank_x, 500, plank_size, 10))
                pygame.display.update()
                break

            for event in pygame.event.get():
                if event.type == pygame.MOUSEMOTION:
                    if event.pos[1] >= 500:
                        last_plank_x = event.pos[0] - plank_size / 2
                        pygame.draw.rect(window, white, (0, 500, win_width, 10))
                        pygame.draw.rect(window, red, (last_plank_x, 500, plank_size, 10))

                    pygame.display.update()

                if event.type == pygame.QUIT: exit()
            # 限制最大帧数为60
            clock.tick(60)

        # 画Gameover画面
        Start_bool = True
        tem_bool = True  # 控制只执行一次的按钮if判断
        while Start_bool:
            pygame.draw.rect(window, (128, 128, 128), (0, 0, win_width, win_height / 4))
            pygame.display.update()
            clock.tick(1)
            pygame.draw.rect(window, (128, 128, 0), (0, win_height / 4, win_width, win_height*2 / 4))
            pygame.display.update()
            clock.tick(1)
            pygame.draw.rect(window, (128, 0, 128), (0, win_height*2 / 4, win_width, win_height*3 / 4))
            pygame.display.update()
            clock.tick(1)
            pygame.draw.rect(window, (0, 128, 128), (0, win_height*3 / 4, win_width, win_height))
            pygame.display.update()
            clock.tick(1)
            Start_bool = False
        # 画结束按钮
        button_pos = ((win_width - 200)/2, 350)
        button_refresh_init = pygame_os.Button(window, (255, 0, 0), button_pos, 200, 50, font_file, 30, white, "重来")
        pygame_os.Button.set_button(button_refresh_init)

        button_pos = ((win_width - 200)/2, 450)
        button_end_init = pygame_os.Button(window, (255, 0, 0), button_pos, 200, 50, font_file, 30, white, "退出")
        pygame_os.Button.set_button(button_end_init)

        # 画GAMEOVER字样
        pygame_os.Font.set_font(window, "IPix中文像素字体.ttf", 45, "GAMEOVER", (0, 0, 0), "center")

        pygame.display.update()

        Start_bool = True
        while Start_bool:
            for event in pygame.event.get():
                if event.type == pygame.MOUSEMOTION:
                    if (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 350 <= event.pos[1] <= 400:
                        if tem_bool == True:
                            pygame_os.Button.button_MOUSEMOTION(button_refresh_init)
                            tem_bool = False
                    elif (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 450 <= event.pos[1] <= 500:
                        if tem_bool == True:
                            pygame_os.Button.button_MOUSEMOTION(button_end_init)
                            tem_bool = False
                    # 重画
                    else:
                        pygame_os.Button.button_MOUSEMOTION_end(button_refresh_init)
                        pygame_os.Button.button_MOUSEMOTION_end(button_end_init)
                        tem_bool = True

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 350 <= event.pos[1] <= 400:
                        pygame_os.Button.button_MOUSEDOWN(button_refresh_init)
                    if (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 450 <= event.pos[1] <= 500:
                        pygame_os.Button.button_MOUSEDOWN(button_end_init)

                if event.type == pygame.MOUSEBUTTONUP:
                    if (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 350 <= event.pos[1] <= 400:
                        pygame_os.Button.button_MOUSEUP(button_refresh_init)
                        Start_bool = False
                    if (win_width - 200) / 2 <= event.pos[0] <= (win_width + 200) / 2 and 450 <= event.pos[1] <= 500:
                        pygame_os.Button.button_MOUSEUP(button_end_init)
                        exit()

                if event.type == pygame.QUIT:exit()


"""
①道具
②砖块消失 √
③分裂球
④按Esc游戏暂停且跳出窗口
"""

pygame_os库:

import pygame


class Start_Name:
    def __init__(self, win_width, win_height, bg_color, caption_title):
        self.win_width = win_width
        self.win_height = win_height
        self.bg_color = bg_color
        self.caption_title = caption_title

    def start_init(self):
        pygame.init()
        window = pygame.display.set_mode((self.win_width, self.win_height))
        pygame.display.set_caption(self.caption_title)
        window.fill(self.bg_color)
        return window


class Button:
    def __init__(self, window, button_color, pos, width, height, font_name, font_size, font_color, font_text):
        self.window = window
        self.button_color = button_color
        self.pos = pos
        self.width = width
        self.height = height
        self.font_name = font_name
        self.font_size = font_size
        self.font_color = font_color
        self.font_text = font_text
        self.button_tem_DU_color = button_color
        self.button_tem_motion_color = button_color

    def set_button(self):
        x, y = self.pos
        pygame.draw.rect(self.window, self.button_color, (x, y, self.width, self.height))
        font01 = pygame.font.Font(self.font_name, self.font_size)
        text01 = font01.render(self.font_text, True, self.font_color)
        w, h = text01.get_size()
        self.window.blit(text01, (x + (self.width - w) / 2, y + (self.height - h) / 2))
        pygame.display.update()
        return text01

    def button_MOUSEDOWN(self):
        self.button_tem_DU_color = self.button_color
        self.button_color = (128, 128, 128)
        Button.set_button(self)
        return True

    def button_MOUSEMOTION(self):
        self.button_tem_motion_color = self.button_color
        self.button_color = (175, 175, 175)
        Button.set_button(self)
        return True

    def button_MOUSEUP(self):
        self.button_color = self.button_tem_DU_color
        Button.set_button(self)
        return True

    def button_MOUSEMOTION_end(self):
        self.button_color = self.button_tem_motion_color
        Button.set_button(self)
        return True


class Font:
    @staticmethod
    def set_font(window, font_file, font_size, text, font_color, text_pos):
        font01 = pygame.font.Font(font_file, font_size)
        text01 = font01.render(text, True, font_color)
        if text_pos == "top":
            text_pos = ((window.get_size()[0] - text01.get_size()[0])/2, 0)
        if text_pos == "bottom":
            text_pos = (0, (window.get_size()[1] - text01.get_size()[1]) / 2)
        if text_pos == "center":
            text_pos = ((window.get_size()[0] - text01.get_size()[0])/2, (window.get_size()[1] - text01.get_size()[1])/2)
        window.blit(text01, text_pos)
        pygame.display.update()
        return text01

你可能感兴趣的:(Python代码,游戏,学习,python,pygame,游戏)