简体   繁体   中英

Java applet not drawing correctly

Here is the main code

import java.awt.*;  

import javax.swing.*;  
import java.awt.event.*;  
import java.applet.Applet;  

import java.applet.*;  
import java.awt.image.*;  
import java.util.*;  
import java.net.*;  
public class AlcatrazBreakout extends JApplet implements KeyListener, FocusListener  {  
    int choice=0,curloc=0;  
    boolean focus = false;  
    boolean left=false, right=false, up=false, down=false, space=false, enter=false;  

    public double randNum(Graphics canvas)
    {
        double x;
        x=Math.random()*100;
        return x;
    }
    public void init()
    {

        addKeyListener(this);
        addFocusListener(this);
        play(getCodeBase(), "SpyHunter.mid");

    }
    public void paint(Graphics canvas)
    {
        clearScreen(canvas);

        canvas.setColor(Color.BLACK);  // Must do this so words will
                                       // display on the screen

         if (!focus)
         {
            canvas.setColor(Color.WHITE);
            canvas.drawString("Welcome to Alcatraz Breakout! The objective of the game is to escape Alcatraz.",10,10);
            canvas.drawString("Click the screen to begin the game.",10,30);
            return;
         }
         else if (focus)
         {
             startbody(canvas);
         }


     }
    public void showstats(Graphics canvas)
    {
        int hp=10,hpmax=10,defense=0,attack=0;
        canvas.drawString("HP: " + hp ,1750,10);
        canvas.drawString("/" + hpmax,1790,10);
        canvas.drawString("Attack: " + attack,1750,30);
        canvas.drawString("Defense: " + defense,1750,50);
    }
    public void startbody(Graphics canvas)
    {
        space=enter=left=right=up=down=false;
        clearScreen(canvas);
        canvas.setColor(Color.WHITE);
        showstats(canvas);
        canvas.drawString("You are in your cell.",0,10);
        canvas.drawString("Left: To the Training Room.",0,30);
        canvas.drawString("Right: To the Showers",0,50);
        curloc=0;
        makeMove(canvas,curloc, left,right,up,down);
        canvas.drawString(" "+curloc,0,70);
    }
    public void train(Graphics canvas)
    {
        System.out.println("You are at train");
        space=enter=left=right=up=down=false;
        clearScreen(canvas);
        canvas.setColor(Color.WHITE);
        showstats(canvas);
        canvas.drawString("You are in the training room.",0,10);
        canvas.drawString("Right: To your cell.",0,30);
        makeMove(canvas,curloc,left,right,up,down);

    }
    public void showers(Graphics canvas)
    {
        System.out.println("You are in the showers");
        space=enter=left=right=up=down=false;
        clearScreen(canvas);
        canvas.setColor(Color.WHITE);
        showstats(canvas);
        canvas.drawString("You are in the showers.",0,10);
        canvas.drawString("Left: To your cell.",0,30);
        curloc=1;
        makeMove(canvas,curloc, left,right,up,down);
    }
    public void cellBlockC(Graphics canvas)
    {
        space=enter=left=right=up=down=false;
        clearScreen(canvas);
        canvas.setColor(Color.WHITE);
        canvas.drawString("You are in CellBlock C", 0, 10);
        canvas.drawString("Left: Back to your cell",0,20);
        canvas.drawString("Up: to security room 1", 0, 40);
        curloc=2;
        makeMove(canvas,curloc, left,right,up,down);
    }
    public void SecRoom1(Graphics canvas)
    {
        space=enter=left=right=up=down=false;
        clearScreen(canvas);
        canvas.setColor(Color.WHITE);
        canvas.drawString("Your in Secrity room 1.", 0, 10);
        canvas.drawString("Down: Back to Cell Block C",0,20);
        canvas.drawString("Up: Left to Guard Post", 0, 40);
        curloc=3;
        makeMove(canvas,curloc, left,right,up,down);
    }
    public void tunnel(Graphics canvas)
    {
        space=enter=left=right=up=down=false;
        clearScreen(canvas);
        canvas.setColor(Color.WHITE);
        canvas.drawString("Your in Secrity room 1.", 0, 10);
        canvas.drawString("Down: Back to Cell Block C",0,20);
        canvas.drawString("Up: Left to Guard Post", 0, 40);
        curloc=7;
        makeMove(canvas,curloc, left,right,up,down);
    }
    public void guardPost(Graphics canvas)
    {
        space=enter=left=right=up=down=false;
        clearScreen(canvas);
        canvas.setColor(Color.WHITE);
        canvas.drawString("Your in the Guard Post.", 0, 10);
        canvas.drawString("Left: to go to the Court Yard",0,20);
        canvas.drawString("Right: to go to Security room 1", 0, 40);
        canvas.drawString("Up: to go to Solitary Confinement",0,60);
        curloc=4;
        makeMove(canvas,curloc, left,right,up,down);
    }
    public void courtyard(Graphics canvas)
    {
        space=enter=left=right=up=down=false;
        clearScreen(canvas);
        canvas.setColor(Color.WHITE);
        canvas.drawString("Your in the Court Yard", 0, 10);
        canvas.drawString("Down: to Security Room 2.",0,20);
        canvas.drawString("Up: To Guard Post", 0, 40);
        curloc=8;
        makeMove(canvas,curloc, left,right,up,down);
    }
    public void SecRoom2(Graphics canvas)
    {
        space=enter=left=right=up=down=false;
        clearScreen(canvas);
        canvas.setColor(Color.WHITE);
        canvas.drawString("Your in Security Room 2.", 0, 10);
        canvas.drawString("Up: To the Court Yard", 0, 40);
        curloc=9;
        makeMove(canvas,curloc, left,right,up,down);
    }
    public void fight(Graphics canvas)
    {
        space=enter=left=right=up=down=false;
        clearScreen(canvas);
        canvas.setColor(Color.WHITE);
        canvas.drawString("Your at the Final Fight!!!", 0, 10);
        curloc=11;
        makeMove(canvas,curloc, left,right,up,down);
    }
    public void free(Graphics canvas)
    {
        space=enter=left=right=up=down=false;
        clearScreen(canvas);
        canvas.setColor(Color.WHITE);
        canvas.drawString("You Won!!!!", 0, 10);
        curloc=11;
        makeMove(canvas,curloc, left,right,up,down);
    }
    public void solitaryConfinement(Graphics canvas)
    {
        space=enter=left=right=up=down=false;
        clearScreen(canvas);
        canvas.setColor(Color.WHITE);
        canvas.drawString("Your in Solitary Confinement.", 0, 10);
        canvas.drawString("Down: Guard Post",0,20);
        curloc=5;
        makeMove(canvas,curloc, left,right,up,down);
    }
    public void makeMove(Graphics canvas,int curloc,boolean left, boolean right, boolean up, boolean down )
    {
        if (curloc==0)
        {
            if(left)
            {
                train(canvas);
                left=right=up=down=false;
            }
        }
    }
     public void delayGame(int numSecs)
     {
        int delayTime = 1000 * numSecs;
        long startDelay = System.currentTimeMillis();
        long endDelay = 0;

        while (endDelay - startDelay < delayTime)
        {
          endDelay = System.currentTimeMillis();
        }
     }
     public void clearScreen(Graphics g)
     {
        g.setColor(Color.BLACK);
        g.fillRect(0,0,5000,5000);
     }
     public void keyPressed(KeyEvent e)
     {
      int key = e.getKeyCode();


      if (key == KeyEvent.VK_LEFT)
      {
        left = true;
        repaint();
      }

      if (key == KeyEvent.VK_DOWN)
      {
        down = true;
        repaint();
      }

      if (key == KeyEvent.VK_RIGHT)
      {
        right = true;
        repaint();
      }

      if (key == KeyEvent.VK_UP)
      {
        up = true;
        repaint();
      }

      if (key == KeyEvent.VK_SPACE)
      {
        space = true;
        repaint();
      }

      if (key == KeyEvent.VK_ENTER)
      {
        enter = true;
        repaint();
      }

     }
     public void focusGained(FocusEvent evt) {focus=true; repaint();}
     public void focusLost(FocusEvent evt) {focus=false;}
     public void keyReleased(KeyEvent e){}
     public void keyTyped(KeyEvent e) {}
     public void restart(Graphics g){}

}  

so the number for curloc isnt bing passed into makeMove and the program keys arn't working.
thanks
chris s

edit:

You are at train
[message repeated 1075 time]
You are at train
Exception in thread "AWT-EventQueue-1" java.lang.StackOverflowError
    at sun.nio.cs.SingleByteEncoder.encodeArrayLoop(Unknown Source)
    at sun.nio.cs.SingleByteEncoder.encodeLoop(Unknown Source)
    at java.nio.charset.CharsetEncoder.encode(Unknown Source)
    at sun.nio.cs.StreamEncoder.implWrite(Unknown Source)
    at sun.nio.cs.StreamEncoder.write(Unknown Source)
    at java.io.OutputStreamWriter.write(Unknown Source)
    at java.io.BufferedWriter.flushBuffer(Unknown Source)
    at java.io.PrintStream.write(Unknown Source)
    at java.io.PrintStream.print(Unknown Source)
    at java.io.PrintStream.println(Unknown Source)
    at AlcatrazBreakout.train(AlcatrazBreakout.java:75)
    at AlcatrazBreakout.makeMove(AlcatrazBreakout.java:196)
    at AlcatrazBreakout.train(AlcatrazBreakout.java:81)
    at AlcatrazBreakout.makeMove(AlcatrazBreakout.java:196)
    at AlcatrazBreakout.train(AlcatrazBreakout.java:81)
    at AlcatrazBreakout.makeMove(AlcatrazBreakout.java:196)
    at AlcatrazBreakout.train(AlcatrazBreakout.java:81)
    at AlcatrazBreakout.makeMove(AlcatrazBreakout.java:196)
    at AlcatrazBreakout.train(AlcatrazBreakout.java:81)
    at AlcatrazBreakout.makeMove(AlcatrazBreakout.java:196)
    at AlcatrazBreakout.train(AlcatrazBreakout.java:81)
    at AlcatrazBreakout.makeMove(AlcatrazBreakout.java:196)
    at AlcatrazBreakout.train(AlcatrazBreakout.java:81)
    at AlcatrazBreakout.makeMove(AlcatrazBreakout.java:196)
    at AlcatrazBreakout.train(AlcatrazBreakout.java:81)
    at AlcatrazBreakout.makeMove(AlcatrazBreakout.java:196)
    at AlcatrazBreakout.train(AlcatrazBreakout.java:81)

this is my console output in Eclipse

You should NOT:

  1. Override the paint() method of the applet. Custom painting is done by overriding the paintComponent() method of a JPanel and then you add the panel to the applet.

  2. Use a tight loop to "delay" the game. Instead use a Swing Timer to schedule the next move of the game.

In a AWT/Swing (or about any GUI) program (which includes applets), you have to decouple the program logic (ie your moving between the rooms) from the painting.

This means, your keyPress and similar event-driven methods should (maybe indirectly by calling other methods) change some internal state of the program (ie in which room I'm now), then call repaint() , and be finished.

Your paint method should look at the state, paint the applet according to this state, and then be finished.

What you are doing is recursively invoking some method from itself without a recursion-end condition, and this causes the StackOverflowError (which also is the eponym for this web site) you observed.


So, here is an example applet reacting on user input:

class ExampleApplet extends JApplet {

   /** our game state. */
   private int colorCode = 0;

   /**
    * This method will be called by the applet environment on loading the applet.
    */    
   public void init() {
      EventQueue.invokeLater(new Runnable() { public void run() {
         JApplet app = ExampleApplet.this;
         app.setContentPane(new Painter());
         app.addKeyListener(new Listener());
      }});
   }

   /**
    * An object of this class is registered as a key listener for our applet.
    * It changes the game state whenever a key is typed, and then invokes repaint().
    */
   class Listener extends KeyAdapter {
      public void keyTyped(KeyEvent e) {
         colorCode ++;
         repaint();
      }
   }

   /** This class is the contentPane of the applet, and responsible for the painting. */
   class Painter extends JPanel {

      private Color chooseColor() {
          switch(colorCode % 11) {
             case  0: return Color.WHITE;
             case  1: return Color.BLUE;
             case  2: return Color.YELLOW;
             case  3: return Color.RED;
             case  4: return Color.CYAN;
             case  5: return Color.LIGHT_GRAY;
             case  6: return Color.MAGENTA;
             case  7: return Color.GREEN;
             case  8: return Color.ORANGE;
             case  9: return Color.PINK;
             case 10: return Color.BLACK;
          }
          throw new IllegalStateException("colorCode is negative: " + colorCode);
      }

      /**
       * Paints the component dependent on the current state of the game.
       */
      public void paintComponent(Graphics g) {
         g.setColor(chooseColor());
         g.fillRectangle(0,0, getHeight(), getWidth());
      }
   }

}

Of course, in your game you would not want to paint a rectangle in some color, but you would call the right painting method for the room you are currently in. Your internal state would include the room, and it would be changed to one of the other rooms when the right key is pressed.

The two problems that I spotted:

  1. In paint() you either paint the init screen('Welcome to...') or you call startbody() depending on focus . The first thing you do in startbody is space = enter = left = right = up = down = false; ie you 'clear' the values of all the 'keys'. This is why your program keys aren't having any effect. You seem to be doing this in all of your methods for different 'places' in the game

  2. You also reset curloc to 0. Same problem. And you needn't really pass curloc as an argument to different methods since it's an instance variable and will be visible everywhere in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM