If statement variables [closed] - python

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.

Related

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 *=

Need help trying to loop my enemies after they have died

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!

(Microbit) Player position resets after function completes

I've been working on a program for the Microbit inspired by some basic blocks script I saw a few years back. The functionality of the AI controlled pixel and the player controlled pixel work as intended--which one annoying, and game breaking bug--the player ship resets to its spawn position whenever the AI ship completes its function.
I suspect this is because I have an assigned position for the ship in the beginning of the code, where it is then modified in the function itself. Removing this results in an error where a variable is not referenced--however, I cannot leave the problem alone. I welcome any guidance. The code is below.
from microbit import *
import random
enemyXpos = 4
playerXpos = 2
while True:
display.set_pixel(enemyXpos,0,4)
display.set_pixel(playerXpos,4,6)
def laser(laserXpos, laserYpos):
laserXpos = playerXpos
laserYpos = 3
for i in range (4):
display.set_pixel(laserXpos,laserYpos,9)
if laserYpos > 0:
display.set_pixel(laserXpos,laserYpos,0)
laserYpos -= 1
display.set_pixel(laserXpos,laserYpos,9)
if laserYpos == 0 and laserXpos == enemyXpos:
display.show(all_booms, delay=200)
score = score + 1
continue
elif laserYpos == 0:
display.set_pixel(bombXpos,bombYpos,0)
laserYpos = newlaserYpos
sleep (200)
def enemy_left(enemyXpos, playerXpos):
enemyXpos = 4
for i in range (4):
display.clear()
enemyXpos -= 1
display.set_pixel(enemyXpos,0,4)
display.set_pixel(playerXpos,4,6)
if button_a.is_pressed() and button_b.is_pressed():
laser(laserXpos,laserYpos)
elif button_a.is_pressed() and playerXpos > 0:
playerXpos -= 1
elif button_b.is_pressed() and playerXpos < 4:
playerXpos += 1
sleep(200)
def enemy_right(enemyXpos, playerXpos):
enemyXpos = 0
for i in range (4):
display.clear()
enemyXpos += 1
display.set_pixel(enemyXpos,0,4)
display.set_pixel(playerXpos,4,6)
if button_a.is_pressed() and button_b.is_pressed():
laser(laserXpos,laserYpos)
elif button_a.is_pressed() and playerXpos > 0:
playerXpos -= 1
elif button_b.is_pressed() and playerXpos < 4:
playerXpos += 1
sleep(200)
enemy_left(enemyXpos, playerXpos)
enemy_right(enemyXpos, playerXpos)

restarting a while loop in python for a new level [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
New to python (1st semester), I have a game that I am working on for my final project. I have written the code to do all I want for a "level" but I need to know how to make it start a new level if a condition is met. If I have a while loop already, should I create another loop outside for the level? (first post, so i'm not certain if this is enough info.) Thank you for anything you can provide.
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if (pygame.key.get_pressed()[pygame.K_RIGHT] != 0 ):
newbasketx = basketx + 15
if newbasketx <= 600:
basketx = newbasketx
if (pygame.key.get_pressed()[pygame.K_LEFT] != 0 ):
newbasketx = basketx - 15
if newbasketx >= 0:
basketx = newbasketx
basket_rect = pygame.Rect(basketx, baskety, 200, 70)
for index in range (0,nFruits):
fruity[index] = fruity[index] + fruitSpeed[index]
thisFruit_rect = pygame.Rect (fruitx[index], fruity[index],150,75)
if thisFruit_rect.colliderect (basket_rect):
fruity[index] = random.randrange (-1000, -10)
fruitx[index] = random.randrange (0,600)
thisFruit = fruitList[index]
if thisFruit == badpear:
life = life -1
if thisFruit == banana:
score = score + 5
totalScore = totalScore + 5
if thisFruit == apple:
score = score + 10
totalScore = totalScore + 10
if thisFruit == cherry:
score = score + 15
totalScore = totalScore + 15
if thisFruit == grapes:
score = score + 1
totalScore = totalScore + 1
elif fruity[index] > height:
fruity[index] = random.randrange (-1000, -10)
fruitx[index] = random.randrange (0,600)
fruitMiss = fruitMiss + 1
if fruitMiss == 10:
life = life - 1
fruitMiss = 0
if life == 0:
print 'game over'
break
screen.fill(LIME)
for index in range (0,nFruits):
screen.blit(fruitList[index],(fruitx[index],fruity[index]))
screen.blit(basket, (basketx, baskety))
pygame.display.update()
if score >= 100:
life = life + 1
score = 0
pygame.time.delay(15)
print 'total', totalScore, 'Score', score, 'Life', life, 'miss',fruitMiss
without knowing your specific structure this is very hard to answer. however, you could do something like this:
while level == 1:
[do level 1 stuff]
while level == 2:
[do level 2 stuff]
etc.
you can use break to exit a while loop if the level is no longer the same.
See here for more information about control structures in python!
You can use the break or continue statements to go out of your loop or in the next loop, see here for a short introduction.

Loops incorrectly then crashes

I've got a piece of code I'm working on for a school project and the basic idea is that there's a battle between two characters where the user can input 2 attributes to each character: Strength and Skill. Now there are also modifiers for skill and strength which is the difference of the player's skill and strength attributes, divided by 5 and then rounded down respectively. Then each player has a dice roll, depending on who got the higher roll, that player gets the skill and strength modifiers added to their given attributes whilst the one that lost gets the modifiers deducted from their score. This then repeats until the strength attribute of one of them reaches 0 where that player then dies and the game ends.
In my code, the dice rolling function runs twice, and then crashes for an unknown reason I cannot identify.
import random
import time
import math
import sys
strength_mod = 0
skill_mod = 0
def delay_print(s):
for c in s:
sys.stdout.write( '%s' % c )
sys.stdout.flush()
time.sleep(0.05)
def str_mod(charone_str,chartwo_str):
if charone_str > chartwo_str:
top = charone_str
bottom = chartwo_str
calc = top - bottom
calc = calc / 5
calc = math.floor(calc)
return calc
elif chartwo_str > charone_str:
top = chartwo_str
bottom = charone_str
calc = top - bottom
calc = calc / 5
calc = math.floor(calc)
return calc
elif charone_str == chartwo_str:
top = charone_str
bottom = chartwo_str
calc = top - bottom
calc = calc / 5
calc = math.floor(calc)
return calc
def skl_mod(charone_skl, chartwo_skl):
if charone_skl > chartwo_skl:
top = charone_skl
bottom = chartwo_skl;
calc = top - bottom
calc = calc / 5
calc = math.floor(calc)
return calc
elif chartwo_skl > charone_skl:
top = chartwo_skl
bottom = charone_skl
calc = top - bottom
calc = calc / 5
calc = math.floor(calc)
return calc
elif charone_skl == chartwo_skl:
top = charone_skl
bottom = chartwo_skl
calc = top - bottom
calc = calc / 5
calc = math.floor(calc)
return calc
def mods():
global strength_mod
global skill_mod
strength_mod = str_mod(charone_strength, chartwo_strength)
skill_mod = skl_mod(charone_skill, chartwo_skill)
print "\nFor this battle, the strength modifier is:",strength_mod
time.sleep(0.20)
print "For this battle, the skill modifier is: ",skill_mod
time.sleep(0.20)
diceroll(charone, chartwo)
print "\n"+str(charone)+"'s","dice roll is:",player1
time.sleep(1)
print "\n"+str(chartwo)+"'s","dice roll is:",player2
def diceroll(charone, chartwo):
print "\n"+str(charone)+" will roll the 6 sided dice first!"
time.sleep(0.5)
global player1
player1 = random.randint(1,6)
delay_print("\nRolling dice!")
global player2
player2 = random.randint(1,6)
time.sleep(0.5)
print "\nNow",chartwo,"will roll the 6 sided dice!"
time.sleep(0.5)
delay_print("\nRolling dice!")
def battle(charone_str, chartwo_str, charone_skl, chartwo_skl, str_mod, skl_mod):
global charone_strength
global charone_skill
global chartwo_strength
global chartwo_skill
if player1 == player2:
print "\nThis round is a draw! No damage done"
elif player1 > player2:
charone_strength = charone_str + str_mod
charone_skill = charone_skl + skl_mod
chartwo_strength = charwo_skl - str_mod
chartwo_skill = chartwo_skl - skl_mod
print "\n"+charone+" won this round"
print "\n"+"Character 1:",charone
print "Strength:",charone_strength
print "Skill:",charone_skill
time.sleep(1)
print "\nCharacter 2:",chartwo
print "Strength:",chartwo_strength
print "Skill:",chartwo_skill
elif player2 > player1:
chartwo_strength = chartwo_str + str_mod
chartwo_skill = chartwo_skl + skl_mod
charone_strength = charone_str - str_mod
charone_skill = charone_skl - skl_mod
print "\n"+chartwo+" won this round"
print "\nCharacter 2:",chartwo
print "Strength:",chartwo_strength
print "Skill:",chartwo_skilll
time.sleep(1)
print "\n"+"Character 1:",charone
print "Strength:",charone_strength
print "Skill:",charone_skill
if charone_skill >= 0:
charone_skill = 0
elif chartwo_skill >= 0:
chartwo_skill = 0
if charone_strength <= 0:
print charone,"has died!",chartwo,"wins!"
elif chartwo_strength <= 0:
print chartwo,"has died!",charone,"wins!"
charone = raw_input("Enter the name of character one: ")
chartwo = raw_input("Enter the name of character two: ")
time.sleep(1.5)
print "\n",charone,"encounters",chartwo
delay_print("\nBattle Initiated!")
charone_strength = int(raw_input("\nEnter the strength score for "+str(charone)+" (between 50 and 100): "))
while charone_strength > 100 or charone_strength < 50:
print "That number is not between 50-100"
charone_strength = int(raw_input("\nEnter the strength score for "+str(charone)+" (between 50 and 100): "))
else:
pass
charone_skill = int(raw_input("Enter the skill score for "+str(charone)+" (between 50 and 100): "))
while charone_skill > 100 or charone_skill < 50:
print "That number is not between 50-100"
charone_skill = int(raw_input("Enter the skill score for "+str(charone)+" (between 50 and 100): "))
else:
pass
time.sleep(1.0)
chartwo_strength = int(raw_input("\nEnter the strength score for "+str(chartwo)+" (between 50 and 100): "))
while chartwo_strength > 100 or chartwo_strength < 50:
print "That number is not between 50-100"
chartwo_strength = int(raw_input("\n Enter the strength score for "+str(chartwo)+" (between 50 and 100): "))
else:
pass
chartwo_skill = int(raw_input("Enter the skill score for "+str(chartwo)+" (between 50 and 100): "))
while chartwo_skill > 100 or chartwo_skill < 50:
print "That number is not between 50-100"
chartwo_skill = int(raw_input("Enter the skill score for "+str(chartwo)+" (between 50 and 100): "))
else:
pass
time.sleep(2)
print "\nCharacter 1:",charone
print "Strength:",charone_strength
print "Skill:",charone_skill
time.sleep(1)
print "\nCharacter 2:",chartwo
print "Strength:",chartwo_strength
print "Skill:",chartwo_skill
time.sleep(1)
while charone_strength != 0 or chartwo_strength != 0:
ent = raw_input("Press Enter to roll! ")
mods()
diceroll(charone,chartwo)
battle(charone_strength, chartwo_strength, charone_skill, chartwo_skill, str_mod, skl_mod)
else:
play = raw_input("\nWould you like to play again?")
if play in ["yes","y","Yes","Y"]:
execfile("gcse.py")
else:
print "Goodbye"
This code is an excellent example of how not to program:
heavy use of global variables
multiple variables with very similar names (ie charone_strength, charone_str)
reuse of names in different contexts (in global scope, str_mod is a function, but in function battle it is supposed to be an integer
Your immediate problem: in line 182, you call
battle(charone_strength, chartwo_strength, charone_skill, chartwo_skill, str_mod, skl_mod)
which should be
battle(charone_strength, chartwo_strength, charone_skill, chartwo_skill, strength_mod, skill_mod)
but is confused because in the function strength_mod is referred to as str_mod.
Here is a greatly cleaned-up version. (Further suggestions for improvement are welcome).
from __future__ import division, print_function
from random import randint
import sys
from time import sleep
# Python 2/3 compatibility shim
if sys.hexversion < 0x3000000:
# Python 2.x
inp = raw_input
rng = xrange
else:
# Python 3.x
inp = input
rng = range
PRINT_DELAY = 0.02
PAUSE_DELAY = 0.2
TF_VALUES = {
'y': True, 'yes': True, 't': True, '': True,
'n': False, 'no': False, 'f': False
}
def get_int(prompt="Enter an integer: ", lo=None, hi=None):
while True:
try:
i = int(inp(prompt))
if (lo is None or lo <= i) and (hi is None or i <= hi):
return i
except ValueError:
pass
def get_tf(prompt="Yes or no? ", tf_values=TF_VALUES):
while True:
s = inp(prompt).strip().lower()
tf = tf_values.get(s, None)
if tf is not None:
return tf
def pause(delay=PAUSE_DELAY):
sleep(delay)
def roll(die_sides=6):
return randint(1, die_sides)
def slow_print(s, delay=PRINT_DELAY):
for ch in s:
print(ch, end='', flush=True)
sleep(delay)
print('') # end of line
def wait_for_enter(prompt):
inp(prompt)
class Fighter:
#classmethod
def get_fighter(cls, prompt):
print(prompt)
name = inp ("Name: ")
health = get_int("Health: (50-100) ", 50, 100)
skill = get_int("Skill: (50-100) ", 50, 100)
return cls(name, health, skill)
def __init__(self, name, health, skill):
self.name = name
self.health = health
self.skill = skill
def is_alive(self):
return self.health > 0
def health_mod(self, other_fighter):
delta = abs(self.health - other_fighter.health)
return int(delta / 5)
def skill_mod(self, other_fighter):
delta = abs(self.skill - other_fighter.skill)
return int(delta / 5)
def attack(self, other_fighter):
wait_for_enter("Hit Enter to fight!")
# figure out mod values
health_mod = self.health_mod(other_fighter)
skill_mod = self.skill_mod (other_fighter)
self_roll = roll()
other_roll = roll()
slow_print(
"Health mod: {} Skill mod: {} {} rolls {} {} rolls {}"
.format(
health_mod, skill_mod,
self.name, self_roll,
other_fighter.name, other_roll
)
)
# figure out who won this round
if self_roll == other_roll:
print("Draw! No damage done.")
else:
winner, loser = (self, other_fighter) if self_roll > other_roll else (other_fighter, self)
print("{} hits {}!".format(winner.name, loser.name))
winner.health += health_mod
winner.skill += skill_mod
loser.health -= health_mod
loser.skill -= skill_mod
# show results
print('')
print(self)
print(other_fighter)
print('')
def __str__(self):
return "{}: health {}, skill {}".format(self.name, max(self.health, 0), max(self.skill, 0))
def fight():
f1 = Fighter.get_fighter("\nFirst fighter:")
pause()
f2 = Fighter.get_fighter("\nSecond fighter:")
pause()
slow_print("\n{} encounters {}\nBattle Initiated!".format(f1.name, f2.name))
while f1.is_alive() and f2.is_alive():
f1.attack(f2)
winner, loser = (f1, f2) if f1.is_alive() else (f2, f1)
print("{} has died; {} wins!".format(loser.name, winner.name))
def main():
while True:
fight()
if not get_tf("Would you like to play again? (Y/n)"):
print("Goodbye!")
break
if __name__=="__main__":
main()

Categories

Resources