java微型贪吃蛇(1)Yard.java Dir.java

import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Yard extends Frame {

	

	public static final int ROWS = 50;
	public static final int COLS = 50;
	public static final int BLOCK_SIZE = 10;
    private  boolean flag = true;
    Font font = new Font("宋体",Font.BOLD,50);
    PaintThread paintThread = new PaintThread();
    
    public int score = 0; 
	Egg e = new Egg();
	Snake s = new Snake(this);
    
    
	public static void main(String[] args) {
		new Yard().launch();
	}
	
	public void stop()
	{
		flag = false;
	}
	public int getScore()
	{
		return score;
	}
	public void setScore(int score)
	{
		this.score = score;
	}
  
	public void launch() {
		this.setLocation(200, 200);
		this.setSize(ROWS * BLOCK_SIZE, COLS * BLOCK_SIZE);
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent arg0) {
				System.exit(0);
			}
		});
		this.setVisible(true);
		//new Thread(new PaintThread()).start();
	    Thread t = new Thread(paintThread);
	    t.start();  
	    this.addKeyListener(new KeyMonitor());
	}

	public void paint(Graphics g) {
		Color c = g.getColor();
		g.setColor(Color.GRAY);
		g.fillRect(0, 0, ROWS * BLOCK_SIZE, COLS * BLOCK_SIZE);
		g.setColor(Color.DARK_GRAY);
		
		for (int i = 1; i < ROWS; i++) {
			g.drawLine(0, BLOCK_SIZE * i, BLOCK_SIZE * COLS, BLOCK_SIZE * i);
		}
		
		for (int i = 1; i < ROWS; i++) {
			g.drawLine(BLOCK_SIZE * i, 0, BLOCK_SIZE * i, BLOCK_SIZE * ROWS);
		}
        
		g.setColor(Color.YELLOW);
		g.drawString("score:" + this.score , 10, 60);
		g.setColor(c);
		e.draw(g);
		s.eat(e);
		s.draw(g);
		g.setColor(Color.RED);
		
		if(flag == false)
		{   
			g.setFont(font);
			g.drawString("Game Over", 150, 250);
			paintThread.gameOver();
		}
			
	}
	
	Image offScreenImage =null;//创建一个image对象  
	@Override
	public void update(Graphics g){
		if(offScreenImage == null){
			offScreenImage = this.createImage(COLS * BLOCK_SIZE,ROWS * BLOCK_SIZE);
			//如果image对象为空   用本画板创建这个缓冲区
		}
		Graphics gOff = offScreenImage.getGraphics();//将本缓冲区内的图像取出
		paint(gOff);//绘制
		g.drawImage(offScreenImage, 0, 0, null);
	}
	
	
	private class PaintThread implements Runnable{
		private boolean running = true;
		
		public void run()
		{
			while(running)
			{
				repaint();
				try{
					Thread.sleep(100);
				}catch(InterruptedException e){
					e.printStackTrace();
				}
			}
		}
	   
		public void gameOver()
		{
			running = false;
		}
		
	}
	
	private class KeyMonitor extends KeyAdapter{

		@Override
		public void keyPressed(KeyEvent e) {
		     s.keyPressed(e);
		}
		
	}

}



public enum Dir {
      L,R,V,D
}


你可能感兴趣的:(java)