栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

测试tic tac toe获胜条件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

测试tic tac toe获胜条件

这有点冗长,但是我认为这可能是最有效的方法(除非有人可以提出一种巧妙的方法来一次检查两个对角线)。

public class TicTacToe{    char[][] ticTacToe =     {{'X',' ','O'},     {'O','X','O'},     {'X',' ','X'},};    private Character winner = null;    public Character getWinner()    {        return this.winner;    }    public boolean isSolved()    {        this.checkSolved();        return this.winner != null;    }    private void checkSolved()    {        for(int i = 0; i < ticTacToe.length; i++)        { Character win = checkRow(i); if(win != null || (win = checkColumn(i)) != null) {     this.winner = win;     return; }        }        //Check diagonal top left to bottom right        if(this.ticTacToe[0][0] != ' ')        { if(this.ticTacToe[0][0] == this.ticTacToe[1][1] &&    this.ticTacToe[1][1] == this.ticTacToe[2][2]) {     this.winner = this.ticTacToe[0][0]; }        }        //Check diagonal top right to bottom left        else if(this.ticTacToe[0][2] != ' ')        { if(this.ticTacToe[0][2] == this.ticTacToe[1][1] &&    this.ticTacToe[1][1] == this.ticTacToe[2][0]) {     this.winner = this.ticTacToe[0][2]; }        }    }    private Character checkRow(int row)    {        if(this.ticTacToe[row][0] == ' ')        { return null;        }        if(this.ticTacToe[row][0] == this.ticTacToe[row][1] &&this.ticTacToe[row][1] == this.ticTacToe[row][2])        { return this.ticTacToe[row][0];        }        return null;    }    private Character checkColumn(int column)    {        if(this.ticTacToe[0][column] == ' ')        { return null;        }        if(this.ticTacToe[0][column] == this.ticTacToe[1][column] &&this.ticTacToe[1][column] == this.ticTacToe[2][column])        { return this.ticTacToe[column][0];        }        return null;    }    public static void main(String[] args)    {        TicTacToe ttt = new TicTacToe();        if(ttt.isSolved())        { System.out.println(ttt.getWinner());  // X        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/469317.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号