## Test your maths skills at the MathDOJO!

Another pro­duc­tive week­end bares fruit for another mini game! This time I’ve put together a dojo-themed mini game whose sole pur­pose is to test your abil­ity to do sim­ple (well, mostly) arith­metic cal­cu­la­tions in your head and your tol­er­ance for my sense of humour (which is not so bad I hope ;-) ).

#### Screen­shots

Here’s some screen­shots taken from the game:

As you can see, the main game loop is sim­ple: see some dia­logue from your oppo­nent, he asks a ques­tion, you answer, if you answer cor­rectly within time then your oppo­nent loses health point, when the opponent’s HP is depleted then you’ve defeated him and move onto the next opponent.

So far there’re 7 oppo­nents in the game, each with his own set of dia­logues and ques­tions become pro­gres­sively harder, your score is tracked and you can get a big bonus in score if you answer the ques­tions quickly (and cor­rectly of course!) and man­age to string together a suc­ces­sion of cor­rect answers! As the oppo­nents become tougher, their ques­tions will yield greater scores too, and not to men­tion they’ll be harder to beat as they have a higher HP value which means you have more chance to bet­ter your all-time top score!

#### Game Flow

With­out going through all the steps of mak­ing the game (maybe I’ll do that at a later date), the basic flow of the game goes some­thing like this:

The tricky thing is then how do you con­trol this flow eas­ily so that depend­ing on the state you’re in the right action is trig­gered when the play presses the ENTER key.

In the end I set­tled for a mech­a­nism where the DOM’s onkey­down event is han­dled by this bit of code:

`   1: // hook up the onkeydown event to execute the 'next' action whatever it might be`

`   2: document.onkeydown = function(event) {`

`   3:     if (event.keyCode == 13) {`

`   4:         nextAction();`

`   5:     }`

`   6: };`

The nex­tAc­tion vari­able is updated at each step of the game loop so that when the player presses the ENTER key the game does the right thing. The only devi­a­tion from this pat­tern is when I try to get the answer from a player, because there’s a time restric­tion on answer­ing the ques­tions I needed to set up a timer so that when it times out it’ll trig­ger the state tran­si­tion as well.

#### Play

You can play the game at:

http://mathdojo.theburningmonk.com

http://LNK.by/fgzcu

Enjoy! Do let me know if you have any sug­ges­tions, dif­fi­culty level, etc. etc.

## Creating a count down meter with CSS3 and JQuery

Whilst work­ing on the Math­DOJO mini game one of the neat lit­tle things I tried to do was imple­ment a time meter which steadily counts down and changes colour (from green to yel­low to glow­ing red) as it approaches 0:

First, you need some­thing to rep­re­sent the meter, a sim­ple <span> ele­ment will do:

`   1: <body>`

`   2:     <span id="count-down-meter"></span>`

`   3: </body>`

Then you need CSS to define its colour (and glow effect using CSS3 ani­ma­tion which for now, is only sup­ported by webkit browser unfor­tu­nately) at dif­fer­ent stages

`   1: /* define the animation (webkit-only) */`

`   2: @-webkit-keyframes redPulse`

`   3: {`

`   4:     from { -webkit-box-shadow: 0 0 9px #f00; }`

`   5:     50% { -webkit-box-shadow: 0 0 18px #f00; }`

`   6:     to { -webkit-box-shadow: 0 0 9px #f00; }`

`   7: }`

`   8:`

`   9: /* initial state of the meter */`

`  10: #count-down-meter`

`  11: {`

`  12:     display: block;`

`  13:     width: 100%;`

`  14:     height: 15px;`

`  15:     margin-top: 10px;`

`  16:     background-color: #0f0;`

`  17: }`

`  18:`

`  19: /* change color at midway */`

`  20: #count-down-meter.middle`

`  21: {`

`  22:     background-color: #ff0;`

`  23: }`

`  24:`

`  25: /* change colour and play animation when it's on its last leg */`

`  26: #count-down-meter.lastleg`

`  27: {`

`  28:     background-color: #f00;`

`  29:     -webkit-animation-name: redPulse;`

`  30:     -webkit-animation-duration: 2s;`

`  31:     -webkit-animation-iteration-count: infinite;`

`  32: }`

The ani­ma­tion itself is han­dled by Javascript, using JQuery’s ani­mate method:

`   1: function start() {`

`   2:         // change to yellow when 40% way through`

`   3:     var midWidth = meter.width() * 0.6,`

`   4:         // change to glowing red when 70% way through`

`   5:         lastlegWidth = meter.width() * 0.3;`

`   6:`

`   7:     meter.animate({`

`   8:         width: 0 + "px",`

`   9:     }, {`

`  10:         duration: 5000,`

`  11:         easing: "linear",`

`  12:         step: function(now, fx) {`

`  13:             if (now <= midWidth) {`

`  14:                 meter.addClass("middle");`

`  15:`

`  16:                 if (now <= lastlegWidth) {`

`  17:                     meter.addClass("lastleg");`

`  18:                 }`

`  19:             }`

`  20:         }`

`  21:     });`

`  22: };`

To reset the state changes to the meter after­wards, it’s eas­i­est to remove the “style” attribute as JQuery applies the changes through the “style” attribute, which can be a prob­lem if you had man­u­ally inserted style in your HTML:

`   1: function reset() {`

`   2:     meter.stop()`

`   3:          .removeAttr("style")`

`   4:          .removeClass("middle")`

`   5:          .removeClass("lastleg");`

`   6: };`

Here’s a live demo:

So that’s it, nice and easy! Enjoy! Hope you find some good use for it.

## Converting List<T> using covariance

I saw an inter­est­ing use of covari­ance today, con­sider an inter­face IMy­Class and an imple­ment­ing class MyClass:

`   1: public interface IMyClass { }`

`   2:`

`   3: public class MyClass : IMyClass { }`

If you want to con­vert an List<MyClass> to a List<IMyClass> you would nor­mally use the Enumerable.Cast method but did you know that you can also use C# 4’s sup­port for covari­ance in the type para­me­ter and do this instead:

`   1: var original = new List<MyClass>();`

`   2:`

`   3: var converted = original.ToList<IMyClass>()`

Funky, eh? ;-)

Though I think it’s a party trick best avoided for any pro­duc­tion code, for which you should still prefer:

`   1: var converted = original.Cast<IMyClass>().ToList();`

because:-

• it achieves the same result
• it is just as expressive
• it is the stan­dard way of doing this kind of con­ver­sions in LINQ
• it is under­stood by most C# devel­op­ers so unlikely to cause confusion

There’s another argu­ment for using Cast, in the case of use-defined implicit/explicit oper­a­tors. Imag­ine if you have another class which does not inherit from MyClass but defines an explicit oper­a­tor which allows you to cast an instance of MyClass:

`   1: public class MyOtherClass`

`   2: {`

`   3:     public static explicit operator MyClass(MyOtherClass other)`

`   4:     {`

`   5:         return new MyClass();`

`   6:     }`

`   7: }`

In cases like this, you won’t be able to use the covari­ance trick:

`   1: void Main()`

`   2: {`

`   3:     var original = new List<MyClass>();`

`   4:`

`   5:     Console.WriteLine(original.GetType());                               // List<MyClass>`

`   6:`

`   7:     // cast here doesn't actually do anything`

`   8:     Console.WriteLine(original.Cast<IMyClass>().ToList().GetType());     // List<IMyClass>`

`   9:`

`  10:     // changes the compile type, works because of covariance`

`  11:     Console.WriteLine(original.ToList<IMyClass>().GetType());            // List<IMyClass>`

`  12:`

`  13:     // casts the objs to MyOtherClass using the defined convertor`

`  14:     Console.WriteLine(original.Cast<MyOtherClass>().ToList().GetType()); // List<MyOtherClass>`

`  15:`

`  16:     // this line won't compile.`

`  17:     // it doesn't work because this is not covariance, there's no inheritance`

`  18:     // relationship between MyClass and MyOtherClass`

`  19:     // Console.WriteLine(objs.ToList<MyOtherClass>().GetType());`

`  20: }`

##### Ref­er­ences:

Stack­Over­flow ques­tion – Cast­ing List<T> – covariance/contravariance problem

## IList<T> doesn’t extend IList

Look­ing at these two images snapped right off MSDN, what do you notice?

.

.

.

that IEnumerable<T> extends IEnu­mer­able but IList<T> doesn’t extend IList!?

I know, pecu­liar isn’t it?

Turns out, it was for a good reason:

“A sequence of inte­gers can be treated as a sequence of objects, by box­ing every inte­ger as it comes out of the sequence. But a read-write list of inte­gers can­not be treated as a read-write list of objects, because you can put a string into a read-write list of objects. An `IList<T>` is not required to ful­fill the whole con­tract of `IList`, so it does not inherit from it.”

Inter­est­ing.

## Eric Lippert on the decision to omit Enumerable.ForEach

Found another inter­est­ing post on Eric Lippert’s blog, this one explain the ratio­nales behind why there’s no built-in Enumerable.ForEach exten­sion method, one which myself and no doubt many oth­ers had decided to imple­ment ourselves.

As he explains, there are two main philo­soph­i­cal rea­sons why he’s against such an exten­sion method:

“The first rea­son is that doing so vio­lates the func­tional pro­gram­ming prin­ci­ples that all the other sequence oper­a­tors are based upon. Clearly the sole pur­pose of a call to this method is to cause side effects.

“The sec­ond rea­son is that doing so adds zero new rep­re­sen­ta­tional power to the lan­guage. Doing this lets you rewrite this per­fectly clear code:

foreach(Foo foo in foos){ state­ment involv­ing foo; }

into this code:

foos.ForEach((Foo foo)=>{ state­ment involv­ing foo; });

which uses almost exactly the same char­ac­ters in slightly dif­fer­ent order. And yet the sec­ond ver­sion is harder to under­stand, harder to debug, and intro­duces clo­sure seman­tics, thereby poten­tially chang­ing object life­times in sub­tle ways.”

Well, that clears a few things up, hear­ing from one of the guys on the C# com­piler team.

#### Ref­er­ences:

Eric Lip­pert – fore­ach vs ForEach