Here is my code so far, how would I code a checkWin function that will determine the winner of the tic tac toe game?

6 次查看(过去 30 天)
clear all; clc;
bd = initBoard(3)
win = false;
while win == false
% player 1 plays
r = input('player 1 row ');
c = input('player 1 col ');
bd = updateBoard(bd, r, c, 1);
win = checkWin(bd)
% player 2 plays
r = input('player 2 row ');
c = input('player 2 col ');
bd = updateBoard(bd, r, c, 2);
win = checkWin(bd)

回答(1 个)

Rollin Baker
Rollin Baker 2017-4-13
Hi Sterling,
You didn't specify exactly how you were modeling your tic-tac-toe board, but I'm going to assume you are storing it as a 3x3 array. If you aren't doing this, it may be a good idea to see if the way you are representing the board makes sense.
To determine how a 'CheckWin' function should work, just think about what you are actually checking for: a player wins the game when they have three spaces in a row marked with either an X or an O. So your solution should probably involve searching through the indices of your stored matrix.
There are a few ways to do this. One way could involve exhaustively searching every possible winning path. There are only 8 possible ways to win, so while this might not be the most clever solution, it should not be too expensive to check them all.
Additionally, the way your code is set up, it won't be able to tell who actually won the game. Your 'CheckWin' function either needs to return an extra variable indicating which player won, or you will have to maintain two variables outside of the function as the condition for the while loop (For example, have a 'player1Win' and 'player2Win' variable instead of just 'win').
I hope this able to get you going in the right direction. Good luck on your project!
-Rollin
  2 个评论
Rik
Rik 2017-4-13
win may be encoded as 0 for no win, 1 for player 1 wins and 2 for player 2 wins, that what I assumed. (and it would work with this code)
Guillaume
Guillaume 2017-4-13
编辑:Guillaume 2017-4-13
Actually, checkWin does not even need to tell you who won, since it carries out a check after each player's move. If nobody had won before and checkWin now says that somebody won, then clearly it's the current player who won.
A logical response would be enough.
Anyway, Rollin Baker, is right, it's dead easy to check who wins. Just check the 3 rows, 3 columns and two diagonals for 3 identical values (e.g. are all the values the same as the first one?). The all, any, diag and fliplr functions may be useful here.
Can be done in just one (longish) line of code. Easier if you use NaN for empty spaces.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by