f = open("sample.txt", "r")
text = f.read()

f2 = open("newfile.txt", "w")
f2.write("We're in Lecture 1!")
f2.close()

###

import re
import csv
import nltk
from nltk.sentiment import SentimentIntensityAnalyzer

# Download the VADER lexicon if not already present
#nltk.download('vader_lexicon', quiet=True)

def parse_gutenberg_chapters(file_path: str) -> list[tuple[str, str]]:
    """
    Reads a Project Gutenberg text file and splits it into chapters
    based on standard headings (e.g., CHAPTER I, CHAPTER 1, etc.).
    """
    with open(file_path, 'r', encoding='utf-8') as f:
        text = f.read()

    # Lookahead regex to split on lines starting with CHAPTER/Chapter
    chapter_pattern = r'\n(?=(?:CHAPTER|Chapter)\s+(?:[IVXLCDM]+|\d+)\b)'
    raw_chunks = re.split(chapter_pattern, text)
    
    chapters = []
    for chunk in raw_chunks:
        chunk_str = chunk.strip()
        if not chunk_str:
            continue
            
        heading_match = re.match(r'^(CHAPTER|Chapter)\s+([IVXLCDM]+|\d+)', chunk_str)
        if heading_match:
            chapter_title = heading_match.group(0)
            chapters.append((chapter_title, chunk_str))
            
    return chapters

def analyze_and_display(file_path: str):
    sia = SentimentIntensityAnalyzer()
    chapters = parse_gutenberg_chapters(file_path)
    
    if not chapters:
        print("No standard chapter headings found. Please check file formatting.")
        return

    # Print formatted table header
    header = f"{'Chapter':<15} | {'Compound':<10} | {'Positive':<10} | {'Neutral':<10} | {'Negative':<10} | {'Sentiment':<10}"
    print("\n" + header)
    print("-" * len(header))
    
    results = []
    for title, text in chapters:
        scores = sia.polarity_scores(text)
        compound = scores['compound']
        
        if compound >= 0.05:
            label = "Positive"
        elif compound <= -0.05:
            label = "Negative"
        else:
            label = "Neutral"
            
        row = {
            "Chapter": title,
            "Compound": round(compound, 3),
            "Positive": round(scores['pos'], 3),
            "Neutral": round(scores['neu'], 3),
            "Negative": round(scores['neg'], 3),
            "Sentiment": label
        }
        results.append(row)
        
        # Print table row
        print(f"{row['Chapter']:<15} | {row['Compound']:<10} | {row['Positive']:<10} | {row['Neutral']:<10} | {row['Negative']:<10} | {row['Sentiment']:<10}")

    # Save to a standard CSV file
    with open("chapter_sentiments.csv", "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=["Chapter", "Compound", "Positive", "Neutral", "Negative", "Sentiment"])
        writer.writeheader()
        writer.writerows(results)
        
    print("\nResults successfully saved to 'chapter_sentiments.csv'.")

if __name__ == "__main__":
    file_path = "alice.txt"  # Replace with your Project Gutenberg text file path
    analyze_and_display(file_path)

###

import requests

def get_pittsburgh_temperature():
    # Coordinates for Pittsburgh, PA
    latitude = 40.4406
    longitude = -79.9959

    # Open-Meteo Forecast API endpoint
    url = "https://api.open-meteo.com/v1/forecast"

    params = {
        "latitude": latitude,
        "longitude": longitude,
        "current": "temperature_2m",
        "temperature_unit": "fahrenheit"
    }

    try:
        response = requests.get(url, params=params)
        response.raise_for_status()  # Raise an exception for HTTP errors
        
        data = response.json()
        
        current_temp = data["current"]["temperature_2m"]
        temp_unit = data["current_units"]["temperature_2m"]
        
        print(f"Current temperature in Pittsburgh, PA: {current_temp}{temp_unit}")

    except requests.exceptions.RequestException as e:
        print(f"Failed to retrieve weather data: {e}")

if __name__ == "__main__":
    get_pittsburgh_temperature()

###

import random
import pygame

# --- Configuration & Constants ---
GRID_SIZE = 20  # 20x20 grid
CELL_SIZE = 30  # Size of each cell in pixels
FPS = 5  # Speed of simulation (frames per second)

# Window dimensions
WIDTH = GRID_SIZE * CELL_SIZE
HEIGHT = GRID_SIZE * CELL_SIZE

# Colors (R, G, B)
COLOR_BG = (20, 20, 20)
COLOR_GRID = (40, 40, 40)
COLOR_HUMAN = (50, 150, 255)  # Blue
COLOR_ZOMBIE = (220, 50, 50)  # Red
COLOR_TEXT = (255, 255, 255)


def get_random_empty_pos(occupied_positions):
    """Generates a random (x, y) position on the grid not already taken."""
    while True:
        pos = (
            random.randint(0, GRID_SIZE - 1),
            random.randint(0, GRID_SIZE - 1),
        )
        if pos not in occupied_positions:
            return pos


def main():
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Zombie Takeover Simulation")
    clock = pygame.time.Clock()
    font = pygame.font.SysFont(None, 28)

    # Track positions
    occupied = set()

    humans = set()
    for _ in range(20):
        pos = get_random_empty_pos(occupied)
        humans.add(pos)
        occupied.add(pos)

    zombies = set()
    for _ in range(5):
        pos = get_random_empty_pos(occupied)
        zombies.add(pos)
        occupied.add(pos)

    turns = 0
    running = True

    while running:
        # 1. Event Handling
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        # 2. Update State (only if humans remain)
        if len(humans) > 0:
            turns += 1

            # Move zombies to new positions
            new_zombies = set()
            for z_x, z_y in zombies:
                # Directions: Up, Down, Left, Right, or Stay
                directions = [(0, -1), (0, 1), (-1, 0), (1, 0), (0, 0)]
                dx, dy = random.choice(directions)

                # Keep movement within grid boundaries
                new_x = max(0, min(GRID_SIZE - 1, z_x + dx))
                new_y = max(0, min(GRID_SIZE - 1, z_y + dy))

                new_zombies.add((new_x, new_y))

            zombies = new_zombies

            # Check for collisions with humans
            humans_to_remove = set()
            for human_pos in humans:
                if human_pos in zombies:
                    # 50% chance to turn into a zombie
                    if random.random() < 0.5:
                        humans_to_remove.add(human_pos)

            # Apply conversions
            for human_pos in humans_to_remove:
                humans.remove(human_pos)
                zombies.add(human_pos)

        # 3. Drawing
        screen.fill(COLOR_BG)

        # Draw Grid Lines
        for x in range(0, WIDTH, CELL_SIZE):
            pygame.draw.line(screen, COLOR_GRID, (x, 0), (x, HEIGHT))
        for y in range(0, HEIGHT, CELL_SIZE):
            pygame.draw.line(screen, COLOR_GRID, (0, y), (WIDTH, y))

        # Draw Humans (Blue)
        for h_x, h_y in humans:
            rect = pygame.Rect(
                h_x * CELL_SIZE + 2,
                h_y * CELL_SIZE + 2,
                CELL_SIZE - 4,
                CELL_SIZE - 4,
            )
            pygame.draw.rect(screen, COLOR_HUMAN, rect, border_radius=4)

        # Draw Zombies (Red)
        for z_x, z_y in zombies:
            rect = pygame.Rect(
                z_x * CELL_SIZE + 2,
                z_y * CELL_SIZE + 2,
                CELL_SIZE - 4,
                CELL_SIZE - 4,
            )
            pygame.draw.rect(screen, COLOR_ZOMBIE, rect, border_radius=4)

        # Draw Game Over Banner when all humans are gone
        if len(humans) == 0:
            msg = f"Takeover Complete! Time: {turns} steps"
            text_surf = font.render(msg, True, COLOR_TEXT)
            text_rect = text_surf.get_rect(center=(WIDTH // 2, HEIGHT // 2))

            # Background box for readability
            bg_rect = text_rect.inflate(20, 20)
            pygame.draw.rect(screen, (0, 0, 0), bg_rect)
            pygame.draw.rect(screen, COLOR_ZOMBIE, bg_rect, 2)
            screen.blit(text_surf, text_rect)

        pygame.display.flip()
        clock.tick(FPS)

    pygame.quit()


if __name__ == "__main__":
    main()