Java Not Using a parameter of the same class in a method - java

I have the following method inside the class Player that uses one of his emporiums available and sets it on a determined City
public void setEmporium(City city){
Emporium emporium = getEmporiums().get(0);//gets the emporium from the player
city.getEmporium().add(emporium);//adds it to the city
LinkedList<Bonus> bonus = city.getBonus();
for (int i=0;bonus!=null&&i<bonus.size();i++){
bonus.get(i).applyBonus(player);//Error line
}
getEmporiums().remove(0);//removes the emporium from the player
}
To correct the error of course i can just use the parameter player like this
public void setEmporium(City city,Player player){
but it isn't kind of redundant to use a parameter in its same class?
because when i test it would be like
Player player = new Player(1);
City city = new City(CityName.BURGEN,Color.YELLOW,4);
player.setEmporium(city, player);
and if i would create another object i would be able to do this
Player player2 = new Player(2);
player2.setEmporium(city, player);
This would mean that another player could build using emporiums from another player which shouldn't be possible, a player can only build using its own emporiums.
The only other solution that eclipse gives me is to create a local variable Player player; but then it says that it's not initialized, is there another way?

Related

Checking if an ArrayList exists in a map

My football team has 5 different teams and I am trying to make a program to keep a track of which players are registered with each team. I want to be able to add a new player but first the program checks if that player is already registered. I would also be able to add new teams in the future and again I would like to check if that team already exists.
I have made a Map variable with
private Map<String, List<Player>> teamName;
then initialised this in the constructor
teamName = new HashMap<>();
I then have a method to add new teams and new players, I want the method to check if the Club name already exists and then if it does exist, add the player name to that Club. if it doesn't exist then I want the program to add a new Club and then add that player to that club.
So far I have a method for adding a new player,
public void newPlayer(String club, Player name) {
}
I am not sure how I now go about checking that an ArrayList exists for club and if it does add name to this list, if club does not exist then I want to make a new list and add name to it.
if I then run the program and write,
Player jamesAtkinson = new Player();
newPlayer("first team", jamesAtkinson);
it would check if there is a List in the Map called 'first team' and then either add James Atikinson to it, or create a new List called first team and then add James Atkinson.
Is this even possible to do?
Although there are a few problems with code you've provided in the question. What you're looking for is the .containsKey function that hangs off of the Map interface.
if (players.containsKey("first team") {
// Do something
} else {
List<Player> firstTeam = new ArrayList<>();
firstTeam.add(jamesAtikson);
players.put("first team", jamesAtikson);
}

Java ArrayList update with points seems to replace all elements in said array with the most recent point

short description of what I am trying to do: I'm building a simple game where the user controls a vehicle and after some time more and more ghosts begin following the player, they follow the same trajectory as the player did with a delay.
To accomplish this I create an Array that contains the history of the player's location as a sequence of points. The problem, however, is that when I look at the data stored in this array I see that on all indices only the most recent location is stored.
First I create the array in a botManager class:
public class BotManager {
private ArrayList<Bots> bots;
private List<Point> history;
BotManager() {
history = new ArrayList<>();
bots = new ArrayList<>();
}
Then in the update method of the manager class I add the current location of the player to the array
public void update(Point currLoc) {
history.add(currLoc);
for (Bots bot : bots) {
bot.setLocationData(history);
bot.update();
}
}
A look at the update method in the main GameView class, in case I forgot something here
public void update() {
player.update(playerPoint);
botManager.update(playerPoint);
}
In the bots class' constructor I pass the history list (locationData) and determine its length to find out the delay in positioning. After which the following code handles the position of the bot.
#Override
public void update() {
loc = locationData.get(delay - 1);
this.rectangle = new Rect(loc.x - Constants.BOTSIZE/2, loc.y - Constants.BOTSIZE/2,
loc.x + Constants.BOTSIZE/2, loc.y + Constants.BOTSIZE/2);
}
To get back to the problem, whenever I check the contents of the history array, I find that it only contains one point on all indices, and its the most recent even when I moved the player, causing the ghost to always remain on top of me.
So my question here is, what am I doing wrong here?
Not clear from your posted code, but could it be, that you are just modifying the Point which you are adding instead renewing your object's Point objects?
Try
public void update(Point currLoc) {
history.add(new Point(currLoc)); // new Point object added here
for (Bots bot : bots) {
bot.setLocationData(history);
bot.update();
}
}

Understanding the theory, but not able to construct a multi-class project?

So this is my very first mini-javaproject and I have been stuck for days now on the basic structure and the (non existing) relation between anything within my code. I linked the code in my comment below, could not paste it in here for some reason - (Main is empty, so did not copy it.)
So I spent some time getting my head around the basics of Java (as my first programming adventure) and to be honest I felt pretty confident. (On Codewars I completed like 100+ Katas, but of course those are "single-class", so I was not prepared for the "real world.)
It is hard to exactly pinpoint my question, but I will try to give some examples.
1, (Main is empty right now, but anyway) Basically "nothing can be used" in main. Like methods of objects, like room1, or player1, etc.
2, In my Room.java line 21-22 why is the object room1 not visible? Why does Intellij say "Unknown class: RoomArray if I just created that very thing before??
3, I understand that I am supposed to have my variables set to private, which I plan to do later on. Also, I should use setter and getter methods, which I tried to do so with basically everything. But for example in Player.java I have this
Player player1 = new Player(300, 50, "Conan", 75, false);
public Player getPlayer1() {
return player1;
}
and if I try to use the getPlayer1() method in any other class it just simply can not see/access it?
3, And to make me even more confused Room1 class has access to getMyDungeon () method created in the Dungeon class. Why is that so?
(Maybe it has to do with inheritance? The fact that Room1 extends Room which extends Room? But if so, it seems strange because not all classes can have a HAS-A or IS-A relationship with something. An example - if I create all 10 Rooms later on as Room1, Room2, etc. in separate classes, how could I ever create a Room [] array containing them? No matter where I started to do that it will always give me the error "Cannot resolve smybol" for all the Room objects...)
I have spent the past few days reading up on the topic and understand it all, but still when I try to build this project it all falls apart. I realize that an experienced programmer might not even my question because how basic it is, but if anyone can help me to get this whole thing clear in my head, I would appreciate it. (Really not looking for the complete code, but just some direction I should go, or the missing step, etc.)
It seems you to be trying to create an object within the class of that object The correct use is:
public static void main(String[] args){
Player player1 = new Player(300, 50, "Conan", 75, false);
}
or if you want your Room class to have a lot of players
public class Room {
//this object will be create when you do Room room = new Room();
List<Player> players = new ArrayList<>();
public void createPlayer(){
players.add(new Player());
}
//this is a getter
public List<Player> getPlayers() {
return players;
}
}
your Player:
public class Player {
//Fields and Methods
}
and your main:
public static void main(String[] args)
{
Room room =new Room();
room.createPlayer();
for (Player p:room.getPlayers()) {
//p.doSomething
}
}
if you want an object to be created without the need to create an instance from the outside you need to use the static keyword (don't do that unless you know what you are doing)
static Player player1 = new Player(300, 50, "Conan", 75, false);
public static Player getPlayer1() {
return player1;
}

bukkit - Prevent player from running command when in combat

So I'm developing a Java Plugin and I need to do something like the KitPvP servers do these days, the player selects a kit, and then they are only allowed to get a kit again once they've died.
I've tried this using strings to check if the player is in command, but I really don't know what/"how" to do with them. Any suggestions?
You could use a list to check if the player has got the kit in "this life".
For example in your main plugin class or in your command class you could add a static member like this:
public static ArrayList<UUID> usedKit = new ArrayList<UUID>();
In the onCommand() method you can check if the player hasn't got his kit yet:
if (!usedKit.contains(player.getUniqueId())) {
// Code to give the kit here...
usedKit.add(player.getUniqueId()); // Adds the player to the list
} else
player.sendMessage("You already got your kit.");
return true;
When the player dies you have to remove him from the list:
#EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
if (usedKit.contains(event.getPlayer().getUniqueId()))
usedKit.remove(event.getPlayer().getUniqueId());
}
I know that this answer is similar to Kerooker's but you should try to use UniqueIds since you can change your name in minecraft.
What you can do is create a list containing the names of the players that have already used the kits
List<String> players = new ArrayList<String>();
Then whenever they use the command, you check if the player is inside your list
boolean isInList = players.contain(yourPlayer.getName());
You can check that when you handle the command
if (isInList) {
player.sendMessage("You must die to use this again!");
return true; //To commandExecutor
}
If the player is not in the list, add him to the list and give the kit
players.add(yourPlayer.getName());
//Give the kit
Whenever a player die, you should try to remove his name from the List.
#EventHandler
public void onDeath(PlayerDeathEvent e) {
//Remove player from the list
}
Note that inside a onCommand, you have the following attributes of a command: CommandSender sender, Command cmd, String label, String[] args.
The sender argument may be your player, and you can check that by
if (sender instanceof Player) {
Player commandPlayer = (Player) sender;
}
I assume that you use the Spigot API and you'r probably searching for something like this PlayerDeathEvent
This gets triggered everytime a Player dies and you can compare them with your Players list and update the permissions(bukkit) permission(spiggot).
Hopefully this answered your question.

Iterating a loop through all objects of a class

New to Java-
I'm building a poker program and I've created a player class with some instance variables including "toppair", "highcardst",etc... I tried to use a placeholder variable to refer to the appropriate player's instance variable rather than relying on if statements.
int handsdealt=0;
int straightval=0;
String placeholder="blank";
player playerone = new player("Richard");
player playertwo = new player("Negreanu");
//code omitted
if (handsdealt==1) placeholder="playerone";
else placeholder="playertwo";
//code to determine if hand is a straight -if it is it sets straightval to 1
**if(straightval==1) placeholder.highcardst=straightHigh;**
I receive an error on that last line- it looks like java doesn't accept this syntax. Essentially, since this hand is a straight I want to append the value of the "highcardst" instance variable of the "n" th player as n hands have been dealt.
Thank you.
You seem to be uses a String for your placeholder variable where you actually want to refer to a player object.
player playerone = new player("Richard");
player playertwo = new player("Negreanu");
//code omitted
player placeholder;
if (handsdealt==1) placeholder=playerone;
else placeholder=playertwo;
//code to determine if hand is a straight -if it is it sets straightval to 1
if(straightval==1) placeholder.highcardst=straightHigh;
Also, it will make your code easier to follow if you follow normal Java code conventions, such as capitalising the first letter of a class name (e.g. Player, not player).
You could make a list of players and get the instance of the player from the list as required.
List<player> players = new ArrayList<player>();
players.add(new player("Richard"));
players.add(new player("Negreanu"));
if(straightval==1) {
players.get(handsdealt).highcardst=straightHigh;
}
Or something like that.
I think the problem could be in this statement:
placeholder.highcardst=straightHigh;
You've defined placeholder of type String, so the property called highcardst does not exist.
if(straightval==1) placeholder.highcardst=straightHigh;
Error is here. place holder is String type not Player type. Make temp variable as Player variable and assign
Player placeholder;
if (handsdealt==1) placeholder=playerone;

Categories