结构与 Swing 无关的生命游戏问题

Game of Life problems with structure not Swing related

我目前正在尝试开发一款生命游戏。我设法找到了几乎所有问题的解决方案,但我正在努力解决 "patterns"。几乎所有我尝试过的东西都不会提供像 "blinker" 这样的正确模式。我认为 GUI / Swing 可能是由于延迟导致错误模式的原因,但我不确定这一点,甚至不确定解决该问题的方法。

我将附上静态模式的屏幕截图和我当前的代码。任何建议表示赞赏。实施的策略接口仅提供一些整数(3 = MAX,2 = MIN)。让我自己使用界面。

GameOfLifeFrame

public class GameOfLifeFrame extends JFrame implements ActionListener{
    private GameOfLifeBoard gameBoard;
    private GameOfLifeInterface gameInterface;
    private JPanel btnPanel;
    private JPanel jPanel;
    private JMenuBar jMenuBar;
    private JMenu jMenu;
    private JButton btnStart;
    private JButton btnStop;

private JMenuItem jMenuItemStart;
private JMenuItem jMenuItemStop;
private JMenuItem jMenuItemReset;
private JMenuItem jMenuItemExit;
 * Constructor
 */
public GameOfLifeFrame(){
    initComponents();
}

private void initComponents(){
    gameBoard = new GameOfLifeBoard();
    gameInterface = new GameOfLifeInterface(gameBoard);
    add(gameInterface);

    btnPanel = new JPanel();
    jPanel = new JPanel();
    setJMenu();

    setButtons();

    setTitle("Game of Life");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationByPlatform(true);

    Dimension minDim = new Dimension(500,500);
    Dimension prefDim = new Dimension(500,500);
    setMinimumSize(minDim);
    setPreferredSize(prefDim);

    add(jMenuBar, BorderLayout.PAGE_START);
    add(jPanel, BorderLayout.NORTH);
    add(btnPanel, BorderLayout.SOUTH);

    pack();
    setVisible(true);
}

/**
 * private void setJMenu
 * Creates JMenu for GameOfLife Frame
 */
private void setJMenu(){
    jMenuBar = new JMenuBar();
    jMenu = new JMenu("Menü");
    jMenuItemStart = new JMenuItem("Start");
    jMenuItemStop = new JMenuItem("Stop");
    jMenuItemReset = new JMenuItem("Zurücksetzen");
    jMenuItemExit = new JMenuItem("Verlassen");

    //Menu ActionListener
    jMenuItemStart.addActionListener(this);
    jMenuItemStop.addActionListener(this);
    jMenuItemReset.addActionListener(this);
    jMenuItemExit.addActionListener(this);

    //Adding MenuItem to Menu & Menu to MenuBar
    jMenu.add(jMenuItemStart);
    jMenu.add(jMenuItemStop);
    jMenu.add(jMenuItemReset);
    jMenu.add(jMenuItemExit);
    jMenuBar.add(jMenu);
}

/**
 * actionPerformed
 * get Action on GUI. Reaction depends on Buttons.
 *
 * @param e ActionEvent
 */
@Override
public void actionPerformed(ActionEvent e){
    if(e.getSource() == jMenuItemStart){
        gameInterface.setActivity(true);
        if(btnStart.getText() == "Resume"){
            btnStart.setText("Start");
        }
    }
    else if(e.getSource() == jMenuItemStop){
        gameInterface.setActivity(false);
        if(btnStart.getText() == "Start"){
            btnStart.setText("Resume");
        }
    }
    else if(e.getSource() == jMenuItemReset){
        gameBoard.setGameBoard(gameBoard.clearGameBoard());
        if(!(btnStart.getText() == "Start")){
            btnStart.setText("Start");
        }
        gameBoard.randomize();
    }
    else if(e.getSource() == jMenuItemExit){
        System.exit(0);
    }
    else if(e.getSource() == btnStart){
        gameInterface.setActivity(true);
        if(btnStart.getText() == "Resume"){
            btnStart.setText("Start");
        }
    }
    else if(e.getSource() == btnStop){
        gameInterface.setActivity(false);
        btnStart.setText("Resume");
    }
}

/**
 * setButtons
 * sets Buttons Start and Stop and adds them to the Panel & ActionListener
 */
private void setButtons(){
    btnStart = new JButton("Start");
    btnStop = new JButton("Stop");
    btnPanel.add(btnStart);
    btnPanel.add(btnStop);
    btnStart.addActionListener(this);
    btnStop.addActionListener(this);
}

/**
 * Main Method, creates an instance of GameOfLifeFrame(GameOfLifeBoard)
 * @param args Main Method
 */
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new GameOfLifeFrame();
        }
    });
}

}

GameOfLifeBoard

public class GameOfLifeBoard implements Strategy {
    private boolean[][] gameBoard;

public GameOfLifeBoard() {
   this.gameBoard = new boolean[ROW][COL];
    for (int i = 0; i < gameBoard.length; i++) {
        for (int j = 0; j < gameBoard[i].length; j++) {
            gameBoard[i][j] = false;
        }
    }
}

/**
 * getGameBoard
 * @return gameBoard
 */
boolean[][] getGameBoard(){
    return gameBoard;
}

/**
 * setGameBoard
 * @param boolArray two-dimensional Array
 */
void setGameBoard(boolean[][] boolArray){
    for (int i = 0; i < boolArray.length; i++){
        for (int j = 0; j < boolArray[i].length; j++){
            gameBoard[i][j] = boolArray[i][j];
        }
    }
}

/**
 * clearGameBoard clears the current gameBoard by setting all boolean to false
 * @return clGameBoard returns a blank gameBoard
 */
boolean[][] clearGameBoard(){

    for (int i = 0; i < gameBoard.length; i++) {
        for (int j = 0; j < gameBoard[i].length; j++) {
            gameBoard[i][j] = false;
        }
    }
    return gameBoard;
}

/**
 * nextGeneration calculates the new Generation (gameBoard)
 * using the static variables 3 and 2 (MAX and MIN) from Strategy (interface)
 * by applying the rules from Strategy
 *
 * nextGeneration uses a temporary 2D boolean Array to replace the old Generation with the new Generation
 * by looping through the current gameBoard and replacing each cell with the new status of the cell
 * in the new generation
 */
void nextGeneration(){
    boolean[][] newGen = new boolean[ROW][COL];;

    for (int i = 0; i < gameBoard.length; i++) {
        for (int j = 0; j < gameBoard[i].length; j++) {

            newGen[i][j] = gameBoard[i][j];

            switch (getAliveNeighbourCells(i,j)){
                case MAX:
                    if(getCellState(i,j)){
                        newGen[i][j] = true;
                    }
                    else if(!getCellState(i,j)){
                        newGen[i][j] = true;
                    }
                    break;
                case MIN:
                    if(getCellState(i,j)){
                        newGen[i][j] = true;
                    }
                    else if(!getCellState(i,j)){
                        newGen[i][j] = false;
                    }
                    break;
                default:
                    newGen[i][j] = false;
                    break;
            }
        }
    }
    for (int i = 0; i < gameBoard.length; i++) {
        for (int j = 0; j < gameBoard[i].length; j++) {
            gameBoard[i][j] = newGen[i][j];
        }
    }

}

/**
 * randomize randomizes each cell on the gameBoard by setting it to true or false (25% true)
 */
void randomize(){
    for(int i = 0; i < gameBoard.length; i++){
        for(int j = 0; j < gameBoard[i].length; j++){
            double d = Math.random();
            if(d <= 0.25){
                gameBoard[i][j] = true;
            }
            else{
                gameBoard[i][j] = false;
            }
        }
    }
}

/**
 * getNeighbourCells, counts the surrounding cells next to the current cell
 * @param x delivers position of current cell
 * @param y delivers position of current cell
 * @return counter-1, because the loops count the current cell itself
 */

private int getAliveNeighbourCells(int x, int y) {
    int counter = 0;
    for (int i = x-1; i <= x + 1; i++) {
        for (int j = y-1; j <= y + 1; j++) {
            if(i >= 0 && i < gameBoard.length-1 && j >= 0 && j < gameBoard[i].length-1){
                if(gameBoard[i][j]){
                    counter++;
                }
            }
        }
    }
    return counter;
}

/**
 * getCellState returns CellState of a specific cell on the gameBoard
 * @param i delivers position of current cell
 * @param j delivers position of current cell
 * @return gameBoard[i][j] returns current CellState on gameBoard at position [i][j]
 */
@Override
public boolean getCellState(int i, int j) {
    return gameBoard[i][j];
}

GameOfLifeInterface

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class GameOfLifeInterface extends JPanel implements ActionListener{
private Timer time = new Timer(150, this);
private GameOfLifeBoard gameBoard;
private boolean isActive;

/**
 * GameOfLifeInterface randomizes the gameBoard
 * @param gameBoard gets randomized by GameOfLifeBoard.randomize
 */
public GameOfLifeInterface(GameOfLifeBoard gameBoard){
    this.gameBoard = gameBoard;
    gameBoard.randomize();
}

/**
 * paintComponent draws the current Generation (Dead Cell will be painted in white, Alive Cell in Black)
 * and restarts or stops the Timer time
 * @param graph Graphics
 */

public void paintComponent(Graphics graph){
    super.paintComponent(graph);
    int iBox = 2;
    for (int i = 0; i < gameBoard.getGameBoard().length; i++) {
        for (int j = 0; j < gameBoard.getGameBoard()[i].length; j++) {
            graph.setColor(!gameBoard.getGameBoard()[i][j]? Color.WHITE : Color.BLACK);
            graph.fillRect(i * iBox, j * iBox, iBox, iBox);
        }
    }
    if(isActive){
        time.restart();
    }
    else{
        time.stop();
        repaint();
    }
}

/**
 * setActivity sets private boolean: true or false
 * @param activity boolean stores decision of User (Buttons: Stop / Start)
 */
public void setActivity(boolean activity){
    isActive = activity;
}

/**
 * actionPerformed if Timer time has past, the current Generation will be replaced with the new Generation
 * GameBoard gets repainted to show the new Generation
 * @param e ActionEvent
 */
@Override
public void actionPerformed(ActionEvent e) {
    if(e.getSource().equals(time)){
        gameBoard.nextGeneration();
        repaint();
    }
}

接口策略

public interface Strategy {
int ROW = 500;
int COL = 500;
int MIN = 2;
int MAX = 3;

boolean getCellState(int i, int j);

}

你的getAliveNeighborCells方法是错误的。它计算中心单元格的值,而它应该只计算周围的单元格。

因此您的代码将检查以下模式:

XXX
XXX
XXX

什么时候应该只计算这些细胞:

XXX
X X
XXX

最简单的解决方案就是将条件 (i != x || j != y) 添加到您的 if 语句中,如下所示:

if(gameBoard[i][j] && (i != x || j != y)){ //...

你的代码中可能还有其他错误,但是你遗漏了很多重要的部分,所以我无法编译和测试它。

这里有一些 improve/correct 您的代码的建议:

与其像普通组件一样添加 JMenuBar,不如使用 setJMenuBar 方法,该方法明确用于该目的。

这更像是一种风格决定,但我会将您的 setJMenu 方法更改为 getJMenuBar 方法,return 是一个新的 JMenuBar 方法,并且调用者将其分配给该字段。与此有点相关,我还建议在初始化后制作任何不应更改的字段 final.

在您的 actionPerformed 方法中,您使用 == 比较 Strings。那是一个 bad idea,在这种情况下它在技术上是有效的,但几乎肯定会在某些时候意外地失败。您应该将 Strings 与 equals 进行比较。

GameOfLifeBoard 中,我建议删除 getGameBoard 方法并将其替换为访问器方法以获得必要的信息。我推荐的方法是 bool getBoardItem(int row, int col)getCellState 已经涵盖了这个方法)、int getBoardRows()int getBoardColumns(int row)。这些会让您获得相同的信息,但不会让调用者修改面板,这让您可以更好地控制它的状态。

nextGeneration 中,您手动将 newGen 中的每个字段复制到 gameBoard 中。这行得通,但是使用 gameBoard = newBoard.

更新参考会更快

Strategy 中定义 ROWCOL 似乎不必要地将您锁定在一种尺寸上。您可以将其替换为 int getRowSize()int getColSize() 的方法声明,并让实现 return 您想要的值。这将使不同的实现可以使用他们想要的任何大小。

我认为这些是可能的改进。