我正在用Python创建一个滑动拼图游戏,其中有一个n x n网格,每个正方形都有一个数字,除了一个是空白的,玩家输入一个数字,这个数字在空白正方形的旁边或上面/下面,与它交换位置。每次有效移动后,网格都会更新并打印出来,然后询问玩家下一步的移动,除非谜题被解决。游戏的目的是让所有的数字按数字顺序排列,最后一个方块是空白的。我需要你帮我数一个玩家完成拼图所走的步数。
我试过使用初始化为零的number_of_moves,并在玩家每次移动时增加一个。但是,当打印移动次数时,它总是打印“移动次数= 0”,然后打印“移动次数= 1”。不管我走多少步都是这样。到目前为止我写的代码是:
def milestone_2(tiles):
def valid_moves(tiles_list, grid_size):
number_moves = 0
while tiles_list[:-1] != sorted(tiles_list[:-1]) and tiles_list[-1] != "":
while True:
choice = input("Your move: ")
if choice == 'quit':
print("Quitting...")
return
if choice not in tiles_list:
print(f"{choice} is not valid. Try again.")
number_moves += 1
continue
blank_square_index = tiles_list.index("")
choice_index = tiles_list.index(choice)
if abs(choice_index - blank_square_index) == grid_size or ((choice_index // grid_size) == (blank_square_index // grid_size)) and (abs(choice_index - blank_square_index)) == 1 :
tiles_list[blank_square_index], tiles_list[choice_index] = tiles_list[choice_index], tiles_list[blank_square_index]
milestone_2(','.join(tiles_list))
number_moves += 1
break
else:
print(f"{choice} is not valid. Try again.")
number_moves += 1
print(f"You won in {number_moves} moves. Congratulations!")
def create_grid():
tiles_list = tiles.split(',')
grid_size = int(len(tiles_list) ** 0.5)
result = "┌" + ("────┬") * (grid_size -1) + "────┐\n"
for i in range(0, len(tiles_list), grid_size):
result += "│"
for j in range(grid_size):
tile = tiles_list[i+j]
if tile == "":
result += " │"
elif len(tile) == 1:
result += " " + tile + " │"
elif len(tile) == 2:
result += " " + tile + " │"
result += "\n"
if i < len(tiles_list) - grid_size:
result += "├" + (grid_size-1) * "────┼" + "────┤\n"
result += "└" + (grid_size-1)*"────┴" + "────┘"
print(result)
valid_moves(tiles_list, grid_size)
create_grid()
milestone_2("1,2,3,4,5,6,7,8,9,10,11,12,13,14,,15")
1条答案
按热度按时间3zwjbxry1#
您将获得2个输出
你赢了0步。恭喜!
你赢了1步。恭喜!
因为你在同一个函数中调用了milestone_2()函数。
更正为,
试试看