简体   繁体   中英

Python raw_input a variable name

So I'm making a little game, where the current plan is for the user to input the name of a tile (eg. A1 or B7) then a sprite will move tot hat tile. I have made variables called A1 and B7 etc, and then given them values of (x,y) where x and y are their relative positions on the grid. I have used the raw_input command to get the user to input their tile name, but I want the value of that variable to be the name of the tiles variable.

So say the user inputs "C5" I want this to reference the variable "C5", which stores the coordinates of tile C5, then move the sprite to those coordinates. Is there any way of doing this?

Store your locations and their names in a dictionary like this:

>>> locations = {'A1': (1, 0),
                'B1': (2, 0),
                'C1': (3, 0),
                'A2': (1, 1),
                'B2': (2, 1)
                }

>>> destination = raw_input('Where would you like to move?: ')

Now when the user enters a location, like 'A2' we can access the coordinates by checking the dict:

>>> locations[destination]
(1, 1)

Then you can send this to whatever you're using to move the sprite ( move_sprite() ) as a guess / example:

>>> move_sprite(locations[destination])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM