可以帮我写一个消消乐小程序的代码吗
时间: 2023-12-05 11:05:37 浏览: 102
消消乐源码
当然可以,以下是一个简单的消消乐小程序代码:
```
import random
ROW = 10 # 棋盘行数
COLUMN = 10 # 棋盘列数
COLORS = ['R', 'G', 'B', 'Y', 'P'] # 可选颜色
# 生成随机棋盘
def create_board():
board = []
for i in range(ROW):
row = []
for j in range(COLUMN):
row.append(random.choice(COLORS))
board.append(row)
return board
# 输出当前棋盘
def print_board(board):
for row in board:
print(row)
# 消除相邻的同色块
def eliminate(board):
eliminated = False
for i in range(ROW):
for j in range(COLUMN):
color = board[i][j]
if color == ' ':
continue
count = 0
row = i
col = j
while row < ROW and board[row][col] == color:
count += 1
row += 1
if count >= 3:
eliminated = True
for k in range(i, row):
board[k][col] = ' '
count = 0
row = i
col = j
while col < COLUMN and board[row][col] == color:
count += 1
col += 1
if count >= 3:
eliminated = True
for k in range(j, col):
board[row][k] = ' '
return eliminated
# 下落未消除的块
def drop(board):
for j in range(COLUMN):
top = ROW - 1
for i in range(ROW-1, -1, -1):
if board[i][j] == ' ':
continue
if i == top:
top -= 1
continue
board[top][j] = board[i][j]
board[i][j] = ' '
top -= 1
# 主函数
def main():
board = create_board()
print_board(board)
while True:
if not eliminate(board):
break
drop(board)
print_board(board)
if __name__ == '__main__':
main()
```
这个小程序生成一个10x10的随机棋盘,然后不断消除相邻的同色块,直到没有可以消除的块为止。消除后会让上面的块下落填补空洞,直到没有空洞为止。每次消除和下落后输出当前棋盘。
阅读全文