java - 从返回枚举的接口(interface)检索数据

标签 java enums

我收到了一个使用枚举来解决的项目,但我有点卡住了。这是一款井字棋游戏,具有用于存储 3x3 网格表中单元格位置的枚举,以及用于存储单元格状态(空、X 或 O)的枚举。另外,我有一个返回 CellState 的 GameBoard 接口(interface):getCellState (CellLocation cellLocation);

我的任务只是编写Consultant接口(interface),我无法更改提供给我的代码中的任何内容。 在每一步之前,我都在努力检查Board的状态。

我的想法是 X 开始游戏,我使用 for 循环作为步骤,并在每个步骤中检查 if nrOfSteps%2==0。如果,我将 cellState 设置为玩家 O。检查我们是否处于获胜位置、是否获胜或是否平局。如果没有,我会建议采取行动。 例如

if (nrOfSteps%2!=0){
    cState =CellState.OCCUPIED_BY_X;
      if (isWon(cState, board)){
        throw new IllegalStateException("Player X won!");
      } else if (draw(board, locations)){
        throw new IllegalStateException("No more empty fields!");
      } else
        for (int remainingCells = 0; remainingCells <9; remainingCells++) {
            if (board.equals(locations[remainingCells]) && 
            cState==CellState.EMPTY){
            availableCells[index] = locations[remainingCells];
            index++;
        }
        CellLocation cellToTake = availableCells[(int)(Math.random()*
        (availableCells.length-1))];
        return cellToTake;
}

现在,我的问题是我已经为 isWon 方法尝试了以下方法(部分代码目前仅验证第一行):

private boolean isWon(CellState player, GameBoard board){
if (board.equals(CellLocation.TOP_LEFT) && cState==player &&
    board.equals(CellLocation.TOP_CENTRE) && cState==player && 
    board.equals(CellLocation.TOP_RIGHT) && cState==player){
  return true;
}

return false;
}

但是当我检查上面的代码时,我意识到板的当前状态不能只等于一个单元格。而且它显然不能等于 3 个不同的“只有一个单元格”。我什至不确定我是否可以通过以下方式检查棋盘上是否只有一个单元格被玩家 X 占据:

board.equals (CellLocation.TOP_LEFT) && cState==player

有人可以提供有关如何将 CellStateCellLocation 合并到一个查询中的提示吗?我应该使用数组吗?例如CellState[][]

最佳答案

您可以计算矩阵中单元格的总和(每列、行和对角线)。像这样:

import java.io.IOException;
import java.util.Arrays;
import java.util.Random;

public class CrossAndZeros {
    private static CellState winner;
    private static Enum[][] field = new Enum[3][3];

    public static void main(String[] args) throws IOException {

        for (int i = 0; i < field.length; i++) {
            for (int j = 0; j < field[i].length; j++) {
                field[i][j] = CellState.values()[new Random().nextInt(3)];
            }
        }

        for (Enum[] enums : field) {
            System.out.println(Arrays.toString(enums));
        }
        System.out.println();

        System.out.println("Winner is found: " + isWinnerFound());

        System.out.println(winner == null ? "No winner, GAME OVER" : winner);
    }

    private static boolean isWinnerFound() {
        int[] result = calculate();
        int count = 0;

        for (int win : result) {
            if (win == 3) {
                winner = CellState.OCCUPIED_BY_X;
                return true;
            } else if (win == -12) {
                winner = CellState.OCCUPIED_BY_O;
                return true;
            } else if (win == -9 || win == -2 || win == -3) { // This means that the line is spoilt
                count++;
            }
        }
        return count == 8; // If all the lines are spoilt, the game is over
    }

    private static int[] calculate() {
        int[] result = new int[8];

        for (int i = 0; i < field.length; i++) {
            for (int j = 0; j < field[i].length; j++) {
            result[i] += getCellOwner(field[j][i]); // a column
            result[i + 3] += getCellOwner(field[i][j]); // a row
        }
        result[field.length * 2] += getCellOwner(field[i][i]); // diagonal
        result[field.length * 2 + 1] += getCellOwner(field[i][field.length - i - 1]); // diagonal

        }

        System.out.println(Arrays.toString(result));

        return result;
    }

    private static int getCellOwner(Enum cell) {
        switch ((CellState) cell) {
            case OCCUPIED_BY_O:
                return -4;
            case OCCUPIED_BY_X:
                return 1;
            case EMPTY:
            default:
                return 0;
        }
    }

    public enum CellState {
        /**
         * this cell is occupied by player X
         */
        OCCUPIED_BY_X,

        /**
         * this cell is occupied by player O
         */
        OCCUPIED_BY_O,

        /**
         * this cell is Empty
         */
        EMPTY
    }
}

关于java - 从返回枚举的接口(interface)检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44230100/

相关文章:

c# - 什么是更好的 : an Enum or a singleton

Java 比较枚举器(奇怪的行为)

java - 听众如何工作

java - 如何模拟配置类进行测试

java - Eclipse IDE 搜索具有给定名称的函数

Swift 枚举,从关联的枚举中获取原始值

c# - MongoDb C# 驱动程序 - 将 List<enum> 序列化为字符串 []

java - 注释内的代码在 Unicode 序列之后执行

java - 如何将 Activity Intent 传递给另一个类?

java - 将斜杠添加到 Java 中的枚举