问题描述
最近在做打飞机小游戏,要子弹连发的,我是想在这里ArrayList<Missile>arr=newArrayList<Missile>();caseKeyEvent.VK_SPACE:arr.add(newMissile());每按一次空格就创建一个这样的对象,再当对象X坐标超过边界就用arr.remove()但是要创建一个类Missile我想把飞机,障碍物,导弹分到三个类里面去。但是我不知道哪些应该放进去,就是关于代码优化求助packagegraphics;importjava.awt.Color;importjava.awt.Graphics;importjava.awt.Image;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.event.KeyEvent;importjava.awt.event.KeyListener;importjava.util.ArrayList;importjavax.imageio.ImageIO;importjavax.swing.JPanel;importjavax.swing.Timer;publicclassGameextendsJPanelimplementsActionListener,KeyListener{privateintsize;privateImagecraft;privateImagebarrier;privateImagemissle;privateintx=0;privateinty=0;privateintdx=0;privateintdy=0;privateintmissleX=0;privateintmissleY=0;privateint[][]starsLoaction=newint[10][2];ArrayList<Missle>arr=newArrayList<Missle>();booleanshowMissle=false;privateTimertimer;publicGame(intsize,intx,inty){this.x=x;this.y=y;try{craft=ImageIO.read(Game.class.getResource("huiji.jpg"));barrier=ImageIO.read(Game.class.getResource("yunshi.bmp"));missle=ImageIO.read(Game.class.getResource("missle.bmp"));}catch(Exceptione){e.printStackTrace();}//注册键盘事件监听器this.setFocusable(true);this.addKeyListener(this);timer=newTimer(1,this);timer.start();for(int[]wangcai:starsLoaction){wangcai[0]=(int)(Math.random()*500);wangcai[1]=(int)(Math.random()*500);}}publicGame(){super();}publicvoidpaint(Graphicsg){super.paint(g);for(int[]wangcai:starsLoaction){g.drawImage(barrier,wangcai[0],wangcai[1],null);}if(showMissle){g.drawImage(missle,x,y,null);}setBackground(Color.BLACK);g.drawImage(craft,x,y,null);}/***飞船移动*/privatevoidmovecraft(){x+=dx;y+=dy;}/***障碍物移动*/privatevoidmovebarrier(){for(int[]wangcai:starsLoaction){if(wangcai[0]>=0){wangcai[0]-=2;}else{wangcai[0]=485;wangcai[1]=(int)(Math.random()*500);}}}privatevoidmovemissle(){if(missleX>=x+craft.getWidth(null)){missleX+=5;}else{showMissle=false;}}@OverridepublicvoidactionPerformed(ActionEvente){movemissle();movebarrier();movecraft();repaint();}/***开火*/publicvoidfire(){showMissle=true;missleX=x+craft.getWidth(null);missleY=y+craft.getHeight(null)/2;}/***键盘监听器*/@OverridepublicvoidkeyTyped(KeyEvente){}/***键盘按下的时候*/@OverridepublicvoidkeyPressed(KeyEvente){intkeyCode=e.getKeyCode();switch(keyCode){caseKeyEvent.VK_UP:dy=-10;break;caseKeyEvent.VK_DOWN:dy=10;break;caseKeyEvent.VK_LEFT:dx=-10;break;caseKeyEvent.VK_RIGHT:dx=10;break;caseKeyEvent.VK_SPACE:arr.add(newMissle());fire();break;default:break;}}@OverridepublicvoidkeyReleased(KeyEvente){intkeyCode=e.getKeyCode();switch(keyCode){caseKeyEvent.VK_UP:dy=0;break;caseKeyEvent.VK_DOWN:dy=0;break;caseKeyEvent.VK_LEFT:dx=0;break;caseKeyEvent.VK_RIGHT:dx=0;break;default:break;}}}