My solution:
from sys import exit
f = file("input.txt")
horseloc = f.readline()[:-1] # White, first move.
pawnloc = f.readline() # Black.
f.close()
alphavalue = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7}
horseloc = [(alphavalue[horseloc[0]], int(horseloc[1]) - 1)]
pawnloc = (alphavalue[pawnloc[0]], int(pawnloc[1]) - 1)
#
# Functions for checking if the game is over, and, if so, exiting.
#
def finish():
f = file("output.txt", "w")
f.write(str(movecount))
f.close()
print "Done. Check output.txt for the solution."
def check():
global movecount
isdone = bool(0)
for mustang in horseloc:
if mustang == pawnloc: # Checks if a horse ate the pawn.
isdone = bool(1)
if (pawnloc[0] == mustang[0]) and (pawnloc[1] - 1 == mustang[1]):
isdone = bool(1) # Checks if the a is blocking the pawn's path.
if pawnloc[1] == 0: # Checks if the pawn reached n0.
isdone = bool(1)
movecount = 0
if isdone == bool(1): # Checks if the game is over because of one of the above reasons.
finish()
exit()
return isdone
#
# Functions for moving around the board.
# cleanuphorse(): Removes repeating values caused by various paths that lead to identical locations on the board.
# movehorse(): Moves the horse (or, rather, horses) around the board and removes the old locations from the board.
# movepawn(): Moves the pawn around. Also eats the horse if it's in the pawn's hit range.
#
def cleanuphorse():
for mustang in horseloc[:]:
if horseloc.count(mustang) > 1:
horseloc.pop(horseloc.index(mustang))
def movehorse():
for mustang in horseloc[:]:
global horseloc
if mustang[1] <= 5:
if mustang[0] <= 6:
horseloc.append((mustang[0] + 1, mustang[1] + 2))
if mustang[0] >= 1:
horseloc.append((mustang[0] - 1, mustang[1] + 2))
if mustang[1] >= 2:
if mustang[0] <= 6:
horseloc.append((mustang[0] + 1, mustang[1] - 2))
if mustang[0] >= 1:
horseloc.append((mustang[0] - 1, mustang[1] - 2))
if mustang[1] <= 6:
if mustang[0] <= 5:
horseloc.append((mustang[0] + 2, mustang[1] + 1))
if mustang[0] >= 2:
horseloc.append((mustang[0] - 2, mustang[1] + 1))
if mustang[1] >= 1:
if mustang[0] <= 5:
horseloc.append((mustang[0] + 2, mustang[1] - 1))
if mustang[0] >= 2:
horseloc.append((mustang[0] - 2, mustang[1] -1))
horseloc.pop(horseloc.index(mustang))
global movecount
movecount = movecount + 1
cleanuphorse()
check()
def movepawn():
for mustang in horseloc[:]:
if ((pawnloc[0] - 1 == mustang[0]) and (pawnloc[1] - 1 == mustang[1])) or ((pawnloc[0] + 1 == mustang[1]) and (pawnloc[1] - 1 == mustang[1])):
horseloc.pop(horseloc.index(mustang))
global pawnloc
pawnloc = (pawnloc[0], pawnloc[1] - 1)
check()
movecount = 0
check()
for n in range(1, 15):
if n % 2 != 0:
movehorse()
if n % 2 == 0:
movepawn()
I think I could've done a bit better with how I called all of the functions (call them from within the loop), but it works, so I'm not complaining.