Subscribe to Blog via Email
So I don’t doubt that many parents are bleeding out money for kid’s school fees, supplies, clothing and other demands this time of year. How many of you are in their local Target, Walmart or other store and after filling the cart with the necessary, the kids eye up the toy aisle and start to ask for something?
Even teens are not immune and may be asking for games. If you could turn around and say to them, “If you want the game, then why don’t you build it instead of buying it?”
Now as many of you have figured out, I’m starting to build an arsenal of Raspberry Pi content to teach in classes and meetups. The following is to simulate the game “Pass the Pigs”. If you’ve ever played this popular game that uses plastic pigs in the place of dice, it required my brain to rethink how I was coding my dice games to how I would code a game that used the fall placement of a plastic pig. This demonstrated one of the greatest things about Python- I still was using the same module, but I just used it in a different way to code my new game!
So let’s say we want to code a simple roll of dice game.
#Dice Roll import random #Insert space between import and code... for x in range(1, 2): dice_1 = random.randint(1, 6) dice_2 = random.randint(1, 6) print(dice_1 + ' + ' + dice_2)
The above code will do the following:
Now to change the code and create the Pass the Pigs game, we get to use the RANDOM module again, but the code changes as we are going to use a function to tell Random what “word options” will be used instead of random numbers to return. It will then use two pigs and then will output the roll, (which is a function).
#Pass the Pigs import random pig_fall = ['Razorback', 'Trotter', 'Snouter', 'Leaning Jowl', 'Pig Out', 'Oinker'] def pick_pigs(): Pig1 = random.randint(0, len(pig_fall) -1) Pig2 = random.randint(0, len(pig_fall) -1) return pig_fall[Pig1] + ' + ' + pig_fall[Pig2] print (pick_pigs())
This code is different from the first one, even though it really ends up doing the same thing. Notice that there are six options, just like there are six sides to a die. This is really very similar to the dice game, we’ve just used different code that works more efficiently with our requirements. By execution the code, we can then play the game!
>sudo python3 <script_name>.py
Leaning Jowl + Pig Out Trotter + Pig Out Leaning Jowl + Razorback
We can use the game instructions, (can be found online) to then add up our scores for our three players-
So there you have it and next time your kids ask you for toys and games, consider getting them a Raspberry Pi instead and make it pay forward, creating projects and games with it instead!
Until next time…