首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Tac-Tac-Toe Win检查功能

Tac-Tac-Toe Win检查功能
EN

Stack Overflow用户
提问于 2015-10-02 21:38:33
回答 1查看 866关注 0票数 1

我正在写一个tic tac toe游戏,“编码规则”的一部分是应该有一个“checkwin”函数来查看玩家是否赢了。我定义了两个名为'tttXArray‘和'tttOArray’的变量,来查看一个玩家是否已经连续三次输入水平、垂直或对角线。

代码语言:javascript
复制
function [won] = checkwin
%Check to see whether the game has been won or not
% Horizontal
    if (tttXArray(1,1) == tttXArray(1,2) && tttXArray(1,1) == tttXArray(1,3))
        won = 1;
    elseif (tttXArray(2,1) == tttXArray(2,2) && tttXArray(2,1) == tttXArray(2,3))
        won = 1;
    elseif (tttXArray(3,1) == tttXArray(3,2) && tttXArray(3,1) == tttXArray(3,3))
        won = 1;
    % Vertical
    elseif (tttXArray(1,1) == tttXArray(2,1) && tttXArray(1,1) == tttXArray(3,1)) 
        won = 1;
    elseif (tttXArray(1,2) == tttXArray(2,2) && tttXArray(1,2) == tttXArray(3,2)) 
        won = 1;
    elseif (tttXArray(1,3) == tttXArray(2,3) && tttXArray(1,3) == tttXArray(3,3)) 
        won = 1;
    % Diagonal
    elseif (tttXArray(1,1) == tttXArray(2,2) && tttXArray(1,1) == tttXArray(3,3))
        won = 1;
    elseif (tttXArray(1,3) == tttXArray(2,2) && tttXArray(1,3) == tttXArray(3,1))
        won = 1;
    end
end

Checkwin是while循环的一部分:

代码语言:javascript
复制
while ~checkwin

    playerXTurn = 1;
    playerOTurn = 1;
    %Let Player X go first
    while playerXTurn
        pickXSpot %Prompt  Player
        disp('Test1')
        checktaken %Check taken location
        %If place is taken, prompt player to input again
        if checktaken == 1
            pickXspot
        else
            tttArray(pXInputRow, pXInputCol) = 1; %Set the position as taken
            tttXOArray(pXInputRow, pXInputCol) = 1; %Set the position for X(1)
            plot(pXInputRow, pXInputCol, 'x')
            hold on
            playerXTurn = 0;
        end
    end

    %Check if theres a win
    checkwin

    %Otherwise continue to Player O's turn
    while playerOTurn == 1
        pickOSpot %Prompt Player
        checktaken
        %If place is taken, prompt player to input again
        if checktaken == 1
            pickOspot
        else
            tttArray(pOInputRow, pOInputCol) = 1;%Set the position as taken
            tttXOArray(pOInputRow, pOInputCol) = 0;%Set the position for O(0)
            plot(pOInputRow, pOInputCol,'o')
            hold on
        end
    end  

    %Check win again
    checkwin
end

我得到的错误是:

代码语言:javascript
复制
Undefined function 'tttXArray' for input arguments of type 'double'.

什么地方出问题了?

EN

回答 1

Stack Overflow用户

发布于 2015-10-04 07:00:43

所以我意识到我没有正确地调用函数,也没有给它任何参数。这就是我现在要做的

代码语言:javascript
复制
function [won] = checkwin(tttXArray)

我还将所有if/else语句简化如下:

won = any(all(tttXArray) | all(tttXArray, 2)' | all(diag(tttXArray)) | all(fliplr(diag(tttXArray))));

谢谢你的建议!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32908455

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档