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.
This question already has answers here:
How to make program go back to the top of the code instead of closing [duplicate]
(7 answers)
Asking the user for input until they give a valid response
(22 answers)
Repeating a function in Python
(2 answers)
Closed 8 months ago.
import random
user = input("You reconize this creture. The feared BaLaKe. Its weakness is 'rock', 'paper',''scissors' Are you willing to challenge him in a battle of Rock Paper Scissors? (ENTER)" )
print("ROARRRRRRRRRRRRRRRRRRR!!!!!")
Below is the function I want to loop when userhealth and dragonhealth <= 0. I want it to keep asking for input for rock, paper, or scissors and go through the conditions.
def fight(userhealth,dragonhealth):
dragon = random.choice(["r","p","s"])
user=input("Rock(r), Paper(p) or Scissors(s): ").lower()
print(dragon)
if user==dragon:
print("You both missed your attacks. Bruh ;-;")
elif is_win(user,dragon):
dragonhealth-=20
print("You hit BaLaKe! 20 DMG Done!!! :) ")
print("Your health: "+str(userhealth )+" HP")
print("BaLaKe\'s health: "+str(dragonhealth )+" HP")
else:
print("Ow! You got hit by BaLake. -20 HP :( ")
userhealth-=20
print("Your health: "+str(userhealth )+" HP")
print("BaLaKe\'s health: "+str(dragonhealth )+" HP")
def is_win(player,opponent):
if (player=="r" and opponent=="s") or (player=="s" and opponent=="p") or (player=="p" and opponent=="r"):
return True
fight(100,100)
Do you want this ?
import random
user = input("You recognize this creture. The feared BaLaKe. Its weakness is 'rock', 'paper',''scissors' Are you willing to challenge him in a battle of Rock Paper Scissors? (ENTER)" )
print("ROARRRRRRRRRRRRRRRRRRR!!!!!")
def fight(userhealth,dragonhealth):
while(userhealth>0 and dragonhealth>0):
dragon = random.choice(["r","p","s"])
user=input("Rock(r), Paper(p) or Scissors(s): ").lower()
print(dragon)
if user==dragon:
print("You both missed your attacks. Bruh ;-;")
elif is_win(user,dragon):
dragonhealth-=20
print("You hit BaLaKe! 20 DMG Done!!! :) ")
print("Your health: "+str(userhealth )+" HP")
print("BaLaKe\'s health: "+str(dragonhealth )+" HP")
else:
print("Ow! You got hit by BaLake. -20 HP :( ")
userhealth-=20
print("Your health: "+str(userhealth )+" HP")
print("BaLaKe\'s health: "+str(dragonhealth )+" HP")
def is_win(player,opponent):
if (player=="r" and opponent=="s") or (player=="s" and opponent=="p") or (player=="p" and opponent=="r"):
return True
fight(100,100)
Try the following code:
import random
user = input("You reconize this creture. The feared BaLaKe. Its weakness is 'rock', 'paper',''scissors' Are you willing to challenge him in a battle of Rock Paper Scissors? (ENTER)" )
print("ROARRRRRRRRRRRRRRRRRRR!!!!!")
dragonhealth = 100
userhealth = 100
def fight(userhealth,dragonhealth,choice):
dragon = random.choice(["r","p","s"])
print(dragon)
if choice==dragon:
print("You both missed your attacks. Bruh ;-;")
elif is_win(choice,dragon):
dragonhealth-=20
print("You hit BaLaKe! 20 DMG Done!!! :) ")
print("Your health: "+str(userhealth )+" HP")
print("BaLaKe\'s health: "+str(dragonhealth )+" HP")
else:
print("Ow! You got hit by BaLake. -20 HP :( ")
userhealth-=20
print("Your health: "+str(userhealth )+" HP")
print("BaLaKe\'s health: "+str(dragonhealth )+" HP")
return userhealth,dragonhealth
def is_win(player,opponent):
if (player=="r" and opponent=="s") or (player=="s" and opponent=="p") or (player=="p" and opponent=="r"):
return True
while (userhealth>0 or dragonhealth>0):
choice=input("Rock(r), Paper(p) or Scissors(s): ").lower()
userhealth,dragonhealth = fight(userhealth,dragonhealth,choice)
if userhealth>0:
print("You won! ")
elif dragonhealth>0:
print("You lost! ")
Explanation: Sets the original healths at the start. Sets up a while loop to check if either of them have less than 0 health. Subtracts and updates the health when you lose/win. Declares a winner at the end!
Use While loop for repeating the game util someone gets 0 HP.
I created a function to terminate the game when someone is at 0 HP. See it
enter code here
import random
user_health = 100 # used underscore snake case love:)
dragon_health = 100 # I initialized both variables outside
def fight(user_health, dragon_health): # according to PEP8 I guess. we shouldn't use shadow names. Still,not a big deal
dragon = random.choice(["r", "p", "s"])
user = input("Rock(r), Paper(p) or Scissors(s): ").lower()
print(dragon)
if user == dragon:
print("You both missed your attacks. Bruh ;-;")
return user_health, dragon_health
elif is_win(user, dragon):
dragon_health -= 20
print("You hit BaLaKe! 20 DMG Done!!! :) ") #
print("Your health: " + str(user_health) + " HP")
print("BaLaKe\'s health: " + str(dragon_health) + " HP")
return user_health, dragon_health
else:
print("Ow! You got hit by BaLake. -20 HP :( ")
user_health -= 20
print("Your health: " + str(user_health) + " HP")
print("BaLaKe\'s health: " + str(dragon_health) + " HP")
return user_health, dragon_health
def is_win(player, opponent):
if (player == "r" and opponent == "s") or (player == "s" and opponent == "p") or (
player == "p" and opponent == "r"):
return True
# this function terminates game when someone is at 0 HP and prints output
def game_terminator(user_health, dragon_health): # I continued with the shadow names to avoid confusion
if user_health == 0:
print("Dragon killed you!")
return False
elif dragon_health == 0:
print("Thrashed dragon to dealth! YOU WON!") # Nerd outputs :)
return False
else:
return True
game_is_on = True
# Use while loop for game to run until someone gets 0 HP
while game_is_on: # game_is_on is a boolean variable
user_health, dragon_health = fight(user_health, dragon_health)
game_is_on = game_terminator(user_health, dragon_health)
# Thank Me :)
My Problem(s):
The problem now is that whenever I enter a number of times to play, it just ignores it and plays forever. It is also not updating the score even though I have global variables and I am adding to them every time there is a win or loss.
Also, I do not want to ask the player(s) for their names every time they play (only when using the "out of a certain number of points function of the game). Any suggestions/help would be greatly appreciated!
My code is below for reference:
from random import randint
import sys
print("Lets play a game!")
dotheywantotplay = input("Do you want to play Rock-Paper-Scissors? (y or n) ")
bestOutOf = int(input("Best out of: (Enter a number 1-10) "))
player1score = 0
player2score = 0
computerscore = 0
class PlayWithFriend:
def __init__(self, player1, player2, name1, name2, player1score, player2score):
self.player1 = player1
self.player2 = player2
self.name1 = name1
self.name2 = name2
self.player1score = player1score
self.player2score = player2score
if player1 == player2:
print("Tie!")
elif player1 == "Rock":
if player2 == "Paper":
print("You Win", name2,"!")
print(player2, "covers", player1)
player2score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
else:
print("You Win", name1,"!")
print(player1, "smashes", player2)
player1score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
elif player1 == "Paper":
if player2 == "Scissors":
print("You Win", name2,"!")
print(player2, "cut", player1)
player2score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
else:
print("You Win", name1,"!")
print(player1, "covers", player2)
player1score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
elif player1 == "Scissors":
if player2 == "Rock":
print("You Win", name2,"!")
print(player2, "smashes", player1)
player2score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
else:
print("You Win", name1,"!")
print(player1, "cut", player2)
player1score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
else:
print("That's not a valid play. Check your spelling!")
class PlayWithComputer:
def __init__(self, player, name, player1score, computerscore):
self.player = player
self.player1score = player1score
self.computerscore = computerscore
self.name = name
t = ["Rock", "Paper", "Scissors"]
computer = t[randint(0,2)]
if player == computer:
print("Tie!")
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
elif player == "Rock":
if computer == "Paper":
print("You lose!", computer, "covers", player)
computerscore += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
else:
print("You win!", player, "smashes", computer)
player1score += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
elif player == "Paper":
if computer == "Scissors":
print("You lose!", computer, "cut", player)
computerscore += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
else:
print("You win!", player, "covers", computer)
player1score += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
elif player == "Scissors":
if computer == "Rock":
print("You lose...", computer, "smashes", player)
computerscore += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
else:
print("You win!", player, "cut", computer)
player1score += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
else:
print("That's not a valid play. Check your spelling!")
if dotheywantotplay == "y":
PlayWith = input("Do you want to play Rock-Paper-Scissors with computer or a friend? (computer, friend, exit) ")
while PlayWith in ('computer', 'friend', 'exit'):
if PlayWith == "friend":
player1 = input('Enter first players name: ')
player2 = input('Enter second players name: ')
while player1score + player2score < bestOutOf:
personchoice1 = input("First player... Rock, Paper or Scissors? ")
personchoice2 = input("Second player... Rock, Paper or Scissors? ")
PlayWithFriend(personchoice1, personchoice2, player1, player2, player1score, player2score)
elif PlayWith == "computer":
player = input('Enter first players name: ')
while player1score + computerscore < bestOutOf:
personchoice = input("Rock, Paper, Scissors? ")
PlayWithComputer(personchoice, player, player1score, computerscore)
elif PlayWith == "exit":
sys.exit()
else:
print("That's not a valid play. Check your spelling!")
else:
print("I am sad now :-(")
sys.exit()
I went over your code and cleaned it up. I made the formatting, variable names, and processes much more pythonic. You will find it is much easier to use python when you use these best practices, so I recommend you at least look over the code and see what I did. For me, I know this would've been helpful when I started learning python.
from random import choice
def get_result(choice1, choice2):
return {
('paper', 'rock'): dict(win='player 1', action='covers'),
('rock', 'paper'): dict(win='player 2', action='covers'),
('rock', 'scissors'): dict(win='player 1', action='smashes'),
('scissors', 'rock'): dict(win='player 2', action='smashes'),
('scissors', 'paper'): dict(win='player 1', action='cuts'),
('paper', 'scissors'): dict(win='player 2', action='cuts'),
}[(choice1, choice2)] # index this dictionary
def main():
print('Lets play a game!')
if input('Do you want to play Rock-Paper-Scissors? (y or n) ') != 'y':
quit()
num_games = int(input('Best out of: (Enter a number 1-10) '))
num_games = max(min(num_games, 10), 1) # clamp num_games between 1-10
while True: # infinite loop, we can break out or quit when we need
inp = input('Do you want to play Rock-Paper-Scissors with computer or a friend? (computer, friend, exit) ')
if inp == 'exit':
quit()
play_with_computer = inp == 'computer'
name1 = input('Enter first players name: ')
name2 = 'computer' if play_with_computer else input('Enter second players name: ')
score = {name1: 0, name2: 0}
for game_number in range(num_games):
choice1 = input(f'{name1}... rock, paper or scissors? ')
choice2 = choice(['rock', 'paper', 'scissors']) if play_with_computer else input(f'{name2}... rock, paper or scissors? ')
if choice1 == choice2:
print('Tie!')
continue
result = get_result(choice1, choice2)
win_name = name1 if result['win'] == 'player 1' else name2
lose_name = name2 if result['win'] == 'player 1' else name1
score[win_name] += 1
print(f'{win_name} {result["action"]} {lose_name}')
print(f'Game {game_number+1}, the score is {score[name1]} {name1}, {score[name2]} {name2}')
print(name1 if score[name1] > score[name2] else name2, 'wins!')
if __name__ == '__main__': # this just means if the file is run
main()
The main thing I did was get rid of your rock paper scissors logic, (which you repeated twice which is never best practice in programming), and replaced it with a get_result function which returns the winner and action of the moves. I also replaced your if statements that test if the game is against the computer, with a bool play_with_computer. This can be used when getting player 2 name and the second choice, which is all that is really different when playing with a computer. The last thing is your game loop while. Since you never really need to execute any code after this (only reason to exit is to quit), I find it to be cleaner to have an infinite loop while True, and just call quit() if the input is 'exit'.
Okay so the mistake is:
while PlayWith != "computer" or "friend" or "exit":
try this thing:
while PlayWith != "computer" or PlayWith != "friend" or PlayWith != "exit":
And sorry if this does not work
which while loops and if statements are you having trouble with?
Upon first glance, the while statement below will never break the moment a player enters a value besides "computer", "friend" or "exit".
Instead, what you can do is put the process of the game within a function, that is continuously called back when the player enters a value besides the ones aforementioned.
while PlayWith != "computer" or "friend" or "exit":
if PlayWith == "friend":
player1 = input('Enter first players name: ')
player2 = input('Enter second players name: ')
personchoice1 = input("First player... Rock, Paper or Scissors? ")
personchoice2 = input("Second player... Rock, Paper or Scissors? ")
i = 0
while i in range(0, bestOutOf):
if i >= bestOutOf:
sys.exit()
if bestOutOf >= 1 and bestOutOf <= 10:
PlayWithFriend(personchoice1, personchoice2, player1, player2, player1score, player2score)
i += 1
else:
print("Setting default game to: \"best out of three\"")
PlayWithFriend(personchoice1, personchoice2, player1, player2, player1score, player2score)
i = bestOutOf - 3
if PlayWith == "computer":
i = 0
while i in range(0, bestOutOf - 1):
if i >= bestOutOf:
sys.exit()
else:
player = input('Enter first players name: ')
if bestOutOf >= 1 and bestOutOf <= 10:
personchoice = input("Rock, Paper, Scissors? ")
PlayWithComputer(personchoice, player, player1score, computerscore)
else:
personchoice = input("Rock, Paper, Scissors? ")
print("Setting default game to: \"best out of three\"")
PlayWithComputer(personchoice, player, player1score, computerscore)
if PlayWith == "exit":
sys.exit()
elif PlayWith != "exit" or "computer" or "friend":
print("That's not a valid play. Check your spelling!")
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.