import java.util.List; import java.util.LinkedList; /* This class represents a game that begins with a pile of sticks of a given size, and where players alternate taking exactly one or two sticks from the pile. The player who takes last stick, thus leaving an empty pile, is the winner. */ public class OneOrTwoState implements State { private int remainder; // the number of sticks remaining /* A constructor @param n the number of sticks initially in the pile */ public OneOrTwoState(int n) { remainder = n; } // If there is at least one stick remaining, // a successor is created that corresponds // to the current player's taking exactly one stick // If there are at least two sticks remaining, // a successor is created that corresponds // to the current player's taking exactly two sticks public List findSuccessors() { LinkedList successors = new LinkedList(); if (remainder>=1) successors.add( new OneOrTwoState(remainder-1)); if (remainder>=2) successors.add( new OneOrTwoState(remainder-2)); return successors; } // a state is a goal state iff there are // no sticks remaining public boolean isGoal() { return remainder==0; } // if there are no elements left, // the current player loses public boolean findValue() { return false; } /** the printed representation of a state just says how many sticks remain */ public String toString() { return Integer.toString(remainder); } }