2016-11-20 4 views
1

Я создаю программу угадывания, которая позволяет двум игрокам конкурировать, где один вводит число, а другой догадывается ответ. Однако сначала я использовал код ввода для пользователя, чтобы ввести число, но это отобразило пользовательский ввод, который позволяет второму пользователю просматривать запись.Использование msvcrt.getch()

Если я устал, используя 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' 
+1

Я не думаю, что вы имели в виду, чтобы иметь 'nuberGuress' там ... –

+1

вы используете Python 2 или 3? Какой ключ вы нажали, чтобы получить значение «ValueError»? – martineau

+0

@martineau python 3.5 – Sarah

ответ

0

Как я уже сказал в комментарии, я не могу воспроизвести ваша проблема с 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()