Help with pong like game

Hi all profesionals.
I am trying to create a pong like game, called PinPong (As it is a mix of pinball and pong)
However, i am not happy with how the ball behaves in the game.
Does anyone have some insigt on how to go about improving this behaviour?
Thanx!
You can download the fla here ... www.netfun.no/files/PinPong.fla (301 056 bytes)

First of all, thx for trying to help!
well.. its a different kind of snake game: the starting point of the snake always stays the same. this means, that the snake grows longer and longer, without the butt moving behind the snake, but staying in the same position.
so, if i'd try to put all those lines into an array (every line of the snake is very small, it is been added every 30 millisecs another line) this array would explode, and this would not be a very fast or elegant solution. so i think it must be possible to read the Color of a single pixel, the pixel, where the snake moves next... so that if the color would be other than the background color, it should stop, because the snake must have been crashed into something.
so.. i posted this into an earlier thread and somebody said the class BufferedImage and its method getRGB() should help. im currently trying to do so, but it doesnt work.
i cant seem to get the data from the JPanel (where i am drawing the snakes (i think thats the problem)) into the bufferedimage.. anyone could help, please?
here is some code from the game:
CODE
BufferedImage bi = new BufferedImage(505,505,BufferedImage.TYPE_INT_RGB);
CurrentBackgroundRGB = bi.getRGB((int)(Worm1.xStart+Worm1.x),(int)(Worm1.yStart+Worm1.y));
if(HintergrundRGB != BackgroundCol.getRGB())this.interrupt();
end CODE
"this" is the current thread of the animation
I think the problem is obvious: how can i get the Buffered image to check the data from my JPanel?

Similar Messages

  • Plz help with snake-like game..

    hi.
    i am new to java and want to programm a kind of worm-game where there are multiple worms, each different color and when your worm (you can choose your direction by pressing left and right button) crashes in something, that isnt the clear background (worms or the border rectangle) then it should stop. so my problem is:
    how can I get the program to know, that the worm has crashed into something?
    i think the easiest solution would be, if I could determine the Color of a specific Pixel on the canvas (i am using a canvas for the playfield).
    or another solution could be that if i could determine, wheter the Pixel is an element of the worm or the rectangle (dont think this is possible).
    somebody wrote in an earlier question that i should use the buffered image class. im currently trying to do so.
    another big problem is, that it has to be very fast. its a problem that i have to, in order to show the animation, repaint the canvas every 30 milisecs or so (im using a thread). is there a possibility to only redraw the worms? (im using g2d lines as "worms", that are beeing added every animation another line)
    THX VERY MUCH FOR HELPING!!

    First of all, thx for trying to help!
    well.. its a different kind of snake game: the starting point of the snake always stays the same. this means, that the snake grows longer and longer, without the butt moving behind the snake, but staying in the same position.
    so, if i'd try to put all those lines into an array (every line of the snake is very small, it is been added every 30 millisecs another line) this array would explode, and this would not be a very fast or elegant solution. so i think it must be possible to read the Color of a single pixel, the pixel, where the snake moves next... so that if the color would be other than the background color, it should stop, because the snake must have been crashed into something.
    so.. i posted this into an earlier thread and somebody said the class BufferedImage and its method getRGB() should help. im currently trying to do so, but it doesnt work.
    i cant seem to get the data from the JPanel (where i am drawing the snakes (i think thats the problem)) into the bufferedimage.. anyone could help, please?
    here is some code from the game:
    CODE
    BufferedImage bi = new BufferedImage(505,505,BufferedImage.TYPE_INT_RGB);
    CurrentBackgroundRGB = bi.getRGB((int)(Worm1.xStart+Worm1.x),(int)(Worm1.yStart+Worm1.y));
    if(HintergrundRGB != BackgroundCol.getRGB())this.interrupt();
    end CODE
    "this" is the current thread of the animation
    I think the problem is obvious: how can i get the Buffered image to check the data from my JPanel?

  • Help with pong collision

    I am working on a pong-like game for a project... and i am having some trouble with collision checks... again.
    Here is our code so far, the problem is that the ball seems to be stopping completely when it is aligned with a paddle on the Y axis (even if it is at the center of the screen)
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class TestApplet extends Applet implements Runnable
        //Paddle dimensions
        int PaddleHeight = 50;
        int PaddleWidth = 10;
        //Other variables
        boolean isStop = true;
        int[] theKeys = new int[256]; //Array with one element representing each key
        Random Rand = new Random();
        int bounces = 0;
        boolean isAI2 = false;
        boolean isAI1 = false;
        ArrayList <Ball> TheBalls = new ArrayList <Ball>();
        Paddle[] ThePaddles = new Paddle[2];
        //Player scores
        int Score1 = 0;
        int Score2 = 0;
        private Image dblimage;
        private Graphics dbg;
        public void init()
            //Set Background color to black
            setBackground(Color.black);
        public void start()
            //Define new thread
            Thread th = new Thread(this);
            //Start the new thread
            th.start();
            for(int z=0; z<256; z++)
                theKeys[z] = 0; //Set all keys to default position (released)
            enableEvents(AWTEvent.KEY_EVENT_MASK);
            ThePaddles[0]=(new Paddle(true, PaddleHeight, PaddleWidth, 10, this.getWidth(), this.getHeight(), 'w', 's'));
            ThePaddles[1]=(new Paddle(false, PaddleHeight, PaddleWidth, 10, this.getWidth(), this.getHeight(), '8', '5'));
            TheBalls.add(new Ball(this.getHeight(), this.getWidth()));
            TheBalls.get(0).AddPaddle(ThePaddles[0]);
            TheBalls.get(0).AddPaddle(ThePaddles[1]);
        public void run ()
            //Minimize thread priority
            Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
            while (true)
                for(int i=0; i<ThePaddles.length; i++)
                    if(isKeyPress(87))
                        ThePaddles.Move(1);
    else if(isKeyPress(83))
    ThePaddles[i].Move(-1);
    if(isKeyPress(32))
    for(int x=0; x < TheBalls.size(); x++)
    TheBalls.get(x).Start();
    isStop = false;
    bounces = 0;
    for(int i=0; i<TheBalls.size(); i++)
    TheBalls.get(i).Move();
    String scored = TheBalls.get(i).IsScore();
    if(scored == "Player 1")
    Score1++;
    break;
    else if(scored == "Player 2")
    Score2++;
    break;
    repaint();
    try
    Thread.sleep (20);
    catch (InterruptedException ex)
    // do nothing
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    public void paint(Graphics g)
    //set color
    g.setColor(Color.green);
    for(Ball temp : TheBalls)
    int[] tempfo = temp.BallInfo();
    g.fillOval(tempfo[0], tempfo[1], tempfo[2], tempfo[3]);
    for(Paddle temp: ThePaddles)
    int[] PadTemp = temp.PaddleData();
    g.fillRect(PadTemp[0], PadTemp[1], PadTemp[2], PadTemp[3]);
    //paint player 1 score
    g.drawString("Player 1 score: "+Score1, 10, 50);
    //paint player 2 score
    g.drawString("Player 2 score: "+Score2, 400, 50);
    //paint current bounce count
    g.drawString("Bounces: "+bounces, 250, 50);
    g.drawString(""+ThePaddles[0].GetUp(), 100, 100);
    g.drawString(""+ThePaddles[0].GetDown(), 100, 400);
    g.drawString(""+ThePaddles[1].GetUp(), 200, 100);
    g.drawString(""+ThePaddles[1].GetDown(), 200, 400);
    g.drawString(""+TheBalls.get(0).Collide(), 250, 250);
    g.drawLine(ThePaddles[0].getX(), ThePaddles[0].GetTop(), ThePaddles[0].getX()-500, ThePaddles[0].GetTop());
    public void update (Graphics g)
    // initialize buffer
    if (dblimage == null)
    dblimage = createImage (this.getSize().width, this.getSize().height);
    dbg = dblimage.getGraphics ();
    // clear screen in background
    dbg.setColor (getBackground ());
    dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
    // draw elements in background
    dbg.setColor (getForeground());
    paint (dbg);
    // draw image on the screen
    g.drawImage (dblimage, 0, 0, this);
    public void processKeyEvent(KeyEvent ev)
    int keycode = (ev.getKeyCode()&0xff);
    if (ev.getID() == KeyEvent.KEY_PRESSED)
    theKeys[keycode] = 1; //1 Represents key is pressed
    else if (ev.getID() == KeyEvent.KEY_RELEASED)
    theKeys[keycode] = 0; //0 Represents key is not pressed
    repaint();
    //Checks if a given key is pressed
    public boolean isKeyPress(int theKey)
    return (theKeys[theKey] != 0);
    //Checks if a given key is released
    public boolean isKeyRel(int theKey)
    return(theKeys[theKey] == 0);
    class Paddle
    private int
    XPos,
    YPos,
    Width,
    Height,
    Speed,
    AppletHeight,
    AppletWidth,
    Down,
    Up;
    boolean
    LeftSide;
    public Paddle(boolean LeftSide, int Height, int Width, int Speed, int AppletWidth, int AppletHeight, char Up, char Down)
    this.AppletHeight = AppletHeight;
    this.AppletWidth = AppletWidth;
    YPos = AppletHeight/2;
    this.Height = Height;
    this.Width = Width;
    this.Speed = Speed;
    this.LeftSide = LeftSide;
    if(LeftSide)
    this.XPos = 15;
    else
    this.XPos = AppletWidth-25;
    Character UpChar = new Character(Up);
    Character DownChar = new Character(Down);
    this.Up = UpChar.charValue();
    this.Down = DownChar.charValue();
    public void Move(int x)
    if(x > 0)
    YPos -= Speed;
    else
    YPos += Speed;
    public int GetTop()
    return YPos - Height/2;
    public int GetBottom()
    return YPos + Height/2;
    public int GetUp()
    return Up;
    public int GetDown()
    return Down;
    public int getX()
    return XPos;
    public int getY()
    return YPos;
    public int GetHeight()
    return Height;
    public int GetWidth()
    return Width;
    public int[] PaddleData()
    if(LeftSide)
    return new int[]{XPos+Width/2, YPos-Height/2, Width, Height};
    return new int[]{XPos-Width/2, YPos-Height/2, Width, Height};
    class Ball
    private int
    XPos,
    XSpeed,
    YPos,
    YSpeed,
    Radius,
    MaxSpeed,
    Height,
    Width;
    private boolean
    IsStill;
    private ArrayList <Paddle>
    ThePaddles=new ArrayList <Paddle>();
    private Random Rand=new Random();
    public Ball(int Width, int Height)
    this.ThePaddles=ThePaddles;
    this.Height=Height;
    this.Width=Width;
    XPos=Width/2;
    YPos=Height/2;
    IsStill=true;
    MaxSpeed=9;
    Radius=10;
    ChangeAngle();
    public void AddPaddle(Paddle temp)
    ThePaddles.add(temp);
    public int[] BallInfo()
    return new int[]{XPos-Radius, YPos-Radius, 2*Radius, 2*Radius};
    public void Start()
    IsStill = false;
    public int getX()
    return XPos;
    public int getY()
    return YPos;
    public int getRad()
    return Radius;
    public void RevX()
    XSpeed *= -1;
    public int getXSp()
    return XSpeed;
    public int getYSp()
    return YSpeed;
    public boolean isNeg()
    if(XSpeed < 0)
    return true;
    return false;
    //Generates a random trajectory for the ball
    public void ChangeAngle()
    int Num, Opp;
    Num= Rand.nextInt(MaxSpeed)+1;
    Opp = MaxSpeed-Num;
    XSpeed = ((XSpeed>0)?1:-1)*Num;
    YSpeed = ((Rand.nextInt(2)==0)?1:-1)*Opp;
    public boolean Collide()
    boolean collid=false;
    for(Paddle i: ThePaddles)
    if(YPos >= i.GetTop() && YPos <= i.GetBottom())
    if(i.LeftSide)
    collid = (((XPos - Radius) <= (i.getX() + i.GetWidth())));
    if(!collid)
    collid = (((XPos + Radius) >= (i.getX() - i.GetWidth())));
    if(!collid)
    collid = ((YPos<=0 && YSpeed < 0) || (YPos>=Height && YSpeed > 0));
    return collid;
    public String IsScore()
    if(XPos >= Width)
    XPos = Width/2;
    YPos = Height/2;
    IsStill = true;
    return "Player 1";
    if(XPos <= 0)
    XPos = Width/2;
    YPos = Height/2;
    IsStill = true;
    return "Player 2";
    return "";
    public void Move()
    boolean temp = false;
    for(int i=0; i<=Math.abs(XSpeed); i++)
    if((Collide()) && !temp)
    RevX();
    ChangeAngle();
    temp = true;
    break;
    XPos = ((XSpeed>0)?XPos+1:XPos-1);
    temp = false;
    for(int i=0; i<=Math.abs(YSpeed); i++)
    if((Collide()) && !temp)
    YSpeed *= -1;
    temp = true;
    break;
    YPos = ((YSpeed>0)?YPos+1:YPos-1);

        public boolean Collide()
            boolean collid=false;
            for(Paddle i: ThePaddles)
                if(YPos >= i.GetTop() && YPos <= i.GetBottom())
                    if(i.LeftSide)
                        collid = (((XPos - Radius) <= (i.getX() + i.GetWidth())));
    //                if(!collid)
                    else
                        collid = (((XPos + Radius) >= (i.getX()/* - i.GetWidth()*/)));

  • Need help with ending a game

    i'm making a game at the moment.......
    i need help with a way to check all the hashmaps of enimies in a class called room......i need to check if they all == 0...when they all equal zero the game ends......
    i know i can check the size of a hash map with size().....but i want to check if all the hashmaps within all the rooms == 0.

    First of all stop cross posting. These values in the HashMap, they are a "Collection" of values, so what is wrong with reply two and putting all these collections of values into a super collection? A collection of collections? You can have a HashMap of HashMaps. One HashMap that holds all your maps and then you can use a for loop to check if they are empty. A map is probably a bad choice for this operation as you don't need a key and an array will be much faster.
    HashMap [] allMaps = {new HashMap(),new HashMap()};

  • Help with first flash game?

    Hi. My name's Rory.
    I am an artist.
    http://www.youtube.com/profile?user=PimpOfPixels
    http://roaring23.cgsociety.org/gallery/
    I am learning action script and Flash so that I can make
    games.
    I am not a complete novice in programming. I am proficient in
    Java and in MaxScript (3DSMAX embedded language).
    I have been making some progress in action script and I have
    a functional (although incomplete) game in the works. You can view
    it here:
    http://secure2.streamhoster.com/~rlu...orniverous.swf
    The idea is it's a color game
    red beats green, green beats, blue beats red. Think paper
    scissor rock.
    The idea is to change the entire circle into one color.
    The graphics are place holders BTW.
    I am using FlexBuilder 2.0 and Flash CS3, and I have come
    across a problem not covered in either of my books.
    I'd really appreciate any help that you guys can offer.
    I have gotten this far on my own.
    My #1 question (and I have many more) is:
    How do you through Flash specify animation segments for a
    MovieClip Symbol?
    Notice how the red creatures occasionally open their mouths.
    I want to have a walk, an attack, an absorb, and a bounce animation
    on the same timeline and trigger the appropriate one depending on
    which color the creature collides with. I do not know how to go
    about this problem. I’ve just been trying to get the walk
    animation to loop without playing the attack animation so far.
    I've tried frame-labeling in flash, with scripts on the key
    frames of a second layer that specify when to stop or repeat the
    animation... No dice.
    I have a symbol named RedShot in the library of a flash
    project named "graphics"
    In my timeline I have 2 animation segments, and I have a
    second layer denoting two corresponding frames named "walk" and
    "attack" from the properties menu.
    On the final frames of the animations I have scripts.
    Code:
    gotoAndPlay("walk");
    and
    Code:
    gotoAndPlay("attack");
    respectively.
    Im my library I have linkage options specified as such:
    Class:RedShot
    BaseClass:flash.display.MovieClip
    export of actionscript#CHECKED
    export on 1st frame#CHECKED
    on the main stage of my flash project I have actionscript for
    2 functions:
    Code:
    function walk(){
    red_shot.gotoAndPlay("walk");
    function attack(){
    red_shot.gotoAndPlay("attack");
    I export the project and the opened window has the "walk"
    animation looping properly.
    In my FlexBuilder project I embed the symbol
    Code:
    //Inside class global variables:
    [Embed(source="../graphics.swf", symbol="RedShot")]
    public var RedShot:Class;
    private var _shot:MovieClip;
    Code:
    //and in my buildShot function:
    _shot = new RedShot();
    addChild(_shot);
    When I build the project the characters appear, and they
    animate. The only trouble is that there are no breaks in the
    animation. The animation loops right through the frames where I
    have specified that the animation should "gotoAndPlay" from a
    different part.
    What's weirder is that I can call
    Code:
    "gotoAndPlay("attack");"
    without an error and it will go to and play from that point.
    The only trouble is that it will begin to loop the entire animation
    again without stopping at the gotoAndPlay events stored in the
    frames of the timeline.
    It seems like all embedded actions are ignored, add I can't
    think of another way to controll the animation.
    Any thoughts?

    After hours of searching the internet I finally got this
    blasted question figured out.
    How to you export a symbol from Flash for use in a Flex
    Builder project without destroying actionscript stored within the
    frames of the Symbol's timeline?
    That's a long winded way of saying: "In FlexBuilder, how do
    you control MovieClips from Flash". I'm trying to make games, and
    this was a particularly important question for me :).
    Here's how:
    1) You need a hotfix from Adobe.
    [HTML]http://kb.adobe.com/selfservice/viewContent.do?externalId=kb401493&sliceId=2[/HTML]
    This allows Flash CS3 to export a SWC file.
    2)You have to set the linkage properties for your various
    symbols in the flash library panel.
    a)right click on symbol in library panel
    b)choose "linkage"
    c)"Class:" = (pick a name)
    d)"Base class:" = flash.display.MovieClip;
    e)"Export for ActionScript" = CHECKED
    f)"Export in first frame"=CEHCKED
    3)If you want to have multiple segmented animations as I
    certainly did you'll want to create frames and actionscripts within
    the symbols timeline to define where these animations are.
    a) in the symbol's timeline make a second layer. We'll name
    that layer "labels" for the sake of not having this get too
    confusing.
    b) on that layer create a new frame for each of the animation
    segments that you'd like to define and stretch them to the length
    of the corresponding animations.(I'm assuming that you have a
    keyframe animation on the 1st layer... otherwise what's the point
    of all this :P?)
    c)in the properties panel name the frames in the "labels"
    layer accordingly ie. "walk" "run" shoot" etc.
    d)Define whether the various animations play once or loop by
    adding a script to the last frame of the animation. If you want the
    animation to loop add
    [CODE]gotoAndPlay("name-of-the-animation");[/CODE]
    if you want the animation to play once and stop add
    [CODE]stop();[/CODE]
    if you want the animation to play once and then return to a
    different animation add
    [CODE]gotoAndPlay("name-of-a-different-animation");[/CODE]
    4) now you can export the symbols to an SWC file. Note: you
    do not get this option unless you have installed the hotfix.
    [HTML]http://kb.adobe.com/selfservice/viewContent.do?externalId=kb401493&sliceId=2[/HTML] .
    a)rightclick on a symbol in the library panel
    b)choose "exportSWCfile..."
    c)export the file to a logical place such as the root of your
    FlexBuilder project.
    5) Now you have to tell flexbuilder about the new SWC file.
    Note: Once this file is added to the FlexBuilder library you can
    instantiate classes from it as though they were included using the
    "include" function.
    a)Right clicking on the root of the project in the Navigator
    view.
    b)going to properties.
    c)Going to library path. (2nd tab)
    d)and pressing the "Add SWC" button
    Now you're done and you can instantiate any of the symbols
    from your library while preserving any actions from your symbols
    timeline just as though you had imported it as a class from a
    typical library.
    Sweet huh?
    Thanks to the countless people and internet resources I found
    on the subject. Hopefully it will be easier for anyone who finds
    this post.
    Here's an adobe video which covers the basic process.
    https://admin.adobe.acrobat.com/_a300965365/p75214263/

  • Help with Kevin Bacon game

    I would really appreciate some help. Yes this is an assignment who in his crazy mind would try to do this just to learn or practice their java. I have some code already done but I ran out of memory. The other thing my code works like the one at Virginia University. I'm awarding 10 dukes I can award another 10 dukes. I'll let you know later, thanks in advance.
    This is the code I have:
    import java.io.*;
    import java.util.zip.*;
    import java.util.ArrayList;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Set;
    import java.util.Iterator;
    * A class that download files , create Maps and search for information with
    * in the maps, giving an output of the actor that share more movies with the
    * input actor that the user gives
    public class DataBase
      private Map map1 = new HashMap( );  // actor
      private Map map2= new HashMap( );   //movies
      private int okactor = 0;
    // Main Method
      public static void main (String args [])throws IOException
        DataBase testing = new DataBase();
        System.out.println("Program was run in Pentium 4 in AUL");
        System.out.println("Starting Time : " + System.currentTimeMillis());
        testing.loadFile("C:\\My Documents\\FIU\\COP3530_Data_Strutures\\program5\\actresses.list.gz");   
        testing.loadFile("C:\\My Documents\\FIU\\COP3530_Data_Strutures\\program5\\actors.list.gz");
        //testing.loadFile("\\\\Cougar\\cop3530\\actresses.list.gz");   
        //testing.loadFile("\\\\Cougar\\cop3530\\actors.list.gz");
        System.out.println(" Ending Time of Downloading:  " + System.currentTimeMillis());
        int infiniteloop = 0 ;
           while (infiniteloop == 0)
                     System.out.println("Number of Actors and Actresses : " + testing.getActorCount());
                  System.out.println("Number of Movies: " + testing.getMovieCount());  
                      System.out.println("");
                      System.out.println("Enter a name please");
                      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                      String name = in.readLine(); 
                      testing.computeSharedMovies(name);
                  List listofnames = new ArrayList();
                  listofnames =  testing.mostSharedMovies();  
                  testing.print(name, listofnames);
    //static class actor 
      private static final class Actor
         String name;
         int    data;  // number of shared movies,
                       // determined by computeSharedMovies
         public String toString( )
           { return name; }
         public int hashCode( )
           { return name.hashCode( ); }
         public boolean equals( Object other )
           { return (other instanceof Actor) &&
                    ( (Actor) other ).name.equals( name );
    *Loads the two files files
    *@param String is the fileName to be download
      public void loadFile( String fileName ) throws IOException
           BufferedReader x = new BufferedReader ( new InputStreamReader(new GZIPInputStream (new BufferedInputStream( new FileInputStream(fileName)))));
                String line;
          int start = 0 ;
          ArrayList actorList = new ArrayList();
          ArrayList movies = new ArrayList();
          Actor key = new Actor();
          int p = 0;    //parameters
          int p2 =0 ;
          String you = null ;
          String year = null;
          String trimMovie = null;
          int par1 = 0;    //parameter
          int par2 =0;
          String addingmovie = null;
            while((line = x.readLine()) != null)
                if(line.indexOf("Name") == 0 )
                      start++;
                if(start == 0)
                continue;
                  if( start >= 1)
                                  if(line.indexOf("-----------------------") == 0)
                                          break;
                                  if(((line.trim()).length()) == 0)
                                         continue;
                                  else if(line.indexOf("----") == 0)
                                          continue;
                                     else if (line.indexOf("Name") == 0)
                                             continue;
                                  else if(line.indexOf("\t") != 0)
                                     p  = line.indexOf("\t");
                                     p2 = line.lastIndexOf(")");
                                     String actor = (line.substring(0,p));
                                       key = new Actor();
                                       key.name = actor;                              
                                        you = (line.substring(p, (p2 + 1)));
                                          if (you.indexOf("(TV)") > 0)
                                                         continue;                                                                                                
                                       p = you.indexOf("\t");
                                       p2 = you.indexOf(")");
                                      you = (you.substring(p, p2 +1)).trim();                                 
                                            if(you.indexOf("\"") == 0)
                                                    continue;                                                                                        
                                            year = you ;
                                       p = year.indexOf("(");
                                       p2 = year.indexOf(")");
                                       year = year.substring(p + 1 , p2);                                 
                                            if ( ( ((Comparable)year).compareTo("2002") ) >= 0)
                                                    continue;                                                                                         
                                     you = you.intern();                                                                  
                                     movies = new ArrayList();
                                      movies.add(you);
                                     movies.trimToSize() ;                    
                                        map1.put(key , movies);
                                           if(map2.containsKey(you))
                                                      ((ArrayList)map2.get(you)).add(key) ;
                                            else
                                                         actorList = new ArrayList();
                                                           actorList.add(key);
                                                           actorList.trimToSize() ;                                                          
                                                           map2.put(you, actorList);
                               else if(line.indexOf("\t") == 0)
                                    par1 = line.indexOf(")");
                                    par2 = line.indexOf("\t");
                                    trimMovie = (line.substring(par2, par1 +1)).trim();
                                    trimMovie = trimMovie.intern();                              
                                    String ye = trimMovie;
                                    par1 = trimMovie.indexOf("(");
                                    par2 = trimMovie .indexOf(")");                              
                                    ye = (ye.substring(par1 + 1 , par2));                             
                                     addingmovie = (line.trim());
                                           if(addingmovie.indexOf("(TV)") > 0)
                                           else if ( (((Comparable)ye).compareTo("2002")) >= 0)
                                           else  if(addingmovie.indexOf("\"") == 0)
                                           else if(addingmovie.indexOf("(archive footage)") > 0)
                                            else
                                                     if(map1.containsKey(key))
                                                                 ((ArrayList)map1.get(key)).add(trimMovie);                         
                                                              ((ArrayList)map1.get(key)).trimToSize() ;
                                                    else
                                                          movies = new ArrayList();
                                                          movies.add(trimMovie);
                                                          movies.trimToSize() ;
                                                          map1.put(key, movies);
                                              if(map2.containsKey(trimMovie))
                                                 {     ((ArrayList)map2.get(trimMovie)).add(key);
                                                     ((ArrayList)map2.get(trimMovie)).trimToSize() ;
                                            else
                                                           actorList = new ArrayList();
                                                         actorList.add(key);
                                                        actorList.trimToSize() ;
                                                        map2.put(trimMovie, actorList);
    *Compute the amount of shared movies for all actor compared to the one
    *given from the user
    *@param String actor is the actor that the user wish to search for some
    *other actors/actresses with the most shared movies with him
        public void computeSharedMovies( String actor )
             Actor actor2 = new Actor();
             actor2.name = actor;
            if(map1.containsKey(actor2))
                  okactor = 0 ;
                  Actor actor3 = new Actor();
                  actor3 = actor2;
                      for(int count = 0 ; count < ((ArrayList)(map1.get(actor2))).size() ; count++)
                           String movie = (String)((ArrayList)(map1.get(actor2))).get(count);      
                                for (int count2 = 0 ; count2 < ((ArrayList)map2.get(movie)).size() ; count2++)     
                                          Actor iuu = (Actor)((ArrayList)map2.get(movie)).get(count2);
                                          if(!(iuu.name).equals( actor3.name))
                                                     iuu.data++;
             Set entries = map1.entrySet();
             Iterator itr = entries.iterator();
                 List x2 = new ArrayList() ;
                 Actor big = new Actor();
                 big.data = 0;
                 List list = new ArrayList();
             while (itr.hasNext())
                       Map.Entry thisPair = (Map.Entry) itr.next();                 
                          Actor actorCompare = ((Actor)thisPair.getKey());                                   
                          if( actorCompare.data > big.data)
                               big.name = actorCompare.name;
                               big.data = actorCompare.data;
                               list = new ArrayList();
                               list.add(actorCompare);
                      else if (actorCompare.data == big.data)
                                list.add(actorCompare);
          }//end of if, if actor is in map
           else
                   okactor = 1;
    *Prints the final output
    *@param String actor1 is the actor pick by the user to be search
    *@param List most is the list with all the actors/actresses that had
    *the most shared movies
      public void print (String actor1 , List most)
         if(okactor == 0)
               Actor actorPrint = new Actor();
               actorPrint.name = actor1;
               Actor y = new Actor();
               y = actorPrint;
               List  list = new ArrayList();
               list = most;
               int data = ((Actor)list.get(0)).data;
               ArrayList list2 = new ArrayList();
               list2 = (ArrayList)(map1.get(actorPrint));
                  for(int getActor = 0 ; getActor < list.size() ;getActor++)
                           System.out.println(list.get(getActor) + "  :   (" +  data  + "  " + "Shared roles)");
                            Actor name3  = (Actor)list.get(getActor);
                           String na  = name3.name;
                             Map map3 = new HashMap();
                            ArrayList ji = new ArrayList ();
                            ji = (ArrayList)map1.get(list.get(getActor));
                    for (int array1 = 0 ; array1 < ji.size()  ; array1++)
                         map3.put( ji.get(array1) , na);
                    for(int count = 0 ; count < list2.size() ; count++)
                           if(map3.containsKey(list2.get(count)))
                           System.out.println("                    " + (list2.get(count))); 
             Set entries =map1.entrySet();
             Iterator itr = entries.iterator();
             Actor  actortoclean = new Actor();
                  while(itr.hasNext())
                       Map.Entry thisPair = (Map.Entry)itr.next();
                       actortoclean = (Actor)thisPair.getKey();     
                       actortoclean.data = 0 ;      
       else  //else if okactor greater than 0
       System.out.println("THE ACTOR IS NOT IN FILE PLEASE TRY AGAIN") ;
    * Coputes what actors or actresses have the most shared movies
    *return a List with all the actor that have the most shared
    *movies
      public List mostSharedMovies( )
        if(okactor == 0)
        Set entries = map1.entrySet();
        Iterator itr = entries.iterator();
        List x = new ArrayList() ;
        Actor big = new Actor();
        big.data = 0;
        List list = new ArrayList();
          while (itr.hasNext())
                  Map.Entry thisPair = (Map.Entry) itr.next();
                     Actor o1 = ((Actor)thisPair.getKey());
                          if( o1.data > big.data)
                               big.name = o1.name;
                               big.data = o1.data;                 
                               list = new ArrayList();
                               list.add(o1);
                           else if (o1.data == big.data)
                                list.add(o1);
        return list;
      else
         return null;
    *Gives the amount of actor in the map of actors
    *return an int with the quantity
      public int getActorCount( )
          return map1.size();
    *Gives the amount of movies in the map of movies
    *return an int with the quantity
      public int getMovieCount()
           return map2.size();
    }Kevin Bacon Game
    For a description of the Kevin Bacon game, follow this link http://www.cs.virginia.edu/oracle/ . Try the game a few times and see if you can find someone with a Bacon Number higher than 3. In this program you will find all persons with a Bacon Number of 8 or higher. One of these persons is a former President of the United States.
    Strategy
    This is basically a shortest path problem. After that is done, find the large Bacon numbers by scanning the bacon numbers and print out the high-numbered actors and their chains. To print out a high-numbered actor, you should use recursion. Specifically, if some actor x has a Bacon number of b, then you know that they must have been in a movie with someone, call them actor y with a Bacon number of b-1. To print out x's chain, you would print out y's chain (recursively) and then the movie that x and y had in common.
    The Input Files
    There are two data files; both have identical formats. These files are: actors file and actresses file. These files are both compressed in .gz format, and were obtained from the Internet Movie Database. Combined, they are 52 Mbytes (compressed!) and were last updated October 17, 2002. These files are available at ftp://ftp.imdb.com/pub/interfaces/
    These datafiles contain approximately 571,000 actors/actresses in a total of 192,000 movies, with 2,144,000 roles. These files also list TV roles, but you must not include TV roles in your analysis.
    Before you run on the large data sets, use the small (uncompressed) file sample.list(http://www.fiu.edu/~lmore004/cop3530/sample.list) to debug the basic algorithms. In this data file, there are six actors, named a, b, c, d, e, and f, who have been in movies such as X, Y, and Z.
    Input File Hints
    Since it is not my input file, I cannot answer questions about it. Here are some observations that I used in my program, that should suffice. You can read the input file line by line by wrapping a FileInputStream inside a BufferedInputStream inside a GZIPInputStream inside an InputStreamReader inside a BufferedReader. You may not uncompress the file outside of your program.
    There are over 200 lines of preamble that can be skipped. This varies from file to file. However, you can figure it out by skipping all lines until the first occurrence of a line that begins with "Name", and then skipping one more.
    There are many postamble lines, too, starting with a line that has at least nine dashes (i.e. ---------).
    A name is listed once; all roles are together; the name starts in the first column.
    A movie title follows the optional name and a few tab stops ('\t'). There are some messed up entries that have spaces in addition to tab stops.
    The year should be part of the movie title.
    Movies made in 2003 or later should be skipped.
    A TV movie, indicated by (TV) following the year, is to be skipped.
    Archive material, indicated by (archive footage), is to be skipped. (Otherwise JFK is a movie star).
    Cameo appearances, indicated by [Cameo appearance], should be skipped.
    A TV series, indicated by a leading " in the title is to be skipped.
    A video-only movie, indicated by (V) following the year is allowed.
    Blank lines separate actors/actresses, and should be skipped.
    Strategy
    In order to compute your answers, you will need to store the data that you read. The main data structures are a Map in which each key is an Actor and each value is the corresponding list of movies that the actor has been in, and then a second Map, in which key is a movie and each value is the list of Actors in the movie (i.e. the cast). A movie is represented simply as a String that includes the year in which it was made, but an Actor includes both the name of the actor, and a data field that you can use to store computed information later on. Thus, ideally, you would like to define a class that looks somewhat like this (with routines to compute Bacon Numbers not listed):
    public class Database
      private static final class Actor
         String name;
         int    data;  // Bacon number ,
                       // determined by computeBaconNumbers
         public String toString( )
           { return name; }
         public int hashCode( )
           { return name.hashCode( ); }
         public boolean equals( Object other )
           { return (other instanceof Actor) &&
                    ( (Actor) other ).name.equals( name ); }
        // Open fileName; update the maps
      public void loadFile( String fileName ) throws IOException
      public int getActorCount( )
      public int getMovieCount( )
      private Map actorsToMovies = new HashMap( );
      private Map moviesToActors = new HashMap( );
      Memory Details
    The description above is pretty much what you have to do, except that you must take extra steps to avoid running out of memory.
    First, you will need to increase the maximum size of the Java Virtual Machine from the default of 64Meg to 224Meg. You may not increase it any higher than that. If you are running the java interpreter from the command line, the magic option is -Xmx224m. If you are using an IDE, you will have to consult their documentation --- don't ask me.
    Second, you will quickly run out of memory, because if you find two movies that are the same, but are on different input lines, the default setup will create two separate (yet equal) String objects and place them in the value lists of two different actors. Since there are 2.1 million roles, but only 192,000 movies, this means that you will have ten times as many String objects as you really need. What you need to do is to make sure that each movie title is represented by a single String object, and that the maps simply store references to that single String object. There are two basic alternatives:
    The String class has a method call intern. If you invoke it, the return value on equal Strings will always reference the same internal String object.
    You can keep a HashMap in which each key is a movie title, and each value is the same as the key. When you need a movie title, you use the value in the HashMap.
    Option two is superior (performancewise) to option #1 and it is required that you use it to avoid memory problems.
    When you maintain the list of movies for each actor, you will want to use an ArrayList. It takes little effort to ensure that the capacity in the ArrayList is not more than is needed, and you should do so, to avoid wasting space (since there are 571,000 such array lists).
    When you construct the HashMaps, you can issue a parameter (the load factor). The higher the load factor, the less space you use (at the expense of a small increase in time). You should play around with that too; the default is 0.75; you will probably want a load factor of 2.00 or 3.00.
    You must be very careful to avoid doing any more work in the inner loops than you need to, including creating excessive objects. IF YOU CREATE EXCESSIVE OBJECTS, YOUR PROGRAM MAY SLOW TO A CRAWL BECAUSE ALL ITS TIME WILL BE SPENT IN THE GARBAGE COLLECTOR OR RUN OUT OF MEMORY COMPLETELY.
    What to Submit
    Submit complete source code and the actors/actresses with Bacon Numbers of 8 or higher. Include the complete paths for each of the actors/actresses (with shared movie titles). Also indicate how long your algorithm takes. This means how long it takes to load, and also how long it takes to run the shortest path computation (not including the output of the answer), by inserting calls to System.currentTimeMillis at appropriate points in your code, and tell me how many actors and movies there are. Also, insert this code (at the end of your program) that tells me how large the VM is:
    Runtime rt = Runtime.getRuntime( );
    int vmsize = (int) rt.totalMemory( );
    System.out.println( "Virtual machine size: " + vmsize );
    Don't forget to write in the processor speed of the computer you are using. If it's somewhat fast, or provably space-efficient, you can get extra credit. You cannot receive credit for a working program if your program fails to produce a large set of actors and actresses with Bacon Numbers of 8 or higher. Note: the data you will work on and the data the Oracle uses (and the IMDB data) are all slightly out of sync. So you might not be able to exactly reproduce the results, although I was able to get a complete set of Bacon Numbers 8 and higher when I ran my program on October 23, using the Oct 17 files.
    Due Date
    This program is due on Thursday November 14.
    Additional Notes
    The exact sizes of the data files are 36381624 and 18263563 bytes, respectively. If you download and the files are larger, then you messed up the download. Note that if you are using Windows XP, these files might be uncompressed during downloading. If so, you can use this program to recompress the file. If the files are smaller, then the download probably got interrupted before it finished and you will need to retry. Here is a gzipped sample.list for you to test that aspect of your program.
    Running on COTTON in the AUL, which is a 450 MHz Pentium III, and accessing the files over the network as "\\\\couger\\cop3530\\actors.list.gz", (and similarly for actresses.list.gz), and with no other processes running besides notepad, the data files loaded in 180 seconds. You should be able to get faster results on a faster machine. Some of the AUL machines are 1.6 GHz. You should indicate which AUL machine (with processor speed) ran your submission.
    Entries with years such as (1996/I) are optional.
    When writing and reading make sure you are using BufferedInputStream and BufferedOutputStream, as appropriate.
    Sketch of the basic shortest path computation:
    // typically invoked with Kevin Bacon as parameter
    // This is the basic algorithm; there's stuff

    I forgot to post the code, here it is:
    import java.util.LinkedList ;
    import java.io.*;
    import java.util.zip.*;
    import java.util.ArrayList;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Set;
    import java.util.Iterator;
    import java.util.HashSet;
    * A class that download files , create Maps and search for information with
    public class DataBase2 implements Serializable
      private Map map1 = new HashMap((int)515927, (float)0.85 );  // actor
      private Map map2= new HashMap((int)172911, (float)0.85 );   //movies
      transient private Map map3 = new HashMap();   //movie and movie
      transient private int okactor = 0;
      transient static final int INFINITY = Integer.MAX_VALUE;
    // Main Method
      public static void main (String args [])throws IOException
        int c  = 0 ;
        System.out.println("Program was run in Pentium 4 in AUL");        
        DataBase2 testing = new DataBase2();   
        try{   
            ObjectInputStream ii1 = new ObjectInputStream (new BufferedInputStream (new FileInputStream("file2.ser")));
        catch (FileNotFoundException ex)
            System.out.println("FILE NOT ON DISK PLEASE WAIT WHILE DOWNLOADING");
            long x = System.currentTimeMillis();
            testing.loadFile("\\\\Cougar\\cop3530\\actresses.list.gz");   
            testing.loadFile("\\\\Cougar\\cop3530\\actors.list.gz");
            long y = System.currentTimeMillis();
            System.out.println("DONE WITH DOWNLOADING, USING NORMAL METHOD " +(y - x)/1000 + " seconds");                       
            System.out.println("The actors count is:  " + testing.getActorCount());
            System.out.println("The movies count is:  "  + testing.getMovieCount());
            testing.loadser(testing);      
            System.out.println("END OF DUMPING");      
            testing.findBacon();  
            c++;        
        if (c == 0 )
            long o= System.currentTimeMillis();   
            testing = testing.fastloading(testing);
            long y = System.currentTimeMillis(); 
            System.out.println("DONE WITH LOADING, FROM SERIALIZED FILES  " + (y-o)/1000 + "seconds");         
            System.out.println("The actors count is:   " + testing.getActorCount());
            System.out.println("The movies count is:   " + testing.getMovieCount());
            testing.findBacon();             
            Runtime rt = Runtime.getRuntime( );       
            int vmsize = (int) rt.totalMemory( );       
            System.out.println(" " );
            System.out.println( "The Virtual Machine size is : " + vmsize + " bytes" );
    //static class actor 
      private static final class Actor implements Serializable
         String name;
         int    data;  // number of shared movies,
                       // determined by computeSharedMovies          
         public String toString( )
           { return name; }
         public int hashCode( )
           { return name.hashCode( ); }         
         public boolean equals( Object other )
           { return (other instanceof Actor) && ( (Actor) other ).name.equals( name );}
    *Method to find the bacon number of each actor
    *and also send information, actors greater than 7,  to be print
      public void findBacon()
        ArrayList actorlist = new ArrayList();
        long time1 = System.currentTimeMillis();
        Actor actor2 = new Actor();    
        actor2.name = "Bacon, Kevin";
        actor2.data = 0;
        Set entries =map1.entrySet();
        Iterator itr = entries.iterator();
        Actor  actortoInfinity = new Actor();
        Set listofMovies = new HashSet();          
                    while(itr.hasNext())
                            Map.Entry thisPair = (Map.Entry)itr.next();
                            actortoInfinity = (Actor)thisPair.getKey();    
                            if((actortoInfinity.name).equals( actor2.name))
                                    actortoInfinity.data = 0 ;                     
                            else
                            actortoInfinity.data = INFINITY ;      
         Actor actor3 = new Actor() ;      
         LinkedList list = new LinkedList();
         list.addLast(actor2) ;
         Actor out = new Actor();
                    while (list.isEmpty() != true)
                            out = (Actor)list.getFirst();
                        list.removeFirst() ;
                                    for(int count = 0 ; count < ((ArrayList)(map1.get(out))).size() ; count++)
                                            String movie = (String)((ArrayList)(map1.get(out))).get(count);                      
                            if(listofMovies.contains(movie))
                            {continue;}
                            else
                            listofMovies.add(movie);
                                    for(int count2 = 0; count2 < ((ArrayList)(map2.get(movie))).size() ; count2++)
                                                    actor3  =   (Actor)(((ArrayList)(map2.get(movie))).get(count2) )  ;
                                            if(actor3.data == INFINITY)
                                                actor3.data = out.data + 1;
                                                list.addLast(actor3) ;
                                    if(actor3.data >= 7)
                                            actorlist.add(actor3);                                                                 
                                                             }//inner loop                
                         }//else
                     }//outer loop
                 }//while loop
         long time2 = System.currentTimeMillis();
         System.out.println("Done gettig Bacon Number(shortest path): " + (time2 - time1)/1000 + " Seconds");
                    for(int count = 0 ; count < actorlist.size() ; count++)
                                    print((Actor)(actorlist.get(count)));
    *Method used to print the chain of information within
    *each actor with Bacon number of 7 and over
    *it uses recursion to do it
      private void   printPath (Actor target)
        int c = 0 ;  
        Actor actor = new Actor();
            String movies ;
              if (target.data == 0)
                  System.out.println("-----------------------------END OF PATH-----------------------------");                           
              else
                    for(int x = 0 ; x < ((ArrayList)(map1.get(target))).size(); x++)
                    movies = (String)(((ArrayList)(map1.get(target))).get(x));
                    for (int y = 0 ; y < ((ArrayList)map2.get(movies)).size() ;  y++)
                            actor = (Actor)(((ArrayList)(map2.get(movies))).get(y));
                            if(actor.data == target.data - 1)
                                    System.out.println("* " + target + "  acted with " + actor+ " how's BK # is " + actor.data + ", both in movie: " + movies ) ;
                                c++;
                                break;                      
                     }//inner loop
                   if (c > 0)
                   break;
                  }//outer loop
              printPath(actor);
    *Gets the actor to print
    *and sends the same actor to
    *PrintInfo method to print
    *its chain
    *@param target the actor to print
      public void print(Actor target)
                            System.out.println(" " );
                                    System.out.println(" " ); 
                            System.out.println(" " );
                                    System.out.println(target.name + "'s Bacon number is: " +target.data);
                                    System.out.println(" " );
                                printPath(target);                                                                                                                                                                         
    *A method to load the Serialization file
    *so it,the file,  can be manipulated
    *@param x the DataBase object to be load
    *with all the files
    *@return the object x with all the file
    *withit
      public DataBase2 fastloading(DataBase2  target2) throws IOException
            try{ 
                    ObjectInputStream ii1 = new ObjectInputStream (new BufferedInputStream (new FileInputStream("file2.ser")));
                    target2= (DataBase2) ii1.readObject();
                    ii1.close();
        catch(ClassNotFoundException e )
           System.out.println("Error, class exception");
        catch(FileNotFoundException ex)
           System.out.println("Error, the file is not on the disk");       
        return target2;            
    *Method to write the Object DataBase2, created before, into a Serializable file
      public void loadser(DataBase2 ObjecttoLoad ) throws IOException
            ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("file2.ser")));
            oo.writeObject(ObjecttoLoad);
            oo.close();
    /**Method use to download files for the first time
    *it creates maps, which contains actor and movies
    *@param fileName it gets the file to be read and
    *used to get the data into the maps
      public void loadFile( String fileName ) throws IOException
          BufferedReader x = new BufferedReader ( new InputStreamReader(new GZIPInputStream (new BufferedInputStream( new FileInputStream(fileName)))));
          String line;          
          int start = 0 ;    
          ArrayList actorList = new ArrayList();
          ArrayList movies = new ArrayList();
          Actor key = new Actor();
          int p = 0;    //parameters
          int p2 =0 ;
          String you = null ;
          String year = null;
          String trimMovie = null;
          int par1 = 0;    //parameter
          int par2 =0;
          String addingmovie = null;
            while((line = x.readLine()) != null)
                if(line.indexOf("Name") == 0 )
                    start++;                       
                if(start == 0)
                continue;                       
                if( start >= 1)
                                  if(line.indexOf("-----------------------") == 0)
                                         break;                    
                                  if(((line.trim()).length()) == 0)
                                     continue;
                                  else if(line.indexOf("----") == 0)
                                     continue;
                                      else if (line.indexOf("Name") == 0)
                                             continue;
                                  else if(line.indexOf("\t") != 0)
                                     p  = line.indexOf("\t");
                                     p2 = line.lastIndexOf(")");                               
                                     String actor = (line.substring(0,p));                                        
                                             key = new Actor();
                                             key.name = actor;                               
                                             you = (line.substring(p, (p2 + 1)));                                                                                                                                                                                                                                                                              
                                             if (you.indexOf("(TV)") > 0)
                                                            continue;                                                                                              
                                     p = you.indexOf("\t");
                                     p2 = you.indexOf(")");
                                         you = (you.substring(p, p2 +1)).trim();                                    
                                          if(you.indexOf("\"") == 0)
                                                             continue;                      
                                     year = you ;      
                                     p = year.indexOf("(");
                                     p2 = year.indexOf(")");
                                     year = year.substring(p + 1 , p2);                                 
                                           if ( ( ((Comparable)year).compareTo("2002") ) >= 0)
                                                  continue;                                           
                                           if (map3.containsKey(you))
                                               else
                                                          map3.put(you, you);                                                                                              
                                     movies = new ArrayList();
                                     movies.add(map3.get(you));
                                     movies.trimToSize() ;                         
                                     map1.put(key , movies);
                                          if(map2.containsKey(map3.get(you)))
                                                              ((ArrayList)map2.get(map3.get(you))).add(key) ;
                                          else
                                                              actorList = new ArrayList();
                                                                          actorList.add(key);
                                                                      actorList.trimToSize() ;                                                                     
                                                                      map2.put(map3.get(you), actorList);
                             else if(line.indexOf("\t") == 0)
                                    par1 = line.indexOf(")");
                                    par2 = line.indexOf("\t");                                                          
                                    trimMovie = (line.substring(par2, par1 +1)).trim();
                                    // trimMovie = trimMovie.intern();                           
                                    if(map3.containsKey(trimMovie))
                                    else
                                    map3.put(trimMovie , trimMovie);
                                    String ye = (String)map3.get(trimMovie);
                                    par1 = trimMovie.indexOf("(");
                                    par2 = trimMovie .indexOf(")");                             
                                    ye = (ye.substring(par1 + 1 , par2));                                                               
                                    addingmovie = (line.trim());
                                        if(addingmovie.indexOf("(TV)") > 0)
                                            else if ( (((Comparable)ye).compareTo("2002")) >= 0)
                                            else  if(addingmovie.indexOf("\"") == 0)
                                            else if(addingmovie.indexOf("(archive footage)") > 0)
                                        else
                                            if(map1.containsKey(key))
                                                            ((ArrayList)map1.get(key)).add(map3.get(trimMovie));                            
                                                            ((ArrayList)map1.get(key)).trimToSize() ;
                                            else
                                                    movies = new ArrayList();
                                                    movies.add(map3.get(trimMovie));
                                                    movies.trimToSize() ;
                                                    map1.put(key, movies);
                                           if(map2.containsKey(trimMovie))
                                                {   ((ArrayList)map2.get(map3.get(trimMovie))).add(key);
                                                    ((ArrayList)map2.get(map3.get(trimMovie))).trimToSize() ;
                                               else
                                                            actorList = new ArrayList();
                                                                    actorList.add(key);
                                                            actorList.trimToSize() ;
                                                            map2.put(map3.get(trimMovie), actorList);
                                      }     //end of last else if          
                        }//end of if
                }//end of while
        }//end of method
    *Gives the amount of actor in the map of actors
    *return an int with the quantity
      public int getActorCount( )    
          return map1.size();
    *Gives the amount of movies in the map of movies
    *return an int with the quantity
      public int getMovieCount()
           return map2.size();
    }//end of DataBase2 class

  • I need some help with my java game using applets, CAN SOMEBODY PLEASE HELP

    Hi,
    I am in the process of creating a RPG program using Java. I am not very experienced with java, however the problem i am currently facing is something i can't seem to figure out. I would like to draw a simple grid where a character (indicated by a filled circle) moves around this grid collecting items (indicated by a red rectangle). When the character moves on top of the grid with the item, i would like it to disappear. Right now i am not worrying about the fact that the item will reappear after the character moves away again, because sometimes, when the character moves over the item, nothing happens/another item disappears. i have been at this for 4 days and still cannot figure out what is goign on. can somebody please help me? it would be most appreciated.
    Thanks
    PS if i needed to send you my code, how do i do it?

    Thank you for replying.
    The thing is, I am taking java as a course, and it is necessary for me to start off this way (this is for my summative evaluation). i agree with you on the fact, however, that i should go in small steps. i have been doing that until this point, and my frustration caused me to jump around randomly for an answer. I also think that it may just be a bug, but i have no clue as to how to fix it, as i need to show my teacher at least a part of what i was doing by sometime next week. Here is my code for anybody willing to go through it:
    // The "Keys3" class.
    import java.applet.*;
    import java.awt.*;
    import java.awt.Event;
    import java.awt.Font;
    import java.awt.Color;
    import java.applet.AudioClip;
    public class Keys3 extends java.applet.Applet
        char currkey;
        int currx, curry, yint, xint;
        int itmval [] = new int [5],
            locval [] = new int [5],
            tempx [] = new int [5], tempy [] = new int [5],
            tot = 0, score = 0;
        boolean check = true;
        AudioClip bgSound, bgSound2;
        AudioClip hit;
        private Image offscreenImage;
        private Graphics offscreen;     //initializing variables for double buffering
        public void init ()  //DONE
            bgSound = getAudioClip (getCodeBase (), "sound2_works.au");
            hit = getAudioClip (getCodeBase (), "ah_works.au");
            if (bgSound != null)
                bgSound.loop ();
            currx = 162;
            curry = 68;
            setBackground (Color.white);
            for (int count = 0 ; count < 5 ; count++)
                itmval [count] = (int) (Math.random () * 5) + 1;
                locval [count] = (int) (Math.random () * 25) + 1;
            requestFocus ();
        public void paint (Graphics g)  //DONE
            resize (350, 270);
            drawgrid (g);
            if (check = true)
                pickitems (g);
                drawitems (g);
            g.setColor (Color.darkGray);
            g.fillOval (currx, curry, 25, 25);
            if (currkey != 0)
                g.setColor (Color.darkGray);
                g.fillOval (currx, curry, 25, 25);
            if (collcheck () != true)
                collision (g);
            else
                drawitems (g);
        } // paint method
        public void update (Graphics g)  //uses the double buffering method to overwrite the original
                                         //screen with another copy to reduce flickering
            if (offscreenImage == null)
                offscreenImage = createImage (this.getSize ().width, this.getSize ().height);
                offscreen = offscreenImage.getGraphics ();
            } //what to do if there is no offscreenImage copy of the original screen
            //draws the backgroudn colour of the offscreen
            offscreen.setColor (getBackground ());
            offscreen.fillRect (0, 0, this.getSize ().width, this.getSize ().height);
            //draws the foreground colour of the offscreen
            offscreen.setColor (getForeground ());
            paint (offscreen);
            //draws the offscreen image onto the main screen
            g.drawImage (offscreenImage, 0, 0, this);
        public boolean keyDown (Event evt, int key)  //DONE
            switch (key)
                case Event.DOWN:
                    curry += 46;
                    if (curry >= 252)
                        curry -= 46;
                        if (hit != null)
                            hit.play ();
                    break;
                case Event.UP:
                    curry -= 46;
                    if (curry <= 0)
                        curry += 46;
                        if (hit != null)
                            hit.play ();
                    break;
                case Event.LEFT:
                    currx -= 66;
                    if (currx <= 0)
                        currx += 66;
                        if (hit != null)
                            hit.play ();
                    break;
                case Event.RIGHT:
                    currx += 66;
                    if (currx >= 360)
                        currx -= 66;
                        if (hit != null)
                            hit.play ();
                    break;
                default:
                    currkey = (char) key;
            repaint ();
            return true;
        public boolean collcheck ()  //DONE
            if (((currx == tempx [0]) && (curry == tempy [0])) || ((currx == tempx [1]) && (curry == tempy [1])) || ((currx == tempx [2]) && (curry == tempy [2])) || ((currx == tempx [3]) && (curry == tempy [3])) || ((currx == tempx [4]) && (curry == tempy [4])))
                return false;
            else
                return true;
        public void collision (Graphics g)
            drawgrid (g);
            for (int count = 0 ; count < 5 ; count++)
                if ((currx == tempx [count]) && (curry == tempy [count]))
                    g.setColor (Color.darkGray);
                    g.fillOval (currx, curry, 25, 25);
                else if ((currx != tempx [count]) && (curry != tempy [count]))
                    g.setColor (Color.red);
                    g.fillRect (tempx [count], tempy [count], 25, 25);
        public void drawitems (Graphics g)
            for (int count = 0 ; count < 5 ; count++)
                g.setColor (Color.red);
                g.fillRect (tempx [count], tempy [count], 25, 25);
        public void pickitems (Graphics g)
            check = false;
            for (int count = 0 ; count < 5 ; count++)
                if (locval [count] <= 5)
                    tempy [count] = 22;
                else if (locval [count] <= 10)
                    tempy [count] = 68;
                else if (locval [count] <= 15)
                    tempy [count] = 114;
                else if (locval [count] <= 20)
                    tempy [count] = 160;
                else if (locval [count] <= 25)
                    tempy [count] = 206; //this determines the y-position of the item to be placed
                if (locval [count] % 5 == 0)
                    tempx [count] = 294;
                else if ((locval [count] == 1) || (locval [count] == 6) || (locval [count] == 11) || (locval [count] == 16) || (locval [count] == 21))
                    tempx [count] = 30;
                else if ((locval [count] == 2) || (locval [count] == 7) || (locval [count] == 12) || (locval [count] == 17) || (locval [count] == 22))
                    tempx [count] = 96;
                else if ((locval [count] == 3) || (locval [count] == 8) || (locval [count] == 13) || (locval [count] == 18) || (locval [count] == 23))
                    tempx [count] = 162;
                else if ((locval [count] == 4) || (locval [count] == 9) || (locval [count] == 14) || (locval [count] == 19) || (locval [count] == 24))
                    tempx [count] = 228;
        public void drawgrid (Graphics g)  //DONE
            g.drawRect (10, 10, 330, 230); //draws the outer rectangular border
            int wi = 10; //width of one square on the board
            int hi = 10; //height of one square on the board
            for (int height = 1 ; height <= 5 ; height++)
                for (int row = 1 ; row <= 5 ; row++)
                    if (((height % 2 == 1) && (row % 2 == 1)) || ((height % 2 == 0) && (row % 2 == 0)))
                        g.setColor (Color.gray);
                        g.fillRect (wi, hi, 66, 46);
                    else /*if (((height % 2 == 0) && (row % 2 == 1)) || ((height % 2 == 0) && (row % 2 == 0)))*/
                        g.setColor (Color.lightGray);
                        g.drawRect (wi, hi, 66, 46);
                        g.setColor (Color.lightGray);
                        g.drawRect (wi, hi, 66, 46); //drawn twice to make a shadow effect
                    wi += 66;
                wi = 10;
                hi += 46;
            } //this draws the basic outline of the game screen
    } // Keys3 class

  • Need help with " Number guessing game " please?

    This is what teacher requires us to do for this assignment:
    Write a program that plays a simple number guessing game. In this game the user will think of a number and the program will do the guessing. After each guess from the program, the user will either indicate that the guess is correct (by typing �c�), or that the next guess should be higher (by typing �h�), or that it should be lower (by typing �l�). Here is a sample output for a game. In this particular game the user thinks of the number 30:
    $java GuessingGameProgram
    Guess a number between 0 and 100
    Is it 50? (h/l/c): l
    Is it 25? (h/l/c): h
    Is it 37? (h/l/c): l
    Is it 31? (h/l/c): l
    Is it 28? (h/l/c): h
    Is it 29? (h/l/c): h
    Is it 30? (h/l/c): c
    Thank you for playing.
    $
    This program is implementing a binary search algorithm, dividing the range of possible values in half with each guess. You can implement any algorithm that you want, but, all things being equal, binary search is the best algorithm.
    Write the program so that the functionality is split between two classes: GuessingGameProgram, and NumberGuesser.
    GuessingGameProgram will only be used for its main function. It should instantiate a NumberGuesser, and it will be responsible for the loop that notifies the user of the next guess, reads the �h�, �l�, or �c� from the user, and sends an appropriate message to the number guesser accordingly.
    The guesses themselves should all be generated by the NumberGuesser class. Here is a diagram of the members and methods for the class. Notice that the members are unspecified. Feel free to give your NumberGuesser class any members (which we have also been calling fields, or instance variables) that you find useful. Make them all private.
    NumberGuesser
    NumberGuesser(int upperLimit, int lowerLimit)
    int guess()
    void higher()
    void lower()
    The constructor should take two integer arguments, a lower and upper bound for the guesses. In your program the constructor will be called with bounds of 0 and 100.
    The guess method should return the same value if it is called more than once without intervening calls to the lower or higher methods. The class should only change its guess when it receives a message indicating that its next guess should be higher or lower.
    Enjoy. Focus your attention on the NumberGuesser class. It is more interesting than the GuessingGameProgram class because it is a general-purpose class, potentially useful to anybody who is writing a number guessing game. Imagine, for instance, that a few weeks from now you are asked to write a number guessing game with a graphical Java Applet front end. If you NumberGuesser class is well written, you may be able to reuse it without any modifications.
    I'm new to JAVA and I'm set with my 2nd homework where I'm so confused. I know how to do something of this source in C language, but I'm a bit confused with Java. This is the code me and my classmate worked on, I know it's not 100% of what teacher asked, but is there any way possibly you guys could help me? I wrote this program if the game is played less then 10 times, thought I would then re-create a program without it, but now I'm confused, and my class book has nothing about this :( and I'm so confused and lost, can you please help? And out teacher told us that it's due the end of this week :( wish I knew what to do. Thank you so so much.
    Here's the code:
    import java.text.*;
    import java.io.*;
    class GuessingGame
    public static void main( String[] args ) throws IOException
    BufferedReader stdin = new BufferedReader(new InputStreamReader( System.in ) );
    int guess = 0, limit = 9, x = 0, n, a = 0 ;
    double val = 0 ;
    String inputData;
    for ( x = 1; x <= 10; x++)      //number of games played
    System.out.println("round " + x + ":");
    System.out.println(" ");
    System.out.println("I am thinking of a number from 1 to 10. ");
    System.out.println("You must guess what it is in three tries. ");
    System.out.println("Enter a guess: ");
    inputData = stdin.readLine();
    guess = Integer.parseInt( inputData );
    val = Math.random() * 10 % limit + 1;     //max limit is set to 9
    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(0);               //format number of decimal places
    String s = nf.format(val);
    val = Integer.parseInt( s );
         for ( n = 1; n <= 3; n++ )      //number of guess's made
                   if ( guess == val)
                        System.out.println("RIGHT!!");                    //if guess is right
                        a = a + 1;
                        System.out.println("You have won " + a + " out of " + x + " rounds");
    System.out.println(" ");
    n = 3;
    continue;
              if (n == 3 && guess != val)                         //3 guesses and guess is wromg
                        System.out.println("wrong");
    System.out.println("The correct number was " + val);
                        System.out.println("You have won " + a + " out of " + x + " rounds");
    System.out.println(" ");
    continue;
                   //how close guess is to value
                   if ( guess == val - 1 || val + 1 == guess) //Within 1
                   System.out.println("hot");
         else if ( guess == val - 2 || val + 2 == guess) // Within 2
                   System.out.println("warm");
              else
                   System.out.println("cold");                         // Greater than 3
         inputData = stdin.readLine();
         guess = Integer.parseInt( inputData );
    //ratings
    if ( a <= 7)
         System.out.println("Your rating is: imbecile.");
    else if ( a <= 8)
         System.out.println("Your rating is: getting better but, dumb.");
    else if (a <= 9)
         System.out.println("Your rating is: high school grad.");
    else if ( a == 10)
         System.out.println("Your rating is: College Grad.!!!");

    Try this.
    By saying that, I expect you ,and your classmate(s), to study this example and then write your own. Hand it in as-is and you'll be rumbled as a homework-cheat in about 20ms ;)
    When you have an attempt where you can explain, without refering to notes, every single line, you've cracked it.
    Also (hint) comment your version well so your tutor is left with the impression you know what you're doing.
    In addition (huge hint) do not leave the static inner class 'NumberGuesser' where it is. Read your course notes and find out where distinct classes should go.
    BTW - Ever wonder if course tutors scan this forum for students looking for help and/or cheating?
    It's a double edged sword for you newbies. If you ask a sensible, well researched question, get helpful answers and apply them to your coursework, IMHO you should get credit for doing that.
    On the other hand, if you simply post your assignment and sit there hoping some sucker like me will do it for you, you should be taken aside and given a good kicking - or whatever modern educational establishments consider appropriate abmonishment ;)
    I'd say this posting is, currently, slap bang between the two extreemes, so impress us. Post your solution in the form you intend to hand it in, and have us comment on it.
    Good luck!
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    public class GuessingGame
         public static void main(String[] args)
              throws Exception
              BufferedReader reader= new BufferedReader(
                   new InputStreamReader(System.in));
              NumberGuesser guesser= new NumberGuesser(0, 100);
              System.out.println(
                   "\nThink of a number between 0 and 100, oh wise one...");
              int guess= 0;
              while (true) {
                   guess= guesser.guess();
                   System.out.print("\nIs it " +guesser.guess() +"? (h/l/c) ");
                   String line= reader.readLine();
                   if (line == null) {
                        System.out.println(
                             "\n\nLeaving? So soon? But we didn't finish the game!");
                        break;
                   if (line.length() < 1) {
                        System.out.println("\nPress a key, you muppet!");
                        continue;
                   switch (line.toLowerCase().charAt(0)) {
                        case 'h':  
                             guesser.higher();
                             break;
                        case 'l':     
                             guesser.lower();
                             break;
                        case 'c':
                             System.out.println("\nThank you for playing.");
                             System.exit(0);
                        default:
                             System.out.println(
                                  "\nHow hard can it be? Just press 'h' 'l' or 'c', ok?");
                             continue;
                   if (guess == guesser.guess()) {
                        System.out.println(
                             "\nIf you're going to cheat, I'm not playing!");
                        break;
         private static class NumberGuesser
              private int mLower;
              private int mUpper;
              private int mGuess;
              NumberGuesser(int lowerLimit, int upperLimit)
                   mLower= lowerLimit;
                   mUpper= upperLimit;
                   makeGuess();
              private void makeGuess() {
                   mGuess= mLower + ((mUpper - mLower) / 2);
              int guess() {
                   return mGuess;
              void higher()
                   mLower= mGuess;
                   makeGuess();
              void lower()
                   mUpper= mGuess;
                   makeGuess();
    }                  

  • I need help with an app game purchase

    I recently added 20$ to my account with 2 10$ Itunes cards. I play the app called clash of clans, in the game you can buy things with itunes, I tried to make a purchase for 19.99 when there is just about 21 $ in my itunes and it's telling me I have insufficient funds. This is odd becusee a couple days ago I did the same thing with the itunes card but now I'm getting this error. I checked my itunes again and I have the money, please help!

    What country are you in ? If you are in the US then does your state's sales tax take it over what you have on your account ?

  • Help with text based game.

    SO I've just begun to make a text based game and i've already ran into a problem :/
    I've made a switch statement that has cases for each of the classes in the game..for example
    Output will ask what you want to be
    1. Fighter
    2. etc
    3. etc
    case 1: //Fighter
    My problem is i want to be able to display the class
    as in game class not java class
    as Fighter
    That may be a bit confusing to understand sorry if it isn't clear
    Here is my code that i'm using this may help.
    import java.util.Scanner;
    public class main {
         public static void main(String args[]) {
              Scanner input = new Scanner(System.in);
              int health = 0;
              int power = 0;
              int gold = 0;
              System.out.println("Welcome to my game!");
              System.out.println("First of what is your name?");
              String name = input.next();
              System.out.println(name + " you say? Interesting name. Well then " + name + " what is your race?");
              System.out.println();
              System.out.println("Press 1. for Human");
              System.out.println("Press 2. for Elf");
              System.out.println("Press 3. for Orc");
              int Race = input.nextInt();
              switch (Race) {
              case 1: // Human
                   String race = "Human";
                   health = 10;
                   power = 10;
                   gold = 25;
              break;
              case 2: // Elf
                   health = 9;
                   power = 13;
                   gold = 25;
              break;
              case 3: // Orc
                   health = 13;
                   power = 9;
                   gold = 30;
              break;
              default:
                   System.out.println("Invalid choice Please choose 1-3");
              break;
              System.out.println("Now what is your class?");
              System.out.println("Press 1. Fighter");
              System.out.println("Press 2. Mage");
              System.out.println("Press 3. Rogue");
              int Class = input.nextInt();
              switch (Class) {
              case 1: // Fighter
                   health = health + 1;
                   power = power + 1;
                   gold = gold + 1;
              break;
              case 2: // Mage
                   health = health + 1;
                   power = power + 1;
                   gold = gold + 1;
              break;
              case 3: // Rogue
                   health = health + 1;
                   power = power + 1;
                   gold = gold + 1;
              break;
              default:
                   System.out.println("Invalid choice Please choose 1-3");
              break;
              System.out.println("So your name is " + name );
              System.out.println("and your race is: " + race);
              System.out.println("and your class is: " + Class);
    }Thanks in advance!

    Brushfire wrote:
    So you're advising him to run his console based game on the EDT, why?Far King good question... To which I suspect the answer is "Ummm... Ooops!" ;-)
    @OP: Here's my 2c... if you don't follow then ask good questions and I'll consider giving good answers.
    package forums;
    import java.util.Scanner;
    abstract class Avatar
      public final String name;
      public int type;
      public int health;
      public int power;
      public int gold;
      protected Avatar(String name, int health, int power, int gold) {
        this.name = name;
        this.health = health;
        this.power = power;
        this.gold = gold;
      public String toString() {
        return "name="+name
             +" health="+health
             +" power="+power
             +" gold="+gold
    class Human extends Avatar
      public Human(String name) {
        super(name, 10, 11, 31);
    class Elf extends Avatar
      public Elf(String name) {
        super(name, 9, 13, 25);
    class Orc extends Avatar
      public Orc(String name) {
        super(name, 6, 17, 13);
    interface AvatarFactory
      public Avatar createAvatar();
    class PlayersAvatarFactory implements AvatarFactory
      private static final Scanner scanner = new Scanner(System.in);
      public Avatar createAvatar() {
        System.out.println();
        System.out.println("Lets create your avatar ...");
        String name = readName();
        Avatar player = null;
        switch(readRace(name)) {
          case 1: player = new Human(name); break;
          case 2: player = new Elf(name); break;
          case 3: player = new Orc(name); break;
        player.type = readType();
        return player;
      private static String readName() {
        System.out.println();
        System.out.print("First off, what is your name : ");
        String name = scanner.nextLine();
        System.out.println(name + " you say? Interesting name.");
        return name;
      private static int readRace(String name) {
        System.out.println();
        System.out.println("Well then " + name + ", what is your race?");
        System.out.println("1. for Human");
        System.out.println("2. for Elf");
        System.out.println("3. for Orc");
        while(true) {
          System.out.print("Choice : ");
          int race = scanner.nextInt();
          scanner.nextLine();
          if (race >= 1 && race <= 3) {
            return race;
          System.out.println("Bad Choice! Please try again, and DO be careful! This is important!");
      private static int readType() {
        System.out.println();
        System.out.println("Now, what type of creature are you?");
        System.out.println("1. Barbarian");
        System.out.println("2. Mage");
        System.out.println("3. Rogue");
        while(true) {
          System.out.print("Choice : ");
          int type = scanner.nextInt();
          scanner.nextLine();
          if (type >= 1 && type <= 3) {
            return type;
          System.out.println("Look, enter a number between 1 and 3 isn't exactly rocket surgery! DO atleast try to get it right!");
    public class PlayersAvatarFactoryTest {
      public static void main(String args[]) {
        try {
          PlayersAvatarFactoryTest test = new PlayersAvatarFactoryTest();
          test.run();
        } catch (Exception e) {
          e.printStackTrace();
      private void run() {
        AvatarFactory avatarFactory = new PlayersAvatarFactory();
        System.out.println();
        System.out.println("==== PlayersAvatarFactoryTest ====");
        System.out.println("Welcome to my game!");
        Avatar player1 = avatarFactory.createAvatar();
        System.out.println();
        System.out.println("Player1: "+player1);
    }It's "just a bit" more OOified than your version... and I changed random stuff, so you basically can't cheat ;-)
    And look out for JSG's totally-over-the-top triple-introspective-reflective-self-crushing-coffeebean-abstract-factory solution, with cheese ;-)
    Cheers. Keith.
    Edited by: corlettk on 25/07/2009 13:38 ~~ Typo!
    Edited by: corlettk on 25/07/2009 13:39 ~~ I still can't believe the morons at sun made moron a proscribed word.

  • Need help with a guessing game

    Hi. hopefully, this is a really easy issue to resolve. I had to write a program that administers a guessing game, where the computer chooses a random number, and the user has to guess the number. If the user doesn't get it within 5 guesses, they lose and start all over with a new number. I have this all in a while loop (as per my instructions). My issue is that whenever the user enters 0, the program should quit with the users final score and so on. My program will not quit unless the 0 is entered on the last (fifth) guess. please help, it would be very appreciated. Here is my code:
    import java.util.Scanner;
      public class guessgame {
        public static void main(String[] args) {
          Scanner scanner = new Scanner (System.in);
            int randnum;        //random number generated by computer
            int userguess = 1;      //number the user guesses
            int userscore = 0;      //number of correct guesses by user
            int compscore = 0;      //number of times not guessed
            int guessnum = 0;       //number of guesses for one number
            int gamenum = 0;        //number of games played
        System.out.println ("I will choose a number between 1 and 10");
        System.out.println ("Try to find the number using as few guesses as possible");
        System.out.println ("After each guess i will tell you if you are high or low");
        System.out.println ("Guess a number (or 0 to quit)");
        while (userguess != 0) {
          randnum = 1 + (int)(Math.random() * 10); //generates random number
          gamenum ++;
          userguess = userguess;
            for (guessnum = 1; guessnum < 6 && userguess != randnum; guessnum ++) {
                userguess = scanner.nextInt();
                userguess = userguess;
               if (guessnum >= 5) {
                  System.out.println ("You did not guess my number!");
                                  } //closes if statement
               if (userguess == randnum) {
                 userscore ++;
                 System.out.println ("You guessed it! It took you " + guessnum + " tries.");
                 System.out.println ("If you want to play again, enter a guess");
                 System.out.println ("If you do not want to play again, enter 0");
                                        } //closes if statement
               else if (userguess < randnum)
                 System.out.println ("Your guess is too low");
               else if (userguess > randnum)
                 System.out.println ("Your guess is too high");
                                                          }//closes for loop
                              } //closes while loop
    compscore = gamenum - userscore;
            System.out.println ("Thanks for playing! You played " + gamenum + " games");
            System.out.println ("Out of those " + gamenum + " games, you won " + userscore + " times");
            System.out.println ("That means that I won " + compscore + " times"); 
    } //closes main
    } //ends guessgame class

    The problem with your program is that the while loop doesn't get checked. The condition of the while loop will only get checked each iteration, and not during one iteration. The time you are in your for-loop is still one iteration so it won't check if userguess is 0. see it liek this
    While: is userguess 0, no, do 1 iteration
    while-iteration-forloop: check 5 guesses, userguess can be anything even 0 while loop won't stop.
    end of for loop
    end of while-iteration
    new while iteration, is userguess 0?
    and so on.
    HTH,
    Lima

  • Help with saving FarmVille game data...

    Ok, I need a bit of help...
    I have an issue with saving data from a facebook game, FarmVille.
    On my old computer which was running Windows XP when playing FarmVille the game only ever used to reload when it was updated. If I quit the game then went back in and it appeared to be loading the content from some saved data as it would load straight away compared with the 5 minutes it took when ever the game was updated.
    I have now bought a new computer running Windows 7 and when I play FarmVille it now wants to reload from scratch each time I go into the game and it is sucking up my broadband usage really quick by doing this.
    I have been trying to play around with different settings to see if I can get flash player to save the data but nothing seems to work. I am now starting to think it may not be flash player that is the problem.
    If anyone knows how to fix this problem it would be greatly appreciated.
    Thanks.

    I am using IE9 but I do not have that setting set and I hardly ever delete all my history etc.
    I have also just tried playing on my partners apple which I dont know much about except that it is about 5 years old. Anyway the apple is doing the same thing that this new computer is doing... hmmm.

  • Need a little help with a trivia game

    Hey guys I was wondering if I could get some help. I'm taking a class at school for java programming and its my first class. And I have to do a final assignment, which is to make a java trivia game. I have all the parts coded already pretty sure. Now be forewarned that I'm not "that" great at programming.
    But the part that I'm stuck on and cant really get any help on is this: For the game I need to have a file with all the questions and answers, which is created already and works. The file writer has the question, choice 1, choice 2, choice 3, choice 4 and the answer written to it, in that order. We needed to implement a GUI and I coded that as a message label on top where the question will go, in the middle 4 radio buttons where the choices to the answer will go and on the bottom a next question, ok and quit button.
    My question is this: How do I pull the information from the file that was written to appear in the GUI, such as the question and the choices for the answers for the question? ANY and ALL help would be appreciated

    Read the information using a BufferedReader wrapped around a FileReader. Change your GUI using setText on the component you want to display the text.
    Edit: An example that does both things
    import java.io.*;
    import javax.swing.*;
    public class FileAndSwing {
       public static void main(String[] args) throws Exception {
          BufferedReader reader = new BufferedReader(
                new FileReader("FileAndSwing.java"));
          StringBuilder builder = new StringBuilder();
          for ( String line = null; (line = reader.readLine()) != null; ) {
             builder.append(line).append("\n");
          JFrame frame = new JFrame("FileAndSwing.java");
          frame.setSize(500, 500);
          JTextArea field = new JTextArea();
          frame.add(field);
          field.setText(builder.toString());
          frame.setVisible(true);
    }This is also kind of a Quine :-).
    Edited by: endasil on 15-Dec-2009 4:00 PM

  • Need help with Connect 4 game, IndexOutOfRangeException was unhandled

    Hi! I've been struggling with this for a while now, the issue is that as soon i move a game piece to the field i get this errorats "IndexOutOfRangeException was unhandled" and i don't know why since my intention with the code was to use for loops
    look through the 2D array thats based on two constants: BOARDSIZEx = 9 and BOARDSIZEy = 6. Instead of traditional 7*6 connect 4 grid i made it 9 squares wide due to having pieces on the side to drag and drop.
    Here's the code for my checkwin:
    public bool checkWin(Piece[,] pieceArray, bool movebool)
    bool found = false;
    //Horizontal
    for (int i = 0; i < BOARDSIZEx - 3; i++)
    for (int j = 0; j < BOARDSIZEy; j++)
    if ((pieceArray[i, j] != null)
    && (pieceArray[i, j] == pieceArray[i, j + 1])
    && (pieceArray[i, j] == pieceArray[i, j + 2])
    && (pieceArray[i, j] == pieceArray[i, j + 3]))
    if (pieceArray[i, j].IsStarter != movebool)
    found = true;
    goto Done; //interesting way of getting out of nested for loop
    //for more on goto: http://stackoverflow.com/questions/324831/breaking-out-of-a-nested-loop
    //Vertikal
    for (int i = 0; i < BOARDSIZEx; i++)
    for (int j = 0; j < BOARDSIZEy - 3; j++)
    if ((pieceArray[i, j] != null)
    && (pieceArray[i, j] == pieceArray[i + 1, j]) && (pieceArray[i, j] == pieceArray[i + 2, j])
    && (pieceArray[i, j] == pieceArray[i + 3, j]))
    if (pieceArray[i, j].IsStarter != movebool)
    found = true;
    goto Done; //interesting way of getting out of nested for loop
    //for more on goto: http://stackoverflow.com/questions/324831/breaking-out-of-a-nested-loop
    //Diagonal, Lower left to upper right
    for (int i = 0; i < BOARDSIZEx - 3; i++)
    for (int j = 0; j < BOARDSIZEy - 3; j++)
    if ((pieceArray[i, j] != null)
    && (pieceArray[i, j] == pieceArray[i + 1, j +1])
    && (pieceArray[i, j] == pieceArray[i + 2, j + 2])
    && (pieceArray[i, j] == pieceArray[i + 3, j + 3]))
    if (pieceArray[i, j].IsStarter != movebool)
    found = true;
    goto Done; //interesting way of getting out of nested for loop
    //for more on goto: http://stackoverflow.com/questions/324831/breaking-out-of-a-nested-loop
    //Diagonal, upper left to lower right
    for (int i = 0; i >= BOARDSIZEx; i--)
    for (int j = 0; j < BOARDSIZEy - 3; j++)
    if ((pieceArray[i, j] != null)
    && (pieceArray[i, j] == pieceArray[i - 1, j + 1])
    && (pieceArray[i, j] == pieceArray[i - 2, j + 2])
    && (pieceArray[i, j] == pieceArray[i - 3, j +3]))
    if (pieceArray[i, j].IsStarter != movebool)
    found = true;
    goto Done; //interesting way of getting out of nested for loop
    //for more on goto: http://stackoverflow.com/questions/324831/breaking-out-of-a-nested-loop
    Done:
    return !found;
    It's at the vertical check that the error occurs and also my checkwin doesnt seem to respond to the call in the game.cs code.
    //check for win
    bool moveBool = true; //returns yes or no depending on whether both players have moved their pieces
    if (move % 2 == 0) moveBool = false;
    bool win = rules.checkWin(pieceArray, moveBool);
    //The game is won!
    if (win)
    string winningPlayerName = player1.Name; //creating a new player instance, just for shortening the code below
    if (moveBool == false) winningPlayerName = player2.Name; //if it was player 2 who won, the name changes
    message = winningPlayerName + " has won the game!\n\n"; //The name of the player
    Board.PrintMove(message); //Print the message
    if (moveBool == true) player1.Score += 1; else player2.Score += 1; //update score for the players
    //The player's labels get their update texts (score)
    Board.UpdateLabels(player1, player2);
    //Here, depending on what one wants to do, the board is reset etc.
    else
    move++; //draw is updated
    And here's a picture on how it looks like at the moment.
    Thanks in Advance!
    Student at the University of Borås, Sweden

    for (int i = 0; i < BOARDSIZEx; i++) // If BOARDSizex is the number of elements in the first dimension...
    for (int j = 0; j < BOARDSIZEy - 3; j++)
    if ((pieceArray[i, j] != null)
    && (pieceArray[i, j] == pieceArray[i + 1, j]) && (pieceArray[i, j] == pieceArray[i + 2, j])
    && (pieceArray[i, j] == pieceArray[i + 3, j])) // Then [i + anything, j] will be out of range.
    You probably meant to add the one, two, or three to the j rather than the i.

  • Help with completing sentences game code

    Hi, I`m a bit stuck, I`m making a game where you have to complete the sentences by dragging the words which are generated dinamically to its right place over some boxes, everything works fine but if you pull the words out of the boxes one all are placed it crashes.
    Unfortunately this is someone elses code (another programmer who bailed on us in the middle of the proyect) although I manage to make it work with new words, making the draggable items undraggable one you place all 4 of them in the right boxes is totally unclear to me. I`ll appreciate any help I can get.
    Here`s all the code that this part of the movie is using:
    function aleatorio(min, max)
        var _loc2 = true;
        if (usados.length <= max - min)
            while (_loc2 != false)
                var _loc1 = Math.floor(Math.random() * (max - min + 1));
                _loc2 = repetido(_loc1);
            } // end while
            usados.push(_loc1);
            return (_loc1);
        else
            return (0);
        } // end else if
    } // End of the function
    function repetido(num)
        var _loc1 = false;
        for (i = 0; i < usados.length; i++)
            if (num == usados[i])
                _loc1 = true;
            } // end if
        } // end of for
        return (_loc1);
    } // End of the function
    stop ();
    var usados = new Array();
    _root.palabras_colocadas = 0;
    palabras_correctas = 0;
    listado_x = 700;
    listado_y = 400;
    origenx = 0;
    origeny = 0;
    estaba_en = -1;
    apagar = false;
    _root.frase = 2;
    var palabras = new Array("huts", "made", "mud", "straw");
    var correctas = new Array(false, false, false, false);
    var ocupadas = new Array(-1, -1, -1, -1);
    var my_font = new TextFormat();
    my_font.font = "Arial";
    my_font.color = 0;
    my_font.size = 30;
    palabras[i].embedFonts = true;
    my_font.bold = true;
    var i = 0;
    while (i < 4)
        this["cuadro" + i].gotoAndStop(1);
        this.createEmptyMovieClip("myClip" + i, this.getNextHighestDepth());
        largo = palabras[i].length * 22;
        this["myClip" + i].createTextField("label", 1, 0, 0, largo, 40);
        this["myClip" + i].label.text = palabras[i];
        this["myClip" + i].label.setTextFormat(my_font);
        this["myClip" + i].onPress = function ()
            temp = this._name;
            temp = Number(temp.charAt(6));
            if (ocupadas[0] == temp)
                apagar = true;
                estaba_en = 0;
            } // end if
            if (ocupadas[1] == temp)
                apagar = true;
                estaba_en = 1;
            } // end if
            if (ocupadas[2] == temp)
                apagar = true;
                estaba_en = 2;
            } // end if
            if (ocupadas[3] == temp)
                apagar = true;
                estaba_en = 3;
            } // end if
            if (!apagar)
                estaba_en = -1;
            } // end if
            origenx = this._x;
            origeny = this._y;
            trace ("estaba en " + estaba_en);
            this.startDrag();
        this["myClip" + i].onRelease = this["myClip" + i].onReleaseOutside = function ()
            this.stopDrag();
            cual = this._name;
            cual = Number(cual.charAt(6));
            drop = eval(this._droptarget);
            trace (drop);
            donde = String(drop);
            cuadro = donde.substr(8, 6);
            donde = Number(donde.charAt(14));
            trace (cual + " en " + donde + " " + cuadro);
            if (cuadro == "cuadro")
                if (ocupadas[donde] >= 0 && ocupadas[donde] <= 3 || donde == estaba_en)
                    apagar = false;
                    this._x = origenx;
                    this._y = origeny;
                else
                    if (!apagar)
                        ++_root.palabras_colocadas;
                    } // end if
                    tramo = eval("tramo" + (donde + 1) + "_mc");
                    tramo.gotoAndPlay(2);
                    if (_root.palabras_colocadas >= 4)
                        startbtn.start();
                        start_mc.gotoAndPlay(2);
                    else
                        palabra_ok.start();
                    } // end else if
                    largo = palabras[cual].length * 8.500000E+000;
                    drop.gotoAndStop(2);
                    this._y = drop._y - 22;
                    this._x = drop._x - largo;
                    ocupadas[donde] = cual;
                    if (apagar)
                        apaga = eval("cuadro" + estaba_en);
                        apaga.gotoAndStop(1);
                        tramo = eval("tramo" + (estaba_en + 1) + "_mc");
                        tramo.gotoAndPlay(6);
                        ocupadas[estaba_en] = -1;
                        correctas[estaba_en] = false;
                        apagar = false;
                        trace ("hay " + _root.palabras_colocadas + " palabras");
                        if (_root.palabras_colocadas == 3)
                            trace ("apaga sin ruido");
                            start_mc.gotoAndStop(1);
                        } // end if
                    } // end if
                    trace (ocupadas[0] + " " + ocupadas[1] + " " + ocupadas[2] + " " + ocupadas[3]);
                    if (cual == donde)
                        ++palabras_correctas;
                        correctas[donde] = true;
                    } // end if
                } // end if
            } // end else if
            if (cuadro == "myClip" || cuadro == "start_")
                palabra_error.start();
                this._x = origenx;
                this._y = origeny;
            } // end if
            if (cuadro == "fondo")
                if (apagar)
                    apaga = eval("cuadro" + estaba_en);
                    apaga.gotoAndStop(1);
                    tramo = eval("tramo" + (estaba_en + 1) + "_mc");
                    tramo.gotoAndPlay(6);
                    ocupadas[estaba_en] = -1;
                    correctas[estaba_en] = false;
                    --_root.palabras_colocadas;
                    apagar = false;
                    trace ("hay " + _root.palabras_colocadas + " palabras");
                    if (_root.palabras_colocadas == 3)
                        startbtn.start();
                        start_mc.gotoAndStop(1);
                    } // end if
                } // end if
            } // end if
        ++i;
    } // end while
    var ii = 0;
    while (ii < 4)
        var numeroNuevo = aleatorio(1, 4);
        trace (numeroNuevo);
        this["myClip" + numeroNuevo]._x = listado_x;
        this["myClip" + numeroNuevo]._y = listado_y + 40 * i;
        ++ii;
    } // end while

    that's too much code to go through line by line.  i'd recommend placing some trace() functions in strategic locations to narrow the location of the problem.

Maybe you are looking for

  • Captivate and Macbook Pro Retina display support. When?

    Hi there. Having just purchased a new MBP with retina display I was disappointed to find that Captivate 7 appeared not to support the display settings. It looks blocky and ill-defined compared to all the other programs, Powerpoint included. My web-se

  • Delete PSA request from ODS

    Hello Guys, I need to know how can I delete the PSA request number generated when request is activated This request is type:  ODSR_* I need to delete this request in order to activate again the data of my ODS reuqest ID, because a problem the activat

  • How do you rearrange photos in iPhoto's on iPad.

    In the help drop down in iPhoto it says that you can drag to rearrange photos.  I can't get this to work and I want to reorder my photos.

  • Creating simple Business Rules in BPEL process

    Hi, I have an environment consisting of SOA Suite 11g running on Weblogic Server. I'm using JDeveloper 11g for development. Scenario I have a BPEL process which starts off by polling a DB table and I then assign the input to a Recieve activity's Inpu

  • Exception while Parsing SELECT

    I'm working with NB 5.5.1, VWP 5.5.1, MySQL 5.0.45 and J/Connect 5.0.7. When I enter following SELECT in the SQL-Editor-Window of a RowSet: SELECT DISTINCT twibu_ergebnisse.spieltag   FROM twibu_ergebnisse     WHERE     twibu_ergebnisse.saisonnr = 45