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

📄 snake.java

📁 贪吃蛇
💻 JAVA
字号:
package cn.cavtc;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;

public class Snake {
	public static final int UP=1;
	public static final int DOWN=-1;
	public static final int LEFT=2;
	public static final int RIGHT=-2;
	private LinkedList<Point> body=new LinkedList<Point>();
	private Set<SnakeListener> listeners=new HashSet<SnakeListener>();
	
	private int direction,oldDir; //蛇移动的方向
	
	private Point oldTail;
	
	private boolean life;
	
	public Snake(){
		//初始化蛇
		//init();
	}
	private void init() {
		int x=Global.WIDTH/2;
		int y=Global.HEIGHT/2;
		body.clear();
		for(int i=0;i<3;i++){
			body.add(new Point(x++,y));
		}
		direction=oldDir=LEFT;
		life=true;
	}
	
	public void move(){
		System.out.println("Snake's move");
		//去尾
		oldTail=body.removeLast();
		//计算新加的头
		int x=body.getFirst().x;
		int y=body.getFirst().y;
		if(oldDir+direction!=0) oldDir=direction;
		switch(oldDir){
		case UP:
			y--;
			if(y<0) y=Global.HEIGHT-1;
			break;
		case DOWN:
			y++;
			if(y>=Global.HEIGHT) y=0;
			break;
		case LEFT:
			x--;
			if(x<0) x=Global.WIDTH-1;
			break;
		case RIGHT:
			x++;
			if(x>=Global.WIDTH) x=0;
			break;
		}
		Point newHead=new Point(x,y);
		//加头
		body.addFirst(newHead);
		
	}
	
	public void changeDirection(int dir){
		System.out.println("Snake's change direction");
		direction=dir;
		
	}
	
	public void eatFood(){
		System.out.println("Snake's eat food");
		body.addLast(oldTail);
		
	}
	
	public boolean isEatBody(){
		System.out.println("Snake eat body");
		for(int i=1;i<body.size();i++){
			if(body.get(i).equals(getHead())) return true;
		}
		return false;
	}
	
	public void drawMe(Graphics g){
		System.out.println("Draw snake");
		g.setColor(Color.RED);
		int head=1;
		for(Point p:body){
			g.fill3DRect(p.x*Global.CELL_SIZE, 
					p.y*Global.CELL_SIZE, 
					Global.CELL_SIZE, Global.CELL_SIZE, true);
			if(head==1){
				head=-1;
				g.setColor(Color.PINK);
			}
		}
		
	}
	
	private class SnakeDriver implements Runnable{

		public void run() {
			while(life){
				move();
				for(SnakeListener l:listeners){
					l.snakeMoved(Snake.this);
				}
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO 自动生成 catch 块
					e.printStackTrace();
				}
			}
			
		}
		
	}
	
	public void start(){
		init();
		new Thread(new SnakeDriver()).start();
	}
	
	public void die(){
		life=false;
	}
	
	public void addSnakeListener(SnakeListener l){
		if(l!=null){
			listeners.add(l);
		}
	}
	
	public Point getHead(){
		return body.getFirst();
	}
	
	public boolean  getLife(){
		return life;
	}

}

⌨️ 快捷键说明

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