Sliding Puzzle Game Implementation
Problem Statement
Create a method create_puzzle that generates a sliding puzzle game like in Resident Evil 4. The puzzle consists of a 4x4 grid with 15 numbered tiles and one empty space. The tiles are shuffled randomly.
Task
Implement the create_puzzle method in the SlidingPuzzle class. The method should return a 2D list representing the puzzle grid.
Constraints
- The grid size is fixed at 4x4.
- The tiles are numbered from 1 to 15.
- The empty space is represented by 0.
Boilerplate Code
import random
class SlidingPuzzle:
def __init__(self):
pass
def create_puzzle(self):
# TO DO: Implement this method
pass
def print_puzzle(self, puzzle):
for row in puzzle:
print(' '.join(str(tile).rjust(2) for tile in row))
def is_solvable(puzzle):
# Flatten the puzzle grid
flat_puzzle = [tile for row in puzzle for tile in row]
# Count the number of inversions
inversions = 0
for i in range(len(flat_puzzle)):
if flat_puzzle[i] == 0:
continue
for j in range(i + 1, len(flat_puzzle)):
if flat_puzzle[j] != 0 and flat_puzzle[i] > flat_puzzle[j]:
inversions += 1
# Check if the puzzle is solvable
return inversions % 2 == 0
def main():
puzzle = SlidingPuzzle()
grid = puzzle.create_puzzle()
puzzle.print_puzzle(grid)
print("Is solvable:", is_solvable(grid))
if __name__ == "__main__":
main()
Requirements
- The
create_puzzle method should generate a random 4x4 grid with 15 numbered tiles and one empty space.
- The generated puzzle should be solvable (i.e., it should be possible to slide the tiles to form a sorted grid).
Example Output
14 1 9 6
4 11 0 8
2 3 5 10
12 13 7 15
Is solvable: True
Note
The is_solvable function checks if the generated puzzle is solvable. You can use this function to verify the correctness of your implementation.
Your Task
Implement the create_puzzle method in the SlidingPuzzle class. The method should return a 2D list representing the puzzle grid. Make sure the generated puzzle is solvable.