Skip to content
Snippets Groups Projects
Commit 9a62a3cb authored by Joe Stephenson's avatar Joe Stephenson
Browse files

pull

parents 35b9ba6d fc12fbc9
Branches
No related tags found
No related merge requests found
#sliding puzzle
import random
class SlidePuzzle:
solved_board = [[1, 2, 3], [4, 5, 6], [7, 8, " "]] # Final solved board
def __init__(self):
"""
Create a new shuffled board when the object is created
"""
self.board = self.shuffled_board()
def print_board(self):
"""
Prints the current state of the board
"""
for row in self.board:
print('_|_'.join(str(cell) for cell in row))
def find_empty_cell(self):
"""
Finds the position of the empty cell in the board
"""
for i, row in enumerate(self.board):
for j, cell in enumerate(row):
if cell == " ":
return i, j
def shuffled_board(self):
"""
Creates a new shuffled board by randomly shuffling numbers
"""
board = [1, 2, 3, 4, 5, 6, 7, 8, " "]
random.shuffle(board)
return [board[i:i+3] for i in range(0, len(board), 3)]
def is_solved(self):
"""
Checks if the current board is the solved board or not
"""
return self.board == SlidePuzzle.solved_board
def move(self, direction):
"""
Moves the empty cell in the given direction if it is valid. Otherwise, it prints an error message.
"""
empty_cell = self.find_empty_cell()
i, j = empty_cell
if direction == "up" and i > 0:
self.board[i][j], self.board[i-1][j] = self.board[i-1][j], self.board[i][j]
elif direction == "down" and i < 2:
self.board[i][j], self.board[i+1][j] = self.board[i+1][j], self.board[i][j]
elif direction == "left" and j > 0:
self.board[i][j], self.board[i][j-1] = self.board[i][j-1], self.board[i][j]
elif direction == "right" and j < 2:
self.board[i][j], self.board[i][j+1] = self.board[i][j+1], self.board[i][j]
else:
print("Invalid direction! Try again.")
def play_game():
"""
The main game loop, asks the player for a move until the puzzle is solved
"""
puzzle = SlidePuzzle()
while not puzzle.is_solved():
puzzle.print_board()
move = input("Enter the direction (up, down, left, right): ").lower()
puzzle.move(move)
if puzzle.is_solved():
print("Congratulations! You solved the puzzle!")
puzzle.print_board()
play_game()
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment