-
Notifications
You must be signed in to change notification settings - Fork 1
/
JavaLife.java
106 lines (75 loc) · 2.63 KB
/
JavaLife.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/**
* @author mr.The
* @skype mr-the
* @twitter @mr_The
*/
package javalife;
import javax.swing.*;
/**
* Main class.
*/
public class JavaLife {
TorArray data;
boolean calc=false;
int cell_size=10;
public static void main(String[] args) {
JFrame f = new JFrame("Game of Life");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(630,630); //canvas size
f.validate();
f.setVisible(true);
f.toFront();
GCanvas canvas = new GCanvas();
f.getContentPane().add(canvas);
JavaLife jl = new JavaLife();
jl.init(canvas, 60, 60); // array size
for(;;) { // main cycle
if(jl.calc)
jl.calc(); //recalc
jl.draw(canvas); //redraw
try {
Thread.sleep(50); //pause
} catch (Exception e) {}
}
}
public void init(GCanvas canvas, int w, int h) {
canvas.setCellSize(cell_size);
data = new TorArray(w, h);
GMouseListener mouseListener = new GMouseListener();
mouseListener.setCellSize(cell_size);
mouseListener.setLife(this);
GKeyListener keyListener = new GKeyListener();
keyListener.setLife(this);
canvas.addMouseListener(mouseListener);
canvas.addMouseMotionListener(mouseListener);
canvas.addKeyListener(keyListener);
cleanArray();
}
public void cleanArray() {
for(int i=0; i<data.getWidth(); i++) {
for(int j=0; j<data.getHeight(); j++) {
data.setCell(i, j, 0);
}
}
}
public void calc() {
TorArray temp = new TorArray(data.getWidth(), data.getHeight());
for(int i=0; i<data.getWidth(); i++) {
for(int j=0; j<data.getHeight(); j++) {
int count = data.getCellsCount(i, j);
//rule 1 // рождаемость
if(data.getCell(i, j)==0 && count==3) temp.setCell(i, j, 1);
//rule 2 перенаселённость
else if(data.getCell(i, j)==1 && count>3) temp.setCell(i, j, 0);
//rule 3 одиночество
else if(data.getCell(i, j)==1 && count<2) temp.setCell(i, j, 0);
else temp.setCell(i, j, data.getCell(i, j));
}
}
data=temp;
}
public void draw(GCanvas canvas) {
canvas.setLife(this);
canvas.repaint();
}
}