如何添加“作弊代码”来猜测我拥有的数字代码?

时间:2015-10-14 05:10:07

标签: python-2.7 random while-loop

下面有一段代码,其中随机选择了三个数字,用户有10次尝试来解决代码。我想添加一个作弊代码(可以这么说),以允许用户继续前进到下一个类/函数,而不必猜测三位数。

我尝试在or guess == 'cheat'之后添加while guess != code and guesses < 10。我尝试将if guess == code:转换为elif guess == code并在elif之前添加if guess == 'cheat'。我是一个菜鸟,我正在学习的来源说我的目标可以在一行中用两个单词完成。我迷路了... ...

 code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
 guess = raw_input("[keypad]> ")
 guesses = 0

 while guess != code and guesses < 9:
        print "WRONG!"
        guesses += 1
        guess = raw_input("Guess 3 numbers> ")

    if guess == code:
        print "Correct!"
        return my_func()
    else:
        print "Game over"
        return exit()

1 个答案:

答案 0 :(得分:0)

首先,确保您的代码正确缩进。由于你有它的工作,它似乎只是问题上的格式问题。

有点不清楚这个作弊码会是什么,但我会把它作为两件事之一:作弊或其他字符串。无论哪种方式,它都可以存储在名为cheat的变量中,当猜测为codecheat时,您可以退出while循环。

cheat = 'cheat'

while guess not in [code, cheat]:

还不清楚使用cheat时会发生什么,有两种可能的情况:

  1. cheat以失败告终。

    code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
    cheat = 'cheat'
    guess = raw_input("[keypad]> ")
    guesses = 0
    
    while guess not in [cheat, code] and guesses < 9:
        print "WRONG!"
        guesses += 1
        guess = raw_input("Guess 3 numbers> ")
    
    if guess == code:
        print "Correct!"
        return my_func()
    else:
        print "Game over"
        return exit()
    
  2. cheat以胜利结束游戏。

    code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
    cheat = 'cheat'
    guess = raw_input("[keypad]> ")
    guesses = 0
    
    while guess not in [cheat, code] and guesses < 9:
        print "WRONG!"
        guesses += 1
        guess = raw_input("Guess 3 numbers> ")
    
    if guess in [cheat, code]:
        print "Correct!"
        return my_func()
    else:
        print "Game over"
        return exit()