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

📄 snake.java

📁 java做的贪食蛇的游戏源码,其中各个模块都有
💻 JAVA
字号:
package cn.itcast.snake.entities;

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

import cn.itcast.snake.listener.SnakeListener;
import cn.itcast.snake.util.Global;

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 int oldDirection;
	private int newDirection;
	private LinkedList<Point> body=new LinkedList<Point>();
	private Set<SnakeListener> listeners=new HashSet<SnakeListener>();
	private Point oldTail;
	private boolean life;
	
	
	public Snake(){
		init();
	}
	public void init(){
		int x=Global.HEIGHT/2;
		int y=Global.WIDTH/2;
		life=true;
		for(int i=0;i<10;i++){
			body.addLast(new Point(x--,y));
		}
		oldDirection = newDirection = RIGHT;
	}
	
	public void move(){
		System.out.println("snake move");
		//quwei
		if(!((oldDirection+newDirection)==0)){
			oldDirection=newDirection;
		}
		oldTail=body.removeLast();
		
		
		int x=body.getFirst().x;
		int y=body.getFirst().y;
		switch(oldDirection){
		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);
		//jiatou
		body.addFirst(newHead);
	}
	public void changeDirection(int direction){
		System.out.println("snake change direction");
		
		
			newDirection=direction;
		
	
	}
	public void eatFood(){
		System.out.println("eat food");
		
		body.addLast(oldTail);
		
	}
	public boolean isEatBody(){
		System.out.println("eat body");
		
		for(int i=1;i<body.size();i++){
			if(body.get(i).equals(this.getHead()))
				return true;
		}
		return false;	
	}
	public void drawMe(Graphics g){
		System.out.println("draw me");
		g.setColor(Color.BLUE);
		for(Point p:body){
			g.fill3DRect(p.x*Global.CELL_SIZE, p.y*Global.CELL_SIZE
					, Global.CELL_SIZE, Global.CELL_SIZE, true);
		}
	}
	private class SnakeDriver implements Runnable{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			while(life){
				move();
				for(SnakeListener l:listeners){
					l.snakeMoved(Snake.this);
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}
	public void start(){
		new Thread(new SnakeDriver()).start();
	}
	public void addSnakeListener(SnakeListener l){
		if(l!=null){
			this.listeners.add(l);
		}
	}
	
	public Point getHead(){
		return body.getFirst();
	}
	public void die(){
		life=false;
	}
}

⌨️ 快捷键说明

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