用java实现简单贪食蛇游戏功能简介能够通过面板上的按钮和键盘上的“+”,“-”实现加速,减速。能够通过面板上的按钮和键盘上的“r“来实现重新开始游戏。能够在面板上通过复选框选择游戏模式(挑战模式,普通模式)。二、运行结果截图代码1、地图packagesnake;import;import;import;import;//读取字符文件类FileReaderimport;lassmap{ int[][]map=newint[20][20]; intsnakeX,snakeY; intfoodX,foodY; publicmap(intlevel){ Stringfilepath="mapc/"+level+".txt"; Filefile=newFile(filepath); FileReaderfr=null;//利用FileReader流来读取一个文件中的数据 BufferedReaderbr=null;//字符读到缓存里 try{ fr=newFileReader(file); br=newBufferedReader(fr); for(inti=0;i<20;i++){ Stringline=();//以行为单位,一次读一行利用BufferedReader的readLine,读取分行文本 byte[]point=();//将字符串转换为字节数组 for(intj=0;j<20;j++){ map[i][j]=point[j]-48;//根据ASCall码表要减掉30H(十进制的48) if(map[i][j]==3){ snakeX=i; snakeY=j; } if(map[i][j]==5){ foodX=i; foodY=j; } } } } catch(FileNotFoundExceptione){ ();//深层次的输出异常调用的流程} catch(IOExceptione){ ();//深层次的输出异常调用的流程} catch(NullPointerExceptione){ ();//深层次的输出异常调用的流程} finally{ if(br==null){ try{ (); } catch(IOExceptione){ (); } br=null; } if(fr==null){ try{ (); }catch(IOExceptione){ (); } fr=null; } } } publicint[][]getMap(){ returnmap; } publicintgetManX(){ returnsnakeX; } publicintgetManY(){ returnsnakeY; }}2、游戏packagesnake;import.*;import.*;import;import.*;import.*;lassgreedsnakeextendsJFrameimplementsKeyListener,ActionListener{ staticintik=0,jk=0,flag=0; Booleanrunning=true; Stringdirection="DOWN"; Stringpre_dir="DOWN"; snakemovesnake; intlevel=1; JButtonrestart,pause,speed_add,speed_sub; JComboBoxmode; Stringmodes[]={"挑战模式","普通模式"}; staticintsleeptime=250,speed=250; publicgreedsnake(){ super("贪吃蛇"); Containerc=getContentPane(); FlowLayoutlayout=newFlowLayout(); (); (layout); (); restart=newJButton("重新开始"); pause=newJButton("暂停"); speed_add=newJButton("加速"); speed_sub=newJButton("减速"); mode=boBox(modes); (this); (this); (this); (this); (restart); (pause); (speed_add); (speed_sub); (mode); //游戏模式的选择( newItemListener(){ publicvoiditemStateChanged(ItemEvente){ if(()==){ level=1+(); running=true; direction="DOWN"; pre_dir="DOWN"; repaint(); requestFocus(); }
用java实现简单贪食蛇游戏模板 来自淘豆网www.taodocs.com转载请标明出处.