Need help fixing my game in Python - python

import random
hp = 100
eh = 100
x = 0
y = 0
print("Hello welcome to the beta version of my game.
This game is a 1 v 1 fight to the death against an unknown enemy.
In this game you and the enemy both start out with 100 health.
You can choose to either attack or heal each turn. Have fun and
pay attention to the following rules.")
print("Rule 1: You cannot heal while your health is over 84 points.
If you break this rule your turn will be void.")
print("Rule 2: You can only enter attack, Attack, heal, or Heal.
If you break this rule your turn will be void.")
print("Please press enter to start")
while hp > 0 and eh > 0:
print("Action? (attack, heal, nothing):")
act = input(">")
attack = random.randint(1, 30)
heal = random.randint(1, 15)
enemy_attack = random.randint(1, 30)
enemy_heal = random.randint(1, 15)
enemy_heal_within_5 = random.randint(1, 5)
enemy_decision = random.randint(1, 2)
if act == "attack" or act == "Attack":
eh = eh - attack
print(attack)
print("You have dealt %s damage" % attack)
elif act == "heal" and hp < 85:
hp = hp + heal
print("You have healed %s points" % heal)
elif act == "heal" and hp > 84:
while x == 0:
if act == "attack":
x +=1
else:
print("You cannot heal at this time, please try again.")
act = input(">")
if enemy_decision == 1:
hp = hp - enemy_attack
print("The enemy has dealt %s damage" % enemy_attack)
elif enemy_decision == 2 and eh > 94:
pass
elif enemy_decision == 2:
eh = eh + enemy_heal_within_5
print("The enemy has healed %s points" % enemy_heal_within_5)
elif enemy_decision == 2 and eh < 85:
eh = eh + enemy_heal
print("The enemy has healed %s points" % enemy_heal)
else:
print("Your health is now %s" % hp)
print("The enemy's health is now %s" % eh)
if hp <= 0:
print("You have lost")
elif eh <= 0:
print("You have won")
I need help creating an else statement where if the player enters something other than attack or heal, it asks them to try to input either attack or heal again. I tried repeating what I did in the hp > 84 section, but it ended up running that section instead of the else section.

You can make something like:
...
while hp > 0 and eh > 0:
act = "empty"
print("Action? (attack, heal, nothing):")
# With this while, you are accepting anything like "aTTaCk", "AttaCK", etc
while act.lower() not in ["attack","heal", "", "nothing"]:
act = input(">")
attack = random.randint(1, 30)
heal = random.randint(1, 15)
enemy_attack = random.randint(1, 30)
enemy_heal = random.randint(1, 15)
enemy_heal_within_5 = random.randint(1, 5)
enemy_decision = random.randint(1, 2)
...
I added the option nothing and also an empty string("") as an option if the player doesn't want to make anything. If you don't need any of them, just delete both from the list in while statement.

import random
hp = 100
eh = 100
x = 0
y = 0
print("Hello welcome to the beta version of my game. This game is a 1 v 1 fight to the death against an unknown enemy. In this game you and the enemy both start out with 100 health. You can choose to either attack or heal each turn. Have fun and pay attention to the following rules.")
print("Rule 1: You cannot heal while your health is over 84 points. If you break this rule your turn will be void.")
print("Rule 2: You can only enter attack, Attack, heal, or Heal. If you break this rule your turn will be void.")
print("Please press enter to start")
while hp > 0 and eh > 0:
act = ""
print("Action? (attack, heal, nothing):")
while act.lower() != "attack" and act.lower() != "heal":
act = input(">")
attack = random.randint(1, 30)
heal = random.randint(1, 15)
enemy_attack = random.randint(1, 30)
enemy_heal = random.randint(1, 15)
enemy_heal_within_5 = random.randint(1, 5)
enemy_decision = random.randint(1, 2)
if act == "attack" or act == "Attack":
eh = eh - attack
print(attack)
print("You have dealt %s damage" % attack)
elif act == "heal" and hp < 85:
hp = hp + heal
print("You have healed %s points" % heal)
elif act == "heal" and hp > 84:
while x == 0:
if act == "attack":
x +=1
else:
print("You cannot heal at this time, please try again.")
act = input(">")
if enemy_decision == 1:
hp = hp - enemy_attack
print("The enemy has dealt %s damage" % enemy_attack)
elif enemy_decision == 2 and eh > 94:
pass
elif enemy_decision == 2:
eh = eh + enemy_heal_within_5
print("The enemy has healed %s points" % enemy_heal_within_5)
elif enemy_decision == 2 and eh < 85:
eh = eh + enemy_heal
print("The enemy has healed %s points" % enemy_heal)
else:
print("Your health is now %s" % hp)
print("The enemy's health is now %s" % eh)
if hp <= 0:
print("You have lost")
elif eh <= 0:
print("You have won")
Use a while loop that checks whether the input is not "attack" and if it is not "heal", or any capitalized version of the two. I use !=, but you can also use not, as Ruben Bermudez showed below.

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.

Opponents health not decreasing, and turns not flipping over [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
So, for the main action sequence of my game, I have this code for the battle. It works, sort of. I can choose the moves and all the text will display, but it doesn't take health off of the opponent, and the turn doesn't change over. I can't for the life of me figure out what I've done wrong. Here is the code:
I'm using python 2.7.
play_again = True
while play_again is True:
winner = None
player_health = 100
computer_health = random.randrange(1,200)
player_turn = True
computer_turn = False
while (player_health != 0 or computer_health != 0):
heal_up = False
miss = False
moves = {"Punch": random.randint(18, 25),
"Slap": random.randint(10, 35),
"Kick": random.randint(10, 25)}
if player_turn is True:
print("""1. Punch
2. Slap
3. Kick
""")
player_move = raw_input(">>> ")
move_miss = random.randint(1,10)
if move_miss == 1:
miss = True
else:
miss = False
if miss:
player_move = 0
print("You missed!")
else:
if player_move in ("1", "punch"):
player_move = moves["Punch"]
print("You used Punch! It dealt %s damage!") % player_move
elif player_move in ("2", "slap"):
player_move = moves["Slap"]
print("\nYou used Slap!. It dealt %s damage.") % player_move
elif player_move in ("3", "kick"):
player_move = moves["Kick"]
print("\nYou used Kick! It dealt %s damage.") % player_move
else:
print("\nThat is not a valid move. Please try again.")
else:
move_miss = random.randint(0, 10)
if move_miss == 1:
miss = True
else:
miss = False
if miss:
computer_move = 0
print('The Opponent Missed!')
else:
imoves = ["Punch", "Slap","Kick"]
imoves = random.choice(imoves)
CPU_move = moves[imoves]
if CPU_move == moves["Punch"]:
print("The opponent used Punch. It dealt %s Damage.") % CPU_move
player_health -= CPU_move
if CPU_move == moves["Slap"]:
print("\nThe opponent used Slap. It dealt %s Damage.") % CPU_move
player_health -= CPU_move
if CPU_move == moves["Kick"]:
print("\nThe opponent used Kick. It dealt %s Damage.") % CPU_move
player_health -= CPU_move
if player_turn is true:
computer_health -= player_move
if computer_health <= 0:
computer_health = 0
winner = "Player"
break
else:
if player_health <= 0:
player_health = 0
winner = "Computer"
break
print("Your health: %s, Opponents health: %s") % (player_health, computer_health)
# switch turns
player_turn = not player_turn
computer_turn = not computer_turn
if winner == "Player":
print("Your health: %s, Opponents health: %s") % (player_health, computer_health)
print('Congratulations! You have won.')
else:
print("Your health: %s, Opponents health: %s") % (player_health, computer_health)
print("Sorry, but your opponent wiped the floor with you. Better luck next time.")
Your entire code that deals with decreasing the opponent's health and flipping the turns are improperly indented to be inside the outer loop (which checks if the player wants to play again) instead of the inner loop (which is the main loop that actually plays each turn).
Simply indent that code with two more spaces, and fix your typo of True in if player_turn is true: (the first letter of True has to be capitalized), and your code would work:
import random
play_again = True
while play_again is True:
winner = None
player_health = 100
computer_health = random.randrange(1,200)
player_turn = True
computer_turn = False
while (player_health != 0 or computer_health != 0):
heal_up = False
miss = False
moves = {"Punch": random.randint(18, 25),
"Slap": random.randint(10, 35),
"Kick": random.randint(10, 25)}
if player_turn is True:
print("""1. Punch
2. Slap
3. Kick""")
player_move = raw_input(">>> ")
move_miss = random.randint(1,10)
if move_miss == 1:
miss = True
else:
miss = False
if miss:
player_move = 0
print("You missed!")
else:
if player_move in ("1", "punch"):
player_move = moves["Punch"]
print("You used Punch! It dealt %s damage!") % player_move
elif player_move in ("2", "slap"):
player_move = moves["Slap"]
print("\nYou used Slap!. It dealt %s damage.") % player_move
elif player_move in ("3", "kick"):
player_move = moves["Kick"]
print("\nYou used Kick! It dealt %s damage.") % player_move
else:
print("\nThat is not a valid move. Please try again.")
else:
move_miss = random.randint(0, 10)
if move_miss == 1:
miss = True
else:
miss = False
if miss:
computer_move = 0
print('The Opponent Missed!')
else:
imoves = ["Punch", "Slap","Kick"]
imoves = random.choice(imoves)
CPU_move = moves[imoves]
if CPU_move == moves["Punch"]:
print("The opponent used Punch. It dealt %s Damage.") % CPU_move
player_health -= CPU_move
if CPU_move == moves["Slap"]:
print("\nThe opponent used Slap. It dealt %s Damage.") % CPU_move
player_health -= CPU_move
if CPU_move == moves["Kick"]:
print("\nThe opponent used Kick. It dealt %s Damage.") % CPU_move
player_health -= CPU_move
if player_turn is True:
computer_health -= player_move
if computer_health <= 0:
computer_health = 0
winner = "Player"
break
else:
if player_health <= 0:
player_health = 0
winner = "Computer"
break
print("Your health: %s, Opponents health: %s") % (player_health, computer_health)
# switch turns
player_turn = not player_turn
computer_turn = not computer_turn
if winner == "Player":
print("Your health: %s, Opponents health: %s") % (player_health, computer_health)
print('Congratulations! You have won.')
else:
print("Your health: %s, Opponents health: %s") % (player_health, computer_health)
print("Sorry, but your opponent wiped the floor with you. Better luck next time.")
Here's a sample output with the fix:
1. Punch
2. Slap
3. Kick
>>> 2
You used Slap!. It dealt 34 damage.
Your health: 100, Opponents health: 59
The opponent used Slap. It dealt 31 Damage.
Your health: 69, Opponents health: 59
1. Punch
2. Slap
3. Kick
>>> 1
You used Punch! It dealt 21 damage!
Your health: 69, Opponents health: 38
The Opponent Missed!
Your health: 69, Opponents health: 38
1. Punch
2. Slap
3. Kick
>>> 1
You used Punch! It dealt 19 damage!
Your health: 69, Opponents health: 19
The opponent used Kick. It dealt 19 Damage.
Your health: 50, Opponents health: 19
1. Punch
2. Slap
3. Kick
>>> 1
You used Punch! It dealt 22 damage!
Your health: 50, Opponents health: 0
Congratulations! You have won.
1. Punch
2. Slap
3. Kick
>>>

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)

Blackjack, won't restart game in python

Right now I'm having trouble with the code restarting. It restarts but it doesn't go back to the beginning. It just keeps asking me if I want to restart.
For example it says
The player has cards [number, number, number, number, number] with a total value of (whatever the numbers add up too.)
--> Player is busted!
Start over? Y/N
I type in Y and it keeps saying
The player has cards [number, number, number, number, number] with a total value of (whatever the numbers add up too.)
--> Player is busted!
Start over? Y/N
Can anyone please fix it so that it will restart. - or tell me how to my code is below.
from random import choice as rc
def playAgain():
# This function returns True if the player wants to play again, otherwise it returns False.
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y')
def total(hand):
# how many aces in the hand
aces = hand.count(11)
t = sum(hand)
# you have gone over 21 but there is an ace
if t > 21 and aces > 0:
while aces > 0 and t > 21:
# this will switch the ace from 11 to 1
t -= 10
aces -= 1
return t
cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
c2win = 0 # computer2 win
cwin = 0 # computer win
pwin = 0 # player win
while True:
player = []
player.append(rc(cards))
player.append(rc(cards))
pbust = False # player busted
cbust = False # computer busted
c2bust = False # computer2 busted
while True:
tp = total(player)
print ("The player has cards %s with a total value of %d" % (player, tp))
if tp > 21:
print ("--> Player is busted!")
pbust = True
print('Start over? Y/N')
answer = input()
if answer == 'n':
done = True
break
elif tp == 21:
print ("\a BLACKJACK!!!")
print("do you want to play again?")
answer = input()
if answer == 'y':
done = False
else:
break
else:
hs = input("Hit or Stand/Done (h or s): ").lower()
if 'h' in hs:
player.append(rc(cards))
if 's' in hs:
player.append(rc(cards))
while True:
comp = []
comp.append(rc(cards))
comp.append(rc(cards))
while True:
comp2 = []
comp.append(rc(cards))
comp.append(rc(cards))
while True:
tc = total(comp)
if tc < 18:
comp.append(rc(cards))
else:
break
print ("the computer has %s for a total of %d" % (comp, tc))
if tc > 21:
print ("--> Computer is busted!")
cbust = True
if pbust == False:
print ("Player wins!")
pwin += 1
print('Start over? Y/N')
answer = input()
if answer == 'y':
playAgain()
if answer == 'n':
done = True
elif tc > tp:
print ("Computer wins!")
cwin += 1
elif tc == tp:
print ("It's a draw!")
elif tp > tc:
if pbust == False:
print ("Player wins!")
pwin += 1
elif cbust == False:
print ("Computer wins!")
cwin += 1
break
print
print ("Wins, player = %d computer = %d" % (pwin, cwin))
exit = input("Press Enter (q to quit): ").lower()
if 'q' in exit:
break
print
print
print ("Thanks for playing blackjack with the computer!")
fun little game, I removed the second dealer for simplicity, but it should be easy enough to add back in. I changed input to raw_input so you could get a string out of it without entering quotes. touched up the logic a bit here and there, redid formating and added comments.
from random import choice as rc
def play_again():
"""This function returns True if the player wants to play again,
otherwise it returns False."""
return raw_input('Do you want to play again? (yes or no)').lower().startswith('y')
def total(hand):
"""totals the hand"""
#special ace dual value thing
aces = hand.count(11)
t = sum(hand)
# you have gone over 21 but there is an ace
while aces > 0 and t > 21:
# this will switch the ace from 11 to 1
t -= 10
aces -= 1
return t
cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
cwin = 0 # computer win
pwin = 0 # player win
while True:
# Main Game Loop (multiple hands)
pbust = False # player busted
cbust = False # computer busted
# player's hand
player = []
player.append(rc(cards))
player.append(rc(cards))
pbust = False # player busted
cbust = False # computer busted
while True:
# Player Game Loop (per hand)
tp = total(player)
print ("The player has cards %s with a total value of %d" % (player, tp))
if tp > 21:
print ("--> Player is busted!")
pbust = True
break
elif tp == 21:
print ("\a BLACKJACK!!!")
break
else:
hs = raw_input("Hit or Stand/Done (h or s): ").lower()
if hs.startswith('h'):
player.append(rc(cards))
else:
break
#Dealers Hand
comp = []
comp.append(rc(cards))
comp.append(rc(cards))
tc = total(comp)
while tc < 18:
# Dealer Hand Loop
comp.append(rc(cards))
tc = total(comp)
print ("the computer has %s for a total of %d" % (comp, tc))
if tc > 21:
print ("--> Computer is busted!")
cbust = True
# Time to figure out who won
if cbust or pbust:
if cbust and pbust:
print ("both busted, draw")
elif cbust:
print ("Player wins!")
pwin += 1
else:
print ("Computer wins!")
cwin += 1
elif tc < tp:
print ("Player wins!")
pwin += 1
elif tc == tp:
print ("It's a draw!")
else:
print ("Computer wins!")
cwin += 1
# Hand over, play again?
print ("\nWins, player = %d computer = %d" % (pwin, cwin))
exit = raw_input("Press Enter (q to quit): ").lower()
if 'q' in exit:
break
print ("\n\nThanks for playing blackjack with the computer!")

get this combat engine working?

Currently stuck on exercise 36 of Zed Shaw's LPTHW and I could really use some help figuring out why this combat engine I made isn't working. I rewrote an earlier attempt to try to make it more clear. Here is the relevant code I believe, I apologize if its too long, but as a newbie I'm not entirely sure what is relevant.
#Check to hit and applies damage / crit + damage use p for player and m for monster
def hit_check(x):
global current_hp, monster_current_hp, to_hit, monster_to_hit, crit
global monster_crit, dmg, monster, monster_dmg
if x == 'p':
if d20() >= to_hit and d100() <= crit:
monster_current_hp = monster_current_hp - dmg * 3
print "You critically wounded the %s!" % monster
next()
elif d20() >= to_hit and d100() > crit:
monster_current_hp = monster_current_hp - dmg
print "You wounded the %s!" % monster
next()
else:
print "You missed the %s." % monster
next()
elif x == 'm':
if d20() >= monster_to_hit and d100() <= monster_crit:
current_hp = current_hp - monster_dmg * 3
print "The %s critically wonded %s!" % (monster, name)
next()
elif d20() >= to_hit and d100() > crit:
current_hp = current_hp - dmg
print "The %s wounded %s." % (monster, name)
next()
else:
print "The %s missed %s." % (monster, name)
next()
else:
print "Ray diddnt correctly assign a hit check"
exit(0)
# Combat engine / prompt
def combat_engine():
global current_hp, monster_current_hp, wins, gold, hit_points, p, m
"""Will choose a monster, and then allow the player to fight monster"""
global current_hp, monster_current_hp, prompt
if wins == 0:
choose_monster(level_zero_monsters)
elif wins == 1:
choose_monster(level_one_monsters)
elif wins == 2:
choose_monster(level_two_monsters)
elif wins == 3:
choose_monster(level_three_monsters)
elif wins == 4:
choose_monster(level_four_monsters)
else:
print "bug in choosing monsters over wins"
exit(0)
print """
Welcome %s to the Arena
Today you will be fighting a %s
Description of monster: %s
""" % (name, monster, description)
next()
running = True
while running:
if current_hp > 0 and monster_current_hp > 0:
prompt = raw_input("Type 'a' to attack, 's' for stats, 'q' for quit :> ")
if prompt == 'a':
hit_check('p')
hit_check('m')
elif current_hp <= 0:
break
print "You were killed by the %s, better luck next time."
exit()
elif monster_current_hp <= 0:
break
print "You defeated the %s! Great Job!"
next()
if wins == 0:
gold_earned = d6() + 2
elif wins == 1:
gold_earned = d6() + d6() + 2
elif wins == 2:
gold_earned = d6() + d6() + 4
elif wins == 3:
gold_earned = d6() + d6() + 5
elif wins == 4:
gold_earned = d6() + d6() + 6
else:
break
print "There is a bug you have wins than allowed"
exit(0)
gold = gold + gold_earned
print "You win %d gold, you have %d gold total." % (gold_earned,
gold)
wins = wins + 1
hit_points = hit_points + d6()
hit_points = current_hp
print "You feel hardier. You make your way back to the barracks."
next()
barracks()
else:
break
print "Bug in combat engine"
exit(0)
When I run this here is what the terminal prints, It's for some reason dumping to the inventory party of my code.
Welcome Ray to the Arena
Today you will be fighting a goblin
Description of monster: A tiny miserable creature that lives to eat shit.
Press Enter To Continue...
Type 'a' to attack, 's' for stats, 'q' for quit :> a
You missed the goblin.
Press Enter To Continue...
The goblin missed Ray.
Press Enter To Continue...
Type 'a' to attack, 's' for stats, 'q' for quit :> a
You wounded the goblin!
Press Enter To Continue...
The goblin wounded Ray.
Press Enter To Continue...
Your current weapon is now a dagger. Press Enter To Continue
logout
[Process completed]
Any help or advice as to how to tackle this issue would be greatly appreciated.
edit: Here is the whole code so people can get it to run.
# Imports, lots of imports,
from random import randint
from random import choice
import pprint
from sys import exit
#Setting some core stats
wins = 0
times_trained = 0
gold = randint(1, 3) + 2
#Some Quips for the barracks
def gladiator_quips():
q = []
q.append('A warrior grunts, "A sword is more versatile than other weapons."')
q.append('A rogue remarks "Oi I heard that training improves your primary skills."')
q.append('A wench stats "At least you can fight for your freedom %s."' % character_class)
q.append('A drunk sings you a song of the legend of Doobieus poorly.')
q.append('A guard remarks how his polearm gets more lucky hits')
q.append('A slave mentions that maces pack a heavy punch.')
q.append('A barkeep laments "I need a vacation."')
q.append('A one eyed gladiator recalls his youth before slavers killed his family.')
q.append('A child remarks how training can affect abilities.')
quips = choice(q)
print quips
#nice little function that brings up the next page prompt
def next():
raw_input("Press Enter To Continue...")
# Barracks need to restrict training after training. Also need to
# add training restrictions.
def barracks():
print """
Welcome to the barracks %s
^^^^ ^^^^^^^^^^^^^^^^
>----<|arena|training|>
~ MMM ~ <|shop<| _ | __ |>
{ } mmm ~~~ [~~~] { } mmm ~~~ <| <|{}\ | /{}\ |>
{ } |||D _______ [~~~] { } |||D _______ <| -||- | -||- |>
{ } ||| <uuuuuuu> [~~~] { } ||| <uuuuuuu> <| ||| | || |>
-------------------------------------------------------------------------
There are several other gladiators moving around, you may 'talk' to them.
You can take a look at your 'stats'
You can 'shop' for new weapons.
You may enroll in skill 'training' nearby.
You may face your next opponent in the 'arena'.
You may give up on your quest for freedom & 'quit'
""" % name
answer = raw_input(":> ")
if "talk" in answer:
gladiator_quips()
next()
barracks()
elif "stats" in answer:
pp = pprint.PrettyPrinter(indent=30)
pp.pprint(character_sheet)
next()
barracks()
elif "training" in answer:
if times_trained == 0:
train()
else:
print "The training center is now closed."
next()
barracks()
elif "arena" in answer:
combat_engine()
elif "quit" in answer:
print "You are now a slave forever. Goodbye %s." % name
exit(0)
elif "shop" in answer:
if wins == 0:
print "The shop is closed for the day, you must win your first fight"
next()
barracks()
elif wins == 1:
buy_weapon(level_one_weapons)
elif wins == 2:
buy_weapon(level_two_weapons)
elif wins == 3:
buy_weapon(level_three_weapons)
elif wins == 4:
buy_weapon(level_four_weapons)
else:
print "Ray left a bug somewhere. Ballz."
exit(0)
else:
print "I didn't understand %s, please try again." % answer
next()
barracks()
#training code
def train_code(stat):
if check != 1:
gold = gold - 7
character_sheet.remove(character_sheet[9])
character_sheet.insert(9, "You have %d gold pieces." % gold)
times_trained = 1
stat = stat + 1
if stat == str:
character_sheet.remove(character_sheet[3])
character_sheet.insert(3, "Strength: %s" % str)
elif stat == dex:
character_sheet.remove(character_sheet[4])
character_sheet.insert(3, "Dexterity: %s" % dex)
elif stat == con:
character_sheet.remove(character_sheet[5])
character_sheet.insert(3, "Constiution: %s" % cond)
else:
print "Ray left a stupid bug somewhere"
print "You feel stronger and return to the barracks as training closes."
next()
barracks()
else:
times_trained = 1
gold = gold - 7
character_sheet.remove(character_sheet[9])
character_sheet.insert(9, "You have %s gold pieces." % gold)
print "You feel like the training was useless. You return to the barracks as training closes."
next()
barracks()
# training room
def train():
global gold, str, dex, con
print """
Welcome %s to the training center.
You currently have %d gold pieces.
You may enroll in one class before each battle.
Keep in mind, there is a chance you will fail to learn anything.
Training costs 7 gold pieces.
You may train 'str', 'dex', or 'con'
Type 'quit' if you wish to return to the barracks.
Which stat do you wish to train?
""" % (name, gold)
answer = raw_input(":> ")
check = randint(1, 6)
if 'str' in answer and gold >= 7:
train_code(str)
elif 'dex' in answer and gold >= 7:
train_code(dex)
elif 'con' in answer and gold >= 7:
train_code(con)
elif 'quit' in answer:
print "You leave the training area."
next()
barracks()
else:
print """"You either dont have enough gold (%s gp,) or you typed in an error (%s)
""" % (gold, answer)
next()
train()
#dice
def d20():
return randint(1, 20)
def d100():
return randint(1, 100)
def d6():
return randint(1, 6)
# Doing Stuff for weapons and the shopkeeper. #################################
def level_zero_price():
"""Generates the price for level one weapons"""
return randint(1, 3)
def level_one_price():
"""Generates the price for level two weapons"""
return randint(3, 6)
def level_two_price():
"""Generates the price for level three weapons"""
return randint(6, 9)
def level_three_price():
"""Generates the price for level four weapons"""
return randint(9, 12)
def level_four_price():
"Generates the price for level four weapons"""
return randint(12, 15)
#weapon inventory code
def weapon_code(weapons):
global current_weapon
weapon_choice = raw_input(":> ")
if weapons[0] in weapon_choice and gold >= sword_price:
gold_math(agile_price)
if wins != 0:
character_sheet.remove(character_sheet[10])
else:
current_weapon = weapons[2]
inventory(weapons[2])
character_sheet.append("Current Weapon: %s" % current_weapon)
barracks()
elif weapons[1] in weapon_choice and gold >= blunt_price:
gold_math(agile_price)
if wins != 0:
character_sheet.remove(character_sheet[10])
else:
current_weapon = weapons[2]
inventory(weapons[2])
character_sheet.append("Current Weapon: %s" % current_weapon)
barracks()
elif weapons[2] in weapon_choice and gold >= agile_price:
gold_math(agile_price)
if wins != 0:
character_sheet.remove(character_sheet[10])
else:
current_weapon = weapons[2]
inventory(weapons[2])
character_sheet.append("Current Weapon: %s" % current_weapon)
barracks()
elif "quit" in weapon_choice and wins != 0:
barracks()
elif "quit" in weapon_choice and wins == 0:
print "You must buy a weapon first before you can go to the barracks."
next()
buy_weapon(level_zero_weapons)
else:
print "Either you dont have enough money, or I dont know what %s means" % weapon_choice
next()
buy_weapon(weapons)
# price display
def prices(weapons):
print """
Please type in the weapon you want to buy.
%s, price: %d gold pieces
%s, price: %d gold pieces
%s, price: %d gold pieces.
""" % (weapons[0], sword_price, weapons[1], blunt_price,weapons[2],
agile_price)
# gold buying
def gold_math(weapon_price):
global gold
character_sheet.remove(character_sheet[9])
gold = gold - weapon_price
character_sheet.insert(9, "You have %s gold pieces." % gold)
### Shop / buy weapons room ###############
def buy_weapon(weapons):
global gold, sword_price, blunt_price, agile_price, current_weapon
"""big bit of code that allows you to buy a weapons from a weapon list.
The function acts a little differently after level zero weapons"""
global current_weapon
if weapons == level_zero_weapons:
sword_price = level_zero_price()
blunt_price = level_zero_price()
agile_price = level_zero_price()
prices(level_zero_weapons)
weapon_code(level_zero_weapons)
elif weapons == level_one_weapons:
sword_price = level_one_price()
blunt_price = level_one_price()
agile_price = level_one_price()
prices(level_one_weapons)
weapon_code(level_one_weapons)
elif weapons == level_two_weapons:
sword_price = level_two_price()
blunt_price = level_two_price()
agile_price = level_two_price()
prices(level_two_weapons)
weapon_code(level_two_weapons)
elif weapons == level_three_weapons:
sword_price = level_three_price()
blunt_price = level_three_price()
agile_price = level_three_price()
prices(level_three_weapons)
weapon_code(level_three_weapons)
elif weapons == level_four_weapons:
sword_price = level_four_price()
blunt_price = level_four_price()
agile_price = level_four_price()
prices(level_four_weapons)
weapon_code(level_four_weapons)
else:
print"~~~There is a bug somwhere, forgot to assign (weapons)\n\n\n"
raw_input("""
Your current weapon is now a %s. Press Enter To Continue
""" % current_weapon)
def inventory(current_weapon):
"""Attaches modifiers to secondary stats according to current weapon """
global mod_dmg, mod_crit
if current_weapon == level_zero_weapons[0]:
mod_dmg = dmg
mod_crit = crit
elif current_weapon == level_zero_weapons[1]:
mod_dmg = dmg + 1
mod_crit = crit
elif current_weapon == level_zero_weapons[2]:
mod_dmg = dmg
mod_crit = crit + 3
elif current_weapon == level_one_weapons[0]:
mod_dmg = dmg + 1
mod_crit = crit + 3
elif current_weapon == level_one_weapons[1]:
mod_dmg = dmg + 2
mod_crit = crit
elif current_weapon == level_one_weapons[2]:
mod_dmg = dmg
mod_crit = crit + 5
elif current_weapon == level_two_weapons[0]:
mod_dmg = dmg + 1
mod_crit = crit + 5
elif current_weapon == level_two_weapons[1]:
mod_dmg = dmg + 3
mod_crit = crit
elif current_weapon == level_two_weapons[2]:
mod_dmg = dmg
mod_dmg = crit + 6
elif current_weapon == level_three_weapons[0]:
mod_dmg = dmg + 2
mod_crit = crit + 5
elif current_weapon == level_three_weapons[1]:
mod_dmg = dmg + 4
mod_crit = crit + 3
elif current_weapon == level_three_weapons[2]:
mod_dmg = dmg + 1
mod_crit = + 8
elif current_weapon == level_four_weapons[0]:
mod_dmg = dmg + 3
mod_crit = crit + 7
elif current_weapon == level_four_weapons[1]:
mod_dmg = dmg + 5
mod_crit = crit + 5
elif current_weapon == level_four_weapons[2]:
mod_dmg = dmg + 2
mod_crit = crit + 10
else:
print"There is a bug, ray forgot a weapon or typed shit wrong."
exit(0)
#End Of Buying / Inventory functions ##########################################
#function for monster damage
def monster_dice(a, b):
return randint(a, b)
#Function for monster stats
def monster_stats(a, b, c, d):
global monster_current_hp, monster_crit, monster_dmg, monster_to_hit
monster_current_hp = a
monster_crit = b
monster_dmg = monster_dice(1, c)
monster_to_hit = d
# Chooses a random monster and sets stats
def choose_monster(monster_list):
global monster, description
if monster_list == level_zero_monsters:
monster = choice(level_zero_monsters)
if monster == 'wolf':
monster_stats(4, 5, 6, 12)
description = "A small and angry dog like creature."
elif monster == 'goblin':
monster_stats(5, 7, 5, 10)
description = "A tiny miserable creature that lives to eat shit."
elif monster == 'kobold':
monster_stats(6, 10, 4, 9)
description = "A small humaniod lizard, very sneaky and annoying"
else:
print "Bug in choose monster level 0"
exit(0)
elif monster_list == level_one_monsters:
monster = choice(level_one_monsters)
if monster == 'orc':
monster_stats(6, 8, 6, 10)
description = "A human sized horrid creature, smells awful."
elif monster == 'gnoll':
monster_stats(7, 10, 8, 12)
description = "A large humanoid dog, they can cackle for hours."
elif monster == 'giant ant':
monster_stats(8, 7, 7, 11)
description = "A large and terrifying insect, it makes clicking noises."
else:
print "Bug in choose monster level 1"
exit(0)
elif monster_list == level_two_monsters:
enemy = choice(level_two_monsters)
if monster == 'wight':
monster_stats(9, 10, 10, 12)
description = "A powerful undead warrior, terrifying in size."
elif monster == 'komodo dragon':
monster_stats(7, 12, 8, 10)
description = "A deadly man sized lizard, very sharp teeth."
elif monster == 'ogre':
monster_stats(10, 5, 12, 11)
description = "A Big and strong stupid ogre."
else:
print "Bug in monster level 2"
elif monster_list == level_three_weapons:
monster = choice(level_three_monsters)
if monster == 'troll':
monster_stats(12, 7, 12, 11)
elif monster == 'owlbear':
monster_stats(10, 12, 11, 10)
elif monster == 'dark priest':
monster_stats(9, 13, 10, 9)
else:
print "Bug in monster level 3"
elif monster_list == level_four_monsters:
monster = choice(level_four_monsters)
if monster == 'dark wizard':
monster_stats(11, 15, 12, 9)
elif monster == 'hydra':
monster_stats(12, 14, 15, 10)
elif monster == 'stone golem':
monster_stats(15, 13, 13, 11)
else:
print "Problem with monster level 4"
else:
print "Ray left diddnt assign a correct combat(argv)"
exit(0)
#Check to hit and applies damage / crit + damage use p for player and m for monster
def hit_check(x):
global current_hp, monster_current_hp, to_hit, monster_to_hit, crit
global monster_crit, dmg, monster, monster_dmg
if x == 'p':
if d20() >= to_hit and d100() <= crit:
monster_current_hp = monster_current_hp - dmg * 3
print "You critically wounded the %s!" % monster
next()
elif d20() >= to_hit and d100() > crit:
monster_current_hp = monster_current_hp - dmg
print "You wounded the %s!" % monster
next()
else:
print "You missed the %s." % monster
next()
elif x == 'm':
if d20() >= monster_to_hit and d100() <= monster_crit:
current_hp = current_hp - monster_dmg * 3
print "The %s critically wonded %s!" % (monster, name)
next()
elif d20() >= to_hit and d100() > crit:
current_hp = current_hp - dmg
print "The %s wounded %s." % (monster, name)
next()
else:
print "The %s missed %s." % (monster, name)
next()
else:
print "Ray diddnt correctly assign a hit check"
exit(0)
# Combat engine / prompt
def combat_engine():
global current_hp, monster_current_hp, wins, gold, hit_points, p, m
"""Will choose a monster, and then allow the player to fight monster"""
global current_hp, monster_current_hp, prompt
if wins == 0:
choose_monster(level_zero_monsters)
elif wins == 1:
choose_monster(level_one_monsters)
elif wins == 2:
choose_monster(level_two_monsters)
elif wins == 3:
choose_monster(level_three_monsters)
elif wins == 4:
choose_monster(level_four_monsters)
else:
print "bug in choosing monsters over wins"
exit(0)
print """
Welcome %s to the Arena
Today you will be fighting a %s
Description of monster: %s
""" % (name, monster, description)
next()
running = True
while running:
if current_hp > 0 and monster_current_hp > 0:
prompt = raw_input("Type 'a' to attack, 's' for stats, 'q' for quit :> ")
if prompt == 'a':
hit_check('p')
hit_check('m')
elif current_hp <= 0:
break
print "You were killed by the %s, better luck next time."
exit()
elif monster_current_hp <= 0:
break
print "You defeated the %s! Great Job!"
next()
if wins == 0:
gold_earned = d6() + 2
elif wins == 1:
gold_earned = d6() + d6() + 2
elif wins == 2:
gold_earned = d6() + d6() + 4
elif wins == 3:
gold_earned = d6() + d6() + 5
elif wins == 4:
gold_earned = d6() + d6() + 6
else:
break
print "There is a bug you have wins than allowed"
exit(0)
gold = gold + gold_earned
print "You win %d gold, you have %d gold total." % (gold_earned,
gold)
wins = wins + 1
hit_points = hit_points + d6()
hit_points = current_hp
print "You feel hardier. You make your way back to the barracks."
next()
barracks()
else:
break
print "Bug in combat engine"
exit(0)
def you_win():
print """
YOU WIN!
CONGRATULATIONS!
THANKS FOR PLAYING!
"""
# Monster List
level_zero_monsters = ['wolf', 'goblin', 'kobold']
level_one_monsters = ['orc', 'gnoll', 'giant ant',]
level_two_monsters = ['wight', 'komodo dragon', 'ogre']
level_three_monsters = ['troll', 'owlbear', 'dark priest']
level_four_monsters = ['dark wizard', 'hydra', 'stone golem']
# Weapon lists
level_zero_weapons = ['short sword', 'club', 'dagger']
level_one_weapons = ['sword', 'mace', 'rapier']
level_two_weapons = ['long sword', 'morningstar', 'trident']
level_three_weapons = ['claymore', 'flail', 'sycthe']
level_four_weapons = ['bastard sword', 'dragon bone', 'crystal halbred']
def roll_3d6():
"""This rolls 3D6, and returns the sum."""
return randint(1, 6) + randint(1, 6) + randint(1, 6)
def character_gen():
"""Creates A character and also can call character sheet"""
global name, str, dex, con, hit_points, dmg, crit, character_class
global gender, damage_print, current_hp, character_sheet, to_hit
character_sheet = []
name = raw_input("Please tell me your name brave soul. :> ")
print "\n\t\tLets now randomly generate brave gladiator %s." % name
str = roll_3d6()
if str > 12:
dmg = randint(1, 6) + 1
damage_print = "1D6 + 1"
else:
dmg = randint(1, 6)
damage_print = "1D6"
dex = roll_3d6()
if dex >= 13:
crit = 15
to_hit = 9
elif dex >= 9 and dex <=12:
crit = 10
to_hit = 10
else:
crit = 10
to_hit = 11
con = roll_3d6()
if con > 14:
hit_points = 8
current_hp = hit_points
else:
hit_points = 6
current_hp = hit_points
if str >= dex:
character_class = "Warrior"
else:
character_class = "Rogue"
random_gender = randint(1, 2)
if random_gender == 1:
gender = "Male"
else:
gender = "Female"
character_sheet.append("Name: %s:" % name)
character_sheet.append("Gender: %s" % gender)
character_sheet.append("Character Class: %s" % character_class)
character_sheet.append("Strength: %s" % str)
character_sheet.append("Dexterity: %s" % dex)
character_sheet.append("Constitution: %s" % con)
character_sheet.append("Damage %s" % damage_print)
character_sheet.append("Crit Chance {}%".format(crit))
character_sheet.append("Hit Points: %s/%s" % (hit_points, current_hp))
character_sheet.append("You have %s gold pieces." % gold)
pp = pprint.PrettyPrinter(indent=30)
pp.pprint(character_sheet)
raw_input("Please Press Enter To Buy A Weapon")
buy_weapon(level_zero_weapons)
#main
character_gen()
Here's a rundown of the flow of your program:
character_gen calls buy_weapon, which calls weapon_code, which calls barracks, which calls combat_engine. Inside combat_engine, once you've reduced the enemy's health to zero or below, it executes the second elif branch, whose first statement is break. This statement causes combat_engine's while loop to terminate. combat_engine ends, so control returns to barracks. barracks ends, so control returns to weapon_code. weapon_code ends, so control returns to buy_weapon. buy_weapon executes whatever code occurs after your call to weapon_code, namely this line:
raw_input("""
Your current weapon is now a %s. Press Enter To Continue
""" % current_weapon)
buy_weapon ends and control returns to character_gen. character_gen ends and control returns to the main module. The main module ends, and your program terminates. This explains why you're getting the output that you're getting.
As for fixing it, I'd suggest two things:
Read up on break to confirm that it's doing what you think it's doing. Anything after break, for example print "You defeated the %s! Great Job!" will never execute under any circumstance.
For the overall flow of your code, look up State Machines. Rather than being functions, barracks/inventory/etc should each be their own state, with the user's input dictating which state to transition into. The way you've got it now, you'll experience a stack overflow after about 500 actions.

Categories