简体   繁体   English

Python raw_input变量名

[英]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. 因此,我正在做一个小游戏,当前的计划是让用户输入图块的名称(例如A1或B7),然后精灵将向该图块移动。 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. 我制作了称为A1和B7等的变量,然后给它们赋值(x,y),其中x和y是它们在网格上的相对位置。 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. 我已使用raw_input命令让用户输入其图块名称,但我希望该变量的值成为图块变量的名称。

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. 假设用户输入“ C5”,我希望它引用变量“ C5”,该变量存储图块C5的坐标,然后将精灵移动到那些坐标。 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: 现在,当用户输入一个位置(如'A2'我们可以通过检查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() )的任何对象,作为一个猜测/示例:

>>> move_sprite(locations[destination])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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