制作一款《Columns》风格的方块匹配游戏 | Wireframe 第25期
树莓派官方出品里克·克罗斯(Rik Cross)本文将指导你使用 Python 和 Pygame Zero 编写一款属于自己的《Columns》风格方块匹配益智游戏。

《Columns》由惠普工程师 Jay Geertsen 开发,是世嘉(Sega)为抗衡任天堂(Nintendo)大获成功的《俄罗斯方块》(Tetris)而推出的炫目竞品。
《Columns》与方块匹配类游戏
方块匹配类游戏始于1984年的《俄罗斯方块》,次年则出现了知名度较低的《Chain Shot!》。此后该类型逐步演化,代表作包括《Dr. Mario》《Columns》《Puyo Puyo》以及《Candy Crush Saga》等。尽管具体机制各异,但目标一致:通过移动棋盘上不同颜色的方块,使它们按颜色完成匹配。
本文中,我将演示如何使用 Python 和 Pygame 创建一款简易的方块匹配游戏。游戏中,任一方块均可与其右侧方块交换位置,目标是形成三个或更多同色方块的匹配。一旦匹配成功,这些方块即从棋盘上消失,其上方方块随之向下掉落以填补空缺。
新游戏开始时,会生成一个由随机方块组成的棋盘。该棋盘以二维数组(初始为空)形式实现,其尺寸由以下变量值决定:rows and columns. A specific tile on the board is referenced by its row and column number.
我们希望起始棋盘真正随机,同时又避免出现任何已匹配的方块。因此,我们向每个棋盘位置逐个添加随机方块,但若某方块与其上方或左侧(若存在)方块颜色相同,则将其替换。

我们的棋盘共含12行、8列方块。按下空格键可交换两个被选中方块(以白色边框标出),本例中即形成一列垂直排列的红色方块匹配。
在本游戏中,任意时刻均有两枚方块处于“被选中”状态,玩家可通过方向键切换所选方块。一个selected variable keeps track of the row and column of the left-most selected tile, with the other tile being one column to the right of the left-most tile. Pressing SPACE swaps the two selected tiles, checks for matches, clears any matched tiles, and fills any gaps with new tiles.
基础版“三连匹配”算法仅需检查棋盘上是否存在左右或上下相邻且颜色相同的方块即可。但我选择了一种稍显复杂的方法,因为它不仅能检测任意长度的匹配,还能追踪多个彼此独立的匹配区域。一个currentmatch list keeps track of the (x,y) positions of a set of matching tiles. Whenever this list is empty, the next tile to check is added to the list, and this process is repeated until the next tile is a different colour.
若currentmatch list contains three or more tiles at this point, then the list is added to the overall matches list (a list of lists of matches!) and the currentmatch list is reset. To clear matched tiles, the matched tile positions are set to None, which indicates the absence of a tile at that position. To fill the board, tiles in each column are moved down by one row whenever an empty board position is found, with a new tile being added to the top row of the board.
此处提供的代码仅为起点,你可从多方面拓展本游戏,例如加入计分系统及动画效果,让方块更富表现力。

以下是 Rik 编写的代码,它用 Python 实现了一个简易的方块匹配游戏。要在你的系统上运行该代码,首先需安装Pygame Zero。要下载完整代码,请点击此处.
获取 Wireframe 第25期杂志
你可以在本期杂志中阅读更多类似内容Wireframe 第25期现已在特易购、WHSmith、所有优质的英国独立报刊亭以及剑桥的树莓派商店有售。
或者您也可以直接从树莓派出版社购买《线框图》——全球配送。如果您想要一份方便的电子版杂志,还可以免费下载第25期的PDF格式版本。

2条评论
Marek
你好。
据我所知,《俄罗斯方块》是由俄罗斯程序员阿列克谢·帕基特诺夫(Alexey Pajitnov)编写的!?
打包 ROM 文件
有人知道 Game Gear 平台上是否有类似的游戏吗?
评论已关闭