#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()
Related
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.
When the player enters the letter 'w' the players' z value increases by one and the enemy x value increases by 0.5. I want the enemy object to be deleted when the player enters the letter 'e' and to have the z value increase when pressed w is pressed as normal. How do I get python to ignore certain sections of code if an object is deleted?
class Enemy:
x = 1
play = True
z = 1
while play:
command = input('')
if command == 'e':
del Enemy
if command == 'w':
z += 1
print(z)
if z >= Enemy.x:
# stop this from being executed after e is pressed
Enemy.x += 0.5
print(Enemy.x)
You can use booleans like this:
class Enemy:
x = 1
play = True
z = 1
deleted = False
while play:
command = input('')
if command == 'e':
del Enemy
deleted = True
if command == 'w':
z += 1
print(z)
if z >= Enemy.x and not deleted:
Enemy.x += 0.5
print(Enemy.x)
You shouldn't be trying to delete classes. Instead, you can create a game context that stores the state of your game. This will contain an enemy object (which can be None if the enemy is deleted) and other variables related to the specific game. Then to start the game, you create a new Game instance and pass it a new Enemy instance. This will allow you to grow you game in a more maintainable way:
class Enemy:
x = 1
class Game:
def __init__(self, enemy):
self.enemy = enemy
self.play = True
self.z = 1
game = Game(Enemy()) # new game with fresh state (enemy, z, etc)
while game.play:
command = input('')
if command == 'e':
game.enemy = None
if command == 'w':
game.z += 1
print(game.z)
if game.enemy is not None and game.z >= game.enemy.x:
# stop this from being executed after e is pressed
game.enemy.x += 0.5
print(game.enemy.x)
You could probably improve the above by making the things in the loop methods of the Game class. And, instead of directly manipulating game.enemy.x, give the enemy class a method for increasing score. That will allow different enemies to have different behavior, etc...
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)
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))
I'm not really sure how to word this, but I'll try my best. I've created a function for a zombie, and another one for attacks. But I don't know how to pass on the parameters of the zombie function into the attack function. Also if there is a more technical way to word this please let me know. Here is my test code for it, I'm sure this community will be able to figure out what I mean. The end goal is to create a function where I can plug in a monster name and have it's assigned parameters (health, defense, etc..) be run in through the combat function. ie def combat(monster_name): Any and all advice is much appreciated. Thank you!
#Functions
def zombie():
global zombie_hp
zombie_hp = 10
print "Zombie encounter"
print "Current Health:", zombie_hp
def attack(monster):
if monster > 0:
while monster > 0:
user_action = raw_input("Do you attack the zombie? [y]: ")
if user_action == "y":
monster_hp = monster_hp - 1
print "Health remaining: ", monster_hp
def user_action():
global user_action
user_action = raw_input("Do you attack the zombie? [y]: ")
# Zombie Encounter (attack_testing)
attack(zombie())
if zombie_hp == 0:
print "Zombie Defeated"
I suggest you use a class:
class Zombie:
def __init__(self):
self.defense = 10
self.hp = 100
def hit(self, hp):
self.hp-=hp
def upgrade(self, level):
self.defense+=level
This will remember the hp and defense for every zombie that you create
>>> Max = Zombie()
>>> Max.hit(17)
>>> Max.upgrade(2)
>>> Max.hp
83
>>> Max.defense
12
>>>