Spigot 1.16.5 block growth rate x2 - java

#EventHandler
public void onGrow(BlockGrowEvent e) {
Block block = e.getBlock();
BlockData blockData = block.getBlockData();
if (Reference.groundCrop().contains(e.getBlock().getType())) {
int x = e.getBlock().getX();
int y = e.getBlock().getY();
int z = e.getBlock().getZ();
String cordinate = x+", "+y+", "+z;
if (config.get("chocked."+cordinate) != null) {
Ageable ageable = (Ageable) blockData;
int currentAge = ageable.getAge();
int newAge = Math.min(currentAge + 1, ageable.getMaximumAge());
ageable.setAge(newAge);
block.setBlockData(blockData);
}
}
}
public static List<Material> groundCrop() {
List<Material> groundCrops = new ArrayList<>();
groundCrops.add(Material.WHEAT);
groundCrops.add(Material.POTATOES);
groundCrops.add(Material.CARROTS);
groundCrops.add(Material.BEETROOTS);
return groundCrops;
}
Does nothing. It failed to change the age but without error. How can I make it multiply the growth to x2?

Related

How to use array of objects in this context?

Assuming that the array is populated with 20 shipments, calculate the total cost of local shipments in the array.
I tried to create a for loop and then call out the method calcCost() and += it to the variable local so it would save the values I guess
I'm pretty sure the way I wrote the code is wrong so if someone could help me with it that would be great!
package question;
public class TestShipment {
public static void main(String[] args) {
Shipment r1 = new Shipment(
new Parcel("scientific calculator " , 250),
new Address("Dubai","05512345678"),
new Address("Dubai","0505432123"),
"Salim"
);
System.out.println(r1);
Shipment[] arr = new Shipment[100];
arr[5] = r1;
Shipment[] a = new Shipment[20];
double local = 0;
for (int i = 0; i < a.length; i++) {
if (a[i].isLocalShipment()) {
System.out.println(a[i].calcCost());
}
}
}
}
public class Shipment {
public Parcel item;
private Address fromAddress;
private Address toAddress;
public String senderName;
public Shipment(Parcel i, Address f, Address t, String name) {
item = i;
fromAddress = f;
toAddress = t;
senderName = name;
}
//setter
public void setFromAddress(String c, String p) {
c = fromAddress.getCity();
p = fromAddress.getPhone();
}
public boolean isLocalShipment() {
boolean v = false;
if (fromAddress.getCity() == toAddress.getCity()) {
v = true;
} else {
v = false;
}
return v;
}
public double calcCost() {
double cost = 0;
if (fromAddress.getCity() == toAddress.getCity()) {
cost = 5;
} else {
cost = 15;
}
if(item.weight > 0 && item.weight <= 200) {
cost += 5.5;
}
if(item.weight > 200) {
cost += 10.5;
}
return cost = cost * (1 + 0.5); //fix the tax
}
public String toString() {
return "From: " + senderName + "\nTo: " + toAddress
+ "\nParcel: " + item.desc+item.weight + "\ncost: " + calcCost();
}
}

Calling function to set array in server and printing array in client

So I'm building the game battleship and I am using a 2d array for the board, but the problem is if I call the function to set the array, I have to call all other functions that use the array to get the same array, otherwise, it will just use a fresh new array. Right now I'm calling the setup function for the array inside the server, and when I call the function to print out the array to the GUI, it prints out a new array, any idea on how to fix this?
Server Class:
public class Server {
private static PrintWriter writerSocket;
private static BufferedReader buffedReader;
public static String player1shipHit;
Controller controller = Controller.returnController();
private static String sharedMessage;
int shipsLeftPlayer1 = 4;
int shipsLeftPlayer2 = 4;
public static String player2hit;
private static InputStreamReader readerSocket;
private final Object lock = new Object();
void waitForLock() {
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
void notifyLock() {
synchronized (lock) {
lock.notify();
}
}
public static void main(String[] args) throws IOException {
new Server().go();
}
void go() throws IOException {
ServerSocket server = new ServerSocket(5000);
Socket connectionOne = server.accept();
controller.player1.setUp(); //Setup
System.out.println("Server>> P1 connected");
writerSocket = new PrintWriter(connectionOne.getOutputStream());
writerSocket.println("Player1> Enter your guess in the format: X,Y");
writerSocket.flush();
new Thread(new JobOne(connectionOne)).start();
Socket connectionTwo = server.accept();
System.out.println("server>> P2 connected");
controller.player2.setUp();
writerSocket = new PrintWriter(connectionTwo.getOutputStream());
writerSocket.flush();
new Thread(new JobTwo(connectionTwo)).start();
}
private class JobOne implements Runnable {
Socket socket;
JobOne(Socket name) {
socket = name;
}
#Override
public void run() {
try {
readerSocket = new InputStreamReader(socket.getInputStream());
buffedReader = new BufferedReader(readerSocket);
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
Controller.state = false;
try {
sharedMessage = buffedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String[] coordinates = sharedMessage.split(",");
int x = Integer.parseInt(coordinates[0]);
int y = Integer.parseInt(coordinates[1]);
if (controller.player2.board.testHit(x, y)) {
controller.player1.board.updateBoard("Hit", x, y);
sharedMessage = "Player 2 has been hit!";
writerSocket.println(sharedMessage);
writerSocket.flush();
if (controller.player2.testShip("C", x, y)) {
sharedMessage = "Player 2's" + player1shipHit + " is Down";
shipsLeftPlayer2--;
if (shipsLeftPlayer2 == 0) {
sharedMessage = "Player 1 has won!";
}
}
} else if (!controller.player2.board.testHit(x, y)) {
sharedMessage = "Player 1 misses!";
}
try {
writerSocket = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
notifyLock();
writerSocket.println(sharedMessage);
writerSocket.flush();
waitForLock();
}
}
}
private class JobTwo implements Runnable {
Socket socket;
JobTwo(Socket name) {
socket = name;
}
#Override
public void run() {
try {
writerSocket = new PrintWriter((socket.getOutputStream()));
readerSocket = new InputStreamReader(socket.getInputStream());
buffedReader = new BufferedReader(readerSocket);
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
waitForLock();
writerSocket.println(sharedMessage);
writerSocket.flush();
while (true) {
Controller.state1 = false;
writerSocket.println("Player2> Enter the coordinates in the format X,Y:");
writerSocket.flush();
try {
sharedMessage = buffedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String[] coordinates = sharedMessage.split(",");
int x = Integer.parseInt(coordinates[0]);
int y = Integer.parseInt(coordinates[1]);
;
System.out.println("Player 2 X:" + x);
System.out.println("PLayer 2 Y:" + y);
Coordinate coordinate = new Coordinate(x, y);
if (controller.player1.board.testHit(x, y)) {
controller.player2.board.updateBoard("Hit", x, y);
sharedMessage = "Player 2 has a hit";
if (controller.player1.testShip(player2hit, x, y)) {
sharedMessage = "Player1s" + player2hit + "is down!" + 50;
shipsLeftPlayer1--;
if (shipsLeftPlayer1 == 0) {
sharedMessage = "PLayer 2 has won!";
}
}
} else {
controller.player2.board.updateBoard("Miss", x, y);
sharedMessage = "PLayer 2 has a miss.";
}
notifyLock();
}
}
}
}
}
Board class:
public class Board {
public int[][] board1 = null;
public int[][] board2;
public Board() {
board1 = new int[20][20];
board2 = new int[20][20];
}
public void updateBoard(String type, int x, int y) {
if (type.equals("hit")) {
board2[x][y] = 1;
} else if (type.equals("miss")) {
board2[x][y] = '0';
}
}
public boolean testHit(int x, int y) {
if (board1[x][y] == 1) {
board1[x][y] = 5;
System.out.println("Its a hit!");
return true;
} else {
System.out.println("It's a miss");
return false;
}
}
}
Player Class:
public class Player {
Destroyer destroyer;
Battleship battleship;
Submarine submarine;
Board board;
int[][] board1;
Turn turn;
int playerId;
boolean guiState;
Carrier carrier;
ArrayList<String> ships = new ArrayList<String>(4);
public Player(int playerIdSet){
board1 = new int[20][20];
playerId = playerIdSet;
board = new Board();
turn = new Turn();
ships.add("Carrier");
ships.add("Destroyer");
ships.add("Battleship");
ships.add("Submarine");
}
public void setSubmarine(Submarine subSet){
submarine = subSet;
}
public Submarine getSubmarine(){
return submarine;
}
public void setBattleship(Battleship battleshipSet) {
battleship = battleshipSet;
}
public Battleship getBattleship() {
return battleship;
}
public void setDestroyer(Destroyer destroyerSet) {
destroyer = destroyerSet;
}
public void setCarrier(Carrier carrierSet){
carrier = carrierSet;
}
public Carrier getCarrier(){
return carrier;
}
public Destroyer getDestroyer() {
return destroyer;
}
public Board getBoard(){
return board;
}
public void setUp(){
for (String ship : ships) {
int x;
int y;
switch (ship) {
case "Destroyer" -> {
x = (int) (Math.random() * (9) + 0);
y = (int) (Math.random() * (9) + 0);
if (board.board1[x][y] == 0) {
Destroyer destroyer = new Destroyer(x, y);
setDestroyer(destroyer);
getDestroyer().createShip(playerId);
} else {
x = (int) (Math.random() * (9) + 0);
y = (int) (Math.random() * (9) + 0);
}
}
case "Carrier" -> {
x = (int) (Math.random() * (9) + 1);
y = (int) (Math.random() * (9) + 1);
if (board.board1[x][y] == 0) {
Carrier carrier = new Carrier(x, y);
setCarrier(carrier);
getCarrier().createShip(playerId);
} else {
x = (int) (Math.random() * (9) + 0);
y = (int) (Math.random() * (9) + 0);
}
}
case "Battleship" -> {
x = (int) (Math.random() * (9) + 0);
y = (int) (Math.random() * (9) + 0);
if (board.board1[x][y] == 0) {
System.out.println("X:" + x);
System.out.println("Y:" + y);
Battleship battleship = new Battleship(x, y);
setBattleship(battleship);
getBattleship().createShip(playerId);
} else {
x = (int) (Math.random() * (9) + 0);
y = (int) (Math.random() * (9) + 0);
}
}
case "Submarine" -> {
x = (int) (Math.random() * (9) + 0);
y = (int) (Math.random() * (9) + 0);
if (board.board1[x][y] == 0) {
System.out.println("X:" + x);
System.out.println("Y:" + y);
Submarine submarine = new Submarine(x, y);
setSubmarine(submarine);
getSubmarine().createShip(playerId);
} else {
x = (int) (Math.random() * (9) + 0);
y = (int) (Math.random() * (9) + 0);
System.out.println("Error checking...\n");
}
}
}
}
}
public void printBoard(){
System.out.println("Attempting to print");
for(int x = 0; x < board.board1.length; x++) {
for (int y =0; y < board.board1[x].length; y++){
System.out.println(board.board1[x][y]);
}
}
}
public void displayBoard(GUIController guiController) {
StringBuilder grid = new StringBuilder();
StringBuilder grid1 = new StringBuilder();
for(int x = 0; x < board.board1.length; x++) {
grid.append(x);
for (int y =0; y < board.board1[x].length; y++){
grid.append("[").append(board.board1[x][y]).append("]");
grid.append(" ");
}
grid.append("\n");
}
guiController.gui.board1Area.setText(String.valueOf(grid));
for(int i =0; i < board.board2.length; i++){
for(int j =0; j < board.board2.length; j++){
grid1.append("[").append(board.board2[i][j]).append("]");
grid.append(" ");
}
grid1.append("\n");
}
guiController.gui.board2Area.setText(String.valueOf(grid1));
}
public boolean testShip(String ship,int row, int col){
switch (ship){
case "Battleship" -> {
for (int[] ints : battleship.battleShipArray) {
for (int anInt : ints) {
return anInt == battleship.battleShipArray[row][col];
}
}
}
case "Carrier" -> {
for (int[] ints : carrier.carrierArray) {
for (int anInt : ints) {
return anInt == carrier.carrierArray[row][col];
}
}
}
case "Submarine" -> {
for (int[] ints : submarine.submarineArray) {
for (int anInt : ints) {
return anInt == submarine.submarineArray[row][col];
}
}
}
case "Destroyer" -> {
for (int[] ints : destroyer.destroyerArray) {
for (int anInt : ints) {
return anInt == destroyer.destroyerArray[row][col];
}
}
}
}
return false;
}
void markShipHit(int x, int y){
for(String ship : ships){
switch(ship){
/*case "Carrier" -> {
if(carrier.testHit(1,x,y)){
carrier.carrierArray[x][y] = 0;
Server.player1shipHit = "Carrier";
}
}*/
case "Battleship" -> {
if(battleship.testHit(1,x,y)){
battleship.battleShipArray[x][y] = 0;
Server.player1shipHit="Battleship";
}
}
case "Destroyer" ->{
if(destroyer.testHit(1,x,y)){
destroyer.destroyerArray[x][y] = 0;
Server.player1shipHit="Destroyer";
}
}
case "Submarine" ->{
if(submarine.testHit(1,x,y)){
submarine.submarineArray[x][y] = 0;
Server.player1shipHit="Submarine";
}
}
}
}
}
}
Client example:
public class PlayerOne {
Socket socket;
InputStreamReader readerSocket;
PrintWriter writerSocket;
BufferedReader bufferedReader;
public static String input;
GUIController guiController;
boolean state = true;
Controller controller = Controller.returnController();
boolean setupState = false;
public static void main(String[] args){
new PlayerOne().go();
}
private void go(){
guiController = new GUIController();
try {
socket = new Socket("127.0.0.1", 5000);
receiveRead();
while(true) {
if (Controller.state) {
writeSend();
Controller.state = false;
} else {
receiveRead();
Controller.state = true;
}
}
}catch (IOException e){
e.printStackTrace();
}
}
void writeSend()throws IOException {
while (input == null) {
input = guiController.inputLine;
}
writerSocket = new PrintWriter(socket.getOutputStream());
writerSocket.println(input);
writerSocket.flush();
controller.player1.displayBoard(guiController);
}
void receiveRead () throws IOException {
readerSocket = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(readerSocket);
String line = bufferedReader.readLine();
guiController.gui.setOutputText(line);
controller.player1.displayBoard(guiController);
}
}

Java - The method getValue() is undefined for the type Object

I'm having this error:
The method getValue() is undefined for the type Object
*This is the code in error: In the line:
final String materialName = BasePlugin.getPlugin().getItemDb().getName(new ItemStack(((Object) ((Map)dataMap).entrySet().iterator().next()).getValue().getItemType(), 1));
Complete Code
public class LandMap
{
private static final int FACTION_MAP_RADIUS_BLOCKS = 22;
private static final Material[] BLACKLISK;
#SuppressWarnings("rawtypes")
public static boolean updateMap(final Player player, final HCF plugin, final VisualType visualType, final boolean inform) {
final Location location = player.getLocation();
final World world = player.getWorld();
final int locationX = location.getBlockX();
final int locationZ = location.getBlockZ();
final int minimumX = locationX - 22;
final int minimumZ = locationZ - 22;
final int maximumX = locationX + 22;
final int maximumZ = locationZ + 22;
final Set<Claim> board = new LinkedHashSet<Claim>();
boolean subclaimBased;
if (visualType == VisualType.SUBCLAIM_MAP) {
subclaimBased = true;
}
else {
if (visualType != VisualType.CLAIM_MAP) {
player.sendMessage(ConfigurationService.RED + "Not supported: " + visualType.name().toLowerCase() + '.');
return false;
}
subclaimBased = false;
}
for (int x = minimumX; x <= maximumX; ++x) {
for (int z = minimumZ; z <= maximumZ; ++z) {
final Claim claim = plugin.getFactionManager().getClaimAt(world, x, z);
if (claim != null) {
if (subclaimBased) {
board.addAll(claim.getSubclaims());
}
else {
board.add(claim);
}
}
}
}
if (board.isEmpty()) {
player.sendMessage(ConfigurationService.RED + "No claims are in your visual range to display.");
return false;
}
for (final Claim claim2 : board) {
if (claim2 == null) {
continue;
}
final int maxHeight = Math.min(world.getMaxHeight(), 256);
final Location[] corners = claim2.getCornerLocations();
final List<MemoryBlockLocation> shown = new ArrayList<MemoryBlockLocation>(maxHeight * corners.length);
for (final Location corner : corners) {
for (int y = 0; y < maxHeight; ++y) {
shown.add(new MemoryBlockLocation(world, corner.getBlockX(), y, corner.getBlockZ()));
}
}
final Object dataMap = plugin.getVisualiseHandler().generate(player, shown, visualType, true);
if (((Map)dataMap).isEmpty()) {
continue;
}
final String materialName = BasePlugin.getPlugin().getItemDb().getName(new ItemStack(((Object) ((Map)dataMap).entrySet().iterator().next()).getValue().getItemType(), 1));
if (!inform || claim2.getFaction() == null) {
continue;
}
player.sendMessage(ConfigurationService.YELLOW + claim2.getFaction().getDisplayName((CommandSender)player) + ConfigurationService.YELLOW + " owns land " + ConfigurationService.GRAY + " (displayed with " + materialName + ")" + ConfigurationService.YELLOW + '.');
}
return true;
}
public static Location getNearestSafePosition(final Player player, final Location origin, final int searchRadius) {
return getNearestSafePosition(player, origin, searchRadius, false);
}
public static Location getNearestSafePosition(final Player player, final Location origin, final int searchRadius, final boolean stuck) {
final FactionManager factionManager = HCF.getPlugin().getFactionManager();
final Faction playerFaction = factionManager.getPlayerFaction(player.getUniqueId());
final int max = ConfigurationService.BORDER_SIZES.get(origin.getWorld().getEnvironment());
final int originalX = Math.max(Math.min(origin.getBlockX(), max), -max);
final int originalZ = Math.max(Math.min(origin.getBlockZ(), max), -max);
final int minX = Math.max(originalX - searchRadius, -max) - originalX;
final int maxX = Math.min(originalX + searchRadius, max) - originalX;
final int minZ = Math.max(originalZ - searchRadius, -max) - originalZ;
final int maxZ = Math.min(originalZ + searchRadius, max) - originalZ;
for (int x = 0; x < searchRadius; ++x) {
if (x <= maxX) {
if (-x >= minX) {
for (int z = 0; z < searchRadius; ++z) {
if (z <= maxZ) {
if (-z >= minZ) {
final Location atPos = origin.clone().add((double)x, 0.0, (double)z);
final Faction factionAtPos = factionManager.getFactionAt(atPos);
if (factionAtPos == null || (!stuck && playerFaction != null && playerFaction.equals(factionAtPos)) || !(factionAtPos instanceof PlayerFaction)) {
final Location safe = getSafeLocation(origin.getWorld(), atPos.getBlockX(), atPos.getBlockZ());
if (safe != null) {
return safe.add(0.5, 0.5, 0.5);
}
}
final Location atNeg = origin.clone().add((double)x, 0.0, (double)z);
final Faction factionAtNeg = factionManager.getFactionAt(atNeg);
if (factionAtNeg == null || (!stuck && playerFaction != null && playerFaction.equals(factionAtNeg)) || !(factionAtNeg instanceof PlayerFaction)) {
final Location safe2 = getSafeLocation(origin.getWorld(), atNeg.getBlockX(), atNeg.getBlockZ());
if (safe2 != null) {
return safe2.add(0.5, 0.5, 0.5);
}
}
}
}
}
}
}
}
return null;
}
private static Location getSafeLocation(final World world, final int x, final int z) {
Block highest = world.getHighestBlockAt(x, z);
Material type = highest.getType();
if (Arrays.asList(LandMap.BLACKLISK).contains(type)) {
return null;
}
while (!type.isSolid()) {
if (highest.getY() <= 1 || Arrays.asList(LandMap.BLACKLISK).contains(type)) {
return null;
}
highest = highest.getRelative(BlockFace.DOWN);
type = highest.getType();
}
return highest.getRelative(BlockFace.UP).getLocation();
}
static {
BLACKLISK = new Material[] { Material.LEAVES, Material.LEAVES_2, Material.FENCE_GATE, Material.WATER, Material.LAVA, Material.STATIONARY_LAVA, Material.STATIONARY_WATER };
}
}
Imports:
import org.bukkit.entity.*;
import net.tutorialesaful.hardcorefactions.faction.claim.*;
import net.tutorialesaful.hardcorefactions.*;
import net.tutorialesaful.hardcorefactions.util.location.*;
import net.tutorialesaful.framework.*;
import net.tutorialesaful.hardcorefactions.visualise.*;
import org.bukkit.inventory.*;
import org.bukkit.command.*;
import org.bukkit.*;
import net.tutorialesaful.hardcorefactions.faction.type.*;
import java.util.*;
import org.bukkit.block.*;
This is a class of bukkit
what object generate() method returns? Could you add generate() method to your question?
you try to cast it to an instance of the Object
((Object) ((Map)dataMap).entrySet().iterator().next()).getValue()...
which (as #MadProgrammer said) doesn't have getValue() method. If you need the Map you should to cast it to the Map and use the get(Object key) method
final String materialName = BasePlugin.getPlugin().getItemDb().getName(new ItemStack(((Map) ((Map)dataMap).entrySet().iterator().next()).get(**the key**).getItemType(), 1));
But in this case you must know the key.

basic planet wars ai issues

I am programming a very basic bot for planet wars in java and I cant seem to find the errors in my code. I am receiving a few different error messages but the main issue for me is the error: class, interface, or enum expected. Ive checked my brackets about a thousand times. Any help would be appreciated. Here's my bot code:
import java.util.List;
import java.util.Random;
import shared.Planet;
import shared.PlanetWars;
public class MyNewBot {
public static void doTurn(PlanetWars pw) {
// (1) If we currently have a fleet in flight, then do nothing until
// it arrives.
if (pw.myFleets().size() >= 10) {
return;
}
// (2) Pick one of my planets based on the number of ships
Planet source = null;
int largestForce = 0;
for (Planet p : pw.myPlanets()){
int force = pw.numShips();
if( force > largestForce){
largestForce = force;
source = p;
}
}
// (3) Pick a target planet at random.
Planet dest = null;
int highestGrowthRate = 0;
int shortestDistance = 9999;
for (Planet p = pw.notMyPlanets()){
int growthRate = pw.growthRate();
if( growthRate > highestGrowthRate){
highestGrowthRate = growthRate;
dest = p;
}else if (growthRate == highestGrowthRate){
int distance = pw.distance(source,p);
if (distance < shortestDistance){
shortestDistance = distance;
dest = p;
}
}
}
// (4) Send half the ships from source to destination.
if (source != null && dest != null) {
int numShips = source.numShips() / 2;
pw.issueOrder(source, dest, numShips);
}
}
// Ignore the main method unless you know what you're doing.
// Refer to the doTurn function to code your bot.
public static void main(String[] args) {
String line = "";
String message = "";
int c;
try {
while ((c = System.in.read()) >= 0) {
switch (c) {
case '\n':
if (line.equals("go")) {
PlanetWars pw = new PlanetWars(message);
doTurn(pw);
pw.finishTurn();
message = "";
} else {
message += line + "\n";
}
line = "";
break;
default:
line += (char) c;
break;
}
}
} catch (Exception e) {
// Owned.
}
}
}
and the supporting class files:
package shared;
public class Planet implements Cloneable {
private int planetID;
private int owner;
private int numShips;
private int growthRate;
private double x, y;
public Planet(int planetID, int owner, int numShips, int growthRate,
double x, double y) {
this.planetID = planetID;
this.owner = owner;
this.numShips = numShips;
this.growthRate = growthRate;
this.x = x;
this.y = y;
}
public int planetID() {
return planetID;
}
public int owner() {
return owner;
}
public int numShips() {
return numShips;
}
public int growthRate() {
return growthRate;
}
public double x() {
return x;
}
public double y() {
return y;
}
public void owner(int newOwner) {
this.owner = newOwner;
}
public void numShips(int newNumShips) {
this.numShips = newNumShips;
}
public void addShips(int amount) {
numShips += amount;
}
public void removeShips(int amount) {
numShips -= amount;
}
private Planet(Planet _p) {
planetID = _p.planetID;
owner = _p.owner;
numShips = _p.numShips;
growthRate = _p.growthRate;
x = _p.x;
y = _p.y;
}
public Object clone() {
return new Planet(this);
}
}
package shared;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class PlanetWars {
// Constructs a PlanetWars object instance, given a string containing a
// description of a game state.
public PlanetWars(String gameStateString) {
planets = new ArrayList<Planet>();
fleets = new ArrayList<Fleet>();
parseGameState(gameStateString);
}
// Returns the number of planets. Planets are numbered starting with 0.
public int numPlanets() {
return planets.size();
}
// Returns the planet with the given planet_id. There are NumPlanets()
// planets. They are numbered starting at 0.
public Planet getPlanet(int planetID) {
return planets.get(planetID);
}
// Returns the number of fleets.
public int numFleets() {
return fleets.size();
}
// Returns the fleet with the given fleet_id. Fleets are numbered starting
// with 0. There are NumFleets() fleets. fleet_id's are not consistent from
// one turn to the next.
public Fleet getFleet(int fleetID) {
return fleets.get(fleetID);
}
// Returns a list of all the planets.
public List<Planet> planets() {
return planets;
}
// Return a list of all the planets owned by the current player. By
// convention, the current player is always player number 1.
public List<Planet> myPlanets() {
List<Planet> r = new ArrayList<Planet>();
for (Planet p : planets) {
if (p.owner() == 1) {
r.add(p);
}
}
return r;
}
// Return a list of all neutral planets.
public List<Planet> neutralPlanets() {
List<Planet> r = new ArrayList<Planet>();
for (Planet p : planets) {
if (p.owner() == 0) {
r.add(p);
}
}
return r;
}
// Return a list of all the planets owned by rival players. This excludes
// planets owned by the current player, as well as neutral planets.
public List<Planet> enemyPlanets() {
List<Planet> r = new ArrayList<Planet>();
for (Planet p : planets) {
if (p.owner() >= 2) {
r.add(p);
}
}
return r;
}
// Return a list of all the planets that are not owned by the current
// player. This includes all enemy planets and neutral planets.
public List<Planet> notMyPlanets() {
List<Planet> r = new ArrayList<Planet>();
for (Planet p : planets) {
if (p.owner() != 1) {
r.add(p);
}
}
return r;
}
// Return a list of all the fleets.
public List<Fleet> fleets() {
List<Fleet> r = new ArrayList<Fleet>();
for (Fleet f : fleets) {
r.add(f);
}
return r;
}
// Return a list of all the fleets owned by the current player.
public List<Fleet> myFleets() {
List<Fleet> r = new ArrayList<Fleet>();
for (Fleet f : fleets) {
if (f.owner() == 1) {
r.add(f);
}
}
return r;
}
// Return a list of all the fleets owned by enemy players.
public List<Fleet> enemyFleets() {
List<Fleet> r = new ArrayList<Fleet>();
for (Fleet f : fleets) {
if (f.owner() != 1) {
r.add(f);
}
}
return r;
}
// Returns the distance between two planets, rounded up to the next highest
// integer. This is the number of discrete time steps it takes to get
// between the two planets.
public int distance(int sourcePlanet, int destinationPlanet) {
Planet source = planets.get(sourcePlanet);
Planet destination = planets.get(destinationPlanet);
double dx = source.x() - destination.x();
double dy = source.y() - destination.y();
return (int) Math.ceil(Math.sqrt(dx * dx + dy * dy));
}
// Returns the distance between two planets, rounded up to the next highest
// integer. This is the number of discrete time steps it takes to get
// between the two planets.
public int distance(Planet source, Planet destination) {
double dx = source.x() - destination.x();
double dy = source.y() - destination.y();
return (int) Math.ceil(Math.sqrt(dx * dx + dy * dy));
}
// Sends an order to the game engine. An order is composed of a source
// planet number, a destination planet number, and a number of ships. A
// few things to keep in mind:
// * you can issue many orders per turn if you like.
// * the planets are numbered starting at zero, not one.
// * you must own the source planet. If you break this rule, the game
// engine kicks your bot out of the game instantly.
// * you can't move more ships than are currently on the source planet.
// * the ships will take a few turns to reach their destination. Travel
// is not instant. See the Distance() function for more info.
public void issueOrder(int sourcePlanet, int destinationPlanet, int
numShips) {
System.out.println("" + sourcePlanet + " " + destinationPlanet + " "
+ numShips);
System.out.flush();
}
// Sends an order to the game engine. An order is composed of a source
// planet number, a destination planet number, and a number of ships. A
// few things to keep in mind:
// * you can issue many orders per turn if you like.
// * the planets are numbered starting at zero, not one.
// * you must own the source planet. If you break this rule, the game
// engine kicks your bot out of the game instantly.
// * you can't move more ships than are currently on the source planet.
// * the ships will take a few turns to reach their destination. Travel
// is not instant. See the Distance() function for more info.
public void issueOrder(Planet source, Planet dest, int numShips) {
System.out.println("" + source.planetID() + " " + dest.planetID() + " "
+ numShips);
System.out.flush();
}
// Sends the game engine a message to let it know that we're done sending
// orders. This signifies the end of our turn.
public void finishTurn() {
System.out.println("go");
System.out.flush();
}
// Returns true if the named player owns at least one planet or fleet.
// Otherwise, the player is deemed to be dead and false is returned.
public boolean isAlive(int playerID) {
for (Planet p : planets) {
if (p.owner() == playerID) {
return true;
}
}
for (Fleet f : fleets) {
if (f.owner() == playerID) {
return true;
}
}
return false;
}
// If the game is not yet over (ie: at least two players have planets or
// fleets remaining), returns -1. If the game is over (ie: only one player
// is left) then that player's number is returned. If there are no
// remaining players, then the game is a draw and 0 is returned.
public int winner() {
Set<Integer> remainingPlayers = new TreeSet<Integer>();
for (Planet p : planets) {
remainingPlayers.add(p.owner());
}
for (Fleet f : fleets) {
remainingPlayers.add(f.owner());
}
switch (remainingPlayers.size()) {
case 0:
return 0;
case 1:
return ((Integer) remainingPlayers.toArray()[0]).intValue();
default:
return -1;
}
}
// Returns the number of ships that the current player has, either located
// on planets or in flight.
public int numShips(int playerID) {
int numShips = 0;
for (Planet p : planets) {
if (p.owner() == playerID) {
numShips += p.numShips();
}
}
for (Fleet f : fleets) {
if (f.owner() == playerID) {
numShips += f.numShips();
}
}
return numShips;
}
// Returns the production of the given player.
public int production(int playerID) {
int prod = 0;
for (Planet p : planets) {
if (p.owner() == playerID) {
prod += p.growthRate();
}
}
return prod;
}
// Parses a game state from a string. On success, returns 1. On failure,
// returns 0.
private int parseGameState(String s) {
planets.clear();
fleets.clear();
int planetID = 0;
String[] lines = s.split("\n");
for (int i = 0; i < lines.length; ++i) {
String line = lines[i];
int commentBegin = line.indexOf('#');
if (commentBegin >= 0) {
line = line.substring(0, commentBegin);
}
if (line.trim().length() == 0) {
continue;
}
String[] tokens = line.split(" ");
if (tokens.length == 0) {
continue;
}
if (tokens[0].equals("P")) {
if (tokens.length != 6) {
return 0;
}
double x = Double.parseDouble(tokens[1]);
double y = Double.parseDouble(tokens[2]);
int owner = Integer.parseInt(tokens[3]);
int numShips = Integer.parseInt(tokens[4]);
int growthRate = Integer.parseInt(tokens[5]);
Planet p = new Planet(planetID++, owner, numShips, growthRate,
x, y);
planets.add(p);
} else if (tokens[0].equals("F")) {
if (tokens.length != 7) {
return 0;
}
int owner = Integer.parseInt(tokens[1]);
int numShips = Integer.parseInt(tokens[2]);
int source = Integer.parseInt(tokens[3]);
int destination = Integer.parseInt(tokens[4]);
int totalTripLength = Integer.parseInt(tokens[5]);
int turnsRemaining = Integer.parseInt(tokens[6]);
Fleet f = new Fleet(owner, numShips, source, destination,
totalTripLength, turnsRemaining);
fleets.add(f);
} else {
return 0;
}
}
return 1;
}
// Store all the planets and fleets. OMG we wouldn't wanna lose all the
// planets and fleets, would we!?
private ArrayList<Planet> planets;
private ArrayList<Fleet> fleets;
}
package shared;
public class Fleet implements Comparable<Fleet>, Cloneable {
private int owner;
private int numShips;
private int sourcePlanet;
private int destinationPlanet;
private int totalTripLength;
private int turnsRemaining;
public Fleet(int owner, int numShips, int sourcePlanet,
int destinationPlanet, int totalTripLength, int turnsRemaining) {
this.owner = owner;
this.numShips = numShips;
this.sourcePlanet = sourcePlanet;
this.destinationPlanet = destinationPlanet;
this.totalTripLength = totalTripLength;
this.turnsRemaining = turnsRemaining;
}
public Fleet(int owner, int numShips) {
this.owner = owner;
this.numShips = numShips;
this.sourcePlanet = -1;
this.destinationPlanet = -1;
this.totalTripLength = -1;
this.turnsRemaining = -1;
}
public int owner() {
return owner;
}
public int numShips() {
return numShips;
}
public int sourcePlanet() {
return sourcePlanet;
}
public int destinationPlanet() {
return destinationPlanet;
}
public int totalTripLength() {
return totalTripLength;
}
public int turnsRemaining() {
return turnsRemaining;
}
public void removeShips(int amount) {
numShips -= amount;
}
// Subtracts one turn remaining. Call this function to make the fleet get
// one turn closer to its destination.
public void TimeStep() {
if (turnsRemaining > 0) {
--turnsRemaining;
} else {
turnsRemaining = 0;
}
}
#Override
public int compareTo(Fleet f) {
return this.numShips - f.numShips;
}
private Fleet(Fleet _f) {
owner = _f.owner;
numShips = _f.numShips;
sourcePlanet = _f.sourcePlanet;
destinationPlanet = _f.destinationPlanet;
totalTripLength = _f.totalTripLength;
turnsRemaining = _f.turnsRemaining;
}
public Object clone() {
return new Fleet(this);
}
}
for (Planet p = pw.notMyPlanets()){ should be for (Planet p : pw.notMyPlanets()){.
You've not posted the Fleet class, so as it is the code won't compile for me. However, the above is the only other error I could see.

Display elements from List - Double type

i have problem with display elements from list.
Button action:
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
int lewy = Integer.parseInt(kresLewy.getText());
int prawy = Integer.parseInt(kresPrawy.getText());
licz(field.getText(),prawy,lewy);
}
});
Here is my list:
static public double licz(String wiersz, int lewy, int prawy) {
double wynik = 0.0;
///////Lista podawana z klawiatury z krokiem co 1
List<Double> listaX = new ArrayList();
for (int i = lewy; i <= prawy; i++) {
listaX.add((double) i);
}
System.out.println(listaX);
try {
StringReader tekstReader = new StringReader(wiersz);
wykresy.parser parser_obj
= new wykresy.parser(new wykresy.MyLexer(tekstReader));
TElement result = (TElement) parser_obj.parse().value;
wynik = result.oblicz();
System.out.println("WYNIK:" + wiersz + " = " + wynik);
} catch (Exception e) {
System.out.println("Podczs obliczenia wystapil blad. (" + e.getMessage() + ")");
} catch (Error error) {
System.out.println("Podczs obliczenia wystapil blad. (" + error.getMessage() + ")");
}
//}
return wynik;
}
I think problem is in "lewy" and "prawy", because list is empty. How can I solve it?
Just iterate through the list and print the values.
Using foreach loop:
for(Double d: listaX){
System.out.println(d);
}
Using functional operation:
listaX.forEach((d) -> {
System.out.println(d);
});
According to your edit, the only problem is: lewy, prawy are switched, so your loop goes from 10 to 0 -> which results in an empty list.
You have several problems:
lewy, prawy are switched
licz does not return something
wynik is unused
public static void main(String[] args) {
int lewy = 0;
int prawy = 10;
licz("Text",lewy, prawy);
}
static public void licz(String wiersz, int lewy, int prawy) {
double wynik = 0.0;
List<Double> listaX = new ArrayList();
for (int i = lewy; i <= prawy; i++) {
listaX.add((double) i);
}
System.out.println(listaX);
}
If you want to print out something you can use System.out.println(listaX), which prints the object to the console.
public static void main(String[] args) {
int lewy = 0;
int prawy = 10;
List<Double> listaX = new ArrayList();
for (int i = lewy; i <= prawy; i++) {
listaX.add((double) i);
}
System.out.println(listaX);
}
See this Post: How to print out all the elements of a List in Java?

Categories