Need help trying to loop my enemies after they have died - python

while phealth > 0
while choice !a:
if choice.lower() == "a":
print('You attack the',name,"and do",pstrength,"damage!")
if random.random() < crit_chance:
print('You got a critical hit +5 more damage')
mhealth = mhealth - pstrength - 5
print(mhealth)
else:
mhealth = mhealth - pstrength
penergy = penergy - pstrength
print(mhealth)
if penergy <= 0:
print('You ran out of energy but thankfully the old man saved but you lost',random.randint(0, pcoins),'coins.')
coins = 0
if mhealth <= 0:
print('You killed the enemy and gained 1 coin')
pcoins = pcoins + 1
The code just keeps going. I would rather want it to reset at the beginning of the loop after the enemy has died.
This is not a full version of the code!!!

As posted by #ewz93 the code needed a reset message at the end!

Related

How can I code a timer to run simultaneously with my code?

import time
import threading
import random
#declare variables and constant
guessingelement = ["Hydrogen", "Magnesium", "Cobalt", "Mercury", "Aluminium", "Uranium", "Antimony"]
nicephrases = ["Nice job", "Marvellous", "Wonderful", "Bingo", "Dynamite"]
wronganswers = ["Wrong answer...", "Nope", "Try again next time.", "Wrong answer. Nice effort"]
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
guess_no = 0
score = 0
def countdown():
global my_timer
my_timer = 5
for i in range(7):
randomelement = random.choice(guessingelement)
guessingelement.remove(randomelement)
time.sleep(1)
for x in range(5):
my_timer = my_timer - 1
time.sleep(1)
print("Out of time.Haiya!")
countdown_thread = threading.Thread(target = countdown)
countdown_thread.start()
while my_timer > 0:
#tips of the element
if randomelement == "Hydrogen" and not out_of_guesses:
print("Tip 1: It is the most flammable of all the known substances.")
print("Tip 2: It reacts with oxides and chlorides of many metals, like copper, lead, mercury, to produce free metals.")
print("Tip 3: It reacts with oxygen to form water.")
#test the number of tries so that it doesn't exceed 3 times if answer is wrong
while guess != randomelement and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("Enter guess: ")
guess_count += 1
else:
out_of_guesses = True
#add score, praise when answer is correct and encourage when answer is wrong for 3 times
if out_of_guesses:
print(random.choice(wronganswers))
print(f"{randomelement} was the element.")
else:
print(random.choice(nicephrases), ", YOU GET IT!")
score = score + 1
if randomelement == "Magnesium" and not out_of_guesses:
print("Tip 1: It has the atomic number of 12.")
print("Tip 2: It's oxide can be extracted into free metal through electrolysis.")
print("Tip 3: It is a type of metal.")
procedure same as the first question. And so on with my questions.
However, it shows that my_timer variable is not defined. The process that I would want it to undergo is that it will countdown for 5 seconds for every questions, and when the timer reaches 0, it will print out of time and proceed to the next question.
In the code you've shown, you haven't assigned a value to my_timer.
my_timer = 5
By assigning the global within countdown() you've merely allowed countdown to change the value of my_timer. You still need to assign a value.

Error with a player turn ending loop in the Zombie Dice game

I'm trying to develop a code for the zombie dice game.
My problem is when the first player replies that he doesn't want to continue playing.
The game ends and I can't get the second player to play. Can someone help me?
import random
print("========== ZOMBIE DICE (PROTÓTIPO SEMANA 4) ==========")
print("========= WELCOME TO THE ZOMBIE DICE GAME! ========")
numeroJogadores = 0
while numeroJogadores < 2:
numeroJogadores = int(input("Enter the number of players: "))
print(numeroJogadores)
if numeroJogadores < 2:
print("NOTICE: You must have at least 2 players to continue!")
listaJogadores = []
for i in range(numeroJogadores):
nome = str(input("\nEnter player name: " + str(i+1) + ": "))
listaJogadores.append(nome)
print(listaJogadores)
dadoVerde = ("brain", "steps", "brain", "shot", "steps", "brain")
dadoAmarelo = ("shot", "steps", "brain", "shot", "steps", "brain")
dadoVermelho = ("shot", "steps", "shot", "brain", "steps", "shot")
listaDados = [dadoVerde, dadoVerde, dadoVerde, dadoVerde, dadoVerde, dadoVerde,
dadoAmarelo, dadoAmarelo, dadoAmarelo, dadoAmarelo,
dadoVerde, dadoVermelho, dadoVermelho]
print("\nSTARTING THE GAME...")
jogadorAtual = 0
dadosSorteados = []
tiros = 0
cerebros = 0
passos = 0
while True:
print("PLAYER TURN: ", listaJogadores[jogadorAtual])
for i in range (3):
numeroSorteado = random.randint(0, 12)
dadoSorteado = listaDados[numeroSorteado]
if (dadoSorteado == dadoVerde):
corDado = "Green"
elif (dadoSorteado == dadoAmarelo):
corDado = "Yellow"
else:
corDado = "Red"
print("Dice Drawn: ", corDado)
dadosSorteados.append(dadoSorteado)
print("\nThe faces drawn were: ")
for dadoSorteado in dadosSorteados:
numeroFaceDado = random.randint(0,5)
if dadoSorteado[numeroFaceDado] == "brain":
print("- brain (you ate a brain)")
cerebros = cerebros + 1
elif dadoSorteado[numeroFaceDado] == "tiro":
print("- shot (you got shot)")
tiros = tiros + 1
else:
print("- steps (a victim escaped)")
passos = passos + 1
print("\nCURRENT SCORE: ")
print("brins: ", cerebros)
print("shots: ", tiros)
if cerebros >= 13:
print("Congratulations, you've won the game!")
break
elif tiros >= 3:
print("You lost the game!")
break
else:
continuarTurno = str(input("\nNOTICE: Do you want to continue playing dice? (y=yes / n=no)")).lower()
if continuarTurno == "n":
jogadorAtual = jogadorAtual + 1
dadossorteados = 0
tiros = 0
cerebros = 0
passos = 0
if jogadorAtual > numeroJogadores:
print("Finalizing the game prototype")
else:
print("Starting another round of the current turn")
dadossorteados = []
print("======================================================")
print("===================== END OF THE GAME ====================")
print("======================================================")
Does anyone know what I'm doing wrong?
I'm new as a programmer. If anyone knows how to help me with this problem, I would be grateful.
EDIT: Well now the code just works. I can switch players just fine, but if you go through all the characters it crashes again since jogadorAtual gets too big for listaJogadores. I don't quite understand the game, but assuming you want to start back with the first player, an elegant way you can accomplish that is by doing modulus with the % operator, which divides two numbers but returns the remainder. If you divide the number of players by the size of listaJogadores, you'll always get a number inside listaJogadores's range.
# Change this...
print("PLAYER TURN: ", listaJogadores[jogadorAtual])
# ...to this
print("PLAYER TURN: ", listaJogadores[jogadorAtual % len(listaJogadores)])
If that's not what you need for your game, let me know.
Original answer: Is the game ending or is it crashing? When I run the game, it always crashes with:
File "C:\Users\me\Desktop\Untitled-1.py", line 56, in <module>
diceDrawns.append(diceDrawn)
AttributeError: 'int' object has no attribute 'append'
This is because after looping, you try to do diceDrawns.append(), but you've already replaced the diceDrawns list with an integer on line 87. I'm not sure if you meant to replace diceDrawn instead, but that's definitely the source of the problem.
An unrelated note: You can do += as a shorthand way to increment a variable by a certain amount, so you can replace a lot of instances of things like currentPlayer = currentPlayer + 1 with currentPlayer += 1, and the same can be done with any operator, so you could also do things like -= or *=

If statement variables [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
So I've been trying to make this turn-based battle and I ran into a slight issue. I can't seem to use the variables that are defined within the if statement. I tried declaring them global but that didn't work. Is there any way to solve this problem while still using if statements?
Here the code that I'm having issues with:
import time
from random import randint
import copy
health = randint(100, 400)
speed = randint(50, 100,)
damage = randint(50, 200)
totalhealth = copy.deepcopy(health)
def stats():
print("Damage:",damage)
print("Health:",totalhealth, "|", health)
print("Speed:",speed)
if spawn == "mandrake":
spawnh = 200
spawnspeed = 50
spawnspeed = 50
eelement = "earth"
buff = "heal self"
gold = randint(10,20)
ms = 3
x = True
ss = 0
s = 0
ms = 0
m = 0
spawn = "mandrake"
while x == True:
battle = input("""
Inventory(1)
Run(2)
Attack(3)
Defend(4)
Skills(5)""")
stats()
if battle == '3':
if ss > 99 and spawnh > 0:
print(spawn, "dealt", spawndamage)
time.sleep(3)
ss -= 100
health = health - spawndamage
ms += 1
if s >= 100:
print("you dealt", damage)
time.sleep(3)
spawnh = spawnh - damage
s -= 100
if s <= 100 and spawnh > 0:
print("you prepare to attack")
time.sleep(3)
s += speed
if ss <= 100 and spawnh > 0:
print(spawn, "prepares to attack")
ss += spawnspeed
if ss >= 100 and spawnh > 0:
print(spawn, "dealt", damage)
time.sleep(3)
ss = ss - 100
health = health - spawndamage
if health <= 0:
print("you died!")
time.sleep(3)
if spawnh <= 0:
print("you are victorious!")
x = False
if spawnspeed < 100 and spawnh > 0:
print(spawn, "prepares to attack")
ss += spawnspeed
if health <= 0:
print("you died!")
time.sleep(3)
exit()
exit()
if spawnh <= 0:
print("you are victorious!")
x = False
You're trying to access a variable before it's been declared.
You've got if spawn == "mandrake": before you declare spawn, move spawn = "mandrake" above the if statement.

Having Trouble With: Tuple and Int?

So I am making a camel game and I get a weird error that says
"TypeError: '>' not supported between instances of 'tuple' and 'int'"
and I am not sure what this means, I have posted before and I will state this again I am a beginner coder. Thank you to whoever helps here is the code and I will put a comment where the error is that you!
import random
done = False
milesTraveled = 0
thirst = 0
camelTired = 0
nativesDis = -20
canteens = 5
print('''
Welcome to Camel!
You have stolen a camel to make your way across the great Mobi desert.
The natives want their camel back and are chasing you down! Survive your
desert trek and outrun the natives. ''')
while not done:
oasis = (1,21)
if oasis == 4:
print("You found an oasis!")
canteens = 5
thrist = 0
if thirst > 6:
print("You died of thrist!")
spc = input("")
done = True
if thirst > 4:
print("You are thirsty")
#under here
if camelTired > 8:
print("Your camel DIED!")
spc = input("")
done = True
if camelTired > 5:
print("Your camel is getting tired")
if nativesDis == milesTraveled + 20:
print('The natives caught up with you!')
spc=input("")
done = True
if milesTraveled == 200:
print('You Win!')
spc = input("")
done = True
print('''
A. Drink from your canteen.
B. Ahead full speed.
C. Stop and rest.
D. Status check.
Q. Quit ''')
user_choice = input("")
if user_choice.upper() == 'Q':
done = True
elif user_choice.upper() == 'D':
print('''
Miles Traveled: 0
Drinks In Canteen:''',canteens,'''
Thirstyness:''',thirst,'''
The Natives Are 20 Miles Behind You''')
elif user_choice.upper() == 'C':
camelTired = 0
nativesDis = random.randint(7,15)
elif user_choice.upper() == 'B':
milesTraveled = random.randint(10,22)
print("You traveled",milesTraveled,"miles!")
thirst + 1
camelTired = (1,3)
nativesDis = (7,14)
elif user_choice.upper() == 'A':
if canteens > 0:
canteens = canteens - 1
thirst
= 0
You need to take the number out of the tuple and into a variable that is also an integer.
There are multiple integers in your tuple.
You can access them in the following way:
some_tuple_of_integers = (12, 432, 345)
index_zero_integer = some_tuple_of_integers[0]
index_one_integer = some_tuple_of_integers[1]
index_two_integer = some_tuple_of_integers[2]
print(index_zero_integer)
print(index_one_integer)
print(index_two_integer)
Or just straight from the tuple itself without creating a new variable (This can sometimes get unreadable when working with lots of indexes and tuples).
print(some_tuple_of_integers[0])
print(some_tuple_of_integers[1])
print(some_tuple_of_integers[2])
You can then easily compare between other values.
If, for example you have a string from the tuple that you need to compare with another integer, you can change it by doing:
index_two_integer = int(index_two_integer)

Repeating a block of "If" statement

I'm trying to make a text based game, and to make my fighting mechanics I have to repeat an if statement until you or the monster dies.
Here it is --
Ph would stand for Player health, str is player strength, mdam is monster damage, mstr is monster strength, monsterh is monsterhealth, the random.random() is the attack bonus you receive (Adding onto this, is there any way to round the number to one or no decimal places?) Thank you! :D
if fight == "A" and ph > 0:
damage = (str) + (random.random())
monsterh = 6
mstr = 0.9
monsterh = (monsterh) - (damage)
print(damage)
print(damage - str)
print('You attack the monster. You deal %s damage.' % damage )
time.sleep(3)
if monsterh > 0:
mstr = 0.9
mdam = (mstr) + (random.random())
print('The monster attacks you!')
ph = ph - mstr
print("You get hit %s" % mdam )
else:
xpgain = damage + 5
print("You won! You've gained %s XP!" % xpgain)
I would wrap your combat seen in a while loop. For example:
while (ph > 0 or monsterh > 0)
# combat rules
# Check who died and move on from there
if (ph > 0)
# next thing the player does
else
# print "You died"
In regards to rounding, there are multiple options depending on exactly what you want to do: python: getting only 1 decimal place
To round the value you get from
random.random()
you can do
round(random.random(),1)
to round to 1 decimal place, or if you want to get rid of decimals, replace
random.random()
with
int(random.random())
As for repeating the if statement, you can put it into a loop which will break when a condition is met
while true:
if fight == "A" and ph > 0:
damage = (str) + (int(random.random()))
monsterh = 6
mstr = 0.9
monsterh = (monsterh) - (damage)
print(damage)
print(damage - str)
print('You attack the monster. You deal %s damage.' % damage )
time.sleep(3)
elif ph<=0 or fight!="A":
print("You lose!")
break
if monsterh > 0:
mstr = 0.9
mdam = (mstr) + (int(random.random()))
print('The monster attacks you!')
ph = ph - mstr
print("You get hit %s" % mdam )
else:
xpgain = damage + 5
print("You won! You've gained %s XP!" % xpgain)
break
Although you wouldn't need the fight!="A" since I don't think you change the value of fight at all.
Also you don't have to do
mdam = (mstr) + (int(random.random()))
You can just do
mdam = mstr+int(random.random())
This above ^ applies to other places in your code as well. If you have any questions please feel free to ask.

Categories

Resources