Cannot find error: calling items from libraries - python

I am having an issue with calling variables to add while within a definition which is in the class 'mountain'. It runs the error:
AttributeError: 'function' object has no attribute 'picture'
Here is the code for it:
import random
class currencies:
film = 5
class pictures:
picture = {"m_goat": 0, "b_eagle": 0, "marmot": 0, "r_snake": 0, "m_lion": 0, "b_dragon": 0, "vulture": 0}
class location:
city = True
shop = False
mountains = False
desert = False
class mountain:
#Travel to mountains
def travel_m():
print("You climb to the top of a tall mountain")
location.mountains = True
animals = ["mountain goat", "bald eagle", "marmot", "rattlesnake", "mountain lion"]
animal_pics = ["m_goat", "b_eagle", "marmot", "r_snake", "m_lion"]
if 1 == 1: #for simplicity I changed this to a non random number
animal = random.randint(0, 4)
str_animal = animals[animal]
ans = input("You see a wild " + str_animal + ". Would you like to take a photo? (y/n) \n")
if ans == "y" and currencies.film == 0:
print("You cannot take a picture of this animal because you are out of film")
elif ans == "y":
currencies.film -= 1
pictures.picture[animal_pics] = pictures.picture[animal_pics] + 1 #this is the line with the error
print("You took a picture of the animal")
elif ans == "n":
print("The animal was left unbothered")
else:
print("I do not recognize that command")
def pictures():
print("You have " + str(pictures.pictures['m_goat']) + " picture(s) of mountain goats")
print("You have " + str(pictures.pictures['b_eagle']) + " picture(s) of bald eagles")
print("You have " + str(pictures.pictures['marmot']) + " picture(s) of marmots")
print("You have " + str(pictures.pictures['r_snake']) + " picture(s) of rattlesnakes")
print("You have " + str(pictures.pictures['m_lion']) + " picture(s) of mountain lions")
mountain.travel_m()
Thank you for any help at all. I'm just learning the language but neither me nor my teacher could find an answer for it online. If it's something stupid, please do say

When you do:
def pictures():
you're redefining the variable pictures. It now names the function, not the class that was defined earlier.
Give the function a name that doesn't conflict with the class, e.g.
def show_pictures():
Also, in the last function you use pictures.pictures. That should be pictures.picture.
After you fix those, this line is wrong:
pictures.picture[animal_pics] = pictures.picture[animal_pics] + 1
animal_pics is a list, you can't use it as a dictionary key. I think you meant:
pictures.picture[str_animal] += 1

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

if, elif & !=, == boolean operations only return "false" with inputs

I am creating an Among Us ripoff (for fun!) and the while True & if/elif/else statements will only return false (not An Impostor) with the inputs. I had created a list for the names and 2 random elements from the list will be chosen as An Impostor. However, whenever I input a name that is The Impostor, it will only return
(player) was not An Impostor.
Here is my code;
import sys, time, random
names = ["player1", "player2", "player3", "player4", "player5", "player6", "player7", "player8", "player9", "player10"]
print("Players: ")
for x in names:
print(x)
print('—————————————————————————')
impostor1 = random.choice(names)
impostor2 = random.choice(names)
crewmates = 8
impostors = 2
tries = 6
while True:
talk = input("Guess who The Impostor(s) are. " + str(crewmates) + " Crewmates are left. " + str(impostors) + " Impostors are left. You have " + str(tries) + " tries left.")
if talk in names:
print(talk + " was voted for.")
time.sleep(0.1)
if talk != impostor1 or talk != impostor2:
notimp = talk + " was not An Impostor. "
names.remove(talk)
for y in notimp:
sys.stdout.write(y)
sys.stdout.flush()
time.sleep(0.05)
crewmates -= 1
tries -= 1
elif talk == impostor1 or talk == impostor2:
wasimp = talk + " was An Impostor. "
names.remove(talk)
for v in wasimp:
sys.stdout.write(v)
sys.stdout.flush()
time.sleep(0.1)
impostors -= 1
else:
print("That player was either ejected or is not a valid player.")
However, whenever I put the Impostor in the input, it says it isn't An Impostor?
I think this line is the source of the problem:
if talk != impostor1 or talk != impostor2:
Let's say impostor1 is player1 and impostor2 is player2 and someone input in player1, according to Python Boolean expression operator or that if statement will evaluate like this:
if player1 != impostor1 evaluated to False because player1 is indeed equals to impostor1.
So far so good, but because the first test is a False, Python simply evaluates and returns the right side operand which may be either True or False. In your case Python will evaluate if talk != impostor2 and return True, thereafter executes the nested block.

How can I condense this simple python program to make it more efficient?

This is just a simple game I tried to put together that asks you a couple questions and then automatically formats a new passcode out of the answers.
Since I am a beginner I'd like to know of some techniques I could use that would increase the efficiency of this code, and maybe remove the crazy amount of functions I've declared. Thank You!
minimum = 3
maximum = 10
name = input("What is your name? ")
def nameInput():
if len(name) < minimum:
print("Name is too small")
return nameInput()
elif len(name) > maximum:
print("Name is too large")
return nameInput()
nameInput()
food = input("What is your favorite food? ")
def foodInput():
if len(food) < minimum:
print("Enter a food name longer than " + (food))
return foodInput()
elif len(food) > maximum:
print("Enter a food name shorter than " + (food))
return foodInput()
foodInput()
birthday = input("What is your date of birth? (mmddyyyy) ")
nameIndex = name[0:2]
foodIndex = food[2: ]
birthIndex = birthday[0:3]
passcode = nameIndex + foodIndex + birthIndex
print("Your password is " + passcode)
If you're after brevity, try to use a single function multiple times rather than multiple functions a single time
def get_input(variable_name, min_size, max_size, begin, end):
data = input("What is your {}? ".format(variable_name))
if len(data) < min_size:
raise ValueError('{} is too small'.format(variable_name.capitalize()))
elif len(data) > max_size:
raise ValueError('{} is too big'.format(variable_name.capitalize()))
return data[begin:end]
name_index = get_input("name", 3, 10, 0, 2)
food_index = get_input("food", 3, 10, 2, 100)
birth_index = get_input("date of birth (mmddyyyy)", 3, 10, 0, 3)
passcode = name_index + food_index + birth_index
print("Your passcode is", passcode)

Python 2.7.3 Code Loops Without a While Loop

I am relatively new to programming, so don't be surprised if there are some minor hiccups in the code, but the problem that is happening is that this code seems to loop itself, the whole thing and I don't understand why. I looked at the actual code that runs this function but it seemed fine. So I cannot find any error in this code that makes it loop itself. (If the problem isn't in this code then the looping code it beneath it)
def thebeast(yourhp):
foe = "Thisisirrelevant"
enemy = int(random.randint(1,4))
if enemy == 1:
foe = "skeleton"
elif enemy == 2:
foe = "man with crazy eyes"
else:
foe = "dog, a big and scary dog"
monsteract = 1
dmg = 0
print "-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~"
time.sleep(0.1)
print " C O M B A T"
time.sleep(0.1)
print "-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~"
time.sleep(0.1)
print "You encounter a " + foe
time.sleep(0.5)
while monsteract == 1:
comb = str(input("What do you do to the " + foe + "?" + " Do you feel like jabbing it or stabbing it?"))
if comb in ["s", "S", "Stab", "STAB", "stab"]:
if spear == 1:
dmg = int(random.randint(1,4))
elif sword == 1:
dmg = int(random.randint(1,3))
else:
dmg = int(random.randint(1,5))
elif comb in ["j", "J", "Jab", "JAB", "jab"]:
if spear == 1:
dmg = int(random.randint(1,3))
elif sword == 1:
dmg = int(random.randint(1,4))
else:
dmg = int(random.randint(1,5))
if dmg == 1:
print "You slay the " + foe + " with graceful ease"
time.sleep(0.5)
monsteract = 0
else:
enemydmg = int(random.randint(1,3))
print "The " + foe + " strikes you for " + str(enemydmg) + " damage"
time.sleep(0.3)
print "That didn't work out as planned, but you pull yourself together and prepare to strike the " + foe
time.sleep(0.3)
yourhp = yourhp - enemydmg
if yourhp < 0:
yourhp = 0
print "You have " + str(yourhp) + " health left"
time.sleep(0.3)
if yourhp < 1:
print "The " + foe + " has slain you, well done, you're dead, on the bright side the innocent "
print foe + " is still alive! Every life counts, even that of a " + foe + "."
monsteract = 0
return thebeast(yourhp)
Looping code:
def randomevents(yourhp):
turn = 10
while turn > 0:
time.sleep(0.1)
happening = int(random.randint(1,6))
time.sleep(0.1)
if yourhp < 1:
turn = 0
print "You managed to escape the dungeon, by dying that is"
elif happening == 1:
turn = turn - 1
thebeast(yourhp)
elif happening == 2:
item(sword, spear)
turn = turn - 1
elif happening in [3, 4, 5]:
friend()
turn = turn - 1
print "Well done! You escaped the dungeon! (Either by running out of it, or by having your soul sent to another world)"
useless = str(input("Are you satsified with yourself?: "))
Thank you!
Look at your return statement at the end of thebeast. At the end of the function, you call the function again! Since this happens every time you call it, you will never stop calling it (until you hit the maximum recursion depth). Considering that you don't capture the return value of thebeast in randomevents, you should consider it not returning anything.

'type' object is not subsrcriptable python

i cant tell what this error is telling me it says the error is on line 64 of this code if possible can you please check too see if my code has additional errors thnx so much guys i tried multiple things and couldn't get it to work.
Traceback (most recent call last):
File "C:\Users\AdamFeffer\triviacrack.py", line 93, in <module>
QnA2()
File "C:\Users\AdamFeffer\triviacrack.py", line 64, in QnA2
if uanswer == quest[whichq].rA:
TypeError: 'type' object is not subscriptable
import random
import time
# Flase = playerone true player 2
wt = False
score = 0
kg = True
kgt = True
playerov = False
class playerone(object):
def __init__(self, name, score, victory):
self.name = name
self.score = score
self.victory = victory
class playertwo(object):
def __init__(self, name, score, victory):
self.name = name
self.score = score
self.victory = victory
class quest(object):
def __init__(self, q, a1, a2, a3, a4, rA):
self.question = q
self.answer1 = a1
self.answer2 = a2
self.answer3 = a3
self.answer4 = a4
self.realanswer = rA
### Questions ###
q1 = quest("The largest artery in the human body helps carry blood from the heart throughout the body. What is it?","Aorta", "your mom haha lol", "Jugular","Borta", 1)
q2 = quest("In the year 1900 in the U.S. what were the most popular first names given to boy and girl babies?", "William and Elizabeth", "Joseph and Catherine", "John and Mary","George and Anne", 3)
q3 = quest("When did the Liberty Bell get its name?", "when it was made, in 1701", "when it rang on July 4, 1776", "in the 19th century, when it became a symbol of the abolition of slavery", " none of the above", 3)
#################
#questoin arrays
questions = [q1, q2, q3]
qt = ["science", "history", "sports", "entertainment", "art"]
def QnA():
global kg
global oneplayer
global score
global player
p = player
whichq = random.randint(0, 4)
print(questions[whichq].question)
print(questions[whichq].answer1 + " (1)")
print(questions[whichq].answer2 + " (2)")
print(questions[whichq].answer3 + " (3)")
print(questions[whichq].answer4 + " (4)")
uanswer = int(input("answer "))
if uanswer == quest[whichq].realanswer:
score = score + 1
print ("YA NEXT QUESTION")
else:
print(p + "you didn't get it right")
kg = False
def QnA2():
global kgt
global wt
whichq = random.randint(0, 4)
print(questions[whichq].question)
print(questions[whichq].answer1 + " (1)")
print(questions[whichq].answer2 + " (2)")
print(questions[whichq].answer3 + " (3)")
print(questions[whichq].answer4 + " (4)")
uanswer = int(input("answer "))
if uanswer == quest[whichq].rA:
if wt == false:
playerone.score = playerone.score + 1
else:
playertwo.score = playertwo.score + 1
if wt == True:
wt = False
else:
wt = True
def timer():
timer = 60
while timer > 0:
print (timer)
timer = timer - 1
time.sleep(1)
print ("times up!!")
oot = int(input("(1) one player sudden death or (2) 2 player: "))
if oot == 1:
oneplayer = True
player = input("player name: ")
while kg == True:
QnA()
print("sorry your score was " + (score) + "gg")
else:
playero = input("player 1 name: ")
playert = input("player 2 name: ")
playerone = playerone(playero, 0, False)
playertwo = playertwo(playert, 0, False)
while kgt == True:
QnA2()
solution
Line 64: if uanswer == questions[whichq].realanswer:
Whats wrong
You are attempting to use quest which is a class instead of the questions list. quest can not be subscripted with [] but questions can, because it is a list.
In addition, you are trying to use rA which is an argument to the __init__ function. You can not use this argument outside of __init__. Instead you need to use the member variable realanswer :)

Categories

Resources