Nim
Rules:
- This is a two player game.
- The game board consists of piles of stones.
- The players take turns removing any number of stones from a single pile.
- On your turn, click on the pile of stones that is not empty and remove
the number of stones that you wish.
- The last player to remove stones looses the game. You win if you force
someone else to remove the last stone.



How to code it:
- Start from the First Button Array Program.
- Add a title, and a label to track whose turn it is.
- When you click on a button it switches whose turn it is.
- When you click on a pile it has a dialogue box that removes stones from
the pile.
- Make sure that the player can’t remove from a pile that has 0 stones.
A player can also not remove more stones than is in a pile. In this case,
their turn is repeated until they play a legal move.
- Make sure that the game stops when someone wins (all the piles are empty).
Print out who wins.
- Get the users’ names and include them in the applet. You can also
change the colours of the buttons based on how close they are to 0: red is
1 stones, orange is 2 stones, etc.
- Set up the reset button so that you can play again.
Button Array Code
import java.awt.*; import java.awt.event.*; import java.applet.*; import javax.swing.*;
public class ButtonArray extends Applet implements ActionListener
{
JButton [] a;
int row = 10;
public void init ()
{ //a grid to layout the screen nicely
Panel p=new Panel ();
resize (500, 100);
//declare a new array of buttons
a = new JButton [row];
//initialize each of the buttons in the array
//with an empty label
for (int nNum = 0 ; nNum < row ; nNum++)
{
a [nNum] = new JButton ("0");
p.add (a [nNum]);
//each button will have an action listener
a [nNum].addActionListener (this);
a [nNum].setBackground (Color.yellow);
//each button will send a message with its number
a [nNum].setActionCommand ("" + nNum);
}
add(p);
}
public void actionPerformed (ActionEvent e)
{
int pos = Integer.parseInt (e.getActionCommand ());
int count = Integer.parseInt (a [pos].getText ());
count++;
a [pos].setLabel (count + "");
if (count == 0)
a [pos].setBackground (Color.yellow);
else
a [pos].setBackground (Color.white);
}
}