gpt4 book ai didi

matlab - 我的 tic-tac-toe 程序在 matlab 中不起作用

转载 作者:行者123 更新时间:2023-12-02 02:22:33 25 4
gpt4 key购买 nike

我在 matlab 中编写了一个井字棋游戏,但它不起作用:

%// 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

我非常努力地试图理解我做错了什么,但 4 小时后,我不知道我做错了什么。有人可以帮我吗?我做错了什么?

编辑: 玩家 1 没问题,所以问题出在玩家 2 身上。当玩家 2 获胜时,我的程序不会显示“玩家 2 赢得了比赛”,而是错误地要求玩家 1 接下来移动(当游戏已经完成时)。

最佳答案

我发现了问题。

当您将字符串与 == 进行比较时而不是 strcmp ,当存在空字符串时,比较返回 [] 。因此逻辑运算符 TRUE | []返回[]这是不正确的。

在您发布的示例中 ([1 1], [1 2], [2 1], [2 2], [1 3], [3 2]) if 的最后一行返回[]

board{1,3}==board{2,2} & board{2,2}==board{3,1}

看起来如果你用 && 替换你的逻辑运算符和||你可以解决这个问题。

关于matlab - 我的 tic-tac-toe 程序在 matlab 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30047471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com