我正在创建一个猜测程序,允许两个玩家竞争,其中一个人输入数字,另一个人猜测答案。但是,一开始我使用输入代码让用户输入一个数字,但这显示了用户输入,这允许第二个用户查看条目。
我试着使用numberGuess = msvcrt.getch(),结果我得到了如下所示的结果。我应该怎么做才能在numberGuess上执行相同的检查,而不会出现错误?以及用户条目被替换为"*“
我的代码:
import msvcrt
from random import randint
import struct
def HumanAgainstHuman ():
changemax = input("Would you like to change the maximum?")
if changemax.lower() == "yes":
maxNumber = int(input("Enter the new max:"))
else:
maxNumber = 9
numberGuess = msvcrt.getch()
nuberGuress= int(numberGuess)
while numberGuess < 1 or numberGuess > maxNumber:
numberGuess = input("Not a valid choice, please enter another number: \n").replace
guess = 0
numberGuesses = 0
while guess != numberGuess and numberGuesses < 3:
guess = int(input("Player Two have a guess: \n"))
numberGuesses = numberGuesses + 1
if guess == numberGuess:
print("Player Two wins")
else:
print("Player One wins")
PlayAgain()
def choosingGame():
Choice = int(input("Choose...\n 1 for Human Vs Human \n 2 for Human Vs AI \n 3 for AI Vs AI \n"))
while Choice < 1 or Choice > 3:
Choice = int(input("Try again...Choose...\n 1 for Human Vs Human \n 2 for Human Vs AI \n 3 for AI Vs AI \n"))
if Choice == 1:
HumanAgainstHuman()
elif Choice == 2:
HagainstAI()
elif Choice == 3:
AIagainstAI()
def PlayAgain():
answer = int(input("Press 1 to play again or Press any other number to end"))
if answer == 1:
choosingGame()
else:
print("Goodbye!")
try:
input("Press enter to kill program")
except SyntaxError:
pass
choosingGame()
运行程序时的结果
Choose...
1 for Human Vs Human
2 for Human Vs AI
3 for AI Vs AI
1
Would you like to change the maximum?no
Traceback (most recent call last):
File "C:/Users/Sarah/Documents/testing.py", line 55, in <module>
choosingGame()
File "C:/Users/Sarah/Documents/testing.py", line 38, in choosingGame
HumanAgainstHuman()
File "C:/Users/Sarah/Documents/testing.py", line 14, in HumanAgainstHuman
ValueError: invalid literal for int() with base 10: b'\xff'
发布于 2016-11-21 21:52:32
正如我在评论中所说的,我不能重现你在getch()
上的问题。也就是说,下面是HumanAgainstHuman()
函数的一个改进版本(但仍然不完善),它演示了一种使用getch()
的方法,该方法可以预防您遇到的问题类型。
这个函数还有另一个问题,它试图在变量guess
被赋值之前引用它的值--然而,由于我不能确切地理解您试图做什么,这个问题仍然留在代码中等待解决……
def HumanAgainstHuman():
changemax = input("Would you like to change the maximum?")
if changemax.lower() == "yes":
maxNumber = int(input("Enter the new max:"))
else:
maxNumber = 9
numberGuess = msvcrt.getch()
try:
numberGuess = int(numberGuess)
except ValueError:
numberGuess = 0 # assign it some invalid number
while numberGuess < 1 or numberGuess > maxNumber:
numberGuess = input("Not a valid choice, please enter another number:\n")
guess = 0
numberGuesses = 0
while guess != numberGuess and numberGuesses < 3: ## different problem here!
guess = int(input("Player Two have a guess:\n"))
numberGuesses = numberGuesses + 1
if guess == numberGuess:
print("Player Two wins")
else:
print("Player One wins")
PlayAgain()
https://stackoverflow.com/questions/40707141
复制相似问题