Making an Alien Blaster Game for python [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Ok I'm trying to make a program where I have a certain health and ammo for the alien and the human. I need them to go ten rounds. I want them to go the ten rounds randomly. I'm new to python, so I have some of it figured out but I don't have all of it figured out. I need to know what exactly am I doing wrong and how to do it.
class Alien(object):
"""Time to shoot the Player"""
def __init__(self,name,health,ammo):
self.name = name
name = input("What would you like to name your Alien?:")
self.health = 75
self.ammo = 50
def _str_(self):
return self.name
def blast(self,enemy):
import random
ammunition = random.randrange(5)
if ammunition >2
self.ammo(health)
print(self.name,"has shot the Player.")
print("He has",self.ammo,"ammo left.")
elif self.ammo == 0:
print(self.name,"is out of ammo.")
def health(self,health):
import random
shoot = random.randrange(10)
if shoot > 5
self.health(ammo)
if self.health >0:
print(self.name,"has been shot down. He has",self.health,"health left.")
elif self.health == 0
print("Im already dead. There's no way you can kill me again!!!")
class Player(object):
"""Time to shoot the Alien"""
def __init__(self,ammo,health,name):
self.name = name
name = input("What would you like to name your player?:")
self.ammo = 50
self.health = 75
def _str_(self):
return self.name
def blast(self,enemy):
import random
ammunition = random.randrange(5)
if ammuntion >2
self.ammo(health)
print (self.name,"has shot the alien.")
print ("He has",self.ammo,"ammo left.")
elif self.ammo == 0:
print(self.name,"is out of ammo.")
def health(self,health):
import random
shoot = random.randrange(10)
if shoot > 5
self.health(ammo)
if self.health >0:
print(self.name,"has been wounded. He has",self.health,"health left.")
elif self.health == 0:
print("I'm already dead. There's no way you can kill me again!!!")
These are my two classes for it.

I think i know what you are looking for. I remember writing a similar program for my sophomore school year and hope this helps.
class Player(object):
""" A player in a shooter game. """
def __init__(self,ammo):
self.ammo = ammo
self.lose = False
def blast(self, enemy):
if self.lose:
print "You were unsuccessful and did not kill the alien!\nNow the Earth was destroyed thanks to you."
else:
print "The player blasts an enemy."
if self.ammo > 0:
self.ammo -= 1
print "Your ammunition count is reduced by 1."
print "The alien took 1 damage! You've done it!\n"
enemy.die()
else:
if enemy.health == 0:
print "They're already dead, yo."
else:
self.lose = True
print "The alien has more health than you have ammo."
print "You run out of ammo and die!"
class Alien(object):
""" An alien in a shooter game. """
def __init__(self, health):
self.health = health
def die(self):
if self.health > 1:
self.health -= 1
print "Is that all you've got??\n"
elif self.health == 1:
self.health -= 1
print "Oh no im gonna die"
else:
print "The alien is already dead. What you're doing is unneccessary."
# main
print "\tThe Death of an Alien\n"
#same health and ammo
print "\n-----You have 6 counts of ammo.-----"
print "-----The alien has 6 health.-----\n"
hero = Player(6)
invader = Alien(6)
for i in range(6):
hero.blast(invader)
#lower health than ammo
print "\n-----You have 6 counts of ammo.-----"
print "-----The alien has 5 health.-----\n"
hero = Player(6)
invader = Alien(5)
for i in range(6):
hero.blast(invader)
#lower ammo than health
print "\n-----You have 5 counts of ammo.-----"
print "-----The alien has 6 health.-----\n"
hero = Player(5)
invader = Alien(6)
for i in range(6):
hero.blast(invader)
raw_input("\n\nPress the enter key to exit.")

Related

how to make a pokemon battle with def

so this is my code( or just a long sample)
from easygui import*
health = 100
ai_h = 100
moves = ['scratch']
class player:
def starter():
starter = buttonbox('what do you want to see?',
choices = ['fjade', 'soarer','mudwet'])
msgbox = ('that is a great choice')
def p_attack():
global ai_h
battle = choicebox('battle, chose your move!',
choices = moves)
if battle == 'scratch':
msgbox('you used scratch')
ai_h = ai_h - 10
msgbox(ai_h)
if health < 0:
msgbox('you failed')
quit()
sys.exit()
def __init__(self):
self.health = health
class ai:
def __init__(self):
self.healtha = ai_h
def attack():
global health
msgbox('the oppenet hit you!')
msgbox('you lost 10 health')
health = health - 10
msgbox(health)
if ai_h < 0:
msgbox('you defeated ai')
class battle:
def __init__():
pass
def war(opponet, opponet_health, your_health):
msgbox('oppent want to battle!')`
that is my code and as you can see the def war(i wanted to use battle)
is not yet finished. I tried many examples but sometimes the ai's health goes to negative something and the program is still going. can anyone help?

Switching players [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm made a program that calculates the current health of a player and switches between them. I need help switching between players. This is what i have so far:
class Player():
def turn(life):
players = ['Player 1', 'Player 2']
life = 100
for player in players:
while life >= 0:
print (life)
print ("+, -, or end turn")
choice = input("> ")
if choice == "+":
print ("Damage taken")
healing = int(input("> "))
life += healing
elif choice == "-":
print ("Damage taken")
damage = int(input("> "))
life -= damage
elif choice == "end turn" or "end":
return
else:
print ("You lose!")
play = Player()
play.turn()
I've been in a similar position before. I would recommend doing something a bit different than the answer you might be looking for. Instead of looking for a solution to this individual problem, I would recommend looking at resources for game design patterns.
While I think that the learning curve might be a bit high initially, I think that if you learn to work with proper design patterns for game mechanics, you will find it much easier to build what you are after.
There are a few different resources that you can choose from. I used http://gameprogrammingpatterns.com/ (I have no association with this individual), but I also have a background in c++. I would look around for what might be the most intuitive for you and give it a try.
All the best!
Here is a start:
class Player:
def __init__(self, name, health=100):
self.name = name
self.health = health
def hit(self, n):
assert n >= 0
self.health -= n
def heal(self, n):
assert n >= 0
self.health += n
#property
def is_dead(self):
return self.health <= 0
class Game:
def __init__(self):
self.players = [Player("Adam"), Player("Bert")]
def turn(self, me, him):
# fill this in!
def play(self):
a, b = self.players
while True:
self.turn(a, b)
if b.is_dead:
print("{} won!".format(a.name))
break
else:
# swap players
a, b = b, a
if __name__ == "__main__":
Game().play()

Converting globals to class

I have been using global variables for a little text game in python and have come across a lot of articles saying that global variables are a no no in python. I have been trying to understand how to get what I have below (just a health variable and being able to change it and print it) working using classes but I am confused how I can converted something like this in a class. Any help, example, point in the right direction would be great.
Here is an example of me using variables.
import sys
import time
health = 100
b = 1
def intro():
print("You will die after two moves")
def exittro():
time.sleep(1)
print("Thanks for playing!")
sys.exit()
def move():
global health
global b
health -= 50
if health <= 51 and b >0:
print("almost dead")
b = b - 1
def death():
if health == 0 or health <= 0:
print("...")
time.sleep(1)
print("You died\n")
time.sleep(2)
print("Dont worry, this game sucks anyway\n")
exittro()
intro()
a = 1
while a == 1:
input("Press Enter to move")
move()
death()
Thank you
Edit: this is the kind of thing I have been trying to do...
class Test:
def __init__(self):
number = 100
def __call__(self):
return number
def reduceNum(self):
number -=10
def printNum(self):
print(number)
a = 1
while a == 1:
input("Enter")
Test.self.reduceNum()
Test.self.printNum()
I would avoid classes for this, as classes are generally slower. You could make the function return the new value for the health variable.
I would also suggest making a main controller function to take the return value and apply it to other functions. This prevents global variables outside of a function's scope.
import time
def intro():
print("You will die after two moves")
def outro():
time.sleep(1)
print("Thanks for playing!")
# sys.exit() # You can avoid this now by just stopping the program normally
def move(health):
health -= 50
if health <= 51:
print("almost dead")
return health # Return the new health to be stored in a variable
def death(health):
if health <= 0:
print("...")
time.sleep(1)
print("You died\n")
time.sleep(2)
print("Dont worry, this game sucks anyway\n")
return True # Died
return False # Didn't die
def main():
health = 100 # You start with 100 health
intro()
while not death(health):
# While the death function doesn't return `True` (i.e., you didn't die) ...
input("Press enter to move")
health = move(health) # `health` is the new health value
outro()
If you want to use classes, you need to actually instantiate the class (Make a new object from it) by doing instance = Test(). You also need to store variables as attributes of self (so self.number = number) as any local variables are different from each other.
class Test:
def __init__(self):
self.number = 100
def __call__(self):
return self.number
def reduceNum(self):
self.number -= 10
def printNum(self):
print(self.number)
a = 1
game = Test()
while a == 1:
input("Enter")
game.reduceNum()
game.printNum()
# Or:
print(game())
# As you've changed `__call__` to return the number as well.

Updating properties of an object in Python OOP

I am trying to create a simple game in Python using the OOP style.
The parent class is set up and there are two sub-classes, one for the hero and one for the ork.
Basically, when the hero attacks the ork (or vice versa) I want the health to be updated based on the damage done (damage is the amount of power the attacking character has). Currently, every time it loops it resets the health values back to the original of 100.
What is the best way of doing this using OOP? I can figure out how to do it in my own procedural and messy way, but I would like to see how it should be done.
class Character:
'''Blueprint for game characters'''
def __init__(self):
#default values
self.character = ""
self.speed = 0
self.power = 0
self.health = 100
def attack(self, attackObj):
self.attacker = self.character
self.attackerPower = self.power
self.victim = attackObj.character
self.victimHealth = attackObj.health
self.newHealth = self.victimHealth - self.attackerPower
print(self.character, "you have chosen to attack", self.victim)
print(self.victim, "you have suffered", self.attackerPower, "damage and your health is now", self.newHealth)
class Hero(Character):
'''Inherits from character to create hero'''
def __init__(self):
Character.__init__(self)
self.character = "Hero"
self.speed = 8
self.power = 9
print(self.character, "you have",self.speed, "speed,", self.power, "power and", self.health, "health.")
class Ork(Character):
'''Inherits from character to create ork'''
def __init__(self):
Character.__init__(self)
self.character = "Ork"
self.speed = 2
self.power = 8
print(self.character, "you have",self.speed, "speed,", self.power, "power and", self.health, "health.")
def main():
charclass = Character()
hero = Hero()
ork = Ork()
endLoop = False
while endLoop == False:
print("Please choose your character by typing the corresponding key: ")
print("H for hero")
print("O for ork")
charChoice = input()
if charChoice in ("H", "h", "hero", "Hero"):
charChoice = hero
enemy = ork
hero = Hero()
elif charChoice in ("O", "o", "ork", "Ork"):
charChoice = ork
enemy = hero
print("Please choose an action by typing the corresponding key: ")
print("A to attack")
actionChoice = input()
if actionChoice in ("A", "a"):
charChoice.attack(enemy)
else:
print("Nothing chosen!")
finishedYN = input("Have you finished? Y/N ")
if finishedYN in ("Y", "y", "Yes", "yes", "YES"):
print("You have chosen to end the game...")
endloop = True
break
else:
pass
if __name__ == "__main__":
main()
A quick fix to your code. Remove all these unecessary attributes, e.g. self.attacker (that's just self), self.attackPower (that's just self.power). self.victim = attackObj.character just gives your object a new attribute that is the same string as whatever attackObj.character is. Similarly, this:self.newHealth = self.victimHealth - self.attackerPower just creates a new attribute each time the method is called that will always be 100 - self.attack
def attack(self, attackObj):
attackObj.health -= self.power
print(self.character, "you have chosen to attack", attackObj.character)
print(attackObj.character, "you have suffered", self.power, "damage and your health is now", attackObj.health)
Really, an even better way is to add methods that mutate your object, that will be used as an interface with how your object interacts with other objects. So, for example:
class Character:
'''Blueprint for game characters'''
def __init__(self):
#default values
self.character = ""
self.speed = 0
self.power = 0
self.health = 100
def attack(self, victim):
victim.receive_damage(self.power)
def receive_damage(raw_damage):
self.health -= raw_damage
This improves the extensibility of your code. You could more easily implement a "buffs" system, or add an "armor" element, that affects how you recieve damage, without ever having to change the code in attack. You can override these methods in subclasses. So, perhaps you want all orks to have "thickskin", and in Ork:
def receive_damage(raw_damage):
self.health -= raw_damage*self.thickskin_modifier
Where self.thickskin_modifier was set in the Ork class __init__. It could be something like 0.9.

Simple way to decrease values without making a new attribute?

I'm making a program where you're firing a 'blaster', and I have 5 ammo. I'm blasting an alien who has 5 health. At the end I instantiate the player and make him blast 6 times to check that the program works correctly. But the way I've done it makes it so that the amount won't decrease. Is there an easy fix to this, or do I just have to make a new attribute for ammo and health? Here's what I have:
class Player(object):
""" A player in a shooter game. """
def blast(self, enemy, ammo=5):
if ammo>=1:
ammo-=1
print "You have blasted the alien."
print "You have", ammo, "ammunition left."
enemy.die(5)
else:
print "You are out of ammunition!"
class Alien(object):
""" An alien in a shooter game. """
def die(self, health=5):
if health>=1:
health-=1
print "The alien is wounded. He now has", health, "health left."
elif health==0:
health-=1
print "The alien gasps and says, 'Oh, this is it. This is the big one. \n" \
"Yes, it's getting dark now. Tell my 1.6 million larvae that I loved them... \n" \
"Good-bye, cruel universe.'"
else:
print "The alien's corpse sits up momentarily and says, 'No need to blast me, I'm dead already!"
# main
print "\t\tDeath of an Alien\n"
hero = Player()
invader = Alien()
hero.blast(invader)
hero.blast(invader)
hero.blast(invader)
hero.blast(invader)
hero.blast(invader)
hero.blast(invader)
raw_input("\n\nPress the enter key to exit.")
Think about it: the amount of ammunition available is part of a player's state. An object's state is best represented as instance variables of that object. So you should not have ammo as an argument to blast -- it should be self.ammo in that method, initialized to 5 or whatever in the __init__ you forgot to code;-).
It's not a matter of seeking for fancy workarounds to hide and stash that state somewhere else -- it's a matter of doing things in the simplest, most straightforward, most effective way. Why would you ever want anything but such a way?!
You need to keep track of the alien's health. All you're doing now is decrementing the "health" local variable in the Alien.die function.
Here's a little snippet that should help get you going in the right direction:
class Alien(object):
def __init__(self):
self.health = 5
def do_damage(self, amount):
self.health -= amount
Similar tracking required for player's ammo.
I just modify the above program by making 2 attributes named ammo and health.
I think they make program so easy. Try it for various outcomes by changing attributes' initial values.
class Player(object):
""" A player in a shooter game. """
def __init__(self, ammo):
self.ammo = ammo
def blast(self, enemy):
if enemy.health > 0:
if self.ammo > 0:
print "The player has blasted the alien.\n"
print "The player has", self.ammo, "ammunition left."
enemy.die()
elif self.ammo == 0:
print "The player can't blast the alien because he is out of ammunition.\n"
self.ammo -= 1
class Alien(object):
""" An alien in a shooter game. """
def __init__(self, health):
self.health = health
def die(self):
if self.health > 0:
self.health -= 1
print "The alien is wounded. He now has", self.health, "health left.\n"
if self.health == 0:
self.health -= 1
print "The alien gasps and says, 'Oh, this is it. This is the big one. \n"\
"Yes, it's getting dark now. Tell my 1.6 million larvae that I "\
"loved them...\nGood-bye, cruel universe.'\n"
elif self.health < 0:
print "The alien's corpse sits up momentarily and says, 'No need to blast me, I'm dead already!"
print "\t\tDeath of an Alien\n"
hero = Player(6)
invader = Alien(3)
blast = int(raw_input("How many times do you want to blast the alien? "))
for cnt in range(blast - 1):
hero.blast(invader)
Probably you want to do something like this:
class Player:
def __init__(self, ammo=5):
self.ammo=ammo
def blast(self, enemy):
if self.ammo>0:
self.ammo-=1
enemy.die(5)
else:
print "U are out of ammunition!"
You need to use self.health for the alien as well.
In class Player in the method named blast() your references to to ammo are incorrect. You want to refer to self.ammo in all cases within that function/method definition.
Furthermore you should probably (almost certainly) define an __init__ method to set the starting ammunition value to 5 (and perhaps later provide a reload() method to set self.ammo back up to 5 ... and so on.

Categories

Resources