python 消消乐 代码包
时间: 2023-10-10 12:12:04 浏览: 90
python版本消消乐
3星 · 编辑精心推荐
以下是一个简单的 Python 消消乐游戏代码示例:
```python
import random
# 定义游戏区域大小
row = 10
col = 10
# 定义颜色和对应数字的字典
colors = {'R': 1, 'G': 2, 'B': 3, 'Y': 4, 'P': 5}
# 初始化游戏区域
board = [[random.choice(list(colors.keys())) for j in range(col)] for i in range(row)]
# 打印游戏区域
def print_board():
for i in range(row):
for j in range(col):
print(board[i][j], end=' ')
print()
# 检查是否有相邻的相同颜色块
def check_neighbor(i, j):
if i > 0 and board[i][j] == board[i-1][j]:
return True
if i < row-1 and board[i][j] == board[i+1][j]:
return True
if j > 0 and board[i][j] == board[i][j-1]:
return True
if j < col-1 and board[i][j] == board[i][j+1]:
return True
return False
# 消除相邻的相同颜色块
def eliminate(i, j):
if board[i][j] == ' ':
return
count = 1
board[i][j] = ' '
if i > 0 and board[i-1][j] == board[i][j]:
count += eliminate(i-1, j)
if i < row-1 and board[i+1][j] == board[i][j]:
count += eliminate(i+1, j)
if j > 0 and board[i][j-1] == board[i][j]:
count += eliminate(i, j-1)
if j < col-1 and board[i][j+1] == board[i][j]:
count += eliminate(i, j+1)
return count
# 循环检查是否有相邻的相同颜色块并消除
def check_elimination():
has_elimination = False
for i in range(row):
for j in range(col):
if check_neighbor(i, j):
has_elimination = True
eliminate(i, j)
return has_elimination
# 循环检查是否还有剩余块
def has_remain():
for i in range(row):
for j in range(col):
if board[i][j] != ' ':
return True
return False
# 计算得分
def calc_score(count):
return count * (count - 1)
# 游戏主循环
score = 0
while True:
print_board()
if not check_elimination():
break
print('Eliminated!')
count = sum(1 for i in range(row) for j in range(col) if board[i][j] == ' ')
score += calc_score(count)
print('Score:', score)
for j in range(col):
for i in range(row-1, -1, -1):
if board[i][j] == ' ':
for k in range(i-1, -1, -1):
if board[k][j] != ' ':
board[i][j], board[k][j] = board[k][j], board[i][j]
break
print('Game over!')
print('Score:', score)
```
在这个示例中,我们使用一个二维列表 `board` 表示游戏区域,每个元素表示一个颜色块。我们通过随机生成颜色块来初始化游戏区域。游戏主循环中,我们先打印游戏区域,然后循环检查是否有相邻的相同颜色块并消除,直到没有相邻的相同颜色块为止。消除相邻的相同颜色块时,我们使用递归来遍历所有相邻的相同颜色块,并将它们标记为空白。消除完毕后,我们计算得分,并将得分加到总得分中。最后,我们将所有空白块下移,并继续下一轮游戏循环。当没有相邻的相同颜色块或没有剩余块时,游戏结束。
阅读全文