I was sitting all week on this and I don't know how to get rid of these global points.
Here I define points.
def init():
global points, hidden_password, hidden_password2, country, used, start_time
points = 0
hidden_password = []
hidden_password2 = []
country = ""
used = []
start_time = datetime.now()
welcome()
choice()
Then it goes to choice() from choice to play_game() than to guessing_capital() and here I use points for the first time, and the program is working until var points reach 5.
def guessing_capital(password, used, user_name):
global points
while points < 5:
checking(password, user_name)
time.sleep(1)
print("\n Letters You failed guessing: ", ", ".join(used), end=".\n")
time.sleep(2)
print("\n *** You lost! Sorry, but the GAME is OVER! ***\n")
time.sleep(3)
init()
Then it goes to checking() and from checking it goes to the letter() and then to checking_password() where if the user didn't guess right letter it adds 1 to points and returns it.
def checking_password(number):
global points, hidden_password2, hidden_password
if hidden_password2 == hidden_password:
points += number
time.sleep(1)
print("\n Boo! You have +", number, "penalty points!")
time.sleep(1)
hidden_password2 = hidden_password
if points < 4:
manage_graphics(points)
elif points == 4:
manage_graphics(points)
print(" Hint: It's a capital of " + country + ".")
elif points >= 5:
manage_graphics(5)
return points
Here is a full code if someone wants: https://codeshare.io/aYBAzb
You can use a class to store attributes.
Class Game:
def __init__():
points = 0
self.hidden_password = []
self.hidden_password2 = []
self.country = ""
self.used = []
self.start_time = datetime.now()
self.welcome() # This should be in main function
self.choice() # This should be in main function
def choice(self, ...):
pass
def welcome(self, ...):
pass
def guessing_capital(self, ...):
pass
def checking_password(self, ...):
pass
Related
Im working on a simple poker game just to improve my OOP experience, i ran into an error that might be beyond my knowledge.
The program goes like this, i have a class called Deck() which is of course the deck, a class called player and a class called table. In the player class i have couple of methods but i'm only gonna name what is necessary for the sake of keeping this as short as possible. I have the following methods (in the player class) bet(), call() fold(), all_in() and player_choice(). The first four method i named are all invoked by the player_choice method(). However the problem is in the bet(), all_in() and call method. the following methods looks like this
def all_in(self):
table.table_money += self.money
self.money = 0
print('{} went all in!').format(self.name)
def cal(self, last_bet):
if last_bet > self.money:
while True:
res = input('You dont have enough money to call.\tyou have=> {}\nDo you want to go all in?\ty/n\n>>> ').format(str(self.money))
if res.lower() == 'y':
self.all_in()
break
elif res.lower() == 'n':
self.fold()
break
else:
print('Invalid input. Try again...')
else:
table.table_money += self.money - last_bet
self.money -= last_bet
print('{} called.').format(self.name)
def bet(self, last_bet):
res = int(input('Enter bet below.\t must be over {}\n>>> '.format(str(last_bet))))
table.latest_bet += res
table.table_money += res
self.money -= res
print('{} has bet {}$').format(self.name, str(res))
The problem is that when i call one of these methods and the method is in the process of subtracting the players money and adding it to the table.table_money() (as shown in the code above) thats when i get a NameError saying 'table' is not defined.
here is the Table() class:
class Table():
def __init__(self):
self.table_money = 0
self.latest_bet = 0
if players == '':
print('Table is empty!')
else:
print(str(len(players)) + ' players on the table.')
def list_table(self):
for i in players:
print(i.__str__())
I know what you might be thinking that i typed table instead of Table. but he is he thing, when i run the code in the main() function i initialize a Table object into a variable called table which is supposed to be the same variable as the one being called by the Player() class methods.
Here is a short view of the main() function:
def main():
while welcome():
rond = 1
while rond <= 5:
table = Table()
deck = Deck()
deck.deal()
user = players[0]
user.list_hand()
user.player_choice(table.latest_bet)
break
break
the structure of the problem is like this:
first i define the player class.
2nd i define the table.
3rd i define main().
This is the output of the error:
Traceback (most recent call last):
File "C:/Users/Alex/PycharmProjects/GUI_prject/venv/Lib/site-
packages/resors2.py", line 161, in <module>
main()
File "C:/Users/Alex/PycharmProjects/GUI_prject/venv/Lib/site-
packages/resors2.py", line 157, in main
user.player_choice(table.latest_bet)
File "C:/Users/Alex/PycharmProjects/GUI_prject/venv/Lib/site-
packages/resors2.py", line 38, in player_choice
self.cal(last_bet)
File "C:/Users/Alex/PycharmProjects/GUI_prject/venv/Lib/site-
packages/resors2.py", line 71, in cal
table.table_money += self.money - last_bet
NameError: name 'table' is not defined
If i didn't include enough details about the program let me know i will share more if needed. I apologize if i didn't explain all this in the best way and if the post is too long. I am more then grateful for any comment.
Thanks for reading.
Full code:
import random as r
suits = ['H','C','S','D']
values = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
players = []
class Card():
def __init__(self, suit, value):
self.suit = suit
self.value = value
def valu(self):
return self.value + self.suit
class Player():
def __init__(self, name, money):
global players
self.name = name
self.money = money
print(self.name+ ' joined the table!')
players.append(self)
self.hand = []
def __str__(self):
return '{}: {}'.format(self.name, str(self.money))
def add_to_hand(self, cards):
self.hand.append(cards)
def list_hand(self):
for i in self.hand:
print(i)
def player_choice(self, last_bet):
while True:
resu = input('c - Call | b - bet | a - all in | f - fold\n>>>
').lower()
if resu == 'c':
self.cal(last_bet)
break
elif resu == 'b':
self.bet(last_bet)
break
elif resu == 'a':
self.all_in()
break
elif resu == 'f':
self.fold()
break
else:
print('Invalid input. Try again...')
def all_in(self):
table.table_money += self.money
self.money = 0
print('{} went all in!').format(self.name)
def cal(self, last_bet):
if last_bet > self.money:
while True:
res = input('You dont have enough money to call.\tyou have=> {}\nDo you want to go all in?\ty/n\n>>> ').format(str(self.money))
if res.lower() == 'y':
self.all_in()
break
elif res.lower() == 'n':
self.fold()
break
else:
print('Invalid input. Try again...')
else:
table.table_money += self.money - last_bet
self.money -= last_bet
print('{} called.').format(self.name)
def bet(self, last_bet):
res = int(input('Enter bet below.\t must be over {}\n>>> '.format(str(last_bet))))
table.latest_bet += res
table.table_money += res
self.money -= res
print('{} has bet {}$').format(self.name, str(res))
def fold(self):
players.remove(self)
print('{} has folded.').format(self.name)
class Table():
def __init__(self):
self.table_money = 0
self.latest_bet = 0
if players == '':
print('Table is empty!')
else:
print(str(len(players)) + ' players on the table.')
def list_table(self):
for i in players:
print(i.__str__())
class Deck():
def __init__(self):
self.cards = []
for suit in suits:
for value in values:
self.cards.append(Card(suit, value).valu())
r.shuffle(self.cards)
def show_deck(self):
return self.cards
def shuffle_d(self):
r.shuffle(self.cards)
def deal(self):
for p in players:
for c in range(0, 1):
p.add_to_hand((self.cards.pop(), self.cards.pop()))
#The welcome function is not a method for any of the classes above
def welcome():
global players
print('''
Welcome to the poker table.
q - Quit
s - Take a seat
''')
res = ''
while res != 'q' or 's':
res = input('>>> ')
if res == 'q':
return False
elif res == 's':
name = input('Enter your name: ')
money = int(input('Enter how much money you wish to have(max 500$): '))
Player(name, money)
return True
else:
print('Invalid input. q - Quit\ts - Take a seat')
def main():
while welcome():
rond = 1
while rond <= 5:
table = Table()
deck = Deck()
deck.deal()
user = players[0]
user.list_hand()
user.player_choice(table.latest_bet)
break
break
main()
Try to ignore the miss
tables is a local variable in the main() function. You should add it as an attribute of the player class.
def go_to_table(self, table):
self.table = table
Then all the methods should use self.table instead of just table. In main, you do:
def main():
while welcome():
rond = 1
while rond <= 5:
table = Table()
deck = Deck()
deck.deal()
user = players[0]
user.go_to_table(table)
user.list_hand()
user.player_choice(table.latest_bet)
break
break
You're confusion a type (like Table) with a single instance of an object of that type like table after table = Table().
The line table = Table() creates a new object of type Table and assigns it to the variable table, so you can refer to it later. However, this variable is defined inside of the function main and is only available there. Inside of the method cal (which I assume is a misspelling of call), there is no table, since you might have many games going on and it doesn't know what table it belongs to.
Since the player is sitting at a specific table, it makes sense to keep a reference to that Table inside the Player, and to assign it in its constructor with something like self.table = table. Then you can reference it from the call method using self.table.
class Player:
def __init__(self, table):
self.table = table
def call(self):
self.table.money += 1
class Table:
def __init__(self):
self.money = 0
table = Table()
player = Player(table)
player.call()
print(table.money)
I have the following code:
import options
import random
class Player():
def __init__(self):
self.name = None
self.gold = 100
self.maxhealth = 100
self.health = self.maxhealth
self.level = 1
self.exp = 0
self.levelUp = 50
self.gainedexp = self.levelUp - self.exp
def get_name(self):
self.name = input("Hey there, traveller! What's your name?\n~~>")
print("Since you are new around here, 100 gold doubloons have been given to you, {}!".format(self.name))
def gold_counter(self):
print("You currently have {} gold!".format(player.gold))
class Dragon():
def __init__(self):
self.name = "Dragon"
self.dropgold = random.randint(13,20)
self.minexp = int(15 * round(player.level * 1.5))
self.maxexp = int(30 * round(player.level * 1.5))
self.expgain = random.randint({}, {}.format(self.minexp, self.maxexp))
self.maxhealth = 80
self.health = self.maxhealth
def intro():
wrong_input = 0
nar_name = "Narrator"
print("{}: Uhhhm...".format(nar_name))
print("{}: Let me check my list...".format(nar_name))
print("{0}: Ah! Yes! {1}, that's right. I heard you were supposed to be arriving today.".format(nar_name, player.name))
I am also using two other modules, but I'm 99% sure they don't affect this. I get the following output:
Hey there, traveller! What's your name?
~~>Savage Potato
Since you are new around here, 100 gold doubloons have been given to you, Savage Potato!
Do you want to see your balance?
~~> Yes
You currently have 100 gold.
Narrator: Uhhhm...
Narrator: Let me check my list...
Narrator: Ah! Yes! None, that's right. I heard you were supposed to be arriving today.
In the last line, it is printing out the Narrator's name, but not the user's inputted name. I also looked at the python documents on their website, but I couldn't find a fix. Any ideas on how I could stop it from outputting None as the user's name?
EDIT #1: I have player = Player() written later in the module.
EDIT #2: This is all the code I used:
Module 1 (main.py)
import prints
import random
class Player():
def __init__(self):
self.name = None
self.gold = 100
self.maxhealth = 100
self.health = self.maxhealth
self.level = 1
self.exp = 0
self.levelUp = 50
self.gainedexp = self.levelUp - self.exp
def get_name(self):
self.name = input("Hey there, traveller! What's your name?\n~~>")
print("Since you are new around here, 100 gold doubloons have been given to you, {}!".format(self.name))
class Dragon():
def __init__(self):
self.name = "Dragon"
self.dropgold = random.randint(13,20)
self.minexp = int(15 * round(player.level * 1.5))
self.maxexp = int(30 * round(player.level * 1.5))
self.expgain = random.randint({}, {}.format(self.minexp, self.maxexp))
self.maxhealth = 80
self.health = self.maxhealth
#while player.exp >= player.levelUp:
#player.levelUp += 1
#player.exp = player.exp - player.levelUp
#player.levelUp = round(player.levelUp * 1.5)
#print("Congrats! You just levelled up to level {} by gaining {} experience!".format(player.level, player.gainedexp))
def start():
player.get_name()
prints.gold_counter()
prints.intro()
prints.encounter()
player = Player()
start()
Module 2 (prints.py)
import options
import random
class Player():
def __init__(self):
self.name = None
self.gold = 100
self.maxhealth = 100
self.health = self.maxhealth
self.level = 1
self.exp = 0
self.levelUp = 50
self.gainedexp = self.levelUp - self.exp
def get_name(self):
self.name = input("Hey there, traveller! What's your name?\n~~>")
print("Since you are new around here, 100 gold doubloons have been given to you, {}!".format(self.name))
def gold_counter(self):
print("You currently have {} gold!".format(player.gold))
class Dragon():
def __init__(self):
self.name = "Dragon"
self.dropgold = random.randint(13,20)
self.minexp = int(15 * round(player.level * 1.5))
self.maxexp = int(30 * round(player.level * 1.5))
self.expgain = random.randint({}, {}.format(self.minexp, self.maxexp))
self.maxhealth = 80
self.health = self.maxhealth
def intro():
wrong_input = 0
nar_name = "Narrator"
print("{}: Uhhhm...".format(nar_name))
print("{}: Let me check my list...".format(nar_name))
print("{0}: Ah! Yes! {1}, that's right. I heard you were supposed to be arriving today.".format(nar_name, player.name))
print("{}: Welcome to... THE DRAGON FIGHTER GAME!".format(nar_name))
print("{}: I know, it isn't the most imaginative name.".format(nar_name))
print("{}: Don't look at me like that, I tried my hardest!".format(nar_name))
print("{}: Anyhoo, let's carry on.".format(nar_name))
print("{}: For some stupid reason, the creator of this game didn't give me an actual name, so\nmy name is just \"Narrator\" or \"N\", but you can call me Larry.".format(nar_name))
while True:
option = input("Narrator: Actually, which name would you prefer to call me?\n").upper()
if option in options.nar_larry_opt:
nar_name = "Larry"
elif option in options.nar_narrator_opt:
nar_name = "Narrator"
while True:
ask = input("{}: Maybe \"N\" for short?".format(nar_name)).upper()
if ask in options.inp_yes_opt:
nar_name = "N"
elif ask in options.inp_no_opt:
break
else:
wrong_input += 1
if wrong_input == 1:
print("Please try again.")
elif wrong_input == 2:
print("Try to not put the same thing in next time.")
elif wrong_input == 3:
print("This isn't funny.")
elif wrong_input == 4:
print("Seriously.")
elif wrong_input == 5:
print("OKAY! THIS IS IT! GO BACK TO THE BEGINNING!")
intro()
continue
break
else:
print("Please try again.")
continue
break
print("{}: So, as I was saying, this game is basically just some dragon quest thingy.".format(nar_name))
print("{}: You'll probably get tips from me every now and again if I can be bothered.".format(nar_name))
print("{}: I'll get an test encounter ready.".format(nar_name))
def gold_counter():
while True:
option = input("Do you want to see your balance?\n~~> ").upper()
if option in options.inp_yes_opt:
print("You currently have {} gold.".format(player.gold))
elif option in options.inp_no_opt:
print("You can check your balance later in the game.")
else:
print("Please try again.")
continue
break
def encounter():
while True:
dragon_appear = random.randint(1,2)
if dragon_appear == 1:
print("What's that? Looks like a huge bir... \nA DRAGON! A MAJESTIC DRAGON JUST FLEW DOWN FROM THE SKY!")
else:
print("What's that? Looks like a huge bir... \n Yeah. Just a giganta-bird.")
while encounter().dragon_appear != 2:
print("So that's the message you'll get when a dragon appears.")
print("And you will be prompted whether you want to run or fight, like so:")
while True:
wrong_input = 0
ask = input("Run away like a coward, or fight the majestic beast?")
if ask in options.enc_run_opt:
escape = random.randint(1,2)
if escape == 1:
print("You managed to get away!")
else:
print("You didn't get away. Better luck next time!")
elif ask in options.enc_attack_opt:
pass
else:
wrong_input += 1
if wrong_input == 1:
print("Please try again.")
elif wrong_input == 2:
print("Try to not put the same thing in next time.")
elif wrong_input == 3:
print("This isn't funny.")
elif wrong_input == 4:
print("Seriously.")
continue
break
player = Player()
Module 3 (options.py)
inp_yes_opt = {"Y", "YE", "YES", "YEAH", "PLEASE", "YES PLEASE"}
inp_no_opt = {"N", "NO", "NOPE", "NAH"}
nar_larry_opt = {"LARRY", "LARR", "LAR", "LA", "L", "LARRY PLEASE"}
nar_narrator_opt = {"NARRATOR", "NARR", "N", "NAR", "NARRATE", "NOT LARRY"}
enc_run_opt = {"RUN", "RU", "R", "SCRAM", "RUN AWAY", "RUUUUN"}
enc_attack_opt = {"ATTACK", "ATTAK", "A", "FIGHT", "F", "ATTACK", ""}
If you want to print out the name of the player , you need to pass in the player object to the intro function as a parameter. That assumes intro is not capturing the player object and the player object is not global
At the moment , it seems there is no player object accessible to the scope of the function which is why it outputs None
My code:
class Lobby(Definition):
Lcount = 0
def __init__(self):
if Lobby.Lcount == 0:
self.description = "test1"
elif Lobby.Lcount > 0:
self.description = "test2"
else:
print("\nHmmm something went wrong...\n")
self.contents = ["Briefcase"]
self.doors = {"n": "terminal", "w": "hallway"}
Lobby.Lcount += 1
I want it to be where after an instance of the room has been created (i.e. you have visited it before), it will display a different description than it the original one. However, it keeps printing the same description. So what precisely am I doing wrong here?
edit: Here is what is in my definition class:
class Definition:
def __init__(self):
self.description = ""
self.contents = []
self.doors = {}
def get_desc(self):
print("{}".format(self.description))
def get_direction(self):
direction = input("Enter a direction or search the room: ").lower()
search = True
if direction == "q":
return direction
elif direction in self.doors:
location = self.doors[direction]
return location
elif direction == "s":
while search:
action = input("\nYou search for some items... Press 1 to continue or 2 to quit.\n")
if action == "1":
if len(location.contents) == 0:
print("\nYou find nothing of value in the room.\n")
else:
find = random.randrange(1, 3)
if find == 1:
found = random.randrange(len(location.contents))
item = location.contents.pop(found)
print("\nYou found a {}\n".format(item))
self.items.append(item)
self.check_items()
else:
print("\nNothing found yet\n")
elif action == "2":
search = False
break
else:
print("\nLocation reminder: ")
location.get_description()
else:
return "\nNot a valid entry\n"
Something in Definition is preventing this from working appropriately.
class FooClass(object):
foo = 0
def __init__(self):
print("Foo {} before".format(self.__class__.foo))
self.__class__.foo += 1
print("Foo {} after".format(self.__class__.foo))
# Works appropriately
>>> x = Foo()
Foo 0 before
Foo 1 after
>>> x = Foo()
Foo 1 before
Foo 2 after
However I'd recommend a different way to track this if it's just a binary "seen" variable. Restricting your ability to create multiple Lobby objects may mess you up in the future. Strongly consider creating a dictionary that houses all your objects, with a visit method that runs the logic your __init__ is doing now, and sets a flag that makes a following visit do something different.
class SomeRoom(Room):
# where Room is some superclass like Definition is now
def __init__(self, *args):
super().__init__(args) # or however
self.__visited = False
#property
def visited(self):
return self.__visited
def visit(self):
if self.visited:
print("Welcome back")
else:
print("Welcome!")
self.__visited = True
Alright so what I am trying to do is to get objects to save in list form when a user creates a NoteSet. It appends the objects to the list db properly when I input NoteSet('ex','example',True). I made a function called makeNewNoteSet() and it seems to be working correctly but it doesnt append to the db list. I can not figure out why.
import sys
import datetime
import pickle
notesets = []
db = []
def save():
global db
filename = "notesets.dat"
file = open(filename, "wb")
if file == None:
print("There was an error creating your file")
return
pickle.dump(db, file)
file.close()
print("Saved words to ",filename)
def load():
global db
filename = "notesets.dat"
file = open(filename, "rb")
db = pickle.load(file)
print("There are ",len(db)," Note Sets")
file.close()
class NoteSet:
nextseqNum = len(db)+2
def __init__(self,name,description,hidden):
global db
self.seqNum = NoteSet.nextseqNum
self.name = name
self.description = description
self.dateCreated = datetime.date.today()
self.hidden = hidden
self.notes = list()
NoteSet.nextseqNum += 1
print(self)
notesets.append(self)
notelist = [self.seqNum,self.name,self.description,self.dateCreated,self.hidden,self.notes]
print(notelist)
db.append(notelist)
NoteSet.nextseqNum += 1
def __str__(self):
printstr = str(self.seqNum),self.name,self.description,str(self.dateCreated)
printstr = str(printstr)
return printstr
class Note:
nextseqNum = 0
def __init__(self,text,dateCreated,description,category,priority,hidden):
self.text = text
self.dateCreated = str
self.dateRead = str
self.description = str
self.category = str
self.priority = int
self.hidden = bool
self.seqNum = Note.nextseqNum
Note.nextseqNum += 1
def main():
while True:
load()
printMainMenu()
selection = int(input("? "))
if selection == 1:
listNoteSets()
elif selection == 2:
listAllNoteSets()
elif selection == 3:
makeNewNoteSet()
elif selection == 4:
selectNoteSet() # this makes the working note set
elif selection == 5:
deleteNoteSet()
elif selection == 6:
sys.exit()
else:
print("Invalid choice")
def printMainMenu():
print("1. List note sets")
print("2. List all note sets (including hidden sets)")
print("3. Make a new note set")
print("4. Select a working note set")
print("5. Delete a note set")
print("6. Quit")
def listNoteSets():
num = 0
for row in db:
if db[num][4] == False:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
input("[Press return to see main menu]")
main()
def listAllNoteSets():
num = 0
for row in db:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
input("[Press return to see main menu]")
main()
def makeNewNoteSet():
num = 0
name = input("What would you like to name your note set? --- ")
for row in db:
if name == db[num][1]:
print("That note set has already been created")
makeNewNoteSet()
description = input("Describe your note set briefly --- ")
hidden = input("Would you like this note set to be hidden? --- ")
if hidden == 'y' or 'yes':
hidden = True
else:
hidden = False
NoteSet(name, description, hidden)
print("noteset created you can now access it through the menu")
input("[Press enter to return to menu]")
main()
def selectNoteSet():
num = 0
for row in db:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
response = input("Enter the number assosciated with the noteset you would like to access")
print("Note set #",response," was selected")
main()
After you add a new note in makeNewNoteSet(), you call main() which calls load() which overwrites the in-memory copy of the database you just changed. You probably want to call save() somewhere in there.
I am new to programming in python and, I started writing a simple text based adventure game. I came across a problem when passing an object from one function to another. Here is my code:
import random
import time
num = random.randint(0,2)
xp1 = random.randint(1,2)
class player:
def __init__ (self, name, health, strength, defense, potion, xp, level):
self.__health = health
self.__strength = strength
self.__defense = defense
self.__name = name
self.__potion = potion
self.__xp = xp
self.__level = level
def getName(self):
return self.__name
def getHealth(self):
return self.__health
def getStrength(self):
return self.__strength
def getDefense(self):
return self.__defense
def getPotion(self):
return self.__potion
def getXP(self):
return self.__xp
def getLevel(self):
return self.__level
def setHealth(self):
self.__health = 10
def setLevel(self):
self.__level = 1
def subHealth(self, num):
self.__health -= num
def subPotion(self):
self.__potion -= 1
return self.__health
def addPotion(self, num1):
self.__potion += num1
def addHealth(self):
self.__health +=2
def addStrength(self):
self.__strength += 1
def addDefense(self):
self.__defense += 1
def addXP(self):
self.__xp += xp1
def addLevel(self):
self.__level += 1
self.__addHealth += 1
self.__defense += 1
self.__strength += 1
def battle(enemy, player1, name1):
player1 = player(name1, player1.getHealth(), player1.getStrength(), player1.getDefense(), player1.getPotion(), player1.getXP(), player1.getLevel())
enemy = player('Dongus', enemy.getHealth(), enemy.getStrength(), enemy.getDefense(), enemy.getPotion(), enemy.getXP(), enemy.getLevel())
s = 0
while s == 0:
time.sleep(1)
attack =int(input("Type 1 to attack, type 2 to use a potion."))
if attack == 1:
time.sleep(1)
print("Dongus's health is", enemy.subHealth(num))
print("Dongus hit you and your health is now at", player1.subHealth(num-player1.getDefense()))
elif attack == 2:
time.sleep(1)
print("You used a potion.")
player1.addHealth(), player1.subPotion()
if player1.getHealth() > 10:
player1.setHealth()
print("Dongus hit you and your health is now at", player1.subHealth(num-player1.getDefense()))
if enemy.getHealth()<=0:
print("Congratulations, you won! You recieved", xp1, "xp!")
player.addXP()
s = 2
def main():
name1 = input("What would you like your name to be?")
time.sleep(1)
print("Hello,", name1, "you are on a quest to save otis from the evil Dongus. You must slay him, or Otis will poop.")
time.sleep(2)
player1 = player(name1, 10, 2, 1, 0, 0, 1)
enemy = player('Dongus', 8, 4, 0, 0, 0, 0)
print("Your stats are, health:", player1.getHealth(), "strength:", player1.getStrength(), "and defense:", player1.getDefense())
time.sleep(2)
print("Fight!")
pick = input("You found a health potion! Press 'p' to pick it up.")
p = 0
while p == 0:
if pick == "p":
print("You added a potion to your inventory.")
player1.addPotion(1)
p = 2
else:
print("You have no potions, you should probably pick this one up.")
player1.addPotion(1)
p = 2
battle(enemy, player1, name1)
if self.__getXP() == 1:
print("You leveled up. You are now level 2.")
player1.addLevel()
print("Your stats are, health:", player1.getHealth(), "strength:", player1.getStrength(), "and defense:", player.getDefense())
loot1 = int(input("Type ''1'' to loot the enemy chest."))
if loot1 == 1:
print("You recieved two potions!")
player1.__addPotion(2)
enemy.setHealth(10)
battle(enemy, player1, name1)
main()
Now the problem is when I run the game, I get to a point where I type "1" to attack the enemy, but it says, for some reason, that after attacking the enemy, the enemies health is at "None". This is the same case when the enemy attacks player1, it says player1's health is at "None". I assume that "None" is the default value in python 3.4.1, so my thinking is that the player1's object from def main() are not being transferred over to def battle() and I cannot see the reason why this is happening. I most likely am missing something here, or it is something I do not already know about Python that is causing the issue. Does anybody know what I can do to fix this, and why it is doing this?
BTW some of the terms I am using may be wrong, so please correct me if they are... I have only been coding for 2 weeks :p.
Thanks!!!
First, received not recieved
2nd yes, If you have a Python function that does not return a value, the result is None
# dummy will return "Positive" or None
def dummy(x):
if X > 0:
return "Positive"
So, you probably want to change
def subHealth(self, num):
self.__health -= num
to
def subHealth(self, num):
self.__health -= num
return self.__health
Your question re: the "player" classes from def main() are not being transferred over to def battle() does not really make sense to me.
But, I see that in the first 2 lines of battle, you are replacing the formal parameters player1 and enemy with local variables, this seems like odd usage in your program.