I decided to go ahead and post a few solutions of my own.
Switch
This one makes use of switch
statements and saves each color as an object literal to improve readability and increase coding speed and efficiency:
var color = { 'green' : '#0f0',
'red' : '#f00',
'yellow': '#ff0'};
switch(player.getColor()) {
case color.green:
player.setColor(color.red); break;
case color.red:
player.setColor(color.yellow); break;
case color.yellow:
player.setColor(color.green); break;
default:
player.setColor(color.green);
}
The default
case at the end isn't necessary for that particular level, as the player's color is already green by default, but I decided to include it anyways for completion's sake.
Increment and modulo
This solution makes use of the increment operator ++
and the modulo operator %
, making the code much, much shorter.
var colors = ['#0f0', '#f00', '#ff0'];
var i = 0;
player.setPhoneCallback(function() {
player.setColor(colors[++i % 3]);
});
player.setColor(colors[++i]);
Since we can't add code outside the player.setPhoneCallback()
method, it has become a bit hacky.
The idea behind this solution, is to define a color array which we will cycle through. For that, the increment and modulo operators are instrumental. For those who don't know: the modulo operator returns the rest of a division.
Since we don't want our variable i
to be reset every time we use the phone, we have to redefine the phone method. Once we're done, we call player.setColor()
to change our color. That part isn't necessary, but without it, we'd have to use the phone twice to change our color for the first time.
Once you understand the above code, we can shorten it even more:
if (!player.i) player.i = 0;
player.setColor(['#0f0', '#f00', '#ff0'][++player.i % 3]);