用python编写一个消消乐游戏
时间: 2023-07-18 10:37:56 浏览: 91
好的,我可以为您提供一个简单的消消乐游戏的代码,但是需要注意的是,这只是一个基础版本的游戏,您可以根据自己的需求进行修改和扩展。以下是代码:
```python
import random
class Block:
def __init__(self, value):
self.value = value
def __str__(self):
return str(self.value)
class Board:
def __init__(self, rows, cols):
self.rows = rows
self.cols = cols
self.board = [[None for _ in range(cols)] for _ in range(rows)]
self.colors = ['R', 'G', 'B', 'Y']
def __str__(self):
res = []
for row in self.board:
res.append(' '.join(str(block) if block is not None else '-' for block in row))
return '\n'.join(res)
def generate_board(self):
for i in range(self.rows):
for j in range(self.cols):
color = random.choice(self.colors)
self.board[i][j] = Block(color)
def remove_blocks(self, blocks):
for block in blocks:
i, j = block
self.board[i][j] = None
def find_matches(self):
matches = []
for i in range(self.rows):
for j in range(self.cols):
block = self.board[i][j]
if block is None:
continue
# check horizontal match
if j < self.cols - 2 and self.board[i][j+1] == block and self.board[i][j+2] == block:
matches.append([(i, j), (i, j+1), (i, j+2)])
# check vertical match
if i < self.rows - 2 and self.board[i+1][j] == block and self.board[i+2][j] == block:
matches.append([(i, j), (i+1, j), (i+2, j)])
return matches
def collapse_board(self):
for j in range(self.cols):
empty_slots = 0
for i in range(self.rows-1, -1, -1):
if self.board[i][j] is None:
empty_slots += 1
elif empty_slots > 0:
self.board[i+empty_slots][j] = self.board[i][j]
self.board[i][j] = None
for i in range(self.rows):
for j in range(self.cols):
if self.board[i][j] is None:
self.board[i][j] = Block(random.choice(self.colors))
class Game:
def __init__(self, rows, cols):
self.board = Board(rows, cols)
self.board.generate_board()
def play(self):
while True:
print(self.board)
matches = self.board.find_matches()
if not matches:
print('No more matches!')
break
print('Matches found:')
for i, match in enumerate(matches):
print(f'{i+1}: {match}')
choice = input('Choose a match to remove (1 - %d): ' % len(matches))
try:
choice = int(choice) - 1
if choice < 0 or choice >= len(matches):
raise ValueError
except ValueError:
print('Invalid choice!')
continue
match = matches[choice]
self.board.remove_blocks(match)
self.board.collapse_board()
if __name__ == '__main__':
game = Game(8, 8)
game.play()
```
这个消消乐游戏使用了面向对象编程的思想,通过 `Block` 类表示每个方块,通过 `Board` 类表示整个游戏板块,通过 `Game` 类表示游戏本身。
在 `Board` 类中,`generate_board` 方法用于生成随机颜色的方块,`remove_blocks` 方法用于移除指定位置的方块,`find_matches` 方法用于查找游戏板块中的匹配方块,`collapse_board` 方法用于将剩余方块下落填补空缺位置。
在 `Game` 类中,`play` 方法用于开始游戏,循环直到没有匹配方块为止。每次循环都会先打印出当前游戏板块的状态,然后查找匹配方块并打印出来,接着让玩家选择要移除的匹配方块,最后移除方块并让剩余方块下落填补空缺位置。
阅读全文