欢迎来到天天文库
浏览记录
ID:39889875
大小:60.50 KB
页数:10页
时间:2019-07-14
《Java编写的贪吃蛇游戏代码》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、贪吃蛇:看了传智博客的视频整理出来的代码Snake类packagesnake;importjava.awt.Color;importjava.awt.Graphics;importjava.awt.Point;importjava.util.HashSet;importjava.util.LinkedList;importjava.util.Set;publicclassSnake{//定义方向的常量publicstaticfinalintUP=-1;publicstaticfinalintDOWN=1;pu
2、blicstaticfinalintLEFT=2;publicstaticfinalintRIGHT=-2;privateintoldDirection,newDirection;privatePointoldTail;privatebooleanlife;privateLinkedListbody=newLinkedList();//蛇的坐标privateSetlistener=newHashSet();//蛇没身体要初
3、始化publicSnake(){init();}publicvoidinit(){//显示区最中间点intx=Global.WIDTH/2;inty=Global.HEIGHT/2;//初始化身体节点for(inti=0;i<3;i++){//添加节点body.addLast(newPoint(x--,y));//蛇头在右边默认方向为右oldDirection=newDirection=RIGHT;life=true;}}publicvoidmove(){System.out.println("Snake's
4、move");if(!((oldDirection+newDirection)==0)){oldDirection=newDirection;}//1.去尾oldTail=body.removeLast();intx=body.getFirst().x;//原坐标inty=body.getFirst().y;switch(oldDirection){caseUP:y--;if(y<0){y=Global.HEIGHT-1;}break;caseDOWN:y++;if(y>=Global.HEIGHT){y=0
5、;}break;caseLEFT:x--;if(x<0){x=Global.WIDTH-1;}break;caseRIGHT:x++;if(x>=Global.WIDTH){x=0;}break;}PointnewHead=newPoint(x,y);//2.加头body.addFirst(newHead);}publicvoidchangeDirection(intdirection){System.out.println("Snake'schangeDirection");/*if(!(direction
6、+this.direction==0)){this.direction=direction;}*/newDirection=direction;}publicvoiddie(){life=false;}publicvoideatFood(){System.out.println("Snake'seatFood");body.addLast(oldTail);}publicbooleanisEatBody(){System.out.println("Snake'sisEatBody");for(inti=1;i
7、
8、al.CELL_SIZE,Global.CELL_SIZE,true);}//得到蛇头的方法publicPointgetHead(){returnbody.getFirst();}//内部类privateclassSnakeDriverimplementsRunnable{publicvoidrun(){while(life){move();for(SnakeListenerl:listener){
此文档下载收益归作者所有