Python Pokemon Battle - pokemon attack twice in one turn - python-2.7

I'm sorta new to python. I'm trying to make a pokemon battle. But i can't seem to figure out why whenever you attack and the enemy attacks, they attack twice. It should work like this:
*battle starts
*you attack enemy
*enemy attacks you
*one of you faints
import time
import random
# pokemon beginning battle
print "mewtwo has appeared"
time.sleep(1)
print "lvl 70"
time.sleep(0.5)
print "HP 128"
print " \n "
# Mewtwo stats
mewtwo_HP = 128
mewtwo_atk = 20
mewtwo_atk2 = 45
move = random.randrange(-1, 1)
# Lapras stats
attack1 = ['hydro pump']
attack2 = ['ice beam']
lapras_HP = 100
attack1range = random.randrange(15,32)
attack2range = random.randrange(20, 25)
run = "you can't run away!"
pokemon = "Lapras"
# Lapras's turn
while True:
print "Lapras's moves:"
print "[ice beam][hydro pump]"
B = raw_input('> ').strip()
Battle = B
if Battle in attack1:
print "Lapras used Hydro pump!"
mewtwo_HP -= attack1range
time.sleep(0.5)
print "Mewtwo has", + mewtwo_HP, 'HP!'
if Battle in attack2:
print "Lapras used Ice beam!"
mewtwo_HP -= attack2range
time.sleep(0.5)
print "Mewtwo has", + mewtwo_HP, 'HP!'
# Mewtwo's turn
if move == 0:
lapras_HP -= random.randrange(21,27)
time.sleep(1)
print "Mewtwo used Psystrike!"
time.sleep(0.5)
print "Lapras has", + lapras_HP,'HP!'
else:
lapras_HP -= random.randrange(19, 35)
print "Mewtwo used Psywave!"
time.sleep(0.5)
print "Lapras has", + lapras_HP,'HP!'
if mewtwo_HP <= 0:
print "Mewtwo fainted!"
if lapras_HP <= 0:
print "Lapras fainted!"
print "you lose!"
And if you have any suggestions to make my code better that would be great (:

Related

How do I get my code to repeat itself if the desired input is not entered?

I just started python 2 weeks ago and I don't know how to make my code repeat itself when the input is something like "fox" when that is not one of the three options I'm accepting (horse, oxen, mule). Also if I want to total up the cost of 2 horse and say 3 mules by having it ask "do you want to buy any more animals", how would i do that? Any help would be very appreciated.
zoo = {}
def main():
print ("Animals available to purchase: " + "horse: 50, oxen: 35, mule: 20")
total_money = 1000
print ("You have " + str(total_money) + " to spend")
cost(total_money)
def animal_cost(total_money):
animal_type = raw_input("Please enter an animal:")
print ("Animal Type Entered: " + str(animal_type))
global animal_quantity
animal_quantity = int(raw_input("Please enter quantity of animals:"))
print ("Animal Quantity Entered: " + str(animal_quantity))
if animal_type in zoo:
zoo[animal_type] += animal_quantity
else: zoo[animal_type] = animal_quantity
while True:
if animal_type == 'horse':
return 50 * animal_quantity
if animal_type == 'oxen':
return 35 * animal_quantity
if animal_type == 'mule':
return 20 * animal_quantity
else:
cost(total_money)
def cost(total_money):
costing = animal_cost(total_money)
total_money -= costing
if total_money <= 0:
print ("No money left, resetting money to 1000.")
total_money = 1000
zoo.clear()
print ("Cost of Animals: " + str(costing))
print ("Remaining Balance:" + str(total_money))
choice = raw_input("Do you want to buy any more animals?(Y/N):")
if choice in('Y','y'):
cost(total_money)
elif choice in ('N','n'):
choice_2 = raw_input("Enter 'zoo' to see the animals you have purchased:")
if choice_2 in('zoo','Zoo'):
print zoo
choice_3 = raw_input("is everything correct?(Y/N):")
if choice_3 in ('Y','y'):
print ("Thank you for shopping!")
elif choice in ('N','n'):
print ("Restarting Transaction")
zoo.clear()
cost(total_money)
if __name__ == '__main__':
main()
You may try this enhanced version of your code:
zoo = {} # creating global dictionary for adding all animals into it.
# function to get animal cost
def animal_cost(total_money):
animal_type = raw_input("Please enter an animal:")
print ("Animal Type Entered: " + str(animal_type))
animal_quantity = int(raw_input("Please enter quantity of animals:"))
print ("Animal Quantity Entered: " + str(animal_quantity))
if animal_type in zoo:
zoo[animal_type] += animal_quantity
else: zoo[animal_type] = animal_quantity
if animal_type == 'horse':
return 50 * animal_quantity
if animal_type == 'oxen':
return 35 * animal_quantity
if animal_type == 'mule':
return 20 * animal_quantity
# getting total_money after animal purchase
def cost(total_money):
costing = animal_cost(total_money)
total_money = total_money - costing
if total_money <=0: # condition when money is less than or equal to 0.
print("No Money left, resetting money to 1000.")
total_money = 1000
print ("Cost of Animals:" + str(costing))
print ("Total Money Left:" + str(total_money))
# Recursion for buying more animals:
choice = raw_input("Do you want to buy any more animals?:")
if choice in ('Yes','y','Y','yes','YES'):
cost(total_money)
# you can use this commented elif condition if you want.
else: # elif choice in('no','No','n','N','NO'):
print("thankyou!!")
print("You have total animals: "+str(zoo))
# main function to initiate program
def main():
print ("Animals available to purchase: " + "horse, oxen, mule")
total_money = 1000
print ("You have " + str(total_money) + " to spend")
cost(total_money)
if __name__ == '__main__':
main()
This might help you out.
Have a look into this for last two lines

elif statement won't run in Python

This is my code. The last ELIF statement it keeps saying is wrong when ran from codeacademy labs - BATTLESHIP GAME EXERCISE!
from random import randint
board = []
#
# All code functions here
for x in range(0, 5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print_board(board)
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
# All game variables for row and col guessing
ship_row = random_row(board)
ship_col = random_col(board)
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
# Prints the variable chosen randomly
print ship_row
print ship_col
#
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sank my battleship!"
THIS STATEMENT. CODEACADEMY KEEPS SAYING IS WRONG EVEN THOUGH IT RUNS
WHAT'S WRONG WITH IT?
elif guess_row not in range(0, len(board)-1) or guess_col not in
range(0, len(board)-1):
print "Oops, that's not even in the ocean"
# final else statement. Prints missed battleship msg
# end of code
else:
print "You missed my battleship!" # msg lost game
board[guess_row][guess_col]="X" # shows guess var
print_board(board)
# end of code. Last else statement.
I don't know how did you even make it run since python is so picky with spaces.
maybe that's it but codecademy let you run it in their console for some reason, if you call the file with python installed on your pc it doesn't run.
from random import randint
board = []
# All code functions here
for x in range(0, 5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print_board(board)
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
# All game variables for row and col guessing
ship_row = random_row(board)
ship_col = random_col(board)
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
# Prints the variable chosen randomly
print ship_row
print ship_col
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sank my battleship!"
# THIS STATEMENT. CODEACADEMY KEEPS SAYING IS WRONG EVEN THOUGH IT
# RUNS
# WHAT'S WRONG WITH IT?
elif guess_row != (0, len(board)-1) or guess_col != range(0, len(board)-1):
print "Oops, that's not even in the ocean"

Python 2: global variable being changed in a function isn't updating to the new value

Sorry if the title is confusing. And if I'm using the wrong terms. I just started coding last week.
I'm writing a dice roll function for the boss battle of a text adventure game and while I can get the the dice function to use the original global variable outside the function, subtract a number and report it within the function, it doesn't update the global variable after the function runs. So the next time I try to call the function, it uses the original value again, which completely defeats the purpose of having the dice there in the first place. (You can't ever kill the boss, lol)
Here's what I've been playing with trying to debug. Thanks in advance!
player = "Dib"
playerhealth = 3
boss = "Zim"
bosshealth = 5
import random
def dice(who, whohealth):
min = 1
max = 3
dice = random.randint(min, max)
if dice == 1:
print "Your opponent lost no health"
print "Your opponent has %d health" % whohealth
elif dice == 2:
print "%s hits" % who
whohealth = whohealth - 1
print "Your opponent lost 1 health"
print "Your opponent has %d health" % whohealth
elif dice == 3:
print "%s crits" % who
whohealth = whohealth - 2
print "Your opponent lost 2 health"
print "Your opponent has %d health" % whohealth
else:
print "stuff"
dice(player, bosshealth)
dice(player, bosshealth)
dice(boss, playerhealth)
dice(boss, playerhealth)
You never returned whohealth back; Python passes objects by reference, but you are rebinding the reference in the function:
whohealth = whohealth - 1
That assigns a new value only to the local name whohealth; the original reference is not updated.
The best way to deal with this is by returning the new value:
def dice(who, whohealth):
min = 1
max = 3
dice = random.randint(min, max)
if dice == 1:
print "Your opponent lost no health"
print "Your opponent has %d health" % whohealth
elif dice == 2:
print "%s hits" % who
whohealth = whohealth - 1
print "Your opponent lost 1 health"
print "Your opponent has %d health" % whohealth
elif dice == 3:
print "%s crits" % who
whohealth = whohealth - 2
print "Your opponent lost 2 health"
print "Your opponent has %d health" % whohealth
else:
print "stuff"
return whohealth
bosshealth = dice(player, bosshealth)
bosshealth = dice(player, bosshealth)
playerhealth = dice(boss, playerhealth)
playerhealth = dice(boss, playerhealth)
Now the function returns the new health value, and you can assign that value back to the bosshealth or playerhealth globals.
Not to try and rewrite things, but here is an alternate way to go about it using dictionaries.
player = {
'name' : "Dib",
'health' : 3
}
boss = {
'name' : "Zim",
'health' : 5
}
import random
def attack(attacker, attacked):
min = 1
max = 3
dice = random.randint(min, max)
if dice == 1:
print "Your opponent lost no health"
print "Your opponent has %d health" % attacked['health']
elif dice == 2:
print "%s hits" % attacker['name']
attacked['health'] -= 1
print "Your opponent lost 1 health"
print "Your opponent has %d health" % attacked['health']
elif dice == 3:
print "%s crits" % attacker['name']
attacked['health'] -= 2
print "Your opponent lost 2 health"
print "Your opponent has %d health" % attacked['health']
else:
print "stuff"
attack(player, boss)
attack(player, boss)
attack(boss, player)
attack(boss, player)

Using a dictionary to choose scenes in a game, but it's not playing the correct scene. Why?

At the start, if a random integer = 1, it will play a random event. The random event should be selected (also randomly) from a dictionary containing each scene name. Instead, it doesn't try to access the other scenes. It only runs each method(function?) in the order written. What am I doing wrong? Is this a bad way to go about this?
I'm still learning, so any pointers are appreciated!
from random import randint
from time import sleep
class RandomEvent(object):
def __init__(self, wallet):
self.wallet = wallet
def old_man(self):
#insert art
print "\nExcuse me, I have an unusual request."
print "My horoscope tells me it's my lucky day,"
print "but I don't have any money."
print "\nIf you'll let me borrow some money, I"
print "promise to give you half of all the winnings."
print "Do we have a deal?"
give_money = raw_input("(y)es or (n)o? ")
if give_money.lower() == "y":
print "\nFunds: $", self.wallet
how_much = int(raw_input("How much money will you give? $"))
if how_much <= self.wallet:
how_much *= randint(2,3)
print "Haha! I won $%d! Here's your share of the money, kiddo." % (how_much*2)
self.wallet += how_much
else:
print "Eh, kids these days... no faith in their elders... (grumble grumble)..."
sleep(2)
print "\nA few moments later you see the old man hit the jackpot at a slot machine."
return self.wallet
def robber(self):
#insert art
print "\nPsssst! Hey, you!"
#sleep(1)
print "\nYou glance down to see a knife discreetly placed"
print "to your stomach."
#sleep(1)
print "\nHand over all your cash. No funny business."
print "\nFunds: $", self.wallet
how_much = int(raw_input("How much money will you give? $"))
lie_success = randint(1,3)
if how_much == self.wallet:
self.wallet = 0
print "\nNice doin' business with ya."
print "The robber quickly disappears into a nearby crowd,"
print "taking all your money with him."
if how_much != self.wallet and lie_success == 1:
self.wallet -= how_much
print "\nNice doin' business with ya."
print "The robber quickly disappears into a nearby crowd,"
print "taking your money with him."
else:
print "\nYou think you're a wise guy, eh?"
sleep(2)
print "\nYou are dead. GAME OVER"
sleep(2)
exit()
return self.wallet
def pretty_woman(self):
pass
###----------------------GAME CODE BELOW---------------
funds = 500
encounter = 1
while True:
if encounter == randint(1, 1): # 1,1 FOR TESTING
story = RandomEvent(funds)
scene_list = {1: story.old_man(), 2: story.robber(), 3: story.pretty_woman()}
funds = scene_list[2] #randint(1,3)] FOR TESTING
else:
print "\n\n\nWelcome to Dreams Casino."
print "Where would you like to go?"
print "(1) Slot Machines"
print "(2) Roulette Table"
print "(3) Leave the Casino"
print "\nFunds: $", funds
game_choice = int(raw_input("> "))
You're calling the functions when creating your dictionary:
scene_list = {1: story.old_man(), 2: story.robber(), 3: story.pretty_woman()}
Since you want scene_list[1] to refer to your function, pass the function:
scene_list = {1: story.old_man, 2: story.robber, 3: story.pretty_woman}

Roulette program will not recognize correct guess. Why?

The following is the roulette portion of a casino game I'm putting together, but I can't seem to get it to work correctly. It won't recognize when the player chooses the correct number, and I'm hoping someone can tell me why. Obviously, a few other parts have not been completed, but I'm just trying to get the basics running. Also, I'm pretty new at this, so feel free to critique anything else! Thanks.
from random import randint
from time import sleep
funds = 50
### Straight Up number bet = 35:1
### Odd/Even payout = 1:1
class RouletteTable(object):
def __init__(self, wallet):
self.wallet = wallet
def spin(self, bets):
print "Spinning..."
sleep(2)
print "The winner is..."
sleep(1)
winner = 25 #randint(0, 36) #FOR TESTING
print "Number ", winner
if winner in bets == True:
bets = True
return bets
else:
print "You bet on: ", bets
print "Better luck next time."
bets = False
return bets
def game(self):
while self.wallet >= 0:
print "\n\nWelcome to Roulette."
print "Test your luck, and place your bets!"
print "Current funds: $", self.wallet
print "\n(1)Place bet or (2)Exit"
choice = raw_input("> ")
if choice == "1":
bets = []
print '''\n\n\n
__________
[ 0 ]
[ 1][ 2][ 3]
[ 4][ 5][ 6]
[ 7][ 8][ 9]
[10][11][12]
[13][14][15]
[16][17][18]
[19][20][21]
[22][23][24]
[25][26][27]
[28][29][30]
[31][32][33]
[34][35][36]
[ODD] [EVEN]
'''
print "How much will you bet (per number)?"
bet_amount = int(raw_input("> $"))
print "Type a number to bet on, and press Enter."
print "When finished choosing, just press Enter."
while True:
print "Funds: $", self.wallet
print "Current Bets: ", bets
number_choice = raw_input("> ")
if number_choice != "":
bets.append(int(number_choice))
self.wallet -= bet_amount
else:
# start spin
self.spin(bets)
# payout for bets
if bets == True:
print "You win $", bet_amount*35
self.wallet += bet_amount*35
break
if choice == "2":
return self.wallet
break
if self.wallet == 0:
print "You're out of money!\n"
roulette = RouletteTable(funds)
funds = roulette.game()
Your main error was this:
# start spin
self.spin(bets)
# payout for bets
It should read:
#start spin
bets = self.spin(bets)
# payount bets
the modified code below does it correctly. Overwriting bets with a different type isn't good style, I'd suggest using a different variable. Also win in bets doesn't need to explicitly compared to True (unless for clarification during learning).
Hope that helps, if you have further questions, just comment ;-)
from random import randint
from time import sleep
funds = 50
### Straight Up number bet = 35:1
### Odd/Even payout = 1:1
class RouletteTable(object):
def __init__(self, wallet):
self.wallet = wallet
def spin(self, bets):
print "Spinning..."
sleep(2)
print "The winner is..."
sleep(1)
winner = 25 #randint(0, 36) #FOR TESTING
print "Number ", winner
if winner in bets:
return True
else:
print "You bet on: ", bets
print "Better luck next time."
return False
def game(self):
while self.wallet >= 0:
print "\n\nWelcome to Roulette."
print "Test your luck, and place your bets!"
print "Current funds: $", self.wallet
print "\n(1)Place bet or (2)Exit"
choice = raw_input("> ")
if choice == "1":
bets = []
print '''\n\n\n
__________
[ 0 ]
[ 1][ 2][ 3]
[ 4][ 5][ 6]
[ 7][ 8][ 9]
[10][11][12]
[13][14][15]
[16][17][18]
[19][20][21]
[22][23][24]
[25][26][27]
[28][29][30]
[31][32][33]
[34][35][36]
[ODD] [EVEN]
'''
print "How much will you bet (per number)?"
bet_amount = int(raw_input("> $"))
print "Type a number to bet on, and press Enter."
print "When finished choosing, just press Enter."
while True:
print "Funds: $", self.wallet
print "Current Bets: ", bets
number_choice = raw_input("> ")
if number_choice != "":
bets.append(int(number_choice))
self.wallet -= bet_amount
else:
# start spin
did_win = self.spin(bets)
# payout for bets
if did_win == True:
ammount = bet_amount*35
self.wallet += ammount
print "You win $", ammount
break
if choice == "2":
return self.wallet
break
if self.wallet == 0:
print "You're out of money!\n"
roulette = RouletteTable(funds)
funds = roulette.game()