Hi. I am a beginner still in Java. This is a 'chutes and ladders' game. It has 3 classes:
Players.java (contains main() )
Player.java (is basically the blue print for Player objects which will be players in the game, sets up variables for player location, number of turns (ie die rolls) taken)
Game.java (has a method called move() which contains the switch statements acting upon location which is basically essence of the game).
I am confused about how to organise the methods and objects. At the moment I am trying to call the move() method from main. I am trying to invoke it upon a player object (Player1). The problem is the move() method is part of the game class. And the Player1 object is derived fromt the Player class. I know this is wrong . But I dont know how better to do it. So, at the moment I am trying to use the move() method upon the Player1 object and passing it (location) as a parameter like this:
[code=Java]
if (count % 2 == 0)
{
Player1.Game.move(location);
System.out.println(Player1);
}
else
[\code]
I know you need to initialize an object from a class to start using methods from that class but I think this is a bit more complex because I am working with three classes. Anyway I look forward to hearing your advice and I will post all three classes now:
//Players.java import java.util.Random; public class Players { public static final int GOAL_NUMBER = 100; public static void main (String[] args) { int location, roll, turns, skipped, count; Random rand = new Random (); Player Player1 = new Player (1, 0, 0); Player Player2 = new Player (1, 0, 0); roll = rand.nextInt (6) + 1; location += roll; while (location != GOAL_NUMBER) { if (location < GOAL_NUMBER) { if (count % 2 == 0) { Player1.Game.move(location); System.out.println(Player1); } else { Player2.Game.move(location); System.out.println(Player2); } count++; } else location -= roll; } //end of while System.out.println ("Somebody has won"); } }
//Game.java public class Game { public int move (int location); { switch (location) { case 1: location = 38; System.out.println("You potted a plant! Climb to 38!"); break; case 5: location = 14; System.out.println("You made cookies! Climb to 14!"); break; case 9: location = 31; System.out.println("You mowed the yard! Climb to 31!"); break; case 15: location = 6; System.out.println("You skipped your homework. Slide down to 6!"); break; case 21: location = 42; System.out.println("You helped a puppy! Climb to 42!"); break; } return location; } }
//Player.java public class Player { int location, turns, skipped; public Player (int l, int t, int s) { l = location; t = turns; s = skipped; } public String toString () { String result; result = "Your Position: " + location; result += "\t Number of turns used: " + turns; result += "Dived over 100: " + skipped; return result; } }