Related
Here is my code so far using random to pick moves:
import time
import random
PHealth = 10
CHealth = 10
PShots = [
"Great Body Shot To Your Opponent!",
"Nice Take Down!",
"Nice Punch!",
"Strong Kick!",
"You Have Him Pinned Against The Cage!",
"Excellent Counter-Shot!"
]
CShots = [
"You Took a Shot to the Body!",
"You Got Taken Down!",
"Strong Kick Hit You!",
"You Took A Big Punch!",
"You Are Pinned Against The Cage",
"Counter-Shot Got Ya!"
]
for i in range(20):
i = random.randint(0, 100)
if i >= 51:
print(random.choice(PShots))
CHealth = CHealth -1
if CHealth >= 1:
print("Player Health", PHealth)
print("Computer Health", CHealth)
time.sleep(5)
if i <= 50:
print(random.choice(CShots))
PHealth = PHealth -1
if PHealth >= 1:
print("Player Health", PHealth)
print("Computer Health", CHealth)
time.sleep(5)
if CHealth < 1:
print("What A Shot!")
time.sleep(1)
print("Down He Goes!")
time.sleep(1)
print("The Referee Has Stopped The Fight!!")
time.sleep(1)
print("Player Wins!!!")
break
if PHealth < 1:
print("What A Shot!")
time.sleep(1)
print("Down You Go!")
time.sleep(1)
print("The Referee Has Stopped The Fight!!")
time.sleep(1)
print("Computer Wins!!!")
break
Basically I'd like to understand how a player can input one move. So if a player inputs body shot it beats take down. If a player inputs kick it beats punch. If a player inputs take down it beats pinned against the cage, etc. Thinking 6-7 variations and counters.
Here is an idea of how you could implement something akin to what you seem to be looking for using a mix of classes and functions.
The following code should work with Python 3.9+ and has no additional dependencies.
First we define a Move class, instances of which need to have a name, a text_used (for when the player successfully uses the move), and a text_affected (for when move is used against the player). Each instance also stores a set of other Move objects, which it trumps, as well as a set of those it is trumped by. We have a helper method should_beat to easily define such a relationship between two moves.
class Move:
def __init__(self, name: str, text_used: str, text_affected: str, damage: int = 1) -> None:
self.name: str = name
self.text_used: str = text_used
self.text_affected: str = text_affected
self.damage: int = damage
self.trumps: set['Move'] = set()
self.trumped_by: set['Move'] = set()
def __str__(self) -> str:
return self.name
def should_beat(self, other_move: 'Move') -> None:
self.trumps.add(other_move)
other_move.trumped_by.add(self)
Next we define a Player class. Its instances have a name and an optional starting_health set to a previously defined constant by default.
A Player also has a use_move method that takes a Move object, another Player object (the opponent), and a second Move object (the move used by the opponent). That method checks which move beats which and calculates the health subtraction accordingly.
Finally, the Player object has win and lose methods that can be called to print out the win/loss statements when necessary.
class Player:
def __init__(self, name: str, starting_health: int = DEFAULT_STARTING_HEALTH) -> None:
self.name: str = name
self.health: int = starting_health
def __str__(self) -> str:
return self.name
def use_move(self, move: Move, vs_player: 'Player', vs_move: Move) -> None:
if vs_move in move.trumped_by:
self.health -= vs_move.damage
print(vs_move.text_affected)
elif move in vs_move.trumped_by:
vs_player.health -= move.damage
print(move.text_used)
else:
print(TEXT_NO_EFFECT)
def win(self, vs: 'Player') -> None:
print("What A Shot!")
sleep(1)
print(f"{vs} Goes Down!")
sleep(1)
print("The Referee Has Stopped The Fight!!")
sleep(1)
print(f"{self} Wins!!!")
def lose(self, vs: 'Player') -> None:
print("What A Shot!")
sleep(1)
print(f"Down You Go, {self}!")
sleep(1)
print("The Referee Has Stopped The Fight!!")
sleep(1)
print(f"{vs} Wins!!!")
Next, we want a function to define our moves and one that conveniently prints a list of moves to the terminal. Obviously you will want to expand the define_moves function to incorporate all your desired moves and their relationships. It should return a list of all your Move objects.
def define_moves() -> list[Move]:
kick = Move("kick", "Strong Kick!", "Strong Kick Hit You!")
punch = Move("punch", "Nice Punch!", "You Took A Big Punch!")
...
kick.should_beat(punch)
...
return [
kick,
punch,
]
def print_moves(moves_list: list[Move]) -> None:
print("Available moves:")
for i, move in enumerate(moves_list):
print(i, "-", move.name)
Now for the fun part, we need our main fighting loop. In each iteration, we prompt the player for a number that corresponds to an index in our list of moves defined earlier. (The player may also type h to see the moves again.) We do some checks to make sure we received a valid number to get our Move object.
Then we randomly chose a move for the computer opponent out of our moves list, and call our use_move method. It does the health calculations for us. So after that we just check, if someone is done to call the appropriate win or lose method and break out of the loop. Otherwise we print the current health stats and continue.
def fight_computer(player: Player, moves_list: list[Move]) -> None:
computer = Player(name="Computer")
while True:
string = input('Choose your move! (or type "h" to see available moves again)\n').strip().lower()
if string == 'h':
print_moves(moves_list)
continue
try:
i = int(string)
except ValueError:
print("You need to pick a number!")
continue
try:
move = moves_list[i]
except IndexError:
print("No move available with number", i)
continue
computer_move = choice(moves_list)
print(computer, "chose", computer_move)
player.use_move(move, vs_player=computer, vs_move=computer_move)
if player.health < 1:
player.lose(vs=computer)
break
if computer.health < 1:
player.win(vs=computer)
break
print(player, "health:", player.health)
print(computer, "health:", computer.health)
sleep(1)
Lastly, we need a main function to put it all together, prompt the player for his name, etc.
def main() -> None:
player_name = input("Enter your name: ").strip()
player = Player(player_name)
moves_list = define_moves()
print_moves(moves_list)
fight_computer(player, moves_list)
if __name__ == '__main__':
main()
Don't forget to add your imports and constant definitions to the start of the module:
from random import choice
from time import sleep
DEFAULT_STARTING_HEALTH = 10
TEXT_NO_EFFECT = "Your move had no effect!"
All together, this should give you a crude version of the game you described. Try it out. Hope this helps.
I am trying some text based rpg game as a beginner in python. But i am struggling to get done one thing.
If i use while loop to run program 5 times. So i want repeat killing monster but without saving his attributes.
If you run this code, character kills a monster in couple of moves and appends his experience to himself and monster hp decreases to <= 0 and dies.
Looping whole program does not work, randomly created monster is still the same, i just want to create new monster with new random attributes every time i loop program. It is possible? I am new to this and can't figure it out at this moment. Some tips ?
Here is some code but without while loop: final output is to loop this menu and fight simulator to gain exp and items from random monsters.
import random
import time
# List of items to drop
normal_items = ['Copper ore', 'Apple', 'Animal skin', 'Stone', 'Feather', 'Rotten egg', 'Bag of sand', "Simple dagger", "Blue flower"]
rare_items = ['Energized wand', 'Staff of purity', 'Enhanced gloves', 'Adamant chest plate']
legendary_items = ['Crown of Immortality', 'Robe of fire-dragon']
drop_chance_dice = random.randint(1, 100)
# Simple drop chance function
def dice():
if drop_chance_dice <= 70:
random_choice = (random.choice(normal_items))
print(f"You got: {random_choice} ")
if 70 <= drop_chance_dice <= 98:
random_choice = (random.choice(rare_items))
print(f"You got: {random_choice} ")
if 99 <= drop_chance_dice <= 100:
random_choice = (random.choice(legendary_items))
print(f"Congratulations! You got an legendary item: {random_choice}")
# Instances and mobs
rat_nest= ['Rat', 'Giant Rat', 'Leader of Rats']
northern_forest = ['Snake', 'Wolf', 'Witch']
# My Character Class
class YourCharacter:
def __init__(self, intro, name, attack, exp, level, hp):
self.intro = intro
self.name = name
self.attack = attack
self.exp = exp
self.level = level
self.hp = hp
# Creating my character(preset)
my_character = YourCharacter("Your character \n", 'FroGres', 16, 0, 1, 100)
# Introduction
def introduction_of_player(my_character):
print(f"{my_character.intro}")
print(f"{my_character.name}")
print(f"Attack: {my_character.attack}")
print(f"Experience: {my_character.exp}")
print(f"Level: {my_character.level}")
print(f"HP: {my_character.hp}")
# Monsters class build
class Monster:
def __init__(self, intro, name, attack, exp, level, hp):
self.intro = intro
self.name = name
self.attack = attack
self.exp = exp
self.level = level
self.hp = hp
# Monsters attributes + list of mobs (for testing - to be upgraded)
# rat nest
rat = Monster("You fight vs: \n", "Rat", random.randint(4, 6), random.randint(8, 14), random.randint(1, 3),
random.randint(50, 100))
giant_rat = Monster("You fight vs: \n", "Giant Rat", random.randint(6, 8), random.randint(10, 18), random.randint(2, 4),
random.randint(80, 130))
rat_boss = Monster("You fight vs: \n", "Leader of Rats", random.randint(4, 6), random.randint(8, 14),
random.randint(1, 3),
random.randint(50, 100))
# northern forest
#Witch = Monster("You fight vs: \n", "Witch", random.randint(8, 12), random.randint(12, 20), random.randint(3, 6), random
# .randint(120, 200))
list_of_mobs = [rat, giant_rat, rat_boss]
event_mob = random.choice(list_of_mobs) # Random pick monster , USED in function
# Introduction of Monster
def introduction_of_monster_ratnest(list_of_mobs):
print(f"{list_of_mobs.intro}")
print(f"{list_of_mobs.name}")
print(f"Attack: {list_of_mobs.attack}")
print(f"Experience: {list_of_mobs.exp}")
print(f"Level: {list_of_mobs.level}")
print(f"HP: {list_of_mobs.hp}")
def escape_or_fight():
take_input = input("[a]ttack or [r]un?")
if take_input == 'a':
return attack()
if take_input == 'r':
print("You run as fast as possible.. ")
print("You returning to your hideout..")
else:
print("Something wrong")
# Menu of actions
def menu_dungs():
asking = input("Where do you want to go?: 1.Rat Nest or 2.Northern Forest :")
if asking == "1":
print("You entering rat nest.. good luck!\n")
time.sleep(1)
print("Some ugly creature stays on your way!")
print(f"{event_mob.name} is looking at you!")
if event_mob == rat:
introduction_of_monster_ratnest(rat)
escape_or_fight()
elif event_mob == giant_rat:
introduction_of_monster_ratnest(giant_rat)
escape_or_fight()
elif event_mob == rat_boss:
introduction_of_monster_ratnest(rat_boss)
escape_or_fight()
else:
print("Something went horribly wrong.. Don't even ask..")
elif asking == "2":
print("You entering northern forest.. good luck!\n")
print("Dungeon unavailable at this moment, try another one")
pass
# Not in use
else:
print("Try again and choose correct location\n")
menu_dungs()
def attack():
gain_exp = event_mob.exp + my_character.exp
rounds = 0
while event_mob.hp > 0:
event_mob.hp = event_mob.hp - my_character.attack
rounds += 1
print(f"You hit with: {my_character.attack} damage. Enemy HP is {event_mob.hp}")
print(f"Enemy HP after your attack is {event_mob.hp}", "\n")
if event_mob.hp <= 0:
print(f"{event_mob.name} has died..")
print(f"It tok you: {rounds} moves to kill that creature! \n")
print("Congratulations! Here is your loot")
dice()
print(f"You got: {event_mob.exp} experience from that fight.")
print(f"Your experience is now: {gain_exp}")
menu_dungs()
I tried: to create new unique monster with new randomly created attributes every time i run program. I used while loop but monster is not "respawning"
I expect: Some sort of simulator, after i kill monster, program creates new one and my character gains experience and items every fight.
I wonder: If there is some method to makes this class unique every loop.
Here is HOW-TO to achieve all goals in your question:
each time generate monsters with different parameters
respawn monsters
First you create 3 sepreate functions that would return a new monster - the class of returned value is always the same (Monster) but they return new instances on each call:
def get_rat():
return Monster("You fight vs: \n", "Rat", ...)
def get_giant_rat():
return Monster(...)
def get_rat_boss():
reutrn Monster(...)
You will also need to modify how you select monsters. I would suggest to create list of functions - so instead of selecting a monster you select a function, that generates monster:
# This should replace the list_of_mob
list_of_mob_generators = [get_rat, get_giant_rat, get_rat_boss]
And the last - you should select monster on each loop interation in main menu (so the monster could respawn). The shortest way is to change your global variable:
event_mob = None # we change event_mob initially to None - we will select in later
def menu_dungs():
global event_mob # this is new
asking = input("Where do you want to go?: 1.Rat Nest or 2.Northern Forest :")
if asking == "1":
event_mob_generator = random.choice(list_of_mob_generators) # get one of the functions
event_mob = event_mob_generator() # call the function to get monster
print("You entering rat nest.. good luck!\n")
time.sleep(1)
print("Some ugly creature stays on your way!")
print(f"{event_mob.name} is looking at you!")
# and this condition has changed, since we do not have one instance of each monster anymore
if event_mob.name == 'Rat':
introduction_of_monster_ratnest(event_mob)
escape_or_fight()
elif event_mob.name == 'Giant Rat':
introduction_of_monster_ratnest(event_mob)
escape_or_fight()
elif event_mob.name == 'Rat Boss':
introduction_of_monster_ratnest(event_mob)
escape_or_fight()
else:
print("Something went horribly wrong.. Don't even ask..")
... # and so on
and of course do not forget a while loop for main menu =)
while True:
menu_dungs()
Thanks for help, program works as i wanted but still shows me 8 yellow errors in attack() function. Cannot find reference 'hp' in 'None' etc.
maybe because this event_mob = None ?
Could you run this code and see what is going on ? very likely i did put something in wrong place..
import random
import time
# List of items to drop
normal_items = ['Copper ore', 'Apple', 'Animal skin', 'Stone', 'Feather', 'Rotten egg', 'Bag of sand', "Simple dagger", "Blue flower"]
rare_items = ['Energized wand', 'Staff of purity', 'Enhanced gloves', 'Adamant chest plate']
legendary_items = ['Crown of Immortality', 'Robe of fire-dragon']
drop_chance_dice = random.randint(1, 100)
# Simple drop chance function
def dice():
if drop_chance_dice <= 70:
random_choice = (random.choice(normal_items))
print(f"You got: {random_choice} ")
if 70 <= drop_chance_dice <= 98:
random_choice = (random.choice(rare_items))
print(f"You got: {random_choice} ")
if 99 <= drop_chance_dice <= 100:
random_choice = (random.choice(legendary_items))
print(f"Congratulations! You got an legendary item: {random_choice}")
# Instances and mobs
rat_nest= ['Rat', 'Giant Rat', 'Leader of Rats']
#not in use
northern_forest = ['Snake', 'Wolf', 'Witch']
# My Character Class
class YourCharacter:
def __init__(self, intro, name, attack, exp, level, hp):
self.intro = intro
self.name = name
self.attack = attack
self.exp = exp
self.level = level
self.hp = hp
# Creating my character(preset)
my_character = YourCharacter("Your character \n", 'FroGres', 16, 0, 1, 100)
# Introduction
def introduction_of_player(my_character):
print(f"{my_character.intro}")
print(f"{my_character.name}")
print(f"Attack: {my_character.attack}")
print(f"Experience: {my_character.exp}")
print(f"Level: {my_character.level}")
print(f"HP: {my_character.hp}")
# Monsters class build
class Monster:
def __init__(self, intro, name, attack, exp, level, hp):
self.intro = intro
self.name = name
self.attack = attack
self.exp = exp
self.level = level
self.hp = hp
# Monsters getting functions
# rat nest
def get_rat():
return Monster("You fight vs: \n", "Rat", random.randint(4, 6), random.randint(8, 14), random.randint(1, 3),
random.randint(50, 100))
def get_giant_rat():
return Monster("You fight vs: \n", "Giant Rat", random.randint(6, 8), random.randint(10, 18), random.randint(2, 4),
random.randint(80, 130))
def get_rat_boss():
return Monster("You fight vs: \n", "Rat Boss", random.randint(4, 6), random.randint(8, 14),random.randint(1, 3),
random.randint(50, 100))
# northern forest
# def get_witch():
# return Monster("You fight vs: \n", "Witch", random.randint(8, 12), random.randint(12, 20), random.randint(3, 6), random
# .randint(120, 200))
list_of_mobs_generators = [get_rat, get_giant_rat, get_rat_boss]
def escape_or_fight():
take_input = input("[a]ttack or [r]un?")
if take_input == 'a':
return attack()
if take_input == 'r':
print("You run as fast as possible.. ")
print("You returning to your hideout..")
else:
print("Something wrong")
# Menu of actions
event_mob = None
def menu_dungs():
global event_mob
asking = input("Where do you want to go?: 1.Rat Nest or 2.Northern Forest :")
if asking == "1":
event_mob_generator = random.choice(list_of_mobs_generators)
event_mob = event_mob_generator()
def introduction_of_monster_ratnest(event_mob):
print(f"{event_mob.intro}")
print(f"{event_mob.name}")
print(f"Attack: {event_mob.attack}")
print(f"Experience: {event_mob.exp}")
print(f"Level: {event_mob.level}")
print(f"HP: {event_mob.hp}")
print("You entering rat nest.. good luck!\n")
time.sleep(1)
print("Some ugly creature stays on your way!")
print(f"{event_mob.name} is looking at you!")
if event_mob.name == 'Rat':
introduction_of_monster_ratnest(event_mob)
escape_or_fight()
elif event_mob.name == 'Giant Rat':
introduction_of_monster_ratnest(event_mob)
escape_or_fight()
elif event_mob.name == 'Rat Boss':
introduction_of_monster_ratnest(event_mob)
escape_or_fight()
else:
print("Something went horribly wrong.. Don't even ask..")
elif asking == "2":
print("You entering northern forest.. good luck!\n")
print("Dungeon unavailable at this moment, try another one")
pass
# Not in use
else:
print("Try again and choose correct location\n")
def attack():
gain_exp = event_mob.exp + my_character.exp
rounds = 0
while event_mob.hp > 0:
event_mob.hp = event_mob.hp - my_character.attack
rounds += 1
print(f"You hit with: {my_character.attack} damage. Enemy HP is {event_mob.hp}")
print(f"Enemy HP after your attack is {event_mob.hp}", "\n")
if event_mob.hp <= 0:
print(f"{event_mob.name} has died..")
print(f"It tok you: {rounds} moves to kill that creature! \n")
print("Congratulations! Here is your loot")
dice()
print(f"You got: {event_mob.exp} experience from that fight.")
print(f"Your experience is now: {gain_exp}")
while True:
menu_dungs()
background: I'm currently writing a text-based adventure and each enemy has a certain amount of turns you can attack it before it attacks back.
So to handle this the code sets an argument in the function for the fight dictating how many times you can attack.
def fight_sequence(rounds):
while rounds > 0:
attack = input()
if attack == magic:
magic("you teleport away to safety. Congratulations you have stayed alive through your journey and found a few souvenoirs. nice job!", 1, "you muster up all of your energy, chant the spell.... and nothing happens.Cthulu... seems unimpressed", 1, "")
elif attack == sword:
sword(1)
def magic(teleportmessage, teleportsuccess, firemessage, firefail, winmessage):
x = 0
while x == 0:
fightorflight = input("""you open the book to cast a spell
Do you want to try teleporting or use a fireball?""").lower()
if "teleport" in fightorflight:
if teleportsuccess = 1:
print(teleportmessage)
x = 1
else:
choice = input("You can't teleport out of this battle. Would you like to try a fireball?")
if choice == yes:
fightorflight = "fireball"
else:
x = 1
elif "fire" in fightorflight:
print(firemessage)
if firefail == 1:
choice = input("do you want to try to teleport instead?").lower()
if "yes" in choice:
fightorflight = "teleport"
else:
x = 1
else:
print(winmessage)
else:
print("Sorry not sure what you mean")
def sword(attacksuccess):
if attacksuccess == 1:
print("You pull out the sword and swing at the monster damaging it severely.")
else:
print("You pull out the sword and swing at the monster, but its immune to blunt objects.")
fight_sequence(3)
both magic() and sword() need to be able to decrease rounds by 1, originally i just did that before entering the magic or sword function. however some items to attack with allow you to attack more than once if you want so that won't work for them. Such as magic if they also choose to teleport. Is there a way to allow me to change the variable rounds while inside of another function?
I think using a return value might help but I'm not sure how to go about it
You can simply add a new argument to the magic function, and pass the 'rounds' variable through when you call it.
e.g.
def fight_sequence(rounds):
...
magic("some message", false, "fired", false, "you won", rounds)
def magic(teleportmessage, teleportsuccess, firemessage, firefail, winmessage, rounds):
Your passing through the variable (not just the value) so it will change in every context where rounds can be seen.
HTH.
I would recommend using classes to create this game rather than lots of functions, an example of a class in a hero game below.
class Hero:
def __init__(self):
self.health = 10
def eatApple(self):
self.health += 1
def takeDamage(self):
self.health -= 1
init function runs as class is initialized.
player = Hero()
print(player.health) # will print 10
player.takeDamage()
print(player.health) # will print 9
This way you can have global variables for you functions which can be changed in each function and is much more organised.
I am quite new to python, having only toyed with it for a few days now. I am trying to cobble together a program to show off a battle system I had in mind. My issue is that I keep getting "None" produced when I try to print
import os
class Player():
def __init__(self, name, hp, maxhp, strength, intel, charm, level):
self.name = name
self.hp = hp
self.maxhp = maxhp
self.strength = 10
self.intel = intel
self.charm = charm
self.level = level
def attack(self, Enemy):
Enemy.hp -= self.strength
class Steve():
def __init__(self, name, hp, maxhp, strength, intel, charm, level):
self.name = name
self.hp = hp
self.maxhp = maxhp
self.strength = strength
self.intel = intel
self.charm = charm
self.level = level
class Barry():
def __init__(self, name, hp, maxhp, strength, intel, charm, level):
self.name = name
self.hp = hp
self.maxhp = maxhp
self.strength = strength
self.intel = intel
self.charm = charm
self.level = level
def Start():
Player.hp = 100
Player.maxhp = 200
Player.strength = 30
Player.intel = 10
Player.charm = 43
Player.level = 23
nameSelection()
def nameSelection():
os.system('cls')
Player.name = input("Please enter your name\n==>")
print("==>")
gameStart()
def gameStart():
os.system('cls')
global Enemy
print ("Player Name:",Player.name)
print ("Who would you like to fight?")
print ("1.)Steve")
print ("2.)Barry")
print ("3.)Change your name")
option = input("==>")
if option == "1":
Enemy = Steve("Steve", 100, 200, 10, 20, 30, 50)
fight()
elif option == "2":
Enemy = Barry("Barry", 100, 200, 10, 20, 30, 50)
fight()
elif option == "3":
nameSelection()
def attack():
Enemy.hp -= Player.strength
def fight():
os.system('cls')
while Enemy.hp > 0:
os.system('cls')
print(CharacterStats())
print ("1.) Attack")
print ("2.) Run")
option = input("==>")
if option == "1":
attack()
print (Enemy.hp)
print ("You did it! You have defeated", Enemy.name,"!")
gameStart()
def CharacterStats():
print ("You now face", Enemy.name)
print ("His current health is", Enemy.hp,"/",Enemy.maxhp)
print ("His strength is", Enemy.strength)
print ("His intelligence is", Enemy.intel)
print ("His charm is", Enemy.charm)
print ("He is level", Enemy.level)
Start()
When I get to a fight encoutner with one of the two options, I get
You now face Steve
His current health is 100 / 200
His strength is 10
His intelligence is 20
His charm is 30
He is level 50
None
1.) Attack
2.) Run
==>
I have read that return could fix it, but I can't seem to get return to give me the desired results I was looking for, both how it looks different went printed in to the player, and it only returns one of these lines of stats. I may be getting some of my terms wrong, I hope I am being clear on what my issue is.
You are getting None because you are printing the function, where you should just call the function, your function doesn't return anything and that is why you are getting None.
Change this line:
print(CharacterStats())
to:
CharacterStats()
In Python, when you call a function, that function does its work and then returns a value. For instance,
def add(x, y):
print("Working on it...")
answer = x + y
print("Got it!")
return answer
When called, this function will do four things. It will print "Working on it..." to the terminal. It will create a variable called answer, and assign it to the sum of x and y. It will print "Got it". And then, it will silently return that answer.
What does return mean? It means two things: it tells Python to return control to the place where the function was called, and it also says: wherever I was called, replace me with a certain value.
So if I write
print(add(2,3))
the function will be called and do its thinking, printing "working" and "got it" to the terminal. It will return 5, so now Python comes back to the print call and replaces add(2, 3) with 5:
print(5)
which will print 5. Similarly, I could do:
x = add(4,6) + add(5,2)
This would print:
Working on it...
Got it!
Working on it...
Got it!
And then x would be set to 10 + 7, or 17.
In your code, since you don't explicitly return anything from your function, Python uses the default, implicit return of None when it reaches the last line of your function. That means that
print(MyFunc())
actually is understood as, do the function, then
print(None)
Hope that clears things up!
As a side note, it will be more suitable if you use inheritance (use the Player class as base class eg: class Steve (Player):pass ) in your game : https://docs.python.org/2/tutorial/classes.html
I can't really copy over all of the code in both of these files since it is over 1000 lines, but essentially I am making a program that has the variables 'strength', 'endurance', 'strength', 'dexterity', 'intelligence', 'wisdom', and 'luck' (it's an rpg game) and I am trying to get the variable 'damage', which is an equation of 'strength' * 'dexterity' / 100, into another file. All of these variables are within the function character() in a file specifically for creating your character, and I'm trying to call over these variables again in another file for the main game, inside a variable called fight(). I've tried a multitude of things such as global variables, and using return, but nothing has worked for me. I'm sorry if I explained that poorly, comment if you have any questions.
The code in question.
character.py
def character():
#tons of stuff go here
global damage
damage = strength * dexterity / 100
game.py
def fight():
choice = input('(Type in the corresponding number to choose.) ')
global enemy_health
global damage
if choice == 1:
print ' '
print enemy_health,
enemy_health += -damage
print '-->', enemy_health
Thank you for your time.
I guess you could try importing character.py to game.py.
game.py: (edited)
import character
character_health = character.health
character_strength = character.strength
def fight():
...
But yeah, use classes.
Edit: example class
game.py:
class Character(object):
def __init__(self, health, strength):
self.health = health
self.strength = strength
self.alive = True
def check_dead(self):
self.alive = not(self.health)
def fight(self, enemy):
self.health -= enemy.strength
enemy.health -= self.strength
self.check_dead()
enemy.check_dead()
if __name__ == "__main__":
player = Character(300, 10) # health = 300, strength = 10
enemy = Character(50, 5) # health = 50, strength = 5
player.fight(enemy)
print("Player's health: {}\nIs he alive? {}\nEnemy's health: {}\nIs he alive? {}".format(player.health, player.alive, enemy.health, enemy.alive))