一个能够记录用户分数的贪吃蛇
- 界面设计
分为两部分,分别是登录窗口设计和游戏界面窗口设计
登录窗口大小为300*220
游戏界面大小为1500*1000并插入一张图片做背景填充
2. 蛇的制作
//蛇的数据结构的设计
int[] snakex=new int[1300];
int[] snakey=new int[800];
int len=3;
String direction= "R";//R:右
- 蛇的随机出现
//设置一个字符串,用来存放上下左右
String[] array = new String[]{"L","R","U","D"};
//定义一个变量,随机生成0-3之间的一个数
int x = new Random().nextInt(4);
//每次生成蛇,为蛇的方向随机初始化
direction= array[x] ;
//每次开始游戏前随机生成蛇的位置
@SuppressWarnings("unused")
Random randomX = new Random();
//随机生成蛇的横坐标
int intX = new Random().nextInt(1300) + 100;
//判断随机生成的蛇的横坐标是否能被25整除,因为一个格子设定的是25,所以必须是25的倍数
while (intX % 25 != 0){
intX = new Random().nextInt(1300)+100;
}
//随机生成蛇的纵坐标
int intY = new Random().nextInt(700) + 100;
//判断随机生成的蛇的横坐标是否能被25整除,因为一个格子设定的是25,所以必须是25的倍数
while (intY % 25 != 0){
intY = new Random().nextInt(700)+100;
}
- 食物的随机出现
food.paintIcon(this, g, foodx, foody);
for(int i=1;i < len;i++){
//判断食物是否随机生成在了,蛇身上,如果是就重新生成一个食物
if(snakex[i] == foodx && snakey[i] == foody){
foodx = r.nextInt(52)*25+25;
foody = r.nextInt(20)*25+125;
}
}
- 障碍的随机出现
//画刺
for(int i = 0;i<3;i++){
thorn.paintIcon(this,g,thornx[i],thorny[i]);
}
//设置十个刺,并且为每一个刺随机初始化分配坐标
for(int i = 0;i < 10;i++){
thornx[i] =r.nextInt(50)*25+25;
thorny[i] = 75;
}