Monday 25 September 2017

Python App 2: Magic Class, Fixing Heals and Charge MP magic type!

It's a pretty awesome feeling when you first use what you have learned to fumble around the code and create something entirely new.



The last lesson I completed was to do with moving magic into its own class rather than the main script. And, although the tutor nearly broke his (and my) game because of a mistake he made in the video, I managed to finish it successfully. I then realised I hadn't included a "heal" function for my Player... So I hacked it together, using some of the code for dealing damage, and replacing the minus sign with a plus. I also added an "if" statement that set the hp to maxhp if the HP went above that amount (effectively capping the HP to whatever the max is.

As such, the magic code looked like this:

...
def take_damage(self, dmg):
self.hp -= dmg
if self.hp < 0:
self.hp = 0
return self.hp

def heal(self, dmg):
self.hp += dmg
if self.hp > self.maxhp:
self.hp = self.maxhp

...
 I then added a line to my main code copying the black magic code but replacing it as such:


...
if spell.type == "white":
player.heal(magic_dmg)
print(bcolors.OKBLUE + "\n" + spell.name + " heals for", str(magic_dmg), "HP." + bcolors.ENDC)
elif spell.type == "black":
enemy.take_damage(magic_dmg)
print(bcolors.OKBLUE + "\n" + spell.name + " attacks for", str(magic_dmg), "HP." + bcolors.ENDC)
...

Feeling pleased with my work, I decided to create a magic that charges some MP called Pray (at a 0MP cost); first I created another copy of the heal code, but tweaked it as such:

...
def charge(self, dmg):
self.mp += dmg
if self.mp > self.maxmp:
self.mp = self.maxmp
...

And then finished by adding an extra line to the main script:

...
elif spell.type == "charge":

player.charge(magic_dmg)
print(bcolors.OKBLUE + "\n" + spell.name + " charges", str(magic_dmg), "MP." + bcolors.ENDC)
...

And... Well, it worked! Which astounded me! It may be a tiny thing, but it shows me that I'm actually learning the ropes and create my own deviations rather than purely copying/pasting code! It appears I'm actually understanding it!

As usual, my code is available to peruse and learn from at my GitHub page.  The course I am learning from is Nick Germaine's "The Complete Python Course: Beginner to Advanced!" Available at StackSkills.

No comments:

Post a Comment