Changing a game 2 player using swing timer to threads

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 3842 Views - Last Post: 02 June 2010 - 05:42 PM Rate Topic: -----

#1 kngofdrkns  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 82
  • Joined: 21-May 08

Changing a game 2 player using swing timer to threads

Posted 01 June 2010 - 10:11 AM

I made a two player pacman game using timer and it works. I want to replace the Swing Timer with the Thread. The game is consisted of 5 classes.

Fruit class:
public class Fruit {
    public double x = 0, y =0, fSize;
    public boolean eaten = false;
    
public void drawFruit (Graphics g) {

  g.setColor (Color.red);
  g.fillOval ((int) x, (int) y, (int) fSize, (int) fSize);
        }
}


Restart Class:
class Restart {

    public Restart() {
        PacmanPanel.xBase = 620;
        PacmanPanel.xBase1 = 307;
        PacmanPanel.yBase = 620;
        PacmanPanel.yBase1 = 307;
        PacmanPanel.score = 0;
        Pressed.leftPressed = false;
        Pressed.rightPressed = false;
        Pressed.upPressed = false;
        Pressed.downPressed = false;
        Pressed.aPressed = false;
        Pressed.dPressed = false;
        Pressed.wPressed = false;
        Pressed.sPressed = false;
        for(int i=0; i<400;i++){
            PacmanFrame.fruit[i].fSize = 5.0;
        }
        if(!PacmanPanel.time.isRunning()){
            PacmanPanel.time.start();
        }
    }

}


Pressed Class:
public class Pressed implements KeyListener{

        public static boolean leftPressed = false;
        public static boolean rightPressed = false;
        public static boolean upPressed = false;
        public static boolean downPressed = false;
        public static boolean aPressed = false;
        public static boolean dPressed = false;
        public static boolean wPressed = false;
        public static boolean sPressed = false;
        public static boolean openedYellow;
        public static boolean openedBlue;


        @Override
        public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();
                setState(keyCode, true);
        }

        @Override
        public void keyReleased(KeyEvent e) {
                int keyCode = e.getKeyCode();
                setState(keyCode, false);
        }

        @Override
        public void keyTyped(KeyEvent e) {}

        void setState(int keyCode, boolean state) {
                switch(keyCode) {
                        case KeyEvent.VK_LEFT:
                                leftPressed = state;
                                break;
                        case KeyEvent.VK_RIGHT:
                                rightPressed = state;
                                break;
                        case KeyEvent.VK_UP:
                                upPressed =  state;
                                break;
                        case KeyEvent.VK_DOWN:
                                downPressed = state;
                                break;
                        case KeyEvent.VK_A:
                                aPressed = state;
                                break;
                        case KeyEvent.VK_D:
                                dPressed = state;
                                break;
                        case KeyEvent.VK_W:
                                wPressed =  state;
                                break;
                        case KeyEvent.VK_S:
                                sPressed = state;
                                break;
                }
        }
}


PacmanPanel Class:
public class PacmanPanel extends JPanel implements ActionListener{    // This method allows us to paint.
    public static Timer time;
    public static int xBase = 620 ,yBase = 620;
    public  static int xBase1 = 307, yBase1 = 307;
    int x = 0 , i = 0;
    public static boolean restart;
    public static int score = 0;
    public static int scorePercent = 0;

    public PacmanPanel(){
        // Every time Timer executes, update everything

        setSize(669, 699);
        
        time = new Timer(15, this);
        time.start();
 
 }

        private void updateAll() {

            if (Pressed.rightPressed){
                xBase += 2;
            }
            else if (Pressed.leftPressed){
                xBase -= 2;
            }
            if (Pressed.upPressed){
                yBase -= 2;
            }
            else if (Pressed.downPressed){
                yBase += 2;
            }

            if (Pressed.dPressed){
                xBase1 += 2;
            }
            else if (Pressed.aPressed){
                xBase1 -= 2;
            }
            if (Pressed.wPressed){
                yBase1 -= 2;
            }
            else if (Pressed.sPressed){
                yBase1 += 2;
                }

            if(xBase > PacmanFrame.FrameW - 130)
                xBase = 20;
            if(xBase1 > PacmanFrame.FrameW - 130)
                xBase1 = 20;

            if(xBase < 0)
                xBase = PacmanFrame.FrameW - 130;
            if(xBase1 < 0)
                xBase1 = PacmanFrame.FrameW - 130;

            Rectangle bounds = new Rectangle(xBase, yBase, 24, 24);
            bounds.createIntersection(bounds);
            Rectangle bounds1 = new Rectangle(xBase1, yBase1, 24, 24);
            bounds.createIntersection(bounds1);
            if(bounds.intersects(bounds1)){
                JOptionPane.showMessageDialog(null, "The Yellow pac man died!!!!\n" + " score =  " + score+" Fruits"+
                        "\n Percentage = "+scorePercent+"%");
                time.stop();
            }

            for(int i = 0; i < PacmanFrame.dotct; i++){
            Rectangle bounds2 = new Rectangle((int) PacmanFrame.fruit[i].x, (int) PacmanFrame.fruit[i].y,
                   (int) PacmanFrame.fruit[i].fSize,(int) PacmanFrame.fruit[i].fSize);
            bounds.createIntersection(bounds2);
            if(bounds.intersects(bounds2) && PacmanFrame.fruit[i].fSize == 5.0){
                score = score + 1;
                scorePercent = score / 4;
                System.out.println(score);
            }
            }

            for(int i = 0; i < PacmanFrame.dotct; i++){
            Rectangle bounds2 = new Rectangle((int) PacmanFrame.fruit[i].x, (int) PacmanFrame.fruit[i].y,
                   (int) PacmanFrame.fruit[i].fSize,(int) PacmanFrame.fruit[i].fSize);
            bounds.createIntersection(bounds2);
            if(bounds.intersects(bounds2)){
                PacmanFrame.fruit[i].fSize = 0.0;
            }
            }

            if(score == 400){
                JOptionPane.showMessageDialog(null, "The yellow pacman WON!!!\n"+" score = "+score+" Fruits"+
                        "\n Percentage = "+scorePercent+"%");
                time.stop();
            }
            Rectangle bounds3 = new Rectangle(103, 100, 10, 270);
            bounds3.createIntersection(bounds3);
           if((xBase < 103) && (bounds.intersects(bounds3))){
                xBase -= 5;
           }

            if((xBase1 < 103) && (bounds1.intersects(bounds3))){
                xBase1 -= 5;
           }

            if((xBase > 103)&& (bounds.intersects(bounds3))){
                xBase += 5;
           }

            if((xBase1 > 103) && bounds1.intersects(bounds3)){
                xBase1 += 5;
           }

            Rectangle bounds4 = new Rectangle(0, 650, 653, 10);
            bounds4.createIntersection(bounds4);

            if((yBase < 650)&& (bounds.intersects(bounds4))){
                yBase -= 5;
           }

            if((yBase1 < 650) && bounds1.intersects(bounds4)){
                yBase1 -= 5;
           }

            Rectangle bounds5 = new Rectangle(50, 403, 450, 10);
            bounds5.createIntersection(bounds5);

            if((yBase < 403)&& (bounds.intersects(bounds5))){
                yBase -= 5;
           }
            if((yBase1 < 403) && bounds1.intersects(bounds5)){
                yBase1 -= 5;
           }
            if((yBase > 403)&& (bounds.intersects(bounds5))){
                yBase += 5;
           }

            if((yBase1 > 403) && bounds1.intersects(bounds5)){
                yBase1 += 5;
           }

            Rectangle bounds6 = new Rectangle(0, 0, 653, 10);
            bounds6.createIntersection(bounds6);

            if((yBase > 0)&& (bounds.intersects(bounds6))){
                yBase += 5;
           }

            if((yBase1 > 0) && bounds1.intersects(bounds6)){
                yBase1 += 5;
           }

            Rectangle bounds7 = new Rectangle(585, 70, 10, 200);
            bounds7.createIntersection(bounds7);

            if((xBase > 585)&& (bounds.intersects(bounds7))){
                xBase += 5;
           }

            if((xBase1 > 585) && bounds1.intersects(bounds7)){
                xBase1 += 5;
           }
            if((xBase < 585)&& (bounds.intersects(bounds7))){
                xBase -= 5;
           }

            if((xBase1 < 585) && bounds1.intersects(bounds7)){
                xBase1 -= 5;
           }

            if(i% 2 == 0){
                Pressed.openedYellow = true;
            }
            else{
                        Pressed.openedYellow = false;
            }
            i++;

            repaint();
}
    public void paintComponent (Graphics g) {
super.paintComponent(g);
         setBackground(Color.black);
 g.setColor (Color.yellow);
        if (Pressed.openedYellow)
                g.fillArc (xBase, yBase, 25, 25, 45, 270);
        else
                g.fillArc (xBase, yBase, 25, 25, 0, 360);

 g.setColor (Color.blue);
 if (Pressed.openedYellow)
                g.fillArc (xBase1, yBase1,25,25,45,270);
        else
                g.fillArc (xBase1, yBase1,25,25,0,360);

 g.setColor(Color.white);

 g.fillRect(0, 650, 653, 10);
 g.fillRect(0, 0, 653, 10);
 g.fillRect(50, 403, 450, 10);
 g.fillRect(103, 100, 10, 270);
 g.fillRect(585, 70, 10, 200);
 g.setColor(Color.ORANGE);
 g.drawString("your score is "+ score, PacmanFrame.FrameW - 120, 100);
 for (int i=0; i < PacmanFrame.dotct; i++) {

     PacmanFrame.fruit[i].drawFruit(g);
         }
}

    public void actionPerformed(ActionEvent e) {
        updateAll();
    }
        }


PacmanFrame Class:
public class PacmanFrame extends JFrame implements ActionListener, KeyListener{

        // Have these set up so they can be seen everywhere
        public static final int FrameW = 760;
        public static final int FrameH = 720;
        public static int place = 30, place1 = 30;
        public static Fruit[] fruit = new Fruit[1000];
        public static int dotct = 0;
        PacmanPanel panel = new PacmanPanel();
        JPanel panel1 = new JPanel();
        public static boolean died = false;

        public PacmanFrame() {
                super("Pacman Game");
     
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                setSize(FrameW, FrameH);
                
                add(panel, BorderLayout.CENTER);

                for(int i=0;i < 400;i++) {
                    fruit[i] = new Fruit();
                    fruit[i].x = place;
                    fruit[i].y = place1;
                    if(!fruit[i].eaten){
                    fruit[i].fSize = 5.0;
                    }
                    else
                        fruit[i].fSize = 0;
                    place += 30;
                    if(place == 630){
                        place1 += 30;
                        place = 30;
                    }
                    dotct++;
                    repaint();
                }

                JOptionPane.showMessageDialog(null, "1)\nYellow move with arrows(UP,DOWN,RIGHT,LEFT).\n"+
                        "2)\nBlue move with letters(W,S,D,A)\n"+
                        "3)\nThe Yellow pacman must eat as many as it can from the fruits before the blue one catch him.\n"+
                        "4)\nThe Blue pacman must kill the yellow one by coliding to him before the yellow one eat more Fruits.\n");

                setVisible(true);

        Pressed press = new Pressed();

                setFocusable(true);
                requestFocus();
                addKeyListener(this);
                addKeyListener(press);

                JMenu menu2 = new JMenu("OPTIONS");
                JMenuBar bar = new JMenuBar();
                menu2.setForeground(Color.blue);
                JPanel panel9 = new JPanel();
                JButton jb1 = new JButton("RESTART (f2)");
                JButton jb2 = new JButton("EXIT (f4)");
                jb1.addActionListener(this);
                jb2.addActionListener(this);
                panel9.add(jb1);
                panel9.add(jb2);
                menu2.add(panel9);
                bar.add(menu2);
                add(bar, BorderLayout.NORTH);

        }   

        public static void main(String[] args) {


            javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new PacmanFrame();
            }
        });
        
        }

    public void actionPerformed(ActionEvent e) {
    if(e.getActionCommand().equals("RESTART (f2)")){
        new Restart();
    }
    if(e.getActionCommand().equals("EXIT (f4)")){
        JOptionPane pane = new JOptionPane(
        "Are you sure yo want to Exit ?");
            Object[] status = new String[] { "Yes", "No" };
            pane.setOptions(status);
            JDialog dialog = pane.createDialog(new JFrame(), "Confirmation");
               dialog.show();
               if (status[0].equals(pane.getValue())){
        System.exit(0);
               }
            }
    }

    public void keyTyped(KeyEvent e) {
    }

    public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_F4){
               JOptionPane pane = new JOptionPane(
        "Are you sure yo want to Exit ?");
            Object[] status = new String[] { "Yes", "No" };
            pane.setOptions(status);
            JDialog dialog = pane.createDialog(new JFrame(), "Confirmation");
               dialog.show();
               if (status[0].equals(pane.getValue())){
        System.exit(0);
               }
    }
    if (e.getKeyCode() == KeyEvent.VK_F2){
               new Restart();
                }

    }

    public void keyReleased(KeyEvent e) {
    }
    }



Is This A Good Question/Topic? 0
  • +

Replies To: Changing a game 2 player using swing timer to threads

#2 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1011
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: Changing a game 2 player using swing timer to threads

Posted 01 June 2010 - 10:25 AM

Why would you do it? swing is not considered as thread safe. so a swing timer is a much better choice here.
anyways, to use a Thread you can do one of the follows:
your class should extends Thread:
public class MyClass extends Thread {
...


OR implement the runnable interface:
public class MyClass implemets Runnable {
...


There is no much difference between the two options, However if 'MyClass' already extends another class, you will have to implement Runnable, as you probably know that a single class can't extend more than one class.

to get you started, here is some info about Threads:
http://www.javabegin...hreads-tutorial
java sun tutorial:
http://java.sun.com/.../runthread.html
Was This Post Helpful? 2
  • +
  • -

#3 kngofdrkns  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 82
  • Joined: 21-May 08

Re: Changing a game 2 player using swing timer to threads

Posted 01 June 2010 - 10:36 AM

It is an assignment and i sent the timer games they said they need it using threads thats all so i want to pass so i will do it even if it is not good :death:
thank you for your help

This post has been edited by kngofdrkns: 01 June 2010 - 10:36 AM

Was This Post Helpful? 0
  • +
  • -

#4 kngofdrkns  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 82
  • Joined: 21-May 08

Re: Changing a game 2 player using swing timer to threads

Posted 01 June 2010 - 11:49 AM

now i removed the timer and removed
UpdateAll()
method and created 3 new classes extending thread but i don't know how to make it work
here are the classes
UpdateArrow class:
public class UpdateArrow extends Thread{
    public void UpdateArrow(){
        start();
        if (Pressed.rightPressed){
                PacmanPanel.xBase += 2;
            }
            else if (Pressed.leftPressed){
                PacmanPanel.xBase -= 2;
            }
            if (Pressed.upPressed){
                PacmanPanel.yBase -= 2;
            }
            else if (Pressed.downPressed){
                PacmanPanel.yBase += 2;
            }
    }
}


UpdateLetter class
public class UpdateLetter extends Thread {
    public void UpdateLetter(){
        start();
        if (Pressed.dPressed){
                PacmanPanel.xBase1 += 2;
            }
            else if (Pressed.aPressed){
                PacmanPanel.xBase1 -= 2;
            }
            if (Pressed.wPressed){
                PacmanPanel.yBase1 -= 2;
            }
            else if (Pressed.sPressed){
                PacmanPanel.yBase1 += 2;
                }
    }
}


UpdateDots class
public class UpdateDots extends Thread{
    public  void UpdateDots(){
start();
            if(PacmanPanel.xBase > PacmanFrame.FrameW - 130)
                PacmanPanel.xBase = 20;
            if(PacmanPanel.xBase1 > PacmanFrame.FrameW - 130)
                PacmanPanel.xBase1 = 20;

            if(PacmanPanel.xBase < 0)
                PacmanPanel.xBase = PacmanFrame.FrameW - 130;
            if(PacmanPanel.xBase1 < 0)
                PacmanPanel.xBase1 = PacmanFrame.FrameW - 130;

            Rectangle bounds = new Rectangle(PacmanPanel.xBase, PacmanPanel.yBase, 24, 24);
            bounds.createIntersection(bounds);
            Rectangle bounds1 = new Rectangle(PacmanPanel.xBase1, PacmanPanel.yBase1, 24, 24);
            bounds.createIntersection(bounds1);
            if(bounds.intersects(bounds1)){
                JOptionPane.showMessageDialog(null, "The Yellow pac man died!!!!\n" + " score =  " + PacmanPanel.score+" Fruits"+
                        "\n Percentage = "+PacmanPanel.scorePercent+"%");
                stop();
            }

            for(int i = 0; i < PacmanFrame.dotct; i++){
            Rectangle bounds2 = new Rectangle((int) PacmanFrame.fruit[i].x, (int) PacmanFrame.fruit[i].y,
                   (int) PacmanFrame.fruit[i].fSize,(int) PacmanFrame.fruit[i].fSize);
            bounds.createIntersection(bounds2);
            if(bounds.intersects(bounds2) && PacmanFrame.fruit[i].fSize == 5.0){
                PacmanPanel.score = PacmanPanel.score + 1;
                PacmanPanel.scorePercent = PacmanPanel.score / 4;
                System.out.println(PacmanPanel.score);
            }
            }

            for(int i = 0; i < PacmanFrame.dotct; i++){
            Rectangle bounds2 = new Rectangle((int) PacmanFrame.fruit[i].x, (int) PacmanFrame.fruit[i].y,
                   (int) PacmanFrame.fruit[i].fSize,(int) PacmanFrame.fruit[i].fSize);
            bounds.createIntersection(bounds2);
            if(bounds.intersects(bounds2)){
                PacmanFrame.fruit[i].fSize = 0.0;
            }
            }

            if(PacmanPanel.score == 400){
                JOptionPane.showMessageDialog(null, "The yellow pacman WON!!!\n"+" score = "+PacmanPanel.score+" Fruits"+
                        "\n Percentage = "+PacmanPanel.scorePercent+"%");
                stop();
            }
            Rectangle bounds3 = new Rectangle(103, 100, 10, 270);
            bounds3.createIntersection(bounds3);
           if((PacmanPanel.xBase < 103) && (bounds.intersects(bounds3))){
                PacmanPanel.xBase -= 5;
           }

            if((PacmanPanel.xBase1 < 103) && (bounds1.intersects(bounds3))){
                PacmanPanel.xBase1 -= 5;
           }

            if((PacmanPanel.xBase > 103)&& (bounds.intersects(bounds3))){
                PacmanPanel.xBase += 5;
           }

            if((PacmanPanel.xBase1 > 103) && bounds1.intersects(bounds3)){
                PacmanPanel.xBase1 += 5;
           }

            Rectangle bounds4 = new Rectangle(0, 650, 653, 10);
            bounds4.createIntersection(bounds4);

            if((PacmanPanel.yBase < 650)&& (bounds.intersects(bounds4))){
                PacmanPanel.yBase -= 5;
           }

            if((PacmanPanel.yBase1 < 650) && bounds1.intersects(bounds4)){
                PacmanPanel.yBase1 -= 5;
           }

            Rectangle bounds5 = new Rectangle(50, 403, 450, 10);
            bounds5.createIntersection(bounds5);

            if((PacmanPanel.yBase < 403)&& (bounds.intersects(bounds5))){
                PacmanPanel.yBase -= 5;
           }
            if((PacmanPanel.yBase1 < 403) && bounds1.intersects(bounds5)){
                PacmanPanel.yBase1 -= 5;
           }
            if((PacmanPanel.yBase > 403)&& (bounds.intersects(bounds5))){
                PacmanPanel.yBase += 5;
           }

            if((PacmanPanel.yBase1 > 403) && bounds1.intersects(bounds5)){
                PacmanPanel.yBase1 += 5;
           }

            Rectangle bounds6 = new Rectangle(0, 0, 653, 10);
            bounds6.createIntersection(bounds6);

            if((PacmanPanel.yBase > 0)&& (bounds.intersects(bounds6))){
                PacmanPanel.yBase += 5;
           }

            if((PacmanPanel.yBase1 > 0) && bounds1.intersects(bounds6)){
                PacmanPanel.yBase1 += 5;
           }

            Rectangle bounds7 = new Rectangle(585, 70, 10, 200);
            bounds7.createIntersection(bounds7);

            if((PacmanPanel.xBase > 585)&& (bounds.intersects(bounds7))){
                PacmanPanel.xBase += 5;
           }

            if((PacmanPanel.xBase1 > 585) && bounds1.intersects(bounds7)){
                PacmanPanel.xBase1 += 5;
           }
            if((PacmanPanel.xBase < 585)&& (bounds.intersects(bounds7))){
                PacmanPanel.xBase -= 5;
           }

            if((PacmanPanel.xBase1 < 585) && bounds1.intersects(bounds7)){
                PacmanPanel.xBase1 -= 5;
           }

            if(PacmanPanel.i% 2 == 0){
                Pressed.openedYellow = true;
            }
            else{
                        Pressed.openedYellow = false;
            }
            PacmanPanel.i++;

    }
}


the updated PacmanPanel class:
public class PacmanPanel extends JPanel implements ActionListener{    // This method allows us to paint.

    public static int xBase = 620 ,yBase = 620;
    public  static int xBase1 = 307, yBase1 = 307;
    public static int x = 0 , i = 0;
    public static boolean restart;
    public static int score = 0;
    public static int scorePercent = 0;
    public static UpdateArrow ua;
    public static UpdateLetter ul;
    public static UpdateDots ud;

    public PacmanPanel(){

        setSize(669, 699);
        ua = new UpdateArrow();
        ua.start();
        ul = new UpdateLetter();
        ul.start();
        ud = new UpdateDots();
        ud.start();

 }

    public void paintComponent (Graphics g) {
super.paintComponent(g);
         setBackground(Color.black);
 g.setColor (Color.yellow);
        if (Pressed.openedYellow)
                g.fillArc (xBase, yBase, 25, 25, 45, 270);
        else
                g.fillArc (xBase, yBase, 25, 25, 0, 360);

 g.setColor (Color.blue);
 if (Pressed.openedYellow)
                g.fillArc (xBase1, yBase1,25,25,45,270);
        else
                g.fillArc (xBase1, yBase1,25,25,0,360);

 g.setColor(Color.white);

 g.fillRect(0, 650, 653, 10);
 g.fillRect(0, 0, 653, 10);
 g.fillRect(50, 403, 450, 10);
 g.fillRect(103, 100, 10, 270);
 g.fillRect(585, 70, 10, 200);
 g.setColor(Color.ORANGE);
 g.drawString("your score is "+ score, PacmanFrame.FrameW - 120, 100);
 for (int i=0; i < PacmanFrame.dotct; i++) {

     PacmanFrame.fruit[i].drawFruit(g);
         }
}

    public void actionPerformed(ActionEvent e) {

        repaint();

    }
        }


i don't understand threads well so please help
Thanks!!!

This post has been edited by kngofdrkns: 01 June 2010 - 12:40 PM

Was This Post Helpful? 0
  • +
  • -

#5 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1011
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: Changing a game 2 player using swing timer to threads

Posted 01 June 2010 - 02:21 PM

I would implement Runnable in the PacManPanel class.
like so:
public class PacmanPanel extends JPanel implements Runnable{
 
//all components, methods...
//the thread:
private Thread t = new Thread(this);

//constructor
public PacmanPanel(){
   //init components...
   t.start();
}


//then override the run method:

public void run(){
    while(true){
        //update input
        //update logic
        //repaint

        try {
           Thread.sleep(20);
        }catch(Exception e){e.printStactTrace();}
    }
}


note that you can also override the addNotify method of the JPanel, to start the thread.

This post has been edited by japanir: 01 June 2010 - 02:22 PM

Was This Post Helpful? 2
  • +
  • -

#6 kngofdrkns  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 82
  • Joined: 21-May 08

Re: Changing a game 2 player using swing timer to threads

Posted 01 June 2010 - 02:50 PM

View Postjapanir, on 01 June 2010 - 01:21 PM, said:

I would implement Runnable in the PacManPanel class.
like so:

note that you can also override the addNotify method of the JPanel, to start the thread.

Thank you alot my friendly :angel: it works well i will add images to make it look better and i hope there is no further problems.
Was This Post Helpful? 0
  • +
  • -

#7 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10803
  • View blog
  • Posts: 40,273
  • Joined: 27-December 08

Re: Changing a game 2 player using swing timer to threads

Posted 01 June 2010 - 02:55 PM

@japanir: Really good shows. :^:

@kngofdrkns: You may also want to check out Dogstopper's tutorial on using SwingWorker to make your GUI Thread-safe.
Was This Post Helpful? 0
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8346
  • View blog
  • Posts: 31,908
  • Joined: 06-March 08

Re: Changing a game 2 player using swing timer to threads

Posted 01 June 2010 - 03:48 PM

View Postkngofdrkns, on 01 June 2010 - 11:11 AM, said:

I made a two player pacman game using timer and it works. I want to replace the Swing Timer with the Thread.

NOT A GOOD IDEA AT ALL.
What does motivate that decison ?
Was This Post Helpful? 0
  • +
  • -

#9 kngofdrkns  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 82
  • Joined: 21-May 08

Re: Changing a game 2 player using swing timer to threads

Posted 01 June 2010 - 04:06 PM

View Postpbl, on 01 June 2010 - 02:48 PM, said:

View Postkngofdrkns, on 01 June 2010 - 11:11 AM, said:

I made a two player pacman game using timer and it works. I want to replace the Swing Timer with the Thread.

NOT A GOOD IDEA AT ALL.
What does motivate that decison ?

The problem is that it is my teacher decison i submited the timer game they gave me 11/20 and i asked they said because we want threads so i asked about it thats all :stuart:
Was This Post Helpful? 0
  • +
  • -

#10 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2831
  • View blog
  • Posts: 11,991
  • Joined: 20-September 08

Re: Changing a game 2 player using swing timer to threads

Posted 01 June 2010 - 04:09 PM

Quote

they said because we want threads


Do us a favour - please post your teacher's specimen answer will you?

This post has been edited by g00se: 01 June 2010 - 04:09 PM

Was This Post Helpful? 0
  • +
  • -

#11 kngofdrkns  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 82
  • Joined: 21-May 08

Re: Changing a game 2 player using swing timer to threads

Posted 01 June 2010 - 04:11 PM

View Postg00se, on 01 June 2010 - 03:09 PM, said:

Quote

they said because we want threads


Do us a favour - please post your teacher's specimen answer will you?

the teacher answer (
The problem with your assignment was that:

It wasn't implemented as an applet or it didn't include a thread. A lot of marks were assigned to this.

Then comes the exception handling.

Can you include a thread and some try and catch, then re-submit quickly?

)
Was This Post Helpful? 0
  • +
  • -

#12 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8346
  • View blog
  • Posts: 31,908
  • Joined: 06-March 08

Re: Changing a game 2 player using swing timer to threads

Posted 01 June 2010 - 04:44 PM

Give that to your teacher:

Swing's Threading Policy

In general Swing is not thread safe. All Swing components and related classes, unless otherwise documented, must be accessed on the event dispatching thread.
Typical Swing applications do processing in response to an event generated from a user gesture. For example, clicking on a JButton notifies all ActionListeners added to the JButton. As all events generated from a user gesture are dispatched on the event dispatching thread, most developers are not impacted by the restriction.

Where the impact lies, however, is in constructing and showing a Swing application. Calls to an application's main method, or methods in Applet, are not invoked on the event dispatching thread. As such, care must be taken to transfer control to the event dispatching thread when constructing and showing an application or applet. The preferred way to transfer control and begin working with Swing is to use invokeLater. The invokeLater method schedules a Runnable to be processed on the event dispatching thread. The following two examples work equally well for transferring control and starting up a Swing application:

public class MyApp implements Runnable {
    public void run() {
        // Invoked on the event dispatching thread.
        // Construct and show GUI.
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new MyApp(args));
    }
}


Or:

public class MyApp {
    MyApp(String[] args) {
        // Invoked on the event dispatching thread. Do any initialization
        // here.
    }

    public void show() {
        // Show the UI.
    }

    public static void main(final String[] args) {
        // Schedule a job for the event-dispatching thread:
        // creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MyApp(args).show();
            }
        });
    }
}


This restriction also applies to models attached to Swing components. For example, if a TableModel is attached to a JTable, the TableModel should only be modified on the event dispatching thread. If you modify the model on a separate thread you run the risk of exceptions and possible display corruption.
As all events are delivered on the event dispatching thread, care must be taken in event processing. In particular, a long running task, such as network io or computational intensive processing, executed on the event dispatching thread blocks the event dispatching thread from dispatching any other events. While the event dispatching thread is blocked the application is completely unresponsive to user input. Refer to SwingWorker for the preferred way to do such processing when working with Swing


Article
Using Timers in Swing Applications

Print-friendly Version


By Hans Muller and Kathy Walrath




Programs -- especially those that present GUIs -- often need to perform a task either repeatedly or after a delay (or both). Timers make it easy for you to schedule the task. As of 1.3, the Java platform provides two Timer classes -- one in the javax.swing package and the other in java.util.

This article describes how to choose and use the appropriate Timer class for your Swing application. We discuss the problems that timers solve, give guidelines for choosing the right solution, and provide examples using timers.

What Timers Do
Generally speaking, a timer supports executing some task periodically or just once at some future time. Timers are important, albeit specialized, tools for the GUI programmer because they simplify the job of scheduling activity that results in a screen update. GUI applications typically use timers for animation, such as for blinking a cursor, or for timing responses, such as popping up a tool tip when the mouse is still for a few moments.

Nearly every computer platform has a timer facility of some kind. For example, UNIX programs can use the alarm function to schedule a SIGALRM signal; a signal handler can then perform the task. The Win32 API has functions such as SetTimer that let you schedule and manage timer callbacks. The Java platform's timer facility includes the same basic functionality as other platforms, and it's relatively easy to configure and extend.

Code Without Timers
In programs written without the benefit of timers, you'll see some rather nasty code for providing delays or periodic task execution. The nastiest algorithm of all is the busy wait loop. This little embarassment attempts to create a delay by keeping the CPU busy:
//DON'T DO THIS!
while (isCursorBlinking()) {
    drawCursor();
    for (int i = 0; i < 300000; i++) {
	Math.sqrt((double)i); // this should really chew up some time
    }
    eraseCursor();
    for (int i = 0; i < 300000; i++) {
	Math.sqrt((double)i); // likewise
    }
}



The reasons why busy wait loops are a bad idea are legion and obvious, so we won't enumerate them here.

A common, relatively practical approach to creating delays or timed loops is to create a new thread that sleeps before executing its task. Using the Thread sleep method to time the delay works well with Swing components as long as you follow the rules for thread usage outlined in the article Threads and Swing. The previous example could be sensibly rewritten like this:
final Runnable doUpdateCursor = new Runnable() {
    boolean shouldDraw = false;
    public void run() {
	if (shouldDraw = !shouldDraw) {
	    drawCursor();
	} else {
	    eraseCursor();
	}
    }
};

Runnable doBlinkCursor = new Runnable() {
    public void run() {
	while (isCursorBlinking()) {
	    try {
		EventQueue.invokeLater(doUpdateCursor);
		Thread.sleep(300);
	    }
	    catch (InterruptedException e) {
		return;
	    }
	}
    }
};

new Thread(doBlinkCursor).start();



As you can see, we've used the invokeLater method to ensure that the draw and erase methods execute on the event-dispatching thread. The main problem with this approach is that it doesn't scale well. Threads and thread scheduling aren't free or even as cheap as one might hope, so in a system where there may be many busy threads it's unwise to allocate a thread for every delay or timing loop.


The Swing Timer Class
The javax.swing.Timer class allows you to schedule an arbitrary number of periodic or delayed actions with just one thread. This Timer class is used by Swing components for things like blinking the text cursor and for timing tool-tip appearances and disappearances.

The Swing timer implementation fires an action event whenever the specified interval or delay time passes. You need to provide an Action object to the timer. Implement the Action's actionPerformed method to perform the desired task. For example, the blinking cursor example above could be written like this:
Action updateCursorAction = new AbstractAction() {
    boolean shouldDraw = false;
    public void actionPerformed(ActionEvent e) {
	if (shouldDraw = !shouldDraw) {
	    drawCursor();
	} else {
	    eraseCursor();
	}
    }
};

new Timer(300, updateCursorAction).start();



In this example we're using a timer to blink the cursor every 300 milliseconds.

The important difference between using the Swing Timer class and creating your own Thread is that the Swing Timer class uses just one thread for all timers. It deals with scheduling actions and putting its thread to sleep internally. The other important feature of this timer class is that the Action's actionPerformed method runs on the event dispatching thread. As a result, you don't have to bother with an explicit invokeLater call.

The Utility Timer and TimerTask Classes
Timers aren't the exclusive domain of GUI applications. In version 1.3 of the Java platform, support for timers was added to the java.util package. Like the Swing timer class, the main java.util timer class is called Timer. (We'll call it the "utility Timer class" to differentiate from the Swing Timer class.) Instead of scheduling Actions, the utility Timer class schedules instances of a class called TimerTask.

The utility timer facility has a different division of labor from the Swing version. For example, you control the utility timer facility by invoking methods on TimerTask rather than on Timer. Still, both timer facilities have the same basic support for delayed and periodic execution.

The utility timer facility provides more flexibility over scheduling timers. For example, the utility timer lets you can specify whether a timer task is to run at a fixed rate or repeatedly after a fixed delay. The latter scheme, which is the only one supported by Swing timers, means that a timer's frequency can drift because of extra delays introduced by the garbage collector or by long-running timer tasks. This drift is acceptable for animations or auto-repeating a keyboard key, but it's not appropriate for driving a clock or in situations where multiple timers must effectively be kept in lockstep.

The most important difference between javax.swing.Timer and java.util.Timer is that the latter doesn't run its tasks on the event-dispatching thread.

Here's one final version of the blinking cursor example. This one uses the new java.util.Timer class.
final Runnable doUpdateCursor = new Runnable() {
    private boolean shouldDraw = false;
    public void run() {
	if (shouldDraw = !shouldDraw) {
	    drawCursor();
	} 
	else {
	    eraseCursor();
	}
    }
};

TimerTask updateCursorTask = new TimerTask() {
    public void run() {
	EventQueue.invokeLater(doUpdateCursor);
    }
};

myGlobalTimer.schedule(updateCursorTask, 0, 300);
 


One other important difference to note here is that each java.util.Timer instance, such as myGlobalTimer in the previous example, corresponds to a single thread. It's up to applications to manage one or more Timer objects.

How to Choose a Timer Class
As we've seen, the Swing and utility timer facilities provide roughly the same functionality. Generally speaking, we recommend that you use the utility classes if you're writing a self contained application, particularly one that's not GUI related. The Swing Timer class is preferred if you're building a new Swing component or module that doesn't require large numbers of timers (where "large" means dozens or more).

The new utility timer classes give you control over how many timer threads are created; each java.util.Timer object creates one thread. If your application requires large numbers of timers you might want to create several java.util.Timer objects and have each one schedule related TimerTasks. In a typical application you'll share just one global Timer object, for which you'll need to create one statically scoped Timer field or property.

The Swing Timer class uses a single private thread to schedule timers. A typical GUI component or application uses at most a handful of timers to control various animation and popup effects. The single thread is more than sufficient for this.

The other important difference between the two facilities is that Swing timers run their task on the event dispatching thread, while utility timers do not. You can hide this difference with a TimerTask subclass that takes care of calling invokeLater. Here is an example:
abstract class SwingTimerTask extends java.util.TimerTask {
    public abstract void doRun();
    public void run() {
	if (!EventQueue.isDispatchThread()) {
	    EventQueue.invokeLater(this);
	} else {
	    doRun();
	}
    }
}



To implement the task, you would then create a SwingTimerTask subclass and override its doRun method (instead of run).
Was This Post Helpful? 4
  • +
  • -

#13 kngofdrkns  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 82
  • Joined: 21-May 08

Re: Changing a game 2 player using swing timer to threads

Posted 01 June 2010 - 04:56 PM

ok i will :gunsmilie:
Was This Post Helpful? 0
  • +
  • -

#14 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2831
  • View blog
  • Posts: 11,991
  • Joined: 20-September 08

Re: Changing a game 2 player using swing timer to threads

Posted 02 June 2010 - 03:43 AM

Quote

the teacher answer...


No, i'm talking about how your teacher thinks it should be implemented. Let's see his/her code
Was This Post Helpful? 0
  • +
  • -

#15 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2876
  • View blog
  • Posts: 11,051
  • Joined: 15-July 08

Re: Changing a game 2 player using swing timer to threads

Posted 02 June 2010 - 05:09 AM

Technically, you CAN have Threads in Swing, but you have to add those threads into Swing's event queue, where it is executed in sequence with everything else. However, there is no real point to this because Timer does this and it is already pre-built.

So, I'd stick with a Timer and print of pbl's excellent advise.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2