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

📄 node.java

📁 贪吃蛇
💻 JAVA
字号:
package com.snake;

import java.awt.*;
import java.util.Random;

public class Node {
	
	public static final int WIDTH = 10;
	int x,y;
	boolean isFood = false;	
	
	public Node(int x, int y) {
		this.x = x;
		this.y = y;
	}
	public Node(int x, int y, boolean isFood) {
		this(x, y);
		this.isFood = isFood;
	}
	/**
	 * 
	 * 生成食物结点
	 *
	 */
	public static Node createFood(java.util.List<Node> snake) {
		Random r = new Random();
		boolean can = false;
		int x, y;
		while(true) {
			x = r.nextInt(GreedySnake.GAME_WIDTH - 10); 		
			y = r.nextInt(GreedySnake.GAME_HEIGHT - 16);
			/*4为离左边界的距离,30为离上面的距离*/
			if(x < 3 || y < 30 || (x - 4) % (Node.WIDTH + 1) != 0 || (y - 30) % (Node.WIDTH + 1) != 0 )
				continue;
			/*检查随机产生的x,y是否可以构成为食物*/
			for(int i=0; i<snake.size(); i++) { 
				Node n = snake.get(i);
				if(n.x == x || n.y == y) {
					can = false;
					break;
				}
				else can = true; //x, y可以生成有效食物
			}
			if(true == can)  break; 
		}	
		return new Node(x, y, true);
	}
	/**
	 * 
	 * 绘制结点
	 *
	 */
	public void draw(Graphics g) {
		Color c = g.getColor();
		/*食物和蛇身用不同的颜色来绘制*/
		if(true == isFood) 
			g.setColor(Color.MAGENTA);
		else 
			g.setColor(Color.WHITE);
		g.fillRect(x, y, WIDTH, WIDTH);
		g.setColor(c);
	}
	/**
	 * 
	 * 节点的所包含的范围矩形
	 * 
	 */
	public Rectangle getRect() {
		return new Rectangle(x, y, WIDTH, WIDTH);
	}
	
	/**
	 * 
	 * 检查是否自己撞到自己
	 * 
	 */
	public boolean collidesWithSnake(java.util.List<Node> snakeList) {
		
		for(int i=0; i<snakeList.size(); i++) {
			Node n = snakeList.get(i);
			/*判断是否本身,是否和其他结点相碰撞*/
			if(this != n) {
				if(this.getRect().intersects(n.getRect())) 				
					return true; 
			}
		}
		return false;
	}	
	
	
}

⌨️ 快捷键说明

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