首页 > 解决方案 > Asking for user input while the program keeps running?

问题描述

Creating an automated battle system, but I want the user to have some input. The problem is whenever I ask for input the entire function stops until it gets input from the user.

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)

If you look at the while loop, I ask for the player input there. The problem is, of course, the entire program stops to get the userInput instead of continuing with the program. I've tried putting that line in a while loop like this

While True:
    special_ability_prompt = input("")

I thought that this would somehow create another line in the program that the user can type in any command they want while the battle is going on live. The effect was that my function was just stuck on this while loop which was stuck on true... If anyone here on this forum knows how to achieve an effect like this let me know. All the code that is necessary to reproduce this problem is down below (removed some parts of the code which was not needed for the issue) Let me know if you need any clarification. Thanks!

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()

标签: pythonpython-3.xclassinput

解决方案


我相信您必须使用线程才能运行单独的进程,同时还要进行用户交互。

您可以在此处阅读 python 中的线程(特别是 Python 3 中的线程模块):https ://docs.python.org/3/library/threading.html


推荐阅读