Python 3 - Object Oriented Programming - Classes & Functions - python-3.x

I have been studying Python 3 for a few months now and have just begun looking at Object Oriented programming. I asked a question on Stack Overflow about a text adventure game I was trying to write and it was suggested that it would be better to use OOP.
I did some searching as I wanted a very simple combat system that could be used in the game. I have the basic framework from the game but I would like some help with the combat system side.
Here is the code I have so far:
import random
import time as t
class Die:
def __init__(self, sides = 6):
self.sides = sides
def roll(self):
return random.randint(1, self.sides)
class Player:
def __init__(self):
self.hit_points = 10
def take_hit(self):
self.hit_points -= 2
class Enemy:
def __init__(self):
self.hit_points = 10
def take_hit(self):
self.hit_points -= 2
p = Player()
e = Enemy()
d = Die(6)
battle = 1
while battle != 0:
human = d.roll() + 6
print("Your hit score: ",human)
enemy = d.roll() + 6
print("Enemy hit score: ",enemy)
if human > enemy:
e.take_hit()
print("Your hit points remaining: ",p.hit_points)
print("Enemy points remaining: ", e.hit_points)
if e.hit_points == 0:
battle = 0
t.sleep(2)
elif human < enemy:
p.take_hit()
print("Your hit points remaining: ",p.hit_points)
print("Enemy points remaining: ", e.hit_points)
if p.hit_points == 0:
battle = 0
t.sleep(2)
The Die class is to simulate a six sided die, and player and enemy are used for game characters. After that the code is used to roll random number and the highest number win the round until either the player or the enemy reach zero points.
I am unsure how to use those last lines of code after the three classes and create a class from it also.
I need to be able to run a battle multiple times in the game and also store the player score with points deducted after each battle.
I really like and enjoy the use of objects and would like to become better, so any help with this is very much appreciated.

You can re-use a class and create more instances from one template. The Player and Enemy class have a identical functionality. You can create different instances from one class simply using the __init__ method with different arguments.
import random
import time as t
class Player:
def __init__(self, hit_points, sides):
self.hit_points = hit_points
self.sides = sides
def take_hit(self):
self.hit_points -= 2
def roll(self):
return random.randint(1, self.sides)
p = Player(hit_points=10, sides=6)
e = Player(hit_points=8, sides=6)
battle = 1
while battle != 0:
human = p.roll()
print("Your hit score: ",human)
enemy = e.roll()
print("Enemy hit score: ",enemy)
if human > enemy:
e.take_hit()
print("Your hit points remaining: ",p.hit_points)
print("Enemy points remaining: ", e.hit_points)
elif human < enemy:
p.take_hit()
print("Your hit points remaining: ",p.hit_points)
print("Enemy points remaining: ", e.hit_points)
t.sleep(2)
if e.hit_points == 0 or p.hit_points == 0:
battle = 0

Related

Stimulate rolling dice game

I want to write a program that stimulate a game as follows:
A random number between 1 and 2 is generated to determine which player
starts the game (player1 or player2).
The player who starts the game will now throw a dice repeatedly adding
the points scored in each throwing until either the player collects 20
or more points or until the player gets a 1 point score.
If the player collects 20 or more points, then the score is added to
the total points of the player and it becomes the other player's turn.
If the player gets a 1 point score before reaching 20 or more points,
then the player loses his turn without getting any points and it
becomes the other player's turn.
The other player now starts to play and plays with the same rules as
described above.
Once the second player ends his turn (either after reaching 20 or more
points or loses the his turn), then it becomes the first player's turn
and the game continues.
The first player who reaches a total score of 1000 points wins the
game.
My program works well, but are there any ways that I can solve the problem by defining only Function play without changing its parameters? Can I make Function turnPoint be a part of Function play without using any loops?
import random
def turnPoint(playerTurnPoint):
if (playerTurnPoint >= 20):
return playerTurnPoint
else:
p = random.randint(1, 6)
print(p, end = " ")
if (p == 1):
return 0
else:
playerTurnPoint += p
return turnPoint(playerTurnPoint)
def play(player1Total, player2Total, currentPlayer):
if (player1Total >= 1000):
print("Player 1 won.")
return None
elif (player2Total >= 1000):
print("Player 2 won.")
return None
else:
playerTurnPoint = 0
if (currentPlayer == 1):
print("Player 1 playing...")
print("Points obtained in this turn: ", end = " ")
playerTurnPoint = turnPoint(0)
print()
print("Turn total points = ", playerTurnPoint)
player1Total += playerTurnPoint
print("Player 1 total points = ", player1Total)
play(player1Total, player2Total, 2)
else:
print("PLayer 2 playing...")
print("Points obtained in this turn:", end = " ")
playerTurnPoint = turnPoint(0)
print()
print("Turn total points = ", playerTurnPoint)
player2Total += playerTurnPoint
print("Player 2 total points = ", player2Total)
play(player1Total, player2Total, 1)
#Main Program
player1Total = 0
player2Total = 0
currentPlayer = random.randint(1, 2)
print("Starting the Game")
print("=================")
play(player1Total, player2Total, currentPlayer)

How to use inheritance to level up a character

# Import Modules
from Dice import dice
d10 = dice(10,1) #I use dice, but you could just as easily use random.randint()
d4 = dice(4,1)
d20 = dice(20,1)
# Assign Classes
class Player_Character:
inventory = []
def __init__(self, HP, MaxHP, AC, ToHitAdjustment, Surprise_Adjustment,
Initiative_Adjustment, Exp, \
MaxExp, Gold, Damage):
self.HP = int(HP)
self.MaxHP = int(MaxHP)
self.AC = int(AC)
self.ToHitAdjustment = int(ToHitAdjustment)
self.Surprise_Adjustment = int(Surprise_Adjustment)
self.Initiative_Adjustment = int(Initiative_Adjustment)
self.Exp = int(Exp)
self.MaxExp = int(MaxExp)
self.Gold = int(Gold)
self.Damage = int(Damage)
this next section may be where the error is, although I doubt it because when I run through the code the character is assigned exp and gold and they seem to grow at the correct rate.
def attack(self, goblin, Player_Character):
Player_attack_roll = d20.die_roll() + Player_Character.ToHitAdjustment
if (Player_attack_roll >= goblin.AC):
print('you did', Player_Character.Damage, 'damage')
goblin.HP -= Player_Character.Damage
if (goblin.HP <= 0):
print("congratulations you killed the goblin")
Player_Character.Exp += goblin.ExpReward
if (Player_Character.Exp >= Player_Character.MaxExp):
print("Congratulations you have leveled up")
Player_Character.LevelUp()
print('you have', Player_Character.Exp, 'exp ')
Player_Character.Gold += goblin.Gold
print("you have", Player_Character.Gold, 'gold ')
del goblin
else:
print("You miss ")
def flee(self):
print("you run away ")
quit()
def heal(self, Player_Character):
Player_Character.HP += d10.die_roll()
if Player_Character.HP >= Player_Character.MaxHP:
Player_Character.HP = Player_Character.MaxHP
print("You have reached max HP ")
this may be where the error is, I expect it to assign the variable name 'MrHezy' which was previously assigned to Player_Character to FighterLvl1, but when I run the code it continuously says that I am leveling up, which I am unsure if that means that the character is remaining as Player_Character, or if there is something else wrong
def LevelUp(self):
MrHezy = FighterLvl1(25, 25, 15, 10, 2, 2, 25, 75, 20, d10.die_roll()+5)
This next section has code is where my question of inheritance comes into play. Even though FighterLvl1 has inherited from (Player_Character) my IDE says things like "unresolved attribute reference 'Exp' for FighterLvl1" Also I am unsure if adding the 'attack' method under FighterLvl1 does anything; I expect it to overwrite the 'attack' method from Player_Character
class FighterLvl1(Player_Character):
def attack(self, goblin, Player_Character):
Player_attack_roll = d20.die_roll() + Player_Character.ToHitAdjustment
if (Player_attack_roll >= goblin.AC):
print('you did', Player_Character.Damage, 'damage')
goblin.HP -= Player_Character.Damage
if (goblin.HP <= 0):
print("congratulations you killed the goblin")
FighterLvl1.Exp += goblin.ExpReward
if (FighterLvl1.Exp >= FighterLvl1.MaxExp):
print("Congratulations you have leveled up")
FighterLvl1.LevelUp()
print('you have', FighterLvl1.Exp, 'exp ')
FighterLvl1.Gold += goblin.Gold
print("you have", FighterLvl1.Gold, 'gold ')
del goblin
def LevelUp(self):
MrHezy = FighterLvl2(Player_Character)
class FighterLvl2(Player_Character):
def LevelUp(self):
MrHezy = FighterLvl3(Player_Character)
class FighterLvl3(Player_Character):
def MaxLevel(self):
print("Congratulations you are level 3, this is the highest programmed level in the game
")
class goblin:
def __init__(self, HP, MaxHP, AC, ToHitAdjustment, Surprise_Adjustment,
Initiative_Adjustment, \
ExpReward, Gold, Damage):
self.HP = int(HP)
self.MaxHP = int(MaxHP)
self.AC = int(AC)
self.ToHitAdjustment = int(ToHitAdjustment)
self.Surprise_Adjustment = int(Surprise_Adjustment)
self.Initiative_Adjustment = int(Initiative_Adjustment)
self.ExpReward = int(ExpReward)
self.Gold = int(Gold)
self.Damage = int(Damage)
def attack(self, Player_Character, goblin):
if (goblin.HP <= 0):
print("the goblin is inert")
else:
goblin_attack_roll = d20.die_roll() + goblin.ToHitAdjustment
if (goblin_attack_roll >= Player_Character.AC):
goblin_damage = d4.die_roll()
print("you take", goblin_damage, 'damage')
Player_Character.HP -= goblin_damage
if (Player_Character.HP <= 0):
print("oh dear you have died")
del Player_Character
quit()
else:
print("the goblin misses ")
MrHezy = Player_Character(20, 20, 10, 5, 0, 0, 0, 25, 0, d10.die_roll())
def spawn_goblin(goblin):
G1 = goblin(5, 10, 8, 2, 0, 0, 25, 5, d4.die_roll())
return G1
goblin1 = spawn_goblin(goblin)
def battle(goblin1):
# user input
player_initiative_adjustment = MrHezy.Initiative_Adjustment
monster_initiative_adjustment = goblin1.Initiative_Adjustment
#define while loop for the battle
while True:
if (goblin1.HP <= 0):
print('oh dear looks like we need a new goblin')
break
#use random.randint(a,b) to generate player and monster base initiative
player_base_initiative = d10.die_roll()
monster_base_initiative = d10.die_roll()
#subtract the adjustment to get player and monster initiative
player_initiative = player_base_initiative - player_initiative_adjustment
monster_initiative = monster_base_initiative - monster_initiative_adjustment
#compare the initiatives and display the results
if (player_initiative < monster_initiative):
attack_flee_heal = input("congratulations you go first. Would you like to attack,
flee, or heal?")
if attack_flee_heal == 'attack':
MrHezy.attack(goblin1, MrHezy)
elif attack_flee_heal == 'heal':
MrHezy.heal(MrHezy)
print("the goblin attacks")
goblin1.attack(MrHezy)
elif attack_flee_heal == 'flee':
MrHezy.flee()
else:
print("uhoh, the monsters go first, they attack!")
goblin1.attack(MrHezy, goblin1)
attack_flee_heal = input("Would you like to attack, flee, or heal? ")
if attack_flee_heal == 'attack':
MrHezy.attack(goblin1, MrHezy)
elif attack_flee_heal == 'heal':
MrHezy.heal(MrHezy)
print("the goblin attacks")
goblin1.attack(MrHezy, goblin1)
elif attack_flee_heal == 'flee':
MrHezy.flee()
#main game loop
while True:
spawn_goblin(goblin)
battle(goblin1)
print("spawn another goblin")
goblin1.HP = 0
goblin1.HP += d10.die_roll()
This code runs perfectly well, please enter it into your IDE.
The problem that I have is a logic error, when a goblin is killed instead of leveling up the character first to level 1 then level 2 then level 3 instead the character levels up to level 1 over and over and over.
I agree with Danny Varod, in that there are very many improvements that need to be made, and I definitely recommend following his advice.
However if you are simply looking to make what you have work you need to specify in your level up methods that you are referencing the global MrHezy variable.
eg:
def LevelUp(self):
global MrHezy
MrHezy = FighterLvl2(Player_Character)
The level up replaces a variable in the object, what you should do, if you want to use a class per level (not necessarily a good idea) is:
Create a Character class.
In Character class define an implementation field.
Initialize implementation field e.g. implementation = SomeSpeciesLevel1().
To "level-up": implementation = implementation.level_up()
This way you have a constant wrapper that doesn't change which wraps the level-changing implementation.
A better design would be to have one class with functionality based on level-dependant formulas.
class CharImpl:
#abstractmethod
def can_level_up() -> bool:
return NotImplemented
#abstractmethod
def next_level() -> CharImpl:
return NotImplemented
pass
class Character:
def __init__(initial_impl: CharImpl=None):
self.impl = initial_impl.copy() if initial_impl else HumanLevel1()
pass
def level_up():
if self.impl.can_level_up():
self.impl = self.impl.next_level()
pass
pass
class Human(CharImpl):
pass
class HumanLevel1(Human):
def __init__(src: Human):
# TODO: copy relevant fields from src
pass
def can_level_up() -> bool:
return True
def next_level() -> CharImpl:
return HumanLevel2(self)
pass
class HumanLevel2(Human):
def __init__(src: Human):
# TODO: copy relevant fields
pass
def can_level_up() -> bool:
return False
def next_level() -> CharImpl:
return self
pass

I don't know why the variable doesn't add up

This is my code so far and i don't know why the variable doesn't add up when i loop the code.
import random
player1=1
player2=1
print("Welcome To My Board Game")
def dice_roll():
dice1=random.randint(1,6)
dice2=random.randint(1,6)
print("Your first roll is",dice1)
print("Your second roll is",dice2)
total_dice=(dice1+dice2)
print("Your total is",total_dice)
print("You moved",total_dice,"spaces, to space",player1+total_dice )
while True:
print("Player 1 Turn")
choice=input("Do you want to roll the dice press r ")
if choice.lower()=="r":
dice_roll()
This is the output of my code
Welcome To My Board Game
Player 1 Turn
Do you want to roll the dice press r r
Your first roll is 6
Your second roll is 5
Your total is 11
You moved 11 spaces, to space 12
Player 1 Turn
Do you want to roll the dice press r r
Your first roll is 4
Your second roll is 5
Your total is 9
You moved 9 spaces, to space 10
Player 1 Turn
Do you want to roll the dice press r
the move space part should add on from the last part
The problem is, dice1, dice2 and total_dice are "destroyed" when the function returns. Those variables are defined within the scope of the function, so they can't be used outside of the function. There are two ways of accessing the variables inside a function:
Change global variables, then read the globals somewhere else. #yi_xiao's answer shows an example of this.
Pass some data in, and return some data.
In general, you should always prefer returning the values instead of mutating (changing) global variables. Using globals variables makes testing harder, and becomes a problem if you need to access the data from more than one thread at a time.
To fix your code, you should return total_dice from dice_roll, and pass the old total in:
import random
player1=1
player2=1
print("Welcome To My Board Game")
# Pass the old total in as total_dice
def dice_roll(total_dice):
dice1=random.randint(1, 6)
dice2=random.randint(1, 6)
print("Your first roll is", dice1)
print("Your second roll is", dice2)
# Increase the running total sum
total_dice += dice1 + dice2
print("Your total is", total_dice)
print("You moved", total_dice, "spaces, to space", player1 + total_dice)
# Return the sum
return total_dice
# Note, in this simple example, sum is actually global.
# In more realistic cases, this would be inside of a function
# instead of being global
sum = 0
while True:
print("Player 1 Turn")
choice = input("Do you want to roll the dice press r ")
if choice.lower() == "r":
# Pass sum to dice_roll
# Reassing sum to the new sum given to us by dice_roll
sum = dice_roll(sum)
Also note, that currently, your loop won't exit, ever. Even if someone types something other than "r", the loop won't exit, you need to tell it to exit. You can either use break, or change from an infinite loop, to something other than while True.
Use global with your var player1, and change it every time.
def dice_roll():
dice1=random.randint(1,6)
dice2=random.randint(1,6)
print("Your first roll is",dice1)
print("Your second roll is",dice2)
total_dice=(dice1+dice2)
print("Your total is",total_dice)
global player1
player1 += total_dice
print("You moved",total_dice,"spaces, to space",player1)
Reference:
The global statement
Python Scopes and Namespaces
Edit:
Go a step further,you can define a class:
import random
class player:
def __init__(self, init_space=1):
self.space = init_space
def dice_roll(self):
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
print("Your first roll is",dice1)
print("Your second roll is",dice2)
total_dice = (dice1 + dice2)
print("Your total is",total_dice)
self.space += total_dice
print("You moved",total_dice,"spaces, to space", self.space)
player1 = player()
player2 = player()
print("Welcome To My Board Game")
while True:
print("Player 1 Turn")
choice = input("Do you want to roll the dice press r ")
if choice.lower() == "r":
player1.dice_roll()
When there are more players, use class will make things easier.

How can I get my game to finish when the player runs out of health?

I'm currently making a simple rogue-like dungeon game for an assignment, i'm pretty new to coding so I've run into problems along the way. I want my game to end when the player's health reaches 0 so i've written this function
def main_game():
global room_count
global player_health
welcome_text()
while player_health >= 1:
room_enter(empty_room, ghost_room, monster_room, exit_room)
else:
print("Game Over :(")
print("Number of rooms entered: ", room_count)
time.sleep(7)
quit()
For whatever reason when the health reaches 0 the game continues to carry on and I can't figure out why, it's far from finished but here's the full game code below:
import time
import random
import sys
player_health = 1
room_count = 1
def scroll_text(s):
for c in s:
sys.stdout.write( "%s" % c )
sys.stdout.flush()
time.sleep(0.03)
def welcome_text():
scroll_text("\nYou wake up and find yourself in a dungeon.")
time.sleep(1.5)
scroll_text("\nYou have no idea how long you have been trapped for.")
time.sleep(1.5)
scroll_text("\nSuddenly, one day, for no apparent reason, your cell door opens.")
time.sleep(1.5)
scroll_text("\nEven though weak from having no food, you scramble out as the door closes behind you.")
time.sleep(1.5)
scroll_text("\nYou see many paths and many rooms ahead of you.")
print("\n ")
print( "-"*20)
def room_enter(empty_room, ghost_room, monster_room, exit_room):
global player_health
global room_count
security = True
while security == True:
direction = input("\nYou have the option to go Left (l), Forward (f), or Right (r), which direction would you like to go? ")
if direction == "l" or direction == "f" or direction == "r":
security == False
room_no = random.randint(1,8)
if room_no == 1 or room_no == 2 or room_no == 3:
empty_room()
room_count = room_count + 1
if room_no == 4 or room_no == 5 or room_no == 6:
ghost_room()
room_count = room_count + 1
if room_no == 7:
monster_room()
room_count = room_count + 1
if room_no == 8:
exit_room()
room_count = room_count + 1
else:
print("\nInvalid Entry")
return player_health
def empty_room():
global player_health
scroll_text("You enter a cold empty room, doesn't look like anyone has been here in years.")
player_health = player_health - 1
print("\n ")
print("-"*20)
print("| Your Health: ", player_health, "|")
print("-"*20)
print("Number of rooms entered: ", room_count)
return player_health
def ghost_room():
global player_health
scroll_text("You enter a room and feel a ghostly presence around you")
time.sleep(1)
scroll_text("\nWithout warning, the ghostly mist surrounding you pools together and the shape of a human-like figure emerges.")
time.sleep(1)
scroll_text("\nI AM THE SPIRIT OF AN UNFORTUNATE EXPLORER KILLED IN THEIR PRIME, DOOMED TO SPEND AN ETERNITY TRAPPED IN THIS CHAMBER!")
time.sleep(1)
scroll_text("\nANSWER MY QUESTION MORTAL AND CONTINUE IN PEACE, GET IT WRONG HOWEVER AND YOU WILL BE BEATEN!")
time.sleep(1)
x = random.randint(1,500)
y = random.randint(1,500)
time.sleep(1)
print("\nTELL ME WHAT", x, "PLUS", y, "IS!")
okay = False
while not okay:
try:
player_answer = int(input("\nWHAT IS YOUR ANSWER?! "))
okay = True
if player_answer == x+y:
scroll_text("\nCONGRATULATIONS YOU GOT IT CORRECT! HAVE A BIT OF HEALTH!")
player_health = player_health + 2
else:
scroll_text("\nUNFORTUNATELY FOR YOU THAT ANSWER IS WRONG! PREPARE FOR THE BEATING!")
player_health = player_health - 1
print("\n ")
print("-"*20)
print("| Your Health: ", player_health, "|")
print("-"*20)
print("Number of rooms entered: ", room_count)
except ValueError:
print("\nInvalid Entry")
return player_health
def monster_room():
global player_health
scroll_text("\nYou hear grunting noises as you enter the room and your worst fears are confirmed when your eyes meet the gaze of a giant monster guarding the other doors.")
time.sleep(1)
scroll_text("\nWith no way to fight the creature, you manage to slip around it however as you are making your escape the beast swipes at you and lands a blow to your back.")
player_health = player_health - 5
print("\n ")
print("-"*20)
print("| Your Health: ", player_health, "|")
print("-"*20)
print("Number of rooms entered: ", room_count)
return player_health
def exit_room():
global player_health
scroll_text("\nYou stumble into the room, almost passing out from the lack of food and energy.")
time.sleep(1)
scroll_text("\nIs that...")
time.sleep(1)
scroll_text("\n... You can't believe your eyes! It's the exit from the dungeon at last!")
time.sleep(1)
print("\nWINNER WINNER CHICKEN DINNER")
print("\n ")
print("-"*21)
print("| Final Health: ", player_health, "|")
print("-"*21)
print("Number of rooms entered: ", room_count)
return player_health
def main_game():
global room_count
global player_health
welcome_text()
while player_health >= 1:
room_enter(empty_room, ghost_room, monster_room, exit_room)
else:
print("Game Over :(")
print("Number of rooms entered: ", room_count)
time.sleep(7)
quit()
main_game()
In room_enter you have a typo - security == False instead of security = False, causing an infinite loop in room_enter, so the condition in main_game is never checked.
it is very simple,
if direction == "l" or direction == "f" or direction == "r":
security == False
you basically never set security to false. It should be
if direction == "l" or direction == "f" or direction == "r":
security = False
Btw, if you declare playerHealth to be global, you don't need to return it at the end of every function you'll have the current value anyways.
Also, I think you don't need those parameters on "room_enter" since they are just functions to be executed. If you find an error saying that they are not declared, just move the declaration above the function room_enter
Let me know if something wasn't clear! Happy coding!

Value lost between functions?

I am working on a simple text based battle game, and I have come across a(nother) problem. I have a main function and a battle function and in the battle function once you finish the battle, you gain a certain amount of XP, which is then (or should be) remembered by changing the value of player1.xp. Right after the battle sequence I set it so in the code if player1.xp >= 1 it will change the value of player1.level to "2". Though, whenever I run the code, for some reason the xp value gets lost when the battle function is finished. I know this because it prints out the value of player1.xp after the battle function, and it says "0". Here is the code:
import random
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 changeHealth(self, h):
self.health = h
def addLevel(self):
self.level += 1
def subHealth(self, num):
self.health -= num
return self.health
def subPotion(self):
self.potion -= 1
return self.health
def addPotion(self, num1):
self.potion += num1
def addHealth(self):
self.health +=2
def addXP(self):
self.xp += xp1
def battle1(enemy, player1, name1):
player1 = player(name1, player1.health, player1.strength, player1.defense, player1.potion, player1.xp, player1.level)
enemy = player("Rat", enemy.health, enemy.strength, enemy.defense, player1.potion, enemy.xp, enemy.level)
print("Fight!")
s = 0
while s == 0:
attack =input("Type 1 to attack, type 2 to use a potion.")
if attack == "1":
enemy.subHealth(15)
elif attack == "2":
if player1.potion > 0:
print("You used a potion.")
elif player1.potion <= 0:
print("You don't have any potions! You are forced to attack.")
enemy.subHealth(15)
else:
print("Your life depends on this!")
if enemy.health <= 0:
print("Congratulations, you won! You recieved", xp1, "xp!")
player1.addXP()
s = 2
def main():
name1 = input("What would you like your name to be?")
print("Hello,", name1, "you are on a quest to save otis from the evil Dongus. You must slay him, or Otis will poop.")
player1 = player(name1, 10, 2, 1, 0, 0, 1)
enemy = player("Rat", 15, 0, 0, 0, 0, 0)
pick = input("You were walking along the path and found a potion! Press 'p' to pick it up.")
if pick == "p":
print("You added a potion to your inventory.")
player1.addPotion = 1
else:
print("You have no potions, you should probably pick this one up.")
print("You added a potion to your inventory.")
player1.addPotion = 1
battle1(enemy, player1, name1)
print(player1.xp)
if player1.xp >= 1:
print("You leveled up. You are now level 2.")
player1.addLevel()
else:
print("You have 0 xp.")
main()
Does anybody have a clue why this is happening? Thanks!
In main you create two player (should be Player) instances, and pass them to battle1:
player1 = player(name1, 10, 2, 1, 0, 1)
enemy = player("Rat", 15, 0, 0, 0, 0)
battle1(enemy, player1, name1)
In battle1 you create two new player instances, based on the two argument instances, modify the new instances, and don't return anything:
# take three parameters (one of which is unnecessary)
def battle1(enemy, player1, name1):
# replace two of the arguments with copies
player1 = player(name1, player1.health, player1.strength, player1.defense, player1.xp, player1.level)
enemy = player("Rat", enemy.health, enemy.strength, enemy.defense, enemy.xp, enemy.level)
# original arguments now inaccessible
It is not clear why you expected that this would work, but the minimal fix is to stop creating new instances in battle1. Also, it might be clearer if you moved xp1 = random.randint(1,2) inside battle1.

Resources