python integrating code with raw_input timeout - python

This is most of my code for my now working python blackjack game (or at least blackjack like game) I have now been told that I need to implement a time limit (user gets asked to input something and only has 3 or so seconds to give a response).
def deck():
cards = range(1, 12)
return choice(cards)
def dealer():
total = deck() + deck()
if total <= 15:
totalf = total + deck()
while totalf <= 21:
return totalf
if total > 15:
return total
def player():
card1 = deck()
card2 = deck()
hand = card1 + card2
print "Cards dealt: %d and %d" % (card1, card2)
while hand <= 21:
choice = raw_input("Would you like to hit or stand?: ")
print choice
if choice == "hit":
hand = hand + deck()
print "Current Total: %d" % hand
elif choice == "stand":
return hand
money = 100
highscore = 0
while money > 0:
opp = dealer()
me = player()
if me > opp:
highscore = highscore + 10
money = money + 10
print "Winner, winner, chicken dinner! You have $%d!" % money
print "********************************************"
elif opp > 21:
highscore = highscore + 10
money = money + 10
print "Winner, winner, chicken dinner! You have $%d!" % money
print "********************************************"
elif me > 21:
money = money - 20
print "Bust! Dealer wins with %d. You have $%d reamaining." % (opp, money)
print "********************************************"
elif opp > me:
money = money - 20
print "Dealer wins with %d. You have $%d reamaining." % (opp, money)
print "********************************************"
elif me == 21:
highscore = highscore + 10
money = money + 10
print "Blackjack! You have $%d!" % money
print "********************************************"
sleep(1)
print "Thank you for playing! Your highscore was $%d." % highscore
This is the code my professor has provided us with to do this:
import sys, time
from select import select
import platform
if platform.system() == "Windows":
import msvcrt
def input_with_timeout_sane(prompt, timeout, default):
"""Read an input from the user or timeout"""
print prompt,
sys.stdout.flush()
rlist, _, _ = select([sys.stdin], [], [], timeout)
if rlist:
s = sys.stdin.readline().replace('\n','')
else:
s = default
print s
return s
def input_with_timeout_windows(prompt, timeout, default):
start_time = time.time()
print prompt,
sys.stdout.flush()
input = ''
while True:
if msvcrt.kbhit():
chr = msvcrt.getche()
if ord(chr) == 13: # enter_key
break
elif ord(chr) >= 32: #space_char
input += chr
if len(input) == 0 and (time.time() - start_time) > timeout:
break
if len(input) > 0:
return input
else:
return default
def input_with_timeout(prompt, timeout, default=''):
if platform.system() == "Windows":
return input_with_timeout_windows(prompt, timeout, default)
else:
return input_with_timeout_sane(prompt, timeout, default)
I am completely lost how to merge these two pieces of code. I've tried for the past couple hours to get it to work but for whatever reason its just not working. Any help would be amazing. (I apologize for the wall of code).

You just need to call input_with_timeout function where you want the user's input.
In your player function:
def player():
card1 = deck()
card2 = deck()
hand = card1 + card2
print "Cards dealt: %d and %d" % (card1, card2)
while hand <= 21:
choice = input_with_timeout("Would you like to hit or stand?: ", 3, "stand")
print choice
if choice == "hit":
hand = hand + deck()
print "Current Total: %d" % hand
elif choice == "stand":
return hand
will prompt for an input, writing the "Would ... or stand" sentence before it. If the user do not answer before the timeout (in this case 3 second) the function will return "stand".
And be sure to include your professor's code in your main file.

Related

Python: CARD GAME BOT - Remastering (How do you make a line continue regardless of where it is?)

I'm remastering the bot by my self and I'm stuck! This is a code which prompts the user to select how many cards they get from the options of
7, 9, 11, and 15
def Cards():
print("Card Amounts")
print("\nChoices")
print(7)
print(9)
print(11)
print(15)
PlayerInput3()
def PlayerInput3():
global PlayersCards
PlayerInput = int(raw_input())
if(PlayerInput == 7):
PlayersCards == range(1,7)
print("Lets get started")
Game()
But when they choose how many cards they want it does stay into affect after the definition is over. I want the Players card range to continue in a different defined area. Here:
def Game():
global roundNumber, MyDeck, PlayersCards
import random
Select = PlayersCards
roundNumber = roundNumber + 1
print("Round %d!") % (roundNumber)
if(roundNumber == 1) or (roundNumber < 15):
PlayersCards = random.randint(1, 50)
MyDeck.append(PlayersCards)
print("Here are your cards")
print(MyDeck)
print("Select a card")
But It wont continue on past the
def Cards():
How Can I make it so that the PlayersCard == range(1,7) Continues on regardless of what definition it is in?
I think this code works as you require:
def instructions():
print("You will be playing with an ai and whoever lays down the highest number wins that round.")
print("The points you get are determined by how much higher your card was from your opponents card.")
print("The person with the most points wins!")
def getUserInput():
global roundNumber, My_Deck, PlayerPoints, AIPoints
My_Deck = []
roundNumber = 0
AIPoints = 0
PlayerPoints = 0
print ("\nDo you want to play?: ")
print("\nChoices")
print("1. Yes")
print("2. No\n")
Choice = input()
if(Choice == 'Yes') or (Choice == 'yes'):
print("\nOkay, lets get started!")
startGame()
elif(Choice in ['No', 'no']):
print("Okay, bye!")
quit()
else:
print("That is not a Choice!")
print("Choose 'Yes' or 'No'")
getUserInput()
def startGame():
global roundNumber, My_Deck, PlayerPoints, AIPoints
print("\nAIPoints = %d PlayerPoints = %d" % (AIPoints, PlayerPoints))
roundNumber = roundNumber + 1
print("\nRound %d!" % (roundNumber))
cardChoosen = None
import random
if(roundNumber == 1):
print("\nHere are your 9 cards.\n")
for Cards in range(9):
Cards = random.randint(1, 100)
My_Deck.append(Cards)
while True:
print("Select one of your cards: "),
print(My_Deck)
Select = int(input())
try:
if (Select in My_Deck):
My_Deck.remove(Select)
print("You choose", Select)
print("Your deck now is:")
print(My_Deck)
cardChoosen = Select
break
else:
print("You don't have that card in your deck!")
except ValueError as e:
print(e)
elif(roundNumber == 10):
if(PlayerPoints > AIPoints):
print("\nCongratulations you won with a score of %d compared to the AI's %d" % (PlayerPoints, AIPoints))
getUserInput()
elif(PlayerPoints < AIPoints):
print("\nUnfortunately you lost with a score of %d compared to the AI's %d" % (PlayerPoints, AIPoints))
getUserInput()
else:
print("\nWow this is basicaly impossible you tied with the AI with you both ahving a score of %d and %d... " % (PlayerPoints, AIPoints))
getUserInput()
else:
print("\nHere are your %d cards.\n" % (9 - roundNumber + 1))
while True:
print("Select one of your cards: "),
print(My_Deck)
Select = int(input())
try:
if (Select in My_Deck):
My_Deck.remove(Select)
print("You choose", Select)
print("Your deck now is:")
print(My_Deck)
cardChoosen = Select
break
else:
print("You don't have that card in your deck!")
except ValueError as e:
print(e)
AINumber = random.randint(1, 100)
if(cardChoosen > AINumber):
print("\nYou won! Your number %d was higher than the AI's number %d" % (cardChoosen, AINumber))
print("\nYou scored %d points" % (cardChoosen - AINumber))
PlayerPoints = PlayerPoints + (cardChoosen - AINumber)
startGame()
elif(cardChoosen < AINumber):
print("\nYou Lost! Your number %d was lower than the AI's number %d" % (cardChoosen, AINumber))
print("\nAI scored %d points" % (AINumber - cardChoosen))
AIPoints = AIPoints + (AINumber - cardChoosen)
startGame()
else:
print("\nYou tied with the AI! Your number %d was the same as the AI's number %d" % (cardChoosen, AINumber))
print("\nNobody scored points!")
startGame()
My_Deck = []
roundNumber = 0
AIPoints = 0
PlayerPoints = 0
instructions()
getUserInput()

Looping and ignoring flag - Python

I am working on learning python and decided to write a small battle engine to use a few of the different items I have learned to make something a bit more complicated. The problem I am having is that I set a selection that the user makes that should cause one of either two parts to load, but instead it skips to my loop instead of performing the selection. Here is what I have so far:
import time
import random
import sys
player_health = 100
enemy_health = random.randint(50, 110)
def monster_damage():
mon_dmg = random.randint(5,25)
enemy_health - mon_dmg
print ('You hit the beast for ' + str(mon_dmg) + ' damage! Which brings its health to ' + str(enemy_health))
player_dmg()
def player_dmg():
pla_dmg = random.randint(5,15)
player_health - pla_dmg
print ('The beast strikes out for ' + str(pla_dmg) + ' damage to you. This leaves you with ' + str(player_health))
def run_away():
run_chance = random.randint(1,10)
if run_chance > 5:
print ('You escape the beast!')
time.sleep(10)
sys.exit
else:
print ('You try to run and fail!')
player_dmg()
def player_turn():
print ('Your Turn:')
print ('Your Health: ' + str(player_health) + ' Monsters Health: ' + str(enemy_health))
print ('What is your next action?')
print ('Please Select 1 to attack or 2 to run.')
action = input()
if action == 1:
monster_damage()
elif action == 2:
run_away()
while player_health > 0 and enemy_health > 0:
player_turn()
if player_health <= 0:
print ('The beast has vanquished you!')
time.sleep(10)
sys.exit
elif enemy_health <= 0:
print ('You have vanquished the beast and saved our Chimichongas')
time.sleep(10)
sys.exit
The function input returns a str not an int
action = input()
So this comparison will always return False
if action == 1:
For example
>>> '1' == 1
False
You can convert their input to an int as follows
action = int(input())

Python game not working(shop only showing up once) [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm trying to make just a simple text game before I go on learning more things, the first part went good, then I tried to add a shop and when the code is run the shop can only be entered once. Here is the code
money = 100
entertainment = 30
rest = 15
social = 30
inv = 1
food = 30
score = 1
def commands():
print "Commands:"
print " 'P' Print commands options"
print " 'S' Go to the shop"
print "Job list? "
print " 'M' Market"
print " 'F' Farm"
print " 'H' Stay at home a rest"
print " 'E' Entertainment/go to fair"
def shop():
print "Shop:"
print " This is the shop, you buy things with your money that you gain"
print "Press 'I' for a potato! This gives you 20 extra Inventory points! Costs 80 money!"
print "Press 'R' for a better bed! This gives you 20 extra rest points! Costs 80 money!"
print "Press 'S' for a texting plan! This gives you 20 extra social points! Costs 80 money!"
print "Press 'E' for a better tv! This gives you 20 extra entertainment points! Costs 80 money!"
print "Press 'H' for this list again!"
print "Press 'L' to return to your game!"
import random
import sys
commands()
def do_farm():
entertainment = entertainment - random.randrange(1,7+1)
rest = rest - random.randrange(1,7+1)
social = social - random.randrange(1,10+1)
food = food + random.randrange(1,7+1)
inv = inv + random.randrange(1,30+1)
money = money - random.randrange(1,10+1)
score = score + 1
print "Money = %d, Entertainment = %d, Rest = %d, Social = %d, Inventory %d, Food %d, Score %d" % (money, entertainment, rest, social, inv, food, score)
if money <= 0:
print "Game over, Score: %d" % (score)
exit()
elif food <= 0:
print "Game over, Score: %d" % (score)
exit()
elif social <= 0:
print "Game over, Score: %d" % (score)
exit()
elif entertainment <= 0:
print "Game over, Score: %d" % (score)
exit()
elif rest <= 0:
print "Game over, Score: %d" % (score)
exit()
def do_home():
entertainment = entertainment + random.randrange(1,3+1)
rest = rest + random.randrange(1,7+1)
social = social + random.randrange(1,5+1)
food = food - 5
money = money - random.randrange(1,10+1)
score = score + 1
print "Money = %d, Entertainment = %d, Rest = %d, Social = %d, Inventory %d, Food %d, Score %d" % (money, entertainment, rest, social, inv, food, score)
if money <= 0:
print "Game over, Score: %d" % (score)
exit()
elif food <= 0:
print "Game over, Score: %d" % (score)
exit()
elif social <= 0:
print "Game over, Score: %d" % (score)
exit()
elif entertainment <= 0:
print "Game over, Score: %d" % (score)
exit()
elif rest <= 0:
print "Game over, Score: %d" % (score)
exit()
def do_ent():
entertainment = entertainment + random.randrange(1,7+1)
social = social + random.randrange(1,5+1)
food = food - 3
money = money - random.randrange(1,10+1)
score = score + 1
print "Money = %d, Entertainment = %d, Rest = %d, Social = %d, Inventory %d, Food %d, Score %d" % (money, entertainment, rest, social, inv, food, score)
if money <= 0:
print "Game over, Score: %d" % (score)
exit()
elif food <= 0:
print "Game over, Score: %d" % (score)
exit()
elif social <= 0:
print "Game over, Score: %d" % (score)
exit()
elif entertainment <= 0:
print "Game over, Score: %d" % (score)
exit()
elif rest <= 0:
print "Game over, Score: %d" % (score)
exit()
def do_market():
entertainment = entertainment - random.randrange(1,7+1)
rest = rest - random.randrange(1,7+1)
social = social + random.randrange(1,5+1)
food = food - 5
money = (inv * 1.5) + money
inv = 1
score = score + 1
print "Money = %d, Entertainment = %d, Rest = %d, Social = %d, Inventory %d, Food %d, Score %d" % (money, entertainment, rest, social, inv, food, score)
if money <= 0:
print "Game over, Score: %d" % (score)
exit()
elif food <= 0:
print "Game over, Score: %d" % (score)
exit()
elif social <= 0:
print "Game over, Score: %d" % (score)
exit()
elif entertainment <= 0:
print "Game over, Score: %d" % (score)
exit()
elif rest <= 0:
print "Game over, Score: %d" % (score)
exit()
def do_shop_inventory():
score = score + 10
inv = inv + 20
money = money - 80
def do_shop_rest():
score = score + 10
rest = rest + 20
money = money - 80
def do_shop_social():
score = score + 10
social = social + 20
money = money - 80
def do_shop_ent():
score = score + 10
entertainment = entertainment + 20
money = money - 80
def shop_commands():
while True:
shop()
shop_choice = raw_input("Shop command: ")
if shop_choice == "I":
do_shop_inventory()
elif shop_choice == "R":
do_shop_rest()
elif shop_choice == "S":
do_shop_social()
elif shop_choice == "E":
do_shop_ent()
elif shop_choice == "H":
shop()
elif shop_choice == "L":
break
choice = raw_input("Your command: ")
while choice != "Q":
if choice == "F":
do_farm()
elif choice == "H":
do_home()
elif choice == "E":
do_ent()
elif choice == "M":
do_market()
elif choice == "S":
shop_commands()
commands()
choice = raw_input("Your command: ")
I am fairly new with Python, about 2-4 weeks. So please no complex answers if possible:D
I would like to know what is wrong and an idea of how to fix it.
Thanks:D
P.S. if you want to suggest an idea that could be added you could do that to!
EDIT:
Changed code, new error
Traceback (most recent call last):
File "C:\Users\ImGone\Desktop\MoneySurvival_bakcup.py", line 173, in <module>
do_farm()
File "C:\Users\ImGone\Desktop\MoneySurvival_bakcup.py", line 46, in do_farm
entertainment = entertainment - random.randrange(1,7+1)
UnboundLocalError: local variable 'entertainment' referenced before assignment
You never clear out shop_choice, so the next time someone tries to go to the shop, they instantly leave it (because shop_choice is already set to L from the previous time they visited and then left the shop).
In addition to the problem Amber found, you've got some indentation problems that will make it hard to get to the store.
The shop == "P" check is inside the rest <= 0 case inside the choice == "F" case. So, the only way to get to the shop is to go to the farm and use up all your rest. That can't be right.
This would be a lot simpler if you factored out your code into functions, like this:
def do_farm():
entertainment = entertainment - random.randrange(1,7+1)
# ...
And then your main loop could just do this:
if choice == "F":
do_farm()
elif choice == "S":
do_shop()
# ...
Also, it's a lot easier to get the loop right if you do things the other way around, asking for the choice at the top of the loop instead of the bottom. For example:
def shop():
while True:
shop()
shop_choice = raw_input("Shop command: ")
if shop_choice == "I":
do_shop_inventory()
elif shop_choice == "R":
# ...
elif shop_choice == "L":
break
It is a bit annoying that you have to do a while True and a break instead of putting the condition directly in the loop, but the alternative is to write the same input code twice (once before the loop, and once again at the end) instead of once (at the top of the loop), or write convoluted code that can handle a "no input yet" state.

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!")

how to get out of my game while game ending conditions are not met?

this is my first attempt at python coding, or any coding for that matter.
I have made this simple little game, and it seems to be running fine but I want to add another option to it.
the code generate a random character with HP, attack power, XP and level, then generates a dragon with HP and attack power, the game then decides each time who strikes, and if the player wins he gets to get some Xp and level up, if the dragon wins the player is dead and it asks you to play again.
what I want to add is what if I'm in the middle of a fight, and don't want to continue, I want ask the user if they want to continue fighting, if not the game ends.
I've tried to do that but I failed.
Also , if there is anything I can do to enhance my code.
thanks in advance.
import random
def charGen():
char = [random.randint(1,10),random.randint(1,3), 0, 0]#[hp, power,xp,level]
return char
def drgnGen():
drgn = [random.randint(1,5),random.randint(1,5)]
return drgn
def playAgain():
print('do you want to play again?(y)es or no')
return input().lower().startswith('y')
def xpValues(levels):
for i in range(levels):
n=0
n=((i+2)**2)
xpLevels.append(n)
def xpIncrement(XP,xpLevels,char):
#returns the level of the character( the bracket in which the character XP level lies within)
#level = char[3]
for i in range(len(xpLevels)):
if XP>= xpLevels[i] and XP<xpLevels[i+1]:
#level = i+1
return i
def levelUp(char,level):
if level+1>char[3]:
char[0] += 1
char[3] += 1
print ('you are now at level %s!, your health now is %s points'%((level+1),char[0]))
def isNotDead(char):
if char[0]>0:
return True
else:
return False
while True:
XP = 5 #the default XP gain after battle win
char = charGen() #generate the character
xpLevels=[]
xpValues(15)
print (xpLevels)
print ('______________________________________')
print ('Welcome to the Battle of the dragons!')
print ("you are a fierce Warrior with %s health points and A power of %s points" %(char[0],char[1]))
print ('------------------------------------------------------------------------')
while isNotDead(char):
print(' ')
print ('While adventuring you have met a scary looking dragon')
print('Without hesitation you jump to fight it off!')
print('=============================================')
print(' ')
drgn = drgnGen() #generate a dragon
while True:
roll = random.randint(0,1)
if roll == 0:
print("the dragon hits you for %s points" %drgn[1])
char[0] = char[0] - drgn[1]
if isNotDead(char) :
print("you have %s health left!" %char[0])
input('Press Enter to continue')
print(' ')
else:
print("you're dead!Game Over")
print(' ')
break
else:
print("you hit the dragon for %s points"%char[1])
drgn[0] = drgn[0] - char[1]
if drgn[0] >0:
print("the dragon have %s health left!" %drgn[0])
input('Press Enter to continue')
print(' ')
else:
char[2]+= XP
print("Horaay!you have killed the dragon!and your experience points are now %s"%char[2])
levelUp(char,(xpIncrement(char[2],xpLevels,char)))
input('Press Enter to continue')
break
if not playAgain():
break
A quick fix to get what you want is to have a couple of flags marking whether the user is fighting or not. Also you can delay printing output until the end of the innermost loop, to avoid having to repeat too much printing:
new_dragon = True
while new_dragon:
print(' ')
print ('While adventuring you have met a scary looking dragon')
print('Without hesitation you jump to fight it off!')
print('=============================================')
print(' ')
drgn = drgnGen() #generate a dragon
fighting = True
while fighting:
message = []
roll = random.randint(0,1)
if roll == 0:
message.append("the dragon hits you for %s points" %drgn[1])
char[0] = char[0] - drgn[1]
if isNotDead(char) :
message.append("you have %s health left!" %char[0])
else:
message.append("you're dead!Game Over")
fighting = False
new_dragon = False
else:
message.append("you hit the dragon for %s points"%char[1])
drgn[0] = drgn[0] - char[1]
if drgn[0] >0:
message.append("the dragon have %s health left!" %drgn[0])
else:
char[2]+= XP
message.append("Horaay!you have killed the dragon!and your experience points are now %s"%char[2])
levelUp(char,(xpIncrement(char[2],xpLevels,char)))
continue_flag = False
for m in message:
print (m)
print ('')
if fighting:
r = input("Press enter to continue or enter q to quit")
if r is 'q':
fighting = False
To improve the code more generally:
make a Character class and classes for Player and Dragon that inherit shared properties from the Character class
the check for whether to level up can be greatly simplified by just comparing whether new_xp > xpLevels[previous_xp]
the programme will soon get over-complicated if you continue to expand it just using nested while loops. What you want is a single while loop, functions (or a class) for each stage/status of the game, variables that record the game's current status (e.g. any dragons present), and a condition that decides what to do next.
give things clear descriptive names, using classes, e.g. player.power instead of char[2]
E.g. the following...
import random
class Character:
def __init__(self, max_hp, max_power):
self.hp = random.randint(1, max_hp)
self.power = random.randint(1, max_power)
def is_dead(self):
return self.hp <= 0
def hit_by(self, enemy):
self.hp -= enemy.power
class Player(Character):
def __init__(self):
Character.__init__(self, max_hp=10, max_power=3)
self.xp = 0
self.level = 0
self.xp_thresholds = [(i + 2) ** 2 for i in range(15)]
def battle_win(self):
self.xp += battle_win_xp
if self.level < len(self.xp_thresholds) and self.xp > self.xp_thresholds[self.level + 1]:
self.level_up()
def level_up(self):
self.hp += 1
self.level += 1
print('you are now at level %s!, your health now is %s points' % (self.level + 1, self.hp))
def begin():
game.player = Player()
print('______________________________________')
print('Welcome to the Battle of the dragons!')
print("you are a fierce Warrior with %s health points and A power of %s points" %(game.player.hp, game.player.power))
print('------------------------------------------------------------------------')
def new_dragon():
print('While adventuring you have met a scary looking dragon')
print('Without hesitation you jump to fight it off!')
print('=============================================')
game.dragon = Character(5, 5)
def fight():
player, dragon = game.player, game.dragon
if random.randint(0, 1):
player.hit_by(dragon)
print("the dragon hits you for %s points" % dragon.power)
if player.is_dead():
print("you're dead! Game over")
return
else:
print("you have %s health left!" % player.hp)
else:
dragon.hit_by(player)
print("you hit the dragon for %s points" % player.power)
if dragon.is_dead():
print("Horaay!you have killed the dragon!and your experience points are now %s"%player.xp)
player.battle_win()
game.dragon = None
return
else:
print ("the dragon have %s health left!" %dragon.hp)
print "Press enter to continue (q to quit)"
if input() is 'q':
game.finished = True
def play_again():
print 'do you want to play again?(y)es or no'
if input().lower().startswith('y'):
game.__init__()
else:
game.finished = True
battle_win_xp = 5 #the default XP gain after battle win
class Game:
def __init__(self):
self.dragon = None
self.player = None
self.finished = False
game = Game()
while not game.finished:
if not game.player:
begin()
elif game.player.is_dead():
play_again()
elif not game.dragon:
new_dragon()
else:
fight()

Categories