我试图得到所有可能的位置,一个骑士可以根据其目前的位置。
下面的代码是python中的。有一个简单的UI,用户输入当前位置,然后显示可能的位置。
,我已经做了很多,如果&否则。有人能显示出更短的路吗?
def getPostions():
ch = p.get()[0]
n = int(p.get()[1])
posList = []
posList = [ chr(ord(ch)-1)+str(int(n)-2), chr(ord(ch)-1)+str(int(n)+2),
chr(ord(ch)+1)+str(int(n)-2), chr(ord(ch)+1)+str(int(n)+2),
chr(ord(ch)-2)+str(int(n)-1), chr(ord(ch)-2)+str(int(n)+1),
chr(ord(ch)+2)+str(int(n)-1), chr(ord(ch)+2)+str(int(n)+1)]
if (ch == "a"):
# del 0,1,4,5
posList = [posList[2], posList[3], posList[6], posList[7]]
if (n == 8):
# del 3,7
posList = [posList[0],posList[2]]
elif (n == 7):
# del 3
posList = [posList[0],posList[2],posList[3]]
elif (n == 1):
# del 2,6
posList = [posList[1],posList[3]]
elif (n == 2):
# del 2
posList = [posList[1],posList[2],posList[3]]
elif (ch == "b"):
# del 4,5
posList = [posList[0],posList[1],posList[2],posList[3],posList[6],posList[7]]
if (n == 8):
# del 1,3,7
posList = [posList[0],posList[2],posList[4]]
elif (n == 7):
# del 1,3
posList = [posList[0],posList[2],posList[4],posList[5]]
elif (n == 1):
# del 0,2,6
posList = [posList[1],posList[3],posList[5]]
elif (n == 2):
# del 0,2
posList = [posList[1],posList[3],posList[4],posList[5]]
elif (ch == "h"):
# del 2,3,6,7
posList = [posList[0],posList[1],posList[4],posList[5]]
if (n == 8):
# del 1,5
posList = [posList[0],posList[2]]
elif (n == 7):
# del 1
posList = [posList[0],posList[2],posList[3]]
elif (n == 1):
# del 0,4
posList = [posList[1],posList[3]]
elif (n == 2):
# del 0
posList = [posList[1],posList[2],posList[3]]
elif (ch == "g"):
# del 6,7
posList = [posList[0],posList[1],posList[2],posList[3],posList[4],posList[5]]
if (n == 8):
# del 1,3,5
posList = [posList[0],posList[2],posList[4]]
elif (n == 7):
# del 1,3
posList = [posList[0],posList[2],posList[4],posList[5]]
elif (n == 1):
# del 0,2,4
posList = [posList[1],posList[3],posList[5]]
elif (n == 2):
# del 0,2
posList = [posList[1],posList[3],posList[4],posList[5]]
result['text'] = "Possible Locations for Knight are: " + ",".join(posList)
result.pack(pady=30)发布于 2013-11-29 19:05:27
在创建列表之后
posList = [ chr(ord(ch)-1)+str(int(n)-2), chr(ord(ch)-1)+str(int(n)+2),
chr(ord(ch)+1)+str(int(n)-2), chr(ord(ch)+1)+str(int(n)+2),
chr(ord(ch)-2)+str(int(n)-1), chr(ord(ch)-2)+str(int(n)+1),
chr(ord(ch)+2)+str(int(n)-1), chr(ord(ch)+2)+str(int(n)+1)]只需过滤:
posList = [pos for pos in posList if pos[0] in 'abcdefgh' and pos[1] in '12345678']https://stackoverflow.com/questions/20291079
复制相似问题