所以我的任务(我必须使用while语句)是做一个数字猜测游戏,其中一部分是显示玩家在得到正确的数字后猜测的次数。我找到了一些我读过的东西,但不起作用。这是我的代码。
#A text program that is a simple number guessing game.
import time
import random
#Setting up the A.I.
Number = random.randint(1,101)
def AI():
B = AI.counter =+ 1
Guess = int(input("Can you guess what number I'm Thinking of?: "))
while Guess > Number:
print("nope, to high.")
return AI()
while Guess < Number:
print("Sorry, thats to low. try again!")
return AI()
while Guess == Number:
print("Congragulations! you win! You guessed " + str(B) + " times")
time.sleep(60)
quit()
AI.counter = 0
AI()虽然当玩家得到正确的数字时,它说玩家在一个猜测中得到了它,即使情况并非如此。
发布于 2018-04-04 20:50:18
使用默认参数:
def AI(B=1):
Guess = int(input("Can you guess what number I'm Thinking of?: "))
while Guess > Number:
print("nope, to high.")
return AI(B + 1)
while Guess < Number:
print("Sorry, thats to low. try again!")
return AI(B + 1)
while Guess == Number:
print("Congragulations! you win! You guessed " + str(B) + " times")
time.sleep(60)
return然后调用该函数:
AI()另外,您应该在这里使用if而不是while,因为循环只运行一次,但是while也能工作,所以这很好。此外,递归可能会消耗您的RAM,这只是浪费资源,前提是您可以实现与循环相同的功能,但是您的方法可以工作,所以这也很好。
发布于 2018-04-04 20:50:35
你离我很近了辛普森!这里有一个稍加修改的版本,应该可以为您提供您想要的内容:)
如果你有什么问题请告诉我!
#A text program that is a simple number guessing game.
import random
#Setting up the A.I.
def AI():
counter = 1
number = random.randint(1,101)
guess = int(input("Can you guess what number I'm Thinking of?: "))
while guess != number:
if guess < number:
print("Sorry, thats to low. try again!")
else:
print("nope, too high")
counter += 1
guess = int(input("Can you guess what number I'm Thinking of?: "))
print("Congragulations! you win! You guessed " + str(counter) + " times")
time.sleep(60)
quit()
AI()发布于 2018-04-04 20:51:26
不使用递归-将时间更改为ifs,并在方法中添加计数器。
import time
import random
Number = random.randint(1,101)
def AI():
B = 1
Guess = int(input("Can you guess what number I'm Thinking of?: "))
while True:
if Guess > Number:
print("nope, to high.")
elif Guess < Number:
print("Sorry, thats to low. try again!")
if Guess == Number:
print("Congragulations! you win! You guessed " + str(B) + " times")
time.sleep(2)
break # leave the while true
# increment number
B += 1
Guess = int(input("Can you guess what number I'm Thinking of?: "))
AI()https://stackoverflow.com/questions/49660097
复制相似问题