Syronex: software solutions

Example Nim Game in Java

This is an example implementation of a Nim game in Java. The user plays against the computer. The player taking the last token wins.

You can download the Java class file and source file. Note if you intend to read the source text that it is not a good example of how to program in Java with objects. This was intended as a programming exercise, for students with procedural programming as their only background.

Game script example

Nim Game Example
Number of heaps (2..n)
> 9
Game state:     4       5       6       9       9       8       8       6       5
USER plays. 
Which heap? 5
Number of tokens to remove? 9
Game state:     4       5       6       9       0       8       8       6       5
MACHINE plays. 
Game state:     4       5       6       4       0       8       8       6       5
USER plays. 
Which heap? 2
Number of tokens to remove? 5
Game state:     4       0       6       4       0       8       8       6       5
MACHINE plays. 
Game state:     4       0       6       4       0       8       8       6       0
USER plays. 
Which heap? 8
Number of tokens to remove? 6
Game state:     4       0       6       4       0       8       8       0       0
MACHINE plays. 
Game state:     4       0       0       4       0       8       8       0       0
USER plays. 
Which heap? 4
Number of tokens to remove? 4
Game state:     4       0       0       0       0       8       8       0       0
MACHINE plays. 
Game state:     0       0       0       0       0       8       8       0       0
USER plays. 
Which heap? 6
Number of tokens to remove? 8
Game state:     0       0       0       0       0       0       8       0       0
MACHINE plays. 
MACHINE wins.