package langxisnake;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Yard extends JFrame/*JPanel*/{
public static final int ROWS=30;
public static final int COLS=30;
public static final int BLOCK_SIZE=15;
PaintThread paintThread=new PaintThread();
private boolean gameOver=false;
private int score=0;
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
Snake snake=new Snake(this);
Egg e=new Egg();
Image offScreenImage=null;//双缓冲---解决闪动问题(刷背景)
@Override
public void update(Graphics g) {
// TODO Auto-generated method stub
if(offScreenImage==null){
offScreenImage=this.createImage(COLS*BLOCK_SIZE,ROWS*BLOCK_SIZE);
}
Graphics gOff=offScreenImage.getGraphics();
paint(gOff);
g.drawImage(offScreenImage,0,0,null);
}
public void launch(){
this.setLocation(300,100);
this.setSize(COLS*BLOCK_SIZE,ROWS*BLOCK_SIZE);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*
* 处理关闭的窗口的函数
* this.addWindowListener(new WindowAdapter(){
* System.exit(0);
* })
*/;
this.setVisible(true);
this.addKeyListener(new KeyNonitor());//注册监听
// new Thread (new PaintThread()).start();
new Thread(paintThread).start();
}
public void stop(){
gameOver=true;
}
public static void main(String[] args) {
/* JFrame frame=new JFrame();
Yard y=new Yard();
y.launch();
frame.add(y);
// frame.pack();
frame.setBounds(300, 100, COLS*BLOCK_SIZE+10, ROWS*BLOCK_SIZE+10);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);*/
new Yard().launch();
}
@Override
public void paint(Graphics g) {//画小格
Color c=g.getColor();
g.setColor(Color.gray);
g.fillRect(0, 0, COLS*BLOCK_SIZE,ROWS*BLOCK_SIZE);
g.setColor(Color.DARK_GRAY);
//画出横线
for(int i=1;i<ROWS;i++){
g.drawLine(0, BLOCK_SIZE*i, COLS*BLOCK_SIZE, BLOCK_SIZE*i);
}
for(int i=1;i<COLS;i++){
g.drawLine(BLOCK_SIZE*i,0, BLOCK_SIZE*i,ROWS*BLOCK_SIZE);
}
g.setColor(Color.YELLOW);
g.drawString("Score:"+score, 10, 60);
if(gameOver){
g.setFont(new Font("宋体",Font.BOLD|Font.HANGING_BASELINE,50));
g.drawString("Game over!", 100, 250);
paintThread.gameOver();
}
g.setColor(c);
snake.eat(e);
snake.draw(g);
e.draw(g);
}
private class PaintThread implements Runnable{
private boolean running=true;
@Override
public void run() {
while(running){
repaint();
try{
Thread.sleep(300);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public void gameOver(){
running=false;
}
}
private class KeyNonitor extends KeyAdapter{
@Override
public void keyPressed(KeyEvent e) {
snake.keyPressed(e);
}
}
}