Geek Culture
Published in

Geek Culture

Roll Initiative: Part 2

Handling Tactical Initiative Data Using Linked Lists

Today, the objective is to sort a C# Dictionary by the value property of each key/value pair, and then load that information into a LinkedList. This list will allow us to easily control who may act and keep the UI updated in the process.

We’ll begin by declaring a LinkedList<KeyValuePair<Actor, int>> to match the data from the dictionary. Then in the RoundStart() method we made in the previous article we’ll remove the debug loop and replace it with another loop that is specifically targeting the key/value pairs in the dictionary:

I changed the Key type from GameObject to Actor — it turned out to be more expedient to reference the class instance, and access the GameObject through that only when necessary.

Here I’m using LINQ to read the dictionary in Value order, and then adding the current value to the first node in the initiative list. This will result in the lowest initiative being stored in the last node when the foreach loop is complete.

Now that the dictionary is sorted, we need to update the UI to show the player where everyone is in the turn order. For that we’ll go to the UI Manager.

Here’s where we take advantage of the LinkedList. Normally, this kind of operation would be very resource intensive, requiring nested for loops. But since each node on the LinkedList has a reference to the nodes before and after it, we can simply remove the last item on the list and put it up front. Since we’re iterating backward from lowest to highest, this will place the portrait and initiative values in their proper places.

Note that to make this extensible we’ll later need to add the ability to populate and expand the _initiativeRoster and _initiativeText lists dynamically to account for any number of actors, but for now we’ll serialize it and populate the list for the four actors we have in the scene.

Finally, we need a button to advance between turns. The button will trigger an AdvanceTurn() method in the GameManager class:

Here I’m moving the first (current) actor/initiative pair on the list to the back of the list. Then I tell the UI Manager to update the initiative display, and I’m letting the SelectionManager know who the active actor is (more on that next article). Finally, I assign the current initiative value to an index so I can track where we are in the initiative round.

Time to look and see what we have:

Magical.

That’s all for today. In my next article I’ll wrap up the initiative system by developing methods that will differentiate between player and AI turns and handle input appropriately.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Micha Davis

Micha Davis

Unity Developer / Game Developer / Artist / Problem Solver