Я создал игру-головоломку, которая решается сама собой, используя грубую силу. Моя решающая функция, кажется, работает нормально. Он проходит через все мои фрагменты и даже запускает новый экземпляр, если значение «is_valid» истинно, и восстанавливает предыдущий экземпляр, если оно неверно. Это мой код решателя.
def solve(board, pieces_used_unused, positions, position_index, ax, prev_match_counter=0):
global match_counter
if match_counter >= TOTAL_MATCHES:
return True
if position_index == len(positions): # If all positions are processed
return False
row, col = positions[position_index]
for i, piece in enumerate(pieces_used_unused['unused']):
# Check edge and corner constraints for pieces with 0 patterns
if piece.sides.count(0) == 2:
if not is_corner_position(row, col):
continue
elif 0 in piece.sides:
if not is_edge_position(row, col):
continue
elif is_edge_position(row, col):
continue
for _ in range(4): # Try all four rotations
if is_valid(board, piece, row, col):
matches = count_matches(board, piece, row, col)
match_counter += matches
board[row][col] = piece
pieces_used_unused['used'].append(piece)
remaining_pieces = pieces_used_unused['unused'][:i] + pieces_used_unused['unused'][i + 1:]
pieces_used_unused['unused'] = remaining_pieces
print_board(board)
if solve(board, pieces_used_unused, positions, position_index + 1, ax, prev_match_counter):
return True
match_counter -= matches
board[row][col] = None
pieces_used_unused['unused'].insert(i, piece)
pieces_used_unused['used'].pop()
print_board(board)
piece.rotate() # Rotate the piece for the next attempt
return False
try:
board, pieces_used_unused, positions, position_index, match_counter = load_state()
print("Loaded saved state.")
except FileNotFoundError:
pieces_array = [
Piece(139,[6,11,18,6]),
Piece(1,[1,17,0,0]),
Piece(2,[1,5,0,0]),
Piece(3,[9,17,0,0]),
Piece(4,[17,9,0,0]),
Piece(5,[2,1,0,1]),
# More pieces....
]
# Initialize the board and pieces
board = [[None for _ in range(16)] for _ in range(16)]
radius = 1
positions = []
start_position = (8, 7)
while radius < 9:
positions.extend(get_clockwise_positions(start_position, radius))
radius += 1
del positions[255-len(positions):]
pieces_array[0].rotate()
pieces_array[0].rotate()
# Place Piece 139 at (8, 7)
board[8][7] = pieces_array[0]
pieces_used_unused = {
'used': [pieces_array[0]],
'unused': pieces_array[1:]
}
position_index = 0
match_counter = 0
print("Initialized new state.")
# Create a figure and axis for drawing the board
fig, ax = plt.subplots(1, figsize=(9, 9))
# Draw the initial board configuration
print_board(board)
# Solve the puzzle
if solve(board, pieces_used_unused, positions, position_index, ax):
print("Puzzle solved!")
else:
print("No solution found.")
# Print the final board configuration
print_board(board)
Моя проблема в том, что если мое приложение завершается по ошибке из-за сбоя компьютера, я хочу начать с того места, где оно осталось. Итак, я попробовал это:
# snip
pieces_used_unused['unused'] = remaining_pieces
print_board(board)
if match_counter > prev_match_counter: # Save the state only if match_counter is bigger than previously saved match_counter
save_state(board, pieces_used_unused, positions, position_index + 1, match_counter)
prev_match_counter = match_counter
#snip
Но он никогда не догонит то, что было до поломки. Фактически, «for i, Piece in enumerate(pieces_used_unused['unused']):» просто проходит через все неиспользованные части и завершает головоломку без решения, что неверно.
Я создал игру-головоломку, которая решается сама собой, используя грубую силу. Моя решающая функция, кажется, работает нормально. Он проходит через все мои фрагменты и даже запускает новый экземпляр, если значение «is_valid» истинно, и восстанавливает предыдущий экземпляр, если оно неверно. Это мой код решателя. [code]def solve(board, pieces_used_unused, positions, position_index, ax, prev_match_counter=0): global match_counter
if match_counter >= TOTAL_MATCHES: return True
if position_index == len(positions): # If all positions are processed return False
row, col = positions[position_index]
for i, piece in enumerate(pieces_used_unused['unused']): # Check edge and corner constraints for pieces with 0 patterns if piece.sides.count(0) == 2: if not is_corner_position(row, col): continue elif 0 in piece.sides: if not is_edge_position(row, col): continue elif is_edge_position(row, col): continue
for _ in range(4): # Try all four rotations if is_valid(board, piece, row, col): matches = count_matches(board, piece, row, col) match_counter += matches
# Create a figure and axis for drawing the board fig, ax = plt.subplots(1, figsize=(9, 9))
# Draw the initial board configuration print_board(board)
# Solve the puzzle if solve(board, pieces_used_unused, positions, position_index, ax): print("Puzzle solved!") else: print("No solution found.")
# Print the final board configuration print_board(board) [/code] Моя проблема в том, что если мое приложение завершается по ошибке из-за сбоя компьютера, я хочу начать с того места, где оно осталось. Итак, я попробовал это: [code]def save_state(board, pieces_used_unused, positions, position_index, match_counter): state = { 'board': [[{'id': piece.id, 'sides': piece.sides} if piece else None for piece in row] for row in board], 'pieces_used_unused': { 'used': [{'id': piece.id, 'sides': piece.sides} for piece in pieces_used_unused['used']], 'unused': [{'id': piece.id, 'sides': piece.sides} for piece in pieces_used_unused['unused']] }, 'positions': positions, 'position_index': position_index, 'match_counter': match_counter } with open('puzzle_state.json', 'w') as f: json.dump(state, f) [/code] и добавил сюда вызов моего решателя: [code]# snip pieces_used_unused['unused'] = remaining_pieces
print_board(board) if match_counter > prev_match_counter: # Save the state only if match_counter is bigger than previously saved match_counter save_state(board, pieces_used_unused, positions, position_index + 1, match_counter) prev_match_counter = match_counter #snip
[/code] Но он никогда не догонит то, что было до поломки. Фактически, «for i, Piece in enumerate(pieces_used_unused['unused']):» просто проходит через все неиспользованные части и завершает головоломку без решения, что неверно.
Я создал игру-головоломку, которая решается сама собой, используя грубую силу. Моя решающая функция, кажется, работает нормально. Он проходит через все мои фрагменты и даже запускает новый экземпляр, если значение «is_valid» истинно, и...
У меня есть программа, в которой я прошу пользователя ввести вес собранных растений, а затем сколько всего растений было собрано, затем генерируется список чисел в диапазоне +100 или -100, в сумме общий вес собранных растений. Моя проблема в том,...
Я написал действительно простой код, который функционирует как «школьный регистр», спрашивая, присутствует ли ученик или нет; Если что -то другое, кроме «да» или «нет», введено, код просто напечатает «неверный ввод».
Я хотел бы иметь ответ «да» или...
Извините, если название сбивает с толку или вводит в заблуждение. Я поменяю его, если ты придумаешь что-нибудь получше, но я думаю, что виноват именно он. Я пытаюсь создать изображение .png из диаграммыcharts.js.