Home > Default > Could someone look at my code, I can't see the error myself

Could someone look at my code, I can't see the error myself

October 11Hits:0
Advertisement
Hi,
I have been working on a small game, and have been able to make most of it run.
However, every now and again when i try to start it, it loads the frame and graphics, but don't start the game loop.
I think i have been starring at it too long, because i can't see WHY?
Here is the code, i assume its something connected to the boolean "waitingForKeyPress"
Sorry about the commentss being in danish, but its a quite simple program, so im sure it makes sense.
public class EagleFlight extends Canvas {
     private static final long serialVersionUID = 1L;
     //Strategybuffer til page flipping, samt grafiske variable.
     private BufferStrategy strategy = null;
     //private BufferedImage backbuffer = null;     
     private ImageEntity background = null;     
     //private Graphics2D g;     
     //private BufferedImage expl;
     private BufferedImage[] explosion2;     
     private boolean gameRunning = true;
     //Lister over entiteter i spillet.
     private ArrayList<Entity> entities = new ArrayList<Entity>();
     private ArrayList<ShipEntity> shipAnimation = new ArrayList<ShipEntity>();
     //Lister over entiteter der evt skal fjernes i gameLoop.
     private ArrayList<Entity> removeList = new ArrayList<Entity>();
     private ArrayList<Entity> removeAsteroid = new ArrayList<Entity>();
     //Variable til spillerens skib.
     private ShipEntity ship, shipL, shipR, eagleM;
     private double moveSpeed = 300;
     private long lastFire = 0;
     private long firingInterval = 500;
     private String message = "";
     //Booleans til keyInput og spilkontrol.
     private boolean waitingForKeyPress = true;
     private boolean leftPressed = false;
     private boolean rightPressed = false;
     private boolean firePressed = false;
     private boolean isThrusting = false;
     private Boolean shipHit = false;
     private Boolean animation = false;
     //Klasser der bruges i spillet.
     private FXSound fxSound = null;
     private Music music;     
     int score =0;
     private int astroidCount = 0;
     //Variable til ekspoltionsanimation.
     private int v = 0, x = 0, y = 0, eksp = 0;
     //Opretter JFrame og tilf&#65533;jer JPanel.
     public EagleFlight(){
          JFrame container = new JFrame("Eagle Flight 1999");                    
          JPanel panel = (JPanel) container.getContentPane();
          panel.setPreferredSize(new Dimension(800,600));
          panel.setLayout(null);
          //Tilf&#65533;jer EagleFlight canvas til JPanel
          setBounds(0,0,800,600);
          panel.add(this);
          //S&#65533;ttes til true, s&#65533; for&#65533;get graphics har ansvaret.
          setIgnoreRepaint(true);
          //Pakker og synligg&#65533;r vinduet.
          container.pack();
          container.setResizable(false);
          container.setVisible(true);
          // Tilf&#65533;jer windows close funktion
          container.addWindowListener(new WindowAdapter() {
               public void windowClosing(WindowEvent e) {
                    System.exit(0);
          // Tilf&#65533;jer keyListener og inputhandler.
          addKeyListener(new KeyInputHandler());
          //S&#65533;tter fokus til dette vindue-
          requestFocus();
          // Laver buffering strategy til accelerated graphics
          createBufferStrategy(2);
          strategy = getBufferStrategy();
          // Tilf&#65533;jer midlertidigt Entities, s&#65533; startsk&#65533;rmen ikke er tom.
          initEntities();
     }//End of EagleFlight().
     //Nulstiller variable og lister.
     private void startGame() {
          entities.clear();
          initEntities();          
          shipHit = false;          
          leftPressed = false;
          rightPressed = false;
          firePressed = false;
          gameRunning = true;
          music = new Music();
          music.start();
          waitingForKeyPress = false;
     }//end of startgame().
     private void initEntities() {
          //Laver 3 skibe til thrusteranimationen.
          ship = new sprite.ShipEntity(this,"eagle.png",370,430);
          shipL = new sprite.ShipEntity(this,"eagle1.png",370,430);
          shipR = new sprite.ShipEntity(this,"eagle2.png",370,430);
          shipAnimation.add(ship);
          shipAnimation.add(shipL);
          shipAnimation.add(shipR);
          //Opretter baggrundsbillede.
          new BufferedImage(800,600,BufferedImage.TYPE_INT_RGB);
          background = new ImageEntity("stars.png",0,0);
          //Klarg&#65533;r special effect lyd.
          fxSound = new FXSound();
          //Opretter eksplotionsanimation
          explosion2 = new ExplotionImages().explosion();
          //Laver en pokkers bunke asteroider og placerer dem "over" JPanel, s&#65533; de falder naturligt.
          for (int row=0;row<6;row++) {
               for (int x=0;x<10;x++) {
                    Entity astroid = new sprite.Astroid(this,"asteroid1.png",20+(x*120),(-2800)+row*400);
                    entities.add(astroid);                                   
                    astroidCount++;
          for (int row=0;row<6;row++) {
               for (int x=0;x<10;x++) {
                    Entity astroid = new sprite.Astroid(this,"asteroid4.png",20+(x*120),(-3800)+row*400);
                    entities.add(astroid);                                   
                    astroidCount++;
          for (int row=0;row<6;row++) {
               for (int x=0;x<10;x++) {
                    Entity astroid = new sprite.Astroid(this,"asteroid2.png",20+(x*120),(-4800)+row*400);
                    entities.add(astroid);                                   
                    astroidCount++;
          for (int row=0;row<6;row++) {
               for (int x=0;x<10;x++) {
                    Entity astroid = new sprite.Astroid(this,"asteroid3.png",20+(x*120),(-5800)+row*400);
                    entities.add(astroid);                                   
                    astroidCount++;
     }//end of initEntities()
     //Fjerner de entities der ikke bruges mere.
     //@param entiteten der skal fjernes.
     public void removeEntity(Entity entity)
          removeList.add(entity);               
     }//end of removeEntity().
     //Tilf&#65533;jer ramte asteroider til remove listen.
     //@param entiteten der skal tilf&#65533;jes.
     public void removeAsteroid(Entity doomed){
          removeAsteroid.add(doomed);
     }//End of removeAsteroid().
     //Udf&#65533;res n&#65533;r spilleren d&#65533;r.
     public void notifyDeath() {
          message = "All your base are belong to us!";
          shipHit = true;
          removeAsteroid.add(eagleM);
          shipAnimation.clear();          
     }//End of notifyDeath().
     //Fors&#65533;ger at affyre v&#65533;ben, hvis reload er ok og skibet ikke er ramt.
     public void tryToFire() {
          // check that we have waiting long enough to fire
          if (System.currentTimeMillis() - lastFire < firingInterval) {
               return;
          if (!shipHit){
               lastFire = System.currentTimeMillis();
               ShotEntity shot = new sprite.ShotEntity(this,"shot.gif",ship.getX()+23,ship.getY()-15);
               entities.add(shot);
               fxSound.fxSound1();
     }//End of tryToFire().
     //Metode til at vinde spillet.
     public void notifyAlienKilled() {
          astroidCount--;
          score++;
          fxSound.fxSound3();
          if (astroidCount == 0) {
     }//End of notifyAlienKilled()
     public void gameLoop() {
          long lastLoopTime = System.currentTimeMillis();
          long timeInGame = 0;
          // I dette loop udf&#65533;res spillets grafik og logik.
          while (gameRunning) {
               // Beregner tid for hvor meget de enkelte grafiske enheder skal flyttes
               long delta = System.currentTimeMillis() - lastLoopTime;
               lastLoopTime = System.currentTimeMillis();
               timeInGame = (timeInGame + System.currentTimeMillis()/100000);
               // Skaffer den grafiske acceleration.
               // Tegner baggrunden.
               Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
               background.draw(g);
               //Cykler rundt mellem asteroider og flytter dem.
               if (!waitingForKeyPress) {
                    for (int i=0;i<entities.size();i++) {
                         Entity entity = (Entity) entities.get(i);
                         entity.move(delta);
                    //Bev&#65533;ger de 3 skibe i sync.
                    for (int e=0;e<shipAnimation.size();e++) {
                         ShipEntity fakeeaglemove = (ShipEntity) shipAnimation.get(e);
                         fakeeaglemove.move(delta);
               // Cykler rundt mellem entities og tegner dem.          
               for (int i=0;i<entities.size();i++) {
                    Entity entity = (Entity) entities.get(i);
                    entity.draw(g);
               //Tegner det skib der er i brug.
               for (int e=0;e<shipAnimation.size();e++)
                    eagleM = (ShipEntity) shipAnimation.get(e);
                    if (leftPressed)
                    {eagleM = shipL;
                    if (rightPressed)
                    {eagleM = shipR;
                    else if ((!leftPressed) && (!rightPressed))
                    {eagleM = ship;
                    eagleM.draw(g);
               //Brute force detection p&#65533; skibet og asteroider.               
               try {
                    for (int c = 0; c < entities.size(); c++) {
                         for (int m = 0; m < shipAnimation.size(); m++) {
                              Entity me = (Entity) shipAnimation.get(m);
                              Entity him = (Entity) entities.get(c);
                              if (me.collidesWith(him)) {
                                   //removeAlien.add(him);
                                   me.collidedWith(him);
                                   him.collidedWith(me);
               } catch (Exception e) {
               //Brute force detection p&#65533; skud og asteroider.
               try {
                    for (int p = 0; p < entities.size(); p++) {
                         for (int s = p + 1; s < entities.size(); s++) {
                              Entity me = (Entity) entities.get(p);
                              Entity him = (Entity) entities.get(s);
                              if (me.collidesWith(him)) {
                                   me.collidedWith(him);
                                   him.collidedWith(me);
               } catch (Exception e) {
               //Explotion animation.
               for (int i=0;i<removeAsteroid.size();i++) {
                    Entity entity = (Entity) removeAsteroid.get(i);
                    explosion(entity);                                   
               if (animation){
                    int sequence[] = { 0,1,2,3,4,5,5,4,3,2,1,0};                    
                    eksp = sequence[v];
                    g.drawImage(explosion2[eksp], x-100,y-100, null);
               //Afslutter spillet hvis spillerens skib er ramt.
               if (eksp == 0 || v == 12){     
                    if (shipHit){
                         animation = false;
                         waitingForKeyPress = true;
                         music.stop();                                        
                         if(isThrusting){
                              fxSound.StopThruster();
                    animation = false;
                    v = 0;
                    eksp = 0;
               v++;//Opdaterer image nummer for eksplotionsanimation til n&#65533;ste genneml&#65533;b.
               // Fjerner entities der ikke er med mere.
               entities.removeAll(removeList);
               entities.removeAll(removeAsteroid);
               //Nulstiller removelisterne
               removeList.clear();                              
               removeAsteroid.clear();
               // Mens der ventes p&#65533; keyinput vises dette.
               if (waitingForKeyPress) {
                    g.setColor(Color.white);
                    g.drawString(message,(800-g.getFontMetrics().stringWidth(message))/2,250);
                    g.drawString("Insert coin",(800-g.getFontMetrics().stringWidth("Insert coin"))/2,300);
                    timeInGame = 0;
               g.setColor(Color.white);               
               g.drawString("Score: "+score,720,595);
               g.drawString("Time in Flight: "+timeInGame/1000000000+" Secs",5,595);
               // Graphics ryttes op og bufferen flippes.
               g.dispose();
               strategy.show();
               // Nulstiller skibets bev&#65533;gelse.
               ship.setHorizontalMovement(0);
               shipL.setHorizontalMovement(0);
               shipR.setHorizontalMovement(0);
               //Tilpasser skibets horizontale bev&#65533;gelseshastighed til input.
               if ((leftPressed) && (!rightPressed))
                    ship.setHorizontalMovement(-moveSpeed);
                    shipL.setHorizontalMovement(-moveSpeed);
                    shipR.setHorizontalMovement(-moveSpeed);
               else if ((rightPressed) && (!leftPressed))
                    ship.setHorizontalMovement(moveSpeed);
                    shipL.setHorizontalMovement(moveSpeed);
                    shipR.setHorizontalMovement(moveSpeed);//animationtest ship changed to eagle
               //Affyrings sekvens
               if (firePressed)
                    tryToFire();
               // Lille pause til andre ting.
               try { Thread.sleep(10); } catch (Exception m) {}
     }//End of gameLoop
     //Metode til kontrol af thrusterlyden.
     private void thrusterSound(){
          if (!isThrusting){
               fxSound.fxSound2();               
               isThrusting = true;
     }//End of thrusterSound
     //Metode til at inds&#65533;tte eksplotion p&#65533; den rette plads.
     //@param den ramte entitet.
     private void explosion(Entity entity){
          x = entity.getX();
          y = entity.getY();
          animation = true;
     }//End of explosion
     //Inner class der klarer input fra keybard.
     private class KeyInputHandler extends KeyAdapter {
          //S&#65533;tter t&#65533;ller til 1, s&#65533; wait for input virker.
          private int pressCount = 1;
          //@param den trykkede tast.
          public void keyPressed(KeyEvent e) {
               // Ser f&#65533;rst om der ventes p&#65533; input til start.
               if (waitingForKeyPress) {
                    return;
               //Er spillet igang udf&#65533;res input
               if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                    leftPressed = true;                         
                    thrusterSound();
               if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                    rightPressed = true;
                    thrusterSound();
               if (e.getKeyCode() == KeyEvent.VK_SPACE) {
                    firePressed = true;
          } //End of keyPressed
          //Stopper handlingen fra input
          //@param den trykkede tast.
          public void keyReleased(KeyEvent e) {
               // if we're waiting for an "any key" typed then we don't
               // want to do anything with just a "released"
               if (waitingForKeyPress) {
                    return;
               if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                    leftPressed = false;
                    fxSound.StopThruster();
                    isThrusting = false;
               if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                    rightPressed = false;
                    fxSound.StopThruster();
                    isThrusting = false;
               if (e.getKeyCode() == KeyEvent.VK_SPACE) {
                    firePressed = false;
          }//End of keyReleased
          //Metode til at starte spillet med any key.
          //@param den trykkede tast.
          public void keyTyped(KeyEvent e) {
               if (waitingForKeyPress) {
                    if (pressCount == 1) {
                         // Starter spillet.
                         waitingForKeyPress = false;
                         startGame();
                         //pressCount = 0;
                    } else {
                         pressCount++;
               // Tilf&#65533;jer esc key til at afslutte spillet.
               if (e.getKeyChar() == 27) {
                    System.exit(0);
     }//End of KeyTyped.
     public static void main(String args[])
          EagleFlight ef = new EagleFlight();          
          ef.gameLoop();
     }//End of main.
}//End of class EagleFlight.

Answers

Mondariz wrote:
It was a copy/paste job from Eclipse, not suer why it formatted like this. You need to add code tags.
[edit: do what Darryl says... as opposed to my crap version that did not format properly either]
As far as the tracing goes. It shouldn't be taking hours. Start by putting them in where your program starts and move on.

Read other 7 answers

Tags:

Related Articles

Copyright (C) 2019 wisumpire.com, All Rights Reserved. webmaster#wisumpire.com 14 q. 1.154 s.