import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JComponent;
@SuppressWarnings("serial")
public class DuckyGame extends JComponent implements Runnable {
public final static int WIDTH = 600;
public final static int HEIGHT = 400;
public final static String[] names = { "diddyDuck", "obstacle1", "obstacle2" };
public final static int DUCKY = 0;
public final static int BUSH_A = 1;
public final static int BUSH_B = 2;
private int horizont = 175;
private Duck duck;
private float bushSpeed = 1.1f;
private float duckSpeed = 3 * bushSpeed / 4;
private ObstaclesLine bushes = new ObstaclesLine(horizont, WIDTH);
private boolean running = false;
private Thread aniamtor = null;
public DuckyGame() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
initGame();
}
private void drawBackGround(Graphics g) {
g.setColor(new Color(184, 233, 236));
g.fillRect(0, 0, WIDTH, HEIGHT / 2);
g.setColor(new Color(135, 121, 74));
g.fillRect(0, HEIGHT / 2, WIDTH, HEIGHT / 2);
}
public KeyAdapter getKeyBoard() {
return new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
duck.setSpeed(-duckSpeed);
if (key == KeyEvent.VK_RIGHT)
duck.setSpeed(duckSpeed);
}
@Override
public void keyReleased(KeyEvent e) {
duck.setSpeed(0);
if (e.getKeyCode() == KeyEvent.VK_SPACE)
duck.jump();
}
};
}
private void initGame() {
duck = new Duck(names[DUCKY], 50, 60);
duck.setPos(100, horizont);
bushes.create(new String[] { names[BUSH_A], names[BUSH_B] }, 50, 60);
bushes.setSpeed(-bushSpeed);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawBackGround(g);
bushes.draw(g);
duck.draw(g);
}
@Override
public void run() {
while (running) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
updateGame();
repaint();
}
}
public void start() {
stop();
running = true;
aniamtor = new Thread(this);
aniamtor.start();
}
private void stop() {
running = false;
while (aniamtor != null && aniamtor.isAlive())
;
aniamtor = null;
}
private void updateGame() {
duck.move();
bushes.move();
if (bushes.isCollision(duck)) {
System.out.println("collision");
}
}
}