using System; /** SlidePuzzle implements a slide-puzzle game. * assumed input: a series of integers between 1 and 15, which indicate the * pieces to move in the slide puzzle * guaranteed output: the slide puzzle, as it appears after each move */ public class SlidePuzzle { public static void Main() { int PUZZLE_SIZE = 4; // how large we make the puzzle // the puzzle, where 0 marks the empty space: int[,] puzzle = { {15, 14, 13, 12}, // use braces to {11, 10, 9, 8}, // initialize an array { 7, 6, 5, 4}, { 3, 2, 1, 0} }; // Or, build the puzzle like this: // int[,] puzzle = new int[PUZZLE_SIZE,PUZZLE_SIZE]; int empty_x = 3; int empty_y = 3; // the x,y-coordinates of the empty space while (true) { // use nested for-loops to print the puzzle: for ( int i = 0; i != PUZZLE_SIZE; i = i + 1 ) { for ( int j = 0; j != PUZZLE_SIZE; j = j + 1 ) { int number = puzzle[i,j]; if (number < 10) { Console.Write(" "); } Console.Write( puzzle[i,j]); Console.Write(" "); } Console.WriteLine(); } // ask for the next move: Console.Write("Type number of piece to move : "); int num = Int32.Parse(Console.ReadLine()); // search the puzzle for the piece numbered num: int found_x = -1; int found_y = -1; for ( int i = 0; i != PUZZLE_SIZE; i = i + 1 ) { for ( int j = 0; j != PUZZLE_SIZE; j = j + 1 ) { if ( num == puzzle[i,j] ) { found_x = i; found_y = j; } } } // The previous loops are finished; did we find the piece ? if ( found_x == -1 ) { Console.WriteLine("illegal move --- try again"); } else // We did find it, so let's try to move it: { // First, check if the piece is adjacent to the empty space if ( ((empty_x == found_x-1) && (empty_y == found_y)) || ((empty_x == found_x+1) && (empty_y == found_y)) || ((empty_x == found_x) && (empty_y == found_y-1)) || ((empty_x == found_x) && (empty_y == found_y+1)) ) // If true, it's ok to move num into the empty space: { puzzle[empty_x,empty_y] = num; puzzle[found_x,found_y] = 0; empty_x = found_x; empty_y = found_y; } else { Console.WriteLine("illegal move --- try again"); } } } // end while-loop } }