Popcorn Hack 1: Real-World Applications

Question:

Name two real-world applications where random number generation is essential and briefly explain why.

Answer:

  1. Online Gaming (e.g. Dice Rolls, Loot Drops)
    • Random numbers are used to determine game outcomes such as dice rolls, card shuffling, enemy behavior, and loot drop chances. This randomness makes the game unpredictable and fair.
  2. Cybersecurity (e.g. Password Generation, Encryption)
    • Secure systems rely on random numbers to generate unpredictable passwords, encryption keys, and tokens. This helps prevent hackers from guessing or reproducing access credentials.

Popcorn Hack 2

import random

def magic_8_ball():
    roll = random.randint(1, 100)
    if roll <= 50:
        return "Yes"
    elif roll <= 75:
        return "No"
    else:
        return "Ask again later"

# Test the magic_8_ball function
for _ in range(5):
    print(magic_8_ball())
#

Pocorn Hack 3

🍿 Popcorn Hack 3: Traffic Light Simulation

πŸ› οΈ Modified Task:

  • Green lasts 5 steps.
  • Yellow lasts 2 steps.
  • Red lasts 4 steps.
  • Run the simulation for 20 time steps.

πŸ“ Modified Python Code:

states = ["Green", "Yellow", "Red"]
durations = {"Green": 5, "Yellow": 2, "Red": 4}
timeline = []

# Simulate 20 time steps
time = 0
state = "Green"
counter = 0

while time < 20:
    timeline.append((time, state))
    counter += 1
    if counter == durations[state]:
        counter = 0
        current_index = states.index(state)
        state = states[(current_index + 1) % len(states)]
    time += 1

for t, s in timeline:
    print(f"Time {t}: {s}")

Explanation: This is a simulation because it models the behavior of a real-world traffic light system over time without needing an actual traffic signal. It helps people understand and test timing patterns, which are important for road safety and efficient traffic flow. In the real world, such simulations are good for pedestrian and driver safety.

Homework Hack 1

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

🎯 Game Rules:

  1. Player rolls two dice.
  2. Win immediately if the sum is 7 or 11.
  3. Lose immediately if the sum is 2, 3, or 12.
  4. Any other sum becomes the β€œpoint”.
  5. Player keeps rolling:
    • Win if they roll the point again.
    • Lose if they roll a 7.

πŸ“ Python Code:

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()

    if first_roll in [7, 11]:
        print("You win!")
        return True
    elif first_roll in [2, 3, 12]:
        print("You lose!")
        return False
    else:
        point = first_roll
        print(f"Point is set to {point}. Keep rolling!")

        while True:
            roll = roll_dice()
            if roll == point:
                print("You hit the 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("Do you want to play a round? (yes/no): ").strip().lower()
        if play == "yes":
            if play_dice_game():
                wins += 1
            else:
                losses += 1
            print(f"Current Stats -> Wins: {wins}, Losses: {losses}")
        elif play == "no":
            print(f"Final Stats -> Wins: {wins}, Losses: {losses}")
            print("Thanks for playing!")
            break
        else:
            print("Please enter 'yes' or 'no'.")

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