import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MyDialog extends JDialog{
public MyDialog(JFrame frame, String title) {
super(frame, true);
JLabel la1=new JLabel("P");
add(la1);
setSize(500,500);
setVisible(false);
}
}
public class Main extends JFrame{
private MyPanel panel=new MyPanel();
private MyDialog dialog;
int arr[] = new int[15];
int x[] = new int[17]; // x[1] ~ x[16] 사용
JLabel la[]=new JLabel[17]; // la[1] ~ la[16] 사용
public Main() {
arr[0]=2;
arr[1]=2;
arr[2]=2;
arr[3]=2;
arr[4]=2;
arr[5]=2;
arr[6]=4;
arr[7]=4;
arr[8]=4;
arr[9]=2;
arr[10]=2;
arr[11]=8;
arr[12]=16;
arr[13]=0;
arr[14]=0;
for(int i=1;i<=16;i++) {
x[i] = arr[(int)(Math.random()*arr.length)];
}
for(int i=1;i<=16;i++) {
la[i]=new JLabel(Integer.toString(x[i]));
la[i].setSize(50,50);
panel.add(la[i]);
}
panel.setLayout(null);
la[1].setLocation(100,75);
la[2].setLocation(225,75);
la[3].setLocation(355,75);
la[4].setLocation(490,75);
la[5].setLocation(100,200);
la[6].setLocation(225,200);
la[7].setLocation(355,200);
la[8].setLocation(490,200);
la[9].setLocation(100,320);
la[10].setLocation(225,320);
la[11].setLocation(355,320);
la[12].setLocation(490,320);
la[13].setLocation(100,450);
la[14].setLocation(225,450);
la[15].setLocation(350,450);
la[16].setLocation(490,450);
dialog= new MyDialog(this,"you win!");
setContentPane(panel);
panel.addKeyListener(new MyKeyListener());
panel.setFocusable(true);
panel.requestFocus();
setSize(609,609);
setVisible(true);
}
class MyPanel extends JPanel{
private ImageIcon icon=new ImageIcon("2048.png");
private Image img=icon.getImage();
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}
class MyKeyListener extends KeyAdapter{
public void keyPressed(KeyEvent e) {
int sum[]=new int[16];
if(e.getKeyCode()==KeyEvent.VK_UP) {
dialog.setVisible(false);
}
if(e.getKeyCode()==KeyEvent.VK_RIGHT) {
//1. la2의 gettext -> string -> int //
//2. la3의 gettext -> string -> int //
//3. 1번 + 2번 -> int -> string
for(int i=1;i<=4;i++) {
sum[1]=sum[1]+Integer.valueOf(la[i].getText());
}
la[4].setText(Integer.toString(sum[1]));
for(int i=5;i<=8;i++) {
sum[2]=sum[2]+Integer.valueOf(la[i].getText());
}
la[8].setText(Integer.toString(sum[2]));
for(int i=9;i<=12;i++) {
sum[3]=sum[3]+Integer.valueOf(la[i].getText());
}
la[12].setText(Integer.toString(sum[3]));
for(int i=13;i<=16;i++) {
sum[4]=sum[4]+Integer.valueOf(la[i].getText());
}
la[16].setText(Integer.toString(sum[4]));
repaint();
}
else if(e.getKeyCode()==KeyEvent.VK_LEFT) {
}
}
}
public static void main(String[] args) {
new Main();
}
}
원