Запрашивает ввод пользователя, пока программа продолжает работать? - PullRequest
0 голосов
/ 17 ноября 2018

Создание автоматизированной боевой системы, но я хочу, чтобы у пользователя был какой-то вклад.Проблема заключается в том, что всякий раз, когда я запрашиваю ввод, вся функция останавливается до тех пор, пока не получит ввод от пользователя.

def EnemyAttack(TypeOfEnemy):
global raceinput
special_ability_prompt = input("") #When you make the magic classes and put them in a dictionary, append them here.
while (Player.hp > 1 and TypeOfEnemy.hp > 1):
    if (special_ability_prompt == "HeavyAttack()"):
        if (raceinput == "CAVE"):
            TypeOfEnemy.hp = TypeOfEnemy.hp - (Player.atk / 2)
            print("You use a Heavy Attack! The ",TypeOfEnemy.name," takes ",(Player.atk / 2), " damage!")
            time.sleep(Player.atkrate * 1.5)
        else:
            TypeOfEnemy.hp = TypeOfEnemy.hp - (Player.atk / 5)
            print("You use a Heavy Attack! The ",TypeOfEnemy.name," takes ",(Player.atk / 2), " damage!")
            time.sleep(Player.atkrate * 3)

Если вы посмотрите на цикл while, я запрашиваю ввод от игрока там.Проблема, конечно, в том, что вся программа останавливается, чтобы получить userInput, а не продолжать работу с программой.Я пытался поместить эту строку в цикл while, как этот

While True:
    special_ability_prompt = input("")

Я думал, что это каким-то образом создаст в программе еще одну строку, которую пользователь может набрать в любой команде, которую он захочет, во время битвы.жить.В результате моя функция просто зависла в цикле while, который был привязан к true ... Если кто-то здесь на этом форуме знает, как добиться такого эффекта, дайте мне знать.Весь код, необходимый для воспроизведения этой проблемы, приведен ниже (удалены некоторые части кода, которые не были необходимы для этой проблемы). Дайте мне знать, если вам нужны какие-либо разъяснения.Спасибо!

import time
import random

playername = input("What is your name?")
zone = 1
movement = 0
restcounter = 0
searchcounter = 0

class Player:
    def __init__(self, name, hp, mp, atk, xp, dodgerate, atkrate, gold):
        self.name = playername
        self.hp = hp
        self.mp = mp
        self.atk = atk
        self.xp = xp
        self.dodgerate = dodgerate
        self.atkrate = atkrate
        self.gold = gold

class Enemy(Player):
    def __init__(self, name, gold, maxhp, hp, mp, atk, xp, atkrate):
        self.name = name
        self.gold = gold
        self.maxhp = maxhp
        self.hp = hp
        self.mp = mp
        self.atk = atk
        self.xp = xp
        self.atkrate = atkrate
class Items:
    def __init__(self, name, quantity, description, price, weight):
        self.name = name
        self.quantity = quantity
        self.description = description
        self.price = price
        self.weight = weight


Player = Player(playername, 1, 1, 1, 1, 1, 0.500, 0)
print(Player.name + " has been created. ")

def raceselection():
    global raceinput
    raceinput = input("Do you float towards the TEMPLE, CAVE or FOREST?")
    if raceinput == "TEMPLE":
        print("You are now a high elf. High elves utlize a lot of magical power at the cost of being very frail.")
        Player.hp = Player.hp + 240
        Player.mp = Player.mp + 100
        Player.atk = Player.atk + 5000
    elif raceinput == "CAVE":
        print("You are now an orc.")
        Player.hp = Player.hp + 100
        Player.mp = Player.mp + 15
        Player.atk = Player.atk + 50
        Player.atkrate = Player.atkrate * 3
        print("cave")
    elif raceinput == "FOREST":
        print("You are now a human.")
        Player.hp = Player.hp + 50
        Player.mp = Player.mp + 25
        Player.atk = Player.atk + 25
    else:
        print("You can't float there!")
        raceselection()
raceselection()
def EnemyAttack(TypeOfEnemy):
    global raceinput
    special_ability_prompt = input("Use: HeavyAttack") #When you make the magic classes and put them in a dictionary, append them here.
    while (Player.hp > 1 and TypeOfEnemy.hp > 1):
        if (special_ability_prompt == "HeavyAttack"):
            if (raceinput == "CAVE"):
                TypeOfEnemy.hp = TypeOfEnemy.hp - (Player.atk / 2)
                print("You use a Heavy Attack! The ",TypeOfEnemy.name," takes ",(Player.atk / 2), " damage!")
                time.sleep(Player.atkrate * 1.5)
            else:
                TypeOfEnemy.hp = TypeOfEnemy.hp - (Player.atk / 5)
                print("You use a Heavy Attack! The ",TypeOfEnemy.name," takes ",(Player.atk / 2), " damage!")
                time.sleep(Player.atkrate * 3)
        time.sleep(TypeOfEnemy.atkrate)
        Player.hp = Player.hp - TypeOfEnemy.atk
        print("The ", TypeOfEnemy.name, " has attacked you for... ", TypeOfEnemy.atk , " hit points!")
        time.sleep(Player.atkrate)
        TypeOfEnemy.hp = TypeOfEnemy.hp - (Player.atk / 10)
        print("You attacked the enemy for ",(Player.atk / 10)," damage (",Player.atkrate ,")" + "The enemy has ",TypeOfEnemy.hp," left!")
        if (Player.hp <= 1):
                    print(TypeOfEnemy.name + " has defeated you!")
                    print("You have lost the game!")
                    losemessage = input("Would you like to try again?(Y or N)")
                    if (losemessage == "Y"):
                        raceselection()
                    if (losemessage == "N"):
                        print("Hope you enjoyed my game!")
        elif (TypeOfEnemy.hp <= 1):
            print("You have defeated ",TypeOfEnemy.name,"!")
            Player.xp = Player.xp + TypeOfEnemy.xp
            Player.gold = Player.gold + TypeOfEnemy.gold
            gameprompt()

inventory = []
def gameprompt():
    global inventory
    global zone
    global movement
    global restcounter
    global searchcounter
    if (movement == 5):
        movement = movement - movement
        zone = zone + 1
        print("You have advanced to zone",zone,"!!!")
        gameprompt()
    if (zone == 1):
        print("Welcome to the first zone! Easy enemies are here with not very good loot./fix grammar, add description of zone/")
    elif (zone == 2):
        print("Hey, it actually travelled to the second zone, awesome!")
    elif (zone == 3):
        print("Zone 3")
    elif (zone == 4):
        print("You are now in Zone 4")
    prompt = input("Would you like to walk, search or rest?: ")

    if (prompt == "walk"):
        encounterchance = random.randint(1, 3)
        if (encounterchance == 2):
            if (zone == 1):
                mobspawnrate = random.randint(1,3)
                if (mobspawnrate == 1):
                    slime = Enemy("Blue SlimeBall", 50, 0, 25, 15, 25, 25, 0.500)
                    print("You have encountered a " + slime.name + "!!!")
                    EnemyAttack(slime)
                    movement = movement + 1
                elif (mobspawnrate == 2):
                    slime = Enemy("Blue SlimeBall", 50, 0, 25, 15, 25, 25, 0.500)
                    print("You have encountered a " + slime.name + "!!!")
                    EnemyAttack(slime)
                    movement = movement + 1
                    print("You move one step because you defeated the enemy!")
                elif (mobspawnrate == 3):
                    slime = Enemy("Blue SlimeBall", 50, 0, 25, 15, 25, 25, 0.500)
                    print("You have encountered a " + slime.name + "!!!")
                    EnemyAttack(slime)
                    movement = movement + 1
                    print("You move one step because you defeated the enemy!")
            if (zone == 2):
                mobspawnrate2 = random.randint(1,3)
                if (mobspawnrate2 == 1):
                    enemy = Enemy("Blue SlimeBall", 50, 0, 25, 15, 25, 0.500)
                    print("You have encountered a " + enemy.name + "!!!")
                    EnemyAttack(slime)
                elif (mobspawnrate2 == 2):
                    enemy = Enemy("Blue SlimeBall", 50, 0, 25, 15, 25, 0.500)
                    print("You have encountered a " + enemy.name + "!!!")
                    EnemyAttack(slime)
                elif (mobspawnrate2 == 3):
                    enemy = Enemy("Blue SlimeBall", 50, 0, 25, 15, 25, 0.500)
                    print("You have encountered a " + enemy.name + "!!!")
                    EnemyAttack(slime)
        else:
            movement = movement + 1
            print("You have walked a step. You are now at ",movement," steps")
            gameprompt()
    elif (prompt == "search"):
        if (searchcounter == 3):
            print("You cannot search this area anymore! Wait until you reach the next zone!")
            gameprompt()
        else:
            searchchance = random.randint(1, 5)
            if (searchchance == 1 or 2 or 3 or 4):
                searchcounter = searchcounter + 1
                print(searchcounter)
                print("You have found something!")
                searchchance = random.randint(1,4)
                if (searchchance == 1 or 2):
                    inventory.append(Items("Old Boot", 1, "An old smelly boot. It's a mystery as to who it belongs to...", 5, 50))
                    print("You have found a Boot!")
                    print(inventory)
                elif(searchchance == 3):
                    inventory.append(Items("Shiny Boot", 1, "Looks like a boot that was lightly worn. You could still wear this.", 5, 50))
                    print(inventory)
                    print("You have found a Shiny Boot!")
                elif(searchchance == 4):
                    inventory.append(Items("Golden Boot", 1, "It's too heavy to wear, but it looks like it could sell for a fortune!", 5, 50))
                    print("You have found a Golden Boot?")
                    print(inventory)
            else:
                searchcounter = searchcounter + 1
                print(searchcounter)
                print("You did not find anything of value")
            gameprompt()
    elif (prompt == "rest"):
        if (restcounter == 1):
            print("Wait until you reach the next zone to rest again!")
            gameprompt()
        else:
            # Add a MaxHP value to the player later, and the command rest will give 25% of that HP back.
            Player.hp = Player.hp + (Player.hp / 5)
            print("You have restored ",(Player.hp / 5)," hit points!")
            restcounter = restcounter + 1
            gameprompt()
    elif (prompt == "examine"):
        print([item.name for item in inventory])
        gameprompt()
gameprompt()

Ответы [ 2 ]

0 голосов
/ 17 ноября 2018

Вот пример решения с использованием потоков.Здесь я создаю новый поток, который ожидает ввода пользователя, а затем передаю этот ввод в качестве аргумента функции.

import time
import threading

def do_sth(inp):
    print('You typed: ' + inp)

def wait_for_input(prompt=''):
    inp = input(prompt)
    do_sth(inp)

x = threading.Thread(target=wait_for_input, args=())
x.start()

print('You can type whatever you want, ill wait')
x.join()
0 голосов
/ 17 ноября 2018

Я полагаю, что вам придется использовать потоки для запуска отдельных процессов, в то же время взаимодействуя с пользователем.

Вы можете прочитать о потоке в Python здесь (в частности, модуль потоков в Python 3): https://docs.python.org/3/library/threading.html

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