Here is my code so far, how would I code a checkWin function that will determine the winner of the tic tac toe game?
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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)
Réponses (1)
Rollin Baker
le 13 Avr 2017
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 commentaires
Rik
le 13 Avr 2017
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
le 13 Avr 2017
Modifié(e) : Guillaume
le 13 Avr 2017
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.
Voir également
Catégories
En savoir plus sur Startup and Shutdown dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!