Loop in function stops randomly - python

So yea, im making an RPG and the battle isnt too reliable... if you can figure out why then that would be great!
#Enemy System
def MMEnemy(PL, HP, STR, DEF, SLTH, Name, CLASSNO):
EnemyLvl = random.randint(PL, (PL * 2))
EnemyHP = random.randint(EnemyLvl * 40, EnemyLvl * 80)
Defend = False
while HP >= 1 & EnemyHP >= 1:
HPPercent = HP / PL
HPPercent = int(HPPercent)
if HPPercent >= 90:
HealthBar = ("█████████▓ | ", HP, " / ",(100 * PL))
elif HPPercent >= 80 and HPPercent <= 89:
HealthBar = ("████████▓░ | ", HP, " / ",(100 * PL))
elif HPPercent >= 70 and HPPercent <= 79:
HealthBar = ("███████▓░░ | ", HP, " / ",(100 * PL))
elif HPPercent >= 60 and HPPercent <= 69:
HealthBar = ("██████▓░░░ | ", HP, " / ",(100 * PL))
elif HPPercent >= 50 and HPPercent <= 59:
HealthBar = ("█████▓░░░░ | ", HP, " / ",(100 * PL))
elif HPPercent >= 40 and HPPercent <= 49:
HealthBar = ("████▓░░░░░ | ", HP, " / ",(100 * PL))
elif HPPercent >= 30 and HPPercent <= 39:
HealthBar = ("███▓░░░░░░ | ", HP, " / ",(100 * PL))
elif HPPercent >= 20 and HPPercent <= 29:
HealthBar = ("██▓░░░░░░░ | ", HP, " / ",(100 * PL))
elif HPPercent >= 10 and HPPercent <= 19:
HealthBar = ("█▓░░░░░░░░ | ", HP, " / ",(100 * PL))
elif HPPercent >= 0 and HPPercent <= 9:
HealthBar = ("▓░░░░░░░░░ | ", HP, " / ",(100 * PL))
else:
HealthBar = "Unknown Health!!"
print("The ", Name," is still standing... (", HealthBar, " HP)")
print("What should you do?")
print("1: Attack\n2: Heal\n3: Defend\n4: Run")
choice = input()
choice = int(choice)
if choice == 1:
roll = random.randint(STR, STR + 2)
print("You attack for ", roll)
EnemyHP -= (roll)
print(Name, " is at ", EnemyHP)
elif choice == 2:
roll = random.randint(PL * -2, PL * 5)
if CLASSNO == 2:
roll += PL * 3
if roll >= 1:
print("You healed for ", roll)
if roll <= 0:
print("You failed your heal [", roll," HP]")
HP += roll
elif choice == 3:
Defend = True
elif choice == 4:
print("Run failed, not implemented yet")
else:
print("None were chosen, you stood still")
DamageTaken = random.randint(5, EnemyLvl * 8)
if Defend == True:
prin("Your Defend was successful")
Defend = False
else:
HP -= DamageTaken
DamageTaken = str(DamageTaken)
print("You got damaged for ", DamageTaken,"!")
if HP <= 0:
print("You have been defeated by the ", Name,"...")
return "Lose"
if EnemyHP <= 0:
print("You defeated ", Name,"!")
return "Win"
CLASSNO = 1
level = 1
Strength = 5
Defence = 5
Stealth = 5
HP = 100
GameEnd = False
battle = MMEnemy(level, HP, Strength, Defence, Stealth, "Irc", CLASSNO)
battle = str(battle)
if battle != "Win" or battle != "Lose":
while battle != "Win" or battle != "Lose":
print("Restarted")
battle = MMEnemy(level, HP, Strength, Defence, Stealth, "Irc", CLASSNO)
battle = str(battle)
if battle == "Win":
print("Battle Won")
GameEnd = True
elif battle == "Lose":
print("Battle lost")
GameEnd = True
else:
print("Nothing Worked")
Ive tried changing the flags for the loop and simplifying it but it doesnt seem to do much. Its supposed to load and put you into battle but it stops halfway without returning anything making it so it wont get out of the loop

Wanted to suggest an improvement to the code, and was having trouble posting the code in the comments, so here it is:
hp_string = ""
if HPPercent > 0:
full_hp = "█"
current_hp = "▓"
used_hp = "░"
for i in range(int((HPPercent-HPPercent % 10)/10)):
hp_string += full_hp
hp_string += current_hp
if HPPercent <= 90:
for i in range(9 - int((HPPercent-HPPercent % 10)/10)):
hp_string += used_hp
HealthBar = (hp_string + " | ", HP, " / ",(100 * PL))
else:
HealthBar = "Unknown Health!!"
Also, as someone mentioned in the comments, & is not the same as and in python.

Related

python blackjack ace problem which breaks my code

I currently am making a blackjack python minigame, where a player plays until he gets a blackjack or stands and returns the value of his deck. This game does not play against a dealer and instead just uses his hands as a score. My problem is, I cannot figure out a way to make aces go from 11 to 1 without looping and breaking the program. Here is my code:
import random
def play():
output = "Your hand: "
player = []
total=0
count = 0
while len(player) != 2:
card = random.randint(1,52)
if card <= 4:
output += "A "
total += 11
player.append("A")
elif card <= 8:
output+="2 "
total+=2
player.append("2")
elif card <= 12:
output+="3 "
total+=3
player.append("3")
elif card <= 16:
output+="4 "
total+=4
player.append("4")
elif card <= 20:
output+="5 "
total+=5
player.append("5")
elif card <= 24:
output+="6 "
total+=6
player.append("6")
elif card <= 28:
output+="7 "
total+=7
player.append("7")
elif card <= 32:
output+="8 "
total+=8
player.append("8")
elif card <= 36:
output+="9 "
total+=9
player.append("9")
elif card <= 40:
output+="10 "
total+=10
player.append("10")
elif card <= 44:
output+="J "
total+=10
player.append("J")
elif card <= 48:
output+="Q "
total+=10
player.append("Q")
elif card <= 52:
output+= "K "
total+=10
player.append("K")
if len(player) == 2:
print(f"{output} ({total}) ")
while len(player) >= 2:
action_taken = input("Would you like to 'hit' or 'stand': ")
if action_taken == "hit":
card = random.randint(1,52)
if card <= 4:
output += "A "
total += 11
player.append("A")
elif card <= 8:
output+="2 "
total+=2
player.append("2")
elif card <= 12:
output+="3 "
total+=3
player.append("3")
elif card <= 16:
output+="4 "
total+=4
player.append("4")
elif card <= 20:
output+="5 "
total+=5
player.append("5")
elif card <= 24:
output+="6 "
total+=6
player.append("6")
elif card <= 28:
output+="7 "
total+=7
player.append("7")
elif card <= 32:
output+="8 "
total+=8
player.append("8")
elif card <= 36:
output+="9 "
total+=9
player.append("9")
elif card <= 40:
output+="10 "
total+=10
player.append("10")
elif card <= 44:
output+="J "
total+=10
player.append("J")
elif card <= 48:
output+="Q "
total+=10
player.append("Q")
elif card <= 52:
output+= "K "
total+=10
player.append("K")
if len(player) >= 2 and total <=21:
print(f"{output} ({total}) ")
if total > 21:
if "A" in player: #Ask why ace always messes up
if count < 1:
count +=1
total-=10
print(f"{output} ({total}) ")
if player.count("A") > 1:
total -= 10
print(f"{output} ({total}) ")
else:
print(f"{output} ({total}) ")
print("BUST!")
return total
if action_taken == "stand":
return total
if action_taken != "hit" or "stand":
print("Enter a valid input ('hit' or 'stand') ")
play()
if "A" in player will always be True once there's an ace in the deck, and so you never get to the else where you print "BUST!" and return, so the loop just continues. You can do something like incremeting count for every ace in the deck and then change the ace part to be:
if total > 21:
player_aces = player.count("A") # How many aces the player has
if player_aces != count: # Meaning there are aces that weren't checked
for _ in range(player_aces - count):
total -= 10 # Could also be simplified to: total -= 10 * (player_aces - count)
count = player_aces
print(f"{output} ({total}) ")
else:
print(f"{output} ({total}) ")
print("BUST!")
return total
Also, if action_taken != "hit" or "stand" doesn't check that action_taken is not "hit" and not "stand". An or treats both its inputs as bool values and returns whether at least one is True. The != operator has precedence over or, so the line is actually if (action_taken != "hit") or "stand". The left part of that does what it's supposed to do, but then the right part evaluates "stand" as a bool, and in python every non-empty string is evaluated as True. So the right expression is always True, and so is the or - and the program will always enter the if statement.
You probably want: if action_taken != "hit" and action_taken != "stand".
There were a coupe of issues that I have fixed. I have created a counter for the number of Aces, this allows us to count how many times we can reduced the total by - otherwise we just keep removing 10.
Also the indentation of the last else statement needed moving out.
import random
def play():
output = "Your hand: "
player = []
total=0
count = 0
reducedA = 0
while len(player) != 2:
card = 1
#card = random.randint(1,52)
if card <= 4:
output += "A "
total += 11
reducedA+=1
player.append("A")
elif card <= 8:
output+="2 "
total+=2
player.append("2")
elif card <= 12:
output+="3 "
total+=3
player.append("3")
elif card <= 16:
output+="4 "
total+=4
player.append("4")
elif card <= 20:
output+="5 "
total+=5
player.append("5")
elif card <= 24:
output+="6 "
total+=6
player.append("6")
elif card <= 28:
output+="7 "
total+=7
player.append("7")
elif card <= 32:
output+="8 "
total+=8
player.append("8")
elif card <= 36:
output+="9 "
total+=9
player.append("9")
elif card <= 40:
output+="10 "
total+=10
player.append("10")
elif card <= 44:
output+="J "
total+=10
player.append("J")
elif card <= 48:
output+="Q "
total+=10
player.append("Q")
elif card <= 52:
output+= "K "
total+=10
player.append("K")
if len(player) == 2:
print(f"{output} ({total}) ")
while len(player) >= 2:
action_taken = input("Would you like to 'hit' or 'stand': ")
if action_taken == "hit":
card = random.randint(1,52)
if card <= 4:
output += "A "
total += 11
player.append("A")
reducedA += 1
elif card <= 8:
output+="2 "
total+=2
player.append("2")
elif card <= 12:
output+="3 "
total+=3
player.append("3")
elif card <= 16:
output+="4 "
total+=4
player.append("4")
elif card <= 20:
output+="5 "
total+=5
player.append("5")
elif card <= 24:
output+="6 "
total+=6
player.append("6")
elif card <= 28:
output+="7 "
total+=7
player.append("7")
elif card <= 32:
output+="8 "
total+=8
player.append("8")
elif card <= 36:
output+="9 "
total+=9
player.append("9")
elif card <= 40:
output+="10 "
total+=10
player.append("10")
elif card <= 44:
output+="J "
total+=10
player.append("J")
elif card <= 48:
output+="Q "
total+=10
player.append("Q")
elif card <= 52:
output+= "K "
total+=10
player.append("K")
if len(player) >= 2 and total <=21:
print(f"{output} ({total}) ")
if total > 21:
if "A" in player: #Ask why ace always messes up
if count < 1:
count +=1
total-=10
print(f"{output} ({total}) ")
if player.count("A") > 1 and reducedA:
total -= 10
reducedA -= 1
print(f"{output} ({total}) ")
else:
print(f"{output} ({total}) ")
print("BUST!")
return total
else:
print(f"{output} ({total}) ")
print("BUST!")
return total
if action_taken == "stand":
return total
if action_taken != "hit" or action_taken != "stand":
print("Enter a valid input ('hit' or 'stand') ")
play()

How would I add this function into a python discord bot and get it to print to discord

I'm looking for some guidance on how to add this function to my bot and have it print to discord.
I want the bot to be able to print the results to discord instead of my terminal like so when the command /combat is entered
import random
def combat():
hp = random.randint(1, 11)
ac = random.randint(1, 7)
print('Your HP is', hp, 'and your armor is', ac)
ehp = random.randint(1, 11)
eac = random.randint(1, 7)
print("My HP is", ehp, 'and my armor is', eac)
i = 0
while not hp < 0 | ehp < 0:
"""add counter"""
i = i + 1
'''hp = random.randint(1,11)
ac = random.randint(1,7)
print(hp, ac)
ehp = random.randint(1,11)
eac = random.randint(1,7)
print(ehp, eac)'''
print('Turn',i,':')
dmg = random.randint(1,9)
tdmg = dmg - eac
if tdmg < 0:
tdmg = 0
ehp = ehp - tdmg
print(' You dealt', tdmg, 'damage to me')
print(' I am at', ehp, 'health')
edmg = random.randint(1,9)
tedmg = edmg - ac
if tedmg < 0:
tedmg = 0
hp = hp - tedmg
print(' I dealt', tedmg, 'damage to you')
print(' You are at', hp, 'health')
if ehp < 1:
print('You win')
break
elif hp < 1:
print('I win')
break
combat()
Your HP is 3 and your armor is 5
My HP is 7 and my armor is 3
Turn 1 :
You dealt 0 damage to me
I am at 7 health
I dealt 3 damage to you
You are at 0 health
I win
This assumes you already have a bot token. If not, see here.
You need to create your bot, register the command, and convert it to be asynchronous and use send instead of print. You're also relying on print to build some of your outputs, which I have replaced with f-strings.
from discord.ext.commands import Bot
bot = Bot("/")
#bot.command()
async def combat(ctx):
hp = random.randint(1, 11)
ac = random.randint(1, 7)
await ctx.send(f'Your HP is {hp} and your armor is {ac}')
ehp = random.randint(1, 11)
eac = random.randint(1, 7)
await ctx.send(f'My HP is {ehp} and my armor is {eac}')
i = 0
while hp > 0 and ehp > 0:
i = i + 1
await ctx.send(f'Turn {i}:')
dmg = random.randint(1,9)
tdmg = dmg - eac
if tdmg < 0:
tdmg = 0
ehp = ehp - tdmg
await ctx.send(f' You dealt {tdmg} damage to me')
await ctx.send(f' I am at {ehp} health')
edmg = random.randint(1,9)
tedmg = edmg - ac
if tedmg < 0:
tedmg = 0
hp = hp - tedmg
await ctx.send(f' I dealt {tedmg} damage to you')
await ctx.send(f' You are at {hp} health')
if ehp < 1:
await ctx.send('You win')
break
elif hp < 1:
await ctx.send('I win')
break
bot.run("Token")

Python repeat random integer in while loop

I am trying to code player and mob attacks for a text based RPG game I am making, I have randomint set up for player and mob hitchance and crit chance but I can't figure out how to get a new integer for them every time I restart the loop, it uses the same integer it got the first time it entered the loop.
### GAME VALUES ###
class roll_dice:
def __init__(self):
self.spawn = random.randint(1,100)
self.escape = random.randint(1,100)
self.playercrit = random.randint(1,100)
self.playerhitchance = random.randint(1,100)
self.mobcrit = random.randint(1,100)
self.mobhitchance = random.randint(1,100)
roll = roll_dice()
### ORC SPAWN ###
if fight_walk.lower() == 'fight':
orcMobSpawn()
while True:
fight_orc = input(">>> ")
if fight_orc.lower() == 'a':
### PLAYER ATTACK ###
while True:
roll.playercrit
roll.playerhitchance
if roll.playercrit <= 10 and roll.playerhitchance >= 6:
print("You crit orc for",str(userPlayer.atk * 2),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk * 2
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance >= 6:
print("You hit orc for",str(userPlayer.atk),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance <= 5:
print("You missed!")
break
elif roll.playercrit <= 10 and roll.playerhitchance <= 5:
print("You missed!")
break
elif orcMob.hp <= 0 and userPlayer.hp >= 1:
print("Your HP:",str(userPlayer.hp))
print("You win!")
break
elif userPlayer.hp <= 0:
print("You died!")
exit()
### ORC ATTACK ###
while True:
roll.mobcrit
roll.mobhitchance
if orcMob.hp <= 0 and userPlayer.hp >= 1:
break
if roll.mobcrit <= 5 and roll.mobhitchance >= 25:
print("\nOrc crit for",str(orcMob.atk * 2),"damage!")
userPlayer.hp = userPlayer.hp - orcMob.atk * 2
print("Your HP:",str(userPlayer.hp))
break
elif roll.mobcrit >= 5 and roll.mobhitchance >= 25:
print("\nOrc hit for",str(orcMob.atk),"damage!")
userPlayer.hp = userPlayer.hp - orcMob.atk
print("Your HP",str(userPlayer.hp))
break
elif roll.mobcrit <= 5 and roll.mobhitchance <= 25:
print("Orc missed!")
print("Your HP:",str(userPlayer.hp))
break
elif roll.mobcrit >= 5 and roll.mobhitchance <= 25:
print("Orc missed!")
print("Your HP:",str(userPlayer.hp))
break
if orcMob.hp <= 0 and userPlayer.hp >= 1:
break
elif orcMob.hp >= 1:
continue
The problem is with your roll_dice class. You have the values defined when the class initializes, but then you never update them again. Therefore self.escape or self.spawn will always be the same value after the program starts. The easiest way to solve your problem without rewriting much would be to make another instance of roll_dice() every time you want to roll the dice. Something like:
### GAME VALUES ###
class roll_dice:
def __init__(self):
self.spawn = random.randint(1,100)
self.escape = random.randint(1,100)
self.playercrit = random.randint(1,100)
self.playerhitchance = random.randint(1,100)
self.mobcrit = random.randint(1,100)
self.mobhitchance = random.randint(1,100)
# roll = roll_dice() # you don't need to make an instance here
### ORC SPAWN ###
if fight_walk.lower() == 'fight':
orcMobSpawn()
while True:
fight_orc = input(">>> ")
if fight_orc.lower() == 'a':
### PLAYER ATTACK ###
while True:
roll = roll_dice() # make a new instance with each loop
roll.playercrit
roll.playerhitchance
if roll.playercrit <= 10 and roll.playerhitchance >= 6:
print("You crit orc for",str(userPlayer.atk * 2),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk * 2
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance >= 6:
print("You hit orc for",str(userPlayer.atk),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance <= 5:
print("You missed!")
break
elif roll.playercrit <= 10 and roll.playerhitchance <= 5:
print("You missed!")
break
elif orcMob.hp <= 0 and userPlayer.hp >= 1:
print("Your HP:",str(userPlayer.hp))
print("You win!")
break
elif userPlayer.hp <= 0:
print("You died!")
exit()
### ORC ATTACK ###
Use functions like
import random
for x in range(10):
print random.randint(1,101)
use a array around for a max 100 people and generate random digits to add in your code.
You can also use a array to create random umber structure and then use the numbers to be shuffled and added as you create them
from random import *
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffle(items)
print items

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()
I believe you'd have to use threads in order to have separate processes running while also having user interaction.
You can read about threading in python here (specifically the threading module in Python 3): https://docs.python.org/3/library/threading.html
Here's example solution using threads. Here I'm creating new thread that's waiting for user input and then pass that input as argument to function.
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()

How come my ork fight stops and doesn't go to the move() command :/

At some parts of my code its just stop and doesn't go back to the move(). I want it to add the score and i did that with score = score + 100 BUT it just disrupts the code ;-;. Its a bit messy and i'm sorry about that but please help I have NO clue why it does this. Fyi I'm using this code on pythonroom if that helps.
import random
weapon = "Wooden Sword"
Damage0 = 1
Damage1 = 8
Speed = 6
lives = 5
score = 0
gold = 80
armor = "Nothing"
health = 20
def please():
name = input("Please put a name and not nothing.")
if name == "":
please1(name)
else:
yon(name)
def please1(name):
name = input("Please put a name and not nothing.")
if name == "":
please1(name)
else:
yon1(name)
def yon(name):
print("So your name is " + name + "?")
yon = input("Is this your name? ''" + name + "'' [Yes] or [No]?")
if yon == "Yes":
begining()
elif yon == "yes":
begining()
else:
sorry(name)
def yon1(name):
yon = input("Is this your +name? ''" + name + "'' [Yes] or [No]?")
if yon == "Yes":
begining()
elif yon == "yes":
begining()
else:
sorry1(name)
def sorry(name):
print(" ")
print("I'm sorry, so what is your name?")
print(" ")
name = input("What is you name?")
if name != "":
yon(name)
else:
please1(name)
def sorry1(name):
name = input("What is you name?")
if name != "":
yon1(name)
else:
please1(name)
def move():
Next = input("Will you go and fight a monster or check stats or quit the game? [Fight] [Stats] [Travel] [Quit]")
Next = Next.lower()
if "tat" in Next:
Stats()
elif "ight" in Next:
Fight()
elif "ravel" in Next:
travel()
elif "uit" in Next:
print("As you quit the game your character disapears...")
else:
move()
def Fight():
your_speed = Speed
enemy_speed = 2
if enemy_speed >= your_speed:
print("The " + enemy + " is faster, it goes first!")
enemy_first()
else:
print("You're faster and get to go first!")
your_first()
def end(enemy_health,your_health):
if your_health > 0:
print(" ")
print("You defeat the Ork")
score = score + 100
gold = gold + 50 'it stops here and won't continue why?
print(gold)
print(score)
move()
else:
print("The ork beat you!")
move()
def your_first():
enemy_health = 20
your_health = health
while your_health > 0 and enemy_health > 0:
your_damage = random.choice(range(Damage0, Damage1))
enemy_health -= your_damage
if enemy_health <= 0:
enemy_health = 0
print(" ")
print("You dealt " + str(your_damage) + " damage!")
print("Enemy's health:" + str(enemy_health))
end(enemy_health,your_health)
else:
print(" ")
print("You dealt " + str(your_damage) + " damage!")
print("Enemy's health:" + str(enemy_health))
enemy_damage = random.choice(range(3, 12))
your_health -= enemy_damage
if your_health <= 0:
your_health = 0
print(" ")
print("Ork dealt " + str(enemy_damage) + " damage!")
print("Your health:" + str(your_health))
end(enemy_health,your_health)
else:
print(" ")
print("Ork dealt " + str(enemy_damage) + " damage!")
print("Your health:" + str(your_health))
def enemy_first():
enemy_health = 20
your_health = health
while your_health > 0 and enemy_health > 0:
enemy_damage = random.choice(range(3, 12))
your_health -= enemy_damage
if your_health <= 0:
your_health = 0
print(" ")
print("Ork dealt " + str(enemy_damage) + " damage!")
print("Your health:" + str(your_health))
end(enemy_health,your_health)
else:
print(" ")
print("Ork dealt " + str(enemy_damage) + " damage!")
print("Your health:" + str(your_health))
your_damage = random.choice(range(Damage0, Damage1))
enemy_health -= your_damage
if enemy_health <= 0:
print(" ")
print("You dealt " + str(your_damage) + " damage!")
print("Enemy's health:" + str(enemy_health))
end(enemy_health,your_health)
else:
print(" ")
print("You dealt " + str(your_damage) + " damage!")
print("Enemy's health:" + str(enemy_health))
def Stats():
if weapon == "Wooden Sword":
Damage = 1, 8
Damage0 = 1
Damage1 = 8
Speed = 6
if weapon == "Rusty Sword":
Damage = 13, 17
Damage0 = 13
Damage1 = 17
Speed = 4
if weapon == "Bow":
Damage = 2, 13
Damage0 = 2
Damage1 = 13
Speed = 10
if weapon == "Bronze Sword":
Damage = 18, 24
Damage0 = 18
Damage1 = 24
Speed = 1
if weapon == "Magic Spell":
Damage = 25, 33
Damage0 = 25
Damage1 = 33
Speed = 10
if armor == "Nothing":
health = 20
print(" ")
print(" ")
print("(+)~~~~~~~~~~~~~~~~~~~~~~")
print(" | Your | Health: ")
print(" | Stats | " + str(health) + " ")
print(" |----------------------- ")
print(" | Weapon Stats: ")
print(" | Damage: "+str(Damage)+" ")
print(" | Speed: "+str(Speed)+" ")
print("(+)~~~~~~~~~~~~~~~~~~~~~~")
print(" Your Score:"+ str(score) +" ")
print(" ")
print(" ")
move()
def begining():
print(" ")
print("Welcome to the nexus!")
print("It is the center of this world.")
print("It is also called the hub.")
print("During the game you can gather items and get xp")
print("At the end of the game you can see your score based")
print("on how well you did and how many items you found!")
move()
def travel():
travel = input("Where will you travel to? [Cave] [Market] [Boss]")
if "ve" in travel:
cave()
elif "et" in travel:
market()
elif "ss" in travel:
Boss_fight()
else:
move()
def cave():
print("pie")
def market():
print("pie")
def Boss_fight():
your_speed = Speed
enemy_speed = 2
if enemy_speed >= your_speed:
print("The " + enemy + " is faster, it goes first!")
Boss_Boss_first
else:
print("You're faster and get to go first!")
Boss_Your_First()
def Boss_end(enemy_health,your_health):
if your_health > 0:
print(" ")
print("You defeat The Boss")
score = score + 2000
move()
else:
print(" ")
if lives == 3 or lives == 2 or lives == 1:
print("The Boss beats you!")
lives = lives - 1
print("You have " + str(lives) + " left")
move()
else:
start= input("Restart or Quit?")
if "start" in start or "try" in start:
reset(xp,lvl,weapon)
else:
print(" ")
def Boss_Your_First():
enemy_health = 50
your_health = health
while your_health > 0 and enemy_health > 0:
your_damage = random.choice(range(Damage0, Damage1))
enemy_health -= your_damage
if enemy_health <= 0:
enemy_health = 0
print(" ")
print("You dealt " + str(your_damage) + " damage!")
print("The Boss's health:" + str(enemy_health))
Boss_end(enemy_health,your_health)
else:
print(" ")
print("You dealt " + str(your_damage) + " damage!")
print("The Boss's health:" + str(enemy_health))
enemy_damage = random.choice(range(15, 19))
your_health -= enemy_damage
if your_health <= 0:
your_health = 0
print(" ")
print("The Boss dealt " + str(enemy_damage) + " damage!")
print("Your health:" + str(your_health))
Boss_end(enemy_health,your_health)
else:
print(" ")
print("The Boss dealt " + str(enemy_damage) + " damage!")
print("Your health:" + str(your_health))
def Boss_Boss_first():
enemy_health = 50
your_health = health
while your_health > 0 and enemy_health > 0:
enemy_damage = random.choice(range(15, 19))
your_health -= enemy_damage
if your_health <= 0:
your_health = 0
print(" ")
print("The Boss dealt " + str(enemy_damage) + " damage!")
print("Your health:" + str(your_health))
Boss_end(enemy_health,your_health)
else:
print(" ")
print("The Boss dealt " + str(enemy_damage) + " damage!")
print("Your health:" + str(your_health))
your_damage = random.choice(range(Damage0, Damage1))
enemy_health -= your_damage
if enemy_health <= 0:
print(" ")
print("You dealt " + str(your_damage) + " damage!")
print("The Boss's health:" + str(enemy_health))
Boss_end(enemy_health,your_health)
else:
print(" ")
print("You dealt " + str(your_damage) + " damage!")
print("The Boss's health:" + str(enemy_health))
print(" ")
print("Hello. What is your name?")
print(" ")
name = input("What is you name?")
if name == "":
please()
else:
yon(name)
You're trying to assign to global variable score within function end like this:
val = 5
def func():
val += 5
It won't work and will result to UnboundLocalError. In order to fix the issue just use keyword global:
val = 5
def func():
global val
val += 5

Categories

Resources