用Python写一个消消乐
时间: 2023-05-13 12:06:43 浏览: 175
好的,以下是一个简单的消消乐游戏的 Python 代码:
```python
import random
# 定义游戏区域大小
ROWS = 8
COLS = 8
# 定义颜色列表
COLORS = ['R', 'G', 'B', 'Y', 'P']
# 初始化游戏区域
board = [[random.choice(COLORS) for _ in range(COLS)] for _ in range(ROWS)]
# 打印游戏区域
def print_board(board):
for row in board:
print(' '.join(row))
print_board(board)
# 消除相邻的同色块
def eliminate(board):
for row in range(ROWS):
for col in range(COLS):
if col < COLS - 2 and board[row][col] == board[row][col+1] == board[row][col+2]:
board[row][col] = board[row][col+1] = board[row][col+2] = ' '
if row < ROWS - 2 and board[row][col] == board[row+1][col] == board[row+2][col]:
board[row][col] = board[row+1][col] = board[row+2][col] = ' '
# 消除所有同色块
def eliminate_all(board):
while True:
eliminated = False
for row in range(ROWS):
for col in range(COLS):
if board[row][col] != ' ':
temp_board = [row[:] for row in board]
temp_board[row][col] = ' '
eliminate(temp_board)
if temp_board != board:
board = temp_board
eliminated = True
break
if eliminated:
break
if not eliminated:
break
# 消除所有同色块并打印结果
eliminate_all(board)
print_board(board)
```
这个代码实现了一个简单的消消乐游戏,首先随机生成一个游戏区域,然后不断消除相邻的同色块,直到所有同色块都被消除为止。最后打印出消除后的游戏区域。
阅读全文