簡(jiǎn)單的貪吃蛇源碼分析_第1頁(yè)
簡(jiǎn)單的貪吃蛇源碼分析_第2頁(yè)
簡(jiǎn)單的貪吃蛇源碼分析_第3頁(yè)
簡(jiǎn)單的貪吃蛇源碼分析_第4頁(yè)
簡(jiǎn)單的貪吃蛇源碼分析_第5頁(yè)
已閱讀5頁(yè),還剩22頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

念和操作方式。具體細(xì)節(jié)先賣一個(gè)關(guān)子,作品準(zhǔn)備參加這次第二屆大學(xué)生android應(yīng)用開Snake*TileView是基于AndroidView類實(shí)現(xiàn)的方塊圖類,用來支撐上層類的調(diào)用,繪制方塊圖的顯示界面。通過這些代碼,能打之了解如何擴(kuò)展View*SnakeViewTileView,實(shí)現(xiàn)了游戲邏輯和具體的*SnakeActivity類。PS:android2.2下左右按鍵操作,現(xiàn)在大多數(shù)android機(jī)是沒有方向鍵的吧。[java]view</pre><p></p><p><strong></strong></p><prename="code"class="java">packagecom.example.android.snake;importimportimportimportimportimportimportimport*TileView:aView-variantdesignedforhandlingarraysof"icons"or**publicclassTileViewextendsView{*Parameterscontrollingthesizeofthetilesandtheirrangewithin*Width/Heightareinpixels,andDrawableswillbescaledtofitto*dimensions.X/YTileCountsarethenumberoftilesthatwillbeprotectedstaticintmTileSizetileprotectedstaticintmXTileCountX量protectedstaticintmYTileCount;//Y量privatestaticintmXOffsetpixelprivatestaticint*Ahashthatmapsintegerhandlesspecifiedbythesubclasserto*drawablethatwillbeusedforthat*著不同種類的bitmap圖。通過resetTiles,loadTile,將游戲中* privateBitmap[]mTileArray;*Adimensionalarrayofintegersinwhichthenumberrepresents*indexofthetilethatshouldbedrawnatthat*整個(gè)界面內(nèi)每個(gè)tile位置應(yīng)該繪制的tile**setTile、clearTile*privateint[][]mTileGrid;privatefinalPaintmPaint=newPaint();publicTileView(Contextcontext,AttributeSetattrs,intdefStyle)super(context,attrs,tileSize。參考: TypedArraya=context.obtainStyledAttributes(attrs,R.styleable.TileVimTileSize=a.getInt(R.styleable.TileView_tileSize, publicTileView(Contextcontext,AttributeSetattrs)super(context, TypedArraya=context.obtainStyledAttributes(attrs,R.styleable.TileVimTileSize=a.getInt(R.styleable.TileView_tileSize, *ReststheinternalarrayofBitmapsusedfordrawingtiles,*setstheumindexoftilestobe*重置mTileArray,在游戲初始的時(shí)候使用**@parampublicvoidresetTiles(inttilecount)mTileArray=new protectedvoidonSizeChanged(intw,inth,intoldw,intoldh)mXTileCount=(int)Math.floor(w/mYTileCount=(int)Math.floor(h/mTileSize);//mXOffsetmYOffsetmXOffset=((w-(mTileSize*mXTileCount))/mYOffset=((h-(mTileSize*mYTileCount))/2);mTileGrid=new *FunctiontosetthespecifiedDrawableasthetilefora*integer*加載具體的磚塊到磚塊字典*即將對(duì)應(yīng)的磚塊的對(duì)應(yīng)的加載到mTileArray數(shù)組*@param*@parampublicvoidloadTile(intkey,Drawabletile)//Drawablebitmap的轉(zhuǎn)換。由于外部程序使用的//drawable格式,而我們的數(shù)組是bitmap格式,方便最終的繪bitmap的轉(zhuǎn)換。Bitmapbitmap=Bitmap.createBitmap(mTileSize,mTileSize,BitmCanvascanvas=newtile.setBounds(0,0,mTileSize,mTileArray[key]= *Usedtoindicatethataparticulartile(setwithloadTileandreferen*byaninteger)shouldbedrawnatthegivenx/ycoordinatesduring*nextinvalidate/draw**@param*@param*@parampublicvoidsetTile(inttileindex,intx,inty)mTileGrid[x][y]=}*Resetsalltilesto0***setTile()publicvoidclearTiles()for(intx=0;x<mXTileCount;x++)for(inty=0;y<mYTileCount;y++)setTile(0,x, *@seepublicvoidonDraw(Canvascanvas)for(intx=0;x<mXTileCount;x+=1)for(inty=0;y<mYTileCount;y+=1)if(mTileGrid[x][y]>0)mXOffset+x*mYOffset+y*}}}}}[java]viewpackageimportimportimportimportimportimportimportimportimportimportimportimport*SnakeView:implementationofasimplegameofpublicclassSnakeViewextendsTileView{ privatestaticfinalStringTAG="SnakeView"; *Currentmodeofapplication:READYtorun,RUNNING,oryouhaveal*lost.staticfinalintsareusedinsteadofanenumfor*privateintmMode=publicstaticfinalintPAUSE0;//publicstaticfinalintREADY1;//publicstaticfinalintRUNNING2;//publicstaticfinalintLOSE3;//結(jié)束,輸了游戲*Currentdirectionthesnakeis*privateintmDirection=privateintmNextDirection=privatestaticfinalintNORTH=privatestaticfinalintSOUTH=privatestaticfinalintEAST=privatestaticfinalintWEST=4;*LabelsforthedrawablesthatwillbeloadedintotheTileView*privatestaticfinalintRED_STAR=privatestaticfinalintYELLOW_STAR=privatestaticfinalintGREEN_STAR=3; *mScore:usedtotrackthenumberofapplescapturedmMoveDelay:numberof *millisecondsbetweensnakemovements.Thiswilldecreaseasapples*privatelongmScore0;// privatelongmMoveDelay600;//每移動(dòng)一步的延時(shí)。初始時(shí)設(shè)置為600ms9折 *mLastMove:trackstheabsolutetimewhenthesnakelastmoved,andisused*todetermineifamoveshouldbemadebasedon*privatelongmLastMove;*mStatusText:textshowstotheuserinsomerun*privateTextViewmStatusText;*mSnakeTrail:alistofCoordinatesthatmakeupthesnake's*mAppleList:thesecretlocationofthejuicyapplesthesnake*兩個(gè)鏈表,分別用來蛇體和果子的坐標(biāo) *每次蛇體的運(yùn)動(dòng),蛇體的增長(zhǎng),產(chǎn)生新的蘋果,被蘋果,都會(huì)在這privateArrayList<Coordinate>mSnakeTrail=newprivateArrayList<Coordinate>mAppleList=new*EveryoneneedsalittlerandomnessintheirprivatestaticfinalRandomRNG=new*Createasimplehandlerthatwecanusetocauseanimationto*setourselvesasatargetandwecanusethe*functiontocauseanupdate/invalidatetooccuratalater*Handler*Handlerandroid的線程模型(注意privateRefreshHandlermRedrawHandler=newRefreshHandler(); classRefreshHandlerextendsHandler{//publicvoidhandleMessage(Messagemsg) //定時(shí)發(fā)送消息給UIpublicvoidsleep(longdelayMillis)this.removeMessages(0清空消息隊(duì)列,Handler進(jìn)入對(duì)新消sendMessageDelayed(obtainMessage(0delayMillis定時(shí)發(fā)送新消息,激活handler}publicSnakeView(Contextcontext,AttributeSetattrs)super(context,initSnakeView();//構(gòu)造函數(shù)中,別忘了,初始化游戲 publicSnakeView(Contextcontext,AttributeSetattrs,intdefStyle)super(context,attrs, privatevoidinitSnakeView()setFocusable(truefocus是不可或缺的。Resourcesr=loadTile(RED_STAR,loadTile(YELLOW_STAR,}privatevoidinitNewGame()//Fornowwe'rejustgoingtoloadupashortdefaulteastbound//that'sjustturnedmSnakeTrail.add(newCoordinate(7,mSnakeTrail.add(newCoordinate(6,mSnakeTrail.add(newCoordinate(5,mSnakeTrail.add(newCoordinate(4,mSnakeTrail.add(newCoordinate(3,mSnakeTrail.add(newCoordinate(2,mNextDirection=//TwoapplestostartmMoveDelay=mScore=}*GivenaArrayListofcoordinates,weneedtoflattenthemintoanarrayof*intsbeforewecanstuffthemintoamapforflatteningand**@paramcvec:aArrayListofCoordinate*@return:asimplearraycontainingthex/yvaluesofthecoordinat*asx1,y1,x2,y2,x3,y3...*Bundle*所以需要將我們的部分?jǐn)?shù)據(jù)結(jié)構(gòu),如蛇體和蘋果位置的數(shù)組,轉(zhuǎn)換int數(shù)組。privateint[]coordArrayListToArray(ArrayList<Coordinate>cvec)intcount=int[]rawArray=newint[count*for(intindex=0;index<count;index++)Coordinatec=rawArray[2*index]=rawArray[2*index+1]=}return}*Savegamestatesothattheuserdoesnotlose*ifthegameprocessiskilledwhilewearein* *@returnaBundlewiththisview'spublicBundlesaveState()Bundlemap=newBundle();map.putInt("mDirection",map.putLong("mScore",map.putIntArray("mSnakeTrail",coordArrayListToArray(mSnakeTrreturn *Givenaflattenedarrayofordinatepairs,wereconstitutetheminto*ArrayListofCoordinate*@paramrawArray:*@returnaArrayListof{ArrayList<Coordinate>coordArrayList=newArrayList<CoordinatintcoordCount=for(intindex=0;index<coordCount;index+=2)Coordinatec=newCoordinate(rawArray[index],rawArray[index+1]); return *Restoregamestateifourprocessisbeing*@paramicicleaBundlecontainingthegamepublicvoidrestoreState(Bundleicicle)mAppleList=coordArrayToArrayList(icicle.getIntArray("mAppleLismDirection=mNextDirection=mMoveDelay=mScore=mSnakeTrail=coordArrayToArrayList(icicle.getIntArray("mSnake}*handleskeyeventsinthegame.Updatethedirectionoursnake*basedontheDPAD.Ignoreeventsthatwouldcausethesnaketoi*turnbackon*按鍵的*現(xiàn)在大多數(shù)的android都沒有按鍵了**@seeandroid.view.View#onKeyDown(int,publicbooleanonKeyDown(intkeyCode,KeyEventmsg)if(keyCode==KeyEvent.KEYCODE_DPAD_UP)if(mMode==READY|mMode==LOSE)*Atthebeginningofthegame,ortheendofaprevious*weshouldstartanew();//return}if(mMode==PAUSE) *Ifthegameismerelypaused,weshouldjustcontinuewhe*weleftreturn} ifmDirectionSOUTH){//mNextDirection=}return}if(keyCode==KeyEvent.KEYCODE_DPAD_DOWN)if(mDirection!=NORTH)mNextDirection= return if(keyCode==KeyEvent.KEYCODE_DPAD_LEFT)if(mDirection!=EAST)mNextDirection= return if(keyCode==KeyEvent.KEYCODE_DPAD_RIGHT)if(mDirection!=WEST)mNextDirection= return}returnsuper.onKeyDown(keyCode,}*SetstheTextViewthatwillbeusedtogiveinformation(suchas"G*Over"tothe*起初不明白這個(gè)方法有什么作用。刪除了以后才發(fā)現(xiàn)錯(cuò)誤。Snaketextview.publicvoidsetTextView(TextViewnewView)mStatusText=}*Updatesthecurrentmodeoftheapplication(RUNNINGorEDorthe*aswellassetsthevisibilityoftextviewfor**@parampublicvoidsetMode(intnewMode)intoldMode=mMode=if(newMode==RUNNING&oldMode!=RUNNING));//updateinitGame中也有update(),不過放心~update不會(huì)影響效果的,//mLastMovemMoveDelay來校驗(yàn)。這會(huì)Update()中體現(xiàn)。//update()似乎不會(huì)影響結(jié) Resourcesres=CharSequencestr=if(newMode==PAUSE)str= if(newMode==READY)str= if(newMode==LOSE)str=res.getString(R.string.mode_lose_prefix)+ + *Selectsarandomlocationwithinthegardenthatisnotcurrentlyco*bythesnake.Currently_could_gointoaninfiniteloopifthe*currentlyfillsthegarden,butwe'llleavediscoveryofthisprizeto*trulyexcellentsnake-*在地圖上隨機(jī)的增加果子。注意蘋果的位置不可以是蛇體所在噢~這里有個(gè)小bug,沒有檢測(cè)**新產(chǎn)生的果子的坐標(biāo)會(huì)增加到mApplistprivatevoidaddRandomApple()CoordinatenewCoord=booleanfound=while(!found)//ChooseanewlocationforourintnewX=1+RNG.nextInt(mXTileCount-intnewY=1+RNG.nextInt(mYTileCount-newCoord=newCoordinate(newX,newY);//Makesureit'snotalreadyunderthebooleancollision=intsnakelength=for(intindex=0;index<snakelength;index++)collision= //ifwe'rehereandthere'sbeennocollision,thenwe//agoodlocationforanapple.Otherwise,we'llcircle//andtryfound= if(newCoord==null)Log.e(TAG,"Somehowendedupwithanull *Handlesthebasicupdateloop,checkingtoseeifweareintherun*state,determiningifamoveshouldbemade,updatingthesnake's*刷新游戲狀態(tài)。每次游戲畫面的更新、游戲數(shù)據(jù)的更新,都是依靠update()來完成的。publicvoidupdate()if(mMode==RUNNING)longnow=System.currentTimeMillis();ifnowmLastMovemMoveDelay){////mMode變化時(shí),對(duì)update()正 updateApples();//mLastMove= mRedrawHandler.sleep(mMoveDelay);//Handler *Drawssome*setTileprivatevoidupdateWalls()for(intx=0;x<mXTileCount;x++)setTile(GREEN_STAR,x,setTile(GREEN_STAR,x,mYTileCount- for(inty=1;y<mYTileCount-1;y++) setTile(GREEN_STAR,0, setTile(GREEN_STAR,mXTileCount-1, *Drawssome*privatevoidupdateApples()for(Coordinatec:mAppleList)setTile(YELLOW_STAR,c.x, *Figureoutwhichwaythesnakeisgoing,seeifhe'srunintoanything(the *walls,himself,oranapple).Ifhe'snotgoingtodie,wethenaddto *frontandsubtractfromtherearinordertosimulatemotion.Ifwewantto*growhim,wedon'tsubtractfromthe*privatevoidupdateSnake()booleangrowSnakefalse;////grabthesnakebytheCoordinateheadmSnakeTrail.get(0);//頭部很重要,只有頭部CoordinatenewHeadnewCoordinate(11蛇下一步一定會(huì)前移,也就試newHead。長(zhǎng)長(zhǎng)只會(huì)從尾部增加。//CoordinatenewHead呢?反正肯定會(huì)給//switch語句中給mDirection=mNextDirection; switch(mDirection) caseEAST: newHead=newCoordinate(head.x+1, caseWEST: newHead=newCoordinate(head.x-1, caseNORTH: newHead=newCoordinate(head.x,head.y- caseSOUTH: newHead=newCoordinate(head.x,head.y+ //Collision//Fornowwehavea1-squarewallaroundtheentire//if((newHead.x<1)||(newHead.y<1)||(newHead.x>mXTileCount-2)||(newHead.y>mYTileCount-2)) //Lookforcollisionswith//intsnakelength={for(intsnakeindex=0;snakeindex<snakelength;Coordinatec=if(c.equals(newHead))}}//Lookfor//intapplecount=for(intappleindex=0;appleindex<applecount;appleindex++)Coordinatec=if(c.equals(newHead))mMoveDelay*=growSnake=}}//pushanewheadontotheArrayListandpulloffthe//mSnakeTrail.add(0,//exceptifwewantthesnaketoif(!growSnake)}//intindex=for(Coordinatec:mSnakeTrail)if(index==0)setTile(YELLOW_STAR,c.x,}elsesetTile(RED_STAR,c.x,}}}*Simpleclasscontaining

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論