【问题标题】:Diagonal winner checking, tic tac toe对角线获胜者检查,井字游戏
【发布时间】:2018-10-09 15:57:31
【问题描述】:

我有这种方法可以在井字游戏中检查获胜者

public boolean hasWinner(Cell shape, int row, int col) {
    int count = 0;
    for(int i=0;i<WIDTH;i++){
        if(this.board[row][i]==shape){
            count++;
        }
        else{
            count=0;
        }
        if(count>=5){
            return true;
        }
    }
    count=0;
    for(int i=0;i<HEIGHT;i++){
        if(this.board[i][col]==shape){
            count++;
        }
        else{
            count=0;
        }
        if(count>=5){
            return true;
        }
    }

我已经编写了检查代码,如果在最后添加的符号的行和列上连续有 5 个相同的符号,现在我需要检查两个对角线,最后添加的符号位于哪个对角线上。有什么技巧吗,还是我必须写board[row+1][col+1]==shape &amp;&amp; board[row+2][col+2]==shape...之类的东西?

【问题讨论】:

  • 我不明白你的行和列参数应该做什么?
  • 它们是最后添加的十字或圆的坐标

标签: java matrix tic-tac-toe


【解决方案1】:

我现在无法真正为您编写解决方案,但我认为您是在询问这个循环:

        Cell shape = null;
        boolean win = true;

        for(int j=0, k = 0; j < WIDTH) {
            if(shape == null) {
                shape = this.board[j][k];
            } else {
                win = win && this.board[j][k] == shape;
            }

        }

它贯穿主对角线,所以你不需要手动写东西。然后你需要对第二条对角线做同样的事情

但老实说,如果我是你,并且我有 3 行或更少的行/列,我会按照你为可读性目的而建议的那样做

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多