整体代码比较简单适合java新手的练习代码,只有5个类
- 项目结构
NUM这个类可以设置食物和蛇的大小
public class NUM {
static int width=15;//蛇食物的宽度
static int height=15;//蛇食物的高度
}
如果将15换成30
15是这样
30是这样
Snake类是蛇类,定义蛇的属性及状态
蛇类中最重要的方法就是鼠标监听事件控制蛇的行动
/**
* 蛇的移动
* @param e键盘事件
*/
public void move(int e, Point point){
switch(e){
case KeyEvent.VK_LEFT:
if (!snakeRIGHT) {
snakeUP=false;
snakeDOWN=false;
snakeLEFT=true;
snakeRIGHT=false;
Point pl = new Point(snakePoint.get(0).x-1,snakePoint.get(0).y);
snakePoint.add(0, pl);
if(!isEat(point)){
snakePoint.remove(snakeLength);
}else{
snakeLength++;
}
}
break;
case KeyEvent.VK_RIGHT:
if (!snakeLEFT) {
snakeUP=false;
snakeDOWN=false;
snakeLEFT=false;
snakeRIGHT=true;
Point pr = new Point(snakePoint.get(0).x+ 1,snakePoint.get(0).y);
snakePoint.add(0, pr);
if(!isEat(point)){
snakePoint.remove(snakeLength);
}else{
snakeLength++;
}
}
break;
case KeyEvent.VK_UP:
if (!snakeDOWN) {
snakeUP=true;
snakeDOWN=false;
snakeLEFT=false;
snakeRIGHT=false;
Point pu = new Point(snakePoint.get(0).x,snakePoint.get(0).y - 1);
snakePoint.add(0, pu);
if(!isEat(point)){
snakePoint.remove(snakeLength);
}else{
snakeLength++;
}
}
break;
case KeyEvent.VK_DOWN:
if (!snakeUP) {
snakeUP=false;
snakeDOWN=true;
snakeLEFT=false;
snakeRIGHT=false;
Point pd = new Point(snakePoint.get(0).x,snakePoint.get(0).y + 1);
snakePoint.add(0, pd);
if(!isEat(point)){
snakePoint.remove(snakeLength);
}else{
snakeLength++;
}
}
break;
default:
break;
}
}
食物类中最重要的方法就是食物的出现
/**
*
* @param p食物
*/
public void setFoodPoint(Vector<Point> p,int width,int height) {
Random r = new Random();
while (true) {
int x = r.nextInt(width/foodWidth);
int y = r.nextInt(height/foodHeight);
for (int i = 0; i < p.size(); i++) {
if(x==p.get(i).x&&y==p.get(i).y){
continue;
}
}
foodPoint.x = x;
foodPoint.y = y;
return ;
}
}
- 源码
链接: https://pan.baidu.com/s/1H4geNkwuv-Kdk9etltihwg 提取码: qiah
点击查看更多内容
10人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦