以下是一个简单的 Python 代码示例,可以用来编写类似'羊了个羊'的消消乐游戏:

import random

board = []
for i in range(5):
    row = []
    for j in range(5):
        row.append(random.randint(1, 4))
    board.append(row)

def print_board(board):
    for row in board:
        print(row)

def remove_sheep(board, x, y):
    sheep_type = board[x][y]
    board[x][y] = 0
    if x > 0 and board[x-1][y] == sheep_type:
        remove_sheep(board, x-1, y)
    if x < len(board)-1 and board[x+1][y] == sheep_type:
        remove_sheep(board, x+1, y)
    if y > 0 and board[x][y-1] == sheep_type:
        remove_sheep(board, x, y-1)
    if y < len(board[0])-1 and board[x][y+1] == sheep_type:
        remove_sheep(board, x, y+1)

def fill_board(board):
    for j in range(len(board[0])):
        for i in range(len(board)-1, -1, -1):
            if board[i][j] == 0:
                for k in range(i-1, -1, -1):
                    if board[k][j] != 0:
                        board[i][j] = board[k][j]
                        board[k][j] = 0
                        break

print_board(board)
while True:
    x = int(input('Enter x coordinate: '))
    y = int(input('Enter y coordinate: '))
    remove_sheep(board, x, y)
    fill_board(board)
    print_board(board)

该程序首先生成了一个 5x5 的随机羊棋盘(1-4 表示不同种类的羊),然后定义了两个函数:print_board() 用于打印棋盘,remove_sheep() 用于移除所有与指定位置上的羊相同的羊。接下来,定义了一个 fill_board() 函数用于将空白格子填充为上面的羊落下来。最后,程序进入一个循环,每次等待用户输入一个羊的位置,然后移除所有与该位置上的羊相同的羊并填充棋盘,然后打印新的棋盘。这样,用户就可以不断地玩这个类似消消乐的游戏了。

这个代码示例只是一个简单的基础,你可以根据自己的想法添加更多功能,例如:

  • 增加游戏关卡
  • 添加分数系统
  • 使用更复杂的棋盘图案
  • 添加游戏音效和动画效果

希望这个示例能够帮助你开始你的消消乐游戏开发之旅。


原文地址: https://www.cveoy.top/t/topic/nGik 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录