from random import choice # 导入choice函数
from os import system # 导入system函数
from time import sleep # 导入等待函数
won = 0 # 清空成功判断
start = False # 清空开始判断
puzzle = [1,2,3,4,5,6,7,8," "] # 初始化棋盘
def showpuzzle() : # 定义显示棋盘
system("clear") # 清屏
print(puzzle[0],puzzle[1],puzzle[2]) # 第1行
print(puzzle[3],puzzle[4],puzzle[5]) # 第2行
print(puzzle[6],puzzle[7],puzzle[8]) # 第3行
def move(direct) : # 定义移动函数
if direct == "W" or direct == "w" : # w向上
if puzzle[0] == " " :
puzzle[0] = puzzle[3]
puzzle[3] = " "
elif puzzle[1] == " " :
puzzle[1] = puzzle[4]
puzzle[4] = " "
elif puzzle[2] == " " :
puzzle[2] = puzzle[5]
puzzle[5] = " "
elif puzzle[3] == " " :
puzzle[3] = puzzle[6]
puzzle[6] = " "
elif puzzle[4] == " " :
puzzle[4] = puzzle[7]
puzzle[7] = " "
elif puzzle[5] == " " :
puzzle[5] = puzzle[8]
puzzle[8] = " "
elif start :
print("不能操作")
sleep(0.5)
elif direct == "S" or direct == "s" : # s向下
if puzzle[3] == " " :
puzzle[3] = puzzle[0]
puzzle[0] = " "
elif puzzle[4] == " " :
puzzle[4] = puzzle[1]
puzzle[1] = " "
elif puzzle[5] == " " :
puzzle[5] = puzzle[2]
puzzle[2] = " "
elif puzzle[6] == " " :
puzzle[6] = puzzle[3]
puzzle[3] = " "
elif puzzle[7] == " " :
puzzle[7] = puzzle[4]
puzzle[4] = " "
elif puzzle[8] == " " :
puzzle[8] = puzzle[5]
puzzle[5] = " "
elif start :
print("不能操作")
sleep(0.5)
elif direct == "A" or direct == "a" : # a向左
if puzzle[0] == " " :
puzzle[0] = puzzle[1]
puzzle[1] = " "
elif puzzle[1] == " " :
puzzle[1] = puzzle[2]
puzzle[2] = " "
elif puzzle[3] == " " :
puzzle[3] = puzzle[4]
puzzle[4] = " "
elif puzzle[4] == " " :
puzzle[4] = puzzle[5]
puzzle[5] = " "
elif puzzle[6] == " " :
puzzle[6] = puzzle[7]
puzzle[7] = " "
elif puzzle[7] == " " :
puzzle[7] = puzzle[8]
puzzle[8] = " "
elif start :
print("不能操作")
sleep(0.5)
elif direct == "D" or direct == "d" : # d向右
if puzzle[1] == " " :
puzzle[1] = puzzle[0]
puzzle[0] = " "
elif puzzle[2] == " " :
puzzle[2] = puzzle[1]
puzzle[1] = " "
elif puzzle[4] == " " :
puzzle[4] = puzzle[3]
puzzle[3] = " "
elif puzzle[5] == " " :
puzzle[5] = puzzle[4]
puzzle[4] = " "
elif puzzle[7] == " " :
puzzle[7] = puzzle[6]
puzzle[6] = " "
elif puzzle[8] == " " :
puzzle[8] = puzzle[7]
puzzle[7] = " "
elif start :
print("不能操作")
sleep(0.5)
else :
print("请输入正确的操作")
sleep(0.9)
for i in range(10000) : # 打乱棋盘,数字越高打乱程度越高
move(choice(["w","s","a","d"])) # 随机方向打乱
print("3*3华容道")
print("#####")
print("输入w向上移,输入s向下移,输入a向左移,输入d向右移,一次可输入多操作,如ww")
input("回车开始,一定有解") # 等待回车
start = True # 设置已开始
while won == 0 :
showpuzzle() # 显示棋盘
run = input() # 询问操作
for i in range(len(run)) : # 重复每一项
move(run[i])
if puzzle == [1,2,3,4,5,6,7,8," "] : # 如果棋盘是初始样子为成功
showpuzzle()
print("成功!")
won = 1 # 设置已成功