One of the more… annoying features about making a game in a non-functional (functional being a technical term, not meaning “useless”) language is that you are always worrying about state. I think I may have posted something about this in a previous entry, but its useful to mention it again, because it’s something that needs to be drilled into your head.
When you make a game, things happen in a loop. The loop takes input, processes and then outputs the data. It’s constantly listening for your input, then does what you tell it and sends out a response.
Currently, I’m working on making a little error noise play when I reach the locked portal without a key. I have the player move, then when it hits the location of the portal, check if the portal is locked or not. If it’s locked, check if I have the key. If I don’t, play an error noise and display a message “Need Key”. Sounds simple, right?
Sure. Except, as long as I’m on the location of the portal, the noise continues to loop. A cheating way to get around this might be to make a fairly long sound that gives a player time to move off the portal location before it would need to retrigger the audio. But that’s dumb, and just a hack.
No – what you do in a language that’s non-functional (and I have to admit, I don’t know enough about functional languages to know what programming a loop like this is like in them) is you set a “flag”. A boolean/binary “yes/no” option. I would create a “canPlayAlertSound” boolean flag that can be set to True or False. I would, at the start of the game, initialize that flag to True. Then, when I land on the portal, I check this boolean flag to see if I am allowed to trigger the sound — “TRUE”, and it plays, then right after it plays, the next line of logic says changes “canPlayAlertSound” to False.. This then since this loop is constantly happening, the next time the loop runs, I check “canPlayAlertSound” and see it’s false, so I don’t play the sound, this is well and good. However…
For some reason, when I slide my piece OFF the location, it triggers the sound. I’m not quite sure why, as in theory I am no longer on that particular spot and thus it should not trigger, but it does when I exit the portal space. So now my next goal is to figure out why it’s triggering.
But the point is – programming a game is quite annoying like this, because it’s a pattern you have to learn over and over and over. Now, there is probably some super cool trick to enable a particular function to fire once and only once during a given loop until it’s reset, but this is the only simple way I’m aware of at this moment. This means that for everything you need to run exactly once, you have to repeat this process. I think I’d consider it an anti-Pattern, though I’m not sure if that’s technically correct. It’s certainly a pattern of some sort. Mostly it’s an annoying Pattern…