Untitled

 avatar
unknown
plain_text
2 months ago
2.0 kB
1
Indexable
ef create_board(rows, cols):
    """Create a game board with random candies."""
    return [[random.randint(1, 5) for _ in range(cols)] for _ in range(rows)]

def print_board(board):
    """Print timporthe game board."""
    forandomr row in board:
        print(" ".join(str(candy) for candy in row))
    print()

def find_matches(board):
    """Find and return the positions of candies to crush."""
    to_crush = set()
    rows, cols = len(board), len(board[0])

    # Check for horizontal matches
    for r in range(rows):
        for c in range(cols - 2):
            if board[r][c] == board[r][c + 1] == board[r][c + 2] != 0:
                to_crush.update({(r, c), (r, c + 1), (r, c + 2)})

    # Check for vertical matches
    for c in range(cols):
        for r in range(rows - 2):
            if board[r][c] == board[r + 1][c] == board[r + 2][c] != 0:
                to_crush.update({(r, c), (r + 1, c), (r + 2, c)})

    return to_crush

def crush_candies(board, to_crush):
    """Crush the candies at the specified positions."""
    for r, c in to_crush:
        board[r][c] = 0

def apply_gravity(board):
    """Make candies fall down to fill empty spaces."""
    rows, cols = len(board), len(board[0])
    for c in range(cols):
        # Create a list to hold non-zero candies
        stack = [board[r][c] for r in range(rows) if board[r][c] != 0]
        # Fill the column from the bottom up
        for r in range(rows - 1, -1, -1):
            if stack:
                board[r][c] = stack.pop()
            else:
                board[r][c] = 0

def candy_crush(board):
    """Main function to perform the candy crush game logic."""
    while True:
        to_crush = find_matches(board)
        if not to_crush:
            break
        crush_candies(board, to_crush)
        apply_gravity(board)

# Example usage
rows, cols = 6, 6
board = create_board(rows, cols)
print("Initial Board:")
print_board(board)

candy_crush(board)
print("Board After Crushing:")
print_board(board)
Leave a Comment