Popcorn Hack #1: Real World Applications

  1. Cybersecurity (e.g., Encryption Keys)
    Random numbers are used to generate cryptographic keys in secure systems. These keys must be unpredictable to prevent hackers from guessing or reproducing them. True randomness helps ensure secure communication, password protection, and online transactions.

  2. Gaming (e.g., Video Games or Gambling)
    In video games and gambling (like slot machines or online poker), random number generation ensures fairness and unpredictability. It determines events like loot drops, enemy behavior, or dice rolls, making the experience engaging and fair for players.

Popcorn Hack 2: Magic 8-Ball

import random

def magic_8_ball():
    """Return a random Magic 8-Ball response based on set probabilities."""
    roll = random.random()  # random float from 0.0 to 1.0

    if roll < 0.5:
        return "Yes"  # 50%
    elif roll < 0.75:
        return "No"   # 25%
    else:
        return "Ask again later"  # 25%

# Example usage
for _ in range(10):
    print("Magic 8-Ball says:", magic_8_ball())

Magic 8-Ball says: Yes
Magic 8-Ball says: No
Magic 8-Ball says: Yes
Magic 8-Ball says: Yes
Magic 8-Ball says: Ask again later
Magic 8-Ball says: Yes
Magic 8-Ball says: Ask again later
Magic 8-Ball says: No
Magic 8-Ball says: Yes
Magic 8-Ball says: Yes

Popcorn Hack 3

def traffic_light_simulation(steps=20):
    cycle = [("Green", 5), ("Yellow", 2), ("Red", 4)]
    current_step = 0
    cycle_index = 0
    time_in_state = 0

    for t in range(1, steps + 1):
        light, duration = cycle[cycle_index]
        print(f"Time Step {t}: {light}")
        time_in_state += 1

        if time_in_state == duration:
            cycle_index = (cycle_index + 1) % len(cycle)
            time_in_state = 0

traffic_light_simulation()

How is this a simulation?

This is a simulation because it models how a traffic light behaves over time, using logical rules and time steps to mimic real-world traffic control. It helps us understand and predict traffic flow patterns, which is crucial for designing safer and more efficient intersections.

Homework Hack 1: Create a Simple Dice Game (Randomness AND Simulation)

import random

def roll_dice():
    """Roll two dice and return their values and sum."""
    die1 = random.randint(1, 6)
    die2 = random.randint(1, 6)
    total = die1 + die2
    print(f"You rolled: {die1} + {die2} = {total}")
    return total

def play_dice_game():
    """
    Play one round of the dice game.
    Returns True if player wins, False if player loses.
    """
    first_roll = roll_dice()

    # Check immediate win or loss conditions
    if first_roll in [7, 11]:
        print("You win!")
        return True
    elif first_roll in [2, 3, 12]:
        print("Craps! You lose.")
        return False
    else:
        point = first_roll
        print(f"Your point is {point}. Keep rolling until you roll {point} (win) or 7 (lose).")
        
        while True:
            roll = roll_dice()
            if roll == point:
                print("You rolled your point! You win!")
                return True
            elif roll == 7:
                print("You rolled a 7. You lose.")
                return False

def main():
    """Main game function with game loop and statistics."""
    wins = 0
    losses = 0

    while True:
        play = input("\nDo you want to play a round? (yes/no): ").strip().lower()
        if play in ['yes', 'y']:
            if play_dice_game():
                wins += 1
            else:
                losses += 1
            print(f"Current Stats -> Wins: {wins}, Losses: {losses}")
        elif play in ['no', 'n']:
            print(f"\nThanks for playing! Final Stats -> Wins: {wins}, Losses: {losses}")
            break
        else:
            print("Please enter 'yes' or 'no'.")

if __name__ == "__main__":
    print("Welcome to the Dice Game!")
    main()