Displaying Dice with Functions

This is an example of defining a function that takes a parameter.

yachtdice.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from __future__ import print_function
import random

def main():
    while True:
        r1 = random.randint(1,6)
        r2 = random.randint(1,6)
        r3 = random.randint(1,6)
        r4 = random.randint(1,6)
        r5 = random.randint(1,6)
        print("\nYou rolled: {} {} {} {} {}".format(r1, r2, r3, r4, r5))
        showDice(r1)
        showDice(r2)
        showDice(r3)
        showDice(r4)
        showDice(r5)
        if r1 == r2 == r3 == r4 == r5:
            break
    print("The Yacht!!")


def showDice(roll):
    print("+---+")
    if roll == 1:
        print("|   |\n| o |\n|   |")
    elif roll == 2:
        print("|o  |\n|   |\n|  o|")
    elif roll == 3:
        print("|o  |\n| o |\n|  o|")
    elif roll == 4:
        print("|o o|\n|   |\n|o o|")
    elif roll == 5:
        print("|o o|\n| o |\n|o o|")
    elif roll == 6:
        print("|o o|\n|o o|\n|o o|")
    print("+---+")


if __name__ == "__main__":
    main()

What You Should See


You rolled: 5 4 5 3 3
+---+
|o o|
| o |
|o o|
+---+
+---+
|o o|
|   |
|o o|
+---+
+---+
|o o|
| o |
|o o|
+---+
+---+
|o  |
| o |
|  o|
+---+
+---+
|o  |
| o |
|  o|
+---+

You rolled: 2 2 5 5 5
+---+
|o  |
|   |
|  o|
+---+
+---+
|o  |
|   |
|  o|
+---+
+---+
|o o|
| o |
|o o|
+---+
+---+
|o o|
| o |
|o o|
+---+
+---+
|o o|
| o |
|o o|
+---+

// skip a whole bunch of rolls

You rolled: 3 3 3 3 3
+---+
|o  |
| o |
|  o|
+---+
+---+
|o  |
| o |
|  o|
+---+
+---+
|o  |
| o |
|  o|
+---+
+---+
|o  |
| o |
|  o|
+---+
+---+
|o  |
| o |
|  o|
+---+
The Yacht!!

So explanation yet, sorry. Hopefully the code is enough. If you're already this far into the assignments, the code is probably enough.

So, did you catch that on line 17? In a lot of programming languages, you can only compare things in pairs. So you would have to do something like this: if r1 == r2 and r2 == r3 and r3 == r4 and r4 == r5:

Python is totally okay with comparing a bunch of things at once, though. It's handy.

Study Drills

  1. Add a sixth dice.



©2017 Graham Mitchell