苹果类:首先苹果有它自向的属性,就是在什么位置(x,y坐标),,还有就是被蛇吃掉后会自动生成一个新的苹果,
属性:x(横坐标),y(竖坐标)
方法:自动生成新的苹果(create),位置在房间内随机
package com.snake.view;
import java.util.Random;
import com.snake.activity.R;
public class Apple {
//苹果的位置
private int x,y;
private int appleColor=R.drawable.greenstar;
public static final int appleSize=24;
//苹果最大能放在哪个位置上生成
private int maxX,maxY;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getAppleColor() {
return appleColor;
}
public void setAppleColor(int appleColor) {
this.appleColor = appleColor;
}
public void setMaxX(int mx,int my){
maxX=mx;
maxY=my;
}
//重新生成苹果
public void create(){
System.out.println("生成苹果-----------");
Random random=new Random();
int x=0;y=0;
while(x==0 || y==0){
x=random.nextInt(maxX-1);
y=random.nextInt(maxY-1);
}
this.setX(x);
this.setY(y);
}
}
蛇:蛇有位置属性,以及移动和吃苹果的方法,可以获取蛇身的长度来判断是否进入下一关
package com.snake.view;
import java.util.ArrayList;
import com.snake.activity.R;
public class Snake {
//初始化蛇身
public Snake(){
sections=new ArrayList<SnakeSection>();
sections.add(new SnakeSection(1,1,0));
sections.add(new SnakeSection(2,1,0));
sections.add(new SnakeSection(3,1,0));
sections.add(new SnakeSection(4,1,R.drawable.yellowstar));
}
public ArrayList<SnakeSection> sections;
//四个方向
public static final int up=1;
public static final int down=2;
public static final int left=3;
public static final int right=4;
//蛇运动的方向,默认先向右移动
private int moveDirection=right;
//获取蛇身长度
public int getSnakeLength() {
return sections.size();
}
public int getMoveDirection(){
return moveDirection;
}
public void setMoveDirection(int moveDirection) {
this.moveDirection = moveDirection;
}
/**
*蛇移动的方法
*/

本文解析了贪吃蛇游戏的源码,包括苹果类、蛇类和房间类的详细实现。苹果类负责生成和更新苹果位置,蛇类包含蛇的位置、移动方向及吃苹果的方法。房间类则包含蛇、苹果集合,以及游戏区域的更新和绘制。通过面向对象设计,实现了游戏的基本逻辑。
最低0.47元/天 解锁文章
1261

被折叠的 条评论
为什么被折叠?



