02 / Projects

Behind
the code.

See Alien Escape in action and explore the code behind my sorting algorithms and news aggregator.

Three projects. Different approaches.

From a Unity game to C++ algorithms and a Python news aggregator, these projects bring together different parts of my toolkit.

01 / Unity & C#

Alien Escape

A Unity game set in an alien planet!

Select Play to start the game with sound.

Play Alien Escape Open on Unity Play
PlayerController.cs Expand full code Collapse code
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
using TMPro;

public class PlayerController : MonoBehaviour
{
    public TextMeshProUGUI countText;   // UI text to display the number of pickups collected
    public GameObject winTextObject;    // "You win!" text (starts disabled)

    private Rigidbody rb;   // the player's rigidbody
    private int count;      // the number of pickups collected
    private float movementX;    // input for horizontal movement
    private float movementY;    // input for vertical movement
    public float jumpPower = 5f;    // starting jump power
    public Transform respawnPoint;  // where the player respawns if they die

    public float dashCooldown = 1f; // how long between dashes
    private float nextDashTime = 0f;    // when the next dash is available

    public float maxSpeed = 8f;          // normal top speed
    public float dashMaxSpeed = 20f;     // top speed while dashing
    public float dashDuration = 0.3f;    // how long the higher speed lasts
    private float dashEndTime = 0f;      // when the dash ends

    public GameObject pauseMenuObject;  // pause menu (starts disabled)
    private bool isPaused;  // whether the game is paused
    private bool gameEnded; // whether the game has ended
    private bool gameWon;   // whether the game has won

    public AudioClip pickupSound; // sound to play when a pickup is collected
    private AudioSource audioSource;    // the player's audio source

    public float startTimeSeconds = 60f;         // how long the player gets to complete the level
    public TextMeshProUGUI timerText;            // on-screen timer text
    public GameObject gameOverTextObject;        // "Game Over" text
    private float timeRemaining;                 // how much time is left
    private bool timerRunning;                   // whether the timer is running

    public int startingLives = 3;                // starting number of lives
    public GameObject[] lifeIcons;               // 3D objects, one per life
    public float invulnerableSeconds = 1.5f;     // grace period after respawning
    private int lives;                           // current number of lives
    private float invulnerableUntil = 0f;        // when the player becomes invulnerable
    private Vector3 startPosition;               // player's starting position for respawning

    public GameObject exitPortal;               // exit portal
    public int pickupsNeeded = 13;              // how many pickups are needed to win
    public string finalSceneName = "LevelTwo";  // name of the final level
    private bool exitUnlocked = false;          // whether the exit has been unlocked
    public bool ExitOpen => exitUnlocked;       // whether the exit is open

    public bool cameraRelativeMovement = false; // tank controls for the camera
    public bool tankControls = false;           // tank controls for the player
    public float TurnInput => movementX;        // input for turning

    void Start()
    {
        // Pause the game.
        Time.timeScale = 1f;
        if (pauseMenuObject != null) pauseMenuObject.SetActive(false);

        // Get the player's rigidbody
        rb = GetComponent<Rigidbody>();
        count = 0;

        // Get the player's starting position.
        startPosition = transform.position;
        lives = startingLives;
        UpdateLivesDisplay();

        // Get the player's audio source
        audioSource = GetComponent<AudioSource>();

        // Start the timer and hide the win text and exit portal.
        if (winTextObject != null) winTextObject.SetActive(false);
        if (exitPortal != null) exitPortal.SetActive(false);
        timeRemaining = startTimeSeconds;
        timerRunning = true;

        // Hide the game over text.
        if (gameOverTextObject != null) gameOverTextObject.SetActive(false);

        SetCountText();
        UpdateTimerText();

    }

    // Called when the player moves.
    void OnMove(InputValue movementValue)
    {
        Vector2 movementVector = movementValue.Get<Vector2>();

        movementX = movementVector.x;
        movementY = movementVector.y;
    }

    // Function is called when the player picks up a pickup.
    // Function also checks if level can be unlocked and game can be won.
    void SetCountText()
    {
        if (countText != null)
        countText.text = "Count: " + count.ToString();

        if (count >= pickupsNeeded && !gameWon && !exitUnlocked)
        {
            bool finalLevel = SceneManager.GetActiveScene().name == finalSceneName;

            if (finalLevel)
            {
            // Level is won
                gameWon = true;
                timerRunning = false;
                if (winTextObject != null) winTextObject.SetActive(true);
            }
        else
        {
            // Level is unlocked
            exitUnlocked = true;

            if (exitPortal != null) exitPortal.SetActive(true);
        }

            GameObject enemy = GameObject.FindGameObjectWithTag("Enemy");
            if (enemy != null) Destroy(enemy);
        }
    }

    // Function is called when the player moves and camera moves.
    void FixedUpdate()
{
    Vector3 input;
    // if statement that moves the camera in the direction of the player when tank controls are on. Used for the second level.
    if (tankControls && Camera.main != null)
    {
        Transform cam = Camera.main.transform;
        Vector3 forward = cam.forward; forward.y = 0f; forward.Normalize();
        input = forward * movementY;
    }
    // else if statement that moves the player in the direction of the camera when tank controls are off. Mainly used for the first level.
    else if (cameraRelativeMovement && Camera.main != null)
    {
        Transform cam = Camera.main.transform;
        Vector3 forward = cam.forward; forward.y = 0f; forward.Normalize();
        Vector3 right = cam.right; right.y = 0f; right.Normalize();
        input = forward * movementY + right * movementX;
    }
    else
    {
        input = new Vector3(movementX, 0f, movementY);
    }

    // if statement that nmakes sure the player doesn't move faster than the max speed.
    if (input.sqrMagnitude > 1f) input.Normalize();
    float currentSpeed = Time.time < dashEndTime ? dashMaxSpeed : maxSpeed;

    Vector3 v = rb.linearVelocity;
    rb.linearVelocity = new Vector3(input.x * currentSpeed, v.y, input.z * currentSpeed); //moves the player
}

    // Called when the player jumps.
    void OnJump(InputValue value)
    {
        if (isPaused || gameEnded) return;

        if (value.isPressed && IsGrounded())
        {
            Vector3 v = rb.linearVelocity;
            rb.linearVelocity = new Vector3(v.x, jumpPower, v.z);
        }
    }

    // Called every frame
    void Update()
    {
        if (gameEnded) return;

        // Pause the game when P is pressed. Calls the function TogglePause()
        if (Keyboard.current != null && Keyboard.current.pKey.wasPressedThisFrame)
        {
            TogglePause();
        }

        // Dash. Calls the function Dash().
        if (Keyboard.current != null && (Keyboard.current.leftShiftKey.isPressed || Keyboard.current.rightShiftKey.isPressed))
        {
            Dash();
        }
                // Timer
                if (timerRunning)
        {
            timeRemaining -= Time.deltaTime;

            if (timeRemaining <= 0f)
            {
                timeRemaining = 0f;
                UpdateTimerText();
                GameOver();
            }
            else
            {
                UpdateTimerText();
            }
        }
    }

    // Function is called when the player dashes. This dictates the dash duration and cooldown.
    void Dash()
    {
        if (Time.time < nextDashTime) return;

        Vector3 direction = new Vector3(movementX, 0.0f, movementY);

        if (direction.sqrMagnitude > 0.01f)
        {
            dashEndTime = Time.time + dashDuration;
            nextDashTime = Time.time + dashCooldown;
        }
    }

    // Function is called when the player pauses. This toggles the pause menu.
    void TogglePause()
    {
        isPaused = !isPaused;
        Time.timeScale = isPaused ? 0f : 1f;

        if (pauseMenuObject != null)
            pauseMenuObject.SetActive(isPaused);
    }

    // Checks if the player is on the ground.
    private bool IsGrounded()
    {
        return Physics.Raycast(transform.position, Vector3.down, 0.6f, ~0, QueryTriggerInteraction.Ignore);
    }

    // Function shows the time remaining.
    void UpdateTimerText()
    {
        if (timerText == null) return;

        int totalSeconds = Mathf.CeilToInt(timeRemaining);
        int minutes = totalSeconds / 60;
        int seconds = totalSeconds % 60;
        timerText.text = "Time: " + minutes.ToString("00") + ":" + seconds.ToString("00");
    }
        // Function shows the number of lives.
        void UpdateLivesDisplay()
    {
        if (lifeIcons == null) return;

        for (int i = 0; i < lifeIcons.Length; i++)
        {
            if (lifeIcons[i] != null)
                lifeIcons[i].SetActive(i < lives);
        }
    }

    // Function is called when the player loses a life.
    void LoseLife()
    {
        if (gameEnded || gameWon) return;
        if (Time.time < invulnerableUntil) return;

        lives--;
        UpdateLivesDisplay();

        if (lives <= 0)
        {
            GameOver();
            return;
        }

        invulnerableUntil = Time.time + invulnerableSeconds;
    }

    //Resapwn the player to the starting position.
    void Respawn()
    {
        rb.linearVelocity = Vector3.zero;
        rb.angularVelocity = Vector3.zero;
        movementX = 0f;
        movementY = 0f;
        transform.position = respawnPoint != null ? respawnPoint.position : startPosition;
    }

    // Function is called when the timer runs out.
     void GameOver()
    {
        timerRunning = false;
        gameEnded = true;

        if (gameOverTextObject != null) gameOverTextObject.SetActive(true);

        Time.timeScale = 0f;
    }

    // Function is called when the player collides with an enemy.
    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Enemy"))
        {
            LoseLife();
        }
    }

    // Function is called when the player collides with a pickup.
    private void OnTriggerEnter(Collider other)
    {
        if(other.gameObject.CompareTag("PickUp"))
        {
            other.gameObject.SetActive(false);
            count = count + 1;

            if (audioSource != null && pickupSound != null)
                audioSource.PlayOneShot(pickupSound);

            SetCountText();
        }

        // if statement is called when the player collides with a kill floor.
        if (other.gameObject.CompareTag("killFloor"))
        {
            LoseLife();
            if (!gameEnded) Respawn();
        }

        //if statement is called when the player collides with a life pickup.
        if (other.gameObject.CompareTag("LifePickup"))
        {
            if (lives < startingLives && !gameEnded)
            {
                lives++;
                UpdateLivesDisplay();
                other.gameObject.SetActive(false);

                if (audioSource != null && pickupSound != null)
                    audioSource.PlayOneShot(pickupSound);
            }
        }
    }
}

02 / C++

Sorting Algorithms

Try a browser version of my C++ sorting program. The result updates as you edit the numbers or choose a different algorithm.

sorting_Homework_Valderrama.cpp Expand full code Collapse code
// Homework sorting

#include <iostream>
using namespace std;

//Insertion Sort
void insertionSort(int arr[], int n)
{
    int i, j, key;
    for (i = 1; i < n; i++)
    {
        key = arr[i];
        j = i - 1;
        while (j >= 0 && arr[j] > key)
        {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = key;
    }
}

//Selection Sort
void selectionSort(int arr[], int n)
{
    int i, j, smallIndex, swap;

    for (i = 0; i < n - 1; i++)
    {
        // Find the minimum value in the array
        smallIndex = i;
        for (j = i + 1; j < n; j++)
        {
            if (arr[j] < arr[smallIndex])
                smallIndex = j;
        }
        if (smallIndex != i)
        {
            swap = arr[i];
            arr[i] = arr[smallIndex];
            arr[smallIndex] = swap;
        }
    }
}

//Bubble Sort
void bubbleSort(int arr[], int n)
{
    int i, j, swap;
    bool swapped;

    // Compare 1st two elements and swaps if they are out of order.
    swapped = false;
    for (i = 0; i < n - 1; i++)
    {
        for (j = 0; j < n - i - 1; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                swap = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = swap;
                swapped = true;
            }
        }
        if (!swapped) break;
    }
}

// Print the array
void printArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        cout << arr[i] << " ";
    cout << endl;
}

// Main function
int main()
{
    int n = 0;

    // Input validation
    while (n <5 || n > 10)
    {
        cout << "How many integers would you like to enter? (5 to 10 only!): ";
        cin >> n;

        if (n < 5 || n > 10)
            cout << "Invalid input. Please enter 5 to 10 integers." << endl;
    }

    int data[10];

    // Input

    for (int i = 0; i < n; i++)
    {
        cout << "Enter integer " << i + 1 << ": ";
        cin >> data[i];
    }

    cout << "Unsorted array: ";
    printArray(data, n);

    //Menu Selection

    int choice = 0;

    while (choice < 1 || choice > 3)
    {
        cout << "Select a sorting algorithm:\n";
        cout << "1. Insertion Sorting\n";
        cout << "2. Selection Sorting\n";
        cout << "3. Bubble Sorting\n";
        cout << "Enter your choice: ";
        cin >> choice;

        if (choice < 1 || choice > 3)
            cout << "Invalid choice. Please select a valid sorting algorithm." << endl;
    }

    switch (choice)
    {
        case 1:
            insertionSort(data, n);
            break;
        case 2:
            selectionSort(data, n);
            break;
        case 3:
            bubbleSort(data, n);
            break;
    }

    // Print the sorted array
    cout << "Sorted array: ";
    printArray(data, n);

    return 0;
}

03 / Python & SQLite

News Aggregator

A Python notebook that fetches five headlines from NewsAPI and stores article details in SQLite without saving duplicate titles.

News Aggregator / Python Expand full code Collapse code
from google.colab import userdata
import requests
import sqlite3

apikey = userdata.get('NewsAggregator')

url = f"https://newsapi.org/v2/everything?domains=wsj.com&apiKey={apikey}"

# a. Prompts the user to enter a news topic (e.g., "technology", "sports").

def main():

    topic = input("Enter news topic: ")
    articles = get_headlines(topic)
    conn, cursor = create_database("news.db")
    store_data(conn, cursor, articles)
    read_data(cursor, articles)
    print("Data has been saved to the database.")
    conn.close()

# b. Retrieves the top 5 headlines related to the topic using the requests package.

def get_headlines(topic):

    url = f"https://newsapi.org/v2/everything?q={topic}&pageSize=5&sortBy=publishedAt&apiKey={apikey}"
    response = requests.get(url)
    data = response.json()
    articles = data['articles']
    return articles

# c. Stores the headlines, descriptions, and publication dates in an SQLite database.

def create_database(db_name):
    conn = sqlite3.connect(db_name)
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS news (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT UNIQUE,
            description TEXT,
            published_at TEXT
        )
    ''')

    conn.commit()
    return conn, cursor

def store_data(conn, cursor, articles):
    for article in articles:
        title = article['title']
        description = article['description']
        published_at = article['publishedAt']

        # e. Ensures that duplicate headlines are not stored in the database.

        cursor.execute('''
            INSERT OR IGNORE INTO news (title, description, published_at)
            VALUES (?, ?, ?)
        ''', (title, description, published_at))

    conn.commit()

# d. Reads back the data from the database and displays it to the user in a readable format. Must be numbered from 1 to 5.

def read_data(cursor, articles):

    print("\nTop Headlines:\n")

    number = 1

    for article in articles:
        cursor.execute('SELECT title, description, published_at FROM news WHERE title = ?', (article['title'],))
        row = cursor.fetchone()

        print(f"{number}. {row[0]}\n")
        print(f"Description: {row[1]}\n")
        print(f"Published At: {row[2]}\n")


        number += 1

main()

Next / Contact

Continue the conversation.

Get in touch →