This is my first little python project. I want to get to a point where i can solve chess puzzles like this one from puzzling.stackexchange. I want to be able to change the board size to something like 15*15 or 3*7 and still all rules to apply.
So far, you can just run the file and it gives all possible moves for a knight on a random starting position. You can also put it a given position in string form like "A5" for the variable "startKnight".
What can I do better? The letter number swap function to swap between the chess and matrix connotation looks so big and ugly... The knightmoves function looks good to me, but maybe you can tell me what to improve :)
from random import randint
def letterNumberSwap(x):
# change letters to numbers and vice versa
if x == "A":
return 1
elif x == "B":
return 2
elif x == "C":
return 3
elif x == "D":
return 4
elif x == "E":
return 5
elif x == "F":
return 6
elif x == "G":
return 7
elif x == "H":
return 8
elif x == 1:
return "A"
elif x == 2:
return "B"
elif x == 3:
return "C"
elif x == 4:
return "D"
elif x == 5:
return "E"
elif x == 6:
return "F"
elif x == 7:
return "G"
elif x == 8:
return "H"
else:
print("Something is wrong.")
moveList = [] # list of moves in matrix connotation
possibleMoves = [] # list of moves in chess connotation
def knightMoves(position):
# calculate all knight moves from position
column, row = list(position.strip().upper())
column = letterNumberSwap(column)
c,r = int(column), int(row)
if (0 < (c - 2) <= 8):
if (0 < (r - 1) <= 8):
moveList.append([c - 2, r - 1])
if (0 < (r + 1) <= 8):
moveList.append([c - 2, r + 1])
if (0 < (c - 1) <= 8):
if (0 < (r - 2) <= 8):
moveList.append([c - 1, r - 2])
if (0 < (r + 2) <= 8):
moveList.append([c - 1, r + 2])
if (0 < (c + 1) <= 8):
if (0 < (r - 2) <= 8):
moveList.append([c + 1, r - 2])
if (0 < (r + 2) <= 8):
moveList.append([c + 1, r + 2])
if (0 < (c + 2) <= 8):
if (0 < (r - 1) <= 8):
moveList.append([c + 2, r - 1])
if (0 < (r + 1) <= 8):
moveList.append([c + 2, r + 1])
for entry in moveList:
# back to chess connotation
possibleMoves.append(letterNumberSwap(entry[0])+str(entry[1]))
randomStart = str(letterNumberSwap(randint(1,8)))+str(randint(1,8))
startKnight = randomStart
knightMoves(startKnight)
print("A Knight on " + startKnight + " can go to:")
for entry in possibleMoves:
print(entry,end = ' ')