2015-10-25 4 views
1

Я использую класс cmd класса Python в своем приложении. Я бы хотел определить cmd.prompt() на лету, но не могу найти способ сделать это. Это то, что у меня есть, что, кажется, не работает:Определить или изменить командную строку с переменной в Python

gamestate = 'adventure' #gamestate is either 'adventure' or 'battle' 

def changestate(arg): 
    global gamestate 
    print('Right now the gamestate is {}'.format(gamestate)) 
    if not arg == '': 
     print("Now we are changing the gamestate from {} to {}".format(gamestate, arg.lower())) 
     gamestate = arg.lower() 
     print('We have changed the gamestate to {}'.format(gamestate)) 
    else: 
     print('{} isn\'t a valid gamestate'.format(arg.upper())) 

class AdventureCmd(cmd.Cmd):  
    global gamestate 
    if gamestate == 'adventure': 
     prompt = '\nWhat do you do?\n' 
    else: 
     prompt = '\nWhat do you battle?\n' #this lets us know we are now in 'battle' gamestate 

    def do_changestate(self,arg): 
     changestate(arg) #'changestate battle' changes the gamestate to 'battle' 

if __name__ == '__main__': 
    AdventureCmd().cmdloop() 

Это выход я получаю:

What do you do? 
changestate adventure 
Right now the gamestate is adventure 
Now we are changing the gamestate from adventure to adventure 
We have changed the gamestate to adventure 

What do you do? 
changestate battle 
Right now the gamestate is adventure 
Now we are changing the gamestate from adventure to battle 
We have changed the gamestate to battle 

What do you do? #should be 'What do you battle' 

Я просто питон n00b, так что, возможно, что-то делать с изменением суперклассов или что-то в этом роде, я еще не знаю, как это сделать. Можете ли вы, ребята, дать мне совет?

EDIT: Я также попытался:

class AdventureCmd(cmd.Cmd): 
    global gamestate 
    def preloop(self): 
     if gamestate == 'adventure': 
      self.prompt = '\nWhat do you do?' 
     elif gamestate == 'battle': 
      self.prompt = '\nWhat do you battle?' 

ответ

0

Большая часть кода выполняется только один раз, когда определен AdventureCmd класс. Он не запускается каждый раз, когда пользователь предоставляет вход. В частности, этот код выполняется только один раз при определении класса:

global gamestate 
if gamestate == 'adventure': 
    prompt = '\nWhat do you do?\n' 
else: 
    prompt = '\nWhat do you battle?\n' #this lets us know we are now in 'battle' gamestate 

Как результат, вы никогда не переопределить переменную prompt. Вы можете сделать это так:

класс AdventureCmd (cmd.Cmd):
глобальный GameState если GameState == 'приключение': подсказка = '\ NWhat поживаете \ п? еще: подскажите = «\ NWhat вы боретесь? \ п» # Эта дает нам знать, мы теперь в «боевом» GameState

def do_changestate(self,arg): 
    changestate(arg) 
    # Note we're setting self.prompt here as the prompt is an 
    # instance variable for this instance of AdventureCmd. Note also 
    # that we change the prompt in the method that gets called to 
    # handle the command 
    if gamestate == 'adventure': 
     prompt = '\nWhat do you do?\n' 
    else: 
     prompt = '\nWhat do you battle?\n' #this lets us know we are now in 'battle' gamestate 

Там в несколько других изменений вы могли бы рассмотреть в вашем коде. Например, вероятно, неплохо сделать gamestate переменной экземпляра, а не глобальной, и это поможет с расширяемостью, если вместо цепочки циклов if/elif для изменения приглашения у вас есть словарь, сопоставляющий игру gamestate, чтобы исправить приглашение.

Примечание: я не тестировал вышеуказанный код, поэтому могут быть опечатки или другие ошибки, но я думаю, что основная идея правильная.

Смежные вопросы