版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
念和操作方式。具体细节先卖一个关子,作品准备参加这次第二届大学生android应用开Snake*TileView是基于AndroidView类实现的方块图类,用来支撑上层类的调用,绘制方块图的显示界面。通过这些代码,能打之了解如何扩展View*SnakeViewTileView,实现了游戏逻辑和具体的*SnakeActivity类。PS:android2.2下左右按键操作,现在大多数android机是没有方向键的吧。[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*整个界面内每个tile位置应该绘制的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,在游戏初始的时候使用**@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*加载具体的砖块到砖块字典*即将对应的砖块的对应的加载到mTileArray数组*@param*@parampublicvoidloadTile(intkey,Drawabletile)//Drawablebitmap的转换。由于外部程序使用的//drawable格式,而我们的数组是bitmap格式,方便最终的绘bitmap的转换。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;//结束,输了游戏*Currentdirectionthesnakeis*privateintmDirection=privateintmNextDirection=privatestaticfinalintNORTH=privatestaticfinalintSOUTH=privatestaticfinalintEAST=privatestaticfinalintWEST=4;*LabelsforthedrawablesthatwillbeloadedintotheTileView*privatestaticfinalintRED_STAR=privatestaticfinalintYELLOW_STAR=privatestaticfinalintGREEN_STAR=3; *mScore:usedtotrackthenumberofapplescapturedmMoveDelay:numberof *millisecondsbetweensnakemovements.Thiswilldecreaseasapples*privatelongmScore0;// privatelongmMoveDelay600;//每移动一步的延时。初始时设置为600ms9折 *mLastMove:trackstheabsolutetimewhenthesnakelastmoved,andisused*todetermineifamoveshouldbemadebasedon*privatelongmLastMove;*mStatusText:textshowstotheuserinsomerun*privateTextViewmStatusText;*mSnakeTrail:alistofCoordinatesthatmakeupthesnake's*mAppleList:thesecretlocationofthejuicyapplesthesnake*两个链表,分别用来蛇体和果子的坐标 *每次蛇体的运动,蛇体的增长,产生新的苹果,被苹果,都会在这privateArrayList<Coordinate>mSnakeTrail=newprivateArrayList<Coordinate>mAppleList=new*EveryoneneedsalittlerandomnessintheirprivatestaticfinalRandomRNG=new*Createasimplehandlerthatwecanusetocauseanimationto*setourselvesasatargetandwecanusethe*functiontocauseanupdate/invalidatetooccuratalater*Handler*Handlerandroid的线程模型(注意privateRefreshHandlermRedrawHandler=newRefreshHandler(); classRefreshHandlerextendsHandler{//publicvoidhandleMessage(Messagemsg) //定时发送消息给UIpublicvoidsleep(longdelayMillis)this.removeMessages(0清空消息队列,Handler进入对新消sendMessageDelayed(obtainMessage(0delayMillis定时发送新消息,激活handler}publicSnakeView(Contextcontext,AttributeSetattrs)super(context,initSnakeView();//构造函数中,别忘了,初始化游戏 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*所以需要将我们的部分数据结构,如蛇体和苹果位置的数组,转换int数组。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*按键的*现在大多数的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*起初不明白这个方法有什么作用。删除了以后才发现错误。Snaketextview.publicvoidsetTextView(TextViewnewView)mStatusText=}*Updatesthecurrentmodeoftheapplication(RUNNINGorEDorthe*aswellassetsthevisibilityoftextviewfor**@parampublicvoidsetMode(intnewMode)intoldMode=mMode=if(newMode==RUNNING&oldMode!=RUNNING));//updateinitGame中也有update(),不过放心~update不会影响效果的,//mLastMovemMoveDelay来校验。这会Update()中体现。//update()似乎不会影响结 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-*在地图上随机的增加果子。注意苹果的位置不可以是蛇体所在噢~这里有个小bug,没有检测**新产生的果子的坐标会增加到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*刷新游戏状态。每次游戏画面的更新、游戏数据的更新,都是依靠update()来完成的。publicvoidupdate()if(mMode==RUNNING)longnow=System.currentTimeMillis();ifnowmLastMovemMoveDelay){////mMode变化时,对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蛇下一步一定会前移,也就试newHead。长长只会从尾部增加。//CoordinatenewHead呢?反正肯定会给//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等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年江苏航运职业技术学院高职单招职业技能测试近5年常考版参考题库含答案解析
- 2025年枣庄职业学院高职单招语文2018-2024历年参考题库频考点含答案解析
- 物业管理的组织与职责分析
- 烟雾探测器的作用与使用方法
- 基于毫米波雷达的手势识别关键技术研究
- 动漫综合知识竞赛考试题库及答案
- 2025年浙教版九年级历史上册月考试卷
- 智能水表技术研发合同(2篇)
- 权益转让协议书(2篇)
- 2025年人教版(2024)八年级历史下册月考试卷含答案
- 2024-2025学年人教版三年级(上)英语寒假作业(九)
- 《招标投标法》考试题库200题(含答案)
- 河南退役军人专升本计算机真题答案
- DB52T 1167-2017 含笑属栽培技术规程 乐昌含笑
- 2025年全国高考体育单招考试政治模拟试卷试题(含答案详解)
- 驾驶证学法减分(学法免分)试题和答案(50题完整版)1650
- 人教版2024新版七年级上册数学第六章几何图形初步学业质量测试卷(含答案)
- 小学数学五年级上册奥数应用题100道(含答案)
- 村卫生室2023年度绩效考核评分细则(基本公共卫生服务)
- 7天减肥餐食谱给你最能瘦的一周减肥食谱
- 最新北师大版八年级数学下册教学课件全册
评论
0/150
提交评论