python开心消消乐代码
时间: 2023-09-21 16:03:24 浏览: 160
Python游戏源码-04 开心消消乐.zip
以下是一个简单的 Python 开心消消乐代码,希望能帮到您:
```python
import random
# 游戏区域大小
N = 8
M = 8
# 颜色数量
COLORS = 4
# 定义颜色
RED = 'R'
GREEN = 'G'
BLUE = 'B'
YELLOW = 'Y'
# 列出所有的颜色
COLOR_LIST = [RED, GREEN, BLUE, YELLOW]
# 初始化游戏区域
board = [[random.choice(COLOR_LIST) for _ in range(N)] for _ in range(M)]
# 打印游戏区域
def print_board():
for row in board:
print(' '.join(row))
# 消除一连串的方块
def eliminate(x, y, color):
if x < 0 or x >= M or y < 0 or y >= N or board[x][y] != color:
return 0
count = 1
board[x][y] = '-'
count += eliminate(x+1, y, color)
count += eliminate(x-1, y, color)
count += eliminate(x, y+1, color)
count += eliminate(x, y-1, color)
return count
# 消除所有可以消除的方块
def eliminate_board():
for i in range(M):
for j in range(N):
if board[i][j] != '-':
eliminate(i, j, board[i][j])
# 下落方块
def drop_board():
for j in range(N):
idx = M-1
for i in range(M-1, -1, -1):
if board[i][j] != '-':
board[idx][j] = board[i][j]
idx -= 1
for i in range(idx, -1, -1):
board[i][j] = '-'
# 开始游戏
def start_game():
while True:
print_board()
color = input("请输入您要消除的颜色: ")
if color not in COLOR_LIST:
print("输入颜色有误,请重新输入。")
continue
count = eliminate(0, 0, color)
if count > 1:
eliminate_board()
drop_board()
print("消除了 %d 个方块。" % count)
else:
print("没有可以消除的方块。")
start_game()
```
希望这个代码能够帮到您,如果还有其他问题请随时问我。
阅读全文