python写消消乐程序
时间: 2023-08-15 18:03:15 浏览: 115
下面是一个简单的 Python 消消乐程序示例:
```python
import random
# 设置游戏区域大小和方块种类数量
ROW, COL = 10, 10
COLORS = ["R", "G", "B", "Y", "P"]
# 初始化游戏区域
board = [[random.choice(COLORS) for _ in range(COL)] for _ in range(ROW)]
# 打印游戏区域
def print_board(board):
for row in board:
print(" ".join(row))
# 检查是否存在可以消除的方块
def check(board):
score = 0
for i in range(ROW):
for j in range(COL):
if board[i][j] == " ":
continue
color = board[i][j]
blocks = [(i, j)]
# 检查上下左右四个方向的方块是否与当前方块相同
for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
x, y = i + dx, j + dy
while 0 <= x < ROW and 0 <= y < COL and board[x][y] == color:
blocks.append((x, y))
x, y = x + dx, y + dy
# 如果存在可以消除的方块,就将它们从数组中删除,并且加上对应的分数
if len(blocks) >= 3:
score += len(blocks)
for x, y in blocks:
board[x][y] = " "
return score
# 移动方块
def move(board):
moved = False
for j in range(COL):
# 将空格移动到底部
i = ROW - 1
while i >= 0 and board[i][j] != " ":
i -= 1
if i < 0:
continue
for k in range(i - 1, -1, -1):
if board[k][j] != " ":
board[i][j], board[k][j] = board[k][j], board[i][j]
i -= 1
moved = True
return moved
# 主循环
score = 0
while True:
print_board(board)
s = check(board)
if s > 0:
score += s
print("Score:", score)
if not move(board):
break
print("Game over!")
```
这个程序会随机生成一个 10x10 的游戏区域,并且包含 5 种不同颜色的方块。程序会不断检查是否存在可以消除的方块,如果存在,就会将它们从数组中删除,并且加上对应的分数。然后,程序会移动方块,直到游戏结束。游戏结束的条件是数组中没有可以消除的方块,或者达到了游戏规定的时间或分数。
阅读全文