beanz Magazine

What are the Odds?

Liz Jones on Flickr

Time to grab your favourite good luck charm and get ready for some high-stakes coding!

Imagine you’re spending the evening at the arcade, dunking hoops, racing cars, shooting clowns, and otherwise having a grand old time. You come away with 100 tickets. But when you get to the prize counter, you’re given the option to play one final game of chance: Double or Nothing.

The rules are simple. You start by betting X number of tickets, and on ‘heads’ you double your bet. On ‘tails’, you lose everything.

In this article, we’ll use Python to write a quick ‘Double or Nothing’ game with five rounds, giving you five opportunities to win or lose tickets. So pull out your favourite good-luck charm and let’s start coding!

GETTING STARTED

Navigate to www.repl.it.

If you have an account, feel free to log in! Otherwise, click the blue ‘+ new repl’ button and select ‘Python’ as your desired language. Hit ‘Create Repl’ to access your code editor.

Start your code by importing the ‘random’ library. In the left-hand editor, write:

from random import *

Libraries are folders full of code written by professional programmers. The Python ‘random’ library will allow us to generate random numbers and pick random elements out of a list. Definitely useful when creating a game of chance!

Next, let’s make a variable to store the number of tickets:

tickets = 100

And finally, to help simulate our coin toss, we’re going to create a list containing the letters “H” (for heads) and “T” (for tails). Make sure to use square brackets for the list and surround your “H” and “T” with quotation marks. And watch out for that pesky comma in the middle!

coin = ["H", "T"]

THE MAIN LOOP

At the heart of every digital game is the concept of rounds. Even in a first-person shooter like Call of Duty or an action RPG like Skyrim, rounds exist in the form of second or millisecond updates to stats and graphics. And if your game has rounds, then your code needs a loop.

The main loop contains all the code for a single round: graphic updates, user input, plot choices, etc. While loops are popular since they keep going and going until something ends them. This allows the user to play for fifteen minutes, an hour, or whatever they want!

For simplicity, however, we’re going to use a for loop and fix our number of rounds at 5:

for _ in range(5):

Now, what needs to happen in a typical round of ‘Double or Nothing’? First, you need to place a bet. Next, we flip a coin, and either double your bet or subtract it from your remaining tickets. And that’s pretty much it!

For the bet, it’s probably a good idea to display how many tickets are left, so you don’t go over:

for _ in range(5):
print("You have " + str(tickets) + " tickets")

Sadly, Python can’t automatically convert between numbers and strings (text). We have to tell the program to treat the ‘tickets’ variable like text using the ‘str’ function.

Now, we’ll use the input function to prompt the player to enter their bet:

for _ in range(5):
print("You have " + str(tickets) + " tickets")
bet = input("How many tickets do you bet? ")

If you’ve used the input function before, you might remember that it always returns a string variable. In our code, however, the ‘bet’ variable corresponds to a number of tickets. So before doing anything else, let’s convert it into an integer:

bet = int(bet)

Psst! ‘Integer’ is just a fancy way of saying ‘whole number’, meaning it’s not a decimal.

FLIPPING THE COIN

To simulate flipping a coin, we’re going to pull out the ‘choice’ function from the random library. Given a list, this function randomly selects a single item. Just like pulling pieces of paper out of a hat! Since our ‘coin’ list only has two options, the result of this function can only be “H” (heads) or “T” (tails).

If the result is heads, we want to increase the player’s tickets by the amount they bet:

if choice(coin) == "H":
print("Heads! You win!")
tickets += bet

And if they lose, we decrease the number of tickets:
else:

print("Tails! You lost.")
tickets -= bet

Because we’re playing a text game, it’s a good idea to include lots of print statements to let the player know what’s going on. It would be jarring to play without knowing the result of the coin toss, and to just see your tickets increase or decrease.

THE PRIZE COUNTER

That’s it for the loop! Let’s add one final line to display the number of tickets remaining at the end of the game:

print("You end the game with " + str(tickets) + " tickets.")

Test out your code by pressing the green ‘run’ button at the top of the screen. If you want to double check your syntax, here’s a full listing of the program. Make sure that everything inside the loop is tabbed correctly, Python-style:

from random import *

tickets = 100
coin = ["H", "T"]

for _ in range(5):
print("You have " + str(tickets) + " tickets")
bet = input("How many tickets do you bet? ")
bet = int(bet)
if choice(coin) == "H":
print("Heads! You win!")
tickets += bet
else:
print("Tails! You lost.")
tickets -= bet

print("You end the game with " + str(tickets) + " tickets.")

At the end of the game, how many tickets do you have left? Let’s see what you could buy at our imaginary prize counter:

  • RUBBER BOUNCY BALL: 50 tickets
  • SQUEAKY DUCK: 100 tickets
  • TOY CAR: 150 tickets
  • SMALL STUFFED GIRAFFE: 200 tickets
  • LAVA LAMP: 250 tickets
  • GIANT STUFFED UNICORN: 300 tickets
  • REMOTE-CONTROL AIRPLANE: 400 tickets

Play the game a few times and see if your luck improves! Do you think ‘Double or Nothing’ is a good strategy to get more tickets?

TAKING THE CODE FURTHER

While we’ve created a simple, functional game, there’s lots of ways to make it more exciting. Here’s a few ideas to get you started:

    1. Make the game’s length variable. Let the user decide how many rounds to play, or use a while loop to make it indefinite.
    2. Make your code robust. In our current game, even if a player has only one ticket left, they can still bet ten. How can we prevent this?
    3. What about adding special ‘lightning rounds’? Instead of doubling your tickets, what if they quadruple them?

Feel free to let your imagination run wild as you invent new features. Happy hacking!

Learn More

Basic Python syntax

https://www.tutorialspoint.com/python/python_basic_syntax.htm

Python

https://www.kidscodecs.com/python/

For loops vs while loops

https://www.tutorialspoint.com/python/python_loops.htm

How Programming languages control the processing of instructions

https://www.kidscodecs.com/programming-control-flows/

Pygame: a primer

https://realpython.com/pygame-a-primer/

Python while loops

https://www.programiz.com/python-programming/while-loop

For and while loops

https://www.guru99.com/python-loops-while-for-break-continue-enumerate.html

What is double or nothing?

https://en.wikipedia.org/wiki/Double_or_nothing

Also In The June 2020 Issue

This online coding website makes it easy and fun to learn to code.

Got robots? Figuring out how to set them on a predefined course?

Looking for smart ways to make the most of your summer?

Computers would not exist without this number which has an interesting history.

Checkout how one school celebrated Pi Day with a helping of Raspberry Pi!

Aim for their Motherboard! This time we are talking about Computer Zombies!

Two satellites in identical orbits help measure the Earth with a unique plaque for future Earthlings.

Ever wonder if a computer could shake hands? It happens more than you would think!

Join us as we explore the weird history of Windows in computers!

Be wary of these password pitfalls that hackers love and learn how to keep your data secure!

Interesting stories about computer science, software programming, and technology for June 2020.