import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
public class Memory extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
JButton[][] buttons;
JTextField tries;
Color[] colors={Color.RED, Color.YELLOW, Color.BLUE, Color.GREEN, Color.BLACK, Color.WHITE, Color.CYAN, Color.GRAY, new Color(160,40,40), Color.MAGENTA, Color.ORANGE, Color.PINK};
Color[][] covColors=new Color[4][6];
Color buttonDesign;
int versuche=0;
int l;
int r;
public Memory() {
setTitle("Memory");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600,400);
Dimension screen=getToolkit().getScreenSize();
setLocation((screen.width-600)/2,(screen.height-400)/2);
tries=new JTextField("Versuche :"+versuche,20);
tries.setEditable(false);
JPanel textarea=new JPanel();
textarea.add(tries);
buttons=new JButton[4][6];
JPanel buttonArea=new JPanel(new GridLayout(buttons.length,buttons.length));
for(int i=0;i<buttons.length;i++) {
for(int j=0;j<buttons[i].length;j++){
buttons[i][j]=new JButton("");
buttonArea.add(buttons[i][j]);
}
}
add(textarea,BorderLayout.NORTH);
add(buttonArea,BorderLayout.CENTER);
setVisible(true);
buttonDesign=buttons[0][0].getBackground();
for(JButton[] b:buttons){
for(JButton n:b){
n.addActionListener(this);
}
}
getSpielfeld();
}
public void getSpielfeld(){
for(Color c:colors){
int counter=0;
while(true){
int line=new Random().nextInt(4);
int row=new Random().nextInt(6);
if(covColors[line][row]!=null)continue;
covColors[line][row]=c;
counter++;
if(counter==2)break;
}
}
}
public static void main(String[] args){
new Memory();
}
public static void pause(int millis){
try{Thread.sleep(millis);}
catch(Exception ignore){}
}
public void actionPerformed(ActionEvent e) {
for(int i=0;i<buttons.length;i++){
for(int n=0;n<buttons[i].length;n++){
if(e.getSource()==buttons[i][n]){
if(buttons[i][n].getBackground()!=buttonDesign)return;
versuche++;
buttons[i][n].setBackground(covColors[i][n]);
if(versuche%2!=0){l=i;r=n;}
else{tries.setText("Versuche: "+versuche/2);
boolean b=true;
for(JButton[] x:buttons){
for(JButton y:x){
if(y.getBackground()==buttonDesign)b=false;
}
}
if(b==true)tries.setText("Memory gelöst!! Versuche: "+versuche/2);
pause(500);
if(buttons[l][r].getBackground()!=buttons[i][n].getBackground()){buttons[l][r].setBackground(buttonDesign);buttons[i][n].setBackground(buttonDesign);}
}
return;
}
}
}
}
}