write a matlab program that allows a user to play the 15-puzzle in matlab

Here's an example of a MATLAB program that allows a user to play the 15-puzzle. It uses a 4 by 4 matrix to represent the puzzle, where 0 represents the blank square.

main.m
% Initialize the 15-puzzle array
puzzle = [10, 9, 11, 13; 6, 0, 14, 12; 7, 5, 15, 1; 3, 2, 8, 4];

while ~isequal(puzzle, [1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,0])
    % Print the current state of the puzzle
    disp(puzzle)
    
    % Ask the user which direction to move the blank square
    direction = input('Which direction to move (up = 1, down = 2, left = 3, right = 4)? ');
    
    % Find the row and column of the blank square
    [row, col] = find(puzzle == 0);
    
    % Move the blank square in the selected direction (if possible)
    if direction == 1 && row > 1
        puzzle(row, col) = puzzle(row-1, col);
        puzzle(row-1, col) = 0;
    elseif direction == 2 && row < 4
        puzzle(row, col) = puzzle(row+1, col);
        puzzle(row+1, col) = 0;
    elseif direction == 3 && col > 1
        puzzle(row, col) = puzzle(row, col-1);
        puzzle(row, col-1) = 0;
    elseif direction == 4 && col < 4
        puzzle(row, col) = puzzle(row, col+1);
        puzzle(row, col+1) = 0;
    end
end

% Print the final state of the puzzle
disp(puzzle)
disp('Congratulations! You solved the puzzle.')
1117 chars
33 lines

The program uses a while loop to repeatedly ask the user for moves until the puzzle is solved. The direction to move the blank square is entered by the user, and the puzzle is updated accordingly. When the puzzle is solved, a congratulatory message is displayed.

related categories

gistlibby LogSnag