2013-10-31 35 views
0

我正在做一个程序来做一个猜谜游戏;我需要能够让程序给出H或L的反馈,只有当一个数字高于3或小于3时。如果x比y高3

这是我目前有

import random 
def game3(): 
    rndnumber = str(random.randint(0,9999)) #gets a number between 0-9999 
    while len(rndnumber) < 4: 
     rndnumber = '0'+ rndnumber # adds 0s incase the number is less then a 1000 
    print(rndnumber) #lets me know that the program generates the right type of number (remove this after testing) 
    feedback = 0 #adds a variable 
    for x in range(1,11): #makes a loop that runs for 10 times 
     print("Attempt",x) 
     attempt = input("Guess a number between 0-9999:")#gets the users guess 
     feedback = "" #makes a feedback variable 
     for y in range(4): #makes a loop that runs for 4 times 
      if attempt[y] == rndnumber[y]: #if attempt is the same then add a Y to the number 
       feedback += "Y" 
      elif attempt[y] < rndnumber[y]: 
       feedback += "L" 
      elif attempt[y] > rndnumber[y]: 
       feedback += "H" 
      else: 
       feedback += "N" 
     print(feedback) 
     if x == 10: 
      print("You Lose the correct answer was",rndnumber) 
     if feedback == "YYYY" and x > 1: 
      print("You win it took",x,"attempts.") 
      break; #stops the program 
     elif feedback == "YYYY": 
      print("You won on your first attempt!") 
      break; #stops the program 
+1

东西时,我就开始学习编程,我意识到的是,有两种方法可以写东西了,名字的事情,讲道理,等:*第一个*,有自己的方式。 *然后*,有正确的方法。当你给变量命名时,首先你要从自己的名字开始,它们可能很长,但它们对你来说是有意义的。问题在于你得到的任何帮助都不在你的心理语言中,你必须翻译很多。最终,更流行的命名约定和逻辑方法对您来说更容易。听听我的建议,并学习现在流行的做事方式;它使学习变得更容易 – jwarner112

+0

为什么比较一个循环中的个位数比较数字?为什么不把整个数字与'if attempt == rndnumber'进行比较? – Barmar

+0

@Barmar因为他正在编写类似于Mastermind的东西。 – sdasdadas

回答

0

您可以使用

if attempt == rndnumber + 3 or attempt == rndnumber - 3: 
    # Do something... 
+0

当我试图做到这一点时,我得到这个错误 'int'对象不可订阅 – Alas

+0

我不知道错误来自哪里 - 但由于你正在与他们作为字符串,你需要包装为了能够加减3,在'int'转换中的变量。 – sdasdadas

+0

当我这样做的时候,我仍然会得到同样的错误,它会把我的rndnumber作为str吗? – Alas

0

在第10行中,您在变量尝试中保存了一个字符串。 然而,在第13行中,您将尝试用作字典。

您可能想要在此重新考虑您的整个方法。

编辑:

当然我也是在一个点上做了猜谜游戏。虽然我现在肯定会使用不同的方法,但我认为这可能对您有所帮助,并在您的Python 3代码中为自己的游戏构建您的需求。

import random 

print ("Hello! What is your name?") 
name = input() 
print ("Well,", name, ", I am thinking of a number between 1 and 100.\nTake a guess.") 
number = random.randint(1, 100) # create a number between 1 and 100 
guess = input() # read user's guess 
guess = int(guess) 
guessnumber = 1 # first try to guess the number 
guessed = False # number isn't guessed yet 
while guessed == False: 
    if (number == guess): 
     print ("Good job,", name + "! You guessed my number in",guessnumber, "guesses!") 
     guessed = True 
    elif (guess > number): 
     print ("Your guess is too high.") 
     guess = input("Take another guess: ") 
     guess = int(guess) 
     guessnumber+=1 
    else: 
     print ("Your guess is too low.") 
     guess = input("Take another guess: ") 
     guess = int(guess) 
     guessnumber+=1 
+0

我觉得他的代码已经很像这个结构了。 – sdasdadas