Skip to content

Instantly share code, notes, and snippets.

@pkulev
Last active March 14, 2016 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pkulev/364eab7e34ec48496668 to your computer and use it in GitHub Desktop.
Save pkulev/364eab7e34ec48496668 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import random
try:
ask = raw_input
except NameError:
ask = input
def make_entity(eclass, *args, **kwargs):
return eclass(*args, **kwargs)
class Entity(object):
def __init__(self, health, attack_power, percent_to_hit):
self.health = health
self.attack_power = attack_power
self.percent_to_hit = percent_to_hit
self.alive = health > 0
def take_damage(self, attack_power, percent_to_hit):
if random.random() <= percent_to_hit:
self.health -= attack_power
if self.health <= 0:
self.alive = False
class Cowboy(Entity):
def __init__(self, health=100, attack_power=35, percent_to_hit=0.5):
super(Cowboy, self).__init__(health, attack_power, percent_to_hit)
class Alien(Entity):
def __init__(self, health=200, attack_power=20, percent_to_hit=0.2):
super(Alien, self).__init__(health, attack_power, percent_to_hit)
def simulation(cowboys_num, aliens_num):
cowboys = [make_entity(Cowboy) for _ in range(cowboys_num)]
aliens = [make_entity(Alien) for _ in range(aliens_num)]
rounds = 0
while all(len(army) > 0 for army in [cowboys, aliens]):
rounds += 1
while cowboys[0].alive and aliens[0].alive:
cowboys[0].take_damage(
aliens[0].attack_power,
aliens[0].percent_to_hit)
aliens[0].take_damage(
cowboys[0].attack_power,
cowboys[0].percent_to_hit)
if not cowboys[0].alive:
cowboys.pop(0)
if not aliens[0].alive:
aliens.pop(0)
print("num of cowboys: ", len(cowboys))
print("num of aliens: ", len(aliens))
print("num of rounds: ", rounds)
def ask_user():
answer = ask("Do you want to continue [Y/n]: ")
return answer == "" or answer in ["Y", "y"]
def main():
cnum = ask("Num of cowboys [40]: ")
cnum = 40 if cnum == "" else int(cnum)
anum = ask("Num of aliens [500]: ")
anum = 500 if anum == "" else int(anum)
running = True
while running:
simulation(cnum, anum)
running = ask_user()
if __name__ == "__main__":
running = True
while running:
main()
running = ask_user()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment