資源描述:
《Java編寫(xiě)的貪吃蛇游戲代碼》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在工程資料-天天文庫(kù)。
1、貪吃蛇:看了傳智博客的視頻整理出來(lái)的代碼Snake類(lèi)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();//蛇的坐標(biāo)privateSetlistener=newHashSet();//蛇沒(méi)身體要初
3、始化publicSnake(){init();}publicvoidinit(){//顯示區(qū)最中間點(diǎn)intx=Global.WIDTH/2;inty=Global.HEIGHT/2;//初始化身體節(jié)點(diǎn)for(inti=0;i<3;i++){//添加節(jié)點(diǎn)body.addLast(newPoint(x--,y));//蛇頭在右邊默認(rèn)方向?yàn)橛襬ldDirection=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;//原坐標(biāo)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();}//內(nèi)部類(lèi)privateclassSnakeDriverimplementsRunnable{publicvoidrun(){while(life){move();for(SnakeListenerl:listener){