




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
面向?qū)ο笳n程設(shè)計潛艇大作戰(zhàn)小游戲
目錄1.需求分析 21.1需求分析: 21.2功能設(shè)計 22.概要設(shè)計 22.1程序設(shè)計思路 22.2程序運(yùn)行界面 32.3流程圖 33.各模塊的功能及程序說明 43.1主界面代碼 43.2潛艇對象的實(shí)現(xiàn) 83.3潛艇爆炸的實(shí)現(xiàn) 133.4游戲說明 143.5時間計時器 16計時產(chǎn)生潛艇 16計時產(chǎn)生魚雷 183.6讀取文件,記錄分?jǐn)?shù) 194.實(shí)驗(yàn)心得 261.需求分析1.1需求分析:本程序的要求為使用Java建立一個小游戲程序中用到Java課程中的重點(diǎn)知識1.2功能設(shè)計本游戲的功能有以下幾個方面:首先繪制一個首頁,首頁包括開始、退出按鈕,采用事件監(jiān)聽。進(jìn)入游戲后使用,通過讀取文件,讀出以前的最好成績,使用菜單按鈕開始游戲通過方向鍵來控制潛艇的移動方向,空格鍵釋放魚雷擊中敵人后加分,同時被敵人擊中一次就扣除一次機(jī)會,共3次機(jī)會2.概要設(shè)計2.1程序設(shè)計思路此游戲的關(guān)鍵點(diǎn)是潛艇是否被擊中的判斷,整個屏幕是個二維坐標(biāo)系,軍艦在一個水平位置移動,當(dāng)在某個位置發(fā)射魚雷,判斷魚雷的圖片與不斷移動的潛艇圖片是否有重合的地方,如果有發(fā)生爆炸,如果沒有繼續(xù)移動。2.2程序運(yùn)行界面2.3流程圖本游戲的基本運(yùn)行流程是啟動后把整個畫布作為一個線程,隨時準(zhǔn)備響應(yīng)用戶按鍵操作的K響應(yīng),100ms掃描一次潛艇和水雷等物體的運(yùn)行狀態(tài)。在掃描潛艇和水雷運(yùn)動時,執(zhí)行各個物體畫面的移動方法。程序并不為每隔新增潛艇和水雷開啟一個新線程,太多線程會造成程序的性能直線下降;而是將每一個物體類型直接加入到畫布中,每當(dāng)一個新物體產(chǎn)生,將直接在畫布上畫出;當(dāng)物體消除時,將直接在畫布上被消除。這樣就形成一種注冊機(jī)制,所有游戲物體的產(chǎn)生和消除都需要畫布注冊,畫布擁有不同類型物體的所有“名單”,所以,當(dāng)執(zhí)行移動命令是只需要遍歷畫布中所有游戲物體,依次執(zhí)行每隔游戲物體中定義的移動方法即可。3.各模塊的功能及程序說明3.1主界面代碼主界面設(shè)計是使用坐標(biāo)系,具體實(shí)現(xiàn)圖如下:publicclassMainPanelextendsJPanel{privatestaticfinallongserialVersionUID=1L;privateMyButtonstartButton;privateMyButtonexitButton;privateJLabelhelpLabel;privateJLabelhelpLabel1;privateJLabelhelpLabel2;privateJLabelhelpLabel3;privateImageimage;privateJLabelcenterlabel;privatebooleanisStart;privatebooleanisExit;privateObservableobs;publicMainPanel(Observableob) {obs=ob;//初始化對象startButton=newMyButton("進(jìn)入游戲");exitButton=newMyButton("退出游戲");helpLabel=newJLabel();helpLabel1=newJLabel();helpLabel2=newJLabel();helpLabel3=newJLabel();centerlabel=newJLabel();this.setLayout(newBorderLayout());this.helpLabel.setPreferredSize(newDimension(645,291));this.helpLabel1.setPreferredSize(newDimension(180,80));this.helpLabel2.setPreferredSize(newDimension(215,80));this.helpLabel3.setPreferredSize(newDimension(645,80));this.centerlabel.setPreferredSize(newDimension(460,80));centerlabel.setLayout(newGridLayout(2,1));centerlabel.add(this.startButton);centerlabel.add(this.exitButton);this.centerlabel.setBackground(newColor(255,255,0));this.add(helpLabel,BorderLayout.NORTH);this.add(helpLabel1,BorderLayout.EAST);this.add(helpLabel2,BorderLayout.WEST);this.add(helpLabel3,BorderLayout.SOUTH);this.add(centerlabel,BorderLayout.CENTER);//類中聲明了游戲中需要的各種對象,并載入游戲中的圖片image=Toolkit.getDefaultToolkit().getImage("imgs/主界面112.png");//image=newImageIcon(image).getImage();//對開始按鈕的監(jiān)聽this.startButton.addActionListener(newActionListener() {publicvoidactionPerformed(ActionEvente) {booleanflag=true; MainPanel.this.setIsStart(flag);//System.out.println(MainPanel.this.getIsStart()); MainPanel.this.obs.notifyObservers(MainPanel.this);//System.out.println("isStart"); } } );//對結(jié)束事件的監(jiān)聽this.exitButton.addActionListener(newActionListener() {publicvoidactionPerformed(ActionEvente) { MainPanel.this.setExit(true); } } ); }publicvoidpaint(Graphicsg) {super.paint(g); Graphics2Dg2=(Graphics2D)g; g2.drawImage(image,0,0,this.getWidth(),this.getHeight(),this);super.paintComponents(g); }publicbooleangetIsStart() {returnthis.isStart; }publicvoidsetIsStart(booleanisStart) {this.isStart=isStart; }publicbooleanisExit(){returnisExit; }publicvoidsetExit(booleanisExit){this.isExit=isExit; }}3.2潛艇對象的實(shí)現(xiàn)publicclassSubmarineimplementsRunnable{privateintX;//位置x,yprivateintY;privateintdx;//移動距離privateintm;//方向:0代表向左1代表向右privateWarShipship;privateMyPanelpanel;privateintweight=65;//默認(rèn)長度和寬度,數(shù)據(jù)來自圖片大小privateintheight=20;publicbooleanflag=false;//運(yùn)行標(biāo)記privateImageimage;//圖片對象//privatestaticintnum=0;publicSubmarine(WarShipship,MyPanelpanel) {this.ship=ship;this.panel=panel;this.dx=1;//隨機(jī)產(chǎn)生潛艇圖片和運(yùn)動方向this.m=(int)(Math.random()*2);if(this.m==0) { Randomr=newRandom();intnum=r.nextInt(3);if(num==0) {image=Toolkit.getDefaultToolkit().getImage("imgs/潛艇1.png");//Toolkit.getDefaultToolkit().createImage("C:\\1.JPG"),用異步的方式創(chuàng)建圖片。當(dāng)線程執(zhí)行到_img.getWidth(this)語句時,創(chuàng)建圖片的線程還沒準(zhǔn)備好圖片所以會返回-1。image=newImageIcon(image).getImage(); }elseif(num==1) {image=Toolkit.getDefaultToolkit().getImage("imgs/潛艇2.png");image=newImageIcon(image).getImage(); }elseif(num==2) {image=Toolkit.getDefaultToolkit().getImage("imgs/潛艇8.png");image=newImageIcon(image).getImage(); } }if(this.m==1) { Randomr1=newRandom();intnum=r1.nextInt(4);if(num==0) {image=Toolkit.getDefaultToolkit().getImage("imgs/潛艇3.png");image=newImageIcon(image).getImage(); }elseif(num==1) {image=Toolkit.getDefaultToolkit().getImage("imgs/潛艇4.png");image=newImageIcon(image).getImage(); }elseif(num==2) {image=Toolkit.getDefaultToolkit().getImage("imgs/潛艇6.png");image=newImageIcon(image).getImage(); }elseif(num==3) {image=Toolkit.getDefaultToolkit().getImage("imgs/潛艇7.png");image=newImageIcon(image).getImage(); } }this.weight=image.getWidth(panel);this.height=image.getHeight(panel);if(m==0) {this.X=this.panel.getWidth()-this.weight; }if(m==1) {this.X=0; } Randomry=newRandom();inty1=ry.nextInt(panel.getHeight())+180;while((y1+this.getHeight())>=panel.getHeight()) { y1=ry.nextInt(panel.getHeight())+180; }this.Y=y1;//計時器每隔一段時間產(chǎn)生魚雷對象 TimeManager2tm2=newTimeManager2(this,this.panel,this.ship,this.panel.getTorpedoArray()); Threadt=newThread(tm2); t.start(); }publicvoiddrawSubmarine(Graphics2Dg) { g.drawImage(image,this.X,this.Y,panel); }publicvoidmoveLeft() {//System.out.println("潛水艇運(yùn)動");this.X-=dx;//System.out.println(this.X);this.panel.repaint();if(this.X<0) {this.flag=true; } }publicvoidmoveright() {this.X+=dx;//this.panel.repaint();if(this.X>this.panel.getWidth()) {this.flag=true; } }publicvoidrun() {//System.out.println("線程激活");while(!flag) {//System.out.println("222");if(this.m==0) {this.moveLeft(); }if(this.m==1) {this.moveright(); }if(this.panel.isStop()) {synchronized(MyPanel.subLock) {try { MyPanel.subLock.wait(); }catch(Exceptione) { e.printStackTrace();this.flag=true; } } }try { Thread.sleep(10); }catch(Exceptione) { e.printStackTrace();this.flag=true; } } }publicintgetX(){returnX; }publicvoidsetX(intx){X=x; }publicintgetY(){returnY; }publicvoidsetY(inty){Y=y; }publicintgetDx(){returndx; }publicvoidsetDx(intdx){this.dx=dx; }publicintgetWeight(){returnweight; }publicvoidsetWeight(intweight){this.weight=weight; }publicintgetHeight(){returnheight; }publicvoidsetHeight(intheight){this.height=height; }3.3潛艇爆炸的實(shí)現(xiàn)/**潛艇被擊中的爆炸效果,通過圖片顯示*/publicclassHitimplementsRunnable{privateMyPanelpanel;//主面板privateImageimage;//圖片privateintliveTime=500;//爆炸效果顯示的時間默認(rèn)為500毫秒privateintbeginX=0;//位置xyprivateintbeginY=0;privatebooleanisRunning=false;//游戲是否正在運(yùn)行標(biāo)志publicHit(intx,inty,MyPanelpanel) {this.beginX=x;this.beginY=y;this.panel=panel;this.image=Toolkit.getDefaultToolkit().getImage("imgs/炸彈效果.png");this.image=newImageIcon(this.image).getImage(); }publicvoiddrawHitting(Graphics2Dg) { g.drawImage(this.image,this.beginX,this.beginY,this.panel); }publicvoidrun() {while(!this.isRunning) {try{ Thread.sleep(this.liveTime); }catch(InterruptedExceptione){//TODOAuto-generatedcatchblock e.printStackTrace(); }this.isRunning=true; } }publicbooleanisRunning(){returnisRunning; }publicvoidsetRunning(booleanisRunning){this.isRunning=isRunning; }}3.4游戲說明/***游戲規(guī)則的對話框,提示游戲規(guī)則信息*/publicclassHelpDialogextendsJDialogimplementsMouseMotionListener,MouseListener{privatestaticfinallongserialVersionUID=1L;protectedJFrameframe1;privateMyPanelpanel;privatebooleanflag=false;privatebooleanisDraw=false;privatebooleanisOutDraw=false;publicHelpDialog(Frameframe,booleanmodal,MyPanelpanel) {super(frame,modal);this.panel=panel;this.addMouseMotionListener(this);this.addMouseListener(this);this.setLocation(frame.getBounds().x+180,frame.getBounds().y+200);this.setSize(300,200);this.setUndecorated(true);this.setVisiableRigeon(this.getWidth(),this.getHeight());this.setVisible(true); }publicvoidpaint(Graphicsg) {super.paint(g); Graphics2Dg2=(Graphics2D)g;//g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); Point2Dstart=newPoint2D.Float(this.getWidth()/2,0); Point2Dend=newPoint2D.Float(this.getWidth()/2,this.getHeight());float[]dist={0.05f,1.0f}; Color[]colors={newColor(58,95,205),Color.CYAN}; LinearGradientPaintp=newLinearGradientPaint(start,end,dist,colors); g2.setPaint(p); g2.fillRect(0,0,this.getWidth(),this.getHeight()); Stringtitle=newString("游戲規(guī)則"); g2.setFont(newFont("華文行楷",Font.BOLD,25)); g2.setColor(Color.yellow); BasicGraphicsUtils.drawString(g2,title,100,90,50); Stringcontext=newString("按<-或A鍵控制軍艦向左"); g2.setFont(newFont("華文行楷",Font.BOLD,15)); g2.setColor(Color.yellow); BasicGraphicsUtils.drawString(g2,context,100,50,100); Stringcontext1=newString("按->或D鍵控制軍艦向右"); g2.setFont(newFont("華文行楷",Font.BOLD,15)); g2.setColor(Color.yellow); BasicGraphicsUtils.drawString(g2,context1,100,50,120); Stringcontext2=newString("按空格鍵扔炸彈"); g2.setFont(newFont("華文行楷",Font.BOLD,15)); g2.setColor(Color.yellow); BasicGraphicsUtils.drawString(g2,context2,100,50,140);//g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);this.repaintShape(); }3.5時間計時器計時產(chǎn)生潛艇publicclassTimeManagerimplementsRunnable{privateWarShipship;privateMyPanelpanel;privateintspeed=1000;publicTimeManager(WarShipship,MyPanelpanel) {this.ship=ship;this.panel=panel; }publicvoidrun() { Randomr=newRandom();while(this.panel.isRunning()) {if(this.panel.isStop()==true) {//System.out.println("777");synchronized(MyPanel.subLock) {try { MyPanel.subLock.wait(); }catch(Exceptione) { e.printStackTrace();//this.flag=true;this.panel.endGame(); } } } Submarinesm=newSubmarine(this.ship,this.panel);this.panel.getSubmarineArray().add(sm); Threadt=newThread(sm); t.start();try { Thread.sleep(this.speed+r.nextInt(this.speed*3)); }catch(Exceptione) { e.printStackTrace(); } } }publicintgetSpeed(){returnspeed; }publicvoidsetSpeed(intspeed){this.speed=speed; }}計時產(chǎn)生魚雷publicclassTimeManager2implementsRunnable{privateWarShipship;privateArrayList<Torpedo>torpedoArray;privateMyPanelpanel;privateSubmarinesm;publicTimeManager2(Submarinesm,MyPanelpanel,WarShipship,ArrayList<Torpedo>torpedoArray) {this.sm=sm;this.torpedoArray=torpedoArray;this.panel=panel;this.ship=ship; }publicvoidrun() { Randomr=newRandom();while(!this.sm.flag) {//System.out.println("333");if(this.panel.isStop()==true) {synchronized(MyPanel.subLock) {//System.out.println("stop");try { MyPanel.subLock.wait(); }catch(Exceptione) { e.printStackTrace();//this.flag=true;this.panel.endGame(); } } } Torpedotp=newTorpedo(this.panel,this.ship,this.sm);this.torpedoArray.add(tp); Threadt=newThread(tp); t.start();try {inttime=r.nextInt(4000)+2000; Thread.sleep(time); }catch(Exceptione) { e.printStackTrace(); } } }}3.6讀取文件,記錄分?jǐn)?shù)publicclassInputDialogextendsJDialog{/** * */privatestaticfinallongserialVersionUID=1L;privateJButtonsubmit;//提交按鈕privateJLabeltext1;privateJLabeltext2;privateJLabeltext3;privateJTextFieldfield;privateMyPanelpanel;privateJPanelcenterPanel;privateJPanelnorthPanel;privateJPanelsouthPanel;publicInputDialog(Frameframe,booleanmodal,MyPanelpanel) {super(frame,modal);this.panel=panel;this.submit=newJButton("提交");this.text1=newJLabel("恭喜您進(jìn)入前十!");this.text1.setFont(newFont("楷體",Font.BOLD,15));this.text1.setHorizontalAlignment(JLabel.CENTER);this.text1.setVerticalAlignment(JLabel.BOTTOM);this.text1.setPreferredSize(newDimension(300,90));this.text2=newJLabel("請輸入您的姓名:");this.text2.setFont(newFont("楷體",Font.BOLD,12));this.text2.setHorizontalAlignment(JLabel.CENTER);this.text2.setPreferredSize(newDimension(130,20));this.text3=newJLabel("總分:"+this.panel.getScore());this.text3.setFont(newFont("楷體",Font.BOLD,12));this.text3.setHorizontalAlignment(JLabel.CENTER);this.text3.setPreferredSize(newDimension(300,30));this.field=newJTextField();this.field.setFont(newFont("楷體",Font.BOLD,15));this.field.setHorizontalAlignment(JLabel.CENTER);this.field.setPreferredSize(newDimension(70,20));this.submit.setBackground(Color.orange);this.submit.setHorizontalAlignment(JLabel.CENTER);this.submit.setPreferredSize(newDimension(80,30));this.submit.setForeground(newColor(61,145,64));this.submit.setFont(newFont("",0,20));this.centerPanel=newJPanel(newFlowLayout(5));this.centerPanel.setPreferredSize(newDimension(200,50));this.centerPanel.add(this.text2);this.centerPanel.add(this.field);this.northPanel=newJPanel(newGridLayout(2,1));this.northPanel.setPreferredSize(newDimension(300,90));this.northPanel.add(this.text1);this.northPanel.add(this.text3); JLabelsouthHelp1=newJLabel(); southHelp1.setPreferredSize(newDimension(100,50)); JLabelsouthHelp2=newJLabel(); southHelp2.setPreferredSize(newDimension(100,50));this.southPanel=newJPanel();this.southPanel.setPreferredSize(newDimension(300,70));this.southPanel.add(southHelp1);this.southPanel.add(this.submit);this.southPanel.add(southHelp2); JLabeleast=newJLabel(); east.setPreferredSize(newDimension(20,30)); JLabelwest=newJLabel(); west.setPreferredSize(newDimension(60,20)); Containerc=this.getContentPane(); c.add(this.northPanel,BorderLayout.NORTH); c.add(this.centerPanel,BorderLayout.CENTER); c.add(this.southPanel,BorderLayout.SOUTH); c.add(east,BorderLayout.EAST); c.add(west,BorderLayout.WEST);this.setContentPane(c);this.setLocation(frame.getBounds().x+180,frame.getBounds().y+200);this.setUndecorated(true); AWTUtilities.setWindowOpacity(this,0.7F);this.setSize(300,200);this.submit.addActionListener(newActionListener() {publicvoidactionPerformed(ActionEventarg0) {//得到用戶信息 Stringname=InputDialog.this.field.getText().trim(); Stringscore=Integer.toString(InputDialog.this.panel.getScore()); Stringpass=Integer.toString(InputDialog.this.panel.getPass()); SimpleDateFormatdf=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss");//設(shè)置日期格式 Stringdate=df.format(newDate());//newDate()為獲取當(dāng)前系統(tǒng)時間 Stringargs[]=date.split(""); Stringtime=args[0]; Stringuser=name+""+score+""+pass+""+time;//將數(shù)據(jù)文件中的用戶信息取出,去掉最后一名,加入玩家信息,并按降序排序 ArrayList<String>userList=newArrayList<String>(); BufferedReaderbr=null; BufferedWriterbw=null;try { br=newBufferedReader(newFileReader("userInfo/user")); Stringtemp=null;intcount=0;while((temp=br.readLine())!=null) {//System.out.println(temp); userList.add(temp); count++; }for(inti=1;i<userList.size();i++) { String[]arg=userList.get(i).split("");intvalue=Integer.parseInt(arg[1]);for(intposition=i;position>0;position--) { String[]indexScore=userList.get(position-1).split("");inttempScore=Integer.parseInt(indexScore[1]);if(tempScore<value) { Stringtemp1=(String)userList.get(position); userList.set(position,(String)userList.get(position-1)); userList.set(position-1,temp1); }
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 別墅拆改合同范本
- 代銷合同范本同+
- 個人買賣瓷器合同范例
- 業(yè)務(wù)結(jié)算補(bǔ)充合同范本
- 俄語貿(mào)易合同范本
- 務(wù)工合同范本可
- 買斷畫稿合同范本
- 公司注銷離職合同范本
- 倉庫搬遷合同范本
- 農(nóng)莊種菜養(yǎng)殖合同范本
- 有理數(shù)總復(fù)習(xí)市公開課一等獎省賽課微課金獎?wù)n件
- 幼兒園安全園本培訓(xùn)
- 第22課《陳涉世家》課件(共71張)
- 化工裝置管道設(shè)置緊急切斷閥的依據(jù)規(guī)范(一)
- (高清版)DZT 0284-2015 地質(zhì)災(zāi)害排查規(guī)范
- 七十歲老人三力測試題庫答案
- 實(shí)驗(yàn)室儀器借用登記表
- 深圳職業(yè)技術(shù)學(xué)院申報國家示范院校項(xiàng)目匯報材料Pow
- 認(rèn)識危險(小班安全第一課)-圖文
- 2024年國家基本公衛(wèi)-老年人健康管理-考試復(fù)習(xí)題庫(含答案)
- 第三講:虹吸管及水泵的水力計算
評論
0/150
提交評論