Trying to solve a Simple RPG game - java

I'm trying to solve a task that's a bit too much for me. The idea is to have a simple RPG game with the parent class (AllPlayers) and a subclass PlayerOne. I'm struggling with the calling of the player profession and his inventory system. I need to print how many coins the player has in its pocket, too.
MAIN:
import java.util.Scanner;
public class Main {
public static Scanner scanner = new Scanner(System.in);
public static String username;
public static PlayerOne player;
public static void main(String[] args) {
System.out.println("Choose your name: ");
username = scanner.nextLine();
System.out.println("Choose your profession: \n" +
"Press 1 for a knight class\n" +
"Press 1 for a rider class\n" +
"Press 1 for a mage class");
player = new PlayerOne(username);
player.displayPlayerOne();
player.displayPlayerInventory();
player.displayPocketCoins();
player.displayPlayerProfession();
}
}
As you can see, I set the getters and setters but that's the farthest I have gone so far. Can you provide me with some clues on how to
call the profession in the main?
call the inventory in the main?
I guess I'll figure out how to call coins in the main later, it will be quite the same as with profession and inventory.
Thank you!
AllPlayers (SUPERCLASS)
public class AllPlayers {
protected String name;
private int level;
private int health;
private int damage;
public AllPlayers(String name, int level, int health, int damage) {
this.name = name;
this.level = level;
this.health = health;
this.damage = damage;
}
}
And here is the player class:
public class PlayerOne extends AllPlayers{
private String [] inventory;
private int coins;
private String [] professions;
public PlayerOne(String name) {
super(name, 1, 20,5);
this.professions = getProfessions();
}
public void setProfessions(String[] professions) {
this.professions = professions;
}
public String[] getProfessions() {
return this.professions;
}
public void setCoins() {
this.coins = coins;
}
public int getCoins() {
return coins;
}
public void setInventory() {
this.inventory = inventory;
}
public String[] getInventory() {
return inventory;
}
public void displayPlayerOne() {
System.out.println("Your name is " + super.name);
}
public void displayPlayerInventory() {
inventory[0] = "knife";
inventory[1] = "sword";
inventory[2] = "spear";
inventory[3] = "potion";
}
public void displayPocketCoins() {
coins = 50;
}
public void displayPlayerProfession() {
professions[0] = "knight";
professions[1] = "rider";
professions[2] = "mage";
}
}

call the profession in the main?
Well, you already have the type declaration PlayerOne player; so just call player.getProfessions() and use the array.
call the inventory in the main?
Just the same: player.getInventory().
However, note that your design is somewhat flawed (although since you're a beginner don't bother too much). The class name PlayerOne indicates any other player (e.g. PlayerTwo) would be different, but that's probably not the case. Also, AllPlayers doesn't actually indicate a class, but it looks more like a collection.
You might think about changing your class names, e.g. assuming AllPlayers will be used for NPCs as well, you could name it Character while the class for players is called Player. Doing this you could have multiple players if needed: Player playerOne, Player playerTwo etc.

Related

Why do I keep getting a Null Exception Error?

I have three classes in my program. Ship.java, Cabin.java and Passenger.java. According to the program a single cabin can hold upto a maximum of 3 passengers. I'm trying to set passenger details but i keep getting this error
Cannot invoke "classes.Passenger.setFirstName(String)" because
"classes.Main.myShip[0].passenger[0]" is null at
classes.Main.main(Main.java:22)
Ship.java
public class Ship
{
public static Scanner scanner = new Scanner(System.in);
public static Cabin[] myShip = new Cabin[12];
public static void main(String[] args)
{
for (int count = 0; count < 12; count++)
{
myShip[count] = new Cabin();
}
myShip[0].passenger[0].setFirstName("a");
}
}
Cabin.java
public class Cabin
{
int cabinNumber;
Passenger[] passenger = new Passenger[3];
public Cabin()
{
}
public Cabin(int cabinNumber, Passenger[] passenger)
{
this.cabinNumber = cabinNumber;
this.passenger = passenger;
}
public void setCabinNumber(int cNumber)
{
cabinNumber = cNumber;
}
public int getCabinNumber()
{
return cabinNumber;
}
}
Passenger.java
public class Passenger
{
String firstName;
String lastName;
int expenses;
public Passenger()
{
}
//Constructors
public Passenger(String cabinFirstName, String cabinLastName, int pExpenses)
{
firstName = cabinFirstName;
lastName = cabinLastName;
expenses = pExpenses;
}
public void setFirstName(String cabinFirstName)
{
firstName = cabinFirstName;
}
public String getFirstName()
{
return firstName;
}
public void setLastName(String cabinLastName)
{
lastName = cabinLastName;
}
public String getLastName()
{
return lastName;
}
public void setExpenses(int pExpenses)
{
expenses = pExpenses;
}
public int getExpenses()
{
return expenses;
}
}
Please be kind enough to help me out.
Your model is wrong. A ship can (and does) have cabins with no occupants. You have provided no way to have unoccupied cabins. Your cabins need to be fully booked before the ship can be built!
I would consider redefining your Cabin class to be constructed empty -- which means it would have a constructor with a signature like Cabin(), and then provide a way to assign Passengers to Cabins. Maybe this would be a method in the Cabin class, like
boolean assignPassenger(Passenger p) {
... check occupancy...
... return false if full up ...
... otherwise add 'p' to the passenger array ...
... and return true ...
}
You're halfway there in that you're attempting to set the Cabins in the Ship by using a Cabin() constructor -- which is essentially an empty Cabin -- but you have not actually implemented a constructor with that signature.
What I'm getting at here is that, rather than just tweaking some Java, I think you should rethink it a bit. You'd want, I think, to be able to have unoccupied cabins and to be able to determine which cabins are occupied.

Java Game - Pick up Item and Look around Function

I have been creating a java text game but I am stuck trying to figure out on how to implement the last 2 methods. I want it to print out the items in the room and the name of the npc thats in the room (A sort of a Look function). I am not sure on how to go on about it. Any help would be appriciated.
Room[] place = new Room[]{station, UC, Ollies, lounge, palace, AT301};
Sword sword = new Sword();
Thing heal = new HealthPotion();
Thing armour = new Armour();
Thing trap = new Trap();
and for the NPC (Mike, Jake, Evil, Carl)
public abstract class Player{
//abstract attributes
private String name;
private int currentHealth;
private int maxHealth;
private int damage;
private Room currentRoom;
private int stack;
private int effect;
//Constructor for player
public Player(String name, int currentHealth, int maxHealth, int damage, int effect, int stack){
this.name = name;
this.currentHealth = currentHealth;
this.maxHealth = maxHealth;
this.damage = damage;
this.effect = effect;
this.stack = stack;
}
//getters
public String getName(){ return name;}
public int getCurrentHealth(){ return currentHealth;}
public int getMaxHealth(){ return maxHealth;}
public int getDamage(){ return damage;}
public Room getCurrentRoom(){ return currentRoom;}
public int getEffect(){ return effect;}
public int getStack(){ return stack;}
//setters
public void setCurrentHealth(int currentHealth){this.currentHealth = currentHealth;}
public void setMaxHealth(int maxHealth){this.maxHealth = maxHealth;}
public void setDamage(int damage){ this.damage = damage;}
public void setCurrentRoom(Room room){this.currentRoom = room;}
public void setEffect(int effect){ this.effect = effect;}
public void setStack(int stack){ this.stack = stack;}
public void enter(Room room){ this.currentRoom = room;}
//abstract method because each player has a different attack;
public void takeDamage(int damage){ setCurrentHealth(this.currentHealth-damage);}
public boolean isDead(){
if(this.currentHealth<=0){ return true;}
return false;
}
}
I was able to make everything functional except the Look function for the player. I can't figure out how to go on about it.
Room is a vector of items right ? If so you can do a function on the player class that when it is called it goes to the vector of the room you're in and simply print out the items that are in the vector, something like this:
String lookAround(){
ArrayList temp = (ArrayList)getCurrentRoom(); //returns the array containing the items in the current room
for(Thing i : temp){
i.getDescription(); //Method present in all classes that come from Thing that prints out the name of the item and/or its caracheteristics
}
}
In the array of the room you should try to include the name of all players in the room including yourself so that you can print out everyone present in the room
Hope this helps
I would recommend you first of all creating a class Npc with attribute name and add it to the room.

Changing data in an Object Array

I have been trying to make a game for a friend, but I'm having a problem with getting my line player[i].setName(getName(pn)); in class Players to work. I want to be able to set the names of the players, or change them, in the list. but I keep getting errors at this line. This happened after i changed the public variables in class Player from static.
"Exception in thread "main" java.lang.NullPointerException
at worldhomicide.drinkinggame.PlayerInfo.Players.setPlayers(Players.java:16)
at worldhomicide.drinkinggame.main.Game.main(Game.java:25)"
Any help would be greatly appreciated! I posted all needed code below.
Game Class
public class Game{
public static void main(String[] args) {
MessageHandler.gameRules(); // Display Game Information
Players.getAmount();Players.setPlayers(); // Get player data
System.out.println("What player would you like to look up?");
int choice = Integer.parseInt(EventHandler.keyboard.next()); choice -= 1;
System.out.println(Players.player[choice].name);
}
}
Players Class
public class Players extends EventHandler {
public static int playerAmount;
public static Player[] player;
public static void setPlayers(){
player = new Player[playerAmount];
for(int i = 0; i < player.length; i++){
int pn = i+1;
player[i].setName(getName(pn));
}
}
public static void getAmount(){
MessageHandler.playerAmount();
playerAmount = Integer.parseInt(keyboard.next());
}
}
Class EventHandler
public class EventHandler {
public static Scanner keyboard = new Scanner(System.in);
public static String getName(int playerNumber){
System.out.println("What is player " + playerNumber + "'s name?");
String name = keyboard.next();
return name;
}
}
Player Class
public class Player {
public String name;
public int score;
public void setName(String name){
this.name = name;
}
}
Note that in your setPlayers() method, inside the loop, you didn't create Player object before accessing the player[i].setName() method.
for(int i = 0; i < player.length; i++){
int pn = i+1;
player[i] = new Player(); //you need to create Player object
player[i].setName(getName(pn));
}

Calling Random Value from an Enum Java

I have a Enum Class, a Player Class, and a class called Lisa that extends Player class. Im trying to randomly generate a value (PAPER, ROCK, or SCISSORS) from the Enum. Error: "The primitive type int of Roshambo does not have a field ROCK." Any advice or pointers would be greatly appreciated. It may be apparent, but this is my fists Java class and Google and Stackoverflow searches have not helped. Here is what I have coded so far:
UPDATE: Thanks for all the assistance. I've updated my whole program below. I was wondering if anyone could suggest the best way/place possible to implement logic to determine the winner/loser of the game? Here is the full code:
MAIN
package gameOfRoshambo;
import java.util.Scanner;
public class RoshamboApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Roshambo!");
System.out.println("Enter your name:");
//Create a new payer
Player1 player1 = new Player1();
String name = sc.nextLine();
player1.setName(name);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
System.out.println("Hello " + name + ". " + "Would you like to play against Bart or Lisa? (B/L)");
String opponent = sc.next();
if(opponent.equalsIgnoreCase("B")){
//Create a new Bart opponent
Bart bart = new Bart();
System.out.println(player1.getName() + ": " + player1.getChoice());
System.out.println("Bart: " + bart.getRoshambo());
}
else if (opponent.equalsIgnoreCase("L")){
//Create a new Lisa opponent
Lisa lisa = new Lisa();
System.out.println(player1.getName() + ": " + player1.getChoice());
System.out.println("Lisa: " + lisa.getRoshambo());
}
// Ask user if they want to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
//Close Scanner
System.out.println("Thanks for playing! Goodbye!");
sc.close();
}
}
ENUM
package gameOfRoshambo;
public enum Roshambo
{ROCK, PAPER, SCISSORS;
public String toString() {
switch(this) {
case ROCK: return "Rock";
case PAPER: return "Paper";
case SCISSORS: return "Scissors";
default: throw new IllegalArgumentException();
}
}
}
PLAYER
package gameOfRoshambo;
abstract class Player {
String name;
Roshambo roshambo;
abstract int generateRoshambo();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Roshambo getRoshambo() {
return roshambo;
}
public void setRoshambo(Roshambo newRoshambo) {
roshambo = newRoshambo;
}
}
PLAYER1
package gameOfRoshambo;
import java.util.Scanner;
public class Player1 extends Player{
String player1 = "";
public Player1(){
super();
}
Scanner scan = new Scanner(System.in);
public Roshambo getChoice(){
System.out.println("Enter Choice: Paper, Rock, Scissors (r/p/s): ");
char playerChoice = scan.nextLine().toUpperCase().charAt(0);
switch (playerChoice){
case 'R':
return Roshambo.ROCK;
case 'P':
return Roshambo.PAPER;
case 'S':
return Roshambo.SCISSORS;
}
System.out.println("Invalid input!");
return getChoice();
}
public String getPlayer1() {
return player1;
}
public void setPlayer1(String player1) {
this.player1 = player1;
}
#Override
int generateRoshambo() {
// TODO Auto-generated method stub
return 0;
}
}
BART
package gameOfRoshambo;
public class Bart extends Player {
public Bart(){
super();
}
public Roshambo getRoshambo(){
return Roshambo.ROCK;
}
#Override
int generateRoshambo() {
// TODO Auto-generated method stub
return 0;
}
}
LISA
package gameOfRoshambo;
import java.util.Random;
public class Lisa extends Player {
private Random rand;
public Lisa(){
super();
rand = new Random();
}
public Roshambo getRoshambo(){
int shoot = rand.nextInt(3);
return Roshambo.values()[shoot];
}
#Override
int generateRoshambo() {
return 0;
}
}
You should store your roshambo field as a Roshambo not an int and update your setter and getter accordingly. This is because in Java Enums cannot be casted to int. See the below stack overflow link for explanation:
Cast Int to enum in Java
Field names should start with a lower case
Use Roshambo.values()[choice]
Get rid of the 1 + in 1 + rand.nextInt(3); because the nextInt() method has the first enum value in position 0. So
Roshambo.values()[0] = ROCK
Roshambo.values()[1] = PAPER
Roshambo.values()[2] = SCISSORS
In the Lisa constructor, change to rand = new Random() instead of Random rand = new Random() to avoid assigning to a new local variable which you lose once the constructor finishes
See the code snippets I've attached below for you
Player Class
package gameOfRoshambo;
abstract class Player {
String name;
Roshambo roshambo;
abstract int generateRoshambo();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Roshambo getRoshambo() {
return roshambo;
}
public void setRoshambo(Roshambo newRoshambo) {
roshambo = newRoshambo;
}
}
Lisa Class
package gameOfRoshambo;
import java.util.Random;
public class Lisa extends Player {
private Random rand;
public Lisa(){
super();
rand = new Random();
}
public Roshambo getRoshambo(){
int choice = rand.nextInt(3);
return Roshambo.values()[choice];
}
#Override
int generateRoshambo() {
return 0;
}
}
Also with the new above implementation you don't use the abstract int generateRoshambo() method so consider removing it and its implementation in Lisa...
Your field Roshambo is of type int. I think you want to declare it as something more like this:
Roshambo roshambo;
It is bad practice to capitalize field names. In this case, it confused you because you mixed up the field name with the type. You will have to replace int with Roshambo in several other places in your code.

how to use abstract classes, and implementing them

I'm not sure how eloquently I can really explain what I don't understand/need help with, I'm still Very new to Object Oriented Programming. This is regarding my coursework and I don't expect anyone to do it for me, I just need help understanding how to move on, and if I'm even on the right track.
Ok, so on to my question. Basically, I am attempting to create an arraylist which will hold a few objects which themselves has a bunch of information(obviously), my spec said to create an abstract class, which will be extended by my constructor class, which I did. The abstract class has a few variables (decided by spec) But I dont know how to move them over to my extended class.
I'll post my code below, and I hope it makes sense. I'd be very thankful for any help you all could provide. I'm very confused right now.
Basically, I would love to know, A) How do I create an object in my arraylist which will be able to contain everything in SportsClub and FootballClub, and preferably all the variables user inputted.
And B) I don't know how to print The object, When I print right now I get coursework.FootballClub#49233bdc, Which I'm sure there's a reason for but I need the information in the objects to display, E.g. name. And if possible to sort the results by alphabetical order with respect to name? I hope this is all written ok. Sorry and Thank you in advance.
package coursework;
import java.util.*;
/**
*
* #author w1469384
*/
public class PremierLeagueManager implements LeagueManager{
public static void main(String[] args) {
Scanner c1 = new Scanner(System.in);
Scanner c2 = new Scanner(System.in);
ArrayList<FootballClub> PL = new ArrayList<FootballClub>();
int choice;
System.out.println("Enter 1; To create a club, 2; To Delete a Club, 3; To display all clubs and 99 to close the program");
choice = c1.nextInt();
//Creates and adds a new FootballClub Object
while (choice != 99){
if (choice == 1){
System.out.println("Please Enter The games played for the club");
int played = c1.nextInt();
System.out.println("Please enter the number of wins");
int wins = c1.nextInt();
System.out.println("please enter the number of losses");
int losses = c1.nextInt();
System.out.println("please enter the number of draws");
int draws = c1.nextInt();
System.out.println("please enter the number of goals for");
int goalsFor = c1.nextInt();
System.out.println("please enter the number of goals against");
int goalsAgainst = c1.nextInt();
FootballClub club = new FootballClub(played, wins, losses, draws, goalsFor, goalsAgainst);
PL.add(club);
System.out.println("check");
}
//Deletes a FootballClub Object
if (choice == 2){
}
//Displays all Football Clubs in the PremierLeague array
if (choice == 3){
System.out.println(PL);
}
//Closes the Program 1
choice = c1.nextInt();
}
}
}
public abstract class SportsClub {
public String name;
public String location;
public int capacity;
public void setName(String Name){
name = Name;
}
public void setLocation(String Location){
location = Location;
}
public void setCapacity(int Capacity){
capacity = Capacity;
}
public String getName(){
return name;
}
public String getLocation(){
return location;
}
public int getCapacity(){
return capacity;
}
}
public class FootballClub extends SportsClub {
//Statistics for the club.
int played;
int wins;
int losses;
int draws;
int goalsFor;
int goalsAgainst;
public FootballClub(int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst){
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
}
public void setPlayed(int newPlayed){
played = newPlayed;
}
public void setWins(int newWins){
wins = newWins;
}
public void setLosses(int newLosses){
losses = newLosses;
}
public void setDraws(int newDraws){
draws = newDraws;
}
public void setGoalsFor(int newGoalsFor){
goalsFor = newGoalsFor;
}
public void setGoalsAgainst(int newGoalsAgainst){
goalsAgainst = newGoalsAgainst;
}
public int getPlayed(){
return played;
}
public int getWins(){
return wins;
}
public int getLosses(){
return losses;
}
public int getDraws(){
return draws;
}
public int getGoalsFor(){
return goalsFor;
}
public int getGoalsAgainst(){
return goalsAgainst;
}
}
FootballClub inherits the variables declared in SportsClub so you can set them as you please.
public FootballClub(
int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst,
String inName, String inLocation, int inCapacity
) {
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
// set the variables from the superclass
name = inName;
location = inLocation;
capacity = inCapacity;
}
FootballClub also inherits the methods declared in SportsClub so you can use the setters and getters too.
Normally you would create a constructor for SportsClub that sets these and then call that constructor from the FootballClub constructor.
// in SportsClub
protected SportsClub(
String inName, String inLocation, int inCapacity
) {
name = inName;
location = inLocation;
capacity = inCapacity;
}
// in FootballClub
public FootballClub(
int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst,
String inName, String inLocation, int inCapacity
) {
super(inName, inLocation, inCapacity);
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
}
You should also make your member variables protected or private if you are using setters and getters.
I don't know how to print The object
You need to override toString. There is a short tutorial here.
Also unrelated side note: all Java variable identifiers should start with a lowercase letter.
When you have a method like this:
public void setName(String Name) { name = Name; }
It should be:
public void setName(String inName) { name = inName; }
Or:
public void setName(String name){ this.name = name; }

Categories

Resources