# open input file and overwrite/create output file filein = open("snakein.txt", "r") fileout = open("snakeout.txt", "w") #read file inputs inputs = filein.read().split() #set initial state of snake facingdir = "up" currentposition = [0,0] goalposition = [int(inputs[0]), int(inputs[1])] moveslist = [] # compute optimal next move based on snake's orientation and position def nextbestmove(currentpos, goalpos, facing): if facing == "up": if goalpos[0] - currentpos[0] < 0: facing = "left" return ["L", "L"] elif goalpos[0] - currentpos[0] > 0: facing = "right" return ["R", "R"] elif goalpos[0] - currentpos[0] == 0: # either left or right - won't change result facing = "right" return ["R", "R"] elif facing == "down": if goalpos[0] - currentpos[0] < 0: facing = "left" return ["R", "L"] elif goalpos[0] - currentpos[0] > 0: facing = "right" return ["L", "R"] elif goalpos[0] - currentpos[0] == 0: # either left or right - won't change result facing = "left" return ["R", "L"] elif facing == "right": if goalpos[1] - currentpos[1] < 0: facing = "down" return ["R", "D"] elif goalpos[1] - currentpos[1] > 0: facing = "up" return ["L", "U"] elif goalpos[1] - currentpos[1] == 0: # either left or right - won't change result facing = "up" return ["L", "U"] elif facing == "left": if goalpos[1] - currentpos[1] < 0: facing = "down" return ["L", "D"] elif goalpos[1] - currentpos[1] > 0: facing = "up" return ["R", "U"] elif goalpos[1] - currentpos[1] == 0: # either left or right - won't change result facing = "up" return ["R", "U"] # continue to calculate move sequence until reach goal while currentposition[0] != goalposition[0] or currentposition[1] != goalposition[1]: newmove = nextbestmove(currentposition, goalposition, facingdir) moveslist.append(newmove[0]) if newmove[1] == "U": facingdir = "up" currentposition[1] = currentposition[1] + 1 elif newmove[1] == "D": facingdir = "down" currentposition[1] = currentposition[1] - 1 elif newmove[1] == "L": facingdir = "left" currentposition[0] = currentposition[0] - 1 elif newmove[1] == "R": facingdir = "right" currentposition[0] = currentposition[0] + 1 # write the list of moves to the output file for item in moveslist: fileout.write(item) #close the files filein.close() fileout.close()