用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - java代码库

贪吃蛇java代码

2018-06-16 作者: hello0991举报

[java]代码库

public class Snake{

	//食物成员变量
	Food food = new Food();

	//蛇的成员变量
	int[] snakex = new int[150];
	int[] snakey = new int[150];
	int len =  3 , score = 0 , speed = 1; 
	int i = 20 , j = 0;
	int tempx = 0 , tempy = 0;
	int tempx1 = 0 , tempy1 = 0;
	boolean start = false;
	boolean failed = true;
	boolean isMove = false;
	boolean pause = true;


	//小蛇移动的方式
	public boolean move(){
		tempx = snakex[0];
		tempy = snakey[0];
		snakex[0] += i;
		snakey[0] += j;
		for (int m = len ; m > 0 ; m--){
			if(m != 1){
				tempx1 = snakex[m-1];
				snakex[m] = tempx1;
				tempy1 = snakey[m-1];
				snakey[m] = tempy1;
			}
			else{
				snakex[m] = tempx;
				snakey[m] = tempy;
			}
		}

		//遇到墙体
		if( snakex[0] < 210)
			snakex[0] = 770;
		if(snakex[0] >= 790)
			snakex[0] = 210;
		if(snakey[0] < 80)
			snakey[0] = 540;
		if(snakey[0] >= 560)
			snakey[0] = 80;

		// 吃食物
		if(snakex[0] == food.eatx && snakey[0] == food.eaty){  
			len ++;
			score += 50*speed;
			food.eatx = food.r.nextInt(29)*20+210;
			food.eaty = food.r.nextInt(24)*20+80;
			for(int k = 0 ; k < len ; k++){
				if(food.eatx == snakex[k] && food.eaty == snakey[k]){
					food.eatx = food.r.nextInt(29)*20+210;
					food.eaty = food.r.nextInt(24)*20+80;
				}
			}
		}
		// 如果蛇头碰到自己的身体游戏结束
		for (int i = 1 ; i < len; i ++){
			if (snakex[0] == snakex[i] && snakey[0] == snakey[i]){
				failed = false;
				start = false;
			}
        }


		//分数越高速度越快
		if(score == 150)
			speed = 2;
		if(score == 450)
			speed = 3;
		if(score == 900)
			speed = 4;
		if(score == 1500)
			speed = 5;
		if(score == 2250)
			speed = 6;
		if(score == 3150)
			speed = 7;

		return isMove = false;
	}

	//蛇的初始化
	public void setup(){
		i = 20;
		j = 0;
		len = 3;
		score = 0;
		speed = 1;
		snakex[0] = 310; snakex[1] = 290; snakex[2] = 270;
		snakey[0] = 300; snakey[1] = 300; snakey[2] = 300;
	}
}

[代码运行效果截图]


贪吃蛇java代码

[源代码打包下载]




网友评论    (发表评论)

共1 条评论 1/1页

发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...