Cant get my balls to move


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Page 1 of 3 123 LastLast
Results 1 to 15 of 43

Thread: Cant get my balls to move

  1. #1
    Join Date
    Apr 2005
    Posts
    20

    Cant get my balls to move

    I am trying to write an applet based on one of the moscow puzzles, basically i have to make a chute long in which will be housed 4 white balls and 4 black, the object of the puzzle is to manouver the black balls passed the whites and out of the chute there is a recess in one side of the chute which functions as a passing place.

    I have adapted the code i had used in an earlier project and managed to get all the components on screen but nowwhen i click on a ball and try to move it, it won't move...however it looks like the applet is trying to move the chute and everything else in it.

    here is what i have

    Thanks in advance for any help you guys can give me


    Code:
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    
    public class RollThemOut extends Applet implements MouseListener, MouseMotionListener
    {
      private Point blkball1, blkball2, blkball3, blkball4,whtball1, whtball2, whtball3, whtball4, mouse;
      private int select;
    
    
    	public void init()
    	{
    	this.addMouseMotionListener(this);
    	this.addMouseListener(this);
    	select=0;
    	blkball1 = new Point(15,110);
    	blkball2 = new Point(60,110);
    	blkball3 = new Point(105,110);
    	blkball4 = new Point(150,110);
    	whtball1 = new Point(195,106);
    	whtball2 = new Point(250,106);
    	whtball3 = new Point(305,106);
    	whtball4 = new Point(360,106);
    	mouse = new Point();
    	}
    
    
    
    		public void paint(Graphics g)
    		{
    		drawBox(g);
    		g.setColor(Color.black);
    		g.fillOval(blkball1.x, blkball1.y, 45, 45);
    		g.fillOval(blkball2.x, blkball2.y, 45, 45);
    		g.fillOval(blkball3.x, blkball3.y, 45, 45);
    		g.fillOval(blkball4.x, blkball4.y, 45, 45);
    		g.drawOval(whtball1.x, whtball1.y, 55, 55);
    		g.drawOval(whtball2.x, whtball2.y, 55, 55);
    		g.drawOval(whtball3.x, whtball3.y, 55, 55);
    		g.drawOval(whtball4.x, whtball4.y, 55, 55);
    		}
    
    
    	public void mouseDragged(MouseEvent e)
    	{
    	if (select==1) blkball1 = mouse;
    	if (select==2) blkball2 = mouse;
    	if (select==3) blkball3 = mouse;
    	if (select==4) blkball4 = mouse;
    	if (select==5) whtball1 = mouse;
    	if (select==6) whtball2 = mouse;
    	if (select==7) whtball3 = mouse;
    	if (select==8) whtball4 = mouse;
    	repaint();
    	}	
    
    	public void mouseMoved(MouseEvent e){}
    	
    	public void mousePressed(MouseEvent e)
    	{
    	mouse = e.getPoint();
    	if (mouse.x > blkball1.x - 10 && mouse.x < blkball1.x + 10 && 
    		mouse.y > blkball1.y - 10 && mouse.y < blkball1.y + 10) select = 1; 
    
    	if (mouse.x > blkball2.x - 10 && mouse.x < blkball2.x + 10 && 
    		mouse.y > blkball2.y - 10 && mouse.y < blkball2.y + 10) select = 2;
    
    	if (mouse.x > blkball3.x - 10 && mouse.x < blkball3.x + 10 && 
    		mouse.y > blkball3.y - 10 && mouse.y < blkball3.y + 10) select = 3;
    
    	if (mouse.x > blkball4.x - 10 && mouse.x < blkball4.x + 10 && 
    		mouse.y > blkball4.y - 10 && mouse.y < blkball4.y + 10) select = 4;
    	
    	if (mouse.x > whtball1.x - 10 && mouse.x < whtball1.x + 10 && 
    		mouse.y > whtball1.y - 10 && mouse.y < whtball1.y + 10) select = 5;
    	
    	if (mouse.x > whtball2.x - 10 && mouse.x < whtball2.x + 10 && 
    		mouse.y > whtball2.y - 10 && mouse.y < whtball2.y + 10) select = 6;
    
    	if (mouse.x > whtball3.x - 10 && mouse.x < whtball3.x + 10 && 
    		mouse.y > whtball3.y - 10 && mouse.y < whtball3.y + 10) select = 7;
    
    	if (mouse.x > whtball4.x - 10 && mouse.x < whtball4.x + 10 && 
    		mouse.y > whtball4.y - 10 && mouse.y < whtball4.y + 10) select = 8;
    
    
    
    	}
    
    
    		public void mouseClicked(MouseEvent e){}
    		public void mouseReleased(MouseEvent e){}
    		public void mouseEntered(MouseEvent e){}
    		public void mouseExited(MouseEvent e){}
    
    public void drawBox(Graphics g)
    {
    
     g.setColor(Color.black);
     g.fillRect(10,100,685 ,68);
     g.fillOval(410, 55, 65, 65);
     g.fillRect(410, 85, 65, 25);
     g.fillRect(690, 107, 20, 55);
     
     g.setColor(Color.white);
     g.fillRect(15,105,675,58);
     g.fillOval(415, 60, 55, 55);
     g.fillRect(415, 90, 55, 20);
     g.fillRect(690, 112, 30, 45);
    
    }
    }
    Last edited by pwnedjoo; 04-14-2005 at 04:33 PM.

  2. #2
    Join Date
    Mar 2005
    Location
    Sendling, MUC, .de
    Posts
    100
    Wow, what a headline!

  3. #3
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    What kind of data structure do you think will be used to hold the white balls being pushed on top of it to get out of the way of the black balls which will just roll right through ... to another data structure which holds the items ariving at its end ...

    Do you have a pseudocode algorithm for how you are approaching this problem? If ball is white, move into " " data structure. If ball is black, move to the end of the data structure at the end of the tunnel. Once all the balls are gone from the start, take all the balls which have accumulated in the "siding" and push them one at a time into the end of the tunnel. Print out the results.

    You wil find many resources on the Internet which refer to a rail switch yard or rail siding ... which use the same basic approach as your project.

  4. #4
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    They are moving now, but where, and why ?

    I have set up the applet as a panel here, I think you should consider
    using a memory image to avoid flickering. You will have to add some more
    code here, - vertical move of a ball should only be allowed where there is
    room for it, - I think.
    Code:
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    
    /**
     * A ball w. a diameter, a color and a location
     */
    class Ball  {
      private Rectangle rect=null;
      private Color color=null;
      public Ball (int x, int y, int diameter, Color color) {
        rect=new Rectangle(x,y,diameter, diameter);
        this.color=color;
      }
      public void draw(Graphics g) {
          Color c = g.getColor();
          g.setColor(color);
          g.fillOval(rect.x, rect.y, rect.width, rect.height);
          g.setColor(c);
      }
      public boolean isHit(Point p) {
        return rect.contains(p);
      }
      public Rectangle getRectangle() {
        return rect;
      }
      public void moveBall(Point p) {
    
          rect.x += p.x;
          /**
           * include next statement to allow vertical dragging, possibly
           * only allowed under the arc...some positional test perhaps ?
           */
          //rect.y += p.y;
      }
    }
    /**
     * Your applet as a panel
     */
    class RollThemOut extends Panel
        implements MouseListener, MouseMotionListener, Comparator {
    
      public static ArrayList bList=new ArrayList();
      public  static Ball [] balls = {
          new Ball(15, 110, 45, Color.black),
          new Ball(60, 110, 45, Color.black),
          new Ball(105, 110, 45, Color.black),
          new Ball(150, 110, 45, Color.black),
          new Ball(195, 106, 55, Color.white),
          new Ball(250, 106, 55, Color.white),
          new Ball(305, 106, 55, Color.white),
          new Ball(360, 106, 55, Color.white)
      };
      private Point lastPos; // last dragging position
      private Point moveOffset=new Point(); // dragging distance
      private int selectedIndex=-1; // index of currently selected ball
    
      public void init() {
        this.addMouseMotionListener(this);
        this.addMouseListener(this);
        selectedIndex = -1;
    
      }
    
      public void paint(Graphics g) {
        update (g);
      }
      public void update(Graphics g) {
        Color c = g.getColor();
        g.setColor(Color.blue);
        g.fillRect(0, 0, this.getSize().width, this.getSize().height);
        drawBox(g);
        drawBalls(g);
        g.setColor(c);
      }
    
      private void drawBalls(Graphics g) {
        for (int i = 0; i < balls.length; i++) {
          balls[i].draw(g);
        }
      }
      public void drawBox(Graphics g) {
        g.setColor(Color.black);
        g.fillRect(10, 100, 685, 68);
        g.fillOval(410, 55, 65, 65);
        g.fillRect(410, 85, 65, 25);
        g.fillRect(690, 107, 20, 55);
    
        g.setColor(Color.darkGray);
        g.fillRect(15, 105, 675, 58);
        g.fillOval(415, 60, 55, 55);
        g.fillRect(415, 90, 55, 20);
        g.fillRect(690, 112, 30, 45);
      }
    
      public void mouseDragged(MouseEvent e) {
        if (selectedIndex == -1) {
          return;
        }
        moveOffset.x = e.getPoint().x - lastPos.x;
        moveOffset.y = e.getPoint().y - lastPos.y;
    
        balls[selectedIndex].moveBall(moveOffset);
        repaint();
    
        lastPos=e.getPoint();
      }
      /**
       * I dont know all the rules here but I've added a sort of the
       * balls array to simplify checking of move-space
       * @param e
       */
      public void mouseReleased(MouseEvent e) {
        if (selectedIndex >= 0) { // dragging may have occurred
          sortBalls();
        }
        selectedIndex = -1;
      }
      /**
       * Sort the ball array on x-position
       */
      private void sortBalls() {
        bList.clear();
        for (int i = 0; i < balls.length; i++) {
          bList.add(balls[i]);
        }
        Collections.sort(bList, this);
        for (int i = 0; i < bList.size(); i++) {
          balls[i] = (Ball) bList.get(i);
        }
      }
      public int compare(Object o1, Object o2) {
        Ball b1 = (Ball) o1;
        Ball b2 = (Ball) o2;
        return b1.getRectangle().x - b2.getRectangle().x;
      }
    
      public boolean equals(Object obj) {
        return false;
      }
    
      /**
       * Check for a hit
       * @param e
       */
      public void mousePressed(MouseEvent e) {
    
        lastPos = e.getPoint();
        selectedIndex = -1;
        for (int i=0; i<balls.length; i++) {
          if (balls[i].isHit(lastPos)) {
            selectedIndex = i;
            break;
          }
        }
        System.out.println("Select:"+selectedIndex+"\r\n");
      }
    
      public void mouseClicked(MouseEvent e) {}
      public void mouseMoved(MouseEvent e) {}
      public void mouseEntered(MouseEvent e) {}
      public void mouseExited(MouseEvent e) {}
    
    }
    public class RollDriver {
      /**
       * ************* MAIN ***************************
       * Sets up a jframe and a textarea for running the applet code
       * @param args
       */
      public static void main (String [] args) {
        Frame f=new Frame();
        f.setLayout(new GridLayout());
        RollThemOut p=new RollThemOut();
        p.init();
        f.add(p);
        f.setSize(780, 600);
        f.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
          }
        });
        f.validate();
        f.setVisible(true);
    
    
      }
    }
    Last edited by sjalle; 04-15-2005 at 08:08 AM.

  5. #5
    Join Date
    Jan 2005
    Location
    Reisterstowwn, MD
    Posts
    72
    Quote Originally Posted by meisl
    Wow, what a headline!
    I realize this forum should be taken with all seriousness, but LOL, I agree! Caught my eye!
    Java has 99 problems but a pointer ain't one

  6. #6
    Join Date
    Apr 2005
    Posts
    3
    I'm no pro but you should put the stuff in mouse released

  7. #7
    Join Date
    Apr 2005
    Posts
    20
    sjalle,

    thankts very much for your help with this, I have a couple of questions for you though,

    firstly to confirm what u mean by memory image, is that like double buffering.

    and secondly should the solution u have posted be split into different class files or left as one,

    and thirdly were you able to run the applet as is or do I have to work on the other areas you suggested before it will run.....the reason I ask is I have split it into 3 seperate .java files and compiled which all went fine. but when i run it in a browser i get a "not inited" error

    I am sorry in advance......I am a complete java noob
    Last edited by pwnedjoo; 04-17-2005 at 05:56 PM.

  8. #8
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    Quote Originally Posted by pasky08
    I'm no pro but you should put the stuff in mouse released
    Yes, in som cases, but when you're dealing with mousedragging the
    mouse released is at the wrong end of things.....

  9. #9
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    firstly to confirm what u mean by memory image, is that like double buffering.
    Yes

    and secondly should the solution u have posted be split into different class files or left as one
    In my opinion that is a question of personal preference. I would just have
    left it as one file (since the size of the code is small). It will split up into
    separate class files anyway, when you compile it.

    and thirdly were you able to run the applet as is or do I have to work on the other areas you suggested before it will run.....the reason I ask is I have split it into 3 seperate .java files and compiled which all went fine. but when i run it in a browser i get a "not inited" error
    .
    I didn't run it as an applet, I cheated and processed it like the Applets
    ancestor, the Panel..

    The other areas must be the restrictions on vertical moves and blocking of
    move attempts on a ball that is trapped, - well thats just for making it a
    functional game.
    not inited
    If you run it in a browser that has a java console (like IE) you will see the
    reson for this message ending up in the status bar (probably missing or
    misplaced class files).

    If you get stuck, just zip the lot and post it here.

    Good luck !
    Last edited by sjalle; 04-18-2005 at 04:59 AM.

  10. #10
    Join Date
    Apr 2005
    Posts
    20
    I hate to keep writing back and exposing my obvious lack of knowledge to you guys, with what must seem like trivial questions, but

    can i just confirm that the RollDriver.class is the main class which i should be calling from my html doc.....and also if this is the case how come after complilation I end up with 2 versions of the RollDriver.class i get

    RollDriver.class and RollDriver$1.class

    Have posted a zip of the files here :

    http://www.lasersheepdipfunk.pwp.blu...k/RollThem.zip

  11. #11
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    Noooo !

    RollThemOut must be changed back to an applet, just replace "extends Panel"
    with "extends Applet". A main() method has no business in an applet. That
    part is handled by the browser that, after loading the applet code, calls
    the init() and start() methods of the applet. In your case you don't need
    the start() method, that one is reserved for applets that uses threads.

    It works like, the init() (and start()) method is invoked after the first time the applet is
    loaded, if the user leaves the page the applet's stop() method (if present) is
    called, and if the user returns to the applet page the start() method
    (if present) is called.

    So you can just scrap the RollDriver class. The blabla$<num> files are not
    versions of the class, they are all part of the class code so upload them
    all.

    So in short, RollThemOut is your applet.

  12. #12
    Join Date
    Apr 2005
    Posts
    20
    thankyou very much, that clears things up considerably,

    thanks again for your time


    p.s. had I not wanted to use this as an applet would I have been able to run the code you gave me from the command line C:\>java <filename>
    Last edited by pwnedjoo; 04-18-2005 at 02:33 PM.

  13. #13
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    Yup, an applet that utilizes no web specific stuff like yours can be treated like a
    Panel, without any modification, and stuffed into a Frame like in the code I posted earlier.
    Just remember to call the applets init() (and start()) method after you've
    set the frame visible.
    Last edited by sjalle; 04-18-2005 at 06:44 PM.

  14. #14
    Join Date
    Apr 2005
    Posts
    20
    heya again, i decided that to try and understand what you had done with my puzzle, it would be worthwhile playing with the code and try to adapt it adapt it to another puzzle, that way I would understand each methods purpose and how the whole program works, as a variation i tried to implement images into the program instead of drawing my objects but i seem to have come unstuck slightly in the Frog Class (its a puzzle which involves moving frogs around toadstools) I think I am just about there just an issue with actually drawing the frog now

    Code:
    class Frog  {
      private Rectangle rect=null;
      private Color color=null;
      
      public Frog(int x, int y, int diameter){
       rect=new Rectangle(x,y,diameter, diameter);
      }
       
      public void draw(Graphics g) {
          
          Image FrogIm;
          FrogIm = getImage(getCodeBase(), "Frog1.gif");
          g.drawImage(FrogIm, rect.x, rect.y, rect.width, rect.height, this);
      }
    
      public boolean isHit(Point p) {
        return rect.contains(p);
      }
      public Rectangle getRectangle() {
        return rect;
      }
      public void moveFrog(Point p) {
          rect.x += p.x;
          rect.y += p.y;
      }
    }
    The probelm seems to be with getCodeBase() and drawImage()

  15. #15
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    Hmmm

    I assume you are running it as an applet now ?

    Well, applet or application; you should never do an image load inside
    the draw method. That method is invoked every time the display needs an
    update (e.g. every time you move anything a little notch), at least in the
    setup I posted here, and you don't want to (up)load like 20 images each
    second... It would never work.

    What you could do is make the frog image part of the Frog constructor's
    parameters, i.e. load the image prior to the frog objects distribution.
    That way you can distrubute the frog image to many Frogs
    (that is what you want...right..?).

    Also, when dealing with image load (both in applications and applets) you
    should use the MediaTracker class to ensure that the image(s) are properly
    loaded before you attempt to display them.

    And one more thing; the drawImage method you use requires an
    ImageObserver as the last parameter. Your Frog is not an
    ImageObserver but if it is painted on a Panel you could also pass the pointer
    of this Panel to each Frog object so they can use it for the drawing operation.

    Yout Frog class would then look something like this:

    Code:
    import java.awt.*;
    
    class Frog  {
      Image frogIm=null; // quack
      Panel theFrogsPlace=null; // the panel where the frogs live
      Rectangle rect=null; // the rectangle that defines this frog's borders
    
      /**
       *  The frog image has been loaded prior to invoking this constructor
       */
      public Frog(int x, int y, Image frogIm, Panel theFrogsPlace){
        this.frogIm=frogIm;
        this.theFrogsPlace=theFrogsPlace;
        rect=new Rectangle(x,y,
                           frogIm.getWidth(theFrogsPlace),
                           frogIm.getHeight(theFrogsPlace));
      }
    
      public void draw(Graphics g) {
        // this version of drawImage will draw the image with a topLeft
        // at rect.x, rect.y using the actual width and height of the image
        g.drawImage(frogIm, rect.x, rect.y, theFrogsPlace);
      }
    
      public boolean isHit(Point p) {
        return rect.contains(p);
      }
      public Rectangle getRectangle() {
        return rect;
      }
      public void moveFrog(Point p) {
          rect.x += p.x;
          rect.y += p.y;
      }
    }
    Last edited by sjalle; 04-19-2005 at 03:27 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center