Frederick Boreham Frederick Boreham -4 years ago 43
Python Question

Check list from input added to string in python 3

Hi stack overflow community, I am working on a chess move predictor in Python 3 and have stumbled into an obstacle, the problem is that I'm trying to check a list of possible moves from a square depending on an input. However to show whether the move is for black or white I have to put say a w after it. How do I check the list which name is made of strings and inputs?
This is a list of possible moves for the first move:

PWA2m = ["A3", "A4", "B3"]
PWB2m = ["B3", "B4", "C3", "A3"]
PWC2m = ["C3", "C4", "D3", "B3"]
PWD2m = ["D3", "D4", "E3", "C3"]
PWE2m = ["E3", "E4", "D3", "F3"]
PWF2m = ["F3", "F4", "E3", "G3"]
PWG2m = ["G3", "G4", "F3", "H3"]
PWH2m = ["H3", "H4", "G3"]
K1WB1m = ["A3", "C3"]
K2WG1m = ["F3", "H3"]

And this is the checker so far:

wmove = input("What square are you moving from?")
if wmove == "":
Piece = squares.get(wmove)

I would like it to output something like this if the user has put in a valid square:

Possible Moves for PawnWhite:
B3, B4, C3, A3

Answer Source

It sounds like you're trying to access the lists for different pieces by searching the names of the lists. However, the names of variables shouldn't generally be accessed by the program. A simple solution to your problem is to use a dict to store the pieces and their lists of possibilities:

current_state = {"A1":"Kw", "B5":"Qb"} # and so on
current_possibilities = {"A1": ["B2", "A2"], "B5":["B4", "B6", "C4", "C5", "C6"]}

Then, you can access the current piece locations/where they can move quite simply:

print("The piece at {} is a {} and can move to: {}".format(
    input, current_state[input][:-1], current_possibilities[input]))

Which, given the input "A1" above, will then print:

The piece at A1 is a K and can move to: ['B4', 'B6', 'C4', 'C5', 'C6']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download