我写了一个简单的骰子游戏,除了我正在努力的部分之外,按预期工作,这是如何用按下的特定键结束游戏。我知道我做的是一个简单的错误(我是初学者),但是如果你能指出代码有什么问题,我会很高兴的。
谢谢!
import random
def game():
while True:
userRoll = int(raw_input("Enter a number from 1 to 10 [press q to end the game]: "))
compRoll = random.randrange(1, 11)
print "You rolled " + str(userRoll)
print "Computer rolled " + str(compRoll)
if userRoll > compRoll and userRoll > 0 and userRoll < 11:
print "You win!"
elif userRoll == compRoll:
print "It's a tie!"
elif userRoll < compRoll:
print "Computer wins!"
elif userRoll == 'q':
print "bye"
break
else:
print "You must enter number from 1 to 10. Try again..."
game()
答案 0 :(得分:1)
此代码无效:
elif userRoll == 'q':
print "bye"
break
到该代码执行时,您已将userRoll
转换为整数。所以,如果永远不能通过q
。
以下代码在转换为整数之前测试userRoll == 'q'
:
import random
def game():
while True:
userRoll = raw_input("Enter a number from 1 to 10 [press q to end the game]: ")
if userRoll == 'q':
print "bye"
break
userRoll = int(userRoll)
compRoll = random.randrange(1, 11)
print "You rolled " + str(userRoll)_
print "Computer rolled " + str(compRoll)
if userRoll > compRoll and userRoll > 0 and userRoll < 11:
print "You win!"
elif userRoll == compRoll:
print "It's a tie!"
elif userRoll < compRoll:
print "Computer wins!"
else:
print "You must enter number from 1 to 10. Try again..."
game()