消消乐python简单代码
时间: 2023-07-09 15:43:22 浏览: 72
以下是一个简单的消消乐游戏的 Python 代码示例:
```python
import random
# 游戏界面大小
ROWS = 8
COLS = 8
# 宝石类型数量
GEM_TYPES = 5
# 宝石类型的字符表示
GEM_CHARS = ['*', '+', '-', '#', '$']
# 计算相邻宝石的位置
ADJACENT = [(0, 1), (0, -1), (1, 0), (-1, 0)]
# 初始化游戏界面
board = [[random.randint(0, GEM_TYPES - 1) for _ in range(COLS)] for _ in range(ROWS)]
# 打印游戏界面
def print_board():
for row in board:
print(' '.join([GEM_CHARS[col] for col in row]))
# 查找相邻的同类型宝石
def find_matches(row, col):
gem_type = board[row][col]
matches = set([(row, col)])
stack = [(row, col)]
while stack:
row, col = stack.pop()
for dr, dc in ADJACENT:
r, c = row + dr, col + dc
if r < 0 or r >= ROWS or c < 0 or c >= COLS:
continue
if board[r][c] == gem_type and (r, c) not in matches:
matches.add((r, c))
stack.append((r, c))
return matches
# 移除相邻的同类型宝石
def remove_matches(matches):
for row, col in matches:
board[row][col] = -1
# 移动宝石到空缺位置
def drop_gems():
for col in range(COLS):
empty_cells = [row for row in range(ROWS) if board[row][col] == -1]
if empty_cells:
non_empty_cells = [row for row in range(ROWS) if board[row][col] != -1]
for row in empty_cells:
board[row][col] = board[random.choice(non_empty_cells)][col]
# 计算得分
def calculate_score(matches):
return len(matches) * 10
# 主循环
while True:
# 打印游戏界面
print_board()
print('')
# 获取玩家输入
row1 = int(input('请选择第一个宝石的行号:'))
col1 = int(input('请选择第一个宝石的列号:'))
row2 = int(input('请选择第二个宝石的行号:'))
col2 = int(input('请选择第二个宝石的列号:'))
# 判断输入是否合法
if row1 < 0 or row1 >= ROWS or col1 < 0 or col1 >= COLS or \
row2 < 0 or row2 >= ROWS or col2 < 0 or col2 >= COLS:
print('输入有误,请重新输入!')
continue
if abs(row1 - row2) + abs(col1 - col2) != 1:
print('两个宝石必须相邻,请重新输入!')
continue
# 交换宝石
board[row1][col1], board[row2][col2] = board[row2][col2], board[row1][col1]
# 查找并移除相邻的同类型宝石
matches = set()
for row in range(ROWS):
for col in range(COLS):
if board[row][col] != -1:
matches |= find_matches(row, col)
if matches:
score = calculate_score(matches)
print('得分:{}'.format(score))
remove_matches(matches)
drop_gems()
else:
# 如果没有可消除的宝石,则交换回来
board[row1][col1], board[row2][col2] = board[row2][col2], board[row1][col1]
```
这只是一个简单的示例,可能还有许多需要改进的地方,例如游戏结束条件、难度等级、界面美化等等。