Thursday, May 22, 2014

I Love the Modulus Operator

Warning - Geek Thoughts Ahead!
Proceed at your own caution.  

Life guards are not on duty.

  I freaking love some of the simpler constructs in programming logic.  The binary operators, the ability to store multiple values in a byte and change it using bit maps, and of course, the modulus function.  Modulus (or % to me and the rest of the programming crowd) is that math method to divide by a (mod) number and you either get a value or 0.   I have used the modulus in quite a few programs in the past, but lately I have found another handy use for it.
  I have been trying to put together a simple Level/Player Artificial Intelligence (A.I.) for the game we are building right now.  (A.I. is kind of awkward to type, let's just call it "HAL", eh?)   Since the game is made up of squares on a board, HAL has to select desired squares on the board as the game progresses.  Anyway, I need HAL to do different or the same thing at various times.  I decided to tie the decisions to the seconds of the clock.  This is where the repetition of using a Modulus operation on the game second clock can give me a consistent repeatable action.  Even better, instead of setting up some custom Timer classes, I can just reference the desired modulus/action combinations in a plain text file.
    Cool, now I can tell HAL to touch the square to his left every 3 seconds by giving him a command like, "Modulus:3 - TouchLeft".   Pass the current game time in seconds to HAL and other players, and we will get the desired player action when it is appropriate.  That aught to slow HAL down a bit...
    Anyway, there are many ways to skin a cat, but this one really appeals to me.   Now I can move on to what exact actions are performed at repeatable times.  Currently, I just have a log message to prove that I put the player calls and the game timer together correctly.  Once I figure out the kinds of moves to make, like "Move Left", then I can assign them keywords and build up a 'script' for HAL to follow.  The more I think about it, moveLeft sounds like a pretty good next step.  HAL is going to be a left-stepping fool before this day is over!
    "HAL, I have some instructions for you..."

No comments:

Post a Comment