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:
- Ask for head or tail
- Flip a coin
- If the guess matches the result, then it’s a win
To build this app, I will work you through the following steps:
- Create a new project workspace
- Just print “flip a coin” and “It’s a head” to console
- 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
- Ask the user for input for random_val (instead of pretending it is always 0.50)
- Instead of getting the random value from the user, get it by calling seed() and random() from the Python random module.
- Improve the “randomness” by using the current timestamp as a “seed”. The coin flip should now be fair.
- Add the for loop, so that the coin is flipped 10 times in a roll
- Keep a tally of how many heads and tails are there after 10 coin flips