Here is an example function that displays a GUI for playing tic-tac-toe when a button is clicked. The GUI is constructed using MATLAB's uicontrol()
function to create buttons and axes for displaying the current state of the game.
function play_tic_tac_toe()
% Create a grid of buttons for playing the game
grid_size = 3;
button_size = 50;
button_spacing = 10;
axis_width = (grid_size * button_size) + ((grid_size + 1) * button_spacing);
axis_height = (grid_size * button_size) + ((grid_size + 1) * button_spacing);
button_handles = zeros(grid_size, grid_size);
for row = 1:grid_size
for col = 1:grid_size
button_x = ((col - 1) * (button_size + button_spacing)) + button_spacing;
button_y = ((grid_size - row) * (button_size + button_spacing)) + button_spacing;
button_handles(row, col) = uicontrol('Style', 'pushbutton', ...
'String', '', ...
'Units', 'pixels', ...
'Position', [button_x, button_y, button_size, button_size], ...
'Callback', {@button_callback, row, col});
end
end
% Create an axis for displaying the current state of the game
axis_handle = axes('Units', 'pixels', ...
'XLim', [0, axis_width], ...
'YLim', [0, axis_height], ...
'Visible', 'off');
text_handle = text('Position', [axis_width/2, axis_height-20], ...
'FontSize', 20, ...
'HorizontalAlignment', 'center');
% Initialize the game state
game_state = zeros(grid_size);
turn = 1;
% Define the button callback function
function button_callback(source, event, row, col)
% Check if the button has already been clicked
if game_state(row, col) ~= 0
return;
end
% Update the game state
game_state(row, col) = turn;
if turn == 1
set(button_handles(row, col), 'String', 'X', 'FontSize', 20);
elseif turn == 2
set(button_handles(row, col), 'String', 'O', 'FontSize', 20);
end
% Check for a winner
winner = check_for_winner(game_state);
if winner ~= 0
set(text_handle, 'String', ['Player ', num2str(winner), ' wins!']);
set(button_handles(:), 'Enable', 'off');
return;
end
% Check for a tie
if all(game_state(:) ~= 0)
set(text_handle, 'String', 'Tie game!');
set(button_handles(:), 'Enable', 'off');
return;
end
% Switch to the next player
turn = mod(turn, 2) + 1;
set(text_handle, 'String', ['Player ', num2str(turn), '''s turn']);
end
% Define the function for checking for a winner
function winner = check_for_winner(game_state)
winner = 0;
for row = 1:grid_size
if all(game_state(row, :) == 1)
winner = 1;
break;
elseif all(game_state(row, :) == 2)
winner = 2;
break;
end
end
if winner ~= 0
return;
end
for col = 1:grid_size
if all(game_state(:, col) == 1)
winner = 1;
break;
elseif all(game_state(:, col) == 2)
winner = 2;
break;
end
end
if winner ~= 0
return;
end
if all(diag(game_state) == 1)
winner = 1;
return;
elseif all(diag(game_state) == 2)
winner = 2;
return;
end
if all(diag(fliplr(game_state)) == 1)
winner = 1;
return;
elseif all(diag(fliplr(game_state)) == 2)
winner = 2;
return;
end
end
end