Why does my program exit unexpectedly when I call input? - python

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)

Related

Doesn't run IF statement even though condition is true, but loops other IF

import random
player_health = 100
boss_health = 80
guard1_health = 10
guard1_status = "alive"
guard2_health = 15
gladiator_health = 20
weapon = 0
level = 0
turn = 0
def choose_weapon():
global weapon
global level
weapon = int(input("Choose your weapon:\n 1: Sword \n 2: Daggers \n 3: Bow \n Type here to choose:"
"\n--------------------------"))
if weapon == 1:
weapon = str("Sword")
print("You have chosen", weapon)
elif weapon == 2:
weapon = str("Daggers")
print("You have chosen", weapon)
else:
weapon = str("Bow")
print("You have chosen", weapon)
level += 1
choose_weapon()
def level_1_enemy():
global guard1_status
global guard1_health
global level
global turn
global weapon
print("Player turn")
if guard1_status == "alive" and guard1_health > 0 and turn == 1:
print("test")
if weapon == 1:
guard1_health -= 8
print("Guard health:", guard1_health)
turn -= 1
elif weapon == 2:
guard1_health -= 5
print("Guard health:", guard1_health)
turn -= 1
elif weapon == 3:
bow_crit = random.randint(1, 10)
if bow_crit == 1:
guard1_health -= 20
print("Guard health:", guard1_health)
else:
guard1_health -= 5
print("Guard health:", guard1_health)
if guard1_health <= 0:
print("You defeated the Guard, next level!")
guard1_status = "dead"
level += 1
return
def level_1_player():
global player_health
global weapon
global level
global turn
if player_health > 0 and turn == 0:
if weapon == 2:
dodge = random.randint(1, 3)
if dodge == 1:
print("You dodged the attack!")
return
else:
player_health -= 5
print("\n\nThe enemy hit you! (-5 hp)")
print("Enemy health: ", guard1_health)
print("Your health: ", player_health)
return
else:
player_health -= 5
print("\n\nThe enemy hit you! (-5 hp)")
print("Enemy health: ", guard1_health)
print("Your health: ", player_health)
return
print("You have died, Game Over.")
return
while level == 1:
if turn == 0:
level_1_player()
turn += 1
elif turn == 1:
level_1_enemy()
turn -= 1
I want to have the game loop through player and enemy turns until either the player is dead or the enemy. It reaches the first IF in level_1_enemy and prints "test", but does not continue to the next if statement even though the condition "weapon == 1" is true.
The last while loop is meant to repeat the level_1_enemy and level_1_player functions. It does do both but will also not stop looping once the guard or player is dead.

how can I subtract the amount Randint generates in the while loop from enemies HP without getting 2 different numbers?

If you run the code you should see that the print says "14" for example, but It retracts something else from enemies HP.
Calculating attack damage for each "spell":
from random import randint
import time
class Player(object):
def __init__(self, health):
self.health = health
#staticmethod
def use_heal():
return randint(9, 21)
#staticmethod
def attack_slice():
return randint(5, 29)
#staticmethod
def attack_bash():
return randint(11, 18)
class Enemy(object):
def __init__(self, health):
self.health = health
#staticmethod
def enemy_attack():
return randint(9, 19)
For setting HP:
player = Player(100)
enemy = Enemy(100)
The loop that is the "game":
while True:
print(f"Your hp: {player.health}\nEnemy hp: {enemy.health}\n")
print("(1) Bash _ (2) Slice _ (3) Heal")
attack_choice = int(input(">>"))
if attack_choice == 1:
print(f"You hit for {Player.attack_bash()}")
enemy.health -= Player.attack_bash()
elif attack_choice == 2:
print(f"You hit for {Player.attack_slice()}")
enemy.health -= Player.attack_slice()
elif attack_choice == 3:
print(f"You heal for {Player.use_heal()}")
player.health += Player.use_heal()
when it calls Player.attack_* it returns a random value to print, and then calls it a second time to actualy damage the enemy so it is likely a defarent value. what it should do is call it once, store it in a variable and use the variable
while True:
print(f"Your hp: {player.health}\nEnemy hp: {enemy.health}\n")
print("(1) Bash _ (2) Slice _ (3) Heal")
attack_choice = int(input(">>"))
if attack_choice == 1:
damage = Player.attack_bash()
print(f"You hit for {damage}")
enemy.health -= damage
elif attack_choice == 2:
damage = Player.attack_slice()
print(f"You hit for {damage}")
enemy.health -= damage
elif attack_choice == 3:
damage = Player.use_heal()
print(f"You heal for {damage}")
player.health += damage
The problem is you are generating two random numbers for each case: The one that gets print and the one that gets subtracted/added.
...
print(f"You hit for {Player.attack_bash()}") # Generates a random number
enemy.health -= Player.attack_bash() # Generates another random number
...
You need to use a temporary variable so you can use the same value twice:
...
damage = Player.attack_bash()
print(f"You hit for {damage}")
enemy.health -= damage
...

Code execution shell vs Jupyter Notebook

I have a general question regarding code execution. I have a case when the same code is executed perfectly in shell and has some issues in Jupiter.
In Jupyter Notebook it tends to stop, usually at the beginning of the loop or before user input. Nothing happens then but the kernel is busy. Same part of the code sometimes works and sometimes doesn't.
Program is very simple so that should not be an issue. Have you ever faced similar issues? Can it be because I haven't split the code into few cells? Many thanks in advance!
EDIT: I've added the full code as I haven't managed to re-create a problem on a smaller sample. Basically the problem occurs either at the very start of the game when hit_or_stand should be executed or at the repeat_game() function level.
# import
import random
# define classes
deck_colors = ["Hearts", "Spades", "Clubs", "Diamonds"]
deck_ranks = ["Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace"]
deck_values = {"Two" : 2, "Three" : 3, "Four" : 4, "Five" : 5, "Six" : 6, "Seven" : 7, "Eight" : 8, "Nine" : 9,
"Ten" : 10, "Jack" : 10, "Queen" : 10, "King" : 10, "Ace" : 11}
class Card():
def __init__(self, color, rank):
self.color = color
self.rank = rank
self.value = deck_values[rank]
def __str__(self):
return self.rank + ' of ' + self.color
class Deck():
def __init__(self):
self.deck = []
for color in deck_colors:
for rank in deck_ranks:
self.deck.append(Card(color, rank))
def __str__(self):
deck_description = ''
for card in self.deck:
deck_description += card.__str__() + '\n'
return "\nCurrent deck:\n" + deck_description
#shuffle deck before the game
def shuffle(self):
random.shuffle(self.deck)
# pop last card to pass it on to players
def pop_card(self):
return self.deck.pop()
class Hand():
def __init__(self, name):
self.cards_in_hand = []
self.value = 0
self.aces = 0
self.name = name
def add_card(self, deck):
new_card = deck.pop_card()
self.cards_in_hand.append(new_card)
self.value += new_card.value
if new_card.rank == "Ace":
self.aces += 1
while self.aces > 0:
if self.value > 21:
self.value -= 10
self.aces -=1
else:
break
class Chips():
def __init__(self):
self.value = 100
self.bet = 0
def take_bet(self):
while True:
bet_value = input(f"You have {self.value} chips. What's your bet? ")
try:
bet_value = int(bet_value)
if bet_value > 0 and bet_value <= self.value:
self.bet = bet_value
self.value -= bet_value
break
elif bet_value > self.value:
print("You don't have enough chips.")
continue
else:
print(f"Choose correct value (1-{self.value})")
continue
except:
print(f"You have to choose correct number (1-{self.value})!")
def win_bet(self):
self.value += (self.bet * 2)
self.bet = 0
def lose_bet(self):
self.bet = 0
def draw(self):
self.value += self.bet
self.bet = 0
# define functions
def show_some_cards(player_hand, dealer_hand):
player_str = ''
for card in player_hand.cards_in_hand:
player_str += f"\n{card.__str__()} "
print("Player's cards:", player_str)
dealer_str = ' '
for card in dealer_hand.cards_in_hand[1:]:
dealer_str += f"\n{card.__str__()} "
print("\nDealer's cards:\n<hidden card>", dealer_str)
def show_all_cards(player_hand, dealer_hand):
player_str = ''
for card in player_hand.cards_in_hand:
player_str += f"\n{card.__str__()} "
print("Player's cards:", player_str)
print("Cards value:", player_hand.value)
dealer_str = ' '
for card in dealer_hand.cards_in_hand:
dealer_str += f"\n{card.__str__()} "
print("\nDealer's cards:", dealer_str)
print("Cards value:", dealer_hand.value)
def hit_or_stand(player1_hand, player2_hand, deck, chips):
global dealer_action
global busted_before
while True:
print('\n'*100)
print("Here're the cards\n")
show_some_cards(player1_hand, player2_hand)
action = input("Do you want another card? (Y/N)")
if action.upper() == "Y":
player1_hand.add_card(deck)
if player_hand.value > 21:
busted(player_hand, dealer_hand, chips)
dealer_action = False
busted_before = True
break
continue
elif action.upper() == "N":
break
else:
print("Choose correct answer (Y/N)")
continue
def dealer_playing(player1_hand, player2_hand, deck, chips):
global busted_before
while True:
print('\n'*100)
print("Here're the cards\n")
show_some_cards(player1_hand, player2_hand)
if player2_hand.value < 17:
player2_hand.add_card(deck)
if player2_hand.value > 21:
busted(dealer_hand, player_hand, chips)
busted_before = True
break
continue
else:
break
def busted(current_hand, other_hand, chips):
print('\n'*100)
if current_hand.name == "Player":
show_all_cards(current_hand, other_hand)
chips.lose_bet()
print(f"Player busted! You now have only {chips.value} chips.")
elif current_hand.name == "Dealer":
show_all_cards(other_hand, current_hand)
chips.win_bet()
print(f"Dealer busted! You now have {chips.value} chips.")
else:
print("Something went wrong! (busted function)")
def check_winners(player1_hand, player2_hand, chips):
print('\n'*100)
if player1_hand.value > player2_hand.value:
show_all_cards(player1_hand, player2_hand)
chips.win_bet()
print(f"Player won! You now have {chips.value} chips.")
elif player1_hand.value < player2_hand.value:
show_all_cards(player1_hand, player2_hand)
chips.lose_bet()
print(f"Dealer won! You now have only {chips.value} chips.")
elif player1_hand.value == player2_hand.value:
show_all_cards(player1_hand, player2_hand)
chips.draw()
print(f"It's a draw! You still have {chips.value} chips.")
def repeat_game(chips):
global repeat
while True:
repetition = input("Would you like to play again? (Y/N)")
if chips.value > 0:
if repetition.upper() == 'Y':
repeat = True
break
elif repetition.upper() == 'N':
repeat = False
break
else:
print("Choose correct value (Y/N)")
continue
else:
print("You don't'have enough chips to continue.")
repeat = False
break
def start_again():
global new_game
while True:
restart_game = input("Would you like to start completely new game? (Y/N)")
if restart_game.upper() == 'Y':
new_game = True
break
elif restart_game.upper() == 'N':
new_game = False
break
else:
print("Choose correct value (Y/N)")
continue
# play the game
new_game = True
while new_game == True:
repeat = True
player_chips = Chips()
print("Welcome to BlackJack!")
while repeat == True:
print('\n'*100)
#### initialization ###
current_deck = Deck()
current_deck.shuffle()
player_hand = Hand("Player")
player_hand.add_card(current_deck)
player_hand.add_card(current_deck)
dealer_hand = Hand("Dealer")
dealer_hand.add_card(current_deck)
dealer_hand.add_card(current_deck)
#### game_ongoing ###
player_chips.take_bet()
dealer_action = True
busted_before = False
hit_or_stand(player_hand, dealer_hand, current_deck, player_chips)
if dealer_action == True:
dealer_playing(player_hand, dealer_hand, current_deck, player_chips)
if busted_before == False:
check_winners(player_hand, dealer_hand, player_chips)
repeat_game(player_chips)
start_again()
Splitting the code in cells has nothing to do with the issue. Different cells are used so you won't run same code again and again. Notebook and shell have some small difference but the basic idea is same. you should share the notebook code, so, i can help you with your issue.

calling a function in Python?

I don't know how to call the functions below I listed a box with what I want to do but don't know how to.
import random
import time
startingP_health = 30
startingE_health = 30
def player_attack():
global startingE_health
time.sleep(1)
print ("What ability would you like to use? (free speach(fs), capatalism(c), or punch(p)")
ability_choice = input()
if(ability_choice == "fs"):
enemy_health = startingE_health-3
enemy_heath = int(enemy_health)
elif(ability_choice == "c"):
enemy_health = startingE_health-(random.randint(1,6))
enemy_heath = int(enemy_health)
elif(ability_choice == "p"):
enemy_health = startingE_health-(random.randint(2,4))
enemy_heath = int(enemy_health)
else:
print("you fell.")
time.sleep(1)
print ("Enemie's health is now: ",enemy_health)
print("")
return int(enemy_health)
def enemy_attack():
global startingP_health
time.sleep(1)
print ("Enemy kicks you")
print("")
player_health = startingP_health - (random.randint(1,3)
player_health = int(player_health)
time.sleep(1)
print ("Your health is now ",player_health)
print ("")
return int(player_health)
def battle_trotsky():
global player_health
print ("Enemy appears")
print ("")
time.sleep(1)
while player_health > 0 and enemy_health > 0:
##############################
#call function player_attack
#call enemy_attack
##############################
if player_health <=0:
break
if enemy_health <= 0:
time.sleep(1)
print ("You have killed the enemy")
if player_health <= 0:
print("Sorry you failed the mission you must restart the mission"))
################################
#initate function sequence
################################
import random
import time
You need to declare enemy_health and player_health as globals so they persist:
startingP_health = 30
startingE_health = 30
enemy_health = startingE_health
player_health = startingP_health
This function doesn't have to return anything, since you declare global enemy_health and then assign it the new value:
def player_attack():
global enemy_health
time.sleep(1)
print ("What ability would you like to use? (free speech(fs), capitalism(c), or punch(p)")
ability_choice = input()
This wasn't working because you were doing enemy_health = starting health - 3, which means every round it would start again from the starting health. Instead here, -= is subtract from the current value: enemy_health = enemy_health - 3:
if(ability_choice == "fs"):
enemy_health -= 3
elif(ability_choice == "c"):
enemy_health -= random.randint(1,6)
elif(ability_choice == "p"):
enemy_health -= random.randint(2,4)
else:
print("you fell.")
time.sleep(1)
print ("Enemy's health is now: ",enemy_health)
print("")
def enemy_attack():
global player_health
time.sleep(1)
print ("Enemy kicks you")
print ("")
player_health -= random.randint(1,3)
time.sleep(1)
print ("Your health is now ",player_health)
print ("")
def battle_trotsky():
global player_health
global enemy_health
print ("Enemy appears")
print ("")
time.sleep(1)
while player_health > 0 and enemy_health > 0:
Functions are called via name(), as seen:
player_attack()
enemy_attack()
if enemy_health <= 0:
time.sleep(1)
print ("You have killed the enemy")
if player_health <= 0:
print("Sorry you failed the mission you must restart the mission")
battle_trotsky()
This is a not a good question for this site as it is not specific, but I feel compelled to fixed this code by a deep power. I'm not sure why you're doing the sleeps, the print("") statements can be replaced with a '\n' in the previous prints, and you are continuously reassigning player health to the starting health - number, which will never reach 0, so you must make the healths global.
Here's a working example
import random
player_health = 30
enemy_health = 30
def player_attack():
global enemy_health
ability_choice = input("What ability would you like to use? (free speach(fs), capatalism(c), or punch(p)")
if(ability_choice == "fs"):
enemy_health -= 3
elif(ability_choice == "c"):
enemy_health -= random.randint(1,6)
elif(ability_choice == "p"):
enemy_health -= random.randint(2,4)
else:
print("you fell.")
print ("Enemy's health is now: "+str(enemy_health)+'\n')
def enemy_attack():
global player_health
print ("Enemy kicks you")
player_health -= random.randint(1,3)
print ("Your health is now "+str(player_health)+"\n")
def battle_trotsky():
print ("Enemy appears\n")
while player_health > 0 and enemy_health > 0:
player_attack()
if check_game_over():
return
enemy_attack()
if check_game_over():
return
def check_game_over():
global player_health, enemy_health
if enemy_health <= 0:
print ("You have killed the enemy\n")
return True
elif player_health <= 0:
print("Sorry you failed the mission you must restart the mission")
return True
else:
return False
if __name__=='__main__':
battle_trotsky()

Python Error: ValueError: Non-integer arg 1 for randrange()

I'm getting the above error in my code. It's just a simple text-based game.
Here's the code:
import os
import sys
import random
class Player:
def __init__(self, name):
self.name = name
self.maxhealth = 100
self.health = self.maxhealth
self.attack = 10
self.gold = 0
self.potions = 0
class Goblin:
def __init__(self, name):
self.name = name
self.maxhealth = 50
self.health = self.maxhealth
self.attack = 5
self.goldgain = 10
GoblinIG = Goblin("Goblin")
class Zombie:
def __init__(self, name):
self.name = name
self.maxhealth = 70
self.health = self.maxhealth
self.attack = 7
self.goldgain = 15
ZombieIG = Zombie("Zombie")
def main():
#os.system("cls")
print("Welcome to my game!")
print("1) Start")
print("2) Load")
print("3) Exit")
option = input("-> ")
if option == "1":
start()
elif option == "2":
pass
elif option == "3":
pass
else:
main()
def start():
#os.system("cls")
print("Hello, what is your name?")
option = input("-> ")
global PlayerIG
PlayerIG = Player(option)
start1()
def start1():
#os.system("cls")
print("Name: %s" % PlayerIG.name)
print("Attack: %s" % PlayerIG.attack)
print("Gold: %i" % PlayerIG.gold)
print("Potions: %i" % PlayerIG.potions)
print("Health: %i/%i" % (PlayerIG.health, PlayerIG.maxhealth))
print("1) Fight")
print("2) Store")
print("3) Save")
print("4) Exit")
option = input("-> ")
if option == "1":
prefight()
elif option == "2":
store()
elif option == "3":
pass
elif option == "4":
sys.exit()
else:
start1()
def prefight():
global enemy
enemynum = random.randint(1,2)
if enemynum == 1:
enemy = GoblinIG
else:
enemy = ZombieIG
fight()
def fight():
print("%s vs %s" % (PlayerIG.name, enemy.name))
print("%s's Health: %s/%s %s Health: %i/%i" % (PlayerIG.name, PlayerIG.health, PlayerIG.maxhealth, enemy.name, enemy.health, enemy.maxhealth))
print("Potions Left: %s\n" % PlayerIG.potions)
print("1) Attack")
#Implement defend system
print("2) Drink Potion")
print("3) Run")
option = input()
if option == "1":
attack()
elif option == "2":
drinkPotion()
elif option == "3":
run()
else:
fight()
def attack():
global PlayerAttack
global EnemyAttack
PlayerAttack = random.randint(PlayerIG.attack / 2, PlayerIG.attack)
EnemyAttack = random.randint(enemy.attack / 2, enemy.attack)
if PlayerAttack == PlayerIG.attack / 2:
print("You missed!")
else:
enemy.health -= PlayerAttack
print("You dealt %i damage!" % PlayerAttack)
option = input(" ")
if enemy.health <= 0:
win()
if EnemyAttack == enemy.attack/2:
print("The enemy missed!")
else:
PlayerIG.health -= EnemyAttack
print("The enemy dealt %i damage!" % EnemyAttack)
option = input("")
if PlayerIG.health <= 0:
dead()
else:
fight()
def drinkPotion():
if PlayerIG.potions == 0:
print("You don't have any potions!")
else:
PlayerIG.health += 50
if PlayerIG.health >= PlayerIG.maxhealth:
PlayerIG.health = PlayerIG.maxhealth
print("You drank a potion!")
option = input(" ")
fight()
def run():
runnum = random.randint(1,3)
if runnum == 3:
print("You have ran away!")
option = input(" ")
start1()
else:
print("You've failed to run away!")
option = input(" ")
EnemyAttack = random.randint(enemy.attack / 2, enemy.attack)
if EnemyAttack == enemy.attack/2:
print("The enemy missed!")
else:
PlayerIG.health -= EnemyAttack
print("The enemy dealt %i damage!" % EnemyAttack)
option = input(" ")
if PlayerIG.health <=0:
dead()
else:
fight()
def win():
enemy.health = enemy.maxhealth
PlayerIG.gold -= enemy.goldgain
print("You have defeated the %s!" % enemy.name)
print("You found %i gold!" % enemy.goldgain)
option = input(" ")
start1()
def dead():
print("You have died!")
option = input(" ")
def store():
pass
main()
I get the error in def run(), in the else: statement. The line that goes like: EnemyAttack = random.randint(enemy.attack / 2, enemy.attack)
Any ideas? Should I elaborate more on my issue? Thanks :)
Use EnemyAttack = random.randint(math.floor(enemy.attack / 2), enemy.attack), or use math.ceil() to round the result of enemy.attack / 2.
randrange() expects whole integers. The error is occurring because the result of enemy.attack / 2 isn't a whole number; it has decimal places whenever enemy.attack is odd. One option is to scale randrange() after it is calculated if you need decimal results.
For example: 0.5*randrange(2*(enemy.attack/2), 2*enemy.attack), which can be simplified into 0.5*randrange(enemy.attack, 2*enemy.attack)

Categories