Darshan Nayak

Full Stack Developer

8-Puzzle Solver

Languages/Libraries: Java

This application implemented the STRIPS planning system, which is based on Predicate Logic, to solve the 8-puzzle problem. Success rate and execution speed depended on the complexity of the initial state of the 8-puzzle game, owing to limits on system resources. This was an assignment for CS 820 (Artificial Intelligence) at University of Regina.

Main.java

Following code snippet shows how the program decides on making a move.

						
//FUNCTION SNIPPET; NOT THE WHOLE CODE OF THE FUNCTION
public static void continuePlay(int currentState[][],int previousState[][]) //this function implements the logic for playing the game
{
	currentLocation = locateZero(currentState);         //locate the position of 0 in 2D array of current state
	previousLocation = locateZero(previousState);       //locate the position of 0 in 2D array of previous state
	
	//now, we will decide where to move, preferring the order--> up,right,down,left; whichever is possible first
	//for example, if up is possible, then go up, else if right is possible, go right, else if....
	String nextMove = "";                               //keeps a track of direction of moving 0 in the current move
	if (currentLocation.i != 0 &&  !("down".equals(previousMove)))//will evaluate true if up is possible and last move was not downwards
	{
		nextMove = "up";
	} else if (currentLocation.j != 2 && !("left".equals(previousMove)))//will evaluate true if right is possible and last move was not towards left
	{
		nextMove = "right";
	} else if (currentLocation.i != 2 && !("up".equals(previousMove)))//will evaluate true if down is possible and last move was not upwards
	{
		nextMove = "down";
	} else if (currentLocation.j != 0 && !("right".equals(previousMove)))//will evaluate true if left is possible and last move was not towards right
	{
		nextMove = "left";
	}
	
	//until now, we have decided what move to make. Now, we will make the move (based on the direction we decided in the above code)
	switch (nextMove)
	{
		case "up":
			goUp(currentState);                                         //swap the 0 with tile above it
			if (Arrays.deepEquals(previousState, currentState))			//check if the move caused the game to go to previous state
			{       
				goDown(currentState);                                   //if game went to previous state, revert, and go to next case of switch(), using fallthrough
			}
			else
			{
				previousMove = nextMove;                                //store move direction for use in next iteration
				printState(currentState);                               //print the game state. This process repeats in the following code for moves in other 3 directions
				actionSequence+="Up\n";
				break;
			}
	}
                    
}