A Simple Battle System
Lately I’ve been playing around with Python. I’ve completed all the Codecademy courses and have gotten nearly all the way through Learn Python The Hard Way, which is a great resource for learning. A couple of the exercises are creating text based adventure games. One of the extra credit prompts from LpTHW was to come up with some sort of battle system. Here’s my first stab at it, it’s also my first attempt at doing some OOP. If you copy this and run it, you will be prompted to make a decision to either fire your weapon or to run away. Each time you fire your weapon there is a chance for a miss, hit or extra damage hit. Same goes for the computers turn. You keep doing this until one of the player’s health reaches zero. It’s not perfect, but I’m proud of it and plan on adding more features, like powerups, different weapons with varying “accuracy” and “damage” amounts, and the ability to fight more than one opponent.
from random import randint
class Character(object):
def __init__(self, name, health):
self.name = name
self.health = health
def attack(self, target):
roll = randint(1,12)
if roll <= 3:
print "%s misses. Deals 0 damage" % (self.name)
return target.take_dmg(0)
elif roll <= 10:
print "%s hits his target. Deals 1 damage" % (self.name)
return target.take_dmg(1)
else:
print "%s hits his target with great accuracy. Deals 3 damage" % (self.name)
return target.take_dmg(3)
print "%s is attacking %s" % (self.name, target.name)
def take_dmg(self, dmg):
self.health = self.health - dmg
return self.health
if self.health <= 0:
self.die()
def die(self):
print "%s is dead" % (self.name)
exit(1)
class Player(Character):
pass
class Villain(Character):
pass
class Battle(object):
def __init__(self, player, villain):
self.player = player
self.villain = villain
def fight(self):
print "You can 'fire' your wepaon or you can try to 'run away' but it may not work!"
while True:
if (self.player.health <= 0):
return self.player.die()
elif (self.villain.health <= 0):
return self.villain.die()
choice = raw_input("> ")
if choice == "fire":
self.player.attack(self.villain)
self.villain.attack(self.player)
print "Your health: %s\n%s health: %s" % (self.player.health, self.villain.name, self.villain.health)
elif choice == 'run away':
if randint(0,1) == 0:
print "You try to run away, but your foe catches you."
self.player.die()
else:
print "You try to run away and are successful... this time."
exit(1)
player_one = Player("Player 1", 10)
computer = Villain("Computer", 10)
battleScene = Battle(player_one, computer)
battleScene.fight()
1 Notes/ Hide
- luckypains liked this
- randallzaitz posted this