Java实现简单的贪吃蛇

这两天学着做了一个简单的贪吃蛇,只是为了练习用,所以很多地方都不完美

实现方式是用链表,代码中有详细注释


活动区域Yard:

<span style="font-size:14px;">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.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;


public class Yard extends Frame {
	// 活动区域
	private static final int ROWS = 30;// 行数
	private static final int COLS = 30;// 列数
	private static final int BLOCK_SIZE = 15;// 格子尺寸
	
	private Font fontGameOver = new Font("宋体", Font.BOLD, 50);//字体
	private int score = 0;// 分数

	Image offScreenImage = null;// 创建一个位图,防止闪烁

	Snake snake = new Snake(this);// 创建一个蛇
	Egg e = new Egg();// 随机创建一个蛋;

	PaintThread paintThread = new PaintThread();
	private boolean gameOver=false;//判断游戏是否结束

	public static int getROWS() {
		return ROWS;
	}

	public static int getCOLS() {
		return COLS;
	}

	public static int getBLOCK_XIZE() {
		return BLOCK_SIZE;
	}

	public int getScore() {
		return score;
	}

	public void launch() {// 设置窗体
		this.setLocation(300, 300);// 窗口出现位置
		this.setSize(COLS * BLOCK_SIZE, ROWS * BLOCK_SIZE);// 窗口大小
		// 添加关闭事件
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		this.setVisible(true);// 窗口是否显示

		this.addKeyListener(new KeyMonitor());// 监听按键
		new Thread(paintThread).start();
		/// 启动线程
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new Yard().launch();
	}

	public void setScore(int score) {// 设置分数
		this.score = score;
	}

	@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, i * BLOCK_SIZE, COLS * BLOCK_SIZE, BLOCK_SIZE * i);
		}
		for (int i = 1; i < ROWS; i++) {
			g.drawLine(i * BLOCK_SIZE, 0, BLOCK_SIZE * i, ROWS * BLOCK_SIZE);
		}

		g.setColor(Color.YELLOW);
		g.drawString("score:" + score, 10, 60);// 画分数

		if(gameOver) {
			g.setFont(fontGameOver);
			g.drawString("游戏结束", 120, 180);
			
			paintThread.pause();
		}
		
		g.setColor(c);

		snake.eat(e);
		snake.draw(g);// 画蛇
		e.draw(g);// 画蛋
	}

	@Override
	public void update(Graphics g) {
		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 stop() {
		gameOver=true;//游戏结束
	}

	private class PaintThread implements Runnable {
		private boolean running = true;
		private boolean pause = false;
		public void run() {
			while(running) {
				if(pause) continue; 
				else repaint();
				
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
		public void pause() {
			this.pause = true;
		}
		
		public void reStart() {
			this.pause = false;
			snake = new Snake(Yard.this);
			gameOver = false;
		}
		
		public void gameOver() {
			running = false;
		}
		
	}

	private class KeyMonitor extends KeyAdapter {
		// 监听键值
		@Override
		public void keyPressed(KeyEvent e) {
			 int key = e.getKeyCode();
			 if(key == KeyEvent.VK_F2) {
			 paintThread.reStart();
			 }
			snake.keyPressed(e);
		}
		
	}
}
</span>

蛇Snake

<span style="font-size:14px;">import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;


public class Snake {

	private Node head = null;// 头结点
	private Node tail = null;// 尾结点
	private int size = 0;// 结点个数

	private Node node = new Node(20, 30, Direction.LEFT);// 初始结点(蛇)
	private Yard y;//在哪个范围内

	public Snake(Yard y) {
		head = node;
		tail = node;
		size = 1;
		this.y=y;
	}

	public void addToTail() {// 结点添加到尾巴
		Node node = null;
		switch (tail.dir) {
		case LEFT:
			node = new Node(tail.row, tail.col + 1, tail.dir);// 向左新建结点
			break;
		case RIGHT:
			node = new Node(tail.row, tail.col - 1, tail.dir);
			break;
		case UP:
			node = new Node(tail.row + 1, tail.col, tail.dir);
			break;
		case DOWN:
			node = new Node(tail.row - 1, tail.col, tail.dir);
			break;
		}
		// 添加尾结点
		tail.next = node;
		node.prev = tail;
		tail = node;
		size++;
	}

	public void addToHead() {// 结点添加到头
		Node node = null;
		switch (head.dir) {
		case LEFT:
			node = new Node(head.row, head.col - 1, head.dir);
			break;
		case UP:
			node = new Node(head.row - 1, head.col, head.dir);
			break;
		case RIGHT:
			node = new Node(head.row, head.col + 1, head.dir);
			break;
		case DOWN:
			node = new Node(head.row + 1, head.col, head.dir);
			break;
		}
		node.next = head;
		head.prev = node;
		head = node;
		size++;
	}

	private void deleteFromTail() {
		if (size == 0)
			return;
		tail = tail.prev;
		tail.next = null;
	}

	private void checkDead() {
		// 检验是否死亡
		if(head.row < 2 || head.col < 0 || head.row > Yard.getROWS()|| head.col > Yard.getCOLS())  {
			y.stop();
		}
		
		for(Node n = head.next; n != null; n = n.next) {
			if(head.row == n.row && head.col == n.col) {
				y.stop();
			}
		}
	}
	
	private void move() {// 蛇移动
		addToHead();// 把尾巴结点添加到头
		deleteFromTail();
		checkDead();
	}

	public void draw(Graphics g) {// 画结点
		if (size <= 0)
			return;
		move();
		for (Node n = head; n != null; n = n.next) {
			n.draw(g);
		}
	}

	private class Node {
		int w = Yard.getBLOCK_XIZE();// 结点宽度
		int h = Yard.getBLOCK_XIZE();// 结点高度
		int row, col;// 结点位置
		Direction dir = Direction.LEFT;// 初始结点向左
		Node next = null;// 下一节
		Node prev = null;// 前一节

		Node(int row, int col, Direction dir) {
			this.row = row;
			this.col = col;
			this.dir = dir;
		}

		void draw(Graphics g) {// 画出结点
			Color c = g.getColor();
			g.setColor(Color.black);
			g.fillRect(Yard.getBLOCK_XIZE() * col, Yard.getBLOCK_XIZE() * row, w, h);
			g.setColor(c);
		}
	}

	public void eat(Egg e) {
		if(this.getRect().intersects(e.getRect())) {
			e.reAppear();
			this.addToHead();
			y.setScore(y.getScore() + 5);
		}
	}

	private Rectangle getRect() {
		return new Rectangle(Yard.getBLOCK_XIZE() * head.col, Yard.getBLOCK_XIZE() * head.row, head.w, head.h);
	}

	public void keyPressed(KeyEvent e) {
		int key = e.getKeyCode();
		switch (key) {
		case KeyEvent.VK_LEFT:
			if (head.dir != Direction.RIGHT)
				head.dir = Direction.LEFT;
			break;
		case KeyEvent.VK_RIGHT:
			if (head.dir != Direction.LEFT)
				head.dir = Direction.RIGHT;
			break;
		case KeyEvent.VK_UP:
			if (head.dir != Direction.DOWN)
				head.dir = Direction.UP;
			break;
		case KeyEvent.VK_DOWN:
			if (head.dir != Direction.UP)
				head.dir = Direction.DOWN;
			break;
		}
	}
}
</span>

目标物体Egg:

<span style="font-size:14px;">import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Random;

public class Egg {
	int row,col;
	int w=Yard.getBLOCK_XIZE();
	int h=Yard.getBLOCK_XIZE();
	private static Random r=new Random();//蛋的随机生成位置
	private Color color=Color.green;//蛋初始颜色
	
	public int getRow() {
		return row;
	}

	public void setRow(int row) {
		this.row = row;
	}

	public int getCol() {
		return col;
	}

	public void setCol(int col) {
		this.col = col;
	}

	
	public Egg(int row, int col) {
		this.row = row;
		this.col = col;
	}
	
	public Egg(){
		this(r.nextInt(Yard.getROWS()-2)+2, r.nextInt(Yard.getCOLS()));
	}
	
	public void reAppear(){//重新设定蛋的位置
		this.row = r.nextInt(Yard.getROWS()-2) + 2;
		this.col = r.nextInt(Yard.getCOLS());
	}
	
	public Rectangle getRect() {
		return new Rectangle(Yard.getBLOCK_XIZE() * col, Yard.getBLOCK_XIZE() * row, w, h);
	}
	
	void draw(Graphics g) {// 画出蛋
		Color c = g.getColor();
		g.setColor(color);
		g.fillOval(Yard.getBLOCK_XIZE() * col, Yard.getBLOCK_XIZE() * row, w, h);
		g.setColor(c);
		if(color==Color.green){
			color=color.red;
		}else{
			color=color.green;
		}
	}
}
</span>

方向direction

<span style="font-size:14px;">public enum Direction {
	LEFT,RIGHT,UP,DOWN
}
</span>



评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值