import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class GamePanel extends JPanel implements KeyListener {
	BufferedImage image;// 主图片
	Graphics2D g2;// 绘图工具，美工
	Dinosaur golden;// 狗蛋

	boolean finish = false;// 游戏结束

	static final int FRESH = 20;// 刷新时间，毫秒

	BackgroundImgae background;// 背景对象

	List<Obstacle> list = new ArrayList<Obstacle>();// 碰瓷的团伙

	int addObstacleTimer = 0;

	int score = 0;// 得分
	int addScoreTimer = 0;

	public GamePanel() {
		image = new BufferedImage(800, 300, BufferedImage.TYPE_INT_BGR);
		g2 = image.createGraphics();
		golden = new Dinosaur();
		background = new BackgroundImgae();
		list.add(new Obstacle());
		FreshThread t = new FreshThread(this);// 刷新线程
		t.start();
	}

	private void paintImage() {// 绘制图片
		golden.move();// 让狗蛋移动
		background.roll();

		g2.drawImage(background.image, 0, 0, this);// 绘制背景

		// Rectangle rt = golden.getHeadBounds();
		// g2.setColor(Color.BLACK);
		// g2.fillRect(rt.x, rt.y, rt.width, rt.height);
		//
		// rt = golden.getfeedBounds();
		// g2.fillRect(rt.x, rt.y, rt.width, rt.height);

		g2.drawImage(golden.image, golden.x, golden.y, this);// 绘制恐龙

		if (addObstacleTimer >= 1300) {
			Random r = new Random();
			int a = r.nextInt(100);
			if (a > 40) {
				list.add(new Obstacle());
			}
			addObstacleTimer = 0;
		}

		for (int i = 0; i < list.size(); i++) {
			Obstacle o = list.get(i);
			o.move();
			// rt = o.getBounds();
			// g2.fillRect(rt.x, rt.y, rt.width, rt.height);
			g2.drawImage(o.image, o.x, o.y, this);// 绘制障碍

			if (o.getBounds().intersects(golden.getHeadBounds()) || o.getBounds().intersects(golden.getfeedBounds())) {
				gameOver();
			} else {
				if (o.x < golden.x) {
					score += o.getScore();
				}

			}

		}

		// if (addScoreTimer >= 500) {
		// score += 10;
		// addScoreTimer = 0;
		// }
		g2.setColor(Color.BLACK);
		g2.setFont(new Font("黑体", Font.BOLD, 24));
		g2.drawString(String.format("%05d", score), 700, 30);

		addObstacleTimer += FRESH;// 让添加障碍计时器计时
		addScoreTimer += FRESH;// 让添加得分计时器计时

	}

	public void gameOver() {
		finish = true;
	}

	@Override
	public void paint(Graphics g) {
		paintImage();
		g.drawImage(image, 0, 0, this);
	}

	public boolean isFinish() {
		return finish;
	}

	@Override
	public void keyTyped(KeyEvent e) {// 按键的类型
		// TODO Auto-generated method stub

	}

	@Override
	public void keyPressed(KeyEvent e) {// 按键按下
		int code = e.getKeyCode();// 获取按下的键盘编码
		if (code == KeyEvent.VK_SPACE) {
			golden.jump();
		}

	}

	@Override
	public void keyReleased(KeyEvent e) {// 按键抬起
		// TODO Auto-generated method stub

	}

}
