#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2011
    Posts
    38
    Rep Power
    3

    Player doesnt move.


    Hey Guys,

    Im working on my PWS which is big final project for school and I am making a game. The idea is very basic it's just you, the player, and you have to survive zombies. It's a topdown shooter. But I have some difficulties.

    Here's the deal, first the applet starts and you can choose a map and difficulty, when you press start a frame with a canvas pops up. On this frame is your player and the selected level. I got the code to walk and shoot but its like the window has frozen. It gives no errors. But just nothing happens. Ill post the code beneath. And if you have any idea's please let me know.

    Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.awt.image.*;
    import java.awt.Font.*;
    import java.awt.Graphics.*;
    import java.awt.Color.*;
    import javax.swing.*;
    import java.net.*;
    
    public class FCApplet extends Applet
    implements ActionListener
    {
       // variables
      private Thread th;
      private Player player;
      private Shot [] shots;
      private Enemy enemy;
    
       // movement
      private final int shotSpeed = 5;
      private final int playerLeftSpeed = -3;
      private final int playerRightSpeed = 3;
      private final int playerUpSpeed = -3;
      private final int playerDownSpeed = 3;
      private boolean playerMoveLeft;
      private boolean playerMoveRight;
      private boolean playerMoveUp;
      private boolean playerMoveDown;
      private final int enemyLeftSpeed = -2;
      private final int enemyRightSpeed = 2;
      private final int enemyUpSpeed = -2;
      private final int enemyDownSpeed = 2;
    
       // Images
      private Image dbImage;
      private Graphics dbg;
      private Image background;
      private Image mist;
      private Image mist1;
      private Image mist2;
    
       // Buttons
      JButton play;
      private JRadioButton Makkelijk, Gemiddeld, Moeilijk;
      private JRadioButton Box, Maze;
      private ButtonGroup group1, group2;
    
       // Stuff
      AudioClip soundFile1;
      AudioClip soundFile2;
    
      public void init()
      {
        background = null;
        
        Toolkit toolkit = Toolkit.getDefaultToolkit ();
        Dimension dim = toolkit.getScreenSize();
        int width = dim.width;
        int height = dim.height;
        JButton play = new JButton(new ImageIcon("play.png"));
        play.setMnemonic('C');
    
        //play = new Button("Play");
        //  play.setFont(new Font("Arial", Font.ITALIC, 20));
    
        Makkelijk = new JRadioButton("Makkelijk", false);
        Gemiddeld = new JRadioButton("Gemiddeld", true);
        Moeilijk = new JRadioButton("Moeilijk", false);
        Box = new JRadioButton("Box", false);
        Maze = new JRadioButton("Maze", false);
        add(Makkelijk);
        add(Gemiddeld);
        add(Moeilijk);
        add(Box);
        add(Maze);
        
        group1 = new ButtonGroup();
        group1.add(Makkelijk);
        group1.add(Gemiddeld);
        group1.add(Moeilijk);
        group2 = new ButtonGroup();
        group2.add(Box);
        group2.add(Maze);
        
        JPanel moeilijkheidsgraad2 = new JPanel();
        moeilijkheidsgraad2.add(Makkelijk);
        moeilijkheidsgraad2.add(Gemiddeld);
        moeilijkheidsgraad2.add(Moeilijk);
        JPanel mapkeuze2 = new JPanel();
        mapkeuze2.add(Box);
        mapkeuze2.add(Maze);
        add(moeilijkheidsgraad2);
        add(mapkeuze2);
        
        Dimension d = getSize();
        //moeilijkheidsgraad2.setLocation(300, 300);
        //mapkeuze2.setLocation(d.width / 2, d.height / 1.5);
    
        player = new Player(200, 200);
        shots = new Shot[100];
        add(play);
        play.addActionListener(this);
        soundFile2 = getAudioClip(getDocumentBase(), "memento.wav");
        soundFile2.loop();
      }
    
      public void loadImages()
      {
        try
        {
          background = getImage(getDocumentBase(), "background.jpg");
          mist = getImage(getDocumentBase(), "mist.jpg");
          mist1 = getImage(getDocumentBase(), "mist1.jpg");
          mist2 = getImage(getDocumentBase(), "mist2.jpg");
        }
        catch(Exception e) { }
      }
    
      public void paint(Graphics g)
      {
        Dimension d = getSize();
        if (background == null)
        loadImages();
        g.drawImage(background, 0, 0, d.width, d.height, this);
      }
    
      public void actionPerformed(ActionEvent e)
      {
        new CsFrame("Spelvenster");
      }
    
      class CsFrame extends Frame
      {
        private Image mist;
    
        public CsFrame(String s)
        { super(s);
          addWindowListener(new WindowAdapter()
          {  public void windowClosing(WindowEvent e)
             {
               dispose();
             }
          });
          setLayout(new BorderLayout());
          MijnCanvas cv = new MijnCanvas();
          add("Center", cv);
          Dimension sd = getToolkit().getScreenSize();
          setSize(sd.width, sd.height);
          setLocation(0, 0);
          setVisible(true);
          setResizable(false);
        }
      }
      
    
      class MijnCanvas extends Canvas
      implements Runnable, MouseListener
      {
        public void init()
        {
          soundFile1 = getAudioClip(getDocumentBase(), "dryfire_pistol.au");
          addMouseListener(this);
        }
      
        public void start ()
        {
          th = new Thread(this);
          th.start ();
        }
    
        public void stop()
        {
          th.stop();
        }
    
        public void destroy()
        {
          th.stop();
        }
    
        public void run()
        {
          Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
    
          while (true)
          {
            // do operations on shots in shots array
            for(int i=0; i<shots.length; i++)
            {
              if(shots[i] != null)
              {
                Dimension d = getSize();
                // move shot
                shots[i].moveShot(shotSpeed);
    
                // test if shot is out
                if(shots[i].getYPos() < 0 || shots[i].getYPos() > d.height || shots[i].getXPos() < 0 || shots[i].getXPos() > d.width)
                {
                  // remove shot from array
                  shots[i] = null;
                }
              }
            }
    
            if(playerMoveLeft)
            {
              player.moveX(playerLeftSpeed);
            }
            else if(playerMoveRight)
            {
              player.moveX(playerRightSpeed);
            }
            else if(playerMoveUp)
            {
              player.moveY(playerUpSpeed);
            }
            else if(playerMoveDown)
            {
              player.moveY(playerDownSpeed);
            }
            
            repaint();
    
            try
            {
              Thread.sleep(10);
            }
            catch (InterruptedException ex)
            {
              // do nothing
            }
    
            Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
          }
        }
    
        public void processKeyEvent(KeyEvent e)
        {
          if (e.getKeyCode() == 37)
          {
            playerMoveLeft = true;
          }
          if (e.getKeyCode() == 38)
          {
            playerMoveRight = true;
          }
          if (e.getKeyCode() == 39)
          {
            playerMoveUp = true;
          }
          if (e.getKeyCode() == 40)
          {
            playerMoveDown = true;
          }
          if (e.getKeyCode() != 37)
          {
            playerMoveLeft = false;
          }
          if (e.getKeyCode() != 38)
          {
            playerMoveRight = false;
          }
          if (e.getKeyCode() != 39)
          {
            playerMoveUp = false;
          }
          if (e.getKeyCode() != 40)
          {
            playerMoveDown = false;
            //super.processKeyEvent(e);
          }
        }
    
        public void update (Graphics g)
        {
          if (dbImage == null)
          {
            dbImage = createImage (this.getSize().width, this.getSize().height);
            dbg = dbImage.getGraphics ();
          }
    
          dbg.setColor (getBackground ());
          dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
    
          dbg.setColor (getForeground());
          paint (dbg);
    
          g.drawImage (dbImage, 0, 0, this);
        }
    
        public void paint(Graphics g)
        {
          Dimension d = getSize();
          loadImages();
          
          if (Box.isSelected())
          {
            loadImages();
            g.drawImage(mist1, 0, 0, d.width, d.height, this);
            player.drawPlayer(g);
            for(int i=0; i<shots.length; i++)
            {
              if(shots[i] != null)
              {
                shots[i].drawShot(g);
              }
            }
          } else if (Maze.isSelected())
          {
            loadImages();
            g.drawImage(mist2, 0, 0, d.width, d.height, this);
            player.drawPlayer(g);
            for(int i=0; i<shots.length; i++)
            {
              if(shots[i] != null)
              {
                shots[i].drawShot(g);
              }
            }
          } else
          {
            loadImages();
            g.drawImage(mist, 0, 0, d.width, d.height, this);
            g.setFont(new Font("Arial", Font.BOLD, 20));
            g.drawString("To play, select a level before pressing 'play'.", d.width / 2 - 230, d.height / 2 - 5);
          }
        }
        
        public void mouseClicked(MouseEvent evt)
        {
          soundFile1.play();
        }
    
        public void mousePressed(MouseEvent evt) {}
        public void mouseReleased(MouseEvent evt) {}
        public void mouseEntered(MouseEvent evt) {}
        public void mouseExited(MouseEvent evt) {}
      }
    }
    I have tried it with a KeyListener too but that also didn't work out. Could it be that the update/repaint method is at the wrong place?

    Any suggestions are welcome.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2011
    Posts
    38
    Rep Power
    3
    I forgot to mention that i do get two warnings. I don't know if these are relevant but here they are.


    FCApplet.java:174:9: warning: [deprecation] stop() in java.lang.Thread has been deprecated
    th.stop();
    ^
    FCApplet.java:179:9: warning: [deprecation] stop() in java.lang.Thread has been deprecated
    th.stop();
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2011
    Posts
    3
    Rep Power
    0
    I would say that the process is running into a loop with an exception that it can't handle. I would go over the structure once more and see if you can run it in a simpler method. It looks like the if else structure for the selection could get bogged down when checking for which shots to draw.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2007
    Posts
    765
    Rep Power
    928
    In the future, these type of questions would go better in the Java forum. There's more people there with Java experience.

    Try adding KeyListener instead of overriding processKeyEvent(). Java doesn't necessarily call processKeyEvent()--it depends on the configuration of the component.

    Note that KeyEvents are dispatched to the component that currently has Focus. If you just pressed the "Play" button, it will be focused and will receive key events instead of the canvas. (I don't know of the Canvas component can even accept focus by default.) The API documentation for KeyListener explains how to work around this.

    Ignoring exceptions makes things hard to debug. Also your calls to Thread.setPriority() could be generating runtime exceptions and I don't really see the point of them.

    A javax.swing.Timer would be more reliable than Thread.sleep() for controlling your update loop.

    You're also using a mixture of AWT and Swing components. While that will probably work, it just seems like asking for complications.
    sub{*{$::{$_}}{CODE}==$_[0]&& print for(%:: )}->(\&Meh);
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2011
    Posts
    38
    Rep Power
    3
    Thanks for the replies, but I actually got it working since two days. I went to a someone and he fixed it. I just encountered some more complications but that shouldnt be a too big problem.
    I'll post the code later for those interested or anyone with the same problem.
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2011
    Posts
    38
    Rep Power
    3
    Code:
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class FCApplet extends Applet implements ActionListener
    {
       // variables
      private Thread th;
      private Player player;
      private Shot [] shots;
    
       // movement/looking
      private final int shotSpeed = 5;
      private final int playerLeftSpeed = -2;
      private final int playerRightSpeed = 2;
      private final int playerUpSpeed = -2;
      private final int playerDownSpeed = 2;
      private boolean playerMoveLeft;
      private boolean playerMoveRight;
      private boolean playerMoveUp;
      private boolean playerMoveDown;
      private boolean mouseMove;
    
       // Images
      private Image dbImage;
      private Graphics dbg;
      private Image background;
      private Image mist;
      private Image mist1;
      private Image mist2;
      Image speler;
    
       // Buttons
      JButton play;
      private JRadioButton Makkelijk, Gemiddeld, Moeilijk;
      private JRadioButton Box, Maze;
      private ButtonGroup group1, group2;
    
       // Stuff
      AudioClip soundFile1;
      AudioClip soundFile2;
    
    
      public void init()
      {
        background = null;
        
        JButton play = new JButton(new ImageIcon(getClass().getResource("play.png")));
        play.setMnemonic('C');
    
        //play = new Button("Play");
        //  play.setFont(new Font("Arial", Font.ITALIC, 20));
    
        Makkelijk = new JRadioButton("Makkelijk", false);
        Gemiddeld = new JRadioButton("Gemiddeld", true);
        Moeilijk = new JRadioButton("Moeilijk", false);
        Box = new JRadioButton("Box", false);
        Maze = new JRadioButton("Maze", false);
        add(Makkelijk);
        add(Gemiddeld);
        add(Moeilijk);
        add(Box);
        add(Maze);
        
        group1 = new ButtonGroup();
        group1.add(Makkelijk);
        group1.add(Gemiddeld);
        group1.add(Moeilijk);
        group2 = new ButtonGroup();
        group2.add(Box);
        group2.add(Maze);
        
        JPanel moeilijkheidsgraad2 = new JPanel();
        moeilijkheidsgraad2.add(Makkelijk);
        moeilijkheidsgraad2.add(Gemiddeld);
        moeilijkheidsgraad2.add(Moeilijk);
        JPanel mapkeuze2 = new JPanel();
        mapkeuze2.add(Box);
        mapkeuze2.add(Maze);
        add(moeilijkheidsgraad2);
        add(mapkeuze2);
        
        //moeilijkheidsgraad2.setLocation(300, 300);
        //mapkeuze2.setLocation(d.width / 2, d.height / 1.5);
        
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        player = new Player(d.width / 2, d.height / 2);
        //player = new Player(
        shots = new Shot[100];
        
        add(play);
        play.addActionListener(this);
        
        soundFile2 = getAudioClip(getDocumentBase(), "memento.wav");
        //soundFile2.loop();
      }
    
      public void loadImages()
      {
        try
        {
          background = getImage(getDocumentBase(), "background.jpg");
          mist = getImage(getDocumentBase(), "mist.jpg");
          mist1 = getImage(getDocumentBase(), "mist1.jpg");
          mist2 = getImage(getDocumentBase(), "mist2.jpg");
          speler = getImage(getDocumentBase(), "spelertje.png");
        }
        catch(Exception e) { }
      }
    
      public void paint(Graphics g)
      {
        Dimension d = getSize();
        if (background == null)
        loadImages();
        g.drawImage(background, 0, 0, d.width, d.height, this);
      }
    
      public void actionPerformed(ActionEvent e)
      {
        CsFrame cs = new CsFrame("Spelvenster");
        cs.addKeyListener(new KeyAdapter()
        {
          @Override
          public void keyReleased(KeyEvent e)
          {
            switch (e.getKeyCode())
            {
              case KeyEvent.VK_LEFT:
                playerMoveLeft = false;
                break;
              case KeyEvent.VK_RIGHT:
                playerMoveRight = false;
                break;
              case KeyEvent.VK_UP:
                playerMoveUp = false;
                break;
              case KeyEvent.VK_DOWN:
                playerMoveDown = false;
                break;
            }
          }
          
          @Override
          public void keyPressed(KeyEvent e)
          {
            switch (e.getKeyCode())
            {
              case KeyEvent.VK_LEFT:
                playerMoveLeft = true;
                break;
              case KeyEvent.VK_RIGHT:
                playerMoveRight = true;
                break;
              case KeyEvent.VK_UP:
                playerMoveUp = true;
                break;
              case KeyEvent.VK_DOWN:
                playerMoveDown = true;
                break;
            }
          }
        });
      }
    
      class CsFrame extends Frame
      {
        public CsFrame(String s)
        { super(s);
          addWindowListener(new WindowAdapter()
          {  public void windowClosing(WindowEvent e)
             {
               dispose();
             }
          });
          setLayout(new BorderLayout());
          MijnCanvas cv = new MijnCanvas();
          add("Center", cv);
          Dimension sd = getToolkit().getScreenSize();
          setSize(sd.width, sd.height);
          setLocation(0, 0);
          setVisible(true);
          setResizable(false);
          cv.setFocusable(false);
        }
      }
    
      class MijnCanvas extends Canvas implements Runnable, MouseListener, MouseMotionListener
      {
        double mousex, mousey;
        double playerx, playery;
        double dx, dy;
        double angle;
      
        public MijnCanvas()
        {
          super();
          init();
        }
      
        public void init()
        {
          soundFile1 = getAudioClip(getDocumentBase(), "dryfire_pistol.au");
          addMouseListener(this);
          addMouseMotionListener(this);
          th = new Thread(this);
          th.start ();
        }
      
        public void run()
        {
          Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
    
          while (true)
          {
            // do operations on shots in shots array
            for(int i=0; i<shots.length; i++)
            {
              if(shots[i] != null)
              {
                Dimension d = getSize();
                // move shot
                shots[i].moveShot(shotSpeed);
    
                // test if shot is out
                if(shots[i].getYPos() < 0 || shots[i].getYPos() > d.height || shots[i].getXPos() < 0 || shots[i].getXPos() > d.width)
                {
                  // remove shot from array
                  shots[i] = null;
                }
              }
            }
    
            if(playerMoveLeft && playerMoveUp)
            {
              player.moveX(playerLeftSpeed);
              player.moveY(playerUpSpeed);
            }
            else if(playerMoveUp && playerMoveRight)
            {
              player.moveX(playerRightSpeed);
              player.moveY(playerUpSpeed);
            }
            else if(playerMoveRight && playerMoveDown)
            {
              player.moveX(playerRightSpeed);
              player.moveY(playerDownSpeed);
            }
            else if(playerMoveLeft && playerMoveDown)
            {
              player.moveX(playerLeftSpeed);
              player.moveY(playerDownSpeed);
            }
            else if(playerMoveLeft)
            {
              player.moveX(playerLeftSpeed);
            }
            else if(playerMoveRight)
            {
              player.moveX(playerRightSpeed);
            }
            else if(playerMoveUp)
            {
              player.moveY(playerUpSpeed);
            }
            else if(playerMoveDown)
            {
              player.moveY(playerDownSpeed);
            }
            
    
            
            repaint();
    
            try
            {
              Thread.sleep(10);
            }
            catch (InterruptedException ex)
            {
              // do nothing
            }
    
            Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
          }
        }
    
        public void update (Graphics g)
        {
          if (dbImage == null)
          {
            dbImage = createImage (this.getSize().width, this.getSize().height);
            dbg = dbImage.getGraphics ();
          }
    
          dbg.setColor (getBackground ());
          dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
    
          dbg.setColor (getForeground());
          paint (dbg);
    
          g.drawImage (dbImage, 0, 0, this);
        }
    
        public void paint(Graphics g)
        {
          Dimension d = getSize();
          loadImages();
          
          if (Box.isSelected())
          {
            g.drawImage(mist1, 0, 0, d.width, d.height, this);
            g.drawImage(speler, player.x_pos, player.y_pos, 60, 30, null);
            for(int i=0; i<shots.length; i++)
            {
              if(shots[i] != null)
              {
                shots[i].drawShot(g);
              }
            }
          } else if (Maze.isSelected())
          {
            g.drawImage(mist2, 0, 0, d.width, d.height, this);
            g.drawImage(speler, player.x_pos, player.y_pos, 60, 30, null);
            for(int i=0; i<shots.length; i++)
            {
              if(shots[i] != null)
              {
                shots[i].drawShot(g);
              }
            }
          } else
          {
            g.drawImage(mist, 0, 0, d.width, d.height, this);
            g.setFont(new Font("Arial", Font.BOLD, 20));
            g.drawString("To play, select a level before pressing 'play'.", d.width / 2 - 230, d.height / 2 - 5);
          }
        }
        
        public void mouseClicked(MouseEvent evt)
        {
          soundFile1.play();
        }
    
        public void mousePressed(MouseEvent evt)
        {
          soundFile1.play();
        }
        
        public void mouseMoved(MouseEvent e)
        {
          mousex = e.getX();
          mousey = e.getY();
          playerx = player.x_pos;
          playery = player.y_pos;
          dx = mousex - playerx;
          dy = mousey - playery;
          
          angle = Math.atan(dy/dx);
          if (dx < 0)
            angle += Math.PI;
    
          if (angle < 0)
            angle += 2 * Math.PI;
    
          double degrees = Math.toDegrees(angle);
    
          //System.out.println(awesome);
        }
    
        public void mouseDragged(MouseEvent e) {}
        public void mouseReleased(MouseEvent evt) {}
        public void mouseEntered(MouseEvent evt) {}
        public void mouseExited(MouseEvent evt) {}
      }
    }
    So that's my code atm.
    I have a little issue though.

    Can someone explain to me how to let the player image look at the mouse? I made a start already at mouseMoved and I think i got the right angle, just the repainting part is what i dont get. I think I should use something like Graphics2D.rotate but I just won't get it working. Can someone take a look pls?

IMN logo majestic logo threadwatch logo seochat tools logo