Python - Using same randint value in different functions within class object - python

I'm quite new in programming and as an exercise, I wanted to try writing a very basic game.
I will not choke you in details. Let me explain where I'm having trouble.
There are 2 players shooting each other. Each turn they spend random amount of bullets between (1,10) and damage the other, and whoever reaches 0 health loses the game.
Right now, I can call random bullet number to shoot the other player. But I want the damage to be related with the amount of bullet used. For example if player1 used 5 bullets that turn, player2 will be damaged 5*10, or if 2 then damaged 2*10 and etc.
And here is my code. I appreciate any kind of help. Thanks!
import random
bullet_spent = random.randrange(1,10)
damage = bullet_spent * 10
# Enemy object
class Enemy():
def __init__(self,name,hp,ammo):
self.name = name
self.hp = hp
self.ammo = ammo
# Defined actions
def attack(self):
bullet_spent = random.randrange(1,10)
print(self.name + " Shoots. " + str(bullet_spent) + " bullets spent.")
self.ammo -= bullet_spent
def be_damaged(self):
damage = bullet_spent * 10
self.hp -= damage
print(self.name + " lost " + str(damage) + " HP.")
print("Remaining HP: " + str(self.hp))
# Enemy list
player1 = Enemy("Player1",100,50)
player2 = Enemy("Player2",100,50)

You should use return bullet_spent in attack()
def attack(self):
# rest
return bullet_spent
and bullet_spent as argument in be_damaged()
def be_damaged(self, bullet_spent):
# rest
and then you can do get value from one player to another
spend1 = p1.attack()
spend2 = p2.attack()
p1.be_damaged(spend2)
p2.be_damaged(spend1)

Related

Python text based game - TypeError: bool oject not callable

I am creating my first python program and have been struggling with a "TypeError: 'bool' object is not callable" error. I have only been studying for a few weeks so any assistance would be great! Also, if there are any tips on how to reduce some of the code that'd be great! Thanks!
import random
class Spacecraft:
def __init__(self, type, health):
self.type = type
self.health = health
self.ship_destroyed = False
def ship_destroyed(self):
self.ship_destroyed = True
if self.health != 0:
self.health = 0
print("Your spacecraft has been destroyed!")
def ship_destroyed_def(self):
self.ship_destroyed = True
if self.health != 0:
self.health = 0
print("Your enemy spacecraft has been destroyed! YOU WON!!")
def lose_health(self, amount):
self.health -= amount
if self.health <= 0:
self.ship_destroyed()
else:
print("Your spacecraft now has {health} hit points remaining.".format(health=self.health))
def lose_health_def(self, amount):
self.health -= amount
if self.health <= 0:
self.health = 0
self.ship_destroyed()
else:
print("The enemy spacecraft now has {health} hit points remaining".format(health=self.health))
print()
def attack(self, enemy_ship):
while True:
damage_fighter = random.randrange(2, 14)
damage_defender = random.randrange(4, 10)
if self.type == "fighter":
print(
'Your {type} spacecraft attacked the enemy ship for {damage} damage and the enemy {enemy_ship} spacecraft attacked your ship for {damage2} damage.'.format(
type=self.type,
damage=damage_fighter,
enemy_ship=enemy_ship.type,
damage2=damage_defender))
self.lose_health(damage_defender)
enemy_ship.lose_health_def(damage_fighter)
elif self.type == "defender":
print(
'Your {type} spacecraft attacked the enemy ship for {damage} damage and the enemy {enemy_ship} spacecraft attacked your ship for {damage2} damage.'.format(
type=self.type,
damage=damage_defender,
enemy_ship=enemy_ship.type,
damage2=damage_fighter))
self.lose_health(damage_fighter)
enemy_ship.lose_health_def(damage_defender)
class Player:
def __init__(self, type):
self.type = type
self.current_type = 0
def attack_enemy_ship(self, enemy_ship):
my_ship = self.type[self.current_type]
their_ship = enemy_ship.type[enemy_ship.current_type]
my_ship.attack(their_ship)
a = Spacecraft("fighter", 40)
b = Spacecraft("defender", 50)
print()
player_name = input('Welcome to Space Warriors! Please enter your name and hit enter. ')
player_style = input('''
Welcome ''' + player_name + '''! Space Warriors is a game that allows you to chose between two classes of spacecraft. If you select a
fighter spacecraft when you will fight again a defender spacecraft. If you choose a defender space craft
then you will fight a fighter spacecraft. Please select "Fighter" or "Defender" and press enter. ''').lower()
player_selected = []
computer_selected = []
if player_style == 'fighter':
player_selected.append(a)
computer_selected.append(b)
else:
player_selected.append(b)
computer_selected.append(a)
live_player = Player(player_selected)
computer_player = Player(computer_selected)
print()
print("Let's get ready to fight! Both ships are launched!")
print()
live_player.attack_enemy_ship(computer_player)
Once one of the two ships reaches zero hit points I am attempting to call ship_destroyed or ship_destroyed_def, to end the game; however the program stops once one of the ships hits "0". This is when I receive the error.
def ship_destroyed(self):
self.ship_destroyed = True
You're trying to make a function and an attribute that are both named ship_destroyed. You can't do that. Pick a different name for one of them.

Complete the while loop

#Code Project : Shooting game.
You are creating a shooting game!
The game has two types of enemies, aliens and monsters. You shoot the aliens using your laser, and monsters using your gun. Each hit decreases the lives of the enemies by 1. The given code declares a generic Enemy class, as well as the Alien and Monster classes, with their corresponding lives count. It also defines the hit() method for the Enemy class.
You need to do the following to complete the program:
1. Inherit the Alien and Monster classes from the Enemy class.
2. Complete the while loop that continuously takes the weapon of choice from user input and call the corresponding object's hit() method.
Sample Input:
laser
laser
gun
exit
Sample Output:
Alien has 4 lives
Alien has 3 lives
Monster has 2 lives
I completed 1st part , but need help with part 2.
class Enemy:
name = ""
lives = 0
def __init__(self, name, lives):
self.name = name
self.lives = lives
def hit(self):
self.lives -= 1
if self.lives <= 0:
print(self.name + ' killed')
else:
print(self.name + ' has '+ str(self.lives) + ' lives')
class Monster(Enemy):
def __init__(self):
super().__init__('Monster', 3)
class Alien(Enemy):
def __init__(self):
super().__init__('Alien', 5)
m = Monster()
a = Alien()
while True:
x = input()
if x == 'exit':
break
Please follow the community guidelines while asking any question on stackoverflow. Please check out this link How do I ask and answer homework questions?
Check out this code :
while True:
x = input()
if x == 'exit':
break
elif x == 'laser':
a.hit()
elif x == 'gun':
m.hit()

an enemy class in a RPG-game

I am in the midst of making an RPG game in Python.
I have made different classes, but I am having problems with one of my enemy types. It is a spider, and to spice things up, I tried to make the spider do dot (damage over time). It is not guaranteed poison damage, but when it does poison you, it stacks.
This is my parent class (enemy):
class Enemy():
def __init__(self, number_of, name):
self.number_of = int(number_of)
self.name = name
self.hp = 20 * self.number_of
self.dmg = 2 * self.number_of
def attack(self):
print(f"you now have {round(class1.hp)} health" + "\n")
def appearing(self):
if self.number_of > 1:
print (f"{self.number_of} {self.name}s have appeared")
else:
print(f"A {self.name} has appeared")
print (f"They have {self.hp} health")
Note: the class1 is the player
This is my spider class:
class Spider(Enemy):
posion_dmg = 0
def __init__(self, number_of, name):
Enemy.__init__(self, number_of, name)
self.posion_dmg = 0
def attack(self,player):
if self.posion_dmg > 0:
dot = 2 ** (self.poison_dmg + 1)
player.hp -= dot
print ("you are posioned" + "\n")
print (f"it deals {round(dot)} damage")
dmg = random.uniform(1.2 * self.dmg, 1.8* self.dmg)
player.hp -= dmg
print ("The spider(s) bite(s) you. ")
print(f"It deals {round(dmg)} damage")
if randint(1,4) == 1:
self.poison_dmg += 1
if self.number_of == 1:
print ("The spider poisons you")
else:
print ("The spiders poison you")
return Enemy.attack(self)
def appearing(self):
print ("*Spiders have a chance to hit you with poison that deals damage over time - this stack exponentially*")
return Enemy.appearing(self)
When I go in combat with the spider, and the randint is 1, it says that "Spider" has no attribute "poison_dmg", but I made it an attribute, right?
im kind of a newbie to python but i've successfully gone through the "Make Your Own Python Text Adventure" guide and i got a basic grip of how this works, although i do not completely understand how you're making the dot work, i think your problem is:
class Spider(Enemy):
posion_dmg = 0
def __init__(self, number_of, name):
Enemy.__init__(self, number_of, name)
self.posion_dmg = 0 <-----------------------HERE
in combination with this:
def attack(self,player):
if self.posion_dmg > 0:
dot = 2 ** (self.poison_dmg + 1)
player.hp -= dot
print ("you are posioned" + "\n")
print (f"it deals {round(dot)} damage")
dmg = random.uniform(1.2 * self.dmg, 1.8* self.dmg)
player.hp -= dmg
print ("The spider(s) bite(s) you. ")
print(f"It deals {round(dmg)} damage")
if randint(1,4) == 1: <----------------------------HERE
self.poison_dmg += 1
if self.number_of == 1:
print ("The spider poisons you")
else:
print ("The spiders poison you")
The if statement is indented within a def that begins with another if poison_dmg > 0, and is not because you've already defined it to be 0 in the init.
i would invert the order of the if statements within the attack function, so you first generate a poison_dmg value, and then you evaluate wether or not that value is greater than 0.
Hope it works!
PD1: This is my firs stackoverflow comment ever, sorry if i missed some answering standards.
PD2: English is not my mother tongue, please let me know if i didn't make myself clear at any point.

Constantly checking a variable Python

Started trying to learn python yesterday, and I have run into a wall already T.T.
I am trying to make a health function in a game in python, and I need the variable health checked constantly to make sure it does not go below 0.
health = 10
health = (health - 5)
health = (health - 6)
Here I need the program to run a completely separate line of code, since health is now equal to -1. I do not want to have
if(health <= 0):
...
because I would need to copy paste this everywhere health is changed.
Would appreciate any help, thanks!
You don't need to check health constantly. Anytime you call a function reducing health (e.g. attack(character, damage)), you could simply check if health > 0. If not, you should call game_over().
Here's some code from a related question:
class Character:
def __init__(self, name, hp_max):
self.name = name
self.xp = 0
self.hp_max = hp_max
self.hp = hp_max
# TODO: define hp_bar here
def is_dead(self):
return self.hp <= 0
def attack(self, opponent, damage):
opponent.hp -= damage
self.xp += damage
def __str__(self):
return '%s (%d/%d)' % (self.name, self.hp, self.hp_max)
hero = Character('Mario', 1000)
enemy = Character('Goomba', 100)
print(enemy)
# Goomba (100/100)
hero.attack(enemy, 50)
print(enemy)
# Goomba (50/100)
hero.attack(enemy, 50)
print(enemy)
# Goomba (0/100)
print(enemy.is_dead())
# True
print(hero.xp)
# 100
I'm not familar with the python language, but my proposal can be tranferred to python.
Create a function that decreases the health value but never returns a value lower than zero. This is the pseudo-code:
function integer decreaseHealth(parameter health, parameter loss)
{
integer newHealth = health - loss
if (health < 0)
return 0
else
return newHealth
}
So I would need to type something like
if(health <= 0)"
print("Game over")
else:
print("New health")
Shame there isn't something in python for this, wish I could put before my code:
cont if(health <= 0):
print("Game over")
This would mean that whenever the health reached 0 or below, no matter where in the code after this, Game Over would print.
Then I wouldn't need to type anything when health is taken away apart from health = health - 1

How to call variable from one function in another file inside a function in another file?

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))

Categories