I am writing a Javascript program to play Nim. In the meantime, if you have Mathematica I have written a short program to play the game.


(* A program to implement Nim strategy
Assume all Nim heaps are < 2^10,
If game is lost, try to lose slowly
As an example, try NimPlay[{7, 5, 3, 1}] *)

NimValue[game_]:=
Fold[#2 + 2 #1&, 0,
Mod[Plus @@ (Rest[IntegerDigits[# + 2^10, 2]]& /@ game), 2]]

NimMove[game_]:=
Block[{g = game, v = NimValue[game], i = 1},
If[v == 0, i = Position[g, Max[g]][[1, 1]]; g[[i]] -= 1,
While[g[[i]] <= NimValue[{v, g[[i]]}], i++];
g[[i]] = NimValue[{v, g[[i]]}]
];
If[g[[i]] == 0, Drop[g, {i}], g]
]

(* Simulating a Nim Game *)

NimPlay[game_]:=
Block[{g = game},
While[g != {},
NimPrint[g];
Print["-----------"];
g = NimMove3[g]];
{}]

NimPrint[game_]:=
Print[MatrixForm[StringJoin[Table["I", {#}]]& /@ game]]

ilan's home page