tic-tac-toe game in matlab

To program a Tic-Tac-Toe game in MATLAB, you can follow these steps:

  1. Create a 3x3 matrix to represent the game board:
    main.m
    board = zeros(3,3);
    
    20 chars
    2 lines
  2. Create a loop that alternates between players, and prompts each player for their move. One way to do this would be to use a mod operator to determine which player's turn it is (player 1 plays on odd-numbered moves, player 2 plays on even-numbered moves). For example:
    main.m
    player = 1;
    for move_num = 1:9
        % Prompt player for input
        fprintf('Player %d, enter your move (row, column): ', player);
        move = input('');
    
        % Update the board with the player's move 
        board(move(1), move(2)) = player;
    
        % Check for win condition
        if check_win(board, player)
            fprintf('Player %d wins!\n', player);
            break;
        end
    
        % Switch to the other player
        player = mod(player, 2) + 1;
    end
    
    439 chars
    19 lines
  3. Define a function to check for win conditions:
    main.m
    function win = check_win(board, player)
        % Check for vertically-aligned pieces
        win = any(all(board == player, 1));
    
        % Check for horizontally-aligned pieces
        win = win || any(all(board == player, 2));
    
        % Check for diagonally-aligned pieces
        diagonal1 = diag(board);
        diagonal2 = diag(fliplr(board));
        win = win || all(diagonal1 == player) || all(diagonal2 == player);
    end
    
    398 chars
    13 lines

This function checks for any rows, columns, or diagonals where all of the pieces belong to the same player.

  1. At the end of the loop, if nobody has won, print a message indicating the game ended in a tie:
    main.m
    if move_num == 9
        fprintf('Game over - tie game!\n');
    end
    
    61 chars
    4 lines

This is just one possible implementation of the game - there are many other ways to do it.

gistlibby LogSnag