blocks = []
for row in range(ROWS):
for col in range(COLS):
rect = (col * block_width, row * block_height, block_width, block_height)
block = image.subsurface(rect)
blocks.append(block)
return blocks
def get_inversion_count(arr):
inv_count = 0
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if arr[i] and arr[j] and int(arr[i]) > int(arr[j]):
inv_count += 1
return inv_count
clock = pygame.time.Clock()
running = True
# 加载并随机分割图片
blocks = load_image("1.jpg")
# 检查拼图是否可解,不可解则重新生成
while not is_puzzle_solvable(blocks):
random.shuffle(blocks)
blank_index = ROWS * COLS - 1
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
col = x // (WIDTH // COLS)
row = y // (HEIGHT // ROWS)
index = row * COLS + col
moveable_indexes = get_moveable_indexes(blank_index)
if index in moveable_indexes:
swap_blocks(blocks, index, blank_index)
blank_index = index
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
solution = solve_puzzle(blocks)
if solution:
for index in solution:
swap_blocks(blocks, index, blank_index)
blank_index = index
screen.fill(WHITE)
block_width = WIDTH // COLS
block_height = HEIGHT // ROWS
for i, block in enumerate(blocks):
if block is not None:
row = i // COLS
col = i % COLS
screen.blit(block, (col * block_width, row * block_height))
pygame.display.flip()
pygame.quit()