Class Attributes not updating in program - python

I am fairly new to coding on Python. In my code, I am trying to change the myPlayer.hp and myPlayer.sp values based on what the myPlayer.job is. But, for some reason, regardless of job, the HP and SP values are still 0 when I check them in the program. If you know how to change them, please let me know and thank you.
Here is the code that deals with my question:
class player:
def __init__(self):
self.name = ''
self.job = ''
self.hp = 0
self.sp = 0
self.pwr = 0
self.res = 0
self.agi = 0
self.smr = 0
self.wll = 0
self.status_effects = []
self.location = 'b2'
self.game_over = False
myPlayer = player()
def main_game_loop():
while myPlayer.game_over is False:
prompt()
def setup_game():
os.system('cls')
question1 = "Hello, what's your name?\n"
for character in question1:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.05)
player_name = input("> ")
myPlayer.name = player_name
question2 = "Hello, what role do you want to play?\n"
question2added = "(You can play as a warrior, mage, or priest)\n"
for character in question2:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.05)
for character in question2added:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.01)
player_job = input("> ")
valid_jobs = ['warrior', 'mage', 'priest']
if player_job.lower() in valid_jobs:
myPlayer.job = player_job
print("You are now a " + player_job + "!\n")
while player_job.lower() not in valid_jobs:
player_job = input("> ")
if player_job.lower() in valid_jobs:
myPlayer.job = player_job
print("You are now a " + player_job + "!\n")
if myPlayer.job == 'warrior':
myPlayer.hp = 25
myPlayer.sp = 0
elif myPlayer.job == 'mage':
myPlayer.hp = 15
myPlayer.sp = 20
elif myPlayer.job == 'priest':
myPlayer.hp = 20
myPlayer.sp = 15

Your code isn't necessarily incorrect, but there is a good chance for an error when the player enters their job.
You have the following code:
if player_job.lower() in valid_jobs:
That means that if the player enters Warrior you understand that they meant warrior. That is good. But when you assign the player's job you do the following:
myPlayer.job = player_job
That can cause a problem, since you aren't calling lower() on the job.
Instead, you likely want:
myPlayer.job = player_job.lower()
That way, when you look at the player's job to assign sp and hp it will match the lowercase strings you are comparing it to.

Related

How do I import my own object in vs studio code?

I'm trying to import the Human object I created for my contact book program and im doing it in VS Studio Code but it gives me an error:
Import "Human" could not be resolved
I tried to make the program in pycharm instead and it imported just fine and I even finished the program. And while looking around for a solution for the VS Studio Code version, I found some stuff like adding
"python.autoComplete.extraPaths": ["./**"],
to my settings.json and I did and a few other things i found on google, but it nothing helped.
VS Studio Code:
from Human import Human
#from Contact_Book_Project.Human import Human # auto generated, Not sure how it is different but i do have these 2 classes in a folder called Contact_Book_Project
book = []
def main():
while (True):
choice = int(input("Press 1 to add someone to your Contact Book\n2 to remove someone from the book\n3 to find someone\n4 to list everyone\n5 to exit\n"))
if (choice == 5):
break
elif (choice == 1):
name = input("Name: ")
phoneNum = input("Phone Number: ")
address = input("Address: ")
person = Human(name, phoneNum, address)
addPerson(person)
def addPerson(person):
book.append(person)
if __name__ == "__main__":
main()
class Human:
def __init__(self, name, phone_Number, address):
self.Name = name
self.Phone_Number = phone_Number
self.Address = address
def getName(self):
return self.Name
def getPhoneNumber(self):
return self.Phone_Number
def getAddress(self):
return self.Address
PyCharm Code:
from Human import Human
book = []
def main():
while (True):
try:
choice = int(input(
"Press 1 to add someone to your Contact Book\n2 to remove someone from the book\n3 to find someone\n4 to "
"list everyone\n5 to exit\n"))
if (choice == 5):
break
elif (choice == 1):
name = input("Name: ")
phoneNum = input("Phone Number: ")
address = input("Address: ")
person = Human(name, phoneNum, address)
addPerson(person)
elif (choice == 2):
name = input("Enter name of person to remove: ")
temp = 0
for i in book:
if i.getName() == name:
book.pop(temp)
print(i.getName() + " removed.")
break
temp += 1
# elif (choice == 3):
# name = input("Enter name of person to check if they are in your contact book and retrieve their "
# "information: ")
#
# if name in book:
# temp = book.__getitem__(name)
# print(
# "Name: " + temp.getName() + "\nPhone Number: " + temp.getPhoneNumber() + "\nAddress: " + temp.getAddress())
# else:
# print(name + " does not exist in your contact book.")
elif (choice == 4):
for p in book:
print(
"Name: " + p.getName() + "\nPhone Number: " + p.getPhoneNumber() + "\nAddress: " + p.getAddress() + "\n")
except ValueError:
print("\nInvalid input.\n")
def addPerson(person):
book.append(person)
if __name__ == '__main__':
main()
both are using the same Human class. How can I fix this? Why is it throwing an error in VS Studio but work in Pycharm?
Maybe try directing VS Code to the exact location of the Human module:
import sys
sys.path.append('file path to Human.py') # Add file path to 'Human.py' here
from Human import Human

method not working when i call it from another method for random name gen in python

I am creating a random name generator using OOP in python however i am very new to this concept which is why i am having so difficulties with accessing methods in other methods. I read a post on stack overflow which said to call a method inside another method in a class, you must add self.funcname(param) however i have already done this and it still does not work
class Rndm_nme_gen:
def __init__(self):
print("THE RANDOM NAME GENERATOR")
self.value = ""
self.range = 5
self.counter = 0
self.loop = True
self.names = []
self.loop2 = True
self.take_input()
def take_input(self):
while self.loop:
user_input = input("ENTER A NAME: ")
self.num_check(user_input)
if self.value == "true":
print("INVALID NAME")
loop = True
elif self.value == "false":
self.counter += 1
self.names.append(user_input)
if self.counter == 5:
self.loop = False
self.genname()
#i am trying to call this function but it is not working as i hoped it would
def num_check(self, string):
self.string = string
for char in self.string:
if char.isdigit():
self.value = "true"
else:
self.value = "false"
def genname(self):
while self.loop:
gen = input("TYPE ENTER TO GENERATE A NAME OR TYPE 'q' TO QUIT").strip().lower()
if gen == " " or gen == "":
num = random.randint(0, 5)
print("NAME : " + str(self.names[num]))
loop == True
elif gen == 'q':
quit()
else:
print("UNKNOWN COMMAND")
loop = True
user1 = Rndm_nme_gen()
In the initialisation method, i called the take_input function so it automatically runs and from that function, i attempted to run the code from the genname function however the program would simply end
If you would like to run the code to see how it works, feel free to do so
Expected output:
ENTER NAME FDSF
ENTER NAME dfsd
ENTER NAME sdfds
ENTER NAME sfdff
ENTER NAME sfdf
TYPE ENTER TO GENERATE A NAME OR TYPE 'q' TO QUIT
it does not say TYPE ENTER TO GENERATE A NAME OR TYPE 'q' TO QUIT when i run the program

Show Output inside Tkinter GUI

I am trying to print the output answer to my GUI in Tkinter and I can not seem to see how it is possible! If anyone has any tips please let me know.
I know its somewhere along the lines of this but I cannot seem to crack it!
DisplayFearFactor.configure( text = " computers FearFactor: " + str(computersCardFearFactor))
DisplayFearFactor.place(bordermode=OUTSIDE, height=60, width=200,x=100,y=100)
here is the full section of code:
def compareFearFactor():
human = []
computer = []
if len(cards) > 0:
human.append(cards.pop(0))
computer.append(cards.pop(0))
humanCard = human.pop(0) if human else None
computersCard = computer.pop(0) if computer else None
print("computers Fear Factor:", computersCard.FearFactor)
Draw = (humanCard.FearFactor == computersCard.FearFactor)
Win = (humanCard.FearFactor > computersCard.FearFactor)
DisplayFearFactor.configure( text = " computers FearFactor: " + str(computersCardFearFactor))
DisplayFearFactor.place(bordermode=OUTSIDE, height=60, width=200,x=100,y=100)
computercardshow = ImageTk.PhotoImage(computersCard.image)
Comp = Label(image = computercardshow)
Comp.configure(image = computercardshow)
Comp.place(x=800,y=50)
Comp.image = computercardshow
if Draw:
print("It's a tie!")
human.append(humanCard)
computer.append(computersCard)
elif Win:
print("You win this hand!")
cards.append(humanCard)
cards.append(computersCard)
playerTurn = True
else:
print("You lose this hand!")
computer.append(computersCard)
computer.append(humanCard)
playerTurn = False

Python(3.6)-How can I create a demo program that will create an object from the VotingMachine class I have created?

This is what I have so far. I have created this class:
class VotingMachine :
def __init__(self):
self._voteCount = 0
self._totalVote = 0
def DemVote(self, vote):
self._voteDemCount = self._voteDemCount + 1
self._totalDemVote = self._totalDemVote + vote
def RepVote(self, vote):
self._voteRepCount = self._voteRepCount + 1
self._totalRepVote = self._totalRepVote + 1
def getDemTally(self):
return self._totalDemVote
def getRepTally(self):
return self._totalRepVote
def clear(self):
self._voteCount = 0
self._totalVote = 0
and this is what I have so far for the demo program.
from votingmachine import VotingMachine
print("Presidential Election")
print("---------------------")
print("R -- Republican")
print("D -- Democrat")
print("X -- Stop")
userInput = input("Enter your vote (R/D/X): ")
My instructions for this are as follows-
Create a voteDemo program that will create one object from the VotingMachine class. The voteDemo program should display a menu, allow the user to enter multiple votes until an X is entered, then show the tally of the Democratic and Republican votes, and also show which candidate won the election.
Make sure to consider that the election could end in a tie.
I know I have probably missed something really simple, but I am a complete beginner at this and do not understand how to go about calling the methods to be able to display a menu, etc. I would really appreciate it if someone would take the time to explain what I need to do to finish this up.
To complete this assignment you need to know how to:
Compare strings
first = "a"
second = "b"
third = "b"
print(first == second) # prints False
print(second == third) # prints True
Use a while loop. For example:
looping = True
while looping:
userInput = input("Press X to leave the loop")
if userInput == "X":
looping = False
print("Left the while loop")
Call methods
class Animal:
def __init__(self):
print("Creating animal")
def make_sound(self, sound):
print("Making a sound...")
print(sound)
# Create an instance of the Animal class.
animal = Animal()
# Call a method. The self parameter implicitly refers to the instance, animal.
animal.make_sound("meow")
You can solve the problem by combining these tools.
Here's a simple loop to do what you want:
userInput = ''
voting_machine = VotingMachine()
while userInput != 'x':
userInput = input("Enter your vote (R/D/X): ").lower()
if userInput == 'd':
pass
elif userInput == 'r':
pass
elif userInput == 'x':
break
else:
print("Wrong input! Try again!")
print(voting_machine.getDemTally())
print(voting_machine.getRepTally())
print("Bye!")
Actually, the definition of your class, has some errors, you didn't define attributes like _voteRepCount before using them.
You can instantiate (create a instance of) a class in python with the following code: machine = VotingMachine().
You might also want to check the code in your DemVote and RepVote methods. self._voteDemCount and self._voteRepCount need to be initialized in your __init__ function and the methods do different things with vote.
Instantiate a voting machine: machine = VotingMachine().
Then run a loop, asking for a vote, feeding it to the machine, and showing the tallies in each iteration.
class VotingMachine:
def __init__(self):
self._totalVote = 0
self._voteDemCount = 0
self._voteRepCount = 0
def demVote(self):
self._voteDemCount += 1
self._totalVote += 1
def repVote(self):
self._voteRepCount += 1
self._totalVote += 1
def getDemTally(self):
return self._voteDemCount
def getRepTally(self):
return self._voteRepCount
def getTally(self):
return self._totalVote
def clear(self):
self._totalVote = 0
voteDemo
from VotingMachine import *
election = VotingMachine()
print("Presidential Election")
vote = ''
while vote != 'X':
print("---------------------")
print("R -- Republican")
print("D -- Democrat")
print("X -- Stop")
vote = input("Enter your vote (R/D/X): ")
if vote == 'X':
print("Tally votes: "+str(election.getTally()))
if election.getDemTally() > election.getRepTally():
print("Democrat WIN")
elif election.getDemTally() < election.getRepTally():
print("Republican WIN")
else:
print("Draw")
print("(D:"+str(election.getDemTally())+" , R:"+str(election.getRepTally())+")")
elif vote == 'R':
election.repVote()
elif vote == 'D':
election.demVote()
else:
print("Vote invalid!")

class in python 3 not working as expected

I have started work on a program that will allow a user to easily take pictures with the raspberry pi camera. The problem I am having is the class I have created does not do what I expected. When the code is run there is no output, what should happen is the Picture_Name_Settings function should be run. I'm still new to classes so I am probably missing something simple and the tutorials I have read online do not give a solution to my problem. Below is my code:
import picamera, time
class CameraController:
def _init_(self):
pass
def Picture_Name_Settings(self, user_name, automatic_name, name_setting):
pic_name = input("To name the image input N\nTo use automatic naming input A ")
pic_name = pic_name.upper()
if pic_name == "N":
user_name = input("Please enter the name of what you want your image to be called ")
name_setting = 1
if pic_name == "A":
current_time = (time.strftime("%H:%M:%S"))
current_date = (time.strftime("%d:%m:%Y"))
automatic_name = "".join(("Image taken at ", current_time, " on the ", current_date, ".jpg"))
name_setting = 2
def Camera_Capture(self):
self.Picture_Name_Settings(user_name, automatic_name, name_settings)
if name_setting == 1:
picture_name = user_name
if name_setting == 2:
picture_name = automatic_name
camera = picamera.PiCamera()
camera.capture(picture_name)
Declare user_name, automatic_name and name_setting variables as instance variables and you should be fine
class CameraController:
def _init_(self):
pass
def Picture_Name_Settings(self):
pic_name = input("To name the image input N\nTo use automatic naming input A ")
pic_name = pic_name.upper()
if pic_name == "N":
self.user_name = input("Please enter the name of what you want your image to be called ")
self.name_setting = 1
if pic_name == "A":
current_time = (time.strftime("%H:%M:%S"))
current_date = (time.strftime("%d:%m:%Y"))
self.automatic_name = "".join(("Image taken at ", current_time, " on the ", current_date, ".jpg"))
self.name_setting = 2
def Camera_Capture(self):
self.Picture_Name_Settings()
if self.name_setting == 1:
picture_name = self.user_name
if self.name_setting == 2:
picture_name = self.automatic_name
camera = picamera.PiCamera()
camera.capture(picture_name)

Categories