Nim

Rules:

How to code it:

  1. Start from the First Button Array Program.
  2. Add a title, and a label to track whose turn it is.
  3. When you click on a button it switches whose turn it is.
  4. When you click on a pile it has a dialogue box that removes stones from the pile.
  5. 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.
  6. Make sure that the game stops when someone wins (all the piles are empty). Print out who wins.
  7. 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.
  8. 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);
   }
   }