【附源码】Python小游戏 ——开心消消乐

目录

前言

开发工具

环境搭建

效果展示

选择关卡首页

游戏界面 

过关 

 代码展示

模块导入

主函数

声音类

树类

元素类

数组类


前言

今天主要是给大家拿牌一个小游戏,开心消消乐

看看有没有小伙伴能够通过呀

开发工具

Python版本:3.7.8

相关模块:

pygame模块;

manager模块;

sys模块;

以及一些python自带的模块。

环境搭建

安装Python并添加到环境变量,pip安装需要的相关模块即可。

效果展示

选择关卡首页

游戏界面 

过关 

 代码展示

模块导入

import pygame
from pygame.locals import *
import sys
import manager

主函数

pygame.init()  # 初始化
pygame.mixer.init()
pygame.display.set_caption('开心消消乐 公众号:Python日志 学习解答加群:494958217 ')
tree = manager.ManagerTree()
m = manager.Manager(0, 0)
sound_sign = 0
world_bgm = pygame.mixer.Sound(manager.SoundPlay.world_bgm)
game_bgm = pygame.mixer.Sound(manager.SoundPlay.game_bgm)
while True:
    if m.level == 0:
        if sound_sign == 0:
            game_bgm.stop()
            world_bgm.play(-1)
            sound_sign = 1
    else:
        if sound_sign == 1:
            world_bgm.stop()
            game_bgm.play(-1)
            sound_sign = 0
    if m.level == 0:
        tree.draw_tree(m.energy_num, m.money)
    else:
        m.set_level_mode(m.level)
        sprite_group = m.draw()
        if m.type == 0:
            m.eliminate_animal()
            m.death_map()
            m.exchange(sprite_group)
        m.judge_level()

    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == pygame.K_q or event.key == pygame.K_ESCAPE:
                exit()
        if event.type == QUIT:
            sys.exit()
        m.level, m.energy_num, m.money = tree.mouse_select(event, m.level, m.energy_num, m.money)
        m.mouse_select(event)

    m.mouse_image()
    pygame.display.flip()

声音类

class SoundPlay:
    game_bgm = "sound/GameSceneBGM.ogg"
    world_bgm = 'sound/WorldSceneBGM.ogg'
    eliminate = ('sound/eliminate1.ogg', 'sound/eliminate2.ogg', 'sound/eliminate3.ogg', 'sound/eliminate4.ogg',\
                 'sound/eliminate5.ogg')  # 消除声音
    score_level = ('sound/good.ogg', 'sound/great.ogg', 'sound/amazing.ogg', 'sound/excellent.ogg',\
                   'sound/unbelievable.ogg')   # 得分声音
    click = "sound/click.bubble.ogg"  # 点击选中声音
    board_sound = 'sound/board.ogg'   # 落板子声音
    click_button = 'sound/click_common_button.ogg'  # 点击按钮声音
    money_sound = 'sound/money.ogg'   # 点击银币声音
    ice_break = 'sound/ice_break.ogg'   # 冰消除声音

    def __init__(self, filename, loops=0):
        self.sound = pygame.mixer.Sound(filename)
        self.sound.play(loops)

树类

class Tree(pygame.sprite.Sprite):
    """树类"""
    tree = 'pic2/tree.png'     # 树
    fruit = 'pic2/fruit.png'   # 果子
    energy_num = 'pic2/energy_num.png'  # 精力
    money = 'pic2/money.png'   # 银币
    energy_buy = 'pic2/energy_buy.png'   # 购买精力
    x, y = 340, 510
    h = 90
    position = ([x, y], [x+50, y-25], [x+105, y-45], [x-5, y-h-5], [x+55, y-25-h+10], [x+105, y-45-h], \
                [x, y-h*2], [x+50+10, y-25-h*2-5], [x+105+25, y-45-h*2-14], [x+30, y-h*3-30])   # 果子坐标组
    energy_num_position = (15, 70)  # 精力坐标
    energy_buy_position = (250, 400)

    def __init__(self, icon, position):
        super().__init__()
        self.image = pygame.image.load(icon).convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.bottomleft = position      # 左下角为坐标

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

元素类

class Element(pygame.sprite.Sprite):
    """ 元素类 """
    # 图标元组,包括6个小动物,
    animal = ('pic2/fox.png', 'pic2/bear.png', 'pic2/chick.png', 'pic2/eagle.png', 'pic2/frog.png', 'pic2/cow.png')
    ice = 'pic2/ice.png'  # 冰层
    brick = 'pic2/brick.png'  # 砖
    frame = 'pic2/frame.png'   # 选中框
    bling = ("pic2/bling1.png", "pic2/bling2.png", "pic2/bling3.png", "pic2/bling4.png", "pic2/bling5.png",\
             "pic2/bling6.png", "pic2/bling7.png", "pic2/bling8.png", "pic2/bling9.png")   # 消除动画

    ice_eli = ('pic2/ice0.png', 'pic2/ice1.png', 'pic2/ice2.png', 'pic2/ice3.png', 'pic2/ice4.png', 'pic2/ice5.png',\
               'pic2/ice6.png', 'pic2/ice7.png', 'pic2/ice8.png')    # 消除冰块动画

    # 得分图片
    score_level = ('pic2/good.png', 'pic2/great.png', 'pic2/amazing.png', 'pic2/excellent.png', 'pic2/unbelievable.png')
    none_animal = 'pic2/noneanimal.png'             # 无可消除小动物
    stop = 'pic2/exit.png'       # 暂停键
    stop_position = (20, 530)

    def __init__(self, icon, position):
        super().__init__()
        self.image = pygame.image.load(icon).convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.topleft = position         # 左上角坐标
        self.speed = [0, 0]
        self.init_position = position

    def move(self, speed):
        self.speed = speed
        self.rect = self.rect.move(self.speed)
        if self.speed[0] != 0:    # 如果左右移动
            if abs(self.rect.left-self.init_position[0]) == self.rect[2]:
                self.init_position = self.rect.topleft
                self.speed = [0, 0]
        else:
            if abs(self.rect.top-self.init_position[1]) == self.rect[3]:
                self.init_position = self.rect.topleft
                self.speed = [0, 0]

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

数组类

class Manager:
    """  数组类 """
    __screen_size = (900, 600)
    screen = pygame.display.set_mode(__screen_size, DOUBLEBUF, 32)
    __brick_size = 50
    __bg = pygame.image.load('pic2/bg.png').convert()
    stop_width = 63
    selected = [-1, -1]   # 现选中[row, col]
    exchange_sign = -1  # 未交换标志
    last_sel = [-1, -1]  # 上一次选中[row, col]
    change_value_sign = False  # 是否交换值标志,初始不交换
    death_sign = True  # 死图标志,初始不是死图
    boom_sel = [-1, -1]   # 四连消特效小动物所在位置 row,col
    level = 0  # 当前关卡数  初始第0关
    money = 100  # 金币
    energy_num = 30  # 精力值
    num_sign = True
    type = 2  # 0代表游戏中; 1代表完成任务,过关; -1代表步数用完,任务未完成,过关失败; 2代表未游戏状态,板子界面
    reset_mode = True     # 是否重新布局(每关布局)
    init_step = 15  # 每关规定步数
    step = init_step     # 代表游戏所剩余的步数
    score = 0        # 得数
    min = 20  # 分数中间值1
    max = 50  # 分数中间值2
    animal_num = [0, 0, 0, 0, 0, 0]   # 本关消除各小动物的个数
    ice_num = 0
    success_board = Board(Board.success_board, [200, 0])  # 过关成功板
    fail_board = Board(Board.fail_board, [200, 0])  # 任务失败板
    height, width = 9, 9
    row, col = 5, 5
    ice_list = [[-1 for col in range(21)]for row in range(21)]   # -1不画,1画冰
    animal = [[-1 for col in range(21)]for row in range(21)]   # -2消除的,-1不画,0-4小动物
    list_x, list_y = (__screen_size[0] - 11 * __brick_size) / 2, (__screen_size[1] - 11 * __brick_size) / 2  # 矩阵坐标

    def __init__(self, width, height):
        self.height = height
        self.width = width
        self.list_x = (Manager.__screen_size[0] - self.width * Manager.__brick_size) / 2
        self.list_y = (Manager.__screen_size[1] - self.height * Manager.__brick_size) / 2
        self.row, self.col = Manager.xy_rc(self.list_x, self.list_y)
        self.list_x, self.list_y = Manager.rc_xy(self.row, self.col)
        self.ice_list = [[-1 for col in range(21)]for row in range(21)]
        self.animal = [[-1 for col in range(21)]for row in range(21)]
        self.reset_animal()

    def reset_animal(self):
        for row in range(self.row, self.row + self.height):
            for col in range(self.col, self.col + self.width):
                self.animal[row][col] = random.randint(0, 5)

  • 10
    点赞
  • 84
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
好的,下面是一个简单的开心消消乐游戏Python实现,使用了Pygame库: ```python import pygame import random # 初始化游戏 pygame.init() # 游戏窗口大小 WINDOW_WIDTH = 640 WINDOW_HEIGHT = 480 # 定义颜色 BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) # 创建游戏窗口 game_window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) pygame.display.set_caption("开心消消乐") # 加载游戏图片 ball_images = [] for i in range(1, 6): ball_images.append(pygame.image.load(f"ball{i}.png")) # 球的大小和间距 BALL_SIZE = 60 BALL_SPACING = 10 # 生成随机球的颜色 def generate_random_color(): return random.choice([RED, GREEN, BLUE, YELLOW]) # 生成随机球的图片 def generate_random_ball_image(): return random.choice(ball_images) # 生成随机的球 def generate_random_ball(x, y): return { "x": x, "y": y, "color": generate_random_color(), "image": generate_random_ball_image() } # 生成随机的球列表 def generate_random_balls(num_balls): balls = [] for i in range(num_balls): x = (i % 8) * (BALL_SIZE + BALL_SPACING) + BALL_SPACING y = (i // 8) * (BALL_SIZE + BALL_SPACING) + BALL_SPACING balls.append(generate_random_ball(x, y)) return balls # 绘制球到屏幕 def draw_balls(balls): for ball in balls: game_window.blit(ball["image"], (ball["x"], ball["y"])) # 检查球是否相邻 def is_adjacent(ball1, ball2): return abs(ball1["x"] - ball2["x"]) <= BALL_SIZE + BALL_SPACING and \ abs(ball1["y"] - ball2["y"]) <= BALL_SIZE + BALL_SPACING # 寻找相邻的球 def find_adjacent_balls(balls, ball): adjacent_balls = [ball] stack = [ball] while len(stack) > 0: current_ball = stack.pop() for other_ball in balls: if other_ball not in adjacent_balls and is_adjacent(current_ball, other_ball) and other_ball["color"] == ball["color"]: adjacent_balls.append(other_ball) stack.append(other_ball) return adjacent_balls # 删除相邻的球 def remove_adjacent_balls(balls, adjacent_balls): for ball in adjacent_balls: balls.remove(ball) # 移动球到空缺位置 def move_balls(balls): for i in range(len(balls)): if balls[i] is None: balls[i] = generate_random_ball(i % 8 * (BALL_SIZE + BALL_SPACING) + BALL_SPACING, i // 8 * (BALL_SIZE + BALL_SPACING) + BALL_SPACING) # 检查游戏是否结束 def is_game_over(balls): for ball in balls: if find_adjacent_balls(balls, ball) != [ball]: return False return True # 游戏循环 def game_loop(): num_balls = 64 balls = generate_random_balls(num_balls) selected_ball = None game_over = False while not game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True elif event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos i = y // (BALL_SIZE + BALL_SPACING) * 8 + x // (BALL_SIZE + BALL_SPACING) if i < num_balls: ball = balls[i] if selected_ball is None: selected_ball = ball elif selected_ball == ball: selected_ball = None elif is_adjacent(selected_ball, ball): adjacent_balls = find_adjacent_balls(balls, selected_ball) if len(adjacent_balls) >= 2: remove_adjacent_balls(balls, adjacent_balls) move_balls(balls) selected_ball = None game_window.fill(WHITE) draw_balls(balls) if is_game_over(balls): font = pygame.font.Font(None, 36) text = font.render("游戏结束!", True, BLACK) text_rect = text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)) game_window.blit(text, text_rect) pygame.display.update() # 退出游戏 pygame.quit() quit() # 启动游戏 game_loop() ``` 运行上述代码,可以看到一个简单的开心消消乐游戏。玩家可以点击相邻的两个颜色相同的球,将它们消除,直到所有的球都被消除为止。当没有相邻的球可以消除时,游戏结束。 注意:上述代码中的游戏图片 ball1.png 到 ball5.png 需要你自己准备,可以从网络上搜索到类似的图片。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值