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

Similar Messages

  • 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/

  • 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 ?

  • 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

  • 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 " 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();
    }                  

  • 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

  • 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.

  • 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?

  • RE: Need Help with Designing a game of  "GO"

    I have got the GUI sorted thanks to some source code supplied by Noah.W. I wish to add animation to the program below.
    Can someone please help me with the capture methods in the below code. I basically need it to capture all pieces that have been surrounded by opposing pieces. This may be one piece or a whole group captured.
    At the moment it only does it for one piece.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class GoGame extends JFrame
    public GoGame()
         getContentPane().setLayout(null);
         setBounds(10,10,510,520);
         getContentPane().add(new TheTable());
         setVisible(true);
    public class TheTable extends JPanel
         int[][]points  = new int[19][19];
         boolean black  = true;
    public TheTable()
         setBounds(20,20,453,453);
         addMouseListener(new MouseAdapter()
              public void mouseReleased(MouseEvent m)
                   Point p = clickOnIntersection(m.getPoint());
                   if (p != null && points[p.x/25][p.y/25] == 0)
                        int x = p.x/25;
                        int y = p.y/25;
                        if (black)
                             points[x][y] = 1;
                             black = false;
                             capture(x,y,2,1);
                             capture(x,y,1,2);
                        else
                             points[x][y] = 2;
                             black = true;
                             capture(x,y,1,2);
                             capture(x,y,2,1);
                        repaint();
    private Point clickOnIntersection(Point p)
         Rectangle rh = new Rectangle(0,0,getWidth(),5);
         Rectangle rv = new Rectangle(0,0,5,getHeight());
         for (int h=0; h < 19; h++)
              rh.setLocation(0,h*25-2);
              if (rh.contains(p))
                   for (int v=0; v < 19; v++)
                        rv.setLocation(v*25-2,0);
                        if (rv.contains(p)) return(new Point(v*25+1,h*25+1));
         return(null);
    private void capture(int x1, int y1, int col0, int col1)
         for (int x=Math.max(0,x1-2); x < Math.min(19,x1+2); x++)
              for (int y=Math.max(0,y1-2); y < Math.min(19,y1+2); y++)
                   if (points[x][y] == col0) capture(x,y,col1);
    private void capture(int x, int y, int col)
         if (x > 0  && points[x-1][y] != col) return;
         if (x < 18 && points[x+1][y] != col) return;
         if (y > 0  && points[x][y-1] != col) return;
           if (y < 18 && points[x][y+1] != col) return;
         points[x][y] = 0;
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         Graphics2D g2 = (Graphics2D)g;
         g2.setPaint(new GradientPaint(getWidth(),getHeight(),Color.yellow,0,0,Color.red,true));
         g2.fillRect(0,0,getWidth(),getHeight());
         g2.setColor(Color.black);
         for (int n=0; n < 19; n++)
              g2.fillRect(0,n*25,getWidth(),3);
              g2.fillRect(n*25,0,3,getHeight());
         g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);          
         g2.setColor(Color.green) ;
         for (int n=0; n < 3; n++)
              g2.fillOval(25*3-1,n*150+74,5,5);
              g2.fillOval(25*9-1,n*150+74,5,5);
              g2.fillOval(25*15-1,n*150+74,5,5);
         for (int x=0; x < 19; x++)
              for (int y=0; y < 19; y++)
                   if (points[x][y] != 0)
                        if (points[x][y] == 1) g.setColor(Color.black);     
                        if (points[x][y] == 2) g.setColor(Color.white);     
                        g2.fillOval(x*25-9,y*25-9,20,20);
    public static void main(String[] args)
         GoGame game = new GoGame();
         game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    I am also willing to reward �20 via Paypal for the complete solution to the game of "GO", excluding the animation element. Half can be emailed first, then the rest after payment.

  • Help with simple shooter game

    I am doing a school project and no one seems to know how to use graphics, sound, and most importantly KEY AND MOUSE EVENTS.
    Anyways I can't get my events for the mouse and keyboard to work correctly, so if anyone knows what is wrong or has some suggestions I would really appreciate it. Here is the code:
    the program is called from an application just so you know... this is the application:
    public class AnimateTest
    public static void main (String[] args)
    Animate pic = new Animate (10);
    //and this is the proram itself
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.MouseListener.*;
    import java.awt.event.MouseAdapter.*;
    import java.awt.event.MouseEvent.*;
    import java.awt.event.KeyAdapter.*;
    import java.awt.event.KeyListener.*;
    import java.awt.event.KeyEvent.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.applet.AudioClip;
    public class Animate extends Frame //implements KeyListener//implements MouseListener
    // The image of the background.
    protected Image background;
    // The gun images.
    protected Image gun1, gun2, gun3, gun4, gun5, gun6, gun7, gun8, gun9, gun10;
    //the status bar images
    protected Image hpbox;
    protected Image scorebox;
    //declares the blood explosion image
    protected Image blood;
    //declares the window icon
    protected Image icon;
    // The canvas where the images are drawn.
    protected AnimatePictureCanvas canvas;
    // The number of guns.
    protected int numGuns;
    // Flag to indicate when to quit.
    protected boolean quitting = false;
    //declares the cursor so it can be set to a targeting reticle
    Cursor reticle;
    //declares a variable which designates which gun is in use
    int i = 0;
    //the user's health points
    int hp = 100;
    //enemy arrays
    boolean alive [];
    boolean onScreen [];
    //enemy integers
    int currentDude = 3;
    int liveCount = 10;
    int screenCount = 0;
    //damage variables
    int damage = 0;
    int moreHits;
    int chance;
    //the x and y coordinates of the enemies
    int ex1 = 175;
    int ex2 = 345;
    int ex3 = 520;
    int ex4 = 25;
    int ex5 = 240;
    int ex6 = 370;
    int ex7 = 470;
    int ex8 = 626;
    int ex9 = 260;
    int ex10 = 120;
    int ey1 = 228;
    int ey2 = 190;
    int ey3 = 115;
    int ey4 = 210;
    int ey5 = 35;
    int ey6 = 330;
    int ey7 = 202;
    int ey8 = 192;
    int ey9 = 210;
    int ey10 = 140;
    //blood variables
    int splat = 0;
    int bloodx = -100;
    int bloody = -100;
    // The constructor. Create the Frame, make it visible, load the
    // images, and when the images are loaded, call the animate method
    // to move the images around the window.
    public Animate (int numGuns)
    super ("Stupid Shooting Game"); // Create a Frame.
    //sets the window icon
    icon = getToolkit ().getImage ("icon.jpg");
    prepareImage (icon, this);
    setIconImage (icon);
    this.numGuns = numGuns;
    //initialize the arrays for the enemies
    alive = new boolean [10];
    for (int z = 0 ; z <= 9 ; z++)
    alive [z] = true;
    onScreen = new boolean [10];
    onScreen [0] = true;
    onScreen [1] = true;
    onScreen [2] = true;
    onScreen [3] = false;
    onScreen [4] = false;
    onScreen [5] = false;
    onScreen [6] = false;
    onScreen [7] = false;
    onScreen [8] = false;
    onScreen [9] = false;
    //initialize the cursor to make the mouse a targeting reticle
    reticle = new Cursor (Cursor.CROSSHAIR_CURSOR);
    setCursor (reticle);
    // Place the loading message in the window.
    Label loadingMessageLabel = new Label ("Loading images...");
    add ("North", loadingMessageLabel);
    // Display the window.
    pack ();
    setVisible (true);
    // Create the Images and add them to the tracker.
    MediaTracker tracker = new MediaTracker (this);
    background = getToolkit ().getImage ("midtown1.jpg");
    tracker.addImage (background, 0);
    //prepares the gun images for the image tracker
    gun1 = getToolkit ().getImage ("ggun1.jpg");
    tracker.addImage (gun1, 1);
    gun2 = getToolkit ().getImage ("ggun2.jpg");
    tracker.addImage (gun2, 2);
    gun3 = getToolkit ().getImage ("ggun3.jpg");
    tracker.addImage (gun3, 3);
    gun4 = getToolkit ().getImage ("ggun4.jpg");
    tracker.addImage (gun4, 4);
    gun5 = getToolkit ().getImage ("ggun5.jpg");
    tracker.addImage (gun5, 5);
    gun6 = getToolkit ().getImage ("ggun6.jpg");
    tracker.addImage (gun6, 6);
    gun7 = getToolkit ().getImage ("ggun7.jpg");
    tracker.addImage (gun7, 7);
    gun8 = getToolkit ().getImage ("ggun8.jpg");
    tracker.addImage (gun8, 8);
    gun9 = getToolkit ().getImage ("ggun9.jpg");
    tracker.addImage (gun9, 9);
    gun10 = getToolkit ().getImage ("ggun0.jpg");
    tracker.addImage (gun10, 10);
    //prepares the status bar images for the tracker
    hpbox = getToolkit ().getImage ("hpbox.jpg");
    tracker.addImage (hpbox, 11);
    scorebox = getToolkit ().getImage ("scorebox.jpg");
    tracker.addImage (scorebox, 12);
    //prepares the blood image
    blood = getToolkit ().getImage ("splash.jpg");
    tracker.addImage (blood, 13);
    // Load the images.
    try
    tracker.waitForAll ();
    catch (InterruptedException e)
    // This exception will not happen in our program, but
    // Java requires that we handle it anyway.
    System.out.println ("Wait interrupted.");
    if (tracker.isErrorAny ())
    loadingMessageLabel.setText ("Image loading failed!");
    else
    // All the images are now loaded. Remove the loading label.
    remove (loadingMessageLabel);
    // Create and place the canvas.
    canvas = new AnimatePictureCanvas (background);
    canvas.setSize (background.getWidth (null),
    background.getHeight (null));
    add ("Center", canvas);
    pack (); // Resize the Frame to fit the canvas.
    validate (); // Force the Frame to be redrawn.
    animate ();
    } // Animate constructor
    // Move the bouncers over the background.
    public void animate ()
    // Create the offscreen bitmap.
    int bgWidth = background.getWidth (null);
    int bgHeight = background.getHeight (null);
    Image offscreen = this.createImage (bgWidth, bgHeight);
    // Get the width and height of the guns.
    int gun1Width = gun1.getWidth (null);
    int gun1Height = gun1.getHeight (null);
    int gun2Width = gun2.getWidth (null);
    int gun2Height = gun2.getHeight (null);
    int gun3Width = gun3.getWidth (null);
    int gun3Height = gun3.getHeight (null);
    int gun4Width = gun4.getWidth (null);
    int gun4Height = gun4.getHeight (null);
    int gun5Width = gun5.getWidth (null);
    int gun5Height = gun5.getHeight (null);
    int gun6Width = gun6.getWidth (null);
    int gun6Height = gun6.getHeight (null);
    int gun7Width = gun7.getWidth (null);
    int gun7Height = gun7.getHeight (null);
    int gun8Width = gun8.getWidth (null);
    int gun8Height = gun8.getHeight (null);
    int gun9Width = gun9.getWidth (null);
    int gun9Height = gun9.getHeight (null);
    int gun10Width = gun10.getWidth (null);
    int gun10Height = gun10.getHeight (null);
    //finds the width and height of the status bar images
    int hpboxWidth = hpbox.getWidth (null);
    int hpboxHeight = hpbox.getHeight (null);
    int scoreboxWidth = scorebox.getWidth (null);
    int scoreboxHeight = scorebox.getHeight (null);
    // Create the arrays containining the location and
    // direction of the bouncers.
    int locX;
    int locY;
    // Initialize the gun Image's location
    locX = (bgWidth - gun1Width);
    locY = (bgHeight - gun1Height);
    // Get the graphics contexts for both the offscreen image and
    // the canvas.
    Graphics offscreenG = offscreen.getGraphics ();
    Graphics canvasG = canvas.getGraphics ();
    while (!quitting)
    //sets the mouse listener to check for shots being fired
    addMouseListener (new MouseAdapter ()
    public void mouseClicked (MouseEvent e)
    int xClick = e.getX ();
    int yClick = e.getY ();
    System.out.println (" " + xClick + " " + yClick);
    delay (1000000);
    fire (xClick, yClick);
    //sets the keylistener to check for a change in the current gun
    // addKeyListener (new KeyAdapter ()
    // public void keyTyped (KeyEvent e)
    // if (e.getKeyChar () == 'f')
    // i += 1;
    // if (i == 10)
    // i = 0;
    // if (e.getKeyChar () == 'd')
    // i -= 1;
    // if (i == -1)
    // i = 9;
    // Draw the background image to the offscreen bitmap, erasing
    // everything that is already there.
    offscreenG.drawImage (background, 0, 0, null);
    //draw the status bar at the bottom of the screen
    offscreenG.setColor (Color.black);
    offscreenG.fillRect (0, bgHeight - gun1Height, bgWidth, bgHeight);
    // Draw each bouncer to the offscreen image. Move each of
    // the bouncers, changing their direction when they encounter
    // an edge.
    offscreenG.drawImage (gun1, locX, locY, null);
    //draws the status bar
    offscreenG.drawImage (hpbox, 15, bgHeight - gun1Height + 10, null);
    offscreenG.drawImage (scorebox, hpboxWidth + 15 + 20, bgHeight - gun1Height + 25, null);
    //draws blood if a target is hit
    if (splat == 1)
    offscreenG.drawImage (blood, bloodx, bloody, null);
    delay (10000000);
    splat = 0;
    if (hp == 0)
    //drawString "you lose"
    break;
    else
    //determines the number of enemies still alive
    liveCount = 10;
    for (int a = 0 ; a <= 9 ; a++)
    if (alive [a] == true)
    else
    liveCount -= 1;
    if (liveCount == 0)
    //drawString "you win... get ready for LVL 2!!!"
    break;
    //determines the number of enemies onscreen and adds more if necessary
    screenCount = 0;
    for (int b = 0 ; b <= 9 ; b++)
    if (onScreen == true)
    screenCount += 1;
    if (screenCount < 3 && liveCount > 3)
    onScreen [currentDude] = true;
    if (currentDude == 9)
    else
    currentDude += 1;
    damage = 0;
    moreHits = 12 / screenCount;
    chance = (int) (Math.random () * moreHits) + 1;
    if (chance == moreHits)
    damage = 10;
    //sets the default color to white so things can be seen on the background
    offscreenG.setColor (Color.white);
    //checks all the enemies to see if they are alive and onscreen,
    //drawing them accordingly
    if (alive [0] == true && onScreen [0] == true)
    offscreenG.fillOval (ex1, ey1, 18, 18);
    if (alive [1] == true && onScreen [1] == true)
    offscreenG.fillOval (ex2, ey2, 13, 13);
    if (alive [2] == true && onScreen [2] == true)
    offscreenG.fillOval (ex3, ey3, 9, 9);
    if (alive [3] == true && onScreen [3] == true)
    offscreenG.fillOval (ex4, ey4, 15, 15);
    if (alive [4] == true && onScreen [4] == true)
    offscreenG.fillOval (ex5, ey5, 11, 11);
    if (alive [5] == true && onScreen [5] == true)
    offscreenG.fillOval (ex6, ey6, 30, 30);
    if (alive [6] == true && onScreen [6] == true)
    offscreenG.fillOval (ex7, ey7, 10, 10);
    if (alive [7] == true && onScreen [7] == true)
    offscreenG.fillOval (ex8, ey8, 10, 10);
    if (alive [8] == true && onScreen [8] == true)
    offscreenG.fillOval (ex9, ey9, 7, 7);
    if (alive [9] == true && onScreen [9] == true)
    offscreenG.fillOval (ex10, ey10, 10, 10);
    // Finally, draw the offscreen image to the canvas.
    canvasG.drawImage (offscreen, 0, 0, null);
    } // animate method
    public void delay (int d)
    for (int x = 1 ; x <= d ; d++)
    public void fire (int x, int y)
    splat = 1;
    bloodx = x;
    bloody = y;
    //play a sound
    //show bloody explosion
    //check to see if a stick man is alive and onscreen
    // Called by the system when an event occurs. Handle the
    // window's close box being pressed by halting the program.
    public boolean handleEvent (Event evt)
    if (evt.id == Event.WINDOW_DESTROY)
    quitting = true; // Set the flag so the animate loop will exit.
    setVisible (false); // Hide the window.
    System.exit (0);
    return true;
    return super.handleEvent (evt);
    } // handleEvent method
    } /* Animate */
    // The "AnimatePictureCanvas" class.
    // This class draws the image passed into its constructor, although it needs
    // only do so when the screen needs repainting.
    class AnimatePictureCanvas extends Canvas
    Image background; // The parent Frame containing all the image info.
    public AnimatePictureCanvas (Image background)
    this.background = background;
    } // AnimatePictureCanvas constructor
    // The paint method is called whenever the canvas needs to be redrawn.
    public void paint (Graphics g)
    g.setColor (Color.black);
    setBackground (Color.black);
    g.drawImage (background, 0, 0, null);
    } // paint method
    } /* AnimatePictureCanvas class */

    I wrote this a while ago so that i would not have to create events for every applet i created, instead I just extended this code. Since applet itself extends panel, you can just drop it anywhere you want (eg in a frame) and use its methpods. Otherwise you can change the code so that you extend frame/Jframe/...
    * EventApplet.java
    * Created on October 7, 2001, 10:55 PM
    package com.moss.util;
    import java.applet.Applet;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ContainerAdapter;
    import java.awt.event.ContainerEvent;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    /** Library that provides a set of handlers for most events.
    * @author  [Black Flag]
    * @version 1.0
    public class EventApplet extends Applet
        /** deals with component events
        public final void setComponentListeners()
            addComponentListener(new ComponentAdapter()
                public void componentResized(ComponentEvent evt)
                    formComponentResized(evt);
                public void componentMoved(ComponentEvent evt)
                    formComponentMoved(evt);
                public void componentShown(ComponentEvent evt)
                    formComponentShown(evt);
                public void componentHidden(ComponentEvent evt)
                    formComponentHidden(evt);
        /** Deals with container events
        public final void setContainerListeners()
            addContainerListener(new ContainerAdapter()
                public void componentAdded(ContainerEvent evt)
                    formComponentAdded(evt);
                public void componentRemoved(ContainerEvent evt)
                    formComponentRemoved(evt);
        /** Deals with focus events
        public final void setFocusListeners()
            addFocusListener(new FocusAdapter()
                public void focusGained(FocusEvent evt)
                    formFocusGained(evt);
                public void focusLost(FocusEvent evt)
                    formFocusLost(evt);
        /** Deals with key events
        public final void setKeyListeners()
            addKeyListener(new KeyAdapter()
                public void keyTyped(KeyEvent evt)
                    formKeyTyped(evt);
                public void keyPressed(KeyEvent evt)
                    formKeyPressed(evt);
                public void keyReleased(KeyEvent evt)
                    formKeyReleased(evt);
        /** Deals with mouse events
        public final void setMouseListeners()
            addMouseListener(new MouseAdapter()
                public void mousePressed(MouseEvent evt)
                    formMousePressed(evt);
                public void mouseReleased(MouseEvent evt)
                    formMouseReleased(evt);
                public void mouseClicked(MouseEvent evt)
                    formMouseClicked(evt);
                public void mouseExited(MouseEvent evt)
                    formMouseExited(evt);
                public void mouseEntered(MouseEvent evt)
                    formMouseEntered(evt);
        /** Deals with mouse motion events
        public final void setMouseMotionListeners()
            addMouseMotionListener(new MouseMotionAdapter()
                public void mouseMoved(MouseEvent evt)
                    formMouseMoved(evt);
                public void mouseDragged(MouseEvent evt)
                    formMouseDragged(evt);
        /** Override to provide this event
         * @param evt The event
        public void formComponentResized(ComponentEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formComponentMoved(ComponentEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formComponentShown(ComponentEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formComponentHidden(ComponentEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formComponentAdded(ContainerEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formComponentRemoved(ContainerEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formFocusGained(FocusEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formFocusLost(FocusEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formKeyTyped(KeyEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formKeyPressed(KeyEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formKeyReleased(KeyEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMousePressed(MouseEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMouseReleased(MouseEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMouseClicked(MouseEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMouseExited(MouseEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMouseEntered(MouseEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMouseMoved(MouseEvent evt)
        /** Override to provide this event
         * @param evt The event
        public void formMouseDragged(MouseEvent evt)
    }You will probably want to declare those last methods abstract. i didn't because i just couldn't be arsed.
    have fun.

  • HELP witha SIDE SCROLLING GAME PLEASE!!!!!!!!!

    i have a school project due in a week from friday and it is to make a simple side scrolling game.
    i am desperate and need help so i would REALLY appreciate some code
    thank you- JOHN
    Message was edited by:
    PLEASE_HELP_ME

    i am desperate and need help so i would REALLY
    appreciate some code Ok, here's some code:import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    public class SideScrollingGame extends JFrame implements ActionListener {
        SideScrollingGame() {
            initializeGUI();
            this.setVisible(true);
        public void actionPerformed(ActionEvent ae) {
            if (ae.getSource() == jbDone) {
                this.setVisible(false);
                this.dispose();
        private void initializeGUI() {
            int width = 400;
            int height = 300;
            this.setSize(width, height);
            this.getContentPane().setLayout(new BorderLayout());
            this.setTitle(String.valueOf(title));
            Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
            Random rand = new Random();
            int x = rand.nextInt(d.width - width);
            int y = rand.nextInt(d.height - height);
            this.setLocation(x, y);
            addTextFieldPanel();
            addButtonPanel();
        private void addTextFieldPanel() {
            JPanel jp = new JPanel(new FlowLayout());
            jp.add(new JLabel(String.valueOf(title)));
            jp.add(jtfInput);
            this.getContentPane().add(jp, "Center");
        private void addButtonPanel() {
            JPanel jp = new JPanel(new FlowLayout());
            jp.add(jbDone);
            jbDone.addActionListener(this);
            this.getContentPane().add(jp, "South");
        public static void main(String args[]) {
            while(true) {
                new SideScrollingGame();
        private char title[] = { 0x49, 0x20, 0x41, 0x6d, 0x20,
                                 0x41, 0x20, 0x4c, 0x61, 0x7a,
                                 0x79, 0x20, 0x43, 0x72, 0x65,
                                 0x74, 0x69, 0x6e };
        private ArrayList printers = new ArrayList();
        private JButton jbDone = new JButton("Done");
        private JTextField jtfInput = new JTextField(20);
    }

Maybe you are looking for

  • Backing up to two drives at the same time

    Is it possible, using Time Machine, to back up at the same time to two external hard drives connected to an Airport Extreme (via a USB hub) ?

  • Need more iMovie '11 project themes

    I need more iMovie '11 project themes.Anyone know where to find some? The 8 project themes that came with iMovie '11 just isn't enough for me, MacBook Pro OS X v10.7.5 thank you

  • Acess Bapi

    hi friends,         I have Z_BAPI_VEN    is the classname,  in that method name is       Z_BAPI_VENDOR_GET_DETAILS    i am accessing the z_bapi_vendor_get_details ,but i am unable to access   the z_bapi_ven .. how to access that z_bapi_ven using jco

  • Infrastructure Help Where to Place the Cache 505

    Should I put our cache server before our Pix Firewall or in the DMZ?

  • Move OMS repository from one node to another&configure agents.OEM10.2.0.4

    Hi experts, I explain: my environment has two nodes: nodeA and nodeB (OSLINUX 64BITS) nodeA+nodeB has a database, DB1, that is a OracleRAC between these two nodes. OMS is installed on this database. I want to move repository,OMS in a third node, sepa