import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import java.applet.*;
public class LifeGameApplet extends JApplet {
public void init(){
Life l = new Life(20,20,false, Color.red, Color.pink, 0);
l.setVisible(true);
l.run();
}
interface PaintStones{
public void routine(Graphics g, int frameX, int frameY, int stoneX, int stoneY);
}
class ImageStone implements PaintStones{
private Image img;
private Life l;
public ImageStone(Life l, String url){
this.l = l;
img = l.getToolkit().getImage(url);
l.repaint();
}
public void routine(Graphics g, int frameX, int frameY, int stoneX, int stoneY){
g.drawImage(img, frameX,frameY,stoneX,stoneY, l);
}
}
class OvalStoneFill implements PaintStones{
public void routine(Graphics g, int frameX, int frameY, int stoneX, int stoneY){
g.drawOval(frameX,frameY,stoneX,stoneY);
}
}
class OvalStone implements PaintStones{
public void routine(Graphics g, int frameX, int frameY, int stoneX, int stoneY){
g.fillOval(frameX,frameY,stoneX,stoneY);
}
}
class RectStoneFill implements PaintStones{
public void routine(Graphics g, int frameX, int frameY, int stoneX, int stoneY){
g.fillRect(frameX,frameY,stoneX,stoneY);
}
}
class RectStone implements PaintStones{
public void routine(Graphics g, int frameX, int frameY, int stoneX, int stoneY){
g.drawRect(frameX,frameY,stoneX,stoneY);
}
}
class ColorScrollbar extends Frame {
private MyScrollbar m_Red = new MyScrollbar();
private MyScrollbar m_Green = new MyScrollbar();
private MyScrollbar m_Blue = new MyScrollbar();
private Life m;
public ColorScrollbar(Life l) {
this.m = l;
setBounds(100,100,300,200);
setLayout(new FlowLayout());
add(m_Red);add(m_Green);add(m_Blue);
setColor();setVisible(true);
}
class MyScrollbar extends Scrollbar {
float m_fValue;
MyScrollbar() {
addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
m_fValue = (float)e.getValue() / (float)(getMaximum()-getVisibleAmount());
setColor();
}
});
}
}
public void setColor() {
m.setBackground(new Color(m_Red.m_fValue,m_Green.m_fValue,m_Blue.m_fVa lue));
// System.out.println(m_Red.m_fValue+" "+m_Green.m_fValue+" "+" "+m_Blue.m_fValue);
}
}
class CloseDialog extends Dialog{
public CloseDialog (Life l){
super(l, true);
setForeground(Color.black);
setTitle("Spiel beenden?");
setLayout(new FlowLayout());
Button btOK = new Button("OK");
add(btOK);
btOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
Button btCancel = new Button("Cancel");
add(btCancel);
btCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
dispose();
}
});
pack();
setLocation((l.dim.width-getSize().width)/2, (l.dim.height-getSize().height)/2);
setVisible(true);
}
}
class EingabeDialog extends Dialog {
private int lifeLaenge;
private int lifeBreite;
private TextField txLdata;
private TextField txBdata;
public EingabeDialog (final Life l){
super(l);
setForeground(Color.black);
setTitle("Dimensionen");
setLayout(new GridLayout(3,2));
setLocation(400,400);
add(new Label("Länge: ", Label.LEFT));
txLdata = new TextField();
txLdata.addTextListener(new TextListener(){
public void textValueChanged(TextEvent e){
lifeLaenge = Integer.parseInt(txLdata.getText());
}
});
add(txLdata);
add(new Label("Breite: ", Label.LEFT));
txBdata = new TextField();
txBdata.addTextListener(new TextListener(){
public void textValueChanged(TextEvent e){
lifeBreite = Integer.parseInt(txBdata.getText());
}
});
add(txBdata);
Button btOK = new Button("OK");
add(btOK);
btOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
l.initLife(lifeLaenge, lifeBreite);
}
});
Button btCancel = new Button("Cancel");
add(btCancel);
btCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
setVisible(false);
}
});
pack();
}
}
class PropDialog extends Dialog {
public PropDialog (final Life l){
super(l);
setLayout(new BorderLayout(4,2));
Panel p1 = new Panel();
p1.setLayout(new GridLayout(1,4));
Label lb1 = new Label("Einstellungen im Lifespiel", Label.LEFT);
lb1.setBackground(Color.lightGray);
add(BorderLayout.NORTH, lb1);
Label lb2 = new Label("", Label.LEFT);
lb2.setBackground(Color.lightGray);
add(BorderLayout.SOUTH, lb2);
add(BorderLayout.CENTER, p1);
Panel p2 = new Panel();
p2.setLayout(new GridLayout(4,1));
p1.add(p2);
CheckboxGroup grp = new CheckboxGroup();
Label lbStoneColor = new Label("Steinfarbe");
Checkbox red = new Checkbox("rot", grp, false);
red.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
l.setForeground(Color.red);
}
});
Checkbox blue = new Checkbox("blau", grp, false);
blue.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
l.setForeground(Color.blue);
}
});
Checkbox green = new Checkbox("gruen", grp, false);
green.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
l.setForeground(Color.green);
}
});
p2.add(lbStoneColor);
p2.add(red);p2.add(blue);p2.add(green);
Panel p3 = new Panel();
p3.setLayout(new GridLayout(4,1));
p3.setBackground(Color.white);
p1.add(p3);
CheckboxGroup grp2 = new CheckboxGroup();
Label lbBackGround = new Label("Hintergrundfarbe");
Checkbox pinc = new Checkbox("pink", grp2, false);
pinc.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
l.setBackground(Color.pink);
}
});
Checkbox black2 = new Checkbox("schwarz", grp2, false);
black2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
l.setBackground(Color.black);
}
});
Checkbox white2 = new Checkbox("weiss", grp2, false);
white2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
l.setBackground(Color.white);
}
});
p3.add(lbBackGround);
p3.add(pinc);p3.add(black2);p3.add(white2);
Panel p4 = new Panel();
p4.setLayout(new GridLayout(2,1));
p1.add(p4);
Label lbStoneForm = new Label("Steinform");
final Choice c = new Choice();
for(int i=0; i<l.stoneArray.length; i++){
c.add(""+i);
}
p4.add(lbStoneForm);
c.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
l.changeStoneForm(c.getSelectedIndex());
}
});
p4.add(c);
Panel p5 = new Panel();
p5.setLayout(new GridLayout(2,1));
p5.setBackground(Color.white);
p1.add(p5);
// final Scrollbar s = new Scrollbar(Scrollbar.VERTICAL,10,5, 10,350);
// s.setValue(l.threadSpeed);
// final Label lbSpeed = new Label("Speed ");
// s.addAdjustmentListener(new AdjustmentListener() {
// public void adjustmentValueChanged(AdjustmentEvent e) {
// switch (e.getAdjustmentType()) {
// case AdjustmentEvent.TRACK: l.threadSpeed = s.getValue(); break;
// case AdjustmentEvent.UNIT_INCREMENT: ++l.threadSpeed; break;
// case AdjustmentEvent.UNIT_DECREMENT: --l.threadSpeed; break;
// case AdjustmentEvent.BLOCK_DECREMENT: ++l.threadSpeed; break;
// case AdjustmentEvent.BLOCK_INCREMENT: --l.threadSpeed; break;
// }
// lbSpeed.setText("Speed "+s.getValue());
// }
// });
// p5.add(lbSpeed);
// p5.add(s);
//Übung 13_2: JSlider
final JSlider slider = new JSlider(JSlider.HORIZONTAL, 10, 500, 200);
slider.setMinorTickSpacing(20);
slider.setMajorTickSpacing(100);
slider.setPaintTicks(true);
final Label lbSpeed = new Label("Speed ");
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
l.threadSpeed = slider.getValue();
lbSpeed.setText("Speed " + slider.getValue());
}
});
p5.add(lbSpeed);
p5.add(slider);
// Übung 14_1: JTabbedPane
JTabbedPane pane = new JTabbedPane(JTabbedPane.TOP);
pane.addTab("Steinfarbe", p2);
pane.addTab("Hintergrundfarbe", p3);
pane.addTab("Steinform", p4);
pane.addTab("Speed", p5);
p1.add(pane);
addWindowListener(new WindowAdapter(){ // Windowclose-Button
public void windowClosing(WindowEvent e){
setVisible(false);
}
});
pack();
setLocation((l.dim.width-getSize().width)/2, (l.dim.height-getSize().height)/2);
}
}
class Life extends Frame {
protected boolean[][] array;
protected boolean[][] array_help2;
protected int stoneForm; // SteinForm
protected PaintStones[] stoneArray = {new OvalStone(), new OvalStoneFill(), new RectStone(), new RectStoneFill()};
protected PopupMenu popMenu = new PopupMenu();
final Toolkit kit = Toolkit.getDefaultToolkit();
final Dimension dim = kit.getScreenSize();
EingabeDialog eDialog;
PropDialog pDialog;
private FileDialog loadDialog;
private FileDialog saveDialog;
int threadSpeed;
public Life() throws IOException {
this(10);
}
public Life(int x) throws IOException {
this(x, 10);
}
public Life(int x, int y) throws IOException {
this(x,y, false);
}
public Life(int x, int y, boolean flag) throws IOException {
this(x,y,flag, Color.red);
}
public Life(int x, int y, boolean flag, Color stoneColor) throws IOException {
this(x,y,flag, stoneColor, Color.black);
}
public Life(int x, int y, boolean flag, Color stoneColor, Color backGroundC) throws IOException {
this(x,y,flag, stoneColor, backGroundC, 0);
}
public Life(int x, int y, boolean flag, Color stoneColor, Color backGroundC, int stoneForm) throws IOException {
setTitle("Life HauptFrame");
initLife(x,y);
setSize(400,400);
eDialog = new EingabeDialog(this);
pDialog = new PropDialog(this);
MenuBar menuBar = new MenuBar();
Menu menu = new Menu("Datei");
threadSpeed = 200;
MenuItem lifeNeuS = new MenuItem("NEU", new MenuShortcut(KeyEvent.VK_N));
lifeNeuS.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
initLife();
}
});
menu.add(lifeNeuS);
MenuItem lifeNeuV = new MenuItem("Life size", new MenuShortcut(KeyEvent.VK_X));
lifeNeuV.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
eDialog.setVisible(true);
}
});
menu.add(lifeNeuV);
MenuItem stoneLoad = new MenuItem("Load stone", new MenuShortcut(KeyEvent.VK_1));
stoneLoad.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
loadStone();
} catch(IOException ex) {
System.out.println("Fehler: "+ex);
}
}
});
menu.add(stoneLoad);
menu.addSeparator();
ActionNeuFormat(15, 10);
ActionNeuFormat(25, 25);
ActionNeuFormat(40, 30);
MenuItem lifeLoad = new MenuItem("Spiel Laden", new MenuShortcut(KeyEvent.VK_L));
menu.add(lifeLoad);
lifeLoad.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
loadLife();
} catch(IOException ex) {
System.out.println("Fehler: "+ex);
}
}
});
MenuItem lifeSave = new MenuItem("Spiel Speichern", new MenuShortcut(KeyEvent.VK_S));
menu.add(lifeSave);
lifeSave.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
saveLife();
} catch(IOException ex2) {
System.out.println("Fehler: "+ex2);
}
}
});
menu.addSeparator();
MenuItem frameCenter = new MenuItem("Fenster Zentrieren", new MenuShortcut(KeyEvent.VK_Z));
menu.add(frameCenter);
frameCenter.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
setLocation((dim.width-getSize().width)/2, (dim.height-getSize().height)/2);
}
});
MenuItem frameMax = new MenuItem("Fenster Maximieren", new MenuShortcut(KeyEvent.VK_M));
menu.add(frameMax);
frameMax.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
setExtendedState(Frame.MAXIMIZED_BOTH);
}
});
MenuItem frameIcon = new MenuItem("Fenster Iconifizieren", new MenuShortcut(KeyEvent.VK_I));
menu.add(frameIcon);
frameIcon.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
setState(ICONIFIED);
}
});
menu.addSeparator();
MenuItem properties = new MenuItem("Einstellungen", new MenuShortcut(KeyEvent.VK_P));
menu.add(properties);
properties.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
pDialog.setVisible(true);
}
});
menu.addSeparator();
MenuItem frameEnd = new MenuItem("Beenden", new MenuShortcut(KeyEvent.VK_B));
menu.add(frameEnd);
frameEnd.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
lifeExit();
}
});
menuBar.add(menu);
setMenuBar(menuBar);
addWindowListener(new WindowAdapter(){ // Windowclose-Button
public void windowClosing(WindowEvent e){
lifeExit();
}
});
addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_C URSOR));
}
public void mouseClicked(MouseEvent e) {
final int stoneX = (getSize().width-getInsets().left-getInsets().right-1) / array.length;
final int stoneY = (getSize().height-getInsets().top-getInsets().bottom-1) / array[0].length;
int mouseX = (e.getX()-getInsets().left-getInsets().right)/stoneX;
int mouseY = (e.getY()-getInsets().bottom-getInsets().top)/stoneY;
System.out.println(mouseY+", "+mouseX+" | "+array.length+" "+array[0].length);
changeStoneStatus(mouseY, mouseX);
repaint();
}
});
this.stoneForm = stoneForm;
setBackground(backGroundC);
setForeground(stoneColor);
add(popMenu);
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
setLocation((dim.width-getSize().width)/2, (dim.height-getSize().height)/2);
try{
if(flag) {
read_in();
return;
}
}catch(FileNotFoundException exep){
System.out.println("nix vorhanden Datei! \n");
}
}
private void loadStone() throws IOException{
loadDialog = new FileDialog(this, "Stein Laden", FileDialog.LOAD);
loadDialog.setVisible(true);
if(loadDialog.getFile() != null) {
PaintStones[] stoneArray2 = new PaintStones[stoneArray.length+1];
for(int i=0; i<stoneArray.length; i++){
stoneArray2[i] = stoneArray[i];
}
stoneArray2[stoneArray.length] = new ImageStone(this, loadDialog.getDirectory()+loadDialog.getFile());
stoneArray = stoneArray2;
}
}
private void loadLife() throws IOException{
loadDialog = new FileDialog(this, "Lifespiel Laden", FileDialog.LOAD);
loadDialog.setVisible(true);
if(loadDialog.getFile() != null) {
read_in(loadDialog.getDirectory()+loadDialog.getFi le());
repaint();
}
}
private void saveLife() throws IOException{
saveDialog = new FileDialog(this, "Lifespiel Speichern", FileDialog.SAVE);
saveDialog.setVisible(true);
if(saveDialog.getFile() != null) {
write_out(saveDialog.getDirectory()+saveDialog.get File());
}
// System.out.println(save.getDirectory()+save.getFil e());
}
public void changeStoneStatus(int x, int y){
if(x>=0 && x<array.length && y>=0 && y<array[0].length){
array[x][y]=!array[x][y];
System.out.println(array[x][y]);
//System.out.println(getNumNeighbours(i,j));
}
}
protected void processMouseEvent(MouseEvent e){
if(e.isPopupTrigger()){
popMenu.show(e.getComponent(), e.getX(), e.getY());
}
super.processMouseEvent(e);
}
public void ActionNeuFormat(MenuItem mI, final int x, final int y, Menu m){
mI.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
initLife(x,y);
}
});
m.add(mI);
}
public void ActionNeuFormat(int x, int y){
MenuItem mI = new MenuItem("Neu "+x+"x"+y);
ActionNeuFormat(mI, x, y, popMenu);
}
public void initLife(){
for(int x=0; x<array.length; x++){
for(int n=0; n<array[0].length; n++){
array[x][n] = java.lang.Math.random() > 0.5d;
}
}
}
protected void initLife(int z, int t){
array = new boolean[z][t];
initLife();
}
public void lifeExit(){
new CloseDialog(this);
}
public void run() throws InterruptedException,IOException {
while(true) {
Thread.sleep(threadSpeed);
simulation();
repaint();
}
}
public void changeStoneForm(){
stoneForm = ++stoneForm%stoneArray.length;
}
public void changeStoneForm(int arrayPosition){
stoneForm = arrayPosition;
}
public void paint(Graphics g){
for(int x=0; x<array.length; x++){
for(int n=0; n<array[0].length; n++){
int stoneX = (getSize().width-getInsets().left-getInsets().right) / array[0].length;
int stoneY = (getSize().height-getInsets().top-getInsets().bottom) / array.length;
int frameX = getInsets().left + n*(stoneX);
int frameY = getInsets().top + x*(stoneY);
if(array[x][n]) {
stoneArray[stoneForm].routine(g,frameX,frameY,stoneX,stoneY);
}
}
}
}
public void printPage(){
Toolkit tKit = getToolkit();
PrintJob pJob = tKit.getPrintJob(this, this.getTitle(), null);
if(pJob != null){
Graphics g = pJob.getGraphics();
if(g != null){
paint(g);
}
pJob.end();
}
}
public void print(PrintStream f) throws IOException {
for(int x=0; x<array.length; x++){
for(int n=0; n<array[0].length; n++){
if(array[x][n]){
f.print("X"+" ");
}else{
f.print("O"+" ");
}
}
f.print("\n");
}
f.print("\n");
}
public void simulation() throws IOException{
array_help2 = new boolean[array.length][array[0].length];
for(int i=0;i<array.length;i++){
for(int j=0;j<array[0].length; j++){
int a=0;
if(array[(i+1)%array.length][j])a++; // unmittelbar unterer Nachbar
if(array[(i+array.length-1)%array.length][j])a++; // unmittelbar oberer Nachbar
if(array[i][(j+array[0].length-1)%array[0].length])a++; // unmittelbar linker Nachbar
if(array[i][(j+1)%array[0].length])a++; // unmittelbar rechter Nachbar
if(array[(i+1)%array.length][(j+array[0].length-1)%array[0].length])a++; // unten links
if(array[(i+array.length-1)%array.length][(j+array[0].length-1)%array[0].length])a++; // oben links
if(array[(i+1)%array.length][(j+1)%array[0].length])a++; // unten rechts
if(array[(i+array.length-1)%array.length][(j+1)%array[0].length])a++; // unten links
array_help2[i][j] = a==3 || (array[i][j] && a==2) ? true : false; // Regeln
}
}
array = array_help2;
}
public void write_out() throws IOException {
write_out("test.txt");
}
public void write_out(String lifeName) throws IOException {
System.out.println(lifeName);
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(lifeName)));
write_out(out);
}
private void write_out(DataOutputStream out) throws IOException {
RandomAccessFile random = new RandomAccessFile("RandomFile.txt", "rw");
out.writeInt(array.length); // Anzahl Spalten
out.writeInt(array[0].length); // Anzahl Zeilen
random.writeInt(array.length);
random.writeInt(array[0].length);
for(int i=0; i<array.length; i++) {
for(int x=0; x<array[0].length; x++) {
out.writeBoolean(array[i][x]);
random.writeBoolean(array[i][x]);
}
}
random.seek(0); // Setze den Index auf o-Position
random.close();
out.close();
}
public void read_in() throws IOException {
read_in("test.txt");
}
private void read_in(String lifeName) throws IOException {
// DataInputStream: Inhalt wird jedes mal gelscht und neu geschrieben
DataInputStream input = new DataInputStream(new BufferedInputStream(new FileInputStream(lifeName)));
read_in(input);
}
private void read_in(DataInputStream input) throws IOException {
int b = input.readInt();
int y = input.readInt();
array_help2 = new boolean[b][y];
for(int i=0; i<array_help2.length; i++) {
for(int x=0; x<array_help2[0].length; x++) {
array_help2[i][x] = input.readBoolean();
}
}
array = array_help2;
input.close();
}
}
class MButton extends Button {
public MButton(final Life l){
super("andere SteinForm!");
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
l.changeStoneForm();
}
});
}
}
class NextFormButton extends Frame {
public NextFormButton(Life l){
setTitle("next stoneForm");
setBounds(200,200, 200, 100);
add(new MButton(l));
setVisible(true);
}
}
// Classe zur Ausgabe des LaufTextes
class LaufText extends Window {
private final String m_lText;
private int m_x;
final Toolkit kit = Toolkit.getDefaultToolkit();
final Dimension dim = kit.getScreenSize();
public LaufText(Frame f){
super(f);
setSize(600, 60);
setLocation((dim.width-getSize().width)/2, (dim.height-getSize().height)/2);
setBackground(Color.cyan);
m_lText = "bin ein Lauftext...";
m_x = getInsets().left;
setVisible(true);
}
public void paint(Graphics g){
int maxY = getSize().height - getInsets().top - getInsets().bottom;
g.drawString(m_lText, m_x, getInsets().top + maxY/2); // (text, x, y)
}
public void run() throws InterruptedException {
for(; m_x <= getWidth(); m_x++) {
Thread.sleep(10);
repaint();
}
for(m_x = getSize().width-getInsets().right; m_x >= getInsets().left-m_lText.length(); m_x--) {
Thread.sleep(10);
repaint();
}
dispose();
}
}
class ReadK {
private String readLine(InputStream in) throws IOException {
byte[] b = new byte[256];
int nrOfChars = in.read(b);
if (nrOfChars > 2)
return new String(b,0,nrOfChars-2);
else
return "";
}
public int inputINT(InputStream in, String mo) throws IOException {
int res = 0;
System.out.println(mo); // Frage stellen
while(res == 0){
try {
int go = Integer.parseInt(readLine(in));
if (go < 0)
System.out.println("Bitte wiederhollen (keine Negativen-Werte)");
else if(go == 0)
System.out.println("Bitte wiederhollen (keine Null-Werte)");
else
res = go;
}
catch (NumberFormatException x) {
System.out.println("Bitte eingabe machen!");
}
}
return res;
}
}
}