ThePythonGameBook

learn Python. Create Games

User Tools

Site Tools


en:python:goblins:step012

012 class

step012

using classes

Enhancing the Goblin Dice Duel game with classes makes the code a bit more readable. Most important, it allows us to create large armys of goblins ! At the moment only 2 goblins, Stinky and Grunty, are created with gauss-randomized stat values:

source code

click reload on your browser if you see no source code here or visit Github.com

code discussion

  • The format mini language: {:>4.1f} inside a format string means: right align (>) a float (=floating point number) with a total length of 4 digits and use 1 digit precision right of the decimal point.
  • the method report(self) of the class Goblin() exist, but is not used in this code example.
  • the funcitons compareValues() and output() and strike() takes now class instances as arguments
  • inside the Game() function, 2 class instances of the Goblin() class are created and stored in the variables stinky and grunty
  • notice the dot-notation (stinky.hitpoints) in the while-loop

output

--- Goblin Dice Duel ---


           Stiny | vs. | Grunty 
 ----------------+-----+-----------
 hitpoints: 13.4 |  <  | 21.5
 attack:    13.4 |  >  |  9.6
 defense:    9.8 |  <  | 10.6

==== combat start ====
---combat round   0--- Stinky: 13 Grunty: 22
Grunty strikes first: The attack failed... (13.61 <= 13.81)
Counterstrike of Stinky: Sucessfull counterattack !  (17.42 > 12.59)
...doing 4.83 damage.
---combat round   1--- Stinky: 13 Grunty: 17
Grunty strikes first: The attack failed... (11.61 <= 15.81)
Counterstrike of Stinky: Sucessfull counterattack !  (18.42 > 11.59)
...doing 6.83 damage.
---combat round   2--- Stinky: 13 Grunty: 10
Stinky strikes first: Sucessfull attack !  (19.42 > 12.59)
...doing 6.83 damage.
Counterstrike of Grunty: The counterattack failed... (11.61 <= 12.81)
---combat round   3--- Stinky: 13 Grunty: 3
Stinky strikes first: Sucessfull attack !  (17.42 > 13.59)
...doing 3.83 damage.
---combat round   4--- Stinky: 13 Grunty: -1
Game Over
Stinky wins

online

You can try out the example online; because the onlinetutor does not like looping more than 300 times i reduced the values stat values to force fewer combat rounds. Just click on the graphic below:
Click me

not using class

If it's only for the dot notation, you can do nearly the same WITHOUT using classes. Instead, use a clever container for your goblins, like a dictionary, where the attribute names of your class ( attack, defense, hitpoints, etc) are the keys of the dictionary and the attributes values are the values of the dictionary.

See this elegant code example from yipyip (as a bonus, it works with python2.x as well as with pyhton3.x:

click reload on your browser if you see no source code here or visit Github.com

step012
/var/www/horst/thepythongamebook.com/data/pages/en/python/goblins/step012.txt · Last modified: 2014/01/09 11:07 (external edit)