Python program keeps asking question again and again - python

I am a python intermediate and tried to make a text based adventure game in python. There is a class called NPC which has the NPCs. In that class there is a method called attack() which will attack the player and the player can also attack or defend. It is position based so the user can enter 3 things - 'high', 'middle' and 'low'. This is the code.
turn = True
while turn:
player_defend_pos = input('Where would you like to defend the attack? High, middle or low. ').lower()
possible_positions = ['high', 'middle', 'low']
attack_pos = random.choice(possible_positions)
while player_defend_pos not in [possible_positions] and player_defend_pos not in possible_actions:
player_defend_pos = input('Where would you like to defend the attack? High, middle or low. ').lower()
if player_defend_pos == 'm':
use_medkit()
elif player_defend_pos == 'help':
help()
elif player_defend_pos == 's':
shop()
elif player_defend_pos != attack_pos:
if equipped_armour == False:
print(f'You don\'t have any armour equipped so the {self.name} will do {self.damage} damage to you.')
player['health'] -= self.damage
if attack_pos == 'high':
print(f'The {self.name} attacked you up high')
print(f'Your health: {player["health"]}')
print(f'{self.name}\'s health: {self.health}')
turn = False
break
elif attack_pos == 'middle':
print(f'The {self.name} attacked you in the middle')
print(f'Your health: {player["health"]}')
print(f'{self.name}\'s health: {self.health}')
turn = False
break
else:
print(f'The {self.name} attacked you down low')
print(f'Your health: {player["health"]}')
print(f'{self.name}\'s health: {self.health}')
turn = False
break
elif equipped_armour == True and shop_items[1][player['armours'][0] + ' protection'] > self.damage:
print(f'Since you have {[player["armours"][0]]} equipped it will not do anything.')
if attack_pos == 'high':
print(f'The {self.name} attacked you up high')
print(f'Your health: {player["health"]}')
print(f'{self.name}\'s health: {self.health}')
turn = False
break
elif attack_pos == 'middle':
print(f'The {self.name} attacked you in the middle')
print(f'Your health: {player["health"]}')
print(f'{self.name}\'s health: {self.health}')
turn = False
break
else:
print(f'The {self.name} attacked you down low')
print(f'Your health: {player["health"]}')
print(f'{self.name}\'s health: {self.health}')
turn = False
break
elif equipped_armour == True and shop_items[1][player['armours'][0] + ' protection'] < self.damage:
player['health'] -= self.damage - shop_items[1][player['armours'][0] + ' protection']
if attack_pos == 'high':
print(f'The {self.name} attacked you up high')
print(f'Your health: {player["health"]}')
print(f'{self.name}\'s health: {self.health}')
turn = False
break
elif attack_pos == 'middle':
print(f'The {self.name} attacked you in the middle')
print(f'Your health: {player["health"]}')
print(f'{self.name}\'s health: {self.health}')
turn = False
break
else:
print(f'The {self.name} attacked you down low')
print(f'Your health: {player["health"]}')
print(f'{self.name}\'s health: {self.health}')
turn = False
break
else:
print('You have successfully defended the attack')
turn = False
break
This is the defend code there is a similar thing in attacking the NPC also which has the same output. Now even if I enter 'high', 'middle' or 'low' It asks the question again and again. Please show me some guidance.

I have found the answer. Actually I should have told that equipped_armour is actually a function. Sorry about that. I actually wanted the return value of equipped_armour() without running everything in it. So I searched my question on stackoverflow. Even that didn't work. So I searched for the global keyword, used it and then got the answer. Maybe your answers were right if equipped_armour was a variable. Anyways thank you all for trying.

I think your problem is in
# this will produce always true
while player_defend_pos not in [possible_positions]
it should be
while player_defend_pos not in possible_positions
I hope my answer help your problem

import random
possible_actions = ['m', 'help', 's']
turn = True
equipped_armour = True
def use_medkit():
print('Medkit!')
def shop():
print('Shop!')
while turn:
player_defend_pos = input('Where would you like to defend the attack? High, middle or low. ').lower()
possible_positions = ['high', 'middle', 'low']
attack_pos = random.choice(possible_positions)
while player_defend_pos not in possible_positions and player_defend_pos not in possible_actions:
player_defend_pos = input('Where would you like to defend the attack? High, middle or low. ').lower()
print(player_defend_pos)
if player_defend_pos == 'm':
use_medkit()
elif player_defend_pos == 'help':
help()
elif player_defend_pos == 's':
shop()
elif player_defend_pos != attack_pos:
turn = False
else:
print('You have successfully defended the attack')
turn = False
break
Try something simple and then make it complex. The code above works for example.

Related

Turn/chance feature in following code is not working

I am trying to create a IPL/Fanstasy cricket simulators in which you create your team and play. You auction the players. In the auction function, I have added a turn feature, which means if the turn variable is even, then its your turn, if its odd, then its other bidders turn.
def auction(money, turn, choice):
if turn % 2 == 0:
while True:
print("It is your turn to choose a player.")
while True:
selected_player = str(
input("Enter the name of the player you wish to choose(leave empty to skip):"))
if selected_player in players:
break
elif selected_player == "":
print("Turn Skipped")
else:
print("That player is not in your players")
selected_player_bid = int(input("Enter the amount of money for which you wish to buy the player(leave "
"empty to skip):"))
if selected_player_bid > money:
print("You dont have enough money to buy the player.")
else:
your_players.append(selected_player)
print("Player bought")
break
break
else:
selected_player = random.choice(players)
selected_player_bid = random.randint(1, 100000)
print(
f"{random.choice(bidders)} chooses {selected_player} for {selected_player_bid}.")
print(
"You can either type [p]ass let them take the player or type [c]hallenge to challenge them.")
while True:
choice = input("Challenge or pass: ")
if choice.lower() == "challenge":
break
elif choice.lower() == "pass":
break
elif choice.lower() == "p":
break
elif choice.lower() == "c":
break
else:
print("Not a valid command, please type again.")
while choice.lower() == "challenge" or choice.lower() == 'c':
bid = int(input("Enter your bid: "))
if bid > money:
print("You do not have enough money.")
elif bid < selected_player_bid:
print("That is lower than the starting bid.")
else:
print(f"{selected_player} bought for {bid}")
money = money - bid
print("You have enough money.")
your_players.append(selected_player)
break
if choice.lower() == "p" or choice.lower() == "pass":
pass
players.remove(selected_player)
The usage of the function(This is where I was trying to fix the code).
while True:
if random_choice:
turn = turn + 1
random_choice = bool(random.choice(binary_numbers))
auction(your_money, turn, choice)
else:
random_choice = bool(random.choice(binary_numbers))
auction(your_money, turn, choice)
pass
if len(players) == 0:
break
else:
continue
GitHub repo
You can comment the fix or create a pull request.
Thanking you in advance.
I expected the code to randomly choose the bidder, either the player or the bots, but when I was fixing it, it was not doing so.

How do I make my code loop the function fight() [duplicate]

This question already has answers here:
How to make program go back to the top of the code instead of closing [duplicate]
(7 answers)
Asking the user for input until they give a valid response
(22 answers)
Repeating a function in Python
(2 answers)
Closed 8 months ago.
import random
user = input("You reconize this creture. The feared BaLaKe. Its weakness is 'rock', 'paper',''scissors' Are you willing to challenge him in a battle of Rock Paper Scissors? (ENTER)" )
print("ROARRRRRRRRRRRRRRRRRRR!!!!!")
Below is the function I want to loop when userhealth and dragonhealth <= 0. I want it to keep asking for input for rock, paper, or scissors and go through the conditions.
def fight(userhealth,dragonhealth):
dragon = random.choice(["r","p","s"])
user=input("Rock(r), Paper(p) or Scissors(s): ").lower()
print(dragon)
if user==dragon:
print("You both missed your attacks. Bruh ;-;")
elif is_win(user,dragon):
dragonhealth-=20
print("You hit BaLaKe! 20 DMG Done!!! :) ")
print("Your health: "+str(userhealth )+" HP")
print("BaLaKe\'s health: "+str(dragonhealth )+" HP")
else:
print("Ow! You got hit by BaLake. -20 HP :( ")
userhealth-=20
print("Your health: "+str(userhealth )+" HP")
print("BaLaKe\'s health: "+str(dragonhealth )+" HP")
def is_win(player,opponent):
if (player=="r" and opponent=="s") or (player=="s" and opponent=="p") or (player=="p" and opponent=="r"):
return True
fight(100,100)
Do you want this ?
import random
user = input("You recognize this creture. The feared BaLaKe. Its weakness is 'rock', 'paper',''scissors' Are you willing to challenge him in a battle of Rock Paper Scissors? (ENTER)" )
print("ROARRRRRRRRRRRRRRRRRRR!!!!!")
def fight(userhealth,dragonhealth):
while(userhealth>0 and dragonhealth>0):
dragon = random.choice(["r","p","s"])
user=input("Rock(r), Paper(p) or Scissors(s): ").lower()
print(dragon)
if user==dragon:
print("You both missed your attacks. Bruh ;-;")
elif is_win(user,dragon):
dragonhealth-=20
print("You hit BaLaKe! 20 DMG Done!!! :) ")
print("Your health: "+str(userhealth )+" HP")
print("BaLaKe\'s health: "+str(dragonhealth )+" HP")
else:
print("Ow! You got hit by BaLake. -20 HP :( ")
userhealth-=20
print("Your health: "+str(userhealth )+" HP")
print("BaLaKe\'s health: "+str(dragonhealth )+" HP")
def is_win(player,opponent):
if (player=="r" and opponent=="s") or (player=="s" and opponent=="p") or (player=="p" and opponent=="r"):
return True
fight(100,100)
Try the following code:
import random
user = input("You reconize this creture. The feared BaLaKe. Its weakness is 'rock', 'paper',''scissors' Are you willing to challenge him in a battle of Rock Paper Scissors? (ENTER)" )
print("ROARRRRRRRRRRRRRRRRRRR!!!!!")
dragonhealth = 100
userhealth = 100
def fight(userhealth,dragonhealth,choice):
dragon = random.choice(["r","p","s"])
print(dragon)
if choice==dragon:
print("You both missed your attacks. Bruh ;-;")
elif is_win(choice,dragon):
dragonhealth-=20
print("You hit BaLaKe! 20 DMG Done!!! :) ")
print("Your health: "+str(userhealth )+" HP")
print("BaLaKe\'s health: "+str(dragonhealth )+" HP")
else:
print("Ow! You got hit by BaLake. -20 HP :( ")
userhealth-=20
print("Your health: "+str(userhealth )+" HP")
print("BaLaKe\'s health: "+str(dragonhealth )+" HP")
return userhealth,dragonhealth
def is_win(player,opponent):
if (player=="r" and opponent=="s") or (player=="s" and opponent=="p") or (player=="p" and opponent=="r"):
return True
while (userhealth>0 or dragonhealth>0):
choice=input("Rock(r), Paper(p) or Scissors(s): ").lower()
userhealth,dragonhealth = fight(userhealth,dragonhealth,choice)
if userhealth>0:
print("You won! ")
elif dragonhealth>0:
print("You lost! ")
Explanation: Sets the original healths at the start. Sets up a while loop to check if either of them have less than 0 health. Subtracts and updates the health when you lose/win. Declares a winner at the end!
Use While loop for repeating the game util someone gets 0 HP.
I created a function to terminate the game when someone is at 0 HP. See it
enter code here
import random
user_health = 100 # used underscore snake case love:)
dragon_health = 100 # I initialized both variables outside
def fight(user_health, dragon_health): # according to PEP8 I guess. we shouldn't use shadow names. Still,not a big deal
dragon = random.choice(["r", "p", "s"])
user = input("Rock(r), Paper(p) or Scissors(s): ").lower()
print(dragon)
if user == dragon:
print("You both missed your attacks. Bruh ;-;")
return user_health, dragon_health
elif is_win(user, dragon):
dragon_health -= 20
print("You hit BaLaKe! 20 DMG Done!!! :) ") #
print("Your health: " + str(user_health) + " HP")
print("BaLaKe\'s health: " + str(dragon_health) + " HP")
return user_health, dragon_health
else:
print("Ow! You got hit by BaLake. -20 HP :( ")
user_health -= 20
print("Your health: " + str(user_health) + " HP")
print("BaLaKe\'s health: " + str(dragon_health) + " HP")
return user_health, dragon_health
def is_win(player, opponent):
if (player == "r" and opponent == "s") or (player == "s" and opponent == "p") or (
player == "p" and opponent == "r"):
return True
# this function terminates game when someone is at 0 HP and prints output
def game_terminator(user_health, dragon_health): # I continued with the shadow names to avoid confusion
if user_health == 0:
print("Dragon killed you!")
return False
elif dragon_health == 0:
print("Thrashed dragon to dealth! YOU WON!") # Nerd outputs :)
return False
else:
return True
game_is_on = True
# Use while loop for game to run until someone gets 0 HP
while game_is_on: # game_is_on is a boolean variable
user_health, dragon_health = fight(user_health, dragon_health)
game_is_on = game_terminator(user_health, dragon_health)
# Thank Me :)

Can't Seem to get my program to stop throwing up invalid syntax [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have been trying to write my first game in python, I've tried to keep it as simple as possible but when I run my code it's simply just throwing up a syntax error even though the option I have provided should work. I think it may be an issue with the player choice #1 specifically. I am still having trouble with the logic of it all so please do you best to show me what I am doing wrong so I can become better in the future :-)
player = {'name': 'George', 'attack': 10, 'heal': 16, 'health': 100}
monster = {'name': 'Fat Boy Joe', 'attack': 15, 'health': 150}
game_running = True
while game_running == True:
player_won = False
monster_won = False
print('Please Select An Option')
print('1)Attack')
print('2)Heal')
player_choice = input()
if player_choice == "1":
print('Attacking')
monster['health'] = monster['health'] - player['attack']
if monster['health'] <= 0:
player_won = True
else:
player['health'] = player['health'] - monster['attack']
elif player_choice == '2':
print('Healing')
player['health'] = player['health'] + player['heal']
print('player health ', player['health'])
else:
print('Invalid input')
if player_won == True or monster_won == True:
game_running = False
if player['health'] <= 0:
player_won = True
print('monster health ', monster['health'], 'and player health ', player['health'])
if player['health'] <= 0:
print('Congratulations you have won the game!')
else:
print('Sorry but the monster A.K.A. Fat Boy Joe won the game this time')
What the game is supposed to do-
My game is a simple monster vs player game
The player attacks the monster and the monster attacks back
The player is allowed to heal himself but the monster deals out more damage than the player
The code should allow for the player to make two decisions either attack or heal himself but it always throws up invalid syntax when I try to pick one
Here is also a list of thing's that I have tried
Changing my indents
Changing the if else elif commands arround to see if that would help
The problem was that you were not using elif statement in the middle. You have to use if-elif-else for checking your player_choice
player = {'name': 'George', 'attack': 10, 'heal': 16, 'health': 100}
monster = {'name': 'Fat Boy Joe', 'attack': 15, 'health': 150}
game_running = True
while game_running == True:
player_won = False
monster_won = False
print('Please Select An Option')
print('1)Attack')
print('2)Heal')
player_choice = input()
if player_choice == '1':
print('Attacking')
monster['health'] = monster['health'] - player['attack']
if monster['health'] <= 0:
player_won = True
else:
player['health'] = player['health'] - monster['attack']
elif player_choice == '2':
print('Healing')
player['health'] = player['health'] + player['heal']
print('player health ', player['health'])
else:
print('Invalid input')
if player_won == True or monster_won == True:
game_running = False
if player['health'] <= 0:
player_won = True
print('monster health ', monster['health'], 'and player health ', player['health'])
if player['health'] <= 0:
print('Congratulations you have won the game!')
else:
print('Sorry but the monster A.K.A. Fat Boy Joe won the game this time')

Enter blank value in try statements

I am making a blackjack game for school and for this part, the user can choose their bet. It can be 0 to quit, press enter to keep the previous bet, or type a new bet. I got the enter 0 part, but I think my ValueError is blocking the user from entering a blank value. I apologize for the messy code. Is there another except statement I could add in to allow some mistakes, or do i need to restructure the entire loop?
import random
import sys
def main():
restart = True
bank_balance = 1000
player_name = input("Please enter your name: ")
while (restart):
print (f"Welcome {player_name}, your bank balance is ${bank_balance} ")
correct = False
user_bet=0
bet = input_bet(user_bet, bank_balance)
if (user_bet == 0):
print('Quiting the game')
break
win_lose = play_hand(player_name, bet)
bank_balance+=win_lose
print(f'Your bank balance: ${bank_balance}')
play=bet
def input_bet(bet, money):
correct = False
while not correct:
try:
enough_money = False
while not enough_money:
bet=int(input("Bet? (0 to quit, press 'Enter' to stay at $25) "))
if (bet > money):
print('not enough money')
elif (bet == 0):
return 0
elif (bet <= money):
print(f'Betting ${bet}')
enough_money=True
return bet
correct = True
except ValueError:
print('Please enter a number')
def play_hand(name, bet):
player= []
dealer= []
play_again = True
dealer.append(random.randint(1, 11))
player.extend([random.randint(1, 11), random.randint(1, 11)])
print ('The dealer received card of value', *dealer)
print(name, 'received cards of value', player[0], 'and', player[-1])
print(f'Dealer total is {sum(dealer)}')
print(f"{name}'s total is {sum(player)}", '\n')
stay = False
bust = False
while (sum(player) <= 21 and stay == False and play_again == True):
hors= input(f"Type 'h' to hit and 's' to stay ")
if (hors == 'h'):
new_card= random.randint(1, 11)
player.append(new_card)
print(f'{name} pulled a {new_card}')
print(f'Dealer total is {sum(dealer)}')
print(f"{name}'s cards are", *player)
print(f"{name}'s total is {sum(player)}", '\n')
elif (hors == 's'):
stay=True
print('stay')
if (sum(player) > 21 ):
bust = True
print('You busted!')
return -bet
while (stay == True and sum(dealer) < 17 and bust == False and play_again == True):
dealer.append(random.randint(1, 11))
print('The dealers cards are', *dealer)
print('The dealers total is', sum(dealer), '\n')
if (sum(dealer) <= 21 and sum(dealer) > sum(player)):
print("The dealer wins!")
return -bet
elif (sum(player) <= 21 and sum(player) > sum(dealer)):
print("You win!")
return bet
if (sum(dealer) > 21):
print ('You win! The dealer busted!')
return bet
if (sum(dealer) == sum(player)):
print('Its a Tie! ')
return 0
main()
The immediate issue is that int("") raises a ValueError, rather than returning 0 like int() does. The solution is to check the return value of input before you attempt to produce an int.
def input_bet(money):
while True:
response = input("Bet? (0 to quite, press 'Enter' to stay at $25) ")
if bet == "0":
return 0
if bet == "":
bet = "25"
try:
bet = int(bet)
except ValueError:
print("Please enter a number")
continue
if bet > money:
print("Not enough money")
continue
return bet
The only parameter input_bet needs is the player's total amount, to prevent betting more than is available. No initial bet is needed.

Why does my program exit unexpectedly when I call input?

I'm trying to get this RPG program to work, but I can't figure it out. I run it and well, you will see when you run the program. For some reason when I run this it stops at 1,2,3,4 after every move I make. Am I not returning anything? What am I doing wrong here, and how can I improve my organization and code in the future?
import math
import random
class character:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
class enemy:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
charspells = ['Fireball']
Loop = True
def fireball(character, enemy):
enemy.hp -= character.int
print('You did, ',character.int ,'to the enemy')
print('Enemy.hp', enemy.hp)
return enemy.hp
items = []
mainc = character(100, 100, 10, 0, 10)
tai_lopez = enemy(30, 30, 5, 0, 10)
def character_battle(character, enemy):
choice = input('What would you like to do?\n 1. Attack \n 2. Spells \n 3. Items \n 4. Run')
if choice == input('1'):
print('You attack the enemy!')
enemy.hp -= character.att
print('You dealt', character.att, 'to the enemy!')
print('Enemy hp =', enemy.hp)
if choice == input('2'):
spellchoice = input('Which spell do you wish to call?')
print('1.', charspells[0],'\n' '2.', charspells[1], '\n' 'q', 'exit')
if spellchoice == ('1'):
print('You used fireball!')
fireball(character, enemy)
elif spellchoice == ('2'):
if charspells[1] != 'Lightning bolt':
print('It doesnt exist, sorry')
# ill add more spell fucntions later
if spellchoice == ('3'):
print('You went back to the menu')
if choice == input('3'):
if items == []:
print('You have no items')
if items == ['potions']:
print ('response')
#placeholder ill add the fucntion later
elif choice == input('4'):
Loop = False
def enemy_battle(enemy, character):
a = random.randint(0,50)
if a <= 35:
print('The enemy attacks you!')
character.hp -= enemy.att
print('Your hp =', character.hp)
elif a <= 50:
print('The enemy uses mind attacks bruh')
character.hp -= enemy.int
print('Your hp =', character.hp)
def battle_loop(character, enemy):
Loop1 = True
while Loop1 == True:
while enemy.hp > 0 and character.hp > 0:
character_battle(character, enemy)
enemy_battle(character, enemy)
if enemy.hp <= 0:
print('You Won')
Loop1 = False
if character.hp <= 0:
print('You lost')
exit()
battle_loop(mainc, tai_lopez)
The problem is you are using input() in if statement. Whenever interpreter tries to check if condition is true or not it executes the input() which demands an input even when you didn't expect it. In one of the methods your input was in wrong order so I fixed that too. So correct code should be :-
import math
import random
class character:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
class enemy:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
charspells = ['Fireball']
Loop = True
def fireball(character, enemy):
enemy.hp -= character.int
print('You did, ',character.int ,'to the enemy')
print('Enemy.hp', enemy.hp)
return enemy.hp
items = []
mainc = character(100, 100, 10, 0, 10)
tai_lopez = enemy(30, 30, 5, 0, 10)
def character_battle(character, enemy):
choice = input('What would you like to do?\n 1. Attack \n 2. Spells \n 3. Items \n 4. Run \n')
if choice == '1':
print('You attack the enemy!')
enemy.hp -= character.att
print('You dealt', character.att, 'to the enemy!')
print('Enemy hp =', enemy.hp)
elif choice == '2':
spellchoice = input('Which spell do you wish to call?')
print('1.', charspells[0],'\n' '2.', charspells[1], '\n' 'q', 'exit')
if spellchoice == ('1'):
print('You used fireball!')
fireball(character, enemy)
elif spellchoice == ('2'):
if charspells[1] != 'Lightning bolt':
print('It doesnt exist, sorry')
# ill add more spell fucntions later
if spellchoice == ('3'):
print('You went back to the menu')
elif choice == '3':
if items == []:
print('You have no items')
if items == ['potions']:
print ('response')
#placeholder ill add the fucntion later
elif choice == '4':
Loop = False
def enemy_battle(character, enemy):
a = random.randint(0,50)
if a <= 35:
print('The enemy attacks you!')
character.hp -= enemy.att
print('Your hp =', character.hp)
elif a <= 50:
print('The enemy uses mind attacks bruh')
character.hp -= enemy.int
print('Your hp =', character.hp)
def battle_loop(character, enemy):
Loop1 = True
while Loop1 == True:
while enemy.hp > 0 and character.hp > 0:
character_battle(character, enemy)
enemy_battle(character, enemy)
if enemy.hp <= 0:
print('You Won')
Loop1 = False
if character.hp <= 0:
print('You lost')
exit()
battle_loop(mainc, tai_lopez)
You didn't need two classes here clearly. But I suppose you might be thinking of adding some more features in future I guess. You can study more about oop and inheritance and figure out a smarter solution in general. I think you should focus on basics. Also try not to name the temporary variable same as that of class. It is a very hastly written code imo. But I fixed it's working.
Looks interesting, send me a copy after you finish will ya?
so basically you use too much input()
you have to enter a value for every input() function
you need to organize your code, maybe look at how others write their code
this is a quick fix, but it doesn't mean that this is the standard, you still have a lot to learn
import random
class character:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
charspells = ['Fireball','iceblock']
Loop = True
items = []
mainc = character(100, 100, 10, 0, 10)
tai_lopez = character(30, 30, 5, 0, 10) # enemy
def fireball(character, enemy):
enemy.hp -= character.int
print('You did, ',character.int ,'to the enemy')
print('Enemy.hp', enemy.hp)
return enemy.hp
def character_battle(character, enemy):
choice = input('What would you like to do?\n 1. Attack \n 2. Spells \n 3. Items \n 4. Run')
if choice == '1':
print('You attack the enemy!')
enemy.hp -= character.att
print('You dealt', character.att, 'to the enemy!')
print('Enemy hp =', enemy.hp)
if choice == '2':
print('Which spell do you wish to call?')
print('1.', charspells[0],'\n' '2.', charspells[1], '\n' 'q', 'exit')
spellchoice = input()
if spellchoice == ('1'):
print('You used fireball!')
fireball(character, enemy)
elif spellchoice == ('2'):
if charspells[1] != 'Lightning bolt':
print('It doesnt exist, sorry')
# ill add more spell fucntions later
if spellchoice == ('3'):
print('You went back to the menu')
if choice == '3':
if items == []:
print('You have no items')
if items == ['potions']:
print ('response')
#placeholder ill add the fucntion later
elif choice == '4':
print("You cowardly run away")
exit()
def enemy_battle(enemy, character):
a = random.randint(0,50)
if a <= 35:
print('The enemy attacks you!')
character.hp -= enemy.att
print('Your hp =', character.hp)
else:
print('The enemy uses mind attacks bruh')
character.hp -= enemy.int
print('Your hp =', character.hp)
def battle_loop(character, enemy):
Loop1 = True
while Loop1:
while enemy.hp > 0 and character.hp > 0:
character_battle(character, enemy)
enemy_battle(character, enemy)
if enemy.hp <= 0:
print('You Won')
Loop1 = False
if character.hp <= 0:
print('You lost')
exit()
battle_loop(mainc, tai_lopez)

Categories