Java Game - Pick up Item and Look around Function - java

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.

Related

Trying to solve a Simple RPG game

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.

searching objects in a class

I'm making a program, in school, that plays monopoly and I set up all the own-able properties as objects in the property class and I want to be able to search for the properties by their position value. so if the player's position is 3 (which is Baltic Ave. in my code) I want to be able to search all own-able properties for one with a position of 3 then have the player buy/pay rent for the property. Is this possible or should I go at the problem from a different angle?
public class property
{
String owner;
int position;
int price;
int rent;
public property(int startPrice, int startPosition, int startRent)
{
price = startPrice;
position = startPosition;
owner = "none";
rent = startRent;
}
public void setOwn(String newOwn)
{
owner = newOwn;
}
public void changePrice(int newprice)
{
price = newprice;
}
public void changeRent(int newRent)
{
rent = newRent;
}
public int getprice()
{
return price;
}
public int getpos()
{
return position;
}
public String getown()
{
return owner;
}
public int getrent()
{
return rent;
}
}
To start, I'd have some sort of data structure to keep track of properties that can be bought. A HashSet is best since order doesn't matter and you can add and remove elements quickly. Set it up so that it contains properties that can be bought. Then I'd make this method: (don't put it in your Property class)
private static Property getPropertyAtPos(Player player, HashSet buyableProperties) {
for(Property p : buyableProperties) {
if(p.position == player.position) {
return p;
}
}
return null;
}
Call this method to get the property that can be bought by that player. Hope this helps.

How to access variables in a different class?

My first class called Match creates an individual soccer/football game. It makes you choose 2 teams and the final score. The second class called "team" is a bit more advanced. When the play (match match) method is called, the number of games played increments by 1. This part works fine. My else if statements for (goalsForThisMatch) also works fine. However, when I inspect the Team class object, it should display the same goals for and goals against that I inputted in the Match class. What actually happens is when I inspect the Team class after pressing the play(Match match) method, most of the methods are set to 0, except the "played" method (which increments by 1 like it's supposed to) and whatever the final score is. So if I inputted the score in the match class so that the home team has scored more goals and has won the match, then the Won method in the object inspector for the Team class will go up by 1. I need two of the other methods in the team class to link with the match class. These methods are: Goals For and Goals Against. If I input the GoalsFor in the match class to be "4" then when I inspect the Team class the goalsFor should be set to 4 also.
I know this all probably sounds VERY confusing, please forgive me, I'm so TIRED I'm about to head off to sleep. Hopefully in the morning, someone would have sorted this issue for me.
public class Match
// instance variables - replace the example below with your own
private String HomeTeam;
private String AwayTeam;
private int HomeGoals;
private int AwayGoals;
/**
* Constructor for objects of class Match
*/
public Match(String ShortHomeTeamName, String ShortAwayTeamName, int NewHomeGoals, int NewAwayGoals)
{
// initialise instance variables
HomeTeam = ShortHomeTeamName;
AwayTeam = ShortAwayTeamName;
HomeGoals = NewHomeGoals;
AwayGoals = NewAwayGoals;
}
public String getHomeTeamName(){
return HomeTeam;
}
public String getAwayTeamName(){
return AwayTeam;
}
public int getHomeGoals(){
return HomeGoals;
}
public int getAwayGoals(){
return AwayGoals;
}
}
public class Team
private String TeamName;
private String ShortName;
private int Played;
private int GoalsFor;
private int GoalsAgainst;
private int GoalDifference;
private int Won;
private int Drawn;
private int Lost;
private int Points;
/**
* Constructor for objects of class Team
*/
public Team(String FullTeamName, String ShortTeamName)
{
// initialise instance variables
TeamName = FullTeamName;
ShortName = ShortTeamName;
Played = 0;
GoalsFor = 0;
GoalsAgainst = 0;
GoalDifference = 0;
Won = 0;
Drawn = 0;
Lost = 0;
Points = 0;
}
public String getTeamName(){
return TeamName;
}
public String getShortName(){
return ShortName;
}
public int getPlayed(){
return Played;
}
public void getGoalsFor(int InsertGoalsFor){
GoalsFor = InsertGoalsFor;
}
public void getGoalsAgainst(int InsertGoalsAgainst){
GoalsAgainst = InsertGoalsAgainst;
}
public int getGoalDifference(){
return (GoalsFor - GoalsAgainst);
}
public int getWon(){
return Won;
}
public int getDrawn(){
return Drawn;
}
public int getLost(){
return Lost;
}
public int getPoints(){
return Points;
}
public void play(Match match){
Played++;
int GoalsFor = match.getHomeGoals();
int goalsForThisMatch = match.getHomeGoals();
int goalsAgainstThisMatch = match.getAwayGoals();
String homeTeam = match.getHomeTeamName();
String ShortName = match.getHomeTeamName();
if (ShortName.equals(TeamName)){
ShortName = homeTeam;
} else {
ShortName = match.getAwayTeamName();
}
if (goalsForThisMatch > goalsAgainstThisMatch){
Won++;
}
else if (goalsForThisMatch == goalsAgainstThisMatch){
Drawn++;
}
else {
Lost++;
}
}
}
I believe the problem you're having is that the fields of your Team class are not being updated when you invoke the play method.
The reason you see this behavior is that you're defining local variables inside the play method that hide your class member variables:
public void play(Match match){
...
int GoalsFor = match.getHomeGoals();
int goalsForThisMatch = match.getHomeGoals();
int goalsAgainstThisMatch = match.getAwayGoals();
String homeTeam = match.getHomeTeamName();
String ShortName = match.getHomeTeamName();
...
Your GoalsFor and ShortName local variables defined inside this method are hiding the class member variables you defined at the top of the class:
public class Team
private String TeamName;
private String ShortName;
private int Played;
private int GoalsFor;
...

error: incompatible types return scores; required: int found: ArrayList<Integer>

//Class declaration of Player class
public class Player
{
/*--------------- Data Fields ---------------------------------------
Attributes of the class
*/
private String name;
private int playerId;
private int bestScore;
private static int numberOfPlayers = 0;
private ArrayList<Integer> scores = new ArrayList<Integer>();
//Create set method for setScores
public void setScore(int score)
{
scores.add(score);
}
//Create get method for getScores
public int getScores()
{
return scores;
}
}
I tried looking for a solution but I cannot seem to find one. I was ask to store 5 scores for one player for a guessing game. Im just wonder what should I put into the getScore method.
Look here, the problem is here:
public int getScores()
{
return scores;
}
You're returning an ArrayList from a method which declares it returns an int

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