Simulation/Games and Random Algorithms
Simulation and Algorithms
Introduction to Simulation & Random Algorithms
What Are Simulations?
According to College Board, simulations are:
- Programs that model real-world events, systems, or processes to analyze behavior, make predictions, or test scenarios.
- Simplifications using abstraction to focus on key elements while omitting unnecessary complexity.
- Tools that often incorporate randomness or data-driven models to explore multiple possible outcomes.
- Efficient ways to study scenarios without real-world consequences, reducing cost and risk.
Why Do Games & AI Use Randomness?
Random algorithms create unpredictability, making games challenging and immersive:
- Enemy AI unpredictability (Pac-Man, Call of Duty)
- Loot drops & rewards (FIFA packs, Gacha games)
- Procedural generation (Minecraft, No Man’s Sky)
-
Go to a Game
Conway’s Game of Life
What is it?
Conway’s Game of Life is a simulation, not a traditional game. It models how cells (like organisms) live, die, or are born based on a few simple rules. It shows how complex patterns can emerge from simple behavior.
The Rules
Each square in the grid is a cell. A cell can be alive or dead. At each step (called a generation), the game follows these rules:
-
Underpopulation
A live cell with fewer than 2 live neighbors dies.
(It’s too lonely.) -
Survival
A live cell with 2 or 3 live neighbors stays alive.
(It has just enough support to live.) -
Overpopulation
A live cell with more than 3 live neighbors dies.
(It’s too crowded.) -
Reproduction
A dead cell with exactly 3 live neighbors becomes alive.
(It gets enough support to be “born.”)
Random Algorithms
A random algorithm is an algorithm that includes random choices to influence its output. These algorithms are useful for simulations, games, and decision-making when multiple outcomes are possible.
Example 1: Generating a Random Number
This algorithm generates a random number between 1 and 10.
import random
def generate_random_number():
"""Generates a random number between 1 and 10."""
return random.randint(1, 10)
# Generate and print a random number
print("Random number:", generate_random_number())
Random number: 5
Popcorn Hack #1: Dice Roll Simulation (Basic)
Objective:
Write a function that simulates a 6-sided dice roll using the random
module.
Starter Code
import random
def roll_dice():
# Write your code here to simulate a 6-sided dice roll
pass
# print("Dice roll:", roll_dice())
Example 2: Generating a Random Number using dice
This algorithm generates a biased dice role
import random
def biased_dice_roll():
"""Simulates a biased 6-sided dice roll where 6 appears 50% of the time."""
numbers = [1, 2, 3, 4, 5, 6]
probabilities = [0.1, 0.1, 0.1, 0.1, 0.1, 0.5] # 6 appears 50% of the time
return random.choices(numbers, probabilities)[0]
# Simulate 10 biased dice rolls
for _ in range(10):
print("Dice roll:", biased_dice_roll())
Popcorn Hack #2: Biased Color Generator
Objective:
Modify the function biased_color()
so that:
- Red appears 50% of the time
- Blue appears 30% of the time
- All other colors share the remaining 20%
Then print 10 random biased colors.
Starter Code
import random
def biased_color():
# Make a biased color generator, with a bias towards Red and Blue.
# Print 10 biased random colors
for _ in range(10):
pass
Key Concepts:
- Uses
random.randint(a, b)
to generate a random integer betweena
andb
. - Demonstrates the core idea of randomness in computing.
- Forms the basis for games, simulations, and decision-making algorithms.
Practice MC
How This Connects to Simulations and Games
1. Simulating Real-World Probability
- Many real-world events have unequal probabilities, just like how a biased coin isn’t 50-50.
- Example: Weather prediction – there’s not always a 50% chance of rain.
2. Decision-Making in AI
- AI in games and simulations often makes probabilistic decisions based on weighted randomness.
- Example: In a game, an enemy might attack 70% of the time and defend 30% of the time, just like our biased coin flip.
How to Tackle College Board Simulations MCQs
In AP CSP, simulation MCQs often involve modeling real-world systems, like robot movement or game behaviors. The goal is to complete algorithms that simulate processes or decisions, without needing to write the entire code—just filling in missing lines.
Approach for MCQs
- Break Down the Problem
- Read the scenario carefully (e.g., robot moving on a grid).
- Identify variables (position, target) and actions (move, check for obstacles).
- Look for Loops and Conditions
- Loops control repetition (e.g., robot keeps moving until it reaches the target).
- Conditions help the robot decide what to do (e.g., check if the path is clear).
- Fill in Missing Lines
-
In MCQs, you’ll often need to fill in missing code or choose the correct line to complete the algorithm.
-
2018 Q18:
A population researcher is interested in predicting the number of births that will occur in a particular community. She created a computer model that uses data from the past ten years, including number of residents and the number of babies born. The model predicted that there would be 200 births last year, but the actual number of births last year was only 120.
Which of the following strategies is LEAST likely to provide a more accurate prediction?
- A: Gathering data for additional years to try to identify patterns in birth rates
- B: Refining the model used in the computer simulation to more closely reflect the data from the past ten years
- C: Removing as many details from the model as possible so that calculations can be performed quickly
- D: Taking into consideration more information about the community, such as the ages of residents —
Homework Hack #1- Coin Flip Win Simulation
Objective:
Simulate a game where two players flip a coin. First to reach 3 heads wins.
Task:
- Use
random.choice()
to simulate flipping a coin ("heads"
or"tails"
). - Each player flips once per round.
- Track how many heads each player has.
- Stop when one player reaches 3 heads.
- Print the winner and how many rounds it took.
Part 2: Take a Quiz
- Submit screenshot of score on google form click to take the quiz