我是一个相对新人,并且正在尝试创建一个游戏,其中用户和comp轮流猜测彼此的游戏。当用户输入字符串时,我知道我在while / if运算符中做错了。是的。
在两个地方:
1.用户决定谁应该先行(if a in ["Y", "y"]
2. compguess
函数(while ans = False:
)中的while循环只是向下跳过。
a = input("Shall I guess first? (Y/N):")
userscore = 1
compscore = 1
def compguess():
global compscore
low = 0
high = 100
c = 50
ans = False
while ans = False:
print ("Is the number", c , "?")
d = input("Enter Y if correct / L if your number is lower or H if higher:")
if d in ["Y" , "y"]:
ans = True
elif d in ["H"]:
high = c
c = int((c + low) / 2)
compscore = compscore + 1
elif d in ["L"]:
low = c
c = int((c + high) / 2)
compscore = compscore + 1
else:
print ("invalid input")
def userguess():
global userscore
g = r.randint(1,100)
h = input("Enter your guess number:")
i = int(h)
while g != i:
if g > i:
h = input("You guessed lower. Guess again:")
i = int(h)
userscore = userscore + 1
else:
h = input("You guessed higher. Guess again:")
i = int(h)
userscore = userscore + 1
if a in ["Y", "y"]:
compguess()
userguess()
else:
userguess()
compguess()
if userscore == compscore:
print("Its a tie !!")
elif userscore < compscore:
print ("Congrats ! You won !")
else:
print ("I won !! Better luck next time")
答案 0 :(得分:1)
我将你的while循环条件更改为:
while not ans:
此外,在r.randint(1,100)
中,r
未定义。如果要使用随机函数,则需要导入它:
您可以执行import random
或from random import randint
。如果您想保留r
,可以执行import random as r
。
您还应该指出猜谜游戏何时结束。虽然它暗示它们互相流动,但我最初感到困惑。
计算机猜测的措辞不正确:
Is the number 50 ?
Enter Y if correct / L if your number is lower or H if higher:H
Is the number 25 ?
Enter Y if correct / L if your number is lower or H if higher:L
Is the number 37 ?
Enter Y if correct / L if your number is lower or H if higher:Y
I won !! Better luck next time
初步猜测是50.然后,我说我的数字更高。然后随后的猜测会降低。你颠倒了数学或措辞。
答案 1 :(得分:0)
while ans = False:
应该是
while ans == False:
答案 2 :(得分:0)
n log(base2) n
在这里检查d是否为H(更高)并且您计算它是否更低print ("Is the number", c , "?")
d = input("Enter Y if correct / L if your number is lower or H if higher:")
if d in ["Y" , "y"]:
ans = True
elif d in ["H"]:
high = c
c = int((c + low) / 2)
compscore = compscore + 1
elif d in ["L"]:
low = c
c = int((c + high) / 2)
compscore = compscore + 1
else:
print ("invalid input")
所以你需要切换
另外,您在((50 + 0) /2) = 25
=