Life GUI (JAVA)

За вознаграждение или нахаляву (если повезёт)

Модераторы: Хыиуду, MOTOCoder, Medved, dr.Jekill

Ответить
Аватара пользователя
Колядин Максим
Сообщения: 297
Зарегистрирован: 16 ноя 2006, 19:09
Откуда: Seattle, WA
Контактная информация:

Для начала, условие
LifeGUI (see http://www.math.com/students/wonders/life/life.html)
Mathematician John Conway devised the Game of Life in 1970. It models a very simple world. The Life world is a two-dimensional plane of cells. Each cell may be empty or contain a single creature. Each day, creatures are born or die in each cell according to the number of neighboring creatures on the previous day. A neighbor is a cell that adjoins the cell either horizontally, vertically, or diagonally. The rules in pseudocode style are:


if ( the cell is alive on the previous day)
{
if (the number of live neighbors was 2 or 3)
{
the cell remains alive
}
else
{
the cell dies
}
}
else if (the cell is not alive on the previous day)
{
if (the number of live neighbors was exactly 3)
{
the cell becomes alive
}
else
{
the cell remains dead
{
}

For example, the world displayed as:

0000000000
0000000000
000xxx0000
0000000000
0000000000
0000000000

where X’s indicate living cells, becomes:


0000000000
0000x00000
0000x00000
0000x00000
0000000000
0000000000

For the non-GUI application, use a 20 by 20 grid. To initialize the grid, the application should prompt the user for the coordinates of live cells on the first day. The application should then generate each day’s world as long as the user wishes to continue or until there are no more live cells.
For the GUI application the 20 by 20 grid should be buttons that initially display all 0s. To select the live cells for the first day, the user clicks the buttons on the positions of live cells. When clicked, a button changes from displaying a 0 to displaying an X. A Next button below the grid can be clicked repeatedly to display the next generation until the user quits or there are no more live cells.
Задачу, в общем, я выполнил. Но программа работает только 1 шаг. На следующий шаг массив обнуляется. Вот код.
Программист - это человек, который решает способом, который вы не понимаете, проблемы, о которых вы даже не подозревали...
Аватара пользователя
Колядин Максим
Сообщения: 297
Зарегистрирован: 16 ноя 2006, 19:09
Откуда: Seattle, WA
Контактная информация:

Код: Выделить всё

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Dimension;

import java.awt.FlowLayout;
import java.awt.GridLayout;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

public class Run extends JFrame{
JPanel p;
JButton b[];
JButton next = new JButton("Start!");
JButton quit = new JButton("«Quit");
boolean started = false;
int[][] b1 = new int[20][20];
int[][] b2 = new int[20][20];
ButtonListener bl = new ButtonListener();

    public Run() {
    super("Power system.");
    p = new JPanel();
    p.setPreferredSize(new Dimension(950,700));
    p.setLayout(new GridLayout(20,20));
    b = new JButton[400];
        for (int i=0; i<b.length; i++) {
            b[i] = new JButton("0");
            p.add(b[i]);
            b[i].addActionListener(bl);
        }
    p.setLayout(new FlowLayout());
    p.add(quit);
    p.add(next);
    next.addActionListener(bl);
    quit.addActionListener(bl);
    setContentPane(p);
        
        for (int i=0; i<20; i++) {
        for (int j=0; j<20; j++) {
                b1[i][j]=0;
        }       }    


    
    }

    class ButtonListener implements ActionListener {
     public void actionPerformed(ActionEvent e) {
    JButton source = (JButton) e.getSource();
    if ((started==false)&&(source.getText()!="Start!")) {  source.setLabel("X");}
    
    if (source == next) {
        if (started==false) {
            for (int i=0; i<20; i++) {
                for (int j=0; j<20; j++) {
                    if (b[(i*20) + j].getText()=="X") {b1[i][j] = 5;}   
                }
                      started=true; 
       next.setLabel("Next»");
       System.out.println("Started!");
       JOptionPane.showMessageDialog(p,"Game started. Click 'next' to see next step.");
        } else {
            nextStep();
            for (int i=0; i<20; i++) {
            for (int j=0; j<20; j++) {
                if (b1[i][j]==5) {b[(i*20) + j].setText("X");} else {b[(i*20)+j].setText("0");}
            }
            }
           
        }
    }
    if (source == quit) {
        System.exit(0);
    }
    

    } }
    public void nextStep() {
    int sum = 0;


        for (int i=0; i<20; i++) {
        for (int j=0; j<20; j++) {
                b2[i][j]=0;
        }     }

        for (int i=0; i<20; i++) {
        for (int j=0; j<20; j++) {
        sum=0;   
            if (b1[i][j]>0) {  System.out.print(b1[i][j] + " ");}
                if ((j!=0)&&(i!=0)) {sum=sum+b1[i-1][j-1];}
                if (i!=0) {sum = sum + b1[i-1][j];}
                if ((j!=19)&&(i!=0)) {sum=sum+b1[i-1][j+1];}    
            
        if (j!=0) {sum = sum + b1[i][j-1];}        
        if (j!=19) {sum=sum+b1[i][j+1];}    
            
        if ((j!=0)&&(i!=19)) {sum=sum+b1[i+1][j-1];}
        if (i!=19) {sum = sum + b1[i+1][j];}
        if ((j!=19)&&(i!=19)) {sum=sum+b1[i+1][j+1];}     
            

            if (b1[i][j]==5) {
                b2[i][j] = 5;
                if ((sum!=10)&&(sum!=15)) {
                b2[i][j] = 0;
                               }
            } else {
                if (sum==15) {b2[i][j]=5;                        }
            }

            }
        }
    b1 = b2;

    }
    public static void main(String[] args) {
        Run run = new Run();
        run.pack();
        run.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        run.setVisible(true);
    }
}
Буду рад помощи
--------------------------------------------------------------------------------
Добавлено сообщение
--------------------------------------------------------------------------------
UPDATE***
--
Программист - это человек, который решает способом, который вы не понимаете, проблемы, о которых вы даже не подозревали...
Ответить