Python Week – Day 2 – Simple Coin Flip Game

Follow the instruction from Day 1 to create another python project. In this python project, create a file called flip.py

How does a Coin Clip game work?

A coin flip is a simple game of chance that can have one of two outcomes: heads or tails. When you flip a coin, the outcome is determined by a combination of the initial conditions of the coin (i.e., its weight distribution, air resistance, initial velocity, etc.) and external factors such as air currents, surface friction, and how the coin lands.

In a fair coin flip, the probability of getting heads or tails is exactly 50%, assuming the coin is not biased in any way. Therefore, if you flip a fair coin multiple times, you would expect to get heads about half the time and tails about half the time.

In a programmatic implementation of a coin flip game, we can simulate the coin flip by generating a random number between 0 and 1. If the result is less than 0.5, we can consider it heads, and if it’s greater than or equal to 0.5, we can consider it tails. This method simulates the 50/50 probability of a fair coin flip and allows us to program a simple and fair coin flip game in Python.

The logic of the game is straightforward – the player chooses whether to flip a coin, and the program uses the logic of the coin flip to randomly generate either “heads” or “tails.” The player’s goal is to predict which outcome will occur, and they win if their prediction is correct.

A very simple coin flip game could work as follow:

  1. Ask for head or tail
  2. Flip a coin
  3. If the guess matches the result, then it’s a win

To build this app, I will work you through the following steps:

  1. Create a new project workspace
  2. Just print “flip a coin” and “It’s a head” to console
  3. Create a placeholder variable called “random_val”, but set it to “0.50” (pretend it’s always 0.50). Add code to check if random_val is larger than 0.50, if so, print HEAD, else print TAIL
  4. Ask the user for input for random_val (instead of pretending it is always 0.50)
  5. Instead of getting the random value from the user, get it by calling seed() and random() from the Python random module.
  6. Improve the “randomness” by using the current timestamp as a “seed”. The coin flip should now be fair.
  7. Add the for loop, so that the coin is flipped 10 times in a roll
  8. Keep a tally of how many heads and tails are there after 10 coin flips

Step 1 Create a new project coin-flip

Create a new folder called “coin-flip”

Open Visual Studio Code and start a new window. Click on “Open Folder” and select the “coin-flip” folder.

Once open, on Windows, hit Control+Shift+P to open the Command prompt. Select “Python: Create Environment”

You can select either Venv or Conda. I use Venv

Select the recommended Python Interpreter

Wait a few minutes for the virtual environment to be set up

Once set up, you should see a dialog that looks like this

As well as the new .venv folder under the coin-flip folder

Click on the “Create a new file” icon, and create a new file called flip.py.

Step 2: Just print “flip a coin” and “It’s a head” to console

Let’s print two lines to the console: (Note, the line that starts that “#” is a comment and is added to help you understand the code but will not be executed by the python interpreter.

# print a value 
print("flip a coin");
print("It's a head");

Step 3: Add another variable to hold the random value to decide the coin flip result

Create a placeholder variable called “random_val”, but set it to “0.50” (pretend it’s always 0.50). Add code to check if random_val is larger than 0.50, if so, print HEAD, else print TAIL

HEAD = "head"
TAIL = "tail"
# define a variable 
random_val = 1;
if (random_val == 1):
    print(HEAD)
else:
    print(TAIL)

Step 4: Ask the user for input for flip

Instead of pretending that the flip is always 0, ask the user to enter it:

HEAD = "head"
TAIL = "tail"
# take user input 
my_input = input("value=");

random_val = int(my_input)

if (flip == 0):
    print(HEAD)
else:
    print(TAIL)

Step 5: Get the real random value using Python random module

Instead of getting the random value from the user, get it by calling seed() and random() from the Python random module.

import random

HEAD = "head"
TAIL = "tail"
random.seed(10)
print(random.random())
flip = random.randint(0,1);
if (flip == 0):
    print(HEAD)
else:
    print(TAIL)

Step 6: Improve the randomness by using the current timestamp as “seed”

Improve the “randomness” by using the current timestamp as a “seed”. The coin flip should now be fair.

import random
import time

HEAD = "head"
TAIL = "tail"

# ts stores the time in seconds
ts = time.time()
  
# print the current timestamp
print(ts)
# use timestamp as random number seed
random.seed(ts)
# generate pseudo random number
flip = random.randint(0,1);
# print the generated random number (ranging from 0 to 1)
print(flip);
# If the generated random number is larger than 0.5, it's a head
# else it's a tail
if (random_val == 0):
    print(HEAD)
else:
    print(TAIL)

Step 7: Add the for loop, so that the coin is flipped 10 times in a roll

import random
import time

HEAD = "head"
TAIL = "tail"

for i in range(10):
    # ts stores the time in seconds
    ts = time.time()

    # use timestamp as random number seed
    random.seed(ts)
    # generate pseudo random number
    random_val = random.random();

    # If the generated random number is larger than 0.5, it's a head
    # else it's a tail
    if (random_val> 0.50):
        print(HEAD)
    else:
        print(TAIL)

Step 8: Keep a tally of how many heads and tails are there after 10 coin flips

import random
import time

HEAD = "head"
TAIL = "tail"
num_heads = 0
num_tails = 0
for i in range(10):
    # ts stores the time in seconds
    ts = time.time()

    # use timestamp as random number seed
    random.seed(ts)
    # generate pseudo random number
    random_val = random.random();

    # If the generated random number is larger than 0.5, it's a head
    # else it's a tail
    if (random_val> 0.50):
        print(HEAD)
        num_heads += 1;
    else:
        print(TAIL)
        num_tails += 1;

# print ( "number of heads=" + num_heads)
# print ( "number of tails=" + num_tails)
print ( "number of heads=" + str(num_heads))
print ( "number of tails=" + str(num_tails))

To learn more:

  • Create/Clone the coinflip project locally
  • Checkout https://www.codecademy.com/courses/learn-python-3 and review the concepts we have gone over today
  • Update the Coin Flip game so that it asks for “guess”, and if the guess matches the result, it’s a Win. Bonus (to get PlayStation swags
  • Build a Dice Throwing game  based on the Coin Flip
  • Checkout PyGame site https://www.pygame.org/news and build a simple game to share