We are making a simple rpg game. Right now we have a class called battleground, where the player can fight monsters. We use a random generator to pick out a random monster when we start the fight. In the terminal/main method, we have commands like "attack" and "run", that will either do damage to the random monster, or make the player leave/quit the game. Right now, we are trying to add a command called "attack scariest", which will let the player fight against the hardest monster with the most damage(there are three to choose from in our main). We need a method to choose a specific object from the ArrayList monsters, based on damage. Does anyone have tips on how we do that?
This is our code in the Battleground class that starts the game:
public void startBattle() {
printWelcomeMessage();
boolean finished = false;
this.currentMonster = getRandomMonster();
if(this.currentMonster == null) {
return;
}
System.out.println("A random monster is chosen for you. Prepare to meet the mighty " + this.currentMonster.getName());
System.out.println("\n-------- Player Stats ---------");
System.out.println(this.player);
while(!finished && monsters.size() > 0) {
ArrayList<String> commands = reader.getInput();
if(isValidCommand(commands)) {
if(commands.contains("quit") && !this.currentMonster.isDead()){
System.out.println("You can't quit the game in the middle of a fight!");
}else if(commands.contains("quit") && this.currentMonster.isDead()) {
finished = true;
System.out.println();
printFinalStats();
System.out.println();
System.out.println("You have left the arena, and the game has ended.");
System.out.println();
}
if(commands.contains("run")) {
finished = true;
System.out.println("You are a coward and you lose 50 gold pieces...\n");
this.player.changeGold(-50);
printFinalStats();
System.out.println("\nThanks for playing...");
}else if(commands.contains("drink") && !this.currentMonster.isDead()){
Potion potion = (Potion) player.findItem(commands.get(1));
player.drinkPotion(potion);
}else if(commands.contains("equip") && !this.currentMonster.isDead()){
Weapons weapon = (Weapons) player.findItem(commands.get(1));
player.useWeapon(weapon);
} else if(commands.contains("attack") && !this.currentMonster.isDead()) {
if(this.player.attack(this.currentMonster)) {
playerWon();
if(this.monsters.size() > 0) {
System.out.println("\nThere are " + this.monsters.size() + " more monsters to beat\nType \"attack\" if you want to attack another monster, or \"quit\" if you want to end the game.");
} else {
System.out.println("\n\n#### Congratulations ####\nYou have beaten every single monster in the game. You are a true champion!");
printFinalStats();
finished = true;
}
} else if(this.currentMonster.attack(this.player)) {
printLosingMessage();
finished = true;
}
} else if(commands.contains("attack") && this.currentMonster.isDead() && this.monsters.size() > 0) {
this.currentMonster = getRandomMonster();
printContinueMessage(this.player, this.currentMonster);
this.player.changeHealth(50);
}
} else {
System.out.println("Please write a valid command. Valid commands are:");
printCommands();
}
}
}
This is the ArrayList of monsters in the main class:
Monster beelzebub = new Monster("Beelzebub", 60);
Monster witch = new Monster("Witch", 40);
Monster ogre = new Monster("Ogre", 80);
ArrayList<Monster> monsters = new ArrayList<>();
monsters.add(beelzebub);
monsters.add(witch);
monsters.add(ogre);
Battleground battleground = new Battleground(monsters, player, reader);
battleground.startBattle();
We appreciate any help!
Replace the ArrayList with a SortedSet or a PriorityQueue. Implement a Comparator for Monster class. Then just pick the first element of the monsters collection.
I can't see your Monster class but I'm assuming the second variable to the constructor is the 'damage level'? If not, ideally this should be something that belongs to each monster so you should be setting it somewhere.
So you have the array Monsters which has all the monsters with various levels of damage already. There are a lot of ways you could do this, but a simple way (given you only have 3 monsters) is to just iterate over your monsters and keep track of the monster with the highest damage, and then return that monster.
For example:
Monster findHardestMonster(ArrayList<Monster> monsters)
{
//Set to the first monster in the list ASSUMING you have
//at least one monster
Monster highestDamageMonster = monsters.get(0);
//Go through every monster in your array
for (Monster monster : monsters)
{
//record the highest so far
if(monster.getDamage() > highestDamageMonster.getDamage())
highestDamageMonster = monster;
}
}
//return it
return highestDamageMonster;
}
If you plan on removing monsters frequently (say, when they're defeated), it might be worth as another poster suggested to use a priority queue or some sort of ordered collection whereby the ordering is based on damage level instead. Then you won't have to iterate over the monsters every time to find the one with max damage.
for(int i=0;i<monsters.size()-1;i++){
Monster m=monsters.get(i);
Monster m2=monsters.get(i+1);
if(m.getDamage()<m2.getDamage()){
Monster rightMonster=m2;
}else{
Monster rightMonster=m;
}
}
This should work if i am not mistaken. i havent tried the code but maybe it gives you hints
The stream operations you can perform on the list will let you do this easily, by using max with a Comparator that ranks the monsters according to damage.
Comparator<Monster> orderByDamage =
(m1, m2) -> m1.getDamage() < m2.getDamage() ? -1
: m1.getDamage() == m2.getDamage() ? 0 : 1;
What this does is compare the damage of two monsters (m1 and m2). If the damage of m1 is less than that of m2, a negative number is returned. If they are equal, zero is returned and if m1 has more damage than m2, a positive number is returned.
Note: if getDamage() returns an Integer and not an int, replace m1.getDamage() == m2.getDamage() with Objects.equals(m1.getDamage(), m2.getDamage()).
Use this with your list to get the monster with the most damage:
Optional<Monster> scariest = monsters.stream().max(orderByDamage);
Note the return type, which is Optional<Monster>. If the list is not empty, the Optional will contain the scariest monster; if the list is empty, the optional will be empty - this will help avoid a NullPointerException if all monsters have been removed.
scariest.ifPresent(monster -> /* do something to the monster */);
You can also use this approach to get the monster with the least damage:
Optional<Monster> leastScary = monsters.stream().min(orderByDamage);
Related
I'm struggling with dealing of inventory scan for my game, it basically search for the user inventory if "Flying Broom" if present(it was collected in another method and upload the code is too long), if not it will run the method challengedragon() again; else, it will proceed to the next challenge if the item is present.I was think of inserting method as parameter but it is not possible. This is what I have now. :
public class Main {
String Flyingbroom = "Flying broom";
public static void main(String[] args) {
Player_inventory p = new Player_inventory();
challengedragon();
}
public void challengedragon() {
System.out.println("a Hungarian Horntail dragon! Let's start the battle! You have four options to beat the dragon: ");
System.out.println("1: Fly away with your broom");
System.out.println("2: Fight the dragon");
System.out.println("3: Just run to the egg and get it");
System.out.println("4: Hide behind a rock");
System.out.println("5: Go back to Hogwart");
System.out.println("Your choice is: ");
Scanner in = new Scanner(System.in);
int dragonfightchoice = in .nextInt();
if (dragonfightchoice == 1) {
{
p.Scanitem(Flyingbroom,
"Good choice! You managed to kill the Hungarian Horntail dragon and to get the golden egg",
"You dont have the broom. Try to search for the broom",
playerHP);
proceedtonextchallengelake();
} else if (dragonfightchoice == 2) {
System.out.println("The Hungarian Horntail dragon fired you. - 70HP. ");
playerHP -= 70;
challengedragon();
} else if (dragonfightchoice == 3) {
System.out.println("Bad idea... You lose 100 HP");
playerHP -= 100;
challengedragon();
} else if (dragonfightchoice == 4) {
System.out.println("The dragon found you. You lose 30 HP");
playerHP -= 30;
challengedragon();
} else if (dragonfightchoice == 5) {
Hogwart();
} else {
invalid();
challengedragon();
}
}
For my inventory class:
public void Scanitem(String item, String trueouputext, String textifconditionisnotmet) {
if (inv.contains(item) == true) {
System.out.println(trueouputext);
} else if (inv.contains(item) == false) {
System.out.println(textifconditionisnotmet);
}
public static ArrayList<String> inv = new ArrayList<String>();
Do you guys have any recommendation?
Are there additional steps to populate the inventory (variable inv)?
Also, wouldn't you want ScanItem to answer true or false, depending on whether the item was found? Then you would have something like this:
public boolean scanitem(String item) {
return ( inv.contains(item) );
}
if ( p.scanItem(flyingBroom) ) {
System.out.println("Good choice! You managed to kill the Hungarian Horntail dragon and to get the golden egg");
} else {
System.out.println("You dont have the broom. Try to search for the broom");
}
That will get you closer to what you want. However, there are two other issues which you'll need to put into your code:
You will need a loop of some sort, instead of calling challengeDragon from inside of itself.
Somehow, the return value from scanItem must be used to decide whether to loop.
Currently, you do a nested call of a method each time the player does something, this means that sooner or later you'll run out of the stack. A better idea for the framework for your text-based adventure is to have some kind of a description of the current game's state. The state could be represented as an object that contains the following information:
where's the player currently at (on which step, at which "crossing" etc.)
the player's stats (HP, available skills etc.)
the contents of the player's inventory
some previously made choices affecting the game
Then, the code could be written as a simple loop that does the following:
process player's input
change the state according to the player's input
present the player with available options according to the new state
wait for the next input
repeat
In the land of Puzzlevania, Aaron, Bob, and Charlie had an argument over which
one of them was the greatest puzzler of all time.
To end the argument once and
for all, they agreed on a duel to the death.
Aaron was a poor shooter and only hit
his target with a probability of 1>3.
Bob was a bit better and hit his target with a
probability of 1>2.
Charlie was an expert marksman and never missed. A hit means
a kill and the person hit drops out of the duel.
To compensate for the inequities in their marksmanship skills, the three decided
that they would fire in turns, starting with Aaron, followed by Bob, and then by
Charlie. The cycle would repeat until there was one man standing, and that man
would be the Greatest Puzzler of All Time.
An obvious and reasonable strategy is for each man to shoot at the most accurate
shooter still alive, on the grounds that this shooter is the deadliest and has the best
chance of hitting back.Write a program to simulate the duel using this strategy.
Your program should use
random numbers and the probabilities given in the problem to determine whether
a shooter hits the target.
Create a class named Duelist that contains the dueler’s
name and shooting accuracy, a Boolean indicating whether the dueler is still alive,
and a method ShootAtTarget ( Duelist target ) that sets the target to dead if
the dueler hits his target (using a random number and the shooting accuracy) and
does nothing otherwise.
Once you can simulate a single duel, add a loop to your program that simulates
10,000 duels. Count the number of times that each contestant wins and print the
probability of winning for each contestant (e.g., for Aaron your program might
output “Aaron won 3,595>10,000 duels or 35.95%”).
An alternate strategy is for Aaron to intentionally miss on his first shot. Modify the
program to accommodate this new strategy and output the probability of winning
for each contestant.
Which strategy is better for Aaron: to intentionally miss on the
first shot or to try and hit the best shooter? Who has the best chance of winning,
the best shooter or the worst shooter?
Ok so that the problem. Here is my code so far:
public class Duelist {
private String name;
private double probabilityOfHitting;
private boolean alive = true;
//Only declared instance variables. Must created setters and getters
public void setName(String newName){
name = newName;
}
//name setter created
public void setProbabilityOfHitting( double newProbabilityOfHitting){
probabilityOfHitting = newProbabilityOfHitting;
}
//probability of hitting setter created
public void setAlive(boolean newAlive){
alive = newAlive;
}
//name setter created
//now must create getters
public String getName(){
return name;
}
//created the name getter
public double getProbabilityOfHitting(){
return probabilityOfHitting;
}
//created the probability of hitting getter
public boolean getAlive(){
return alive;
}
//created the alive getter
//no constructors created before
public Duelist(String tempName, double tempProbability){
name = tempName;
probabilityOfHitting = tempProbability;
}
//constructor is now created
//need to create a method for the duelists to shoot at each other
public void shootAtTarget(Duelist target){
double randomNum = Math.random();
if (this.probabilityOfHitting ==1){
target.setAlive(false);
target.getAlive();
}
else if (randomNum <= this.probabilityOfHitting){
target.setAlive(false);
target.getAlive();
}
else {
target.getAlive();
}
}
}
public class Tester {
public static void main(String[] args) {
int winsA = 0;
int winsB = 0;
int winsC = 0;
Duelist aaron = new Duelist("Aaron",(1/3));
Duelist bob = new Duelist("Bob", (1/2));
Duelist charlie = new Duelist("Charlie", 1);
if(aaron.getAlive() == true){
if(charlie.getAlive()== true){
aaron.shootAtTarget(charlie);
}
else if(bob.getAlive() == true){
aaron.shootAtTarget(bob);
}
else{
winsA++;
}
}
else if(bob.getAlive() == true){
if(charlie.getAlive() == true){
bob.shootAtTarget(charlie);
}
else if(aaron.getAlive() == true){
bob.shootAtTarget(aaron);
}
else{
winsB++;
}
}
else{
if (bob.getAlive() == true){
charlie.shootAtTarget(bob);
}
else if(aaron.getAlive() == true){
charlie.shootAtTarget(aaron);
}
else{
winsC++;
}
}
System.out.println(winsA);
System.out.println(winsB);
System.out.println(winsC);
}
}
I know I haven't gotten close to finishing the problem yet. What I did in my tester class was to try and simulate one duel and once when I simulated one duel, I would be able to loop it so I can simulate more. The problem I'm having is that the when I run the code, the wins for Aaron, Bob, and Charlie all come up to 0 and I don't know why.
As the last parameter in the constructor calls, you wrote
Duelist aaron = new Duelist("Aaron",(1/3));
There you are dividing an int by another int, and the result will be 0 in this case. This has to be changed to
Duelist aaron = new Duelist("Aaron",(1.0/3.0));
so that double values are used (and the result will be 0.3333, as desired).
Most of your Duelist class does not seem to be "wrong", but the shootAtTarget method could be improved.
A general hint: I'd recommend you to never use Math.random(). This will deliver unpredictable results. Instead, you should use an instance of java.util.Random. This can be initialized with a certain random seed, so that it always provides the same sequence of random numbers. This makes debugging much easier.
Additonally, some tests have been redundant. When the probabilityOfHitting is 1.0, then there is no special test required: The random number will always be less-than-or-equal to 1.0. You are also occasionally calling target.getAlive() for no apparent reason.
So in the end, the method could look like this:
private static Random random = new Random(0);
//need to create a method for the duelists to shoot at each other
public void shootAtTarget(Duelist target)
{
double randomNum = random.nextDouble();
if (randomNum <= this.probabilityOfHitting)
{
target.setAlive(false);
}
}
However, the main problem was in your Test class. I'm not sure about general recommendations here. One could go very far in terms of abstraction. (A Java Enterprise Architect would probably end up with writing a AbstractDuelistStrategyFactory somewhere...). But to put it simply: At the moment, you are doing at most one shot. After one shot, nobody can have won. And you don't know how many shots have to be taken before there is only one duelist remaining.
Much of this could be made more elegant and flexible if you placed the Duelists into a List<Duelist>. But without that, an approach that is "structurally close to what you started" could look like this:
int alive = 3;
while (alive > 1)
{
System.out.println("Status: A:"+aaron.getAlive()+" B:"+bob.getAlive()+" C:"+charlie.getAlive());
if (aaron.getAlive())
{
if(charlie.getAlive())
{
System.out.println("A shoots at C");
aaron.shootAtTarget(charlie);
if (!charlie.getAlive())
{
System.out.println("A killed C");
alive--;
}
}
else if(bob.getAlive())
{
System.out.println("A shoots at B");
aaron.shootAtTarget(bob);
if (!bob.getAlive())
{
System.out.println("A killed B");
alive--;
}
}
}
// Other cases ...
}
if (aaron.getAlive())
{
winsA++;
}
if (bob.getAlive())
{
winsB++;
}
if (charlie.getAlive())
{
winsC++;
}
(Note that there are still cases missing!)
I have a text based game that I am making. It is a RPG style where the user is given options linked to numbers and they have to choose a number. Now my problem is that when running the program. A certain method, Decision(), only works certain times. The method is in a superClass while it is being called in the subclass. in the subclass, It works the first time, but not necessarily the second. Also, when I copy the decision method from the superclass into the subclass its starts working, but the next time it is called, it stops. Here is what I've tried and the results. I've included the decision method and where it is being called.
Decision Method:
public int decision(String question, int length, String[] choices){
int[] numbers = new int[length];
int iterator = 1;
for(int i = 0; i < length; i++){
numbers[i] = iterator;
iterator++;
}
boolean done = false;
while(!done){
//print("Test");
print("");
print(question);
String options = "";
for(int i = 0; i < numbers.length; i++){
options = (options + numbers[i] + " - " + choices[i] + " ");
}
print(options);
boolean univSet = true;
int entry = 1;
while(univSet){
if(univInt != 0){
univSet = false;
entry = univInt;
univInt = 0;
//print("testing");
}
}
if(entry == 23){
help();
}else{
for(int i = 0; i < numbers.length; i++){
if(entry == numbers[i]){
done = true;
univInt = 0;
return entry;
}
}
print("Invalid Number, Try again");
print("");
univInt = 0;
}
}
return (Integer) null;
}
Chapter1 Class (Where it's being called:
public class Chapter1 extends Story implements Serializable {
Player player;
public Chapter1(Player player){
this.player = player;
}
public void engage() {
// TODO Auto-generated method stub
player.chapter = 1;
save(player.name);
sPrint("Welcome to Chapter 1");
print("You wake up in a lighted room with white walls.\nA fresh breeze is coming through the window yet the air smells rotten.");
print("You jolt up suddenly. You don't remember anything about how you got here. You've even forgotten who you are.");
print("You look down at your white shirt, there is a streak of blood across the top.\nYou are wearing a nametag that says: " + player.name + ".");
print("You're sitting in a chair but there are no restraints. You decide to get up and look around");
cur = decision("What do you do?", 2, new String[]{"Try the door", "Look out the window"});
print(cur + "");
if(cur == 1){
print("You walk over to the door and try and open it, it is unlocked.\nYou walk through and are welcomed by a cold and poorly lit hallway");
}else{
print("You walk to the window and look outside. You see a huge barren field. You can make out a humanoid like structure.\nYou call out yet the figure doesn't move.");
print("You decide to try the door. It's unlocked so you walk through into a cold dimly lit hallway.");
}
print("You see a dull knife on the floor as well as a door on the end of the hallway");
cur = decision("What do you do?", 2, new String[]{"Go to the door", "Take the knife"});
if(cur == 2){
print("You pick up the knife.");
addWeapon("Kitchen Knife", player);
}else{
print("You walk down the hallway to the door when suddenly the door opens and out comes a zombie.\nIt Lunges for your shoulder. You are caught by surprise and it bites into your skin and you are infected");
gameOver();
}
print("You continue to walk down the hall when suddenly a hideous creature lunges out from the door.\nYou jump back and prepare yourself for a battle.");
battle("Zombie", 5, 2, player);
sPrint("I see that you have succeeded in your first encounter with the undead.\nI congratulate you but you have a long way to go. Remember, I am your only way to learning about your past. \nNow, make your way down to the bottom of the tower. I will help you where I see fit along the way.");
print("You look around and see that the lights have brightened up. The zombie has been mutilated by your Kitchen Knife. \nYou don't know where the voice came from but you are scared. Behind the zombie's original hiding spot you see a staircase.\nYou follow it down, onto what seems to be..the 11th floor.");
print("");
print("Please input 'complete' to continue");
pause();
sPrint("Chapter 1 complete");
}
Now in this class, engage() is being called to run this chapter. And decision is being called where you see it, as well as in the battle() method(the battle method loops a couple times and decision() is called every loop.
Originally, both Decision and battle are in the superclass, but not in the sub class. This results in the first decision method in the class to be called, but not the second. In the second, it stops at the loop checking the value of univInt.
When I put the decision method into the sub class, It passes the first two but it fails to get past the first one in the battle method for the same reason.
When I put both the decision and battle method into the sub class, it has the same result as just putting decision.
Finally if I put battle in the sub class but not decision it only passes the first two again.
In the project I have one variable named cur that holds the integer value of whatever decision returns. I reuse it for every decision. I don't know if that has anything to do with it. This really doesn't make sense to me how whether the methods are in the same class, or inherited would matter at all if they are the same method.
I am ready to clarify anything and I hope someone is able to understand what is going wrong.
EDIT:
univInt is being set to another number other than 0 outside of decision. thats why it works some times. It is a swing class and a method in a superclass sets univInt to whatever is in a TextField when a button is pressed so with that while loop I try to constantly check to see univInt has been changed from 0
It seems like your "univInt" is a class member, not a local variable, and you do not reinitialize it when entering the function. Thus it won't be changed back to allow the program to enter the if-statement you mention.
I dont know why but whenever you or the computer gets a hit in my game, the grids both get updated.
The player and computer grids are multidimensional arrays of '-' chars and when you get a hit it changes to 'x'. In the game loop, their is a player grid and computer grid and I update them each seperately at different times but when they get printed their both the same. Can someone help? Sorry I'm new to programming
public class Game{
public static void main(String[] args){
Grid grid = new Grid();
Computer computer = new Computer();
Player player = new Player();
String playerGuess;
player.setPlayerShips();
computer.setComputerShips();
char[][] playerGrid= Grid.gridArray;
char[][] computerGrid = Grid.gridArray;
System.out.println("Welcome to BATTLESHIP");
System.out.println("You are to sink your opponents 3 ships, each 3 units in length.");
System.out.println("The ships can be both vertical and horizontal.");
System.out.println("Enter your coordinate guess in the form A1, B5, F6, etc.");
System.out.println("Since the grid is 7x7, coordinates go from A1-G7.");
System.out.println("Letters are vertical, numbers are horizontal.");
System.out.println("You will also have 3 ships placed randomly, which the computer will also try to guess.");
System.out.println("During the game, enter exit if you would like to quit.");
System.out.println();
while(true){
System.out.println("Your Grid");
grid.printGrid(playerGrid);
System.out.println("Opponent's Grid");
grid.printGrid(computerGrid);
System.out.println();
playerGuess=player.getGuess();
if(playerGuess.equals("exit")){
break;
}else{
playerGuess=grid.convert(playerGuess);
}
player.setFirstCo(playerGuess);
player.setSecondCo(playerGuess);
System.out.println();
if(player.isHit(player.firstCo, player.secondCo)){
player.addHits(player.firstCo, player.secondCo);
System.out.println("Hit!");
System.out.println();
computerGrid=Grid.newGrid(computerGrid,player.firstCo,player.secondCo);
}else{
System.out.println("Miss.");
System.out.println();
}
if(player.hasWon()){
System.out.println("Congratulations, you have sunk all your opponents ships!");
break;
}
computer.guess=computer.getGuess();
computer.lastGuess=computer.guess;
if(computer.isHit(computer.guess[0],computer.guess[1])){
computer.addHits(computer.guess[0],computer.guess[1]);
System.out.println("Computer has hit!");
System.out.println();
playerGrid=grid.newGrid(playerGrid, computer.guess[0], computer.guess[1]);
if(computer.hasWon()){
System.out.println("Computer has sunk all your ships! You lose.");
break;
}
}else{
System.out.println("Computer has missed.");
System.out.println();
}
}
}
}
i got the grids to print separately but theres something wrong with my place ships method. Can someone take a look at it? It's suppose to choose random x,y coordinates(3 points for each ship) and do this for 3 ships. It places 4 points in a row sometimes and no other ships(I think the ships are just overlapping, but I tried to put a fix in). Anyways, thanks in advance if you can help.
//set player ships coordinates, can be numbers from 0-6
public static void setPlayerShips(){
int randX, randY;
int direction; //will be random int 0-1, determines direction ship will extend(up/down, left/right)
randX=(int)(Math.random()*7);
randY=(int)(Math.random()*7);
direction=(int)(Math.random()*2);
playerShip1[0]=randX;
playerShip1[1]=randY;
if(direction==0){//extend upwards or downwards 2 units(y values change, x stays the same)
playerShip1[2]=randX;
playerShip1[4]=randX;
if(randY>3){//if y value is greater than 3, has to extend down or it wont fit
playerShip1[3]=randY-1;
playerShip1[5]=randY-2;
}else if(randY<2){//if y value is less than 2, has to extend up or it wont fit
playerShip1[3]=randY+1;
playerShip1[5]=randY+2;
}else{//if direction doesnt matter, just extend upwards
playerShip1[3]=randY+1;
playerShip1[5]=randY+2;
}
}else if(direction==1){//extends left or right 2 units(y values stay the same, x changes)
playerShip1[3]=randY;
playerShip1[5]=randY;
if(randX>3){//if x is greater than 3, must extend left or it wont fit
playerShip1[2]=randX-1;
playerShip1[4]=randX-2;
}else if(randX<2){//if x is less than 2, must extend right or it wont fit
playerShip1[2]=randX+1;
playerShip1[4]=randX+2;
}else{//if direction doesnt matter, just extend right
playerShip1[2]=randX+1;
playerShip1[4]=randX+2;
}
}
//do same for both other ships, do quick checks to make sure original coordinates arent the same
do{
randX=(int)(Math.random()*7);
randY=(int)(Math.random()*7);
}while(randX==playerShip1[0] && randY==playerShip1[1]);
direction=(int)(Math.random()*2);
playerShip2[0]=randX;
playerShip2[1]=randY;
if(direction==0){
playerShip2[2]=randX;
playerShip2[4]=randX;
if(randY>3){
playerShip2[3]=randY-1;
playerShip2[5]=randY-2;
}else if(randY<2){
playerShip2[3]=randY+1;
playerShip2[5]=randY+2;
}else{
playerShip2[3]=randY+1;
playerShip2[5]=randY+2;
}
}else if(direction==1){
playerShip2[3]=randY;
playerShip2[5]=randY;
if(randX>3){
playerShip2[2]=randX-1;
playerShip2[4]=randX-2;
}else if(randX<2){
playerShip2[2]=randX+1;
playerShip2[4]=randX+2;
}else{
playerShip2[2]=randX+1;
playerShip2[4]=randX+2;
}
}
do{
randX=(int)(Math.random()*7);
randY=(int)(Math.random()*7);
}while((randX==playerShip1[0]&& randY==playerShip1[1])&&(randX==playerShip2[0] && randY==playerShip2[1]));
direction=(int)(Math.random()*2);
playerShip3[0]=randX;
playerShip3[1]=randY;
if(direction==0){
playerShip3[2]=randX;
playerShip3[4]=randX;
if(randY>3){
playerShip3[3]=randY-1;
playerShip3[5]=randY-2;
}else if(randY<2){
playerShip3[3]=randY+1;
playerShip3[5]=randY+2;
}else{
playerShip3[3]=randY+1;
playerShip3[5]=randY+2;
}
}else if(direction==1){
playerShip3[3]=randY;
playerShip3[5]=randY;
if(randX>3){
playerShip3[2]=randX-1;
playerShip3[4]=randX-2;
}else if(randX<2){
playerShip3[2]=randX+1;
playerShip3[4]=randX+2;
}else{
playerShip3[2]=randX+1;
playerShip3[4]=randX+2;
}
}
}
This is the problem:
char[][] playerGrid= Grid.gridArray;
char[][] computerGrid = Grid.gridArray;
You've only actually got a single char[][] object here. Both variables refer to the same object... any updates made to that object will be visible via both variables.
It looks like Grid.gridArray is actually a static variable, which is another problem. You almost certainly want to make it an instance variable... and then create two instances of Grid rather than just one.
Basically, I would take a step back and work out what an instance of Grid is meant to represent. Do you really need to expose the gridArray variable at all? Why can a grid not print itself?
I'm create an air traffic control system, where it generates a random amount of fuel and also a random amount of planes. I have these two elements done, however the issue is, in the output box it all shows and works perfectly. My issue is that I'm telling it, if there is no planes coming in to call the string no planes and if there is a plane then KLM. I can't get it to write to the main class with all the front end.
I've edited out some of the coding in the screen as I'm using Netbeans drag and drop front end:
enter public void StartSimulation()
{
Start pointer = new Start();
Plane incoming = new Plane();
//Needs a condition in here that checks if the plane and fuel has been
//Generated and also loop to keep up with the constant generated planes and fuel
jTextArea1.setText(incoming.planeName);
I have tried where the condition thing is the following:
if (incoming.nextPlaneLanding != 167) this generates the first thing over and over again in the output box. I've also tried setting a boolean in the plane class but again, it has had no effect even with the following condition around it. if (incoming.completed = true)
This is the stuff I have in my plane class:
class Plane
extends TimerTask
{
public int nextPlaneLoop = 0;
public int planes;
public int fuel;
public String planeName;
#Override
public void run()
{
if(nextPlaneLoop <=167)
{
//Currently only running 1 or 0 planes...
planes = (int) (Math.random()*((2-1)+1));
System.out.println("Random generated plane amount: "+planes);
System.out.println("Method called, one whole day loop");
//Adds to the plane in the airspace loop
nextPlaneLoop++;
System.out.println("Loop incrementing: "+nextPlaneLoop);
if(planes == 0)
{
System.out.println("No fuel is required as no planes are coming in");
planeName = "No incoming plane";
System.out.println("Planes name is: "+planeName);
System.out.println(" ");
}
else
{
//Amount of fuel
fuel = 30 + (int)(Math.random()*((120-30)+1));
System.out.println("Random fuel: "+fuel);
planeName = "KLM AirFrance";
System.out.println("Planes name is: "+planeName);
System.out.println(" ");
}
}
else
{
this.cancel();
System.out.println("Not in loop any more. End of day");
}
}
}
Can anyone suggest have to how to get the names to display on to the screen so I can then try and add them into a queue in the actual airport class.
I think the Observer pattern might work well for you. In Java, this is implemented via Observer and Observable.