Translations of this page:

005 random


Randomizing damage

Even if the Goblin Dice Duel game has now visual (text) output, it is still extremly boring and predictable. Grunty always wins and each game has 22 rounds.

To make the game somewhat more intersting, let us randomize the damage. In game mechanics, this reflect the luck of combat as well as the skill of attacking, hitting and damaging an opponent as well as doging and blocking damage. Or, more practical, to simulate dice with different amount of eyes.

Python has no random functionality in itself but it comes shipped with a large set of standard modules (the python standard libary, often referred to as “batteries included”).

One of those modules is the random module. You can access all functions of this module in your python code if you import the random first, usually at the beginning of your code. After a module is once imported, you can use all of this module's functions. In this case, i use the random.randint() function to get random integer numbers, like if i would rolling dice.


Try it out in the python shell:

>>>import random

You may get other numbers, but if you type it often enough, you will get all (integer) numbers between 1 and 6.

Working with the python shell:
instead of writing the same line over and over again, just use the cursor up key and hit Enter twice.
Less typing, more dice throwing !

The random.randint() function is easy to understand. It has 2 arguments or parameters, the lowerbound and the upperbound. The function will return an integer number between (including) those bounds. See the online documentation:

random.randint(a, b)
Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).

source code example

Now use the python editor with this improved version of the Goblin Dice Duel game:

even better print formatting

You noticed the strange stuff inside the curly brackets ?

print("{0:2d} Stinky: {1:3d} Grunty: {2:3d}".format(combatround, hitpointsStinky, hitpointsGrunty))

While the number left of the colon (“:”) inside the curly brackets still indicate what variable will later displayed at this position, the chars right of the colon control the how this variable is displayed. Here the output is formatted to be 2 (combatround) or three (hitpointStinky, hitpointsGrunty) chars wide.

See for more details

online example

Of course you can play and modify this example online, just click on the graphic:
Click on the graphic!

As you can see in this example output, Stinky did not last long. It is however theoretical possible now that he last longer than Grunty.


en/python/goblins/step005.txt · Last modified: 2014/01/09 11:07 (external edit)