import random
def creatList1(dimension):
global li1
if 1 <= dimension <= 10:
li1 = [i for i in range(1,dimension**2)]
li1.append(0)
random.shuffle(li1)
return li1
elif dimension < 0 or dimension > 10:
print('Wrong dimension interval.')
else:
print('Wrong input')
def judge(array):
inversion = 0
rowNumber = int(array.index(0) / dimension)
index = array.index(0)
array.remove(0)
for i in range(dimension**2-1):
for j in range(i,dimension**2-1):
if array[i] > array[j]:
inversion += 1
array.insert(index,0)
if dimension % 2 == 1:
if inversion % 2 == 0:
return True
else:
return False
elif dimension % 2 == 0:
if rowNumber % 2 == 1:
if inversion % 2 == 0:
return True
else:
return False
if rowNumber % 2 == 0:
if inversion % 2 == 1:
return True
else:
return False
def printPuzzle(array):
for i in range(dimension**2):
if (i % dimension == 0):
print('\n')
if(array[i] == 0 ):
print(" ",end = "\t")
continue
print (array[i],'\t',end='')
def motivation(li1,move):
if move == right:
if (position0 % dimension) == 0:
print('wrong move')
else:
li1[position0] = li1[position0 - 1]
li1[position0 - 1] = 0
elif move == left:
if (position0 % dimension) == (dimension - 1):
print('wrong move')
else:
li1[position0] = li1[position0 + 1]
li1[position0 +1] = 0
elif move == down:
if int(position0 / dimension) == 0:
print('wrong move')
else:
li1[position0] = li1[position0 - dimension]
li1[position0 - dimension] = 0
elif move == up:
if int(position0 / dimension) == (dimension - 1):
print('wrong move')
else:
li1[position0] = li1[position0 + dimension]
li1[position0 + dimension] = 0
def leftmovement(li1):
canmove = ['up-w','left-a','right-d','down-s']
if (position0 % dimension) == 0:
canmove.remove('right-d')
if (position0 % dimension) == (dimension - 1):
canmove.remove('left-a')
if int(position0 / dimension) == 0:
canmove.remove('down-s')
if int(position0 / dimension) == (dimension - 1):
canmove.remove('up-w')
return canmove
up = 'w'
left = 'a'
down = 's'
right = 'd'
li1 = []
print('Welcome to Sliding Puzzle game...')
dimension = int(input('Enter the desired dimension of the puzzle:'))
n = 0
while True:
creatList1(dimension)
if judge(li1):
break
while True:
position0 = li1.index(0)
answer = [i for i in range(1,dimension**2)]
answer.append(0)
printPuzzle(li1)
print('\n Enter your move','(',leftmovement(li1),')',end='')
move = input(':')
motivation(li1,move)
n += 1
if li1 == answer:
print('Congratulations! You solved the puzzle in',n,'moves!')
newgame = input('Enter \'n\' to start a new game or enter\'q\'to end the game:')
if newgame == 'n':
continue
elif newgame == 'q':
break
else:
print('Wrong input')
break
华容道Python实现方法
最新推荐文章于 2024-01-11 09:49:24 发布