Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 19 of 19

Thread: game Snake in the applet, how to execute methods from different classes?

  1. #1
    Junior Member
    Join Date
    Feb 2014
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default game Snake in the applet, how to execute methods from different classes?

    I'm simply looking for any guidance for resolution to a project i was given. Any help is greatly appreciated. please let me know if i need to show StartingClass and Snake classes for more info.

    this is a java applet allows a user to play Snake game, it was created with 4 different classes in the package exam1 : StartingClass, GameException, Snake, Point.
    The driver class for the applet is named "StartingClass" and contians a series of strings and default values.

    For this project i need to review the code and make the following adjustments:

    1. Adjust the Title of the Applet so it is named "Tiger Snake" the current name is "Snakes Game" - DONE in StartingClass
    2. Create a class named {Netid}A06 in the default package. - DONE
    3. Create an instance of "exam1.Snake", starting at position 200, 200 on a board that is 800 by 600 - DONE
    4. Execute the Snake.move() method 10 times. - Need guidance on this step
    5. Execute the Snake.getScore() method and print the following to screen. "Score1: {SCORE}\n" - Need guidance on this step
    6. Create a second instance of snake using the same parameters. - DONE
    7. Read 30 integers from console using a Scanner's nextInt method. - should be similar to as step 5
    8. If a 1 is entered call the snake moveLeft method - Need guidance on this step
    If a 2 is entered call the snake moveRight method
    If a 3 is entered call the snake moveDown method
    If a 4 is entered call the snake moveUp method
    In each loop iteration execute the Snake.move method - Need guidance on this step
    9. At the end of the loop execute the Snake.getScore() method and print the following to screen. "Score2: {SCORE}\n"
    10. Adjust the default difficulty by setting it to 5; - DONE
    11. Adjust the instructions so they explain that pressing the number keys adjusts the difficulty. - Need guidance on this step

    import exam1.Snake;
    import java.util. Scanner;
     
    public class NetIdA06 { // 2. Create a class named {Netid}A06 in the default package
    				public static void main(String[] args) {
     
    			Scanner input = new Scanner(System.in); {
     
    			Snake mySnake1 = new Snake(200, 200, 800, 600); // 3. Create an instance of "exam1.Snake"
     
    			Snake mySnake2 = new Snake(200, 200, 800, 600); // 6. Create a second instance of snake using the same parameters.
    		} 
    }
     }

    I did not see any examples in the book, watched youtube videos and went through a numerous instructions and still not getting how to call for methods from different classes.


  2. #2
    Member
    Join Date
    Feb 2014
    Location
    India
    Posts
    47
    My Mood
    Bored
    Thanks
    0
    Thanked 7 Times in 7 Posts

    Default Re: game Snake in the applet, how to execute methods from different classes?

    You need to create an object of the class in which your method to be called is present.
    Then you need to call the method using that object.
    e.g Class obj1=new Class();
    obj1.method();
    Does this help resolving your problem?

  3. #3
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: game Snake in the applet, how to execute methods from different classes?

    You've asked a lot of questions - very thoroughly - so don't be surprised if you aren't overwhelmed with detailed responses. All who visit and contribute to these forums are volunteers, and most pass through fairly quickly, spreading the wealth and sharing their time in small bits. A topic as large as yours may have to wait for the weekend or a less busy person to happen by. Be patient. Plus, each of your areas builds on the first, so they really need to be taken one at a time.

    In that light, I recommend that you break your topic up into smaller bite-sized pieces. It won't require a new thread, but continue this one with a focus on each of your "Need Guidance" areas, one at a time. For example, take the first one, "Execute the Snake.move() method 10 times." That looks like a loop to me. I think that's where ankurt was headed: create an instance of Snake, perhaps 'snake', and then call the move() method on that instance, snake.move(), in a loop that executes 10 times. Code that, come back and post that code if you need help. If you don't need help with it, move to the next "Need Guidance" area.

    You'll get a more helpful response to each area if you show what you've done, describe what specific help you need with what you've done, posting the code and any errors you've gotten, and by asking specific questions. If we need to see the program's bad behavior to understand the problem, please post enough code for us to duplicate the problem, not pictures or screenshots unless absolutely necessary.

    Good luck!

  4. #4
    Junior Member
    Join Date
    Feb 2014
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: game Snake in the applet, how to execute methods from different classes?

    "You need to create an object of the class in which your method to be called is present."

    i thought that i have created an object with parameters of 200, 200, 800, 600, am i wrong?
    Snake Snake1 = new Snake(200, 200, 800, 600);

    "Then you need to call the method using that object."

    when i call the method Snake1.move() it gives me - "Unhandled exception type Game Exception" message
    Snake1.move();


    --- Update ---

    I'm going to break this thread by points.

    3. Create an instance of "exam1.Snake", starting at position 200, 200 on a board that is 800 by 600

    did i create an instance of "exam1.Snake" with a code below correctly?
    if not, then i will try modify it.
    Snake Snake1 = new Snake(200, 200, 800, 600); // create an instance of exam1.Snake
    why did i create an object with name "Snake1" - cause on step 6. i will need to create a second instance which will call "Snake2".
    please correct my thinking process if i'm wrong.


    Going to the next step of:
    4. Execute the Snake.move() method 10 times. - Need guidance on this step

    "Unhandled exception type Game Exception" message comes up when i do the following code.
    Snake1.move();
    in my understanding i have to create a loop that will execute "Snake.move" 10 times in order for this message to go away.


    I'm posting the Snake.java class to see the picture of what i'm trying to achieve:

    package exam1;
     
    import java.util.ArrayList;
    import java.util.List;
     
    /** 
     * Snake represents a snake in the game, the starting class controls the snake but we could just as easily write a console               * app or an web application
     */
     
    public class Snake {
     
     
    	// This represents the direction the snake is moving
    	enum Direction { left, right, up, down }
     
     
    	// How fast the game will play, larger number slower game
    	private int difficulty = 5; // Large the number slower the game
     
    	// The current score
    	long score = 0;
     
    	// The head of the snake
    	Point currentPoint;
     
    	// The tail of the snake
    	List<Point> points = new ArrayList<Point>();
     
    	// Size of the playing board
    	int xs, ys;
     
    	/**
    	 * Initialize the snake, x is the starting X, y is the starting Y.
    	 * , xs and ys represent the size of the board
    	 * @param x
    	 * @param y
    	 * @param xs
    	 * @param ys
    	 */
    	public Snake( int x, int y, int xs, int ys ) {
    		this.xs = xs;
    		this.ys = ys;
    		currentPoint = new Point( x, y);
    	}
     
    	/**
    	 * Returns the points of the snake (minus the head)
    	 */
    	public List<Point> getPoints() {
     
    		return points;
    	}
     
    	/**
    	 * The size of the snake including the head
    	 * @return
    	 */
    	public int getLength() {
    		return points.size()+1;
    	}
     
    	/**
    	 * Set the snake to move left
    	 * @throws GameException
    	 */
    	public void moveLeft() throws GameException {
    		currentDirection = Direction.left;	
    	}
     
    	/**
    	 * Set the snake to move right
    	 * @throws GameException
    	 */
    	public void moveRight() throws GameException {
    		currentDirection = Direction.right;
    	}
     
    	/**
    	 * Set the snake to move down
    	 * @throws GameException
    	 */
    	public void moveDown() throws GameException {
    		currentDirection = Direction.down;
    	}
     
    	/**
    	 * Set the snake to move up
    	 * @throws GameException
    	 */
    	public void moveUp() throws GameException {
    		currentDirection = Direction.up;
    	}
     
    	// Default direction is right
    	Direction currentDirection = Direction.right;
     
    	/**
    	 * Execute a move in the game
    	 * @throws GameException
    	 */
     
    	public void move( ) throws GameException {
    		int gap = 10;
    		Point p = null;
    		if( currentDirection.equals(Direction.down)) {
    			p = new Point(currentPoint.getX(), currentPoint.getY()+gap);		
    		} else if( currentDirection.equals(Direction.up) ) {
    			p = new Point(currentPoint.getX(), currentPoint.getY()-gap);				
    		} else if( currentDirection.equals(Direction.left) ) {
    			p = new Point(currentPoint.getX()-gap, currentPoint.getY());
    		} else if( currentDirection.equals(Direction.right) ) {
    			p = new Point(currentPoint.getX()+gap, currentPoint.getY());	
    		} 
    		score++;
    		if( p != null && ( score % difficulty ) == 0  ) {
    			addPoint( p );
    		}
    	}
     
    	/**
    	 * Set the point and throw gameover if needed.
    	 * @param p
    	 * @throws GameException
    	 */
    	private void addPoint( Point p ) throws GameException {
     
    		if( currentPoint.equals(p) ) {
    			return;
    		} else {
    			for( int i = 0; i < points.size(); i++ ) {
    				if( points.get(i).equals( p ) ) { 
    					throw( new GameException( "Game over!" ) );
    				}
     
     
    			}
     
    			if( p.getX() > ys || p.getX() < 0 || p.getY() > ys || p.getY() < 0 ) {
    				throw( new GameException( "Game over!, exceeded dimensions" ) );
     
    			}
     
    			points.add( currentPoint );
    			currentPoint = p;	
     
    		}
     
    	}
     
    	public void valid( Point nextPoint ) {
     
    	}
     
    	/**
    	 * Return the snakes score
    	 * @return
    	 */
    	public long getScore() {
    		return score;
    	}
     
    	public int getDifficulty() {
    		return difficulty;
    	}
     
    	public void setDifficulty( int difficulty ) {
    		this.difficulty = difficulty;
    	}
     
     
    	public static int getDefaultDifficulty() {
    		return StartingClass.getDefaultDifficulty();
    	}
     
    	public static String getInstructions() {
    		return StartingClass.getInstructions();
    	}
     
    	public static String getTitle() {
    		return StartingClass.getTitle();
    	}
    }


    --- Update ---

    not sure if this is the way to go, but here it is:
    steps: 3, 4 and 5

    Snake Snake1 = new Snake(200, 200, 800, 600); 	// created first instance of exam1.Snake
    Snake1.move();{ 				//  message persists  "Unhandled exception type Game Exception"
     
    	for(int gap = 0; gap < 10; gap++); // loop to run "move" method 10 times
    		}
    Snake1.getScore();{ 			// executing method "Snake.getScore"
     
    	System.out.print("score1 : {SCORE}\n"); // print out on the screen
    		}

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: game Snake in the applet, how to execute methods from different classes?

    "Unhandled exception type GameException
    See the tutorial on exceptions and try{}catch blocks: Lesson: Exceptions (The Java™ Tutorials > Essential Classes)
    If you don't understand my answer, don't ignore it, ask a question.

  6. #6
    Junior Member
    Join Date
    Feb 2014
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: game Snake in the applet, how to execute methods from different classes?

    so far this is my code in my class for steps 3, 4 and 5.

     import exam1.GameException;
    import exam1.Snake;
     
    import java.util. Scanner;
     
    public class MyclassA06 {	 // 2. Create a class named {Netid}A06 in the default package
    	
    	public static void main(String[] args) throws GameException{
     
    	Scanner input = new Scanner(System.in); {
     
    	Snake Snake1 = new Snake(200, 200, 800, 600); 	 {// created instance of exam1.Snake
     
    	Snake1.move(); 	// executing method Snake.move
     
    	for(int gap = 10; gap < 21; gap++);	//	  System.out.println();
    		}
    	Snake1.getScore();{ 		// executing method Snake.getScore
     
    	System.out.print("score1: {SCORE} \n" );		 // print out on the screen
    		}
    		input.close();
    		}
    	}
    }

    Please let me know what i'm doing wrong here, cause i'm getting errors below:

    Starting snake 600 800
    exam1.GameException: Game over: Game over!
    at exam1.Snake.addPoint(Snake.java:136)
    at exam1.Snake.move(Snake.java:120)
    at exam1.StartingClass.run(StartingClass.java:198)
    at java.lang.Thread.run(Unknown Source)

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: game Snake in the applet, how to execute methods from different classes?

    exam1.GameException: Game over: Game over!
    at exam1.Snake.addPoint(Snake.java:136)
    at exam1.Snake.move(Snake.java:120)
    The addPoint() method (called from line 120) is throwing a GameException at line 136. Look at the code before line 136 to see why the code executes the throw statement. If needed, add some println() statements that print out the the values of all the variables the code uses to make its decision.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Junior Member
    Join Date
    Feb 2014
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: game Snake in the applet, how to execute methods from different classes?

    Norm,

    Thank you for your reply, unfortunately i have no idea what i'm looking at these lines.

    any other guidance?

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: game Snake in the applet, how to execute methods from different classes?

    What was printed out when you added the println() statements to print the values of the variables used to determine if the code should throw the exception.
    For example: Print out the value of p and of points. They are used in this:
    	if( points.get(i).equals( p ) ) {
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Junior Member
    Join Date
    Feb 2014
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: game Snake in the applet, how to execute methods from different classes?

    this is the print output from line 120

    this is the point p - :exam1.Point@64b28abf

     if( p != null && ( score % difficulty ) == 0  )	{
    		addPoint( p );
    		System.out.println ("this is the point p - :" +p);
    		}

    for line 136 i could not figure out how to print the output, thou here is the code

    private void addPoint( Point p ) throws GameException {
     
    	if( currentPoint.equals(p) ) {
    		return;
    	} else {
    		for( int i = 0; i < points.size(); i++ ) {
    			if( points.get(i).equals( p ) ) { 
    				throw( new GameException( "Game over!" ) ); // THIS IS THE LINE 136
    				}
    			}
     
    			if( p.getX() > ys || p.getX() < 0 || p.getY() > ys || p.getY() < 0 ) {
    				throw( new GameException( "Game over!, exceeded dimensions" ) );
     
    			}
     
    			points.add( currentPoint );
    			currentPoint = p;	
     
    		}
     
    	}


    --- Update ---

    if i understood you correctly this is a value of p:
    if i'm not mistaken this is a value of p = exam1.Point@447ecd43

    } else if( currentDirection.equals(Direction.right) ) {
    			p = new Point(currentPoint.getX()+gap, currentPoint.getY());	
    		} 
    		System.out.println("if i'm not mistaken this is a value of p = " +p);
    		score++;

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: game Snake in the applet, how to execute methods from different classes?

    You should ask the author of the code why it throws an exception on line 136. The code is VERY POORLY commented with explanations on why it is doing what it does.

    if( points.get(i).equals( p ) ) {
    When the above is true, the exception is thrown.

    exam1.Point@64b28abf
    That is the default String returned by the Object class's toString() method.
    The Point class needs a toString() method that returns a String with its contents for debugging. With a proper toString() method the printout could be:
    x=300, y=234
    If you don't understand my answer, don't ignore it, ask a question.

  12. #12
    Junior Member
    Join Date
    Feb 2014
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: game Snake in the applet, how to execute methods from different classes?

    I have a separate Point.java class in the same package, maybe it would be of help

     
    package exam1;
     
    /**
     * Just a simple object that represents a point in the game
     * 
     * 
     *
     */
    public class Point {
    	private int x;
    	private int y;
     
     
    	public Point( int x, int y) {
    		this.x=x;
    		this.y=y;
    	}
    	public int getX() {
    		return x;
    	}
    	public void setX(int x) {
    		this.x = x;
    	}
    	public int getY() {
    		return y;
    	}
    	public void setY(int y) {
    		this.y = y;
    	}
     
    	public boolean equals( Point p ) {
    		return p.getX() == this.getX() && p.getY() == this.getY();
    	}
     
    }

  13. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: game Snake in the applet, how to execute methods from different classes?

    For debugging, add a toString() method to the Point class:
    @override
    public String toString() { 
      return "x=" + x + ", y="+y;
    }
    Then when a Point is printed, the output will be like: x=3, y=4;
    If you don't understand my answer, don't ignore it, ask a question.

  14. #14
    Junior Member
    Join Date
    Feb 2014
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: game Snake in the applet, how to execute methods from different classes?

    yes, output is

    value of Point p = x=140, y=140

    and

    this is the point addPoint p= x=130, y=140

  15. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: game Snake in the applet, how to execute methods from different classes?

    What two points are those? What do they have to do with the code on line 136?
    Those points are not equal. If those are the two points being compared in line 136, the if condition should be false because they are not equal?
    Did you print out the contents of the variable: points? It should show the values of all the points in the ArrayList.
    If you don't understand my answer, don't ignore it, ask a question.

  16. #16
    Junior Member
    Join Date
    Feb 2014
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: game Snake in the applet, how to execute methods from different classes?

    when i execute the StartingClass.java or Snake.java i have a game Snake. when the head of the Snake hits its body then i have an output on Console with error on line 136:

    x= number
    y= number
    these two points are printed from line 120.

    but when the head of the Snake goes out of designated area 800x600, then i have an error on line 144 with "x" and "y" numbers.

    is it possible that it should be the way it is when Game is over? and throw the exception.

    sorry for not giving you what you are asking, it is very hard for me to understand what this assignment is referring to.


    points when Snake's head smashes into its body:
    Starting snake 600 800
    this is the point addPoint p= x=110, y=100
    this is the point addPoint p= x=120, y=100
    this is the point addPoint p= x=130, y=100
    this is the point addPoint p= x=130, y=110
    this is the point addPoint p= x=130, y=120
    this is the point addPoint p= x=130, y=130
    this is the point addPoint p= x=120, y=130
    this is the point addPoint p= x=110, y=130
    this is the point addPoint p= x=110, y=120
    this is the point addPoint p= x=110, y=110
    exam1.GameException: Game over: Game over!
    at exam1.Snake.addPoint(Snake.java:136)
    at exam1.Snake.move(Snake.java:120)
    at exam1.StartingClass.run(StartingClass.java:198)
    at java.lang.Thread.run(Unknown Source)

  17. #17
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: game Snake in the applet, how to execute methods from different classes?

    What is shown when the points variable is printed?

    Move the println()s to just before the throw new GameException() statement so you can see what point was the problem. You need to see what Point is causing the problem.

    the way it is when Game is over? and throw the exception.
    Yes. The exception is thrown when the game is over. So the exception is correct.
    If you don't understand my answer, don't ignore it, ask a question.

  18. #18
    Junior Member
    Join Date
    Feb 2014
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: game Snake in the applet, how to execute methods from different classes?

    i tried different points, and did not see anything out of ordinary.

    should i println() in other classes as well?
    could you tell me what i'm i looking for in the output?

    I'm not sure if i need to concentrate on fixing these issues. but i appreciate your help very much.

  19. #19
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: game Snake in the applet, how to execute methods from different classes?

    What issues are there when the program is executed now?
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Snake Game
    By sakonpure6 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: September 23rd, 2013, 03:48 AM
  2. Help with Snake Game Java Code: It's Impossible to Lose the Game
    By haruspex_icis in forum What's Wrong With My Code?
    Replies: 20
    Last Post: December 17th, 2012, 12:21 PM
  3. [SOLVED] Help with the Snake in a Snake Game
    By godlynom in forum What's Wrong With My Code?
    Replies: 20
    Last Post: September 27th, 2012, 06:41 PM
  4. Replies: 6
    Last Post: February 24th, 2012, 09:45 PM
  5. arraylists to store coordinates for a snake applet
    By finalfantasyfreak15 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: February 19th, 2011, 10:21 PM