Scriptable Object Events in Unity and My Cutscene Manager

Hello all. Finals season is over, and I have the most persistent cold I’ve ever experienced… which means I have a lot of time. Luckily, I’ve been working on this project with my friends and had the opportunity to write some really cool code that I’d like to share here. The other engineer on the project, and myself have been trying to build the architecture of this game utilizing a very powerful tool: Scriptable Objects. If you don’t know what these are, I highly recommend watching this talk by Ryan Hipple. TL;DR You can utilize Scriptable Objects to store data, as opposed to individual method calls and dependencies within code, to keep the architecture modular, easily debuggable, and less prone to collapse on you. A Scriptable Object will store a variable and allow any function to access it, or modify it, so that all methods can just respond to this one value. Think “global variable” that exists in the editor.

Another very cool principle in the talk by Ryan is using Scriptable Object Game Events (which take the same above principal, but utilize UnityEngine.Events;) to interface between everything in the scene that would otherwise be dependent through code. So here’s what I wrote: A cutscene manager for my game using Unity Timeline and Scriptable Object Game Events.

How it works: I have a UnityEvent StartScene that is Invoked OnTriggerEnter().

public class StartCutscene : MonoBehaviour
{

    //Event to start scene
    public  UnityEvent startScene;


    //on trigger enter
    private void OnTriggerEnter(Collider other)
    {
        //if player
        if(other.tag == "Player")
        {
            //raise
            startScene.Invoke();
            Debug.Log("Invoked");

        }
    }

}

Then this is what it looks like in editor. As a matter of fact, take my whole “CutsceneTrigger” prefab while you’re at it:

Note the UnityEvent is calling on the Game Event Scriptable Object “PlayCutscene” and Raising it. This signals to any Game Event Listeners (Once again, a Scriptable Object implementing the functionality of a Unity Game Event Listener) elsewhere in the scene that were set to listen to our Game Event Scriptable Object. In this case, I have 2 prefabs listening in on “PlayCutscene”. The first one is my CutsceneManager.

So take a nice long look at that beauty, and I think you might fully see what’s going on here. First off, I have the Game Event Listener which is making a call within my CutsceneManager Script to startNextCutscene(). startNextCutscene utilizes a Dictionary, which I have serialized at the top of the prefab. This dictionary takes the string name and the associated PlayableDirector, which is what controls Unity Timeline Playables. If you’re familiar with Dictionaries then you know they’re not serializable in Editor, but we can fix that with a nifty little work around in code.

//Serialized Dictionary Class
[System.Serializable]
public class Cutscenes
{
    public string cutsceneName;
    public PlayableDirector cutscene;

}


//Cutscene Manager will play the next applicable cutscene, storing all in a dictionary
public class CutsceneManager : MonoBehaviour
{

    //Note to design
    [TextArea]
    public string Notes = "Names should have no spaces or numbers and triggers should be place in order of encounter";

    //Array of Cutscenes, which contain our Dictionary compontents
    public Cutscenes[] toDictionary;

    //Dictionary that takes string name and PlayableDirector
    public Dictionary<string, PlayableDirector> listOfScenes;

    //Int to monitor which have played
    private int selection;

    //Unity Event to on trigger end of scene
    public UnityEvent endCutsceneEvent;


    //establishes Dictionary from serialized "Cutscenes"
    public void Awake()
    {

        //Instantiates Dictionary
        listOfScenes = new Dictionary<string, PlayableDirector>();

        //Fills that shit up
        for(int rep = 0; rep < (toDictionary.Length); rep++)
        {
            listOfScenes.Add(toDictionary[rep].cutsceneName, toDictionary[rep].cutscene);
        }


    }



    //Starts next cutscene
    public void startNextCutscene()
    {

        //Sets temp Playable Director
        Debug.Log("Signal Recieved");
        PlayableDirector temp = listOfScenes[toDictionary[selection].cutsceneName];


        //Starts cutscene
        Debug.Log("Starting...");
        temp.Play();

        //Event "stopped" is assigned to endCutscene, will call this function on raise
        temp.stopped += endCutscene; 
 
        //Increments cutscenes
        selection++;



    }

    //Invokes UnityEvent to tell rest of scene
    private void endCutscene(PlayableDirector aDirector)
    {
        //Ends the cutscene
        endCutsceneEvent.Invoke();

        Debug.Log("Cutscene Ended");
    }

}

So I’ll try to break this down for those who can’t understand my comments, but basically at the very top we have the serialized class Cutscenes, which I’m taking all the components necesary for my dictionary. Then storing them in an array toDictionary. Then, on Awake() I’m taking those individual values from the array and storing them together in my Dictionary ListOfScenes. Also note that I have a UnityEvent here at the top.

So this is where startNextCutscene() comes into play. I take the next PlayableDirector in order and store it in my temp, but note how in the search through my Dictionary ListOfScenes I’m using the corresponding string stored in the Array toDictionary to index the needed PlayableDirector. Just thought that was sick. A little wonky… but cool.

Then temp is played, which cues the animation sequence of the PlayableDirector, otherwise known as the Playable. The PlayableDirector then sets off an event upon finishing which I’m listening to and invoking my own UnityEvent endCutsceneEvent.

This is where my CameraManager comes in. Note that in the above picture of my CutsceneManager Prefab, my Unity Event endCutsceneEvent is attached to another Scriptable Object Game Event “EndCutscene”

From the bottom up, the CameraManager is listening to 2 events, EndCutscene and PlayCutscene. Remember, these are our scriptable events, any listener in the scene has access to them! So these are both invoking responses within my CameraManager script. At the top you can see the manager takes 2 Cameras, as this script is responsible for switching between the cutscene camera, used in our PlayableDirector Playables, and the main camera, used for gameplay. Don’t worry, this is not the only script working on the camera right now, this is just helping us manage between the 2 specifically with Playables. Here’s that code:

[System.Serializable]

public class CameraManager : MonoBehaviour
{

    //Declares the cameras needed
    public Camera playerCam;
    public Camera cutsceneCam;

    public void Awake()
    {
        switchAfterCutscene();
    }


    //Starts the cutscene, swapping cameras
    public void cutsceneStart()
    {

        //Cameras swapped
        switchBeforeCutscene();
        
        //Debug
        Debug.Log("play cutscene");


    }

    //Ends the cutscene, swapping cameras
    public void cutsceneEnd()
    {
        //Cameras swapped back
        switchAfterCutscene();

        Debug.Log("Cutscene end");
    }


    //Swaps active cameras
    private void switchBeforeCutscene()
    {
        playerCam.enabled = false;
        cutsceneCam.enabled = true;

    }

    //Swaps active cameras
    private void switchAfterCutscene()
    {
        cutsceneCam.enabled = false;
        playerCam.enabled = true;
    }
}

Pretty self explanatory, but just note that the methods switchBeforeCutscene() and switchAfterCutscene() are both triggered by the corresponding Game Events in scene, in addition to the startNextCutscene() in the CutsceneManager. I wanted to show you to give an example of how using GameEvent Scriptable Objects allows multiple scripts to interface with one another without ever knowing the other exists!

You have to see how this is such a god send for devs who want to keep dependencies low and the engine easy to use for designers. Here, a designer who has been briefed can easily establish a whole system of cutscenes in their level without ever having to see a single class.

Happy holidays to everyone! I’ll be back soon with more.

Object Interaction

Hello all! Wow… what a few years can do, huh? I have a habit of posting on my birthday, because that’s on of the few days a year you get to do exactly what you want, and writing code is what I want to do! And sharing that code is always fun too! So I thought that in honor of this yearly tradition, we would visit some old code! February of 2018 saw me write some of my first scripts in Unity. I was already pretty well versed in writing code, but Unity was new to me! I ended up writing a few scripts, but one of the scripts I was most proud of was my Object Interaction script. Simple, yeah I know, but I was very proud of this!

Well, here we are now as I turn 23, and am much more confident in my programming, my Unity ability, design ability, and as a human being in general! So why not create an object interaction interface that more properly represents me as I am now? Lets start with just that!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public interface IInteractable
{
    string IPrompt();

    void IAction();

    bool IsInteractable();
}

So lets say that IPrompt is the string that pops up on your screen when you’re within range of interacting with the game object. IAction is what the object does upon interacting. IIsInteractable will help us turn off items after one use or once they are not to be used any more!

Easy Enough! Bye!

Just kidding…….. So from here we have to build ourselves an Interacter which we will attach to the player, that will allow the player to interact with items that inherit from IInteractable! So here I’ll sort of get our of detail and loosely tell you what’s going on here! I wanted to make the interactions like they are in Dark Souls, where you can cycle through multiple intractable objects if they are present, and choose which one you would like to interact with! So I build this interacter around an ArrayList, which stores the currently “selected” element in an int. From here, I just have an OnTriggerEnter and Exit that will add the IInteractables to the ArrayList, and allow the player to sort through their IPrompts, and interact with their different IActions!

That really is it for this one! Lots of private methods to just manage the backend of scrolling and interacting, but I’ll include it all here… Please excuse my debug notes! This was also built as a part of the Project Rat I mentioned in my previous post.. I hope you guys like this code and can see the difference in my skill from 2 years ago to now…. Well I should hope you see the difference…. Here’s some code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Interacter : MonoBehaviour
{

    //LIFO will keep 
    // private Stack<IInteractable> LIFO = new Stack<IInteractable>();
   
    //AL Instantiation    
    ArrayList InteractionAL = new ArrayList();

    public int selection = 1;



    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            doSomething();
        }
        else if (Input.GetKeyDown(KeyCode.R))
        {
            scrollSelection();
        }
    }

    //Adds Object to the ArrayList if is interactible
    private void OnTriggerEnter(Collider other)
    {

        Debug.Log("Something entered my zone!");

        //Gets the game object from the collider entered
        //HERE
        IInteractable newInteractable = other.GetComponent<IInteractable>();

        //If is interatable, add
        if (newInteractable.IsInteractable())
        {
            InteractionAL.Add(newInteractable);

            //Debug Log
            Debug.Log("Added");

        }

    }

    //Removes most recent from the ArrayList on exit
    private void OnTriggerExit(Collider other)
    {
        //Debug Log
        Debug.Log("-1 in array");

        //Finds the collider exited, and removes from the AL
        InteractionAL.Remove(other.GetComponent<IInteractable>());

        
    }

    //Returns the prompt of the IInteractible 
    public string getPrompt(IInteractable temp)
    {

        //Debug Log
        Debug.Log(temp.IPrompt());

        //Returns prompt
        return temp.IPrompt();
    }
    

    //Calls IAction
    //Possibly remove if one time use only
    private void doSomething()
    {

        //Temp IInteractabale
        IInteractable temp = getSelected();

        //If not null
        if(temp != null)
        {

            //Do Something
            temp.IAction();
           
            //Debug
            getPrompt(getSelected());

        }

  
    }

    //Retrieves the IInteractable which is currently to be displayed
    //Incremented by scrollSelecion()
    private IInteractable getSelected()
    {
        //If not empty
        if(InteractionAL.Count != 0)
        {
            //castes the IInteractable as an IInteractable
            return (IInteractable)InteractionAL[(selection - 1)];
        }

        //else
        else
        {
            return null;
        }
      
    }

    //Increments the int which getSelected returns
    private void scrollSelection()
    {
        //Takes size of ArrayList starting at 1
        int tempSize = InteractionAL.Count;

        //Increments selection as long as it's not at the end
        if (selection < tempSize)
        {
            selection++;
        }

        //Resets the scroll selection to the front. 
        //I hate hardcoding this, but this wont change as long as we use .Count
        else if(selection == tempSize) 
        {
            selection = 1;
        }

    }
}

Object Pooling

Hello all! I know I know, more than 1 post in the span of a month? How lucky are you! Well the answer is you’re not, because my last post was a month and a week ago now… so calm down, you. But I do bring some cool stuff to share! Ever heard of Object Pooling in Unity? In brief: If you have a GameObject which you’re constantly creating new copies of and then destroying right after, such as a projectile or an effect, it can be really unnecessarily taxing on your CPU. So an Object Pool just instantiates all necessary instances of the GameObject at the start of the game, and just recycles them, setting them active and inactive when needed, and expanding if necessary, much like an ArrayList, to accommodate however many instances of the object your game needs.

I’m just beginning work as an engineer on a game with some of my friends at school. For now we have dubbed the game “Project Rat”, and this game is why I’ve built this Object Pooler! It’s a really easy object to build but I’ll talk a little about it. I’d like to also start by saying that I read and learned about Object Pooling from Mark Placzek. To start, we define an ObjectPoolItem Class which contains an Int that defines the initial size, a GameObject which will hold the prefab that is to be pooled, and then a bool to represent if we want this size to be dyamic, or a fixed value.

From here we define the ObjectPooler Class, which is a monoBehaviour. Here we declare the List that will be our pool, as well as the List that will contain all of the pools, for easy access by the GameManager. The pool list is then instantiated in Start(), where we then have a loop instantiating as many copies of the GameObject as defined in our ObjectPoolItem (both the GameObject and the size are defined there). In this loop the newly instantiated GameObject is set inactive then added to our List.

And… That’s really it! Then just create a function that takes a string of the tag of item being sought, and returns the first instance of an item with that tag which isn’t already .activeInHeirarchy(). It’s here that we can also create a check on the size of the List and compare it to how far we have to go into our List to get a new GameObject, and decide if we want the List to expand or not, using the bool we defined in the ObjectPoolItem, and just instantiating a new GameObject as we did in Start().

Sweet! Now you just need to keep in mind that the Object Pooler is storing inactive GameObjects, so however you call them you must remember to set them active! And then set inactive once they are no longer in use so that they may be recycled by our object pool! Here’s some code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


//Declares necessary values
[System.Serializable]
public class ObjectPoolItem
{
    public int amountToPool;
    public GameObject objectToPool;
    public bool expand = true;

}

public class ObjectPooler : MonoBehaviour
{

    public static ObjectPooler SharedInstance;

    //Declares List to hold pools
    public List<ObjectPoolItem> listOfPools;

    //Declares List to hold GameObjects 
    private List<GameObject> objectPool;


    void Awake()
    {
        SharedInstance = this;
    }

    void Start()
    {
        //Instantiates List
        objectPool = new List<GameObject>();

        foreach (ObjectPoolItem item in listOfPools)
        {
            // Instantiates the "Object to pool". sets inactive, and stores in List for number in amountToPool
            for (int rep = 0; rep < item.amountToPool; rep++)
            {
                GameObject obj = (GameObject)Instantiate(item.objectToPool);
                obj.SetActive(false);
                objectPool.Add(obj);
            }
        }
    }

    //Returns an INACTIVE instance of the pooled object, need to match tag
    //Can also specify when to expand and when not to.
    public GameObject GetPooledObject(string tag)
    {
        //Cycles through active and inactive elements in List
        for (int rep = 0; rep < objectPool.Count; rep++)
        {
            //If Inactive
            if (!objectPool[rep].activeInHierarchy && objectPool[rep].tag == tag)
            {
                return objectPool[rep];
            }

        }

        //expands necesary lists all at once
        foreach (ObjectPoolItem item in listOfPools)
        {
            if (item.objectToPool.tag == tag)
            {
                if (item.expand)
                {
                    GameObject obj = (GameObject)Instantiate(item.objectToPool);
                    obj.SetActive(false);
                    objectPool.Add(obj);
                    return obj;
                }
            }
        }

        return null;
    }
}

Heapsort in Java

This program sorts data of type E in “heapsort” fashion. Read more about heapsort here.

The class extends an abstract class “sorter”, provided below. This abstract class was written by Adam Smith. The array that is being sorted is set to the size of 500, and is filled with random ints to best test the sorter. This can be altered in the main. For a visual demonstration of many sorting methods, click here. This visual guide was created by Professor Adam Smith for his students.

Screen Shot 2018-01-28 at 11.49.13 AM

/**
 * Algorithm to sort an array of type E in the HeapSort fashion
 * @author AidanTakami
 * @version 1.0
 *
 */
class HeapSort extends Sorter {
	private static int top;

	/**
	 * Method which sorts array in HeapSort fashion.
	 *
	 * @param array which is going to be sorted
	 * @since 1.0
	 */
	@Override
	public <E extends Comparable<E>> void sort(E[] array){
		top = array.length - 1;
		//iterates through the array, heapifying it
		for(int rep = (top/2); rep >= 0; rep--){
			heapify(array, rep);
		}

		//iterates through the array, bringing the highest values to the top and then re heapifying
		for(int i = top; i >= 0; i--){
			E oldValue = array[0];
			array[0] = array[i];
			array[i] = oldValue;
			top--;
			heapify(array, 0);
		}
		//Not sure as to why, but sometimes leaves first 3 elements unsorted. This is a temporary bug fix.
		if(array[1].compareTo(array[2]) > 0){
			E iMadeAnError = array[2];
			array[2] = array[1];
			array[1] = iMadeAnError;
		}
		if(array[0].compareTo(array[1]) > 0){
			E iMadeAnError = array[1];
			array[1] = array[0];
			array[0] = iMadeAnError;
		}

	}
	/**
	 * Method which uses the parameter array and the parameter rep to compare rep to it's children
	 * and then sink rep if it is < a child, and then call itself to sink rep until rep > it's children
	 *
	 * @param array which will be heapified
	 * @param int rep which will be compared to it's children
	 * @since 1.0
	 */
	public <E extends Comparable<E>> void heapify(E[] array,int max){

			//allocates ints for the location of the node's children, and the parent.
			int right = 2 * max+2, left = 2 * max+1, i = max;

			//makes sure the right child's index isnt too high, then compares it to max
			if(right <= top - 1 && array[right].compareTo(array[max]) > 0){
				//sets the max = the right child
				max = right;
			}

			//makes sure the left child's index isnt too high, then compares it to max
			if(left <= top - 1 && array[left].compareTo(array[max]) >= 0){
				//sets the max = the left child
				max = left;
			}

			//makes sure the max has been reset before heapifying again, and sinking the values
			if(max != i){
				sink(array, i, max);
				heapify(array, max);
			}
	}
	//sinks the element at location lesserValSpot, and swaps it with the element at greaterValSpot
	private <E extends Comparable<E>> void sink(E[] array, int lesserValSpot, int greaterValSpot){
		E oldParent = array[lesserValSpot];
		array[lesserValSpot] = array[greaterValSpot];
		array[greaterValSpot] = oldParent;
	}

	/**
	 * Main function to test the HeapSort
	 *
	 * @since 1.0
	 */
	public static void main(String[] args){
		Integer[] arr = new Integer[500];
		for(int rep = 0; rep < arr.length; rep++){
			Integer random =(int )(Math.random() * arr.length + 0);
			arr[rep] = random;
		}

		System.out.print("The unsorted Array: [");
		for(int i = 0; i < arr.length; i++){
			System.out.print(arr[i] + ", ");
		}
		System.out.println("]");

		System.out.print("The sorted Array: [");
		new HeapSort ().sort(arr);
		for(int i1 = 0; i1 < arr.length; i1++){
			System.out.print(arr[i1] + ", ");
		}
		System.out.println();
		double time = new HeapSort().timeSort(500);
		System.out.println("The Array is sorted? " + isSorted(arr));
		System.out.println("The sort took : " + time + " Millisecond(s).");

	}
}

/**
 * Base abstract class for Sorters of various kinds.
 *
 * @author Adam Smith
 * @version 1.0
 */

public abstract class Sorter {
	/**
	 * Do the actual sorting.
	 *
	 * @param array  the array to sort
	 */

	abstract public <E extends Comparable<E>> void sort(E[] array);

	/**
	 * Tells whether or not an array is sorted. Useful for
	 * assertions. Will also return false if one of the elements is
	 * null.
	 *
	 * @param array  the array that may be sorted
	 * @return      whether or not it's sorted
	 */

	public static final <E extends Comparable<E>> boolean isSorted(E[] array) {
		if (array[0] == null) return false;

		// go thru each element, testing for order
		for (int i=1; i<array.length; i++) {
			if (array[i] == null) return false;
			if (array[i].compareTo(array[i-1]) < 0) return false;
		}

		// return true if we finished the loop without problem
		return true;
	}

	/**
	 * Times a sort of an array of a particular size. This method
	 * creates a new array of Integers of the given size, and gives
	 * each one a random value between 0 and the size. (Thus,
	 * duplicate values are almost certainly present, but uncommon.)
	 * It then returns the number of milliseconds this took, not
	 * including time taken to allocate the array and its components.
	 *
	 * @param size  the number of elements to be sorted
	 * @return      the number of milliseconds taken
	 */

	public final int timeSort(int size) {
		// allocation
		Integer[] array = new Integer[size];
		for (int i=0; i<array.length; i++) array[i] = new Integer((int)(Math.random() * size));

		// do the sort now, returning # ms
		long start = System.currentTimeMillis();
		sort(array);
		return (int)(System.currentTimeMillis() - start);
	}
}

Quicksort

Hello! Below is my attempt at a quicksort. Sorters are really interesting code because they can be done in so many different ways, which can make such a difference in the speed an array is sorted. Here (No longer online :(, here’s another) is a visual example from my old professor Adam Smith. From this visual guide, you’re able to see when quicksort is most and least effective. Here’s some output:

Screen Shot 2018-02-02 at 12.00.27 PMScreen Shot 2018-02-02 at 12.01.15 PM

//
//  Quicksort2.cpp
//
//  Sorter which will sort array of random values in the "quicksort" style.
//
//  Created by Aidan Takami on 2/1/18.
//  Copyright © 2018 Aidan Takami. All rights reserved.
//


/*
     Must include iostream, cstdlib, and ctime. Site keeps deleting
     these libraries thinking they are HTML tags
/*
#include 
#include 
#include 



using namespace std;

void printArray(int r[]);
void switchValues(int r[], int, int);
void randmoArray(int r[]);
void quickSort(int r[], int, int);

//Declares the array to be sorted, as well as the const to represent the size of the array
int r[100];
const int SIZE = (sizeof(r)/4);


//Method to print out values of the array
void printArray(int r[])
{
    int i=0;
    while(i<SIZE){
        cout<<r[i]<<",";
        i++;
    }
}


//Method to swap the values at the locations of the 2 int args, within the array provided
void switchValues(int r[],int leftSide, int rightSide){
    int temp = r[leftSide];
    r[leftSide] = r[rightSide];
    r[rightSide] = temp;
}

//Method which will randomize an array of the size of the const int SIZE
void randomArray(int r[]){
    
    for(int rep = 0; rep < SIZE; rep++){
        
        r[rep] = int (rand()%100);
    }
}


//Quicksort method
void quicksort(int r[], int leftSide, int rightSide){
    
    int leftTemp = leftSide;
    int rightTemp = rightSide;
    int pivot = r[(leftSide+rightSide)/2];
    
    while(leftSidepivot)
            rightTemp--;
        
        if(leftTemp<=rightTemp){
            switchValues(r, leftTemp, rightTemp);
            leftTemp++;
            rightTemp--;

        }
        else{
            if(leftSide<rightTemp)
                quicksort(r, leftSide, rightTemp);
            if(leftTemp<rightSide)
                quicksort(r,leftTemp,rightSide);
            return;
        }
    }
}


//Main method for testing the quicksort
int main() {
  
    cout << "Generating random array!" << endl;
    randomArray(r);
    
    cout << "The unsorted array: ";
    printArray(r);
    
    cout << endl << endl;
    cout << "Sorting in progress..." << endl;
    const clock_t beginTime = clock();
    quicksort(r, 0, SIZE);
    float totalTime = ( clock () - beginTime ) /  CLOCKS_PER_SEC;
    
    cout << "The sorted array: ";
    printArray(r);
    cout << endl;
    
    cout << "The sort took " << totalTime << " milliseconds!" << endl;
    
    return 0;
}

Word Checker

This is a short program which utilizes a TreeSet to respond to a user on whether a word exists in the English Lexicon or not. This program operates on a file “english.lex” (Just a heads up, this link will download the file, which is just a .txt of all the words in the english language… No viruses I promise!!)(That’s exactly what someone with an infected file they wanted you to click would say…).

The file provided is in a .lex format, but may be altered, and can be opened in any text editor.

Screen Shot 2018-01-28 at 11.38.20 AM

/**
 * Class which searches the English lexicon and lets user know if an entered word is
 * a word in the English language.
 *
 * @author AidanTakami
 * @since 1.0
 *
 */

import java.util.Scanner;
import java.util.TreeSet;
import java.io.File;
import java.util.ArrayList;

public class WordChecker {
	public static final String FILE_NAME = "english.lex";
	public static TreeSet<String> lexTree = new TreeSet<String>();

	/**
	 * Method which loads the file FILE_NAME into an ArrayList and then into lexTree
	 */
	public static void makeTree(){
		ArrayList<String> lexList = new ArrayList();
		//tries to scan the file and put all lines into an ArrayList.
		try{

			//Creates new file object, a new scanner, and scans the file into the Scanner
			File newFile = new File(FILE_NAME);
			Scanner fileScan = new Scanner(System.in);
			fileScan = new Scanner(newFile);

			//loops through Scanner, adding each nextLine to ArrayList
			while(fileScan.hasNextLine()){
				lexList.add(fileScan.nextLine());
			}
		}
		//Catches an exception which I saw online
		catch(Exception ex){
			ex.printStackTrace();
		}

		//iterates through arrayList, adding each String to lexTree
		for(int rep = 0; rep < lexList.size(); rep++){ 			lexTree.add(lexList.get(rep)); 		} 	} 	 	/** 	 * takes a string given by the user and returns whether it is contained in the  	 * lexTree or not. 	 *  	 * @param word  String given by the user. 	 * @return boolean 	 * @since 1.0 	 */ 	public static boolean isWord(String word){ 		return lexTree.contains(word); 	} 	 	/** 	 * Main function for testing 	 *  	 * @since 1.0 	 */ 	public static void main(String[] args){ 		//makes scanner, tree, and prints intro 		makeTree(); 		Scanner input = new Scanner(System.in); 		System.out.println("Welcome to the Word Checker!"); 		System.out.println("Loading file " + FILE_NAME + " which contains " + lexTree.size() + " words!"); 		System.out.println("Please enter a word or hit enter to quit."); 		 		//loop takes user input and returns answer 		while(true){ 			System.out.print("> ");

			//stores user input in String
			String word = input.nextLine();
			System.out.println();;

			//if string is empty, signifying enter key, breaks loop
			if(word.isEmpty()) break;

			//calls isWord, and responds accordingly
			boolean lexBool = isWord(word);

			if(lexBool){
				System.out.println(word + " is a valid word");
			}
			else{
				System.out.println(word + " is NOT a valid word.");
			}

		}
		System.out.println("Goodbye!");
	}
}

PV = nRT Solver

Hello! Below is a program I wrote after a Chemistry lecture today. PV = nRT is an incredibly fundamental equation within Chemistry. Otherwise known as the Ideal Gas Law, this formula combines basis’ of Boyle’s Law, Charles’ Law, and Avangadro’s Law into a simple equation, which we can use to find any missing variables from the equation, when given the other circumstances.

PV = nRT

P = pressure,

V = volume,

n = substance in moles,

R = 0.0821 (when unit is (atm*L)/(mol*K)) With other units, this constant will vary however, this is the constant used in this program, for these are the units used.            Read more on this constant

T = temperature

The program I have written will take input from the user for the values they DO have, and use those to find the “mystery” value, whichever variable that may be.

Screen Shot 2018-02-22 at 3.04.08 PM

//
//  main.cpp
//  PV=nRT
//
//  Created by Aidan Takami on 2/22/18.
//  Copyright © 2018 Aidan Takami. All rights reserved.
//


#include 
using namespace std;

void numbers();
double calculateP();
double calculateV();
double calculateN();
double calculateT();

//Fields
double p, v, n, t;
string pTemp = "";
string vTemp, nTemp, tTemp;
bool keepGoing = true;
const double R = 0.0821;

//Main
int main() {
    
    //Introduction & directions
    cout << "Hello! Welcome to the PV = nRT calculator! Type \"?\" for the value you are trying to find" << endl;

    
    while(keepGoing){
        //Calls calculation method
        numbers();
    }
    
}


//Method which gathers the numbers to be used in calculation
void numbers(){
    
    //Bool to represent whether mystery value has been found yet
    bool mysteryValue = false;
    
    //Bools to represent which value is mystery value
    bool pBool = false;
    bool vBool = false;
    bool nBool = false;
    bool tBool = false;
    
    //Used for continue/end process
    string temp;
    
   
    //Pressure
    cout << "What is the pressure in atm?" <> pTemp;
    
    //if the first value of the string is a digit
    if(isdigit(pTemp[0])){
        
        //convert the string to a double
        p = stod(pTemp);
    }
    else{
        
        pBool = true;
        mysteryValue = true;
    }

    
    
  
    //Volume
    cout << "What is the volume in L?" <> vTemp;
    
    //if the first value of the string is a digit
    if(isdigit(vTemp[0])){
        
        //convert the string to a double
        v = stod(vTemp);
    }
    else if(mysteryValue == true){
        
        //error message & restart
        cout << "We already have a mystery value! Let's try again!" << endl << endl;
        numbers();
    }
    else{
        
        vBool = true;
        mysteryValue = true;
    }
    
    
    
    
    
    //Moles
    cout << "What is the mole to molar mass ratio of the compound/element?" <> nTemp;
    
    //if the first value of the string is a digit
    if(isdigit(nTemp[0])){
        
        //convert the string to a double
        n = stod(nTemp);
    }
    else if(mysteryValue == true){
        
        //error message and restart
        cout << "We already have a mystery value! Let's try again!" << endl << endl;
        numbers();
    }
    else{
        
        nBool = true;
        mysteryValue = true;
    }
    
    
    
    
    
    //Temperature
    cout << "What is the temperature in Kelvin" <> tTemp;
    
    //if the first value of the string is a digit
    if(isdigit(tTemp[0])){
        
        //convert the string to a double
        t = stod(tTemp);
    }
    else if(mysteryValue == true){
        
        //error message and restart
        cout << "We already have a mystery value! Let's try again!" << endl << endl;
        numbers();
    }
    else{
        
        tBool = true;
        mysteryValue = true;
    }
    
    
    
    //if pressure = mystery value
    if(pBool){
        cout << "The Pressure is: " << calculateP() << " atm!" << endl << endl;
    }
    
    //if volume = mystery value
    else if(vBool){
        cout << "The Volume is: " << calculateV() << " L!" << endl << endl;
    }
    
    //if mole = mystery value
    else if(nBool){
        cout << "The Molar Ratio is: " << calculateN() << " mol!" << endl << endl;
    }
    
    //if temp = mystery value
    else if(tBool){
        cout << "The Temperature is: " << calculateT() << " K!" << endl << endl;
    }
    
    else{
        cout << "You answered your own question! I cannot verify whether it's true or not.!" << endl;
        cout << "Try again!" << endl << endl << endl;
    }

    
    
    //Continue?
    cout << "Would you like to continue? (y/n)" <> temp;
    
    if(temp == "no" || temp == "n"){
        keepGoing = false;
    }
    
    cout << endl;
}

//Calculates Pressure
double calculateP(){
    cout << (n * R * t) << endl;
    
    return (n*R*t)/v;
}


//Calculates Volume
double calculateV(){
    
    return (n*R*t)/p;
}


//Calculates Molar Ratio
double calculateN(){
    
    return (p*v)/(R*t);
}


//Calculates Temp
double calculateT(){
    
    return (p*v)/(R*n);
}

Bounded Set in Java

Below is the code for a “Bounded Set”, which is an object which can store other objects of a generic type . This gives the bounded set the ability to store any type of object, and the methods included also allow the contents to be searched, added to and removed from, as well as a “toString” method which overrides the java method of the same name, to print an actual string of the contents, as opposed to a location of the “Bounded Set” within the computer. The Main() is included for testing purposes as well!

/**
 * BoundedSet is an object which stores objects of a generic type, E, 
 * in an array.
 * 
 *  @author AidanTakami
 *  @version 1.0
 *  
 */
 class BoundedSet {
	 private int size;
	 private E[] array; 
	 
	/**
	 * Constructor for the object BoundedSet which takes the Set size as an int capacity
	 * also sets size = capacity and creates a new array of type Object and castes it as an array
	 * of E. 
	 * 
	 * @since 1.0
	 * @param int capacity which represents the size of the BoundedSet
	 * 
	 */
	 @SuppressWarnings("unchecked")
	 public BoundedSet(int capacity){
		 size = capacity;
		 array = (E[]) new Object[capacity];
	 }
	 
	 /**
	  * method to add E element to the BoundedSet and return a boolean
	  * 
	  * @since 1.0
	  * @param E element which is what will be attempted to be added to the BoundedSet, cannot be null.
	  * @return Boolean: true if added, will return false if element = null, BoundedSet is full, or element has already been added
	  */
	 public boolean add(E element){
		 //returns false if element = null, if element is already contained within BoundedSet, or if BoundedSet is full
		 if(element == null) return false;
		 else if(contains(element)) return false;
		 else if(getSize() == size) return false;
		 else
		 {
			 array[getSize()] = element;
			 return true;
		 
		 }
	 }
	 
	 /**
	  * method to remove E element from the BoundedSet and return a boolean
	  * 
	  * @since 1.0
	  * @param E element which is the element to be removed from the BoundedSet
	  * @return Boolean: true if added, false if element = null, or cannot be found
	  */
	 public boolean remove(E element){
		 //returns false if element = null
		 if(element == null) return false;
		 if(!contains(element)) return false;
		 else
		 {
			int removal = findIndex(element);
			array[removal] = null;
			return true;
		 }
	 }
	 /**
	  * Method to see whether the BoundedSet contains E element
	  * 
	  * @since 1.0
	  * @param E element which is the element which is searched for within the BoundedSet
	  * @return Boolean: true if element is contained, false if not.
	  */
	 public boolean contains(E element){
		 //Calls private method findIndex and returns false if -1 is returned, otherwise returns true
		 if(findIndex(element) == -1) return false;
		 else return true;
	 }
	 
	 /**
	  * Accessor for the capacity of the BoundedSet
	  * 
	  * @since 1.0
	  * @return int representing the capacity of the BoundedSet
	  */
	 public int capacity(){
		 return size;
	 }
	 
	 /**
	  * Accessor for the current size of the BoundedSet
	  * 
	  * @since 1.0
	  * @return int representing the current size of the BoundedSet
	  */
	 public int getSize(){
		 return occupiedSize();
	 }
	 
	 /**
	  * toString method which converts BoundedSet into something human readable
	  * 
	  * @since 1.0
	  * @return String of the BoundedSet
	  */
	@Override
	 public String toString(){
		String set = new String();
		set += "[";
		//loops through BoundedSet and adds each element to String set
		for(int i = 0; i < size; i++){
			set += (array[i] + ", "); 
		}
		set += "]";
		return set;
	}
	 //Finds where E element is located within BoundedSet
	 private int findIndex(E element){
		 for(int i = 0; i < size; i++){
			 if(array[i] == element) return i;
		 }
		 return -1;
	 }
	 
	 //Gets the number of E in the BoundedSet
	 private int occupiedSize(){
		 int occupied = 0;
		 for(int i = 0; i < size; i++){
			 if(array[i] != null) occupied++;
		 }
		 return occupied;
	 }
	 public static void main(String[] args){
		 BoundedSet intSet = new BoundedSet(8);
		 BoundedSet stringSet = new BoundedSet(4);
		 //adds ints to intSet. adds both duplicates and passes capacity
		 intSet.add(14);
		 intSet.add(12);
		 intSet.add(12);
		 intSet.add(52);
		 intSet.add(90);
		 intSet.add(78);
		 intSet.add(2);
		 intSet.add(123);
		 intSet.add(44);
		 intSet.add(50);
		 //adds Strings to stringSet
		 stringSet.add("Hello");
		 stringSet.add("World");
		 
		 System.out.println("We have 2 BoundedSets. The first contains ints, the second contains Stirngs");
		 System.out.println("The first: " + intSet);
		 System.out.println("The second: " + stringSet);
		 System.out.println();
		 System.out.println("Does intSet contain: 54? " + intSet.contains(54));
		 System.out.println("Does intSet contain: 78? " + intSet.contains(78));
		 System.out.println();
		 System.out.println("What is the capacity of stringSet? " + stringSet.capacity());
		 System.out.println("What is the number of elements currently contained in stringSet? " + stringSet.getSize());
		 System.out.println();
		 stringSet.remove("World");
		 System.out.println("We have now removed 'World' from stringSet, which looks as follow: " + stringSet);
		 System.out.println();
	 }
}

Game Sample: Speak Method

This method is a small part of a game I worked on. The purpose of the method is to create a life-like output of words, to mimic dialogue and feel more realistic when characters are communicating.

The method takes a string which is the words to be output, an int which represents, in milliseconds, the pause between each word, and another string, speaker, which is the name of the person speaking.

This method works in a fascinating way and really is able to break down a barrier which is often present in text based games, the lack of realistic interaction.

I am not sure if I will post the entirety of this adventure on my site, but I will continue to update on methods which go into the game.

Screen Shot 2018-01-28 at 11.39.59 AM

<pre>
/*
    Method which creates life like speech by dividing up and outputting single words seperated by intervals
 */

void speak(string statement, int pause, string speaker){
    cout << endl;
    //temp string and stringstream are created
    string temp;
    stringstream ss(statement);
    cout << speaker << ":   ";          //Creates pauses between the output of words     while(ss >> temp){
        std::this_thread::sleep_for(std::chrono::milliseconds(pause));
        cout << temp << " " << flush;
    }
}

</pre>

Linked List

This is a Linked List object which can take any kind of input as a Node and organize it as an arrayList would organize it.

The Object inherits from the interfaces Stack and Queue, written by professor Adam Smith, provided at the bottom!

Enjoy!

/**
 * Linked List object which implements the Stack and Queue interfaces, allowing users to create
 * a linked list of Nodes
 *
 * @version 1.0
 * @author AidanTakami
 *
 */
public class LinkedList implements Queue, Stack{
	//Fields
	public  Node head;
	public  Node tail;
	public  int size;

//*************************
//LinkedList
//*************************

	/**
	 * The constructor for the LinkedList which takes the head and the tail Node
	 * @param Node head
	 * @param Node tail
	 * @since 1.0
	 */
	public LinkedList(Node head, Node tail){
		this.head = head;
		this.tail = tail;
		this.head.setNext(this.tail);
		size = 2;
	}

	/**
	 * adds the E value to the head of the LinkedList
	 *
	 * @param value  the value to be added to the tail
	 * @since 1.0
	 */
	public void addtoHead(E value){
		Node newNode = new Node(value);
		newNode.setNext(head);
		head = newNode;
		size++;
	}

	/**
	 * adds the E value to the tail of the LinkedList
	 *
	 * @param value  the value to be added to the tail
	 * @since 1.0
	 */
	public void addToTail(E value){
		Node newNode = new Node(value);
		tail.setNext(newNode);
		tail = newNode;
		size++;
	}

	/**
	 * Checks to see if the specified value is contained
	 *
	 * @param value  the value to be checked for within the LinkedList
	 * @return boolean  whether or not the value is contained
	 * @since 1.0
	 */
	public boolean contains(E value){
		//if head == value, return true
		if(head.getData().equals(value)) return true;

		Node inspect = head.getPointer();
		//otherwise
		for(int rep = 1; rep  0){
			Node oldHead = head;
			head = oldHead.getPointer();
			size--;
			return (E )oldHead.getData();
		}
		else return null;
	}

	/**
	 * toString method for the LinkedList
	 */
	@Override
	public String toString(){
		//creates string to be returned
		String listString = (" " + head.toString());

		//creates node to be changed and cycle through LinkedList
		Node subject = head;

		//loop which adds each next node to the String
		for(int rep = 0; rep  " + subject + " ");
			}
		}

		//returns the String
		return listString;
	}

//*************************
//Queue Methods
//*************************

	/**
	 * sets the head to the 2nd item in LinkedList and then returns the data
	 * of the previous head
	 *
	 * @since 1.0
	 */
	public E dequeue(){
		Node oldHead = head;
		head = oldHead.getPointer();
		size--;
		return (E )oldHead.getData();
	}

	/**
	 * Adds a Node to the end of the queue and sets that as the new tail
	 *
	 * @param Object value the object to be added to the end
	 * @since 1.0
	 */
	public void enqueue(Object value){
		Node addOn = new Node(value);
		tail.setNext(addOn);
		tail = tail.getPointer();
		size++;
	}

	/**
	 * Peeks at the head of the Queue or Stack
	 *
	 * @since 1.0
	 */
	public E peek(){
		return (E )head.getData();
	}

//*************************
//Stack Methods
//*************************

	/**
	 * removes an item from the head of the Stack, and returns it
	 *
	 * @return the value removed
	 */
	public E pop(){
		Node oldHead = head;
		head = head.getPointer();
		size--;
		return (E )oldHead.getData();
	}

	/**
	 * adds an item to the top of the Stack
	 *
	 * @param value  the value to be added
	 */
	public void push(Object value){
		Node newHead = new Node(value);
		newHead .setNext(head);
		head = newHead;
		size++;
	}

//*************************
//Node Object
//*************************

	/**
	 * Node object which contains a constructor method and a toString.
	 * Node holds an E value as well as a pointer to the next node in a LinkedList.
	 *
	 * @author AidanTakami
	 * @param 
	 * @since 1.0
	 */
	public static class Node{
		//Field
		E data;
		Node nextNode = null;

		/**
		 * Constructor for the Node object. takes the data which will be stored in the Node.
		 * @param data
		 * @since 1.0
		 */
		public Node(E data){
			this.data = data;
		}

		/**
		 * toString Method for the Node object.
		 *
		 * @since 1.0
		 */
		@Override
		public String toString(){
			return "(" + data + ")";
		}

		/*
		 * Returns the Node nextNode of the Node, which is the next Node in the sequence
		 */
		private Node getPointer(){
			return nextNode;
		}

		/*
		 * Returns the data of the Node
		 */
		private E getData(){
			return data;
		}

		/*
		 * Sets the nextNode of the node, only to be accessible by the LinkedList object
		 */
		private void setNext(Node next){
			nextNode = next;
		}

	}
/**
 * This is an interface for a Queue. An object which implements this interface
 * is thus a "first in, first out", or "FIFO" structure. It can enqueue to the
 * end, dequeue from the front, or peek at the front.
 *
 * @author Adam Smith
 * @version 1.0
 */
public interface Queue {
/**
* Removes an item from the front of the queue.
*
* @return the value removed
*/

public E dequeue();

/**
* Adds an item to the end of the queue.
*
* @param value the value to be enqueued
*/

public void enqueue(E value);

/**
* Checks item at the front of the queue, without altering the queue.
*
* @return the value checked
*/

public E peek();
}

/**
 * This is an interface for a Stack. An object which implements this interface
 * is thus a "first in, last out", or "FILO" structure. It can push to the top,
 * pop from the top, or peek at the top.
 *
 * @author Adam Smith
 * @version 1.0
 */

public interface Stack {
	/**
	 * Checks item at the top of the stack, without altering the stack.
	 *
	 * @return the value checked
	 */

	public E peek();

	/**
	 * Removes an item from the top of the stack.
	 *
	 * @return the value removed
	 */

	public E pop();

	/**
	 * Adds an item to the top of the stack.
	 *
	 * @param value  the value to be enqueued
	 */

	public void push(E value);
}