📄 food.java
字号:
package food;
import java.awt.*;
import javax.swing.*;
import java.util.*;//使用其中的Random类
import system.*;
import snake.*;
//食物类
public class Food{
private MainFrame mainFrame;
private Image[] images;//食物的图片数组
private Image current_image;//食物当前的图片
//食物的位置
private int x;
private int y;
//用于产生食物的随机位置,分别为x,y坐标的最大值
private int iX;
private int iY;
//食物的大小
public static final int WIDTH = 20;
public static final int HEIGHT = 20;
//图片总数量
public static final int AMOUNT = 16;
public Food(MainFrame frame){
this.mainFrame = frame;
this.iX = 25;
this.iY = 25;
this.images = new Image[Food.AMOUNT];
//取得食物图片
for(int i = 1; i <= this.images.length; i++){
this.images[i - 1] = this.loadImage(Config.URL_FOOD+"Food_"+i+".gif");
}
//初始化食物图片和位置
this.changeLocation();
}
//加载图片
public Image loadImage(String fileName){
return new ImageIcon(fileName).getImage();
}
//设置食物的位置
public void setLocation(int x, int y){
this.x = x;
this.y = y;
}
//给食物设置一个随机位置
public void changeLocation(){
do{
Random r = new Random();
this.x = r.nextInt(this.iX) * 20;
this.y = r.nextInt(this.iY) * 20;
}
//当食物产生在蛇身上时,重新产生
while(this.isOnSnake());
this.changeImage();//更新食物的图片
}
//食物是否产生在了贪吃蛇的身上
public boolean isOnSnake(){
Snake s = this.mainFrame.getSnake();
for(int i = 0; i < s.size(); i++){
Block b = (Block)s.get(i);
if(this.x == b.getX() && this.y == b.getY()){
return true;
}
}
return false;
}
//返回食物的图片
public Image getImage(){
return this.current_image;
}
//改变食物的图片为一个随机图片
public void changeImage() {
Random r = new Random();
int i = r.nextInt(Food.AMOUNT);
this.current_image = this.images[i];
}
public int getX(){
return this.x;
}
public int getY(){
return this.y;
}
}//:~zj
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -