Система проверки целых чисел в моей текстовой игре не работает - PullRequest
0 голосов
/ 11 марта 2019

Итак, я создал систему для своей игры, чтобы я мог проверить, является ли ввод игрока целым числом.Но по какой-то причине, даже если я введу целое число, оно вернет «Пожалуйста, введите целое число».Я полагаю, что это как-то связано с этой функцией, цель которой - проверить входные данные игроков и определить, является ли это целым числом:

def pII(options):
    #PII stands for Player Input Int 
    playerInput = (input("==> "))

    while playerInput != range(1, options):
        print("Please enter an integer")
        playerInput = (input("==>"))  

    while playerInput <= 0 or playerInput > options:
        print("This is not an available option")
        playerInput = int(input("==>"))    

    return(playerInput)

Логика имеет смысл для меня, поэтому я нене понимаю, почему это не работает.Я не получаю никаких ошибок, так что по крайней мере это так.В любом случае, вот полный код моей игры, если это поможет.Сегмент кода, который я взял, взят из строк 15-27

#Made by Nick Pope--------------------------------------------------#
import sys
import os
import time
import random

os.system("mode con: cols=45 lines=80")
#Functions----------------------------------------------------------#
def save():
    print("                   This is supposed to save, but it doesn't work yet")

def clear():
    os.system('cls')

def pII(options):
    #PII stands for Player Input Int 
    playerInput = (input("==> "))

    while playerInput != range(1, options):
        print("Please enter an integer")
        playerInput = (input("==>"))  

    while playerInput <= 0 or playerInput > options:
        print("This is not an available option")
        playerInput = int(input("==>"))    

    return(playerInput)
#Graphics-----------------------------------------------------------#
  #All Graphic functions start with "g" so that i don't take any 
  #names I might need later
def gLine():
    #Function Draws lines 
    ps2("******************************************************************************************************************")

def gHeader():
    gLine()
    ps2(""" 
___________.__              __      __               __  .__             _____  __________      .__                 
\__    ___/|  |__   ____   /  \    /  \___________ _/  |_|  |__    _____/ ____\ \____    /____  |  |   ____   ____  
  |    |   |  |  \_/ __ \  \   \/\/   |_  __ \__  \\   __\  |  \   /  _ \   __\    /     /\__  \ |  |  / ___\ /  _ \ 
  |    |   |   Y  \  ___/   \        / |  | \// __ \|  | |   Y  \ (  <_> )  |     /     /_ / __ \|  |_/ /_/  >  <_> )
  |____|   |___|  /\___  >   \__/\  /  |__|  (____  /__| |___|  /  \____/|__|    /_______ (____  /____|___  / \____/ 
                \/     \/         \/              \/          \/                         \/    \/    /_____/         """)
    gLine() 

def gExit():
    clear()
    save()
    gLine()
    ps2("""
___________      .__  __  .__                                     
\_   _____/__  __|__|/  |_|__| ____    ____                       
 |    __)_\  \/  /  \   __\  |/    \  / ___\                      
 |        \>    <|  ||  | |  |   |  \/ /_/  >                     
/_______  /__/\_ \__||__| |__|___|  /\___  / /\ /\ /\ /\ /\ /\ /\ 
        \/      \/                \//_____/  \/ \/ \/ \/ \/ \/ \/""")
    gLine()
    sys.exit

def gHelp():
    gLine()
    p2("""
  ___ ___        .__              _____                       
 /   |   \  ____ |  | ______     /     \   ____   ____  __ __ 
/    ~    \/ __ \|  | \____ \   /  \ /  \_/ __ \ /    \|  |  \
\    Y    |  ___/|  |_|  |_> > /    Y    \  ___/|   |  \  |  /
 \___|_  / \___  >____/   __/  \____|__  /\___  >___|  /____/ 
       \/      \/     |__|             \/     \/     \/    """)
    gLine()
    print("Welcome to the help menu!")
    ps("I will write this later")
#Text Functions-----------------------------------------------------#

def ps(str):
    #This function allows the game to type like a real person 
    #PS is short for "Print Slow"
    typing_speed = 50
    count = 0
    space = True
    #This aspect of the function works with the autotext wrap
    #To make sure that it only wraps after full words, not 
    #midway through 
    for letter in str:
        if letter == " ":
            space == True
        else:
            space == False

        count += 1
        sys.stdout.write(letter)
        sys.stdout.flush()
        time.sleep(random.random()*10.0/typing_speed)
        #The 3 lines after this function as an autotext wrap.
        if count == 100 and space == True:
            print('\n')
            count = 0
    print('')

def ps2(str):
    #This function is the same as PS1 but without the Text Wrapping 
    typing_speed = 200
    for letter in str:
        sys.stdout.write(letter)
        sys.stdout.flush()
        time.sleep(random.random()*10.0/typing_speed)
    print('')
#Player Data--------------------------------------------------------#
pName = "Yorick"
playerInput = 0
#Mechanics----------------------------------------------------------#

#Game Loop----------------------------------------------------------#

def titleScreen():
    gHeader()
    ps("1. Start")
    ps("2. Load")
    ps("3. Exit")
    ps("4. Help")
    options = 4

    pII(options)

    if pII == 1:
        start0()
    if pII == 2:
        load
    if PII == 3:
        gExit()
    if PII == 4:
        gHelp()

def start0():
    clear()
    ps("Your name my child..what do the mortals use to summon you?")
    pName = str(input("==>"))
    ps(pName +"?" " I amused by the creativity of the lower realms. The void..she calls to you, she favors you, just as her divinity does to me. You..shall be my avatar. It is time. Her prophecy shall be fullfilled. Awaken, my child!")






titleScreen()

1 Ответ

1 голос
/ 11 марта 2019

Проблема заключается в тестировании, если опция верна с playerInput != range(1, options).Это всегда возвращает true, так как playerInput никогда не является диапазоном.Сравнение должно быть:

playerInput not in range(1, options)

, которое сравнивает playerInput с каждым значением в диапазоне

Помните, что мы также хотим принять входные данные как целое число, поэтомукласс становится:

def pII(options):
    #PII stands for Player Input Int 
    playerInput = (input("==> "))

    while playerInput not in  range(0,options):
        print("Please enter an integer")
        playerInput = int(input("==>"))  

    while playerInput <= 0 or playerInput > options:
        print("This is not an available option")
        playerInput = int(input("==>"))    

    return(playerInput)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...