I wrote a tic-tac-toe game in matlab, but it does not work:
%// 1) Commence the game, display empty board board=cell(3); %// 2) Select which player is ?X? and ?O? (at random) playersymbols={'X','O'}; playersymbolindex=randperm(2); for i=1:2 player(i).symbol=playersymbols{playersymbolindex(i)}; end winner=0; while winner<1 %// 3) Request player1?s move player1move=input('Player 1, please enter your move: '); %// the input is something like [1 3] where the first number is the %// row number and the second number is column number so that [1 3] will %// put X in row 1, column 3. %// Redraw updated board. board{player1move(1),player1move(2)}=player(1).symbol; board %// 5) Decision: has the game been won yet? If so, go to step 9). %// If not, go to step 6). %// The game is won when three respective X are placed in a horizontal, %// vertical, or diagonal row. if board{1,1}==board{1,2} & board {1,2}==board{1,3} | ... board{2,1}==board{2,2} & board{2,2}==board{2,3} | ... board{3,1}==board{3,2} & board{3,2}==board{3,3} | ... board{1,1}==board{2,1} & board{2,1}==board{3,1} | ... board{1,2}==board{2,2} & board{2,2}==board{3,2} | ... board{1,3}==board{2,3} & board{2,3}==board{3,3} | ... board{1,1}==board{2,2} & board{2,2}==board{3,3} | ... board{1,3}==board{2,2} & board{2,2}==board{3,1} %// 9) Display winner on the screen. disp('Winner is player 1!') winner=1; else %// 6) Request player2?s move player2move=input('Player 2, please enter your move: '); %// 7) Input Player2?s move. Redraw updated board. board{player2move(1),player2move(2)}=player(2).symbol; board %// 8) Decision: has the game been won yet? If so, go to step 9). %// If not, go back to step 3). if board{1,1}==board{1,2} & board {1,2}==board{1,3} | ... board{2,1}==board{2,2} & board{2,2}==board{2,3} | ... board{3,1}==board{3,2} & board{3,2}==board{3,3} | ... board{1,1}==board{2,1} & board{2,1}==board{3,1} | ... board{1,2}==board{2,2} & board{2,2}==board{3,2} | ... board{1,3}==board{2,3} & board{2,3}==board{3,3} | ... board{1,1}==board{2,2} & board{2,2}==board{3,3} | ... board{1,3}==board{2,2} & board{2,2}==board{3,1} %// 9) Display winner on the screen. disp('Winner is player 2!') winner=1; end end end
I tried very hard to understand what I was doing wrong, but after 4 hours I did not know what I was doing wrong. Can someone please help me? What am I doing wrong?
EDIT: Player 1 is fine, so the problem is with player 2. When player 2 wins, my program does not show that βplayer 2 won the gameβ and incorrectly asks player 1 the next move (until the game is already finished).