Determining a winner in Tic Tac Toe using if statements
8 ビュー (過去 30 日間)
古いコメントを表示
I'm writing a program to play tic-tac-toe in Matlab.
I'm having trouble in coding how to determine a winner using if statements.
So far, this is my function:
function won = Winner(board, player)
if board(1,1) == 'X' &&
Any help will be much appreciated
0 件のコメント
回答 (2 件)
Adam
2014 年 11 月 21 日
編集済み: Adam
2014 年 11 月 21 日
Your function doesn't give any validation of 'board' and what format it is supposed to be in.
If this is just the background representation of the game rather than what is presented to the user a numeric 3*3 matrix with 1s and 0s representing the two players and NaNs for unused squares would make the task trivial.
Dealing with strings adds an un-necessary complexity unless you are forced to do that, in which case my first step would probably be to convert that into 1s and 0s.
Then you can just sum the columns, rows and leading and reverse-leading diagonals - if the answer to any is 0 or 3 then you declare the winner to be player 0 or 1.
Of course your function may get given an illegal board position, but that is a whole other matter that you haven't gone into so I am assuming that only legal board positions will be given to the function.
1 件のコメント
Adam
2014 年 11 月 21 日
編集済み: Adam
2014 年 11 月 21 日
board = [ ['X', ' ', 'O']; ['X', 'O', 'O']; ['X', 'X', ' '] ];
myBoard = nan(3);
myBoard( board == 'X' ) = 1;
myBoard( board == 'O' ) = 0;
for example, is what I would do with a board of chars!
Then both determining the winner and whether or not the game is over are trivial.
It can be done working with chars of course, but I hate working with chars if I don't have to.
Kyle
2014 年 11 月 21 日
1 件のコメント
Muzammil Aslam
2019 年 5 月 7 日
Can i get a code for human against human instead of human against computer...?
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!