跳至正文
View Categories

1 min read

主要内容 #

    1. 游戏类中生成新的拼图块函数
    2. 游戏类其他函数模块

1.游戏类中生成新的拼图块函数 #

将匹配的拼图块消除之后,我们还需要随机生成新的拼图块,代码实现如下:


	def generateNewGems(self, res_match):
		'''
		新拼图块生成函数
		'''
		if res_match[0] == 1: # 需要用到isMatch()函数,返回1表示水平方向有三个连续一样的宝石
			start = res_match[2]
			while start > -2:
				for each in [res_match[1], res_match[1]+1, res_match[1]+2]:  # 水平方向匹配成功后,需要从第一个位置往后三列都需要生成新的宝石
					gem = self.getGemByPos(*[each, start])
					if start == res_match[2]:
						self.gems_group.remove(gem)
						self.all_gems[each][start] = None  # 当前位置设置为空
					elif start >= 0:
						gem.target_y += GRIDSIZE
						gem.fixed = False
						gem.direction = 'down'
						self.all_gems[each][start+1] = gem  # 边框内匹配位置上面的三列宝石块全部下移
					else:  # 在边框外生成新的宝石块然后下移一个位置
						gem = gemSprite(img_path=random.choice(self.gem_imgs), size=(GRIDSIZE, GRIDSIZE), position=[XMARGIN+each*GRIDSIZE, YMARGIN-GRIDSIZE], downlen=GRIDSIZE)
						self.gems_group.add(gem)
						self.all_gems[each][start+1] = gem
				start -= 1
		elif res_match[0] == 2: # 返回2表示竖直方向有三个连续一样的宝石
			start = res_match[2]
			while start > -4:
				if start == res_match[2]:
					for each in range(0, 3):    # 竖直方向匹配后,只需要在一列中生成3个新的宝石
						gem = self.getGemByPos(*[res_match[1], start+each])
						self.gems_group.remove(gem)
						self.all_gems[res_match[1]][start+each] = None  #  消除当前宝石
				elif start >= 0:
					gem = self.getGemByPos(*[res_match[1], start])
					gem.target_y += GRIDSIZE * 3
					gem.fixed = False
					gem.direction = 'down'
					self.all_gems[res_match[1]][start+3] = gem   #  边框内宝石快右移三个位置
				else:
					gem = gemSprite(img_path=random.choice(self.gem_imgs), size=(GRIDSIZE, GRIDSIZE), position=[XMARGIN+res_match[1]*GRIDSIZE, YMARGIN+start*GRIDSIZE], downlen=GRIDSIZE*3)
					self.gems_group.add(gem)
					self.all_gems[res_match[1]][start+3] = gem # 在边框外生成新的宝石,下移三个位置
				start -= 1

将以上所有代码加入到游戏类代码中,作为成员函数。

接下来需要在各个模块中添加和修改代码,具体如下。

    # 在gemGame类中的removeMatched()函数中找到如下代码
	# self.generateNewGems(res_match)  # 将res_match列表信息传给生成函数

    # 将该代码打开
	self.generateNewGems(res_match)  # 将res_match列表信息传给生成函数

全部修改完之后,运行整体代码,看整体效果,可以看出宝石可以交换和得分展示。

2.游戏类中其他函数模块 #

该模块实现的功能为:分数计算函数。
该部分代码如下:


    def drawAddScore(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)

将以上所有代码加入到游戏类代码中,作为成员函数。

接下来需要在各个模块中添加和修改代码,具体如下。

    # 在gemGame类中的start()函数中找到如下代码
	add_score_showtimes -= 1

    # 在该代码前面新增如下代码
	self.drawAddScore(add_score)

全部修改完之后,运行整体代码,看整体效果。

至此完成了消消乐游戏所有的代码部分,其实代码中还是有一些bug的,希望同学们可以理解代码之后去发现bug并且修正bug。

小结 #

  • 本节主要介绍了消消乐游戏所需的其他成员函数和主循环start函数的完善,至此消消乐游戏开发完成。