I'm looking to add an object called "player" to a binary search tree based on how high the score of the player is, essentially like a scoreboard, but I'm not entirely certain how to add players to the binary tree; I'm curious how to go about writing the method, so I hope this question makes sense.
Here's a part of my BinaryTree class:
import java.util.Iterator;
public class BinaryTree implements Iterable<Player> {
private BinNode root;
public BinaryTree() {
root = null;
}
public boolean isEmpty() {
return root == null;
}
// TODO: add the given player to the binary tree based on the player's game score
public void add(final Player player) {
if (isEmpty())
root = new BinNode(player);
// this is SUUUPER placeholder
} ...
Here's the player class, :
public class Player implements Comparable<Player> {
private String name;
private int score;
private static final int MIN_SCORE = 0;
public Player(final String name, int score) {
this.name = name;
if (score < MIN_SCORE)
this.score = 0;
else
this.score = score;
}
public Player(final String name) {
this(name, MIN_SCORE);
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
#Override
public String toString() {
return name + ": " + score;
}
// TODO: compare player objects based on their scores
#Override
public int compareTo(Player other) {
return score - other.score;// I think this is a step in the right direction???
}
}
Here's my Binary Node class:
public class BinNode {
private Player player;
private BinNode left, right;
public BinNode() {
player = null;
left = right = null;
}
public BinNode(final Player player) {
this.player = player;
left = right = null;
}
public Player getPlayer() {
return player;
}
public BinNode getLeft() {
return left;
}
public BinNode getRight() {
return right;
}
public void setPlayer(final Player data) {
this.player = player;
}
public void setLeft(BinNode left) {
this.left = left;
}
public void setRight(BinNode right) {
this.right = right;
}
#Override
public String toString() {
return player.toString();
}
}
I recommend you not to use your own trees in production, but if you are just learn, then that's fine. To add a new entity to your tree, you have to find a place for it. In this code we search for it by comparing scores of players.
public void add(final Player player){
if (isEmpty()){
root = new BinNode(player);
}
else{
BinNode node = root;
while (true){
if (player.getScore() <= node.getPlayer().getScore()){
if (node.getLeft() == null){
node.getLeft() = new BinNode(player);
return;
}
else{
node = node.getLeft();
}
}
else{
if (node.getRight() == null){
node.getRight() = new BinNode(player);
return;
}
else {
node = node.getRight();
}
}
}
}
}
Related
I can't succeed in making the enemies move from node to node.
I managed to set up the whole pathfinding, I'm getting a full path to the player and the position of the next node all the way to the end.
How do I move the box2d body from node to node?
Or even simpler - how do I move a box2d body to a certain position?
I tried applying impulses, forces weren't able to do it.
Here is my simplified code. Both Monster and Player classes extend Sprite:
public class B2dSteeringEntity implements Steerable<Vector2>, Updateable {
public static final String TAG = B2dSteeringEntity.class.getName();
Body body;
boolean tagged;
float maxLinearSpeed, maxLinearAcceleration;
float maxAngularSpeed, maxAngularAcceleration;
float boundingRadius;
SteeringBehavior<Vector2> behavior;
SteeringAcceleration<Vector2> steeringOutput;
public B2dSteeringEntity(Body body, float boundingRadius) {
this.body = body;
this.boundingRadius = boundingRadius;
this.maxLinearSpeed = 250;
this.maxLinearAcceleration = 200;
this.maxAngularSpeed = 0;
this.maxAngularAcceleration = 0;
this.tagged = false;
this.steeringOutput = new SteeringAcceleration<Vector2>(new Vector2());
}
#Override
public Vector2 getLinearVelocity() {
return body.getLinearVelocity();
}
#Override
public float getAngularVelocity() {
return body.getAngularVelocity();
}
#Override
public float getBoundingRadius() {
return 0;
}
#Override
public boolean isTagged() {
return tagged;
}
#Override
public void setTagged(boolean tagged) {
this.tagged = tagged;
}
#Override
public float getZeroLinearSpeedThreshold() {
return 0;
}
#Override
public void setZeroLinearSpeedThreshold(float value) {
}
#Override
public float getMaxLinearSpeed() {
return maxLinearSpeed;
}
#Override
public void setMaxLinearSpeed(float maxLinearSpeed) {
this.maxLinearSpeed = maxLinearSpeed;
}
#Override
public float getMaxLinearAcceleration() {
return maxLinearAcceleration;
}
#Override
public void setMaxLinearAcceleration(float maxLinearAcceleration) {
this.maxLinearAcceleration = maxLinearAcceleration;
}
#Override
public float getMaxAngularSpeed() {
return maxAngularSpeed;
}
#Override
public void setMaxAngularSpeed(float maxAngularSpeed) {
this.maxAngularSpeed = maxAngularSpeed;
}
#Override
public float getMaxAngularAcceleration() {
return maxAngularAcceleration;
}
#Override
public void setMaxAngularAcceleration(float maxAngularAcceleration) {
this.maxAngularAcceleration = maxAngularAcceleration;
}
#Override
public Vector2 getPosition() {
return body.getPosition();
}
#Override
public float getOrientation() {
return body.getAngle();
}
#Override
public void setOrientation(float orientation) {
}
#Override
public float vectorToAngle(Vector2 vector) {
return SteeringUtils.vectorToAngle(vector);
}
#Override
public Vector2 angleToVector(Vector2 outVector, float angle) {
return SteeringUtils.angleToVector(outVector, angle);
}
#Override
public Location<Vector2> newLocation() {
return null;
}
public Body getBody() {
return body;
}
public void setBehavior(SteeringBehavior<Vector2> behavior) {
this.behavior = behavior;
}
public SteeringBehavior<Vector2> getBehavior() {
return behavior;
}
private void applySteering(float deltaTime) {
boolean anyAccelerations = false;
if(!steeringOutput.linear.isZero()) {
Vector2 force = steeringOutput.linear.scl(deltaTime);
body.applyForceToCenter(force, true);
anyAccelerations = true;
}
if(anyAccelerations) {
Vector2 velocity = body.getLinearVelocity();
float currentSpeedSquare = velocity.len2();
if(currentSpeedSquare > maxLinearSpeed * maxLinearSpeed) {
body.setLinearVelocity(velocity.scl(maxLinearSpeed / (float) Math.sqrt(currentSpeedSquare)));
}
if (body.getAngularVelocity() > maxAngularSpeed) {
body.setAngularVelocity(maxAngularSpeed);
}
}
}
#Override
public void update(float deltaTime) {
if (behavior != null) {
behavior.calculateSteering(steeringOutput);
applySteering(deltaTime);
}
}
}
public Skeleton(B2WorldCreator creator, GameScreen screen, float x, float y, State state, HeroKnight player) {
super(creator, screen, x, y, state, player);
controller = screen.getController();
setBounds(x, y, 150 / Constants.PPM, 150 / Constants.PPM);
enemyAgentComponent = new EnemyAgentComponent(b2body, b2dSteeringEntity, controller, player);
}
And here is the EnemyAgentComponent class:
public class EnemyAgentComponent implements Component, Telegraph, Updateable, Pather<Node> {
public static final String TAG = EnemyAgentComponent.class.getName();
public StateMachine<EnemyAgentComponent, EnemyState> stateMachine;
public boolean isInProximity() {
return inProximity;
}
public boolean inProximity = false;
public boolean lowHP = false;
public boolean isShot = false;
private boolean isRequested = false;
private boolean requestingMovement;
private Steering wayPoint;
private Body body;
private Controller controller;
private HeroKnight player;
private Node startNode, endNode, previousStartNode, previousEndNode;
private Vector2 goal;
private PathfindingTarget newGoal;
private float impulseMag;
private boolean nodeReached;
private boolean pathGenerated;
private Arrive<Vector2> arriveSB;
private Steering waypoint;
private B2dSteeringEntity steering;
private IndexedAStarPathFinder<Node> pathFinder;
private GraphPathImp resultPath = new GraphPathImp();
private float pathfindingTimer;
private boolean firstPathGenerated;
public boolean isTouchingPlayer() {
return touchingPlayer;
}
public void setTouchingPlayer(boolean touchingPlayer) {
this.touchingPlayer = touchingPlayer;
}
private boolean touchingPlayer;
public EnemyAgentComponent(Body body, B2dSteeringEntity steering, Controller controller, HeroKnight player) {
construct(body, steering, controller, player);
}
public void construct(Body body, B2dSteeringEntity steering, Controller controller, HeroKnight player) {
this.steering = steering;
this.controller = controller;
this.body = body;
this.player = player;
stateMachine = new DefaultStateMachine<>(this, EnemyState.SEEKING);
MessageManager.getInstance().addListener(this, Messages.PLAYER_IN_SIGHT);
MessageManager.getInstance().addListener(this, Messages.PLAYER_ATTACKED_ENEMY);
MessageManager.getInstance().addListener(this, Messages.LOW_HP);
MessageManager.getInstance().addListener(this, Messages.PLAYER_OUT_OF_SIGHT);
MessageManager.getInstance().addListener(this, Messages.TOUCHING_PLAYER);
pathFinder = new IndexedAStarPathFinder<Node>(LevelManager.groundGraph, false);
requestingMovement = false;
goal = null;
nodeReached = false;
pathGenerated = false;
firstPathGenerated = false;
pathfindingTimer = 0;
touchingPlayer = false;
}
public Vector2 getGoal() {
return goal;
}
public boolean isRequestingMovement() {
return requestingMovement;
}
public void setRequestingMovement(boolean requestingMovement) {
this.requestingMovement = requestingMovement;
}
public boolean isPathGenerated() {
return pathGenerated;
}
public GraphPathImp getResultPath() {
return resultPath;
}
public void generatePath() {
previousEndNode = endNode;
previousStartNode = startNode;
resultPath.clear();
pathFinder.searchNodePath(startNode, endNode, new HeuristicImp(), resultPath);
newGoal = new PathfindingTarget(resultPath.get(0).getNodePosition());
pathGenerated = true;
}
public void update(float deltaTime) {
startNode = LevelManager.groundGraph.getNodeByXY(body.getPosition().x, body.getPosition().y);
endNode = LevelManager.groundGraph.getNodeByXY(player.b2body.getPosition().x, player.b2body.getPosition().y);
//If player gets in certain range of the enemy and is not touching the enemy, enemy's path is being generated
if (inProximity) {
if (!firstPathGenerated && !touchingPlayer)
if ((pathfindingTimer == 0)) {
generatePath();
previousStartNode = startNode;
previousEndNode = endNode;
firstPathGenerated = true;
}
//If a path was already created, a new path is being requested only if player's position changes
if (firstPathGenerated && (previousEndNode != endNode) && pathfindingTimer == 0 && !touchingPlayer) {
generatePath();
}
if (firstPathGenerated)
pathfindingTimer += deltaTime;
//Paths are generated every 2 seconds
if (pathfindingTimer >= 2) {
pathfindingTimer = 0;
}
//If enemy touches the player pathfinding ends
if (touchingPlayer) {
pathfindingTimer = 0;
pathGenerated = false;
resultPath.clear();
body.setLinearVelocity(0, 0);
}
}
//The arrive behaviour is set, newGoal being the position of next node
if (steering.getLinearVelocity().x == 0 && steering.getLinearVelocity().y == 0 && newGoal != null) {
steering.setBehavior(new Arrive<Vector2>(steering, newGoal));
}
steering.update(deltaTime);
//Updating the next node position based on the enemy reaching a node
if (pathGenerated)
if (Math.abs(body.getPosition().x - newGoal.getPosition().x) <= 0.1f && Math.abs(body.getPosition().y - newGoal.getPosition().y) <= 51 / 2f / Constants.PPM)
{
updatePath();
}
}
public void updatePath() {
//Setting the next target position
if (resultPath.getCount() > 0) {
resultPath.removeIndex(0);
if (!touchingPlayer && resultPath.getCount() > 0) {
newGoal.setPosition(resultPath.get(0).getNodePosition());
requestingMovement = true;
nodeReached = false;
}
}
}
#Override
public boolean handleMessage(Telegram telegram) {
if (telegram.message == Messages.PLAYER_IN_SIGHT) {
inProximity = true;
return true;
}
if (telegram.message == Messages.PLAYER_OUT_OF_SIGHT) {
inProximity = false;
firstPathGenerated = false;
pathGenerated = false;
pathfindingTimer = 0;
resultPath.clear();
}
if (telegram.message == Messages.LOW_HP) {
lowHP = true;
return true;
}
if (telegram.message == Messages.PLAYER_ATTACKED_ENEMY) {
isShot = true;
return true;
}
if (telegram.message == Messages.TOUCHING_PLAYER) {
touchingPlayer = true;
return true;
}
return false;
}
#Override
public void acceptPath(PathFinderRequest<Node> request) {
if (request.pathFound) {
resultPath = (GraphPathImp) request.resultPath;
}
}
}
Skeleton class is being updated and drawn using skeleton.update(deltaTime) and skeleton.draw(deltaTime).
EDIT2:
Now tried using linear impulses, movement is very clunky:
if (newGoal != null) {
Vector2 direction = new Vector2(newGoal.getPosition().x - body.getPosition().x, newGoal.getPosition().y - body.getPosition().y).nor();
float speed = Constants.SKELETON_SPEED;
Vector2 velocity = new Vector2(speed * direction.x, speed * direction.y);
body.applyLinearImpulse(velocity.x * body.getMass(), velocity.y * body.getMass(), body.getWorldCenter().x, body.getWorldCenter().y, true);
}
if (pathGenerated)
if (Math.abs(body.getPosition().x - newGoal.getPosition().x) <= 0.1f && Math.abs(body.getPosition().y - newGoal.getPosition().y) <= 51 / 2f / Constants.PPM)
{
Gdx.app.debug(TAG, "Node reached!");
updatePath();
}
Moving an entity is not directly related to AI. The AI just finds a way, the entity follows it.
With box2d, you have to apply forces or impulses into the right directions, make sure your box2d world's step() method is being called and update your entites rendering coordinates (e.g. the sprite) to match the box2d's body coordinates. Then call your AI from the new coordinates in the next loop again, determine in which direction you have to move now and apply your forces again.
So the loop looks like
Find a way via AI
Find direction to the next node from your position
Apply forces/impulses
box2d world step
Adapt the entities rendering coordinates to match the box2d body position
Repeat
Giving you a more detailed answer requires more knowledge about how you render your entities and what your loop looks like. Please share some example code.
Edit: After you added some code I find it still unclear what you actual problem is. Can you move your entity but fail to stop it? Does it move at all? Do you call world.step()? The only obvious issue I could find after a quick look is that you scale applyForceToCenter with deltaTime which is not needed as world.step already takes a timeStep as a parameter.
I have two classes called Pokemon.java and Move.java which contain methods for creating and modifying Pokemon and their moves. I've created all of the required methods, but I'm having trouble with the attack method, which is supposed to subtract an opponent's health when it's attacked.
Here is the code for the Pokemon.java class:
import java.util.ArrayList;
public class Pokemon
{
// Copy over your code for the Pokemon class here
// Private constants
private static final int MAX_HEALTH = 100;
private static final int MAX_MOVES = 4;
private String name;
private int health;
private int opponentHealth;
public static int numMovesForPokemon = Move.getNumOfMoves();
private Move move;
private static ArrayList<Move> moveListForPokemon = new ArrayList<Move>();
private String pokemonImage;
// Write your Pokemon class here
public Pokemon(String theName, int theHealth)
{
name = theName;
if(theHealth <= MAX_HEALTH)
{
health = theHealth;
}
}
public Pokemon(String name, String image)
{
this.name = name;
health = 100;
pokemonImage = image;
}
public Pokemon(String theName)
{
name = theName;
}
public void setImage(String image)
{
pokemonImage = image;
}
public String getImage()
{
return pokemonImage;
}
public String getName()
{
return name;
}
public int getHealth()
{
return health;
}
public boolean hasFainted()
{
if(health <= 0)
{
return true;
}
else
{
return false;
}
}
public boolean canLearnMoreMoves()
{
if(numMovesForPokemon < 4)
{
return true;
}
else
{
return false;
}
}
public boolean learnMove(Move other)
{
if(canLearnMoreMoves())
{
moveListForPokemon = Move.getList();
moveListForPokemon.add(other);
numMovesForPokemon++;
return true;
}
else
{
return false;
}
}
public void forgetMove(Move other)
{
moveListForPokemon.remove(other);
}
public static ArrayList<Move> displayList()
{
return moveListForPokemon;
}
public boolean knowsMove(Move move)
{
if(moveListForPokemon.contains(move))
{
return true;
}
else
{
return false;
}
}
public boolean knowsMove(String moveName)
{
if(moveListForPokemon.contains(move.getName()))
{
return true;
}
else
{
return false;
}
}
public boolean attack(Pokemon opponent, Move move)
{
if(knowsMove(move))
{
opponentHealth = opponent.getHealth();
opponentHealth -= move.getDamage();
return true;
}
else
{
return false;
}
}
public boolean attack(Pokemon opponent, String moveName)
{
if(knowsMove(moveName))
{
opponentHealth = opponent.getHealth();
opponentHealth -= move.getDamage();
return true;
}
else
{
return false;
}
}
public String toString()
{
return pokemonImage + "\n" + name + " (Health: " + health + " / " + MAX_HEALTH + ")";
}
// Add the methods specified in the exercise description
}
Here is the code for the Move.java class:
import java.util.ArrayList;
public class Move
{
// Copy over your code for the Move class here
private static final int MAX_DAMAGE = 25;
private String name;
private int damage;
public static int numMoves;
private static ArrayList<Move> moveList = new ArrayList<Move>();
public Move(String theName, int theDamage)
{
name = theName;
if(theDamage <= MAX_DAMAGE)
{
damage = theDamage;
}
}
public String getName()
{
return name;
}
public int getDamage()
{
return damage;
}
public static int getNumOfMoves()
{
return numMoves;
}
public static ArrayList<Move> getList()
{
return moveList;
}
public String toString()
{
return name + " (" + damage + " damage)";
}
// Add an equals method so we can compare Moves against each other
public boolean equals(Move other)
{
if(name.equals(other.getName()))
{
return true;
}
else
{
return false;
}
}
}
Finally, here is the code for PokemonTester.java where I test out the methods:
public class PokemonTester extends ConsoleProgram
{
private PokemonImages images = new PokemonImages();
public void run()
{
// Test out your Pokemon class here!
Pokemon p1 = new Pokemon("Charrizard", 100);
Pokemon p2 = new Pokemon("Pikachu", 100);
Move m1 = new Move("Flamethrower", 20);
Move m2 = new Move("Fire Breath", 15);
p1.learnMove(m1);
System.out.println(p1.knowsMove(m1));
System.out.println(p1.knowsMove("Flamethrower"));
System.out.println(p1.attack(p2, m1));
System.out.println(p2.getHealth());
}
}
I suppose your problem is this:
opponentHealth = opponent.getHealth();
opponentHealth -= move.getDamage();
This code has several problems:
I'd suggest using a local variable for opponentHealth instead of a class level field
The opponent doesn't gets to know that it's health was subtracted. You have to share this knowledge with him, e.g. by introducing a setter for health and then calling opponent.setHealth(opponentHealth)
You are first assigning the value of Oponent.getHealth() to the int variable oponentHealth which you then modify, however this modification does not affect the health of Opponent but instead just the oponentHealth variable, you either have to directly access and modify the health field of Opponent or implement some kind of setHealth(int health) method in the class Pokemon
Hello this is my linked list without implementing java.util.linkedlist
I'd like to create a method that display recursively all of the elements in my linked list but I have no idea how to, my method doesn't have any parameters so I don't know how to get to the next value when calling the method itself
public class Pokemon {
private String name;
private String type;
private int niveau;
public Pokemon(String name, String type) {
this.name = name;
this.type = type;
this.niveau = (int) (Math.random() * (1 * 1 - 100) + 100);
}
public void display() {
System.out.println(this.name);
}
public class Trainer {
public final String name;
private Pokeball head;
public Trainer(String name) {
this.name = name;
}
public void addPokemon(Pokemon pok) {
if (this.head != null) {
this.head.addPokemon(pok);
} else {
this.head = new Pokeball(pok);
}
}
public void display() {
if (this.head == null)
return;
else {
this.head.display();
}
}
public class Pokeball {
private Pokemon pok;
private Pokeball next;
public Pokeball(Pokemon pok) {
this.pok = pok;
}
public Pokeball(Pokemon pok, Pokeball next) {
this.pok = pok;
this.next = next;
}
public void addPokemon(Pokemon pok) {
Pokeball current = this;
while (current.next != null) {
current = current.next;
}
current.next = new Pokeball(pok);
}
public void display() {
Pokeball current = this;
if (current.next == null){
return;
} else {
// ....
}
}
I assume this is for Pokeballclass, Why you would like to display using recursion ? why not iteration? Your Trainer class doesn't create a linked list, it has no next.
public void display() {
Pokeball current = this; //Note that this won't change your 'this'
while ( current != null ) {
System.out.print( current.display() + "->" );
current = current.next;
}
}
Recursive:
private void display_recurse( Pokeball current ) {
if ( current == null )
return;
System.out.print( current.display() + "->" );
display_recurse( current.next);
}
You may call this like:
public void display() {
display_recurse( this );
}
Usually this is accomplished using a private helper function that does have a parameter.
public void display() {
Pokeball current = this;
display(current);
}
private void display(Pokeball toDisplay) {
if(toDisplay == null) {
return;
} else {
// code to display current here
// ...
display(toDisplay.next);
}
}
I'm using a Map in my application to store each location within a fictional game map. The current implementation allows me to get the start node, ie Tiberius.
But I'm not sure how I can get to the next location on the map relative to the current location the player is at. For example when I create the map I am at "Tiberius" by default, so I'm wondering how I can create a method that will iterate to the next location, which would be "Desert" while a subsequent call to move() would bring the player to "Jerusalem".
The graph is wired up as shown below with each location having a child location.
From a quick search I see that a list can be iterated through by a field in the ID, like this get element by ID but in this implementation I need to get the next location relative to the current location.
Does anyone know how this method could be implemented?
This is how I've set up the map at the moment in my main class:
public class Main implements Commands{
public static void main(String[] args) {
//Boolean to signify game state
boolean gameNotOver = true;
//main game loop
while (gameNotOver) {
GameMap playerMap = new GameMap();
playerMap.getStartNode();
Main mainObj = new Main();
//Take in user commands here
//and parse commands
String input = Input.getInput();
if (input.equals("description")) {
System.out.println("Description: " );
} else if (input.equals("move")) {
System.out.println("Moving to the next location in map.. " );
mainObj.move();
}
//Game over
System.out.println("Game Over!");
System.exit(0);
}
//Game player commands inherited from GameCharacterInterface:
public String move() {
//want to create a method here that will call the next
//location based on the current location that the player is in.
// TODO Auto-generated method stub
return null;
}
}
This is the Location class used to model the locations:
public class Location {
private Location[] location;
private int id;
private String description;
private String weight;
private String name;
private Item item;
private Exit[] exit;
private boolean visited = false;
private boolean goalLocation;
private int approximateDistanceFromGoal = 0;
private Location parent;
private Map<Location, Integer> children = new HashMap<Location, Integer>();
public Location() {
super();
}
public Location(String name){
this.name = name;
}
public Location(String name, int goalDistance){
this.name = name;
this.approximateDistanceFromGoal = goalDistance;
}
public Location[] children(){
return (Location[]) children.keySet().toArray(new Location[children.size()]);
}
public int getDistance(Location loc){
if(children.get(loc) == null) System.out.println(this.name + ": " + loc.getName());
return children.get(loc);
}
public int getChildLocationCount(){
return children.size();
}
public void addChildLocation(Location child, int distance){
children.put(child, distance);
}
public boolean isLeaf(){
if (children.size() > 0){
return false;
}else{
return true;
}
}
public void removeChild(Location child){
children.remove(child);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public Exit[] getExit() {
return exit;
}
public void setExit(Exit[] exit) {
this.exit = exit;
}
public Location[] getLocation() {
return location;
}
public void setLocation(Location[] location) {
this.location = location;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
public boolean isGoalLocation() {
return goalLocation;
}
public void setGoalLocation(boolean goalLocation) {
this.goalLocation = goalLocation;
}
public int getApproximateDistanceFromGoal() {
return approximateDistanceFromGoal;
}
public void setApproximateDistanceFromGoal(int approximateDistanceFromGoal) {
this.approximateDistanceFromGoal = approximateDistanceFromGoal;
}
public Location getParent() {
return parent;
}
public void setParent(Location parent) {
this.parent = parent;
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
#Override
public String toString() {
return "Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", name=" + name + ", item="
+ item + ", exit=" + Arrays.toString(exit) + "]";
}
}
And this is the GameMap showing each of the locations and the getStartNode():
public class GameMap {
private Location tiberius;
public GameMap() {
//Creating Locations
tiberius = new Location("Tiberius", 200);
tiberius.setDescription("You are in the city of Tiberius. There is a sword on the ground in front of you. You see a long street with high buildings and a castle.You see an exit to the south.");
Location desert = new Location("Desert", 170);
desert.setDescription("You are in hot dreary desert, surrounded by sand dunes and nothingness, you see an exit to the south.");
Location jerusalem = new Location("Jerusalem", 270);
jerusalem.setDescription("You are at battlefield of Jerusalem. You are in awe of your surroundings, you see an exit to the west.");
Location hattin = new Location("Hattin", 120);
hattin.setDescription("You are at battlefield of Hattin. You see the ruination of the battle and fallen comrades...You see an exit to the north.");
Location damascus = new Location("Damascus", 130);
damascus.setDescription("You are in Damascus. You see the some shady characters...you see an exit to the west.");
Location tripoli = new Location("Tripoli", 80);
tripoli.setDescription("You are in Tripoli. You see the some more shady characters...you see an exit to the north.");
Location antioch = new Location("Antioch", 60);
antioch.setDescription("You are in the city of Antioch. You see a long street with high buildings and a castle.. You see the some more shady characters...you see an exit to the north.");
Location sis = new Location("Sis", 100);
sis.setDescription("You are in the city of Sis....exit ahead in the west.");
Location tarsus = new Location("Tarsus", 20);
tarsus.setDescription("You are in the city of Tarsus. ...you see an exit to the south.");
Location cyprus = new Location("Cyprus", 0);
cyprus.setDescription("You have reached the Byzantine Empire, your quest has finished!");
cyprus.setGoalLocation(true);
//Adding child locations
tiberius.addChildLocation(desert, 105);
desert.addChildLocation(jerusalem, 105);
jerusalem.addChildLocation(hattin, 323);
hattin.addChildLocation(damascus, 121);
damascus.addChildLocation(tripoli, 121);
tripoli.addChildLocation(antioch, 220);
antioch.addChildLocation(sis, 126);
sis.addChildLocation(tarsus, 121);
tarsus.addChildLocation(cyprus, 126);
}
public Location getStartNode(){
System.out.println(tiberius.toString());
return tiberius;
}
}
Brian, get rid of this field from Location:
Map<Location,Integer> children;
Replace it with two fields.
Location next;
int goalDistance;
Then, in your game controller, keep a reference to the current location of the character.
For example:
Location currentLoc = tiberius;
Then, each time move() is called, just say
currentLoc = currentLoc.next;
I think you're saying you want a method on the Location class called next() that will return the next location. So why not just do this?
public Location next() {
Location nextLocation = null;
for (Location child : children.keySet()) {
nextLocation = child;
break;
}
return nextLocation;
}
This is based on your assertion that there will only ever be one entry in the children Map, of course. If this ever changes in future, you could add a test (of unknown design at this point) that the child is the one you want:
public Location next() {
Location nextLocation = null;
for (Location child : children.keySet()) {
if (isCorrectChild(child)) {
nextLocation = child;
break;
}
}
return nextLocation;
}
Trying to implement a LinkedList that simulates a Portfolio, consisting of Stock objects. I'm struggling to figure out how to properly iterate through the list and check if each stock contains certain parameters. the SHAREPRICE method is the one I'm having trouble with specifically, if someone could help with that, I'd be very grateful. What I have so far:
import java.util.*;
public class Portfolio<AnyType> implements Iterable<AnyType> {
public int balance, shares;
private Stock<AnyType> beginMarker, endMarker, temp;
LinkedList<Stock> Portfolio = new LinkedList<Stock>();
java.util.Iterator<Stock> iter = Portfolio.iterator();
public int CASHIN(int x) {
balance = x;
return balance;
}
public int CASHOUT(int y) {
balance = balance + (-y);
return balance;
}
public int CASHBALANCE() {
return balance;
}
public void BUY(String t, int s, float pp) {
temp = new Stock<AnyType>(t, s, pp, pp, 0, null, null);
Portfolio.add(temp);
shares = shares + s;
}
public void SELL(String t, int s, float pp) {
shares = shares - s;
}
public void SHAREPRICE(String t, float pp)
{
if(Portfolio.contains(Stock.)
{
}
}
public void QUERY(String t) {
}
public int COUNTPORTFOLIO() {
return shares;
}
public void PRINTPORTFOLIO() {
}
public java.util.Iterator<AnyType> iterator() {
return new Iterator();
}
private class Iterator implements java.util.Iterator<AnyType> {
private Stock<AnyType> current = beginMarker.next;
private boolean okToRemove = false;
public boolean hasNext() {
return current != endMarker;
}
public AnyType next() {
if (!hasNext())
throw new java.util.NoSuchElementException();
AnyType nextItem = (AnyType) current.getTicker();
current = current.next;
okToRemove = true;
return nextItem;
}
public void remove() {
if (!okToRemove)
throw new IllegalStateException();
Portfolio.this.remove(current.prev);
okToRemove = false;
}
}
private class Stock<AnyType> implements Comparable<Stock<AnyType>> {
public String getTicker() {
return ticker;
}
public void setTicker(String ticker) {
this.ticker = ticker;
}
public float getPurchasePrice() {
return purchasePrice;
}
public void setPurchasePrice(float purchasePrice) {
this.purchasePrice = purchasePrice;
}
public float getLatestPrice() {
return latestPrice;
}
public void setLatestPrice(float latestPrice) {
this.latestPrice = latestPrice;
}
public float getPctChange() {
return pctChange;
}
String ticker;
int sharesOwned;
float purchasePrice, latestPrice;
float pctChange = (latestPrice - purchasePrice) / purchasePrice;
Stock<AnyType> prev, next;
public Stock(String ticker, int sharesOwned, float purchasePrice,
float latestPrice, float pctChange, Stock<AnyType> prev,
Stock<AnyType> next) {
this.ticker = ticker;
this.sharesOwned = sharesOwned;
this.purchasePrice = purchasePrice;
this.latestPrice = latestPrice;
this.pctChange = pctChange;
this.prev = prev;
this.next = next;
}
public int compareTo(Stock<AnyType> pctChange) {
return ((Comparable) this.pctChange)
.compareTo(Stock.getPctChange());
}
}
}
class TestPortfolio {
public static void main(String[] args) {
}
}
Forward Direction:
while(itr.hasNext())
{
System.out.println(itr.next());
}
Reverse Direction
while(itr.hasPrevious())
System.out.println(itr.previous());
}