python消消乐代码
时间: 2023-10-07 10:11:31 浏览: 89
python版本消消乐
3星 · 编辑精心推荐
以下是一个简单的Python消消乐游戏的代码:
```python
import random
# 初始化棋盘
board = []
for i in range(10):
board.append([random.randint(1, 5) for j in range(10)])
# 打印棋盘
for i in range(10):
for j in range(10):
print(board[i][j], end=' ')
print()
# 消除相邻的相同颜色块
def remove_blocks(x, y):
color = board[x][y]
board[x][y] = 0
if x > 0 and board[x-1][y] == color:
remove_blocks(x-1, y)
if x < 9 and board[x+1][y] == color:
remove_blocks(x+1, y)
if y > 0 and board[x][y-1] == color:
remove_blocks(x, y-1)
if y < 9 and board[x][y+1] == color:
remove_blocks(x, y+1)
# 循环消去所有块
while True:
removed = False
for i in range(10):
for j in range(10):
if board[i][j] == 0:
continue
if i > 0 and board[i-1][j] == board[i][j]:
removed = True
remove_blocks(i, j)
elif i < 9 and board[i+1][j] == board[i][j]:
removed = True
remove_blocks(i, j)
elif j > 0 and board[i][j-1] == board[i][j]:
removed = True
remove_blocks(i, j)
elif j < 9 and board[i][j+1] == board[i][j]:
removed = True
remove_blocks(i, j)
# 如果没有块被消除,则结束游戏
if not removed:
break
# 打印最终棋盘
print()
for i in range(10):
for j in range(10):
print(board[i][j], end=' ')
print()
```
阅读全文