Tuesday, May 2, 2017

The Real Secret To Coding Productivity: The 10 Best Programming Albums

If you're like me, then you hate walking away from a coding session feeling defeated, beaten down, and unproductive.  Bro, let me tell you the secret to avoiding that feeling for the rest of your sorry life: listen to groovy electro-jams while you code.  Trust me on this.  It will simultaneously relax, stimulate, and inspire you.  I'm talking about the kinda stuff that will put you INSIDE the code, where you can make a nice little home for yourself that you actually ENJOY spending time in (even when you can't figure out why the hell that ninety-line function you've been working on keeps returning nil).

Don't exactly know what I'm talking about?
THAT'S OKAY I MADE A GUIDE FOR YOU.

Furthermore, I'm not even going to defend my selections with words.  Put any one of these suckers on the next time you're rigging up a data structure or parsing some JSON; you'll see what I mean.  Thank me later.

Aphex Twin - Selected Ambient Works 85-92



Basic Channel - BC-01-09 (Series of EPs)


Booka Shade - Movements



Ceephax - Cro Magnox


Daft Punk - Homework


Disasterpeace - Fez Original Soundtrack



The Field - From Here We Go Sublime


Manuel Göttsching - E2-E4



Ricardo Villalobos - Alcachofa



Underworld - Second Toughest In The Infants


Tuesday, March 21, 2017

CloudKit! Oh, Wait... I Guess It's Time To Enroll In The Apple Developer Program

This blog was originally supposed to be about CloudKit and using Apple's cloud services for use in your apps, but after snagging Ray Wenderlich's starter project from his site and launching it in Xcode I was met with this:



O dam.  I guess it's about time to fork up some do$h for a Paid Developer Account with Apple.  The day has finally come.  But what do I actually get for my 99 US Dollars?  Why do even have to pay for this thing at all?  Well, let's dig in.  For those of you that are on the cusp of making the plunge along with me, I hope this article will be helpful on your journey.

BETA RELEASES

The first perk of being a part of the Apple Developer Program is access to the Beta versions of all of their operating systems, including iOS, macOS, tvOS, and watchOS.  This ensures that as a developer you are always in the know about which features are going to be hitting consumers in the next software updates.  Apple also hosts beta releases of Xcode on their developer site, so you'll always have access to the most updated version of the powerful IDE for your Swifting.

KEY APPLE TECHNOLOGIES

There are a bunch of key Apple technologies that become to available to you after you enroll as well. Let's go over some of them.

  • CloudKit: Provides user authentication, database storage, and cloud assets to your program using Apple's iCloud service.  For free, it starts with 10GB Assets Storage, 100MB Database Storage, 2GB of Data Transfers, and allows 40 requests per second.  It even scales up as your user-base increases.
  • Game Center: Apple's social network for gaming.  Tracks high-scores, game invites, and online matchmaking.
  • Wallet: Integrate into your app to track gift cards, concert tickets, boarding passes, and more using PassKit.
  • Apple Pay: Simplifies the payment system of your app by allowing the user to utilize the cards they already have saved in their Apple Pay preferences and verifying their identity using Touch ID.
  • In-App Purchase: Using the StoreKit framework, you can offer premium content, virtual goods, and subscriptions to your user-base.
  • Maps: Gain access to Apple Maps integration, including custom annotations, highlighted regions, overlays, 3D views, and more.
  • Keychain Sharing: Allows the use of Apple Keychain to share user passwords between your apps.
  • App Groups: Lets you share containers between your apps and grants additional features for the apps to communicate with each other.
  • Data Protection: Encrypts the data you are storing locally on your users' devices for increased security.
  • HomeKit: Grants the ability to control Network-enabled devices with your app.  HomeKit compatible door locks, lightbulbs, thermostats, window shades, and more are already on the market.
  • HealthKit: Connects your app to Apple's Health app and lets you use the user data stored there to implement your own features.
  • Wireless Accessory Configuration: Enables your app to connect to and configure external Wi-Fi accessories.
  • Personal VPN: Create and manage custom VPN configurations.
  • Inter-App Audio: Export audio that can be used between other inter-app audio enabled apps.
  • Background Modes:  Define background functionality for your app while the user is doing other things.
  • Associated Domains: Associate your app with specific web domains to connect it to specific services.

APP TESTING

Another key benefit of the Apple Developer Program are the features it provides you for testing your products.  You are permitted to add up to 100 devices to your developer account from each product family (iPhone, iPad, Apple TV, etc.) to directly install your applications on for testing purposes.  This is a great way to give test builds to friends, family, testers, to get some feedback on your app.

A much more robust testing platform is TestFlight.  Think of TestFlight as an official beta release of your app that you can invite up to 2,000 participants to try by simply adding their email to the invite list.  The really cool thing about TestFlight is that it's an officially managed platform by Apple, meaning that once you've submitted your app and it's been approved Apple takes care of all additional device management.  Apple includes all necessary user instructions to get started directly in the invite email.  If you have a new build ready to go out, just let Apple know and all testers will get a notification informing them to download the new build.  Pretty sweet!


APP SUPPORT

Think of this like AppleCare for your apps.  As part of your membership in the Developer program, you are granted up to two sessions a year for code-level support by Apple Technical Support.  These sessions are designed to speed up your development process and get you to deployment as fast as possible.  Not a bad little perk!

DISTRIBUTION

At the end of the day it's all about that do$h, innit?  The single most important thing about the Apple Developer Program is that it lets you host your products on The App Store, accessible from the millions and millions of Macs, iPhones, iPods, Apple TVs, and Apple Watches out there in the wild.  It's important to know that Apple takes a 30% cut of all profits you make from your apps (hey, it could be worse), so prepare for a good chunk of change to be scraped off the top of each check that swings your way.

Specifically for macOS, Apple lets you circumvent the store by providing you with a Developer ID that you can use to register your apps with Apple.  This let's macOS users open your apps after downloading them without having to worry about any security warning or privacy concerns that Apple has built into the OS.  If you are interested in developing extensions for Safari, enrollment in the program also allows you to host your extensions in the Safari Extensions Browsers.

CONCLUSION

This whole article probably comes across as an ad for Apple's Developer services, but guess what?  If you have any hope of seeing your app running on someone's phone other than yours or a close friend's, you've got no choice but to pay up!  Seems aggressive, but that's the way Apple does business and will almost certainly continue to doing business.  At least Apple recognizes the need to continually attract new developers, so has added value to the program by offering the services listed here.  So from my perspective $99 a year is not all that unreasonable.  

Or maybe I've just been drinking the Apple Juice for way too long!

Friday, March 10, 2017

Parsing Mad XML To Snag Some Sweet, Sweet Board Game Data Using BGG's API

Check it.

API: Application Programming Interface
XML: Extensible Markup Language
BGG: Board Game Geek

Now that you're caught up on all of the initialisms in the title of this article, let's write a simple app that's lets us use some of that data.  But what should it do?  Well, I don't know about you doofuses, but I spend almost as much time trying to figure out which game in my collection I'd like to play next as I do playing them.  So here's what we're going to do: make our phones decide for us.  Let's do it.

Let's start with the User Interface.

Game Grabber?  Eh, that's cool.  I can live with that. That text field there is where we can plug in any BGG username to tell our app whose collection to choose the game from. The Game label toward the bottom is going to be what we use to display the name of the game that our phone decides we should play.  Don't worry, its going to stay hidden until the game is actually chosen.

Aight, lets jump into our View Controller and get coding.



Okay, we know we have to make our View Controller a delegate for our text field, but what in the heck is an XMLParserDelegate?  It's a Protocol we're adopting to become a delegate for an XML Parser, you dingus!  All will make sense soon.  Let's move on.



Okay, what do we have we here.  Outlets for our text field and label, an array of strings for the game titles we're going to snag from BGG, a blank string called currentTitle, and a bool keeping track of whether or not our XML document is currently being parsed.  Not bad, not bad.  Let's set up our viewDidLoad next.



Coolio.  Here we set our usernameField delegate to the View Controller, and set up a gesture recognizer for out view and give it an action called dismissKeyboard.  Still no sign of that XMLParserDelegate, though.  Hmmm, I'm sure it will come into play later.  For now let's take a look at dismissKeyboard in more detail.



Well, I don't know what I expected... it dismisses the on-screen keyboard.  Got it.  I wonder what's going on with that text field anyways?



Very nifty.  First thing we do when the user presses the return button and starts their search is check if the gameTitles array is empty.  This is to make sure that if we've already got some game data from a previous API request we don't have to make another one.  We can just take a game out of the titles we already nabbed.

After that is where we are ensuring that randomGameLabel is staying hidden until we put a game title in it.  We also set documentBeingParsed to true because we are about to start digging into some XML!  There are a few checks to make sure of first though: first that the usernameField actually has some text in it, and secondly that there are no spaces in it.  You cannot have spaces in your BGG username!  Unless I missed a memo or something, I probably did.

Whatever, lets get on the net.



There you go, hitting that API like a sledgehammer.  We're snagging the username from our text field and passing that in as part of the URL, but what's that little ?own=1 doohickey?  That's a parameter we're passing in called own with a value of 1.  What that does is ensure that the game our phone spits back out to us is a game we actually own.  The whole point here is to be able to actually play the game that shows up on our screen, remember?  I supposed you could pass in a value of 0 if you wanted your phone to tell you what game you should bur next or something, but I digress.



Pretty standard session and dataTask stuff.  There are two more guards in there making sure we're actually getting a response and usable data back.  The only real standout is that sick switch statement right in the middle of the task.  Finally, our XMLParserDelegate is coming into play.  Notice, however, that this is only the case if the statusCode we get back from BGG is exactly 200, which indicates the data is ready for our perusal.  Otherwise, we break out of the closure.

The funny thing about the BGG API is that it always fails the first time you make a new request.  This is because their servers work on a queuing system.  Think of your first request like knocking on their door, and it isn't until you make another, slightly more polite request, that you're actually let inside.  We'll handle this in a little more detail later, but for now let's look more deeply into our XML Parser.

First things first, we create an XMLParser called xmlParser and we tell it that it's going to be chowing down on the response data we wrestled out of the API.  Then we assign the View Controller as its delegate, and lastly we tell it to GO.  TO.  TOWN.  Let's look into more detail at what our parser is actually doing.



Our first parser delegate function is didStartElement.  This bad simply tells the currentTitle string we declared way up above to empty out its contents every single time it hits a new Element in our XML file.  An element in XML looks like this:

<name>Agricola</name>

So this function fires off every time it hits that first set of brackets.  The reason we want this is to happen is to make sure we can snag every element's String individually and keep our data nice and tidy.



The foundCharacters function continually fires off as it makes its way down the XML file.  Get it now?  That's why we have to make sure at the start of each new element we're clearing our currentTitle string.  Otherwise this function will just keep adding more and more characters to the same darn string!



At the END of each element we check to see if it is a "name" element, if it is we set the currentTitle string equal to a gameTitle variable and append it to our array of gameTitles.  Now you should understand the true nature of XML Parsing!



Lastly, we have this parserDidEndDocument function that switches the documentBeingParsed bool back to false.  This has adds no functionality whatsoever to our app, but I used it for debugging and forgot to take it out.  Sue me!

Okay, we are almost done.  Our dataTask is finished, now we just have to do something with all that data we just got.



If at this point our gameTitles array is still zero, we throw a message up onto the screen to let the user know to try again in a couple of seconds (a bad search will have been caught by an earlier guard statement, so this is in case BGG's API stubbornly decides not to give us any data like it's been known to do).  Otherwise, we got some game titles now to play with!  Heck yes!  Let's randomly select one and spit it up to the screen.

There is one more thing we have to watch out for though.  What if you want to switch between multiple BGG collections by searching different users back to back?  We need an elegant way to flush out the gameTitles array and get it prepared for some new ones.  We didn't include that in the actual search function because we wanted to avoid calling the API over and over again for the same user's collection.  How about this:



There we go.  If the user decides to change the text in the text field, we'll flush the array out then.

That's it, buddy!  Let's see this bad boy in action.  Bear in mind, in the following gif I'm doing searches I've already done several times before which is why I'm not getting hit with the message saying to try again.  Typically, the first request will tell you to cool off and wait for a bit, but that's ok I still love you BGG :)




I love it.  I love everything.  I love board games.  I love Swift.

Fare thee well, bozos.

Wednesday, March 8, 2017

Using Functional Recursion To Create A Self-Playing Version Of 6 Nimmt!

This experiment seeks to fly in the face of the single responsibility principle.  Not because I should, but because I can.  Call me Icarus, if you wish, but my wings are molded from stronger material than wax.  ANYWAYS, nothing in this article is indicative of good coding practices, or is even particularly elegant or efficient in its design.  I do think it gives some interesting perspective on the value recursive functions bring to the programmatic table however, so let's use that as my defense mechanism against the pundits.

What you are about to see is the entire game of 6 Nimmt!, a wonderfully German card game designed by Wolfgang Kramer, defined within a single function.  Set up, tear down, and all of the mechanics will be entirely contained within one function.  Furthermore, unlike my previous posts this one actually runs!  But first we're gonna need some classes and structs and what have you to get us started.

Let's start with the most rudimentary element of any card game, the cards:


Here we have a struct with three properties: number, bulls, and playedBy.  Number is the numeric value of the card, bulls are how many points the card is worth (points are BAD in this game!), and playedBy will help us keep track of which player uses the card in the game.

Next we need a deck to store these cards:












Pretty simple.  An array to store our cards and a function to generate our deck and shuffle it up.  Each card gets assigned a value between 1 and 104, and playedBy is nil for now.  Bulls are a computed property so we don't have to worry about that one at all.

Now we need some players to deal these cards to!


Our Player class has three properties: name, hand, and score.  All pretty self-explanatory.  We also got a neat little function for getting a Player their starting hand in there.

Lastly, we need a class for our game itself.

An array of Players, an array of Card arrays (representing the table where we're playing the game), a roundCounter to keep track of which round of the game we're in, and a simple bool to make sure we don't keep repeatedly setting up a game we're already playing.

Great, we're good to go.  If you don't know how to play 6 Nimmt! already the following function will make very little sense to you.  Too bad, brush up on your European card game history, bro.


Here's what we start with.  A pitiful, disgusting, empty, useless function.  Let's cram it with some functionality.


Our function starts innocently enough with a conditional checking if the game needs to be set up.  If it does, it creates a deck, five players, deals them ten cards each, and starts off each of the four card rows that our game is actually played on.  It ends by telling our game that it doesn't need to be set up anymore, remember we're going to be going through this game over and over again so we don't want to set up a new game every time a new round begins.

Take note that Deck.createDeck() and player.createHand() are the only external function calls in the entire game.  I decided to include those as methods because otherwise this screen shot looked like complete shit.


Next we create an empty array for all the cards players will be playing this round.  Note that it's totally safe to start it as empty because we want a brand new array for each round of the game we go through.  After that each player randomly chooses a card from their hand to play (proper A.I. is for another article, dude), then the cards are sorted from lowest to highest.  This is done because in 6 Nimmt! players take their turns in ascending card value order.

Now, we must find out which row each player's card will be placed in.


We start by calculating the difference between the player's card and the last card in each row.  If this creates a negative number we are setting the difference to a number higher than the highest possible value difference between cards to make the our conditionals much easier to implement.  

Now, to understand the following game logic, keep in mind the following rules of 6 Nimmt!
  1. A player's card value must be higher than the value of the rightmost card in the row they are placing it.
  2. If their card value is higher than the value of the rightmost card in multiple rows they must place it next to the card which has the least difference.
  3. If the row a card must go into already has five cards in it, the player scores all the Bulls in that row and replaces the row with their card.  Remember, players don't want Bulls!
  4. If their card value is lower than the rightmost card values in all four rows they can choose which row they want to score and replace with their card.
Cool, so we already have our player card and rightmost card value differences so lets start playing the game!


This is what happens if a player's card value is lower than all four rows rightmost card value.  The  player scores the row worth the least amount of Bulls and replaces it with their card.





These four conditional statements check to see which row the player's card should go in, then to see if that row already has five cards in it.  If it does, the player must score the row and replace it with their card.  If it doesn't, the player simply adds their card to the row. 

That's actually the entire game!  We're already done.  Not too crazy, right?  The only thing left to do is check to see who won:


This block of code only triggers if we just completed the tenth and final round of the game.  It sorts the players by their scores, prints some stuff to the console, and determines who the winner is.  After that it wipes clean all of our structs and class properties to prepare for another game.  There's only one small thing left to do, and that's make this bad boy recursive!


BAM, son.  We are done.  I could've made the game automatically play another game after finishing the clean up process, but infinite recursion is a terrifying thing and not to be trifled with.  Therefore the only thing left to do is call this functions as many times as we can handle and play 6 Nimmt! over and over and over again.  


Wow, what a journey.  What a world we live in where such great people can meet and bond over dozens of games of 6 Nimmt! each lasting about a second.  I am truly grateful that I was able to make such a meeting of minds happen inside magical the world of Swift.

Until next time!

Monday, February 27, 2017

Gameplay Is Dum

This article is going to be a rip-off of this wonderful article by the indomitable game theorist Alex Kierkegaard, but applied in greater detail to the tabletop space.  So go read that, learn from it, and report back when finished.

...

You finished?  Great!  Let's get started.

'Gameplay' is one of my least favorite words ever.  Now typically when I don't like something about games lingo I just whine incessantly and curse like a drunk, but for this particular subject I'm going to try and approach it with as much clarity and respect as I can muster.  Why the gravity?  Because I firmly believe the word 'gameplay' damages people's abilities to have effective conversations about games and game design, and thus the industry as a whole.  Let me take a few minutes of your precious time to explain myself.

The biggest problem with 'gameplay' is that the word is so exceedingly vague it seems to serve no linguistic function other than putting up a smokescreen in front of an opinion that the person using the word doesn't know how to adequately articulate.  And you know what they say, behind sloppy talking is sloppy thinking.  Did someone say that?  Well I'm saying it now.

I often hear 'gameplay' described as the interaction between the player and the game, or the overall feel of a game while playing it, and I say a word THAT broad is basically useless.  We don't have a word for the overall feel of a movie, or what it's like to read a book, or the way food is to eat, or for any other industry that begets journalistic criticism.  Words like that aren't useful.  We use words like cinematography, editing, narrative, characterization, imagery, taste, texture, substance, etc.  Words that refer to specific elements of the artwork or creation we are expressing an opinion of.  And what do we do when we when we want to make a broad, general statement about those things?  Simple.  We state whether or not WE LIKED IT.

Let's go back to my earlier statement about the word 'gameplay' providing a smokescreen for opinions people don't know how to adequately articulate.  Let's elucidate why this is a problem by imagining this hypothetical conversation:

Tim: How could you not like Game X?
Allen: I don't like the gameplay.

What an obnoxious answer!  What does that even mean?  I see this happen all the time and it drives me flipping crazy.  Here's how a proper conversation should go:

Tim: How could you not like Game X?
Allen: I think it has pacing issues, confusing turn order, obtuse combat, lacks interesting choices, is overly random, and rewards players for playing overly conservatively which doesn't match up well with its theme.

Now regardless of whether or not you agree with Allen, at least you know that he's actually given THOUGHT to his opinion.  At least he made statements that help EXPLAIN why he doesn't like Game X.  Even if all Allen said was "I don't know, I just don't like it" that would be more useful than "I don't like the gameplay" because then at least you'd know that he hasn't given the topic much thought, so it's probably not worth diving into a full conversation with him on it.

Furthermore, every single sentence that uses the word 'gameplay' would make perfect sense without it.  In many cases the sentence would make MORE sense without it.  Here are some examples:

"This game has really fast gameplay."
"This game has really fast pacing."

"This game has confusing gameplay."
"This game's turn order is confusing."

"Top 10 Gameplay Mechanisms"
"Top 10 Game Mechanisms" (Or even just Top 10 Mechanisms, we already know you're talking about board games, bro!)

"I like the theme, but I don't like the gameplay."
"I like the theme, but I don't like the game."

Some of the people I've spoken to at length about this have specifically brought up that last example as a flaw in my argument.  What if you don't like a game's 'gameplay', but you enjoy the theme so much you still enjoy the game?  Doesn't that mean the distinction is important and thus the word is necessary?  I understand where you're coming from, but I'm just not buying it.

First off, is it REALLY possible to like a game's theme SO much that you should say you like a game even though you don't like playing it?  I would argue that you should not.  And if you DO like playing a game despite not liking its 'gameplay', guess what weirdo?  You like the game's 'gameplay' after all, or at least parts of it enough to enjoy sitting through the experience more than once.

Thinking about this mode of thought in context to other art forms reveals what a strange way of thinking it is.  If someone thinks a movie has great characters, but they didn't enjoy watching it; or if they liked the setting of a book, but they didn't enjoy reading it, does it really make sense for these people to say they liked the movie they watched or book they read?  Keep in mind we WATCH movies and READ books, just like we PLAY games.  The capitalized words of course being the way in which we interact with the artwork, therefore being the source of any coherent opinion about it.

To bring the analogy even closer, let's include movie and book terms that take on the function of the word 'gameplay' in games, i.e. its overall feeling.

"I like the movie's characters, but I don't like its watchability."
"I like the book's setting, but I don't like its readability."

How bizarre do those statements sound?  That's what the word 'gameplay' sounds like to me.  There is absolutely nothing wrong with liking a constituent element of a work of art that overall you just didn't care for, trust me you'll be fine.  In fact, in many cases it's necessary!  You see, pointing out the positives and negatives of any work of art is what makes criticism actually useful.

"The movie has great characters, but I still don't really like it."
"The book has a cool setting, but I just don't enjoy reading it."
"The game has a really creative theme, but I don't find it fun to play."

How natural do those statements sound compared to the former ones!  Clear, useful perspectives that words like 'gameplay' seem to do nothing for but obfuscate their intent.

Imagine the confusion if board game critics had separate top 10 lists for their favorite games of the year and the 10 games they thought had the best gameplay:

"Top 10 Games"
"Top 10 Games With The Best Gameplay"

My goodness, it boggles the mind!  Whereas:

"Top 10 Themes"
"Top 10 Art Styles Of The Year"
"Top 10 Twists On Established Mechanisms"

Wow, useful information that makes immediate sense.  Who'd-a thunk it?

I feel like I've made my point, but in the spirit of beating a dead horse, let's continue.  You cannot express anything useful with the word 'gameplay'.  It's impossible.  All it does is add fluff to a conversation and make things take longer than they need.  Let's revisit Tim and Allen for round 2:

Tim: I didn't like this game.
Allen: Why not?
Tim: Its gameplay is all messed up.
Allen: What do you mean?
Tim: Well, let me explain further...

And so on and so forth.  Save us some time, Tim, and just get to the point!

Tim: I didn't like this game.
Allen: Why not?
Tim: Well, the artwork is ugly, the turns take too long, the timing of the card draws makes planning ahead impossible...

See what a pointless little filler word it is?  All it does is wast a lot of everyone's time and energy, but I think the real reason it bothers me as much as it does is that the word seems to be ubiquitously accepted, which I find to be just a disastrous failing of the English language.

When I read Kierkegaard's above article, I immediately began cutting the word out of my writing and speech, and I can state as absolute FACT that I began reaching useful conclusions faster, as if my brain found a programmatic shortcut.  I was no longer wasting time thinking about what was good or bad about a game's 'gameplay', but what was good or bad about the GAME.  It might seem like an insignificant distinction, but I feel it in my bones that eliminating the word from our collective vocabulary would save us all a lot of time and improve the average level of discussion around the hobby exponentially.  If nothing else, it would force people to put more consideration into their thoughts and opinions about the games they are playing.

I'll leave it at that.  Hopefully, my perspective got you thinking a little differently about games and the language we use to discuss them.  I encourage you all to at least make an attempt to remove the word from your lexicon, and just see how it affects your modes of thinking and expression.  Thanks for reading!

Thursday, February 23, 2017

Programmatically Defining Power Grid's Marketplace

Power Grid is one of my all-time favorite games.  In fact, I just played it last weekend!  I won, of course.  But I had an unfair advantage: a deep understanding of the mechanical underpinnings of one of the most crucial systems in the game -- its unpredictable marketplace where players can acquire new power plants each round.

How have I acquired this understanding, you may ask?  It's simple, I was working on this blog post.  Let's get to it.

If we are to represent all of the core functionality of Power Grid's market in Swift, where should we start?  I chose the Resource Type of each of the power plants as my starting point, represented here by an enum:



Sick enum, bro.  Next let's make a struct representing our actual power plants:



Whoa, motherfudger.  That is a doozy.  Looking more closely, you can see that the only stored property of this struct is its number.  Both its resourceType and citiesCanPower properties are computed using switches on that  number.  This makes initializing these PowerPlantCards extremely simple!

Alrighty, we're also going to need some variables to store all these structs we're gonna be messing around with, so lets get those poppin:



Wonderful.  We got three arrays of type PowerPlantCard: one for the actual market where players can select new power plants to add to their collection, another for the future market where players can see power plants that will be available for auction soon, and a third representing a deck where future power plant cards can be drawn from.

We also have a variable to help us keep track of the total amount of cards drawn from this power plant deck.  Why?  Well, a game of Power Grid undergoes a major change on exactly the 35th draw from the power plant deck.  Playing the game, this is represented by an actual card physically placed at the bottom of the deck at the beginning of the game, but because we're in computer world this representative component is strictly unnecessary.

Aight, now lets set up our markets and deck so we can get this game going:



So here we're iterating over a range of numbers (3 and 50, to be exact) and generating powerPlantCards for each of them.  Cards 3-6 go into the actual market, cards 7-10 go into the future market.  The rest are shuffled into the power plant deck, except for card 13 which goes on top.  Any number that pertains to a card that doesn't actually exist in a game of Power Grid just gets iterated over using the continue keyword.

Great, let's take a look at our arrays and check out what they got going on:





Nice shuffling, now we just need some functions to be able to actually do some stuff with our cards.








This function is for removing a power plant from the actual market when a player takes one to add it to their collection.  It checks to make sure the actual market isn't empty, removes the card they select from the array, draws a new card from the deck, and arranges it into the market.  The markets in Power Grid must always be in ascending order with the lowest four ranks in the actual market and the  highest four ranks in the future market.  This makes rearrangement necessary every time a new card is drawn.  Let's take a look at both of these functions:



This function increments the totalDrawnCards variable, checks to see if this is exactly the 35th draw (and sets up the new market if it is), then draws a card and returns it.  The Card must be optional in case the draw deck is empty or the new market is generated on this turn.



This is a meaty function so I made it a bit bigger for your sorry eyes.  We got a new array, we got cards being moved all over the place, we got a sort method, we got functionality to check how the markets need to be arranged.  We got it all.  No questions, please.

At the end of every round of Power Grid the highest value card is put back on the bottom of the deck, so here's that:



Simple enough.  All that's left is our function that gets called by the 35th draw from the draw deck to set up the new market.



Not bad!  Once this function is called, the future market is obliterated for the rest of the game and moves all the power plants to the actual market, which now contains 6 cards instead of the usual 4.

You got all that?  You wanna see it in action?  No prob, here is the market after a round of play in which every player gets a new power plant:




The cards are moved around a bit, and there are four less cards in the deck than before.  But wait!  Haven't we removed five cards?  There are five draw card function calls happening here after all.  Don't forget that the removeHighestPowerPlantCard function also adds a card to the bottom of the deck.  You see that Power Plant Card #31?  If you scroll up and look at the starting state of the market  you can see that was actually the 4th card drawn and added to the market, but since it was the highest ranked card at the end of the round it got moved back to the bottom of the deck.

The last thing to check out is our market state after the 35th card draw.  In our case this happens in the 7th round of play.  Let's check it out:





There you have it.  The future market has tanked (don't gamble on futures, bro) and there are now six cards in the actual market.  The power plant deck now solely consists of cards that have been put at the bottom of the deck by our removeHighestPowerPlantCard function calls.  Just like the real game!

This was a fun challenge, but I happily emerged triumphant in the end!  You see, that's all it takes to be happy, kids.  Tenacity and obsessive fascinations with niche hobbies.  The golden path to any great future!  Thanks for reading!