資源描述:
《貪吃蛇源代碼》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫(kù)。
1、//文件名:SnakeMIDlet.javapackagesnake;importjavax.microedition.midlet.*;importjavax.microedition.lcdui.*;publicclassSnakeMIDletextendsMIDlet{SnakeCanvasdisplayable=newSnakeCanvas();publicSnakeMIDlet(){Display.getDisplay(this).setCurrent(displayable);}publicvoidstartApp(){}publicvoi
2、dpauseApp(){}publicvoiddestroyApp(booleanunconditional){}}//文件名:SnakeCanvas.javapackagesnake;importjava.util.*;importjavax.microedition.lcdui.*;/***貪吃蛇游戲*/publicclassSnakeCanvasextendsCanvasimplementsRunnable{/**存儲(chǔ)貪吃蛇節(jié)點(diǎn)坐標(biāo),其中第二維下標(biāo)為0的x坐標(biāo),第二維下標(biāo)是1的y坐標(biāo)*/int[][]snake=newint[200][2];/*
3、*已經(jīng)使用的節(jié)點(diǎn)數(shù)量*/intsnakeNum;/**貪吃蛇運(yùn)動(dòng)方向,0向上,1向下,2向左,3向右*/intdirection;/*移動(dòng)方向*//**向上*/privatefinalintDIRECTION_UP=0;/**向下*/privatefinalintDIRECTION_DOWN=1;/**向左*/privatefinalintDIRECTION_LEFT=2;/**向右*/privatefinalintDIRECTION_RIGHT=3;/**游戲區(qū)域?qū)挾?/intwidth;/**游戲區(qū)域高度*/intheight;/**蛇身單元寬度*
4、/privatefinalbyteSNAKEWIDTH=4;/**是否處于暫停狀態(tài),true暫停*/booleanisPaused=false;/**是否處于運(yùn)行狀態(tài),true運(yùn)行*/booleanisRun=true;/**時(shí)間間隔*/privatefinalintSLEEP_TIME=300;/**食物的X坐標(biāo)*/intfoodX;/**食物的Y坐標(biāo)*/intfoodY;/**食物的閃爍控制*/booleanb=true;/**Random對(duì)象*/Randomrandom=newRandom();publicSnakeCanvas(){//初始化i
5、nit();width=this.getWidth();height=this.getHeight();//啟動(dòng)線程newThread(this).start();}/***初始化開始數(shù)據(jù)*/privatevoidinit(){//初始化節(jié)點(diǎn)數(shù)量snakeNum=7;//初始化節(jié)點(diǎn)數(shù)據(jù)for(inti=0;i6、ctedvoidpaint(Graphicsg){//清屏g.setColor(0xffffff);g.fillRect(0,0,width,height);g.setColor(0);//繪制蛇身for(inti=0;i7、inti=snakeNum-1;i>0;i--){snake[0]=snake[i-1][0];snake[1]=snake[i-1][1];}//第一個(gè)單元格移動(dòng)switch(direction){caseDIRECTION_UP:snake[0][1]=snake[0][1]-SNAKEWIDTH;break;caseDIRECTION_DOWN:snake[0][1]=snake[0][1]+SNAKEWIDTH;break;caseDIRECTION_LEFT:snake[0][0]=snake[0][0]-SNAKEWIDTH;break;c
8、aseDIRECTION_RIGHT:snake[0][0]=snake[0][0]+SNAK