import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SlidingPuzzlePanel extends JPanel {
private static final long serialVersionUID = 4501938941435763747L;
private static final int SIDE = 4;
private static final int FONT_SIZE = 40;
private static int LEVEL = 10;
private Game game;
private Font font;
private Color background, foreground, borderColor;
private int slotWidth, slotHeight, slotXOffset, slotYOffset;
private int inX, inY, xOffset, yOffset;
private boolean dragged;
public SlidingPuzzlePanel() {
game = new Game(SIDE, LEVEL);
font = new Font(Font.SERIF, Font.BOLD, FONT_SIZE);
slotWidth = SlidingPuzzle.WIDTH / SIDE;
slotHeight = SlidingPuzzle.HEIGHT / SIDE;
slotXOffset = slotWidth / 2 - FONT_SIZE / 4;
slotYOffset = slotHeight / 2 + FONT_SIZE / 3;
background = new Color(123, 155, 232);
foreground = new Color(123, 255, 132);
borderColor = new Color(223, 255, 132);
dragged = false;
setFocusable(true);
requestFocus();
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
if(dragged) {
inX = e.getXOnScreen() - xOffset;
inY = e.getYOnScreen() - yOffset;
SlidingPuzzle.frame.setLocation(inX, inY);
}
else {
dragged = true;
xOffset = e.getX();
yOffset = e.getY();
}
}
@Override
public void mouseMoved(MouseEvent e) {
dragged = false;
}
});
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
switch(key) {
case KeyEvent.VK_ESCAPE:
SlidingPuzzle.frame.dispose();
break;
default:
game.keyPressed(key);
repaint();
if(game.isCorrect()) {
JOptionPane.showMessageDialog(SlidingPuzzle.frame, "You Win!");
LEVEL += 10;
game = new Game(SIDE, LEVEL);
repaint();
}
}
}
});
}
@Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.setFont(font);
g2d.setColor(background);
g2d.fillRect(0, 0, getWidth(), getHeight());
drawBorders(g2d);
g2d.setColor(foreground);
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
if(game.getValueAt(j, i) != 0)
g2d.drawString(""+game.getValueAt(j, i), slotXOffset + j * slotWidth,
slotYOffset + i * slotHeight);
}
}
}
private void drawBorders(Graphics2D g2d) {
g2d.setColor(borderColor);
for(int i = 0; i < 3; i++)
g2d.drawRect(i, i, SlidingPuzzle.WIDTH - 1 - 2 * i, SlidingPuzzle.HEIGHT - 1 - 2 * i);
for(int i = 1; i < 4; i++) {
int level = i * slotHeight;
g2d.drawLine(0, level, SlidingPuzzle.WIDTH, level);
g2d.drawLine(0, level + 1, SlidingPuzzle.WIDTH, level + 1);
g2d.drawLine(0, level + 2, SlidingPuzzle.WIDTH, level + 2);
g2d.drawLine(level, 0, level, SlidingPuzzle.HEIGHT);
g2d.drawLine(level + 1, 0, level + 1, SlidingPuzzle.HEIGHT);
g2d.drawLine(level + 2, 0, level + 2, SlidingPuzzle.HEIGHT);
}
}
}