ort pygame import sys # Initialize pygame pygame.init() # Constants WIDTH, HEIGHT = 300, 300 ROWS, COLS = 3, 3 TILE_SIZE = WIDTH // COLS BLACK = (0, 0, 0) WHITE = (255, 255, 255) # Set up the display screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Sliding Puzzle") # Load the image and create tiles image = pygame.image.load("image.jpg") # Replace with your image path image = pygame.transform.scale(image, (WIDTH, HEIGHT)) tiles = [] for row in range(ROWS): for col in range(COLS): tile = image.subsurface(pygame.Rect(col * TILE_SIZE, row * TILE_SIZE, TILE_SIZE, TILE_SIZE)) tiles.append(tile) # Shuffle the tiles import random random.shuffle(tiles) # Calculate tile positions tile_positions = [(col * TILE_SIZE, row * TILE_SIZE) for row in range(ROWS) for col in range(COLS)] # Main game loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = pygame.mouse.get_pos() col = x // TILE_SIZE row = y // TILE_SIZE clicked_tile_index = row * COLS + col # Check if the clicked tile is next to the empty space empty_tile_index = tiles.index(None) empty_col = empty_tile_index % COLS empty_row = empty_tile_index // COLS if (abs(col - empty_col) == 1 and row == empty_row) or \ (abs(row - empty_row) == 1 and col == empty_col): tiles[empty_tile_index], tiles[clicked_tile_index] = tiles[clicked_tile_index], tiles[empty_tile_index] # Draw the tiles screen.fill(BLACK) for i, tile in enumerate(tiles): if tile: screen.blit(tile, tile_positions[i]) pygame.display.flip() # Clean up pygame.quit()