Home User input as string cannot be used to call variable in a class
Reply: 1

User input as string cannot be used to call variable in a class

Yes imeighteen
1#
Yes imeighteen Published in 2017-11-14 23:05:30Z

Not sure I am even asking the question correctly, but I will explain. I have created a class, and I have created instances in that class, the problem is I want to be able to use an instance which is chosen by the user via input. Let's say I would like to create a chess game. I want to be able to move a piece forward (possibly backward), left, and right. Suppose I have already created a method inside the class to move the piece and each piece has a name, x-coord, and y-coord. This is the issue I get

class Piece(object):
    def __init__(self, x , y):
         self.x = x
         self.y = y

    def move(self, amount, direction):
         if direction == 'right':
            self.x = self.x + amount
         if direction == 'left':
            self.x = self.x - amount
         if direction == 'up':
            self.y = self.y + amount
         if direction == 'down':
            self.y = self.y - amount

rook = Piece(0,0)

piece = input('What piece would you like to move?')

#Assume that the user types rook after this prompt

piece.move(4,'right')

Now I get an error because the input which is assigned to the variable piece is a string, and when I need rook.move, I am actually getting 'rook'.move I understand variables can be changed using int(var), float(var), str(var), but how would one go about changing a variable to a class variable.

alexisdevarennes
2#
alexisdevarennes Reply to 2017-11-14 23:45:38Z

A way would be to have a dictionary that maps the piece names to your classes.

So

pieces = {
    'Queen': Piece(0,0),
    'Tower': Piece(0,0),
    'Rook' Piece(0,0)
}

inp = input('Which piece would you like to move?')

if inp in pieces:
    pieces[inp]().move(4, right)
else:
    print('No such piece: %s - Valid pieces: %s' % (inp, pieces.keys()))
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.344192 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO