напиши алгоритм для решения blockudoku в консоле в виде таблицы где "░" это пустая ячейка, "▓" это заполненная ячейка, "|" и "-" как будет выглядеть таблица. в вводе пишут ввести 3 фигуры через пробел которые являются целыми числами и которые хранятся в словаре, они хранятся в виде "░" и "▓", и всё это будет в цикле продолжая игру. не забудь про логику самой игры.
Assistant
python
import random
# Define the board size
BOARD_SIZE = 9
# Define the empty and filled cell representations
EMPTY_CELL = '░'
FILLED_CELL = '▓'
# Initialize the game board with empty cells
board = [[EMPTY_CELL for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
# Define the pieces dictionary with integer keys and shapes using '░' and '▓'
pieces = {
1: [[FILLED_CELL]],
2: [[FILLED_CELL, FILLED_CELL]],
3: [[FILLED_CELL], [FILLED_CELL]],
4: [[FILLED_CELL, FILLED_CELL, FILLED_CELL]],
5: [[FILLED_CELL], [FILLED_CELL], [FILLED_CELL]],
6: [[FILLED_CELL, FILLED_CELL],
[FILLED_CELL, EMPTY_CELL]],
7: [[FILLED_CELL, EMPTY_CELL],
[FILLED_CELL, FILLED_CELL]],
8: [[FILLED_CELL, FILLED_CELL],
[EMPTY_CELL, FILLED_CELL]],
9: [[EMPTY_CELL, FILLED_CELL],
[FILLED_CELL, FILLED_CELL]],
# Add more pieces as needed
}
def print_board():
print(' ' + ' '.join(str(i) for i in range(BOARD_SIZE)))
print(' +' + '--' * BOARD_SIZE + '+')
for idx, row in enumerate(board):
print(f"{idx} |" + ' '.join(row) + '|')
print(' +' + '--' * BOARD_SIZE + '+')
def can_place(piece, x, y):
piece_height = len(piece)
piece_width = len(piece[0])
if x + piece_height > BOARD_SIZE or y + piece_width > BOARD_SIZE:
return False
for i in range(piece_height):
for j in range(piece_width):
if piece[i][j] == FILLED_CELL and board[x + i][y + j] == FILLED_CELL:
return False
return True
def place_piece(piece, x, y):
piece_height = len(piece)
piece_width = len(piece[0])
for i in range(piece_height):
for j in range(piece_width):
if piece[i][j] == FILLED_CELL:
board[x + i][y + j] = FILLED_CELL
def clear_lines():
# Clear full rows
rows_to_clear = [i for i in range(BOARD_SIZE) if all(cell == FILLED_CELL for cell in board[i])]
for row in rows_to_clear:
for j in range(BOARD_SIZE):
board[row][j] = EMPTY_CELL
# Clear full columns
cols_to_clear = [j for j in range(BOARD_SIZE) if all(board[i][j] == FILLED_CELL for i in range(BOARD_SIZE))]
for col in cols_to_clear:
for i in range(BOARD_SIZE):
board[i][col] = EMPTY_CELL
# Clear 3x3 squares
squares_to_clear = []
for x in range(0, BOARD_SIZE, 3):
for y in range(0, BOARD_SIZE, 3):
if all(board[i][j] == FILLED_CELL for i in range(x, x+3) for j in range(y, y+3)):
squares_to_clear.append((x, y))
for (x, y) in squares_to_clear:
for i in range(x, x+3):
for j in range(y, y+3):
board[i][j] = EMPTY_CELL
def get_random_pieces():
return random.sample(list(pieces.keys()), 3)
def game_over():
# Check if there is any valid move left
for piece_key in pieces:
piece = pieces[piece_key]
for x in range(BOARD_SIZE):
for y in range(BOARD_SIZE):
if can_place(piece, x, y):
return False
return True
def main():
print("Welcome to Blockudoku!")
while True:
print_board()
available_pieces = get_random_pieces()
print(f"Available pieces: {' '.join(str(p) for p in available_pieces)}")
input_str = input("Enter the piece number you want to place (or 'q' to quit): ").strip()
if input_str.lower() == 'q':
print("Thanks for playing!")
break
try:
piece_num = int(input_str)
if piece_num not in available_pieces:
print("Invalid piece number. Please choose from the available pieces.")
continue
piece = pieces[piece_num]
x = int(input("Enter the row number to place the piece: "))
y = int(input("Enter the column number to place the piece: "))
if can_place(piece, x, y):
place_piece(piece, x, y)
clear_lines()
if game_over():
print_board()
print("Game over! No more valid moves.")
break
else:
print("Cannot place the piece at that position. Try again.")
except ValueError:
print("Invalid input. Please enter valid numbers.")
if __name__ == "__main__":
main()
Explanation:
Board Initialization: A 9x9 board is initialized with empty cells represented by '░'.
Pieces Dictionary: A dictionary pieces stores different shapes, each associated with an integer key. The shapes are 2D lists using '░' for empty and '▓' for filled cells.
Display Function (print_board): Prints the current state of the board with row and column indices for easy placement reference.
Placement Validation (can_place): Checks if a piece can be placed at the specified coordinates without overlapping filled cells or going out of bounds.
Place Piece (place_piece): Places the piece on the board by updating the board cells to '▓'.
Line Clearing (clear_lines): After placing a piece, the function checks for full rows, columns, or 3x3 squares and clears them by resetting to '░'.
Game Loop (main function):
Displays the board and available pieces.
Prompts the user to select a piece and position.
Validates the input and placement.
Updates the board and checks for game over condition (no valid moves left).
Game Over Check (game_over): Checks if there are any valid moves left for any piece in any position.
How to Play:
Run the script in a Python environment.
The board will be displayed along with three random available pieces (numbers corresponding to piece shapes).
Enter the number of the piece you wish to place.
Enter the row (x) and column (y) where you want to place the top-left corner of the piece.
The board updates, clearing any full rows, columns, or 3x3 squares.
The game continues until there are no valid moves left.
Note: You can exit the game at any time by entering 'q' when prompted for a piece number.