简体   繁体   English

使用Swing的Java生活游戏

[英]Java Game of Life using Swing

I am trying to make a replica of the Game of Life using swing, I admit i have used code from some 1 else as i am trying to get my head around it and then proceed with my own implementation. 我正在尝试使用“摇摆”制作“生命游戏”的副本,我承认我使用了其他代码,因为我试图绕过它,然后继续自己的实现。 I have some understanding of their code, yet i wanted to implements 2 additional features to their code. 我对他们的代码有些了解,但是我想为他们的代码实现2个附加功能。 However i am finding that the way it is written is posing problems as i wanted to add a MouseListener(To make a cell come to life when clicked) and WindowListener(To make a start,pause and resume button). 但是我发现它的编写方式带来了问题,因为我想添加一个MouseListener(使单元格在单击时生效)和WindowListener(使开始,暂停和继续按钮)。

I do understand how they work to some extent, yet i need your help to get my headaround it. 我确实了解它们在某种程度上是如何工作的,但我需要您的帮助来解决它。

Here is the code: 这是代码:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.Transient;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;


@SuppressWarnings("serial")
public class ConwaysGameOfLife extends JPanel implements MouseListener{

    private int[][] cellsGrid; // grid is the size of the 2d array
    private static final Random rnd = new Random(); // make a new random generator
    private int generationCounter; // counter for the generation

    public ConwaysGameOfLife(int width, int height) {
        this.cellsGrid = new int[width / 4][height / 4];// divides by 4 whatever the width and height set is 
        setupGrid();
    }// new method for creating the game with input sizes for the size of the game window

    /*The grid consists fully of cells, the grid size is divided by 4 to make the cells
     * setupGrid makes the grid of cells
     * 
     * */
    private void setupGrid() {
        for (int[] row : cellsGrid) {
            for (int j = 0; j < row.length; j++) {
                if (rnd.nextDouble() < 0.92)
                    continue;
                row[j] = rnd.nextInt(2);
                //
            }
        }
    }
    /*
     * applies the rule to the existing cells changing their state depending on the position to neighbors set in the rules
     * */
    public void updateGrid() {
        for (int i = 0; i < cellsGrid.length; i++) {
            for (int j = 0; j < cellsGrid[i].length; j++) {
                applyRule(i, j);
            }
        }
    }

    // Rules of game of life cells iterations
    private void applyRule(int i, int j) {
        int left = 0, right = 0, up = 0, down = 0;
        int dUpperLeft = 0, dUpperRight = 0, dLowerLeft = 0, dLowerRight = 0;
        //this shows the 8 possible neighbors in terms of position

        if (j < cellsGrid.length - 1) {
            right = cellsGrid[i][j + 1];
            if(i>0)
                dUpperRight = cellsGrid[i - 1][j + 1];
            if (i < cellsGrid.length - 1)
                dLowerRight = cellsGrid[i + 1][j + 1];
        }

        if (j > 0) {
            left = cellsGrid[i][j - 1];
            if (i > 0)
                dUpperLeft = cellsGrid[i - 1][j - 1];
            if (i< cellsGrid.length-1)
                dLowerLeft = cellsGrid[i + 1][j - 1];
        }

        if (i > 0)
            up = cellsGrid[i - 1][j];
        if (i < cellsGrid.length - 1)
            down = cellsGrid[i + 1][j];

        int sum = left + right + up + down + dUpperLeft + dUpperRight
                + dLowerLeft
                + dLowerRight;

        if (cellsGrid[i][j] == 1) {
            if (sum < 2)
                cellsGrid[i][j] = 0;
            if (sum > 3)
                cellsGrid[i][j] = 0;
        }

        else {
            if (sum == 3)
                cellsGrid[i][j] = 1;
        }

    }

    @Override
    @Transient
    public Dimension getPreferredSize() {
        return new Dimension(cellsGrid.length * 4, cellsGrid[0].length * 4);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Color gColor = g.getColor();

        g.drawString("Generation: " + generationCounter++, 0, 10);
        for (int i = 0; i < cellsGrid.length; i++) {
            for (int j = 0; j < cellsGrid[i].length; j++) {
                if (cellsGrid[i][j] == 1) {
                    g.setColor(Color.black); // change colour
                    g.fillRect(j * 8, i * 8, 8, 8); // change size of cells
                }
            }
        }

        g.setColor(gColor);
        //paint the cells to a colour
    }

    public static void main(String[] args) {
        final ConwaysGameOfLife c = new ConwaysGameOfLife(800, 800);
        JFrame frame = new JFrame();
        frame.getContentPane().add(c);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);

        JButton start=new JButton("START");
        /* This method specifies the location and size
         * of button. In method setBounds(x, y, width, height)
         * x,y) are cordinates from the top left 
         * corner and remaining two arguments are the width
         * and height of the button.
         */
        start.setBounds(80,0,80,20);

        //Adding button onto the frame
        //frame.add(start);

        new Timer(100, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                frame.add(start);
                c.updateGrid();
                c.repaint();
            }
        }).start();
    }


    @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub



    }

    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub

    }
}

First of all, The button flickers, and only appears when hovered over with the mouse, still flickering. 首先,该按钮闪烁,并且仅在将鼠标悬停在该按钮上时才会出现,并且仍在闪烁。 Then i want the iterations to begin after start button is pressed, and pause button to pause it, and resume(Have a decent idea how it would work, but not how to implement it with the structure of swing that is done in this code.) 然后我希望迭代在按下开始按钮后开始,并在暂停按钮处将其暂停,然后继续(有一个体面的想法,它将如何工作,而不是如何使用此代码中完成的swing结构来实现它。 )

Secondly, I wanted the cells to come to life when they are pressed with the mouse, But, i am unsure how to implement the mouseListener to do this. 其次,我希望通过鼠标按下它们使它们恢复活力,但是,我不确定如何实现mouseListener来实现。

I tried something like cellsGrid[i][j] = 1; 我试过像cellsGrid [i] [j] = 1; when clicked by mouse but i get errors, which is due to my lack of understanding of the implementation of cellsGrid. 当用鼠标单击但出现错误,这是由于我对cellGrid的实现缺乏了解。

I am not expecting solutions to the problem, I would like some guidance to understand the Listeners better and maybe how to make this simpler to understand for me. 我没有期望解决该问题的方法,我希望获得一些指导,以更好地了解听众,也许还想如何使之更容易理解。 Thank You :) 谢谢 :)

Your simulation has a model that is a grid of cells; 您的模拟模型是一个单元格网格。 it has a view that paints an 8 x 8 square to represent a cell in the grid. 它具有一个绘制8 x 8正方形以表示网格中单元的视图 As suggested here , you can map model and view coordinates using linear interpolation . 作为建议在这里 ,您可以使用映射模型和视图坐标线性插值 In particular, given the following proportions, you can cross-multiply and solve for the missing coordinate. 特别是,给定以下比例,您可以相乘并求解丢失的坐标。

view.x : panelWidthInPixels :: model.x : modelXRange
view.y : panelHeightInPixels :: model.y : modelYRange

For reference, this complete example maps mouse coordinates to pixel coordinates in an image. 作为参考,此完整示例将鼠标坐标映射到图像中的像素坐标。 A complete example of John Conway's Game of Life in Java Swing is cited here . 此处引用了约翰·康威John Conway)的《 Java Swing中的生命游戏》的完整示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM