Python编写的《消消乐》游戏,附源码分享

曾经风靡一时的消消乐,至今坐在地铁上都可以看到很多人依然在玩,想当年我也是大军中的一员,那家伙,吃饭都在玩,进入到高级的那种胜利感还是很爽的,连续消,无限消,哈哈,现在想想也是很带劲的。今天就来实现一款简易版的,后续会陆续带上高阶版的,先来尝试一把。
首先我们需要准备消消乐的素材,会放在项目的resource文件夹下面,具体我准备了7种,稍后会展示给大家看的。

开心消消乐

先初始化消消乐的游戏界面参数,就是具体显示多大,每行显示多少个方块,每个方块大小,这里我们按照这个大小来设置,数量和大小看着都还挺舒服的:


'''初始化消消乐的参数'''
WIDTH = 600
HEIGHT = 640
NUMGRID = 12
GRIDSIZE = 48
XMARGIN = (WIDTH - GRIDSIZE * NUMGRID) // 2
YMARGIN = (HEIGHT - GRIDSIZE * NUMGRID) // 2
ROOTDIR = os.getcwd()
FPS = 45

每行显示12个,每个方块48个,看看效果

接下来,我们开始实现消除的逻辑:

初始化消消乐的方格:


class elimination_block(pygame.sprite.Sprite):
    def __init__(self, img_path, size, position, downlen, **kwargs):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(img_path)
        self.image = pygame.transform.smoothscale(self.image, size)
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = position
        self.down_len = downlen
        self.target_x = position[0]
        self.target_y = position[1] + downlen
        self.type = img_path.split('/')[-1].split('.')[0]
        self.fixed = False
        self.speed_x = 10
        self.speed_y = 10
        self.direction = 'down'

移动方块:


'''拼图块移动'''

    def move(self):
        if self.direction == 'down':
            self.rect.top = min(self.target_y, self.rect.top + self.speed_y)
            if self.target_y == self.rect.top:
                self.fixed = True
        elif self.direction == 'up':
            self.rect.top = max(self.target_y, self.rect.top - self.speed_y)
            if self.target_y == self.rect.top:
                self.fixed = True
        elif self.direction == 'left':
            self.rect.left = max(self.target_x, self.rect.left - self.speed_x)
            if self.target_x == self.rect.left:
                self.fixed = True
        elif self.direction == 'right':
            self.rect.left = min(self.target_x, self.rect.left + self.speed_x)
            if self.target_x == self.rect.left:
                self.fixed = True

获取方块的坐标:

     '''获取坐标'''

    def get_position(self):
        return self.rect.left, self.rect.top

    '''设置坐标'''

    def set_position(self, position):
        self.rect.left, self.rect.top = position

绘制得分,加分,还有倒计时:


'''显示剩余时间'''

    def show_remained_time(self):
        remaining_time_render = self.font.render('CountDown: %ss' % str(self.remaining_time), 1, (85, 65, 0))
        rect = remaining_time_render.get_rect()
        rect.left, rect.top = (WIDTH - 201, 6)
        self.screen.blit(remaining_time_render, rect)

    '''显示得分'''

    def show_score(self):
        score_render = self.font.render('SCORE:' + str(self.score), 1, (85, 65, 0))
        rect = score_render.get_rect()
        rect.left, rect.top = (10, 6)
        self.screen.blit(score_render, rect)

    '''显示加分'''

    def add_score(self, add_score):
        score_render = self.font.render('+' + str(add_score), 1, (255, 100, 100))
        rect = score_render.get_rect()
        rect.left, rect.top = (250, 250)
        self.screen.blit(score_render, rect)

生成方块:


'''生成新的拼图块'''

    def generate_new_blocks(self, res_match):
        if res_match[0] == 1:
            start = res_match[2]
            while start > -2:
                for each in [res_match[1], res_match[1] + 1, res_match[1] + 2]:
                    block = self.get_block_by_position(*[each, start])
                    if start == res_match[2]:
                        self.blocks_group.remove(block)
                        self.all_blocks[each][start] = None
                    elif start >= 0:
                        block.target_y += GRIDSIZE
                        block.fixed = False
                        block.direction = 'down'
                        self.all_blocks[each][start + 1] = block
                    else:
                        block = elimination_block(img_path=random.choice(self.block_images), size=(GRIDSIZE, GRIDSIZE),
                                                position=[XMARGIN + each * GRIDSIZE, YMARGIN - GRIDSIZE],
                                                downlen=GRIDSIZE)
                        self.blocks_group.add(block)
                        self.all_blocks[each][start + 1] = block
                start -= 1
        elif res_match[0] == 2:
            start = res_match[2]
            while start > -4:
                if start == res_match[2]:
                    for each in range(0, 3):
                        block = self.get_block_by_position(*[res_match[1], start + each])
                        self.blocks_group.remove(block)
                        self.all_blocks[res_match[1]][start + each] = None
                elif start >= 0:
                    block = self.get_block_by_position(*[res_match[1], start])
                    block.target_y += GRIDSIZE * 3
                    block.fixed = False
                    block.direction = 'down'
                    self.all_blocks[res_match[1]][start + 3] = block
                else:
                    block = elimination_block(img_path=random.choice(self.block_images), size=(GRIDSIZE, GRIDSIZE),
                                            position=[XMARGIN + res_match[1] * GRIDSIZE, YMARGIN + start * GRIDSIZE],
                                            downlen=GRIDSIZE * 3)
                    self.blocks_group.add(block)
                    self.all_blocks[res_match[1]][start + 3] = block
                start -= 1

绘制拼图,移除,匹配,下滑的效果等:


'''移除匹配的block'''

    def clear_matched_block(self, res_match):
        if res_match[0] > 0:
            self.generate_new_blocks(res_match)
            self.score += self.reward
            return self.reward
        return 0

    '''游戏界面的网格绘制'''

    def draw_grids(self):
        for x in range(NUMGRID):
            for y in range(NUMGRID):
                rect = pygame.Rect((XMARGIN + x * GRIDSIZE, YMARGIN + y * GRIDSIZE, GRIDSIZE, GRIDSIZE))
                self.draw_block(rect, color=(0, 0, 255), size=1)

    '''画矩形block框'''

    def draw_block(self, block, color=(255, 0, 255), size=4):
        pygame.draw.rect(self.screen, color, block, size)

    '''下落特效'''

    def draw_drop_animation(self, x, y):
        if not self.get_block_by_position(x, y).fixed:
            self.get_block_by_position(x, y).move()
        if x < NUMGRID - 1:
            x += 1
            return self.draw_drop_animation(x, y)
        elif y < NUMGRID - 1:
            x = 0
            y += 1
            return self.draw_drop_animation(x, y)
        else:
            return self.is_all_full()

    '''是否每个位置都有拼图块了'''

    def is_all_full(self):
        for x in range(NUMGRID):
            for y in range(NUMGRID):
                if not self.get_block_by_position(x, y).fixed:
                    return False
        return True

绘制匹配规则,绘制拼图交换效果:


'''检查有无拼图块被选中'''

    def check_block_selected(self, position):
        for x in range(NUMGRID):
            for y in range(NUMGRID):
                if self.get_block_by_position(x, y).rect.collidepoint(*position):
                    return [x, y]
        return None

    '''是否有连续一样的三个块(无--返回0/水平--返回1/竖直--返回2)'''

    def is_block_matched(self):
        for x in range(NUMGRID):
            for y in range(NUMGRID):
                if x + 2 < NUMGRID:
                    if self.get_block_by_position(x, y).type == self.get_block_by_position(x + 1, y).type == self.get_block_by_position(x + 2,
                                                                                                          y).type:
                        return [1, x, y]
                if y + 2 < NUMGRID:
                    if self.get_block_by_position(x, y).type == self.get_block_by_position(x, y + 1).type == self.get_block_by_position(x,
                                                                                                          y + 2).type:
                        return [2, x, y]
        return [0, x, y]

    '''根据坐标获取对应位置的拼图对象'''

    def get_block_by_position(self, x, y):
        return self.all_blocks[x][y]

    '''交换拼图'''

    def swap_block(self, block1_pos, block2_pos):
        margin = block1_pos[0] - block2_pos[0] + block1_pos[1] - block2_pos[1]
        if abs(margin) != 1:
            return False
        block1 = self.get_block_by_position(*block1_pos)
        block2 = self.get_block_by_position(*block2_pos)
        if block1_pos[0] - block2_pos[0] == 1:
            block1.direction = 'left'
            block2.direction = 'right'
        elif block1_pos[0] - block2_pos[0] == -1:
            block2.direction = 'left'
            block1.direction = 'right'
        elif block1_pos[1] - block2_pos[1] == 1:
            block1.direction = 'up'
            block2.direction = 'down'
        elif block1_pos[1] - block2_pos[1] == -1:
            block2.direction = 'up'
            block1.direction = 'down'
        block1.target_x = block2.rect.left
        block1.target_y = block2.rect.top
        block1.fixed = False
        block2.target_x = block1.rect.left
        block2.target_y = block1.rect.top
        block2.fixed = False
        self.all_blocks[block2_pos[0]][block2_pos[1]] = block1
        self.all_blocks[block1_pos[0]][block1_pos[1]] = block2
        return True

准备工作差不多了,开始主程序吧:

def main():
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption('开心消消乐')
    # 加载背景音乐
    pygame.mixer.init()
    pygame.mixer.music.load(os.path.join(ROOTDIR, "resources/audios/bg.mp3"))
    pygame.mixer.music.set_volume(0.6)
    pygame.mixer.music.play(-1)
    # 加载音效
    sounds = {}
    sounds['mismatch'] = pygame.mixer.Sound(os.path.join(ROOTDIR, 'resources/audios/badswap.wav'))
    sounds['match'] = []
    for i in range(6):
        sounds['match'].append(pygame.mixer.Sound(os.path.join(ROOTDIR, 'resources/audios/match%s.wav' % i)))
    # 加载字体
    font = pygame.font.Font(os.path.join(ROOTDIR, 'resources/font.TTF'), 25)
    # 图片加载
    block_images = []
    for i in range(1, 8):
        block_images.append(os.path.join(ROOTDIR, 'resources/images/gem%s.png' % i))
    # 主循环
    game = InitGame(screen, sounds, font, block_images)
    while True:
        score = game.start()
        flag = False
        # 一轮游戏结束后玩家选择重玩或者退出
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT or (event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE):
                    pygame.quit()
                    sys.exit()
                elif event.type == pygame.KEYUP and event.key == pygame.K_r:
                    flag = True
            if flag:
                break
            screen.fill((135, 206, 235))
            text0 = 'Final score: %s' % score
            text1 = 'Press <R> to restart the game.'
            text2 = 'Press <Esc> to quit the game.'
            y = 150
            for idx, text in enumerate([text0, text1, text2]):
                text_render = font.render(text, 1, (85, 65, 0))
                rect = text_render.get_rect()
                if idx == 0:
                    rect.left, rect.top = (212, y)
                elif idx == 1:
                    rect.left, rect.top = (122.5, y)
                else:
                    rect.left, rect.top = (126.5, y)
                y += 100
                screen.blit(text_render, rect)
            pygame.display.update()
        game.reset()


'''test'''
if __name__ == '__main__':
    main()

运行main.py就可以开始游戏了,看看效果吧!

玩了一下,还可以,可能是电脑原因,初始化的时候存在卡顿的情况,后续会优化一下,初始化8个,64大小的方块是最佳情况,大家可以尝试改下配置文件就好了。后续会退出各个小游戏的进阶版,欢迎大家关注,及时获取最新内容。

需要游戏素材,和完整代码,点**开心消消乐**获取。

今天的分享就到这里,希望感兴趣的同学关注我,每天都有新内容,不限题材,不限内容,你有想要分享的内容,也可以私聊我!

作者:程序员面面

物联沃分享整理
物联沃-IOTWORD物联网 » Python编写的《消消乐》游戏,附源码分享

发表评论