Reputation: 95
So i'm making a game, and I have a dictionary of tuples containing the coordinates of the objects on the playing field that looks like this (for example):
location = {player : (1, 4), monster : (3, 2), escape : (4, 0)}
later in my code, I want to change the coordinates to easier to understand areas. The first defining part would be a corresponding letter, and then the second a number, looking like this: player would be in B4, monster in C2, and so on. the top right 'area' is represented by the tuple (4, 4), and the bottom left 'area' is represented by the tuple (0, 0). The only thing I have been able to think of that might work is something like this:
location = {player : (1, 4), monster : (3, 2), escape : (4, 0)}
letters = ["A", "B", "C", "D", "E"]
playerArea = "{}{}".format(letters[int(location[player[0]])+1], location[player[1]])
In short, it didn't work. I think the problem is in unpacking the tuples from the dictionary and using it as the number to get the letter from the list letters. Sorry is this was confusing, i'll try to answer all your questions.
Upvotes: 3
Views: 1120
Reputation: 226734
The core of the question is how to convert numerical row/column coordinates to something more readable (battleship-style). Here is a simple and fast function to do just that:
>>> def rc_to_abc(x, y):
return 'ABCDEFGHIJKLOMOPQRSTUVWXYZ'[x] + str(y)
>>> rc_to_abc(1, 4)
'B4'
>>> rc_to_abc(3, 2)
'D2'
>>> rc_to_abc(4, 0)
'E0'
Upvotes: 6
Reputation: 71471
You can use string.ascii_uppercase
to get a full list of the alphabet to use for each coordinate:
from string import ascii_uppercase as alphabet
location = {"player":(1, 4), "monster":(3, 2), "escape":(4, 0)}
new_location = {a:alphabet[b[0]-1]+str(b[-1]) for a, b in location.items()}
print(new_location)
Output:
{'player': 'A4', 'monster': 'C2', 'escape': 'D0'}
Upvotes: 0
Reputation: 78554
Use a dictionary comprehension using string formatting to build the new values. Unpacking the value-tuples is easily done:
location = {k: '{}{}'.format(letters[x-1], y) for k, (x, y) in location.items()}
print(location)
# {'player': 'A4', 'monster': 'C2', 'escape': 'D0'}
Also, you can use string.ascii_uppercase
instead of defining a list of alphabets manually.
OTOH, since your board supposedly has a (0, 0)
not sure what you intend to make of index 0
since A
is already taken as 1
.
Upvotes: 3