⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 yard.java

📁 用java开发的贪吃蛇程序
💻 JAVA
字号:
package com.bjsxt.snake;

import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.HeadlessException;
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 { 
	private int x, y;
	
	public static final int ROWS = 20;
	public static final int COLS = 20;
	public static final int BLOCK_SIZE = 30;
	
	private Image offImage = null;
	private PaintThread paintThread = new PaintThread();
	
	Snake s = new Snake(this);
	Egg e = new Egg(15, 6);
	
	public void gameOver() {
		paintThread.pause();
		this.repaint();
	}
	
	@Override
	public void paint(Graphics g) {
		Color c = g.getColor();
		g.setColor(Color.DARK_GRAY);
		
		for(int i=0; i<ROWS; i++) {
			g.drawLine(0, i*BLOCK_SIZE, COLS*BLOCK_SIZE, i*BLOCK_SIZE);
		}
		
		for(int i=0; i<COLS; i++) {
			g.drawLine(i*BLOCK_SIZE, 0, i*BLOCK_SIZE, ROWS*BLOCK_SIZE);
		}
		
		if(paintThread.isStop()) {
			g.setColor(Color.RED);
			g.setFont(new Font("Verdana", Font.BOLD, 60));
			g.drawString("GAME OVER", 100, 100);
		}
		
		g.setColor(c);
		
		s.draw(g);
		
		e.draw(g);
		s.eat(e);
		
		
	}

	@Override
	public void update(Graphics g) {
		if(offImage == null) {
			offImage = this.createImage(COLS * BLOCK_SIZE, ROWS * BLOCK_SIZE);
		}
		Graphics gOff = offImage.getGraphics();
		Color c = gOff.getColor();
		gOff.setColor(Color.GRAY);
		gOff.fillRect(0, 0, COLS * BLOCK_SIZE, ROWS * BLOCK_SIZE);
		paint(gOff);
		gOff.setColor(c);
		g.drawImage(offImage, 0, 0, null);
	}

	
	public void launch() {
		this.setLocation(x, y);
		this.setSize(ROWS * BLOCK_SIZE, COLS * BLOCK_SIZE);
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		this.setBackground(Color.GRAY);
		this.addKeyListener(new KeyMonitor());
		this.setVisible(true);
		
		new Thread(paintThread).start();
	}
	
	public static void main(String[] args) {
		new Yard(100, 100).launch();
	}

	public Yard(int x, int y) throws HeadlessException {
		this.x = x;
		this.y = y;
	}
	
	private class KeyMonitor extends KeyAdapter {

		@Override
		public void keyPressed(KeyEvent e) {
			s.keyPressed(e);
		}
		
	}
	
	private class PaintThread implements Runnable {
		
		private boolean stop = false;
		
		public void run() {
			while(!stop) {
				repaint();
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
		public void pause() {
			stop = true;
		}

		public boolean isStop() {
			return stop;
		}

		public void setStop(boolean stop) {
			this.stop = stop;
		}

		
		
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -