欢迎来到天天文库
浏览记录
ID:37852159
大小:59.00 KB
页数:8页
时间:2019-06-01
《java利用集合实现贪吃蛇游戏》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、Node:publicclassNode{privateintx;privateinty;@OverridepublicinthashCode(){return21x+33y;}@Overridepublicbooleanequals(Objectobj){if(!(objinstanceofNode))thrownewRuntimeException();Nodenode=(Node)obj;returnthis.x==node.x&&this.y==node.y;}publicintgetX(){returnx;}publicvoidsetX(intx)
2、{this.x=x;}publicintgetY(){returny;}publicvoidsetY(inty){this.y=y;}publicNode(intx,inty){super();this.x=x;this.y=y;}publicNode(){}@OverridepublicStringtoString(){returnthis.x+","+this.y;}}WormPanelimportjava.util.ArrayList;importjava.util.HashSet;importjava.util.Iterator;importjava
3、.util.LinkedList;importjava.util.Scanner;publicclassWormPanel{privatestaticfinalStringUP="u";privatestaticfinalStringDOWN="d";privatestaticfinalStringLEFT="l";privatestaticfinalStringRIGHT="r";privatestaticLinkedListshe=newLinkedList();privatestaticHashSetfood=new
4、HashSet();//主方法publicstaticvoidmain(String[]args){WormPanel.startGame();}publicstaticvoidstartGame(){Scannerscan=newScanner(System.in);System.out.println("请输入要得到的第一条蛇的长度(2~10):");intsheLang=scan.nextInt();System.out.println("请输入开始事物的个数(2~10):");intfoodNums=scan.nextInt();Worm
5、Panel.getFirstShe(sheLang);//得到蛇WormPanel.getFirstFood(foodNums);//得到食物System.out.println("请输入【u,d,l,y】代表【上,下,左,右】,【exit】结束");WormPanel.printWorm(she,food);Stringstr=WormPanel.She.getFirstFangxiang(she);//根据第一条蛇得到方向WormPanel.She.yidong2(str);}//蛇类staticclassShe{privatestaticStringf
6、angx;staticvoidyidong2(Stringstr){//外部调用的移动蛇函数booleanb=true;while(b){Scannerscan=newScanner(System.in);Stringin=scan.nextLine();if(in.equals("exit")){b=false;System.out.println("结束了");}elseif(in.equals(""+"")){yidong();WormPanel.printWorm(she,food);}else{if(check(in)){System.out.pr
7、intln("不能反向爬行!!");}else{fangx=in;yidong();WormPanel.printWorm(she,food);}}}}privatestaticvoidyidong(){//移动蛇函数if(fangx.equals(UP)){Noden=she.getFirst();Nodexin=newNode(n.getX()-1,n.getY());intx=n.getX()-1;if(x<2){System.out.println("不能穿墙哦!!!");}else{if(food.contains(xin)){food.remov
8、e(xin);she.addFirst(xin);i
此文档下载收益归作者所有