写个开心消消乐的程序代码
时间: 2023-09-02 18:14:20 浏览: 121
好的,下面是简单的开心消消乐程序代码:
```python
import random
# 初始化游戏面板,0表示空格子
board = [[0 for j in range(7)] for i in range(7)]
# 随机生成初始面板
for i in range(7):
for j in range(7):
board[i][j] = random.randint(1, 4)
# 定义消除函数
def eliminate(i, j):
color = board[i][j]
# 上下左右搜索同色格子
if i > 0 and board[i-1][j] == color:
board[i-1][j] = 0
eliminate(i-1, j)
if i < 6 and board[i+1][j] == color:
board[i+1][j] = 0
eliminate(i+1, j)
if j > 0 and board[i][j-1] == color:
board[i][j-1] = 0
eliminate(i, j-1)
if j < 6 and board[i][j+1] == color:
board[i][j+1] = 0
eliminate(i, j+1)
# 输出当前面板
def print_board():
for i in range(7):
for j in range(7):
print(board[i][j], end='')
print()
# 消除所有连续的同色块
def collapse():
has_collapse = False
for i in range(7):
for j in range(7):
if board[i][j] != 0:
count = 1
# 搜索同色块数量
if i > 0 and board[i-1][j] == board[i][j]:
count += 1
if i < 6 and board[i+1][j] == board[i][j]:
count += 1
if j > 0 and board[i][j-1] == board[i][j]:
count += 1
if j < 6 and board[i][j+1] == board[i][j]:
count += 1
if count >= 3:
has_collapse = True
board[i][j] = 0
eliminate(i, j)
if has_collapse:
collapse()
# 显示最终得分
def show_score(score):
print("游戏结束!得分:%d" % score)
# 计算得分并更新面板
def calculate_score(selection):
score = 0
for (i, j) in selection:
score += 10
board[i][j] = 0
collapse()
return score
# 判断选择是否相邻
def is_adjacent(select1, select2):
return ((select1[0] == select2[0] and abs(select1[1] - select2[1]) == 1) or
(select1[1] == select2[1] and abs(select1[0] - select2[0]) == 1))
# 判断选择是否合法
def is_legal(selection):
if len(selection) < 2: # 选择小于两个格子
return False
if not all((0 <= i < 7 and 0 <= j < 7) for (i, j) in selection): # 选择不在界内
return False
if len(set(selection)) != len(selection): # 选择重复
return False
if not all(board[i][j] != 0 for (i, j) in selection): # 选择包含空格子
return False
for i in range(len(selection)):
for j in range(i + 1, len(selection)):
if not is_adjacent(selection[i], selection[j]): # 相邻的格子颜色不相同,或者非相邻格子颜色相同
return False
if board[selection[i][0]][selection[i][1]] != board[selection[j][0]][selection[j][1]]:
return False
return True
# 主游戏循环
score = 0
while True:
print_board()
if all(board[i][j] == 0 for i in range(7) for j in range(7)):
show_score(score)
break
selection = []
# 输入选择
while True:
select_str = input("请选择要消除的连续同色格子,用逗号分隔(如:1,2):")
try:
selection = [(int(s[0])-1, int(s[1])-1) for s in select_str.strip().split(",")]
except:
print("输入错误,请重新输入!")
continue
if is_legal(selection):
break
else:
print("选择不合法,请重新选择!")
score += calculate_score(selection)
```
希望这个程序能让你玩得开心!
阅读全文