A mini combat system using class & function, and random damage. Player is "Java", enemy is "Python"...and you can see the final output attached...
- import
random
- from random import randint
-
- class
player:
- def
__init__(self,name,health):
- self.name = name
- self.health =
health
-
- def
attack(self,enemy):
- player.damage = randint(1,20) #Range
of damage.
- enemy.health -= player.damage #Minus enemy's health points based on
player's damage.
- print
"{} attacks {} !".format(player.name,enemy.name)
- print
"{}'s health is {}!".format(enemy.name,enemy.health)
- return
int(enemy.health)
-
- def
alive(self): #Define the condition that the player is
alive.
- return self.health > 0
-
- class
enemy:
- def
__init__(self,name,health):
- self.name = name
- self.health =
health
-
- def
attack(self,player):
- enemy.damage = randit(1,30) #Range of damage.
- player.health -= enemy.damage #Minus
player's health points based on enemy's damage.
- print
"{} attacks {}!".format(enemy.name,player.name)
- print
"{}'s health is {}!".format(player.name,player.health)
- return
int(player.health)
-
- def
alive(self): #Define the condition that the enemy is
alive.
- return self.health > 0
-
-
- def
combat(player, enemy):
- print "{} and {} enter into the combat!".format(player.name,enemy.name)
- while
player.alive() and enemy.alive(): #While
loop to keep player fighting in the combat.
- player.attack(enemy)
-
- if
player.alive():
- print
"{} killed {}!".format(player.name,enemy.name)
- elif
enemy.alive():
- print
"{} was killed by {}!".format(player.name,enemy.name)
-
- return
- player = player("Java", 80)
- enemy = enemy("Python", 100)
- combat(player,enemy) #Call
the function of combat.
The output:
Java and Python enter into the combat!
Java attacks Python !
Python's health is 96!
Java attacks Python !
Python's health is 83!
Java attacks Python !
Python's health is 79!
Java attacks Python !
Python's health is 62!
Java attacks Python !
Python's health is 61!
Java attacks Python !
Python's health is 48!
Java attacks Python !
Python's health is 31!
Java attacks Python !
Python's health is 14!
Java attacks Python !
Python's health is -3!
Java killed Python!
_______________________________________________________________________
Back to CodeCombat coding. At the level of "The Final Kithmaze":
Our goals are:
- Hero must survive.
- Defeat the ogres(3/3)
- Navigate the maze.
- Under 10 statements.
- Collect the gems.
Coding:
while True:
self.moveRight()
self.moveUp()
self.moveRight()
enemy = self.findNearestEnemy()
self.attack(enemy)
self.attack(enemy)
self.moveDown(2)
self.moveUp()
self.moveRight()
Screenshot:
No comments:
Post a Comment