In this assignment, you are going to design and develop an interactive sliding puzzle game for both 8 and 15 numbers. An 8-number puzzle has a square-framed board consisting of 8 square tiles, numbered 1 to 8, initially placed in random order, while a 15-number puzzle there are 15 numbered square tiles, from 1 to 15, as shown above respectively. The game board has an empty space where one of adjacent tiles slides to. The objective of the game is to re-arrange the tiles into a sequential order by their numbers (left to right, top to bottom) by repeatedly making sliding moves (left, right, up or down). The following figure shows an example of one 8-number puzzle where “INITIAL” is the starting point of the game, and the player needs to repeatedly slide one adjacent tile, one at a time, to the unoccupied space (the empty space) until all numbers appear sequentially, ordered from left to right, top to bottom, shown as “FINAL”.
代码:
#import the necessary libraries
import random
#define the size of the puzzle
size = 3
#create a list of numbers from 0 to size^2 - 1
numbers = [i for i in range(size**2)]
#shuffle the list
random.shuffle(numbers)
#create a 2D array of size x size
puzzle = [[0 for i in range(size)] for j in range(size)]
#fill the array with the shuffled numbers
for i in range(size):
for j in range(size):
puzzle[i][j] = numbers[i*size + j]
#function to check if the puzzle is solved
def is_solved(puzzle):
for i in range(size):
for j in range(size):
if puzzle[i][j] != i*size + j:
return False
return True
#function to move the empty tile
def move_tile(puzzle, direction):
#find the empty tile
for i in range(size):
for j in range(size):
if puzzle[i][j] == 0:
empty_tile = (i, j)
break
#check if the move is valid
if direction == 'up':
if empty_tile[0] == 0:
return False
else:
puzzle[empty_tile[0]][empty_tile[1]] = puzzle[empty_tile[0] - 1][empty_tile[1]]
puzzle[empty_tile[0] - 1][empty_tile[1]] = 0
return True
elif direction == 'down':
if empty_tile[0] == size - 1:
return False
else:
puzzle[empty_tile[0]][empty_tile[1]] = puzzle[empty_tile[0] + 1][empty_tile[1]]
puzzle[empty_tile[0] + 1][empty_tile[1]] = 0
return True
elif direction == 'left':
if empty_tile[1] == 0:
return False
else:
puzzle[empty_tile[0]][empty_tile[1]] = puzzle[empty_tile[0]][empty_tile[1] - 1]
puzzle[empty_tile[0]][empty_tile[1] - 1] = 0
return True
elif direction == 'right':
if empty_tile[1] == size - 1:
return False
else:
puzzle[empty_tile[0]][empty_tile[1]] = puzzle[empty_tile[0]][empty_tile[1] + 1]
puzzle[empty_tile[0]][empty_tile[1] + 1] = 0
return True
#function to print the puzzle
def print_puzzle(puzzle):
for i in range(size):
for j in range(size):
print(puzzle[i][j], end=' ')
print()
#main loop
while not is_solved(puzzle):
print_puzzle(puzzle)
direction = input('Enter the direction to move the empty tile (up/down/left/right): ')
if move_tile(puzzle, direction):
print('Tile moved!')
else:
print('Invalid move!')
print('Puzzle solved!')
该回答引用CHATGPT,GPT_Pro更好的解决问题
import random
class Board:
def __init__(self, size):
self.size = size
self.tiles = [i for i in range(size*size)]
self.empty = size*size - 1
self.shuffle()
def shuffle(self):
for i in range(100):
moves = self.get_moves()
self.move(random.choice(moves))
def get(self, x, y):
return self.tiles[x + y*self.size]
def set(self, x, y, value):
self.tiles[x + y*self.size] = value
def get_pos(self, value):
x = self.tiles.index(value) % self.size
y = self.tiles.index(value) // self.size
return x, y
def get_moves(self):
moves = []
x, y = self.get_pos(self.empty)
if x > 0:
moves.append((x - 1, y))
if x < self.size - 1:
moves.append((x + 1, y))
if y > 0:
moves.append((x, y - 1))
if y < self.size - 1:
moves.append((x, y + 1))
return moves
def move(self, pos):
value = self.get(*pos)
x, y = self.get_pos(self.empty)
self.set(x, y, value)
self.set(*pos, self.empty)
self.empty = value
def is_solved(self):
return self.tiles == [i for i in range(self.size*self.size)]
def __str__(self):
rows = []
for y in range(self.size):
row = []
for x in range(self.size):
value = self.get(x, y)
if value == self.empty:
row.append(" ")
else:
row.append(str(value))
rows.append("|".join(row))
return "\n".join(rows)
class Game:
def __init__(self, size):
self.board = Board(size)
def play(self):
while not self.board.is_solved():
print(self.board)
moves = self.board.get_moves()
print("Moves:", moves)
x, y = map(int, input("Enter coordinates of tile to move: ").split())
if (x, y) in moves:
self.board.move((x, y))
else:
print("Invalid move")
print("Congratulations, you solved the puzzle!")
if __name__ == '__main__':
game = Game(3)
game.play()
回答来自gpt,有帮助的话采纳一下哦!
要用Python编写滑块拼图,可以按照以下步骤进行:
1.界面设计:使用Pygame、Tkinter或其他GUI库创建游戏窗口和拼图面板。
2.初始化拼图:创建一个二维数组表示拼图面板上每个方块的位置和数字。将方块随机打乱,确保生成一个可解的拼图。
3.交互设计:监控玩家的键盘输入或鼠标点击,根据操作调整拼图面板上方块的位置。
4.游戏逻辑:检查玩家的操作是否合法,即判断空格是否与相邻方块相邻。如果玩家完成拼图,游戏结束。
一个简单的示例程序:
import pygame
# 设置游戏窗口和拼图面板大小
WINDOW_SIZE = (400, 400)
PUZZLE_SIZE = 3
# 定义方块的宽度和高度
BLOCK_SIZE = WINDOW_SIZE[0] // PUZZLE_SIZE
# 定义方块的颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 初始化拼图面板
puzzle = [[3, 1, 2], [4, 6, 5], [7, 8, None]]
# 初始化Pygame
pygame.init()
screen = pygame.display.set_mode(WINDOW_SIZE)
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# 处理键盘输入
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
# 上移空格
for i in range(PUZZLE_SIZE):
for j in range(PUZZLE_SIZE):
if puzzle[i][j] is None and i > 0:
puzzle[i][j], puzzle[i-1][j] = puzzle[i-1][j], puzzle[i][j]
elif event.key == pygame.K_DOWN:
# 下移空格
for i in range(PUZZLE_SIZE-1, -1, -1):
for j in range(PUZZLE_SIZE):
if puzzle[i][j] is None and i < PUZZLE_SIZE-1:
puzzle[i][j], puzzle[i+1][j] = puzzle[i+1][j], puzzle[i][j]
elif event.key == pygame.K_LEFT:
# 左移空格
for i in range(PUZZLE_SIZE):
for j in range(PUZZLE_SIZE):
if puzzle[i][j] is None and j > 0:
puzzle[i][j], puzzle[i][j-1] = puzzle[i][j-1], puzzle[i][j]
elif event.key == pygame.K_RIGHT:
# 右移空格
for i in range(PUZZLE_SIZE):
for j in range(PUZZLE_SIZE-1, -1, -1):
if puzzle[i][j] is None and j < PUZZLE_SIZE-1:
puzzle[i][j], puzzle[i][j+1] = puzzle[i][j+1], puzzle[i][j]
# 绘制拼图面板
screen.fill(WHITE)
for i in range(PUZZLE_SIZE):
for j in range(PUZZLE_SIZE):
if puzzle[i][j] is not None:
pygame.draw.rect(screen, BLACK, (j*BLOCK_SIZE, i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 2)
font = pygame.font.Font(None, BLOCK_SIZE)
text = font.render(str(puzzle[i][j]), True, BLACK)
screen.blit(text, (j*BLOCK_SIZE + BLOCK_SIZE//2 - text.get_width()//2, i*BLOCK_SIZE + BLOCK_SIZE//2 - text.get_height()//2))
# 更新显示
pygame.display.flip()
import random
# 游戏界面尺寸
BOARD_SIZE = 3
# 初始状态
INITIAL = [[2, 8, 3], [1, 6, 4], [7, 0, 5]]
# 目标状态
GOAL = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
# 滑动谜题类
class Puzzle:
def __init__(self, board):
self.board = board
self.empty_x, self.empty_y = self.find_empty()
# 查找空格位置
def find_empty(self):
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if self.board[i][j] == 0:
return i, j
return None
# 判断游戏是否完成
def is_solved(self):
return self.board == GOAL
# 滑动方块
def move(self, direction):
x, y = self.empty_x, self.empty_y
if direction == 'left':
new_x, new_y = x, y-1
elif direction == 'right':
new_x, new_y = x, y+1
elif direction == 'up':
new_x, new_y = x-1, y
elif direction == 'down':
new_x, new_y = x+1, y
if 0 <= new_x < BOARD_SIZE and 0 <= new_y < BOARD_SIZE:
self.board[x][y], self.board[new_x][new_y] = self.board[new_x][new_y], self.board[x][y]
self.empty_x, self.empty_y = new_x, new_y
return True
else:
return False
# 打印游戏界面
def print_board(self):
for row in self.board:
print(' '.join([str(elem) for elem in row]))
print()
# 初始化游戏
game = Puzzle(INITIAL)
# 打印初始界面
game.print_board()
# 开始游戏
while not game.is_solved():
direction = input("Enter move (left, right, up, down): ")
if game.move(direction):
game.print_board()
else:
print("Invalid move. Try again.")
导入必要的库和模块:
import pygame
import random
import os
定义游戏窗口的大小和标题:
WIDTH = 640
HEIGHT = 480
TITLE = "Sliding Puzzle"
初始化Pygame库并创建游戏窗口:
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(TITLE)
加载拼图图像,并将其分成若干个小块:
img = pygame.image.load(os.path.join("images", "puzzle.jpg"))
pieces = []
size = 80
for i in range(0, WIDTH, size):
for j in range(0, HEIGHT, size):
piece = img.subsurface(pygame.Rect(i, j, size, size))
pieces.append(piece)
随机打乱小块的顺序:
random.shuffle(pieces)
定义每个小块的位置和索引:
positions = [(i, j) for i in range(4) for j in range(4)]
indexes = [i for i in range(len(pieces))]
random.shuffle(indexes)
mapping = dict(zip(positions, indexes))
定义游戏主循环,处理事件和绘制画面:
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((0, 0, 0))
for i, j in positions:
index = mapping[(i, j)]
x = i * size
y = j * size
if index == len(pieces) - 1:
continue
screen.blit(pieces[index], (x, y))
pygame.display.flip()
pygame.quit()
在这个示例中,我们首先导入必要的库和模块,定义游戏窗口的大小和标题,并初始化Pygame库。然后,我们加载拼图图像,并将其分成若干个小块,并随机打乱小块的顺序。接着,我们定义每个小块的位置和索引,并创建一个字典来映射它们。最后,我们进入游戏主循环,处理事件和绘制画面。当用户单击游戏窗口的关闭按钮时,程序退出并关闭Pygame库。
请注意,上述代码仅为示例代码,并未包括完整的滑动拼图程序所需的所有步骤和功能。您需要根据自己的需求对代码进行修改和扩展。此外,编写滑动拼图程序需要对Python编程和Pygame库有一定的了解。
该回答引用ChatGPT
有疑问以回复我
import random
import sys
class SlidingPuzzle:
def __init__(self, size=3):
self.size = size
self.board = [[(row * size + col) for col in range(size)] for row in range(size)]
self.empty_spot = (size - 1, size - 1)
self.moves = {
"UP": (-1, 0),
"DOWN": (1, 0),
"LEFT": (0, -1),
"RIGHT": (0, 1)
}
def shuffle(self, num_moves=100):
for i in range(num_moves):
possible_moves = self.get_possible_moves()
move = random.choice(possible_moves)
self.make_move(move)
def get_possible_moves(self):
moves = []
for move in self.moves:
new_pos = (self.empty_spot[0] + self.moves[move][0], self.empty_spot[1] + self.moves[move][1])
if self.is_valid_move(new_pos):
moves.append(move)
return moves
def is_valid_move(self, pos):
return (pos[0] >= 0 and pos[0] < self.size and pos[1] >= 0 and pos[1] < self.size)
def make_move(self, move):
new_pos = (self.empty_spot[0] + self.moves[move][0], self.empty_spot[1] + self.moves[move][1])
self.board[self.empty_spot[0]][self.empty_spot[1]] = self.board[new_pos[0]][new_pos[1]]
self.board[new_pos[0]][new_pos[1]] = 0
self.empty_spot = new_pos
def print_board(self):
for row in self.board:
print(" ".join([str(x) if x != 0 else " " for x in row]))
def is_solved(self):
return self.board == [[(row * self.size + col) for col in range(self.size)] for row in range(self.size)]
def play(self):
print("Welcome to Sliding Puzzle!")
print("Use the following commands to move the tiles: UP, DOWN, LEFT, RIGHT.")
self.print_board()
while not self.is_solved():
move = input("Enter a move: ").upper()
if move not in self.moves:
print("Invalid move! Please try again.")
continue
if move not in self.get_possible_moves():
print("You cannot move in that direction! Please try again.")
continue
self.make_move(move)
self.print_board()
print("Congratulations, you solved the puzzle!")
if __name__ == "__main__":
size = int(input("Enter the size of the puzzle (3 or 4): "))
if size != 3 and size != 4:
print("Invalid size! Please enter either 3 or 4.")
sys.exit(1)
puzzle = SlidingPuzzle(size)
puzzle.shuffle()
puzzle.play()
该回答引用CHATGPT
To design and develop an interactive sliding puzzle game for both 8 and 15 numbers, you can follow these steps:Decide on the platform: You can choose any platform to develop your game, such as web, desktop, or mobile. Depending on the platform, you may choose different programming languages and tools.Design the user interface: Design the user interface for the game board and the controls for making sliding moves. You can use graphics and animations to make the game more interactive and engaging.Implement the game logic: Implement the game logic for generating random initial board configurations and checking the correctness of the final configuration. You also need to implement the sliding moves and update the game board accordingly.Test the game: Test the game for different scenarios, such as different initial configurations, different board sizes, and different levels of difficulty.Here is an example Python code for a simple 8-number sliding puzzle game:
import random
class Puzzle:
def __init__(self):
self.board = [[1, 2, 3], [4, 5, 6], [7, 8, None]]
self.empty_row = 2
self.empty_col = 2
def shuffle(self):
for i in range(1000):
moves = self.get_moves()
move = random.choice(moves)
self.move(move)
def move(self, direction):
row_offset, col_offset = direction
new_row = self.empty_row + row_offset
new_col = self.empty_col + col_offset
if new_row < 0 or new_row > 2 or new_col < 0 or new_col > 2:
return False
self.board[self.empty_row][self.empty_col] = self.board[new_row][new_col]
self.board[new_row][new_col] = None
self.empty_row = new_row
self.empty_col = new_col
return True
def get_moves(self):
moves = []
if self.empty_row > 0:
moves.append((-1, 0)) # move up
if self.empty_row < 2:
moves.append((1, 0)) # move down
if self.empty_col > 0:
moves.append((0, -1)) # move left
if self.empty_col < 2:
moves.append((0, 1)) # move right
return moves
def is_solved(self):
for i in range(3):
for j in range(3):
if self.board[i][j] != i*3 + j + 1:
return False
return True
In this code, we define a Puzzle class that represents an 8-number sliding puzzle. The board attribute is a 2D list that represents the game board, where None represents the empty space. The empty_row and empty_col attributes represent the current position of the empty space. The shuffle() method randomly shuffles the initial board configuration. The move() method takes a direction as input and moves the adjacent tile in that direction if possible. The get_moves() method returns a list of possible moves from the current position of the empty space. The is_solved() method checks if the current board configuration is the correct final configuration.
import tkinter as tk
import random
class SlidingPuzzle(tk.Frame):
def __init__(self, parent, size):
tk.Frame.__init__(self, parent)
self.parent = parent
self.size = size
self.tiles = {}
self.empty_pos = None
self.initUI()
def initUI(self):
self.parent.title("Sliding Puzzle")
self.pack(fill=tk.BOTH, expand=1)
self.canvas = tk.Canvas(self, width=400, height=400)
self.canvas.pack(fill=tk.BOTH, side=tk.TOP)
restart_btn = tk.Button(self, text="Restart", command=self.restart)
restart_btn.pack(fill=tk.BOTH, side=tk.BOTTOM)
self.canvas.bind("<Button-1>", self.tile_clicked)
self.restart()
def restart(self):
self.tiles = {}
for row in range(self.size):
for col in range(self.size):
number = row * self.size + col + 1
x1, y1 = col * 100, row * 100
x2, y2 = x1 + 100, y1 + 100
tile = self.canvas.create_rectangle(x1, y1, x2, y2, fill="white", outline="black")
label = self.canvas.create_text(x1+50, y1+50, text=str(number), font=("Arial", 32))
self.tiles[(row, col)] = {"tile": tile, "label": label}
self.empty_pos = (self.size-1, self.size-1)
self.canvas.delete(self.tiles[self.empty_pos]["label"])
self.shuffle()
def shuffle(self):
for i in range(1000):
directions = self.get_valid_moves()
direction = random.choice(directions)
self.move(direction)
def get_valid_moves(self):
moves = []
if self.empty_pos[0] > 0:
moves.append("up")
if self.empty_pos[0] < self.size-1:
moves.append("down")
if self.empty_pos[1] > 0:
moves.append("left")
if self.empty_pos[1] < self.size-1:
moves.append("right")
return moves
def move(self, direction):
row, col = self.empty_pos
if direction == "up":
tile_pos = (row-1, col)
elif direction == "down":
tile_pos = (row+1, col)
elif direction == "left":
tile_pos = (row, col-1)
elif direction == "right":
tile_pos = (row, col+1)
tile = self.tiles[tile_pos]
label = self.canvas.itemcget(tile["label"], "text")
self.canvas.move(tile["tile"], 100*(col-tile_pos[1]), 100*(row-tile_pos[0]))
self.canvas.move(tile["label"], 100*(col-tile_pos[1]), 100*(row-tile_pos[0]))
self.tiles[self.empty_pos] = {"tile": tile["tile"], "label": tile["label"]}
self.tiles[tile_pos] = {"tile": None, "label": None}
self.empty_pos = tile_pos
def tile_clicked(self, event):
col = event.x // 100
row = event.y // 100
if (row, col) in self.get
参考GPT和自己的思路,要编写滑动拼图游戏,您需要了解以下几个步骤:
1 了解游戏规则和逻辑
2 设计游戏图形用户界面(GUI)
3 实现游戏逻辑和交互性
4 测试游戏并进行必要的调整
以下是一个简单的Python代码示例,演示如何实现8数字滑动拼图游戏:
import random
import pygame
# 定义游戏板的宽度和高度
BOARD_WIDTH = 300
BOARD_HEIGHT = 300
# 定义游戏板上每个方块的宽度和高度
TILE_WIDTH = BOARD_WIDTH // 3
TILE_HEIGHT = BOARD_HEIGHT // 3
# 定义颜色常量
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 初始化pygame
pygame.init()
# 创建游戏窗口
game_display = pygame.display.set_mode((BOARD_WIDTH, BOARD_HEIGHT))
pygame.display.set_caption('Sliding Puzzle Game')
# 创建字体对象
font = pygame.font.SysFont('arial', 25)
# 定义游戏板
board = [[1, 2, 3],
[4, 5, 6],
[7, 8, None]]
# 定义空方块的初始位置
empty_pos = (2, 2)
# 定义游戏循环标志
game_exit = False
# 定义游戏主循环
while not game_exit:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
if event.type == pygame.KEYDOWN:
# 处理方向键按下事件
if event.key == pygame.K_LEFT and empty_pos[1] < 2:
board[empty_pos[0]][empty_pos[1]] = board[empty_pos[0]][empty_pos[1] + 1]
board[empty_pos[0]][empty_pos[1] + 1] = None
empty_pos = (empty_pos[0], empty_pos[1] + 1)
elif event.key == pygame.K_RIGHT and empty_pos[1] > 0:
board[empty_pos[0]][empty_pos[1]] = board[empty_pos[0]][empty_pos[1] - 1]
board[empty_pos[0]][empty_pos[1] - 1] = None
empty_pos = (empty_pos[0], empty_pos[1] - 1)
elif event.key == pygame.K_UP and empty_pos[0] < 2:
board[empty_pos[0]][empty_pos[1]] = board[empty_pos[0] + 1][empty_pos[1]]
board[empty_pos[0] + 1][empty_pos[1]] = None
empty_pos = (empty_pos[0] + 1, empty_pos[1])
elif event.key == pygame.K_DOWN and empty_pos[0] > 0:
board[empty_pos[0]][empty_pos[1]] = board[empty_pos[0] - 1][empty_pos[1]]
board[empty_pos[0] - 1][empty_pos[1]] = None
empty_pos = (empty_pos[0] - 1, empty_pos[1])
# 重绘游戏板
for row in range(3):
for col in range(3):
if board[row][col] is not None:
# 绘制方块
pygame.draw.rect(game_display, BLACK, (col * TILE_WIDTH, row * TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT))
# 绘制方块中的数字
text = font.render(str(board[row][col]), True, WHITE)
text_rect = text.get_rect(center=(col * TILE_WIDTH + TILE_WIDTH // 2, row * TILE_HEIGHT + TILE_HEIGHT // 2))
game_display.blit(text, text_rect)
# 绘制分割线
pygame.draw.line(game_display, WHITE, (TILE_WIDTH, 0), (TILE_WIDTH, BOARD_HEIGHT), 5)
pygame.draw.line(game_display, WHITE, (2 * TILE_WIDTH, 0), (2 * TILE_WIDTH, BOARD_HEIGHT), 5)
pygame.draw.line(game_display, WHITE, (0, TILE_HEIGHT), (BOARD_WIDTH, TILE_HEIGHT), 5)
pygame.draw.line(game_display, WHITE, (0, 2 * TILE_HEIGHT), (BOARD_WIDTH, 2 * TILE_HEIGHT), 5)
# 更新屏幕
pygame.display.update()
退出pygame
pygame.quit()
这个代码演示了如何使用pygame库来创建一个8数字滑动拼图游戏。它首先初始化了游戏窗口和游戏板,然后在主循环中处理键盘事件并更新游戏板。最后,它使用pygame库绘制了游戏板和数字方块。
当然,这只是一个简单的示例。要实现15数字滑动拼图游戏,您需要对代码进行适当修改,例如修改游戏板的大小、更新方块的数量等等。此外,您可以添加更多的功能,如计时器、音效等等,来提高游戏的互动性和趣味性。
如果对您有帮助,请给与采纳,谢谢。
以下答案基于ChatGPT与GISer Liu编写:
下面是一个简单的 Python 代码实现,用于创建和解决滑块谜题:
import random
import copy
class SlidePuzzle:
def __init__(self, size):
self.size = size
self.board = []
for i in range(size):
self.board.append([])
for j in range(size):
self.board[i].append(i*size + j + 1)
self.board[size-1][size-1] = 0
self.empty_space = (size-1, size-1)
def shuffle(self):
for i in range(1000):
moves = self.get_possible_moves()
move = random.choice(moves)
self.move(move)
def get_possible_moves(self):
moves = []
row, col = self.empty_space
if row > 0:
moves.append((row-1, col))
if row < self.size-1:
moves.append((row+1, col))
if col > 0:
moves.append((row, col-1))
if col < self.size-1:
moves.append((row, col+1))
return moves
def move(self, move):
row, col = move
self.board[self.empty_space[0]][self.empty_space[1]] = self.board[row][col]
self.board[row][col] = 0
self.empty_space = move
def is_solved(self):
return str(self) == str(SlidePuzzle(self.size))
def copy(self):
return copy.deepcopy(self)
def __str__(self):
s = ''
for i in range(self.size):
for j in range(self.size):
if self.board[i][j] == 0:
s += ' '
else:
s += str(self.board[i][j]).rjust(2)
s += ' '
s += '\n'
return s
def play_puzzle(puzzle):
puzzle.shuffle()
while not puzzle.is_solved():
print(puzzle)
moves = puzzle.get_possible_moves()
print('Possible moves:', moves)
move = input('Enter move (row, col): ')
row, col = map(int, move.split(','))
if (row, col) in moves:
puzzle.move((row, col))
else:
print('Invalid move!')
print('Congratulations, you solved the puzzle!')
if __name__ == '__main__':
size = int(input('Enter size of puzzle (8 or 15): '))
puzzle = SlidePuzzle(size)
play_puzzle(puzzle)
这个代码实现了一个 'SlidePuzzle类,包括初始化、随机打乱、获取可行移动、移动、判断解决和复制等方法。在play_puzzle函数中,用户可以与游戏互动,选择移动并尝试解决谜题。
可以通过运行这个代码来测试,如下所示:
python slide_puzzle.py
Enter size of puzzle (8 or 15): 8
1 2 3 4
12 13 7 6
10 5 0 11
14 9 15 8
Possible moves: [(1, 2), (2, 1)]
Enter move (row, col): 2, 1
1 2 3