Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Use a 6x6 numeric array to represent the game board, zero to indicate an empty position, 1 to indicate black and -1 to indicate white. A board is then initialized by:</p> <pre> >> board = zeros(6, 6) board = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 </pre> <p>To check for a winning board use <a href="http://www.mathworks.com/help/techdoc/ref/sum.html" rel="nofollow">SUM</a> which operates on the board array columns. Subtracting the <a href="http://www.mathworks.com/help/techdoc/ref/min.html" rel="nofollow">MIN</a> of the column will resolve the case where the column contains pieces from both players. Use the dimension argument of the SUM and MIN functions to perform the same check on the rows. Create an array of the three candidate diagonals using <a href="http://www.mathworks.com/help/techdoc/ref/diag.html" rel="nofollow">DIAG</a> and pad the two shorter diagonals with zeros. Perform the same check on the columns of this array.</p> <pre><code>function result = checkBoard(board) result = 'No winner'; diagonals = [diag(board, 0) [diag(board, 1); 0] [diag(board, -1); 0]]; if any(sum(board) - min(board) == 5) ... || any(sum(board, 2) - min(board, [], 2) == 5) ... || any(sum(diagonals) - min(diagonals) == 5) result = 'Black wins!'; elseif any(sum(-board) - min(-board) == 5) ... || any(sum(-board, 2) - min(-board, [], 2) == 5) ... || any(sum(-diagonals) - min(-diagonals) == 5) result = 'White wins!'; end </code></pre> <p>You can now check the board with a call to <code>checkBoard</code>:</p> <pre> >> x = [-1 0 0 0 0 0; -1 0 0 0 0 0; -1 0 0 0 0 0; -1 0 0 0 0 0; -1 0 0 0 0 0; 0 0 0 0 0 0] x = -1 0 0 0 0 0 -1 0 0 0 0 0 -1 0 0 0 0 0 -1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 >> checkBoard(x) ans = White wins! >> x = [-1 0 0 0 0 0; -1 0 0 0 0 0; -1 0 0 0 0 0; -1 0 0 0 0 0; -1 0 0 0 0 0; 1 0 0 0 0 0] x = -1 0 0 0 0 0 -1 0 0 0 0 0 -1 0 0 0 0 0 -1 0 0 0 0 0 -1 0 0 0 0 0 1 0 0 0 0 0 >> checkBoard(x) ans = White wins! >> x = [1 1 1 1 1 0; 0 0 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0; 0 0 0 0 0 0] x = 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 >> checkBoard(x) ans = Black wins! >> x = [1 0 0 0 0 0; 0 1 0 0 0 0; 0 0 1 0 0 0; 0 0 0 1 0 0; 0 0 0 0 1 0; 0 0 0 0 0 0] x = 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 >> checkBoard(x) ans = Black wins! </pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload