001    /*
002     * Created on Sep 12, 2004
003     *
004     */
005    package aima.search.eightpuzzle;
006    
007    import java.util.ArrayList;
008    import java.util.List;
009    
010    import aima.search.framework.Successor;
011    import aima.search.framework.SuccessorFunction;
012    
013    /**
014     * @author Ravi Mohan
015     * 
016     */
017    
018    public class EightPuzzleSuccessorFunction implements SuccessorFunction {
019    
020            public List getSuccessors(Object state) {
021                    EightPuzzleBoard board = (EightPuzzleBoard) state;
022                    List<Successor> successors = new ArrayList<Successor>();
023                    if (board.canMoveGap(EightPuzzleBoard.UP)) {
024                            EightPuzzleBoard newBoard = copyOf(board);
025                            newBoard.moveGapUp();
026                            successors.add(new Successor(EightPuzzleBoard.UP, newBoard));
027                    }
028                    if (board.canMoveGap(EightPuzzleBoard.DOWN)) {
029                            EightPuzzleBoard newBoard = copyOf(board);
030                            newBoard.moveGapDown();
031                            successors.add(new Successor(EightPuzzleBoard.DOWN, newBoard));
032                    }
033                    if (board.canMoveGap(EightPuzzleBoard.LEFT)) {
034                            EightPuzzleBoard newBoard = copyOf(board);
035                            newBoard.moveGapLeft();
036                            successors.add(new Successor(EightPuzzleBoard.LEFT, newBoard));
037                    }
038                    if (board.canMoveGap(EightPuzzleBoard.RIGHT)) {
039                            EightPuzzleBoard newBoard = copyOf(board);
040                            newBoard.moveGapRight();
041                            successors.add(new Successor(EightPuzzleBoard.RIGHT, newBoard));
042                    }
043                    return successors;
044            }
045    
046            private EightPuzzleBoard copyOf(EightPuzzleBoard board) {
047                    EightPuzzleBoard newBoard = new EightPuzzleBoard();
048                    newBoard.setBoard(board.getPositions());
049                    return newBoard;
050            }
051    
052    }