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

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);
}
}

Related

Limit execution time of my Method

The following is my Brute force code for Sudoku:
public abstract class SudokuBoard
{
protected int ROWS = 9;
protected int COLS = 9;
int solutionsCounter;
double startTime;
double endTime;
String[] data = new String[8];
int puzzleNum = countTotalRows();
// data accessors
public abstract int get(int r, int c);
public abstract void set(int r, int c, int v);
// specific constraints checker, returns true even if the values are not complete
abstract boolean isRowCompatible(int r, int c);
abstract boolean isColCompatible(int r, int c);
abstract boolean isBoxCompatible(int r, int c);
// returns true if element S[r,c] is compatible, even if some values arount it are not filled
public boolean isCompatible(int r, int c)
{
for (int i=0; i<ROWS; i++)
for (int j=0; j<COLS; j++)
if(! (isRowCompatible(r, c) && isColCompatible(r, c) && isBoxCompatible(r, c)))
return false;
return true;
}
// this is the one called to solve the sudoku
public void solve()
{
//convert to seconds
startTime = System.nanoTime() / 1000000000.0;
solve(1,1);
}
// function to incorporate clues
public void incorporateClues(int[] clues)
{
for (int i=0; i<clues.length; i++)
set(clues[i]/100, (clues[i]%100)/10, clues[i]%10);
}
// the recursive backtracking function that does the hardwork
void solve(int r, int c)
{
while (((System.nanoTime() / 1000000000.0) - startTime) < 10) {
System.out.println("Time: " + ((System.nanoTime() / 1000000000.0) - startTime));
if (r<=9 && c<=9)
{
if (get(r,c) == 0)
{
for (int v=1; v<=COLS; v++)
{
set(r,c,v);
if (isCompatible(r,c))
solve((c==9)?(r+1):r, (c==9)?1:(c+1));
}
set(r, c, 0);
}
else
solve((c==9)?(r+1):r, (c==9)?1:(c+1));
}
else
{
solutionsCounter = solutionsCounter + 1;
//convert to seconds
endTime = System.nanoTime() / 1000000000.0;
// print();
}
}
}
// sample display function
void print()
{
for(int i=1; i<=ROWS; i++)
{
for (int j=1; j<=COLS; j++)
System.out.print(get(i,j));
System.out.println();
}
System.out.println("count: " + solutionsCounter);
}
void saveData (String[] data) throws java.io.IOException
{
try
{
java.io.BufferedWriter outfile = new java.io.BufferedWriter(new java.io.FileWriter("15-clue_results.csv", true));
for (int i = 0; i < data.length; i++) {
outfile.write(String.valueOf(data[i]));
outfile.append(',');
}
outfile.append('\n');
outfile.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
static int countTotalRows () {
int count = 0;
try
{
java.io.BufferedReader bufferedReader = new java.io.BufferedReader(new java.io.FileReader("15-clue_results.csv"));
String input;
while((input = bufferedReader.readLine()) != null)
{
count = count + 1;
}
} catch (java.io.IOException e) {
e.printStackTrace();
}
return count;
}
public static void main(String []arg)
{
int numClues;
try {
java.io.BufferedReader csvFile = new java.io.BufferedReader(new java.io.FileReader("clue_set"));
String dataRow;
while ((dataRow = csvFile.readLine()) != null) {
SudokuBoard board = new SB_IntMatrix();
String[] stringSet = new String[15];
int[] PUZZLE1 = new int[15];
board.puzzleNum = board.puzzleNum + 1;
stringSet = dataRow.split(" ");
for (int i = 0; i < stringSet.length; i++) {
PUZZLE1[i] = Integer.parseInt(stringSet[i]);
}
board.incorporateClues(PUZZLE1);
for (int i = 0; i < 1; i++) {
board.solutionsCounter = 0;
board.solve();
board.data[0] = Integer.toString(board.puzzleNum);
board.data[1] = dataRow;
board.data[2] = Integer.toString(board.solutionsCounter);
board.data[3 + i] = Double.toString(board.endTime - board.startTime);
}
try
{
board.saveData(board.data);
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
csvFile.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
The requirement is to limit the solving time of solve(int r, int c) to only 1 hour.
To do this, I tried to put it inside a while loop while (((System.nanoTime() / 1000000000.0) - startTime) < 10) . The number 10 is to just test the code.
I understand that I looped it only 5 times in main method but, it resets back to 0 always and never stops and exceeds the limit of my loop in main.
You should use a Future:
final ExecutorService executor = Executors.newFixedThreadPool(4);
final Future<Boolean> future = executor.submit(() -> {
// Call solve here
return true;
});
future.get(60, TimeUnit.MINUTES); // Blocks
You can do something like:
Init the start date:
LocalDateTime startDateTime = LocalDateTime.now();
And check if 1 hour has elapsed:
LocalDateTime toDateTime = LocalDateTime.now();
if (Duration.between(startDateTime, toDateTime).toHours() > 0) {
// stop the execution
}

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.

Threads communication Java

I have a problem dealing with thread communication in java. I am doing a project that will connect people to 3 different Elevators (depending on the floor they want to go) that have a capacity limit. The thing is I have three difficulties.
My code is Consumer-Producer problem based, and I don't know how to change it so the elevator doesn't wait for it to be full, but starts after time by itself.
Another one is that the program stops before completing the loops. (no idea why).
If i try to check if the elevator hasn't been chosen (by geting the capacity) and not display the info of it being back at floor 0, the program doesn't work.
My code: (Classes of elevator 2 and 3 and their buffers are identical)
public class Proba { //test class
public static void main(String[] args) {
Pojemnik c = new Pojemnik();
Pojemnik1 d = new Pojemnik1();
Pojemnik2 e = new Pojemnik2();
Winda p1 = new Winda(c, 1);
Winda1 p2 = new Winda1(d, 2);
Winda2 p3 = new Winda2(e, 3);
Osoba c1 = new Osoba(c, d, e, 1);
p1.start();
p2.start();
p3.start();
c1.start();
}
}
class Osoba extends Thread //person class
{
private Pojemnik pojemnik;
private Pojemnik1 pojemnik1;
private Pojemnik2 pojemnik2;
private int number;
public Osoba(Pojemnik c, Pojemnik1 d, Pojemnik2 e, int number) {
pojemnik = c;
pojemnik1 = d;
pojemnik2 = e;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++)
{
int k=0;
while (k==0){ //i dont; want floor 0
k = -2 + (int)(Math.random()*7);} //choosing floor
int h;
if(k>-3&&k<1){ //decision which elevator
value = pojemnik.get(); // getting possible capacity
if(value>0){
pojemnik.put(value-1);} //lowering capacity
h=5-value; // how many people are already in
System.out.println("Ktos wsiadl do windy #1"
//+ this.number
+ " jest w niej " + h + " osob i wybrano pietro nr " + k);
}
if(k>-1&&k<4){
value = pojemnik1.get();
if(value>0){
pojemnik1.put(value-1);}
h=5-value;
System.out.println("Ktos wsiadl do windy #2"
//+ this.number
+ " jest w niej " + h + " osob i wybrano pietro nr " + k);
}
if(k>3&&k<8){
value = pojemnik2.get();
if(value>0){
pojemnik1.put(value-1);}
h=5-value;
System.out.println("Ktos wsiadl do windy #3"
//+ this.number
+ " jest w niej " + h + " osob i wybrano pietro nr " + k);
}
}
}
}
}
//import java.util.*;
//import java.lang.*;
class Pojemnik //buffor class
{
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
}
catch (InterruptedException e) {
}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
}
catch (InterruptedException e) {
}
}
contents = value;
if(value>5){ //way to never get too high capacity
contents=5;
}
available = true;
notifyAll();
}
}
// import java.lang.*; // elevator class
class Winda extends Thread {
private Pojemnik pojemnik; //bufor
private int number;
public Winda(Pojemnik c, int number) {
pojemnik = c;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
//pojemnik.get();
pojemnik.put(5); // the elevator is empty 5 people can go in
System.out.println("Winda #" + this.number
+ " jest na poziomie 0 "); //info that elevator is on floor 0
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
}

The hierarchy of the type 'classname' is incosistent--java error in eclipse

I have a class CircleController, which extends a class VehicleController, and I am confused as to why I am getting this error. any help would be greatly appreciated.
The CircleController is...
import java.math.*;
import javax.realtime.*;
public class CircleController extends VehicleController{
public final static int XMiddle = 50;
public final static int YMiddle = 50;
public final static int radius = 25;
//private GroundVehicle v;
public CircleController(Simulator s, GroundVehicle v){
super(s,v);
}
public CircleController(Simulator s, GroundVehicle v, SchedulingParameters sched, ReleaseParameters release){
super(s,v,sched, release);
}
public Control getControl(int sec, int msec){
double position[] = this.newVehic.getPosition();
double dist = Math.sqrt((position[0]-XMiddle)*(position[0]-XMiddle)+(position[1]-YMiddle)*(position[1]-YMiddle));
double angleFromCircleMiddle = Math.atan2(position[1]-YMiddle,position[0]-XMiddle);
double omega=0;
double speed =Simulator.maxTransSpeed;
double angleDelta = position[2]-angleFromCircleMiddle; //angle we need to turn
Control c = new Control(speed, omega);
if (dist<radius+.01){// inside the circle so need to move outwards
//double desiredTheta = angleFromCircleMiddle;
omega = angleDelta/(100.0/1000.0);
//checking omega
if (omega>Math.PI/4)
omega = Math.PI/4;
else if (omega<-Math.PI/4)
omega=-Math.PI/4;
c = new Control(speed, omega);
}
else if (dist+.01>radius){
angleDelta = -angleDelta; //coming from outside inwards
omega = angleDelta/(100.0/1000.0);
//checking omega
if (omega>Math.PI/4)
omega = Math.PI/4;
else if (omega<-Math.PI/4)
omega=-Math.PI/4;
c = new Control(speed, omega);
}
else{
//speed = radius*omega
omega = speed/radius;
c = new Control(speed, omega);
}
c=avoidWalls(this.newVehic.getPosition());
return c;
}
}
The VehicleController class is...
import javax.realtime.*;
public class VehicleController extends RealtimeThread{
protected Simulator newSim;
protected GroundVehicle newVehic;
private double prevTime;
private int numSides;
public double turnDuration;
public double edgeTravelDuration;
public boolean isTurning = false;
public boolean controllerInitialized=false;
public double timeOfManoeuverStart;
protected static int numControllers=0;
protected int controllerID = 0;
private static double avoidWallDist = 15;
private static double timeUpdateInterval = .1;
//constants
private final int diameter=50;
public VehicleController(Simulator s, GroundVehicle v){
//error if input is incorrect
if (s==null)
throw new IllegalArgumentException("error, a null Simulator was inputted.");
if (v==null)
throw new IllegalArgumentException("error, a null Ground Vehicle was inputted.");
this.newSim=s;
this.newVehic=v;
setNumSides(5);
synchronized(VehicleController.class){
controllerID=numControllers;
numControllers++;
}
}
public VehicleController(Simulator s, GroundVehicle v, SchedulingParameters schedule, ReleaseParameters release){
//error if input is incorrect
if (s==null)
throw new IllegalArgumentException("error, a null Simulator was inputted.");
if (v==null)
throw new IllegalArgumentException("error, a null Ground Vehicle was inputted.");
this.newSim=s;
this.newVehic=v;
setNumSides(5);
synchronized(VehicleController.class){
controllerID=numControllers;
numControllers++;
}
}
private void initializeController(){
/* The bulk of this method is to determine how long to spend turning at
* each corner of the polygon, and how long to spend driving along each
* edge. We calculate turnDuration and edgeTravelDuration, and then use
* these inside getControl to decide when to switch from turning to
* travelling straight and back again. */
double interiorAngle = (Math.PI/180)*(180+180*(numSides-3))/numSides;
double turningAngle = Math.PI - interiorAngle;
double minTurningRadius = newSim.minTransSpeed/newSim.maxRotSpeed; // v/w=r
double arcLength = (turningAngle)*minTurningRadius; //need to know at what point we need to start turning
turnDuration = arcLength/newSim.minTransSpeed; //shortest length needed to make this turn
double edgeLength = diameter*Math.cos(interiorAngle/2) -(2*minTurningRadius*Math.tan((turningAngle)/2));
edgeTravelDuration =edgeLength/newSim.maxTransSpeed;
isTurning=true; //meaning we are done with the straightaway and need to turn.
timeOfManoeuverStart = -turnDuration/2.0;
controllerInitialized=true;
}
public Control getControl(int sec, int msec) {
double controlTime = sec+msec*1E-3;
Control c = null;
if (isTurning) {
if (controlTime - timeOfManoeuverStart < turnDuration)
c = new Control(newSim.minTransSpeed, newSim.maxRotSpeed);
else {
isTurning = false;
timeOfManoeuverStart = controlTime;
c = new Control(newSim.maxTransSpeed, 0);
}
}
else {
if (controlTime - timeOfManoeuverStart < edgeTravelDuration)
c = new Control(newSim.maxTransSpeed, 0);
else {
isTurning = true;
timeOfManoeuverStart = controlTime;
c = new Control(newSim.minTransSpeed, newSim.maxRotSpeed);
}
}
return c;
}
public void setNumSides(int n){
if (n>10 || n<3)
numSides=numSides;
else
numSides=n;
initializeController();
}
public int getNumSides(){
return numSides;
}
public void run(){
int sec=0, mSec=0;
double currentTime=0;
//prevTime=0;
// The simulation time is called by multiple threads, so we must put it in a simulator block.
double prevTime=0;
while (currentTime<100){
synchronized(newSim){
sec = newSim.getCurrentSec();
mSec = newSim.getCurrentMSec();
currentTime =sec+mSec/1000.0;
if (currentTime>prevTime+ timeUpdateInterval){
prevTime = currentTime;
Control c =getControl(sec,mSec);
if (c!=null){
newVehic.controlVehicle(c);
}
}
newSim.notifyAll();
}
}
}
protected Control avoidWalls(double[] pos) {
if (pos[0] > 100 - avoidWallDist && pos[1] > 100 - avoidWallDist) {
if (pos[2] > -3 * Math.PI / 4.0) {
return new Control(5, -Math.PI/4);
} else {
return new Control(5, Math.PI/4);
}
}
if (pos[0] > 100 - avoidWallDist && pos[1] < 0 + avoidWallDist) {
if (pos[2] > 3 * Math.PI / 4.0) {
return new Control(5, -Math.PI/4);
} else {
return new Control(5, Math.PI/4);
}
}
if (pos[0] < 0 + avoidWallDist && pos[1] > 100 - avoidWallDist) {
if (pos[2] > -Math.PI / 4.0) {
return new Control(5, -Math.PI/4);
} else {
return new Control(5, Math.PI/4);
}
}
if (pos[0] < 0 + avoidWallDist && pos[1] < 0 + avoidWallDist) {
if (pos[2] > Math.PI / 4.0) {
return new Control(5, -Math.PI/4);
} else {
return new Control(5, Math.PI/4);
}
}
if (pos[0] > 100 - avoidWallDist) {
if (pos[2] > 0) {
return new Control(5, Math.PI/4);
} else {
return new Control(5, -Math.PI/4);
}
}
if (pos[0] < 0 + avoidWallDist) {
if (pos[2] > 0) {
return new Control(5, -Math.PI/4);
} else {
return new Control(5, Math.PI/4);
}
}
if (pos[1] < 0 + avoidWallDist) {
if (pos[2] > Math.PI / 2) {
return new Control(5, -Math.PI/4);
} else {
return new Control(5, Math.PI/4);
}
}
if (pos[1] > 100- avoidWallDist) {
if (pos[2] > -Math.PI / 2) {
return new Control(5, -Math.PI/4);
} else {
return new Control(5, Math.PI/4);
}
}
return null;
}
}

The extended class doesn't seem to be inheriting some stats

I have three classes, Organism, Creature and Plant. Creature and Plant both extend Organism. Now, this code worked when everything was bundled into Organism, so I assume the GUI class isn't at fault. Basically, what is happening is only Creature specific stats are being generated, whereas the Organism stats are being ignored, returning 0. I cannot find anything wrong with it, so I thought you guys could help. (Ignore the mess, I am still playing around.)
Creature Class
import java.awt.Color;
import java.util.Random;
public class Creature extends Organism
{
private char gender;
private int strength, speed, diet, aggression;
private int mated, maxMated;
public Creature()
{
super();
Random rand = new Random();
if(rand.nextInt(2) == 0)
{
gender = 'f';
}
else
{
gender = 'm';
}
mated = 0;
setStats();
}
public Creature(String gen[])
{
super(gen);
Random rand = new Random();
if(rand.nextInt(2) == 0)
{
gender = 'f';
}
else
{
gender = 'm';
}
x = rand.nextInt(maxX);
y = rand.nextInt(maxY);
setStats();
}
public Creature(String gen[], int newX, int newY)
{
super(gen, newX, newY);
this.gene = gen;
Random rand = new Random();
if(rand.nextInt(2) == 0)
{
gender = 'f';
}
else
{
gender = 'm';
}
isAlive = true;
x = newX;
y = newY;
setStats();
}
public int getAggro()
{
return aggression;
}
public int getDiet()
{
return diet;
}
public int getSpeed()
{
return speed;
}
public void setStats()
{
strength = (gene[1].charAt(0)-48) + 1 + ((gene[1].charAt(1)-48) * (gene[1].charAt(2)-48));
speed = (strength + (gene[2].charAt(0)-48) - (gene[2].charAt(1)-48) + (gene[2].charAt(2)-48))/(size + 1);
diet = (gene[7].charAt(0)-48) + 1 + ((gene[7].charAt(1)-48) * (gene[7].charAt(2)-48)*(3/4));
aggression = ((strength + size)/2) / (gene[8].charAt(0)-48 + gene[8].charAt(1)-48 + gene[8].charAt(2)-48 + 1);
maxHealth = 64 + size + (strength / 2);
maxHunger = 100 + (size - speed - aggression);
health = maxHealth;
hunger = maxHunger;
}
public Creature breed(Creature mate)
{
Random rand = new Random();
int x = rand.nextInt(gene.length);
int y = rand.nextInt(gene[x].length());
String geneY[] = new String[16];
int i;
for(i = 0; i < x; i++)
{
geneY[i] = gene[i];
}
geneY[x] = gene[x].substring(0,y);
geneY[x] = geneY[x] + mate.gene[x].substring(y);
for(i = x + 1; i < 16; i++)
{
geneY[i] = mate.gene[i];
}
char newGender;
if(rand.nextInt(2) == 0)
{
newGender = 'f';
}
else
{
newGender = 'm';
}
hunger = hunger /2;
mate.hunger = mate.hunger /2;
mated = mated + 1;
mate.mated = mate.mated + 1;
Creature temp = new Creature(geneY,this.getX(),this.getY());
temp.mutate();
return temp;
}
public void eat(Organism b) //A eats B
{
b.isAlive = false;
this.hunger = this.hunger + b.size;
}
public boolean isCompatible(Creature org)
{
int differences = 0;
for(int i = 0; i < this.gene.length; i++)
{
if(!this.gene[i].equals(org.gene[i]))
{
differences = differences + 1;
}
}
if(differences > 1 || this.gender == org.gender || mated == maxMated || org.mated == org.maxMated)
{
return false;
}
return true;
}
public void moveTo(Organism org)
{
int vectX, vectY, moveX = 0, moveY = 0;
double angle;
vectX = this.x - org.x;
vectY = this.y - org.y;
if(vectX == 0)
{
moveY = this.speed;
}
if(vectY == 0)
{
moveX = this.speed;
}
if(vectX == 0 && vectY == 0)
{
moveX = 0;
moveY = 0;
}
if(vectX != 0 && vectY != 0)
{
angle = ((Math.atan((vectY)/(vectX)))/(2*Math.PI))*360;
if(angle < 0)
{
angle = angle * - 1;
}
moveX = (int)(Math.sin(angle)*this.speed);
moveY = (int)(Math.cos(angle)*this.speed);
}
if(Math.sqrt((vectX*vectX)+(vectY*vectY)) < speed)
{
if(vectX > 0)
{
this.x = this.x - vectX;
}
else
{
this.x = this.x + vectX;
}
if(vectY > 0)
{
this.y = this.y - vectY;
}
else
{
this.y = this.y + vectY;
}
}
else
{
if(vectX > 0)
{
this.x = this.x - moveX;
}
else
{
this.x = this.x + moveX;
}
if(vectY > 0)
{
this.y = this.y - moveY;
}
else
{
this.y = this.y + moveY;
}
}
}
}
Organism Class
import java.awt.Color;
import java.util.Random;
public class Organism
{
protected String gene[] = new String[16];
protected boolean isAlive;
protected int x;
protected int y;
protected int size, sense, fertility, scent;
protected int health, hunger, maxHealth, maxHunger;
protected int maxX = 1000;
protected int maxY = 1000;
private Color color = new Color(255,0,0);
public Organism()
{
Random rand = new Random();
for(int i = 0; i < 16; i++)
{
gene[i] = ""+ rand.nextInt(4) + rand.nextInt(4) + rand.nextInt(4);
}
isAlive = true;
x = rand.nextInt(maxX);
y = rand.nextInt(maxY);
setStats();
}
public Organism(String gen[])
{
Random rand = new Random();
this.gene = gen;
isAlive = true;
x = rand.nextInt(maxX);
y = rand.nextInt(maxY);
setStats();
}
public Organism(String gen[], int newX, int newY)
{
this.gene = gen;
isAlive = true;
x = newX;
y = newY;
setStats();
}
public Color getColor()
{
return color;
}
public int getX()
{
return x;
}
public void setX(int tempX)
{
this.x = tempX;
}
public int getY()
{
return y;
}
public void setY(int tempY)
{
this.y = tempY;
}
public int getHunger()
{
return hunger;
}
public void setHunger(int hun)
{
this.hunger = hun;
}
public int getHealth()
{
return health;
}
public void setHealth(int heal)
{
this.health = heal;
}
public void setStats()
{
size = (gene[0].charAt(0)-48) + 1 + ((gene[0].charAt(1)-48) * (gene[0].charAt(2)-48));
sense = (gene[5].charAt(2)-48) + 1 + ((gene[5].charAt(1)-48) * (gene[5].charAt(2)-48));
fertility = 22 - size + (gene[6].charAt(0)-48) + 1 + ((gene[6].charAt(1)-48) * (gene[6].charAt(2)-48));
scent = (gene[8].charAt(0)-48 + gene[8].charAt(1)-48 + gene[8].charAt(2)-48);
}
public int getSize()
{
return size;
}
public int getSense()
{
return sense;
}
public boolean getAlive()
{
return isAlive;
}
public void setAlive(boolean live)
{
this.isAlive = live;
}
public String getInfo()
{
String info;
info = "Health: " + this.health + ", Hunger: "+ this.hunger + ", Status: " + this.isAlive;
return info;
}
/*public String getStats()
{
String info = "Size: " + this.size + ", Strength: " + this.strength +
", Speed: " + this.speed + ", Sight: " + this.sight +
", Smell: " + this.smell + ", Hearing: " + this.hearing +
", Fertility: " + this.fertility + ", Diet: " + this.diet +
", Aggression: " + this.aggression + ", Scent: " + this.scent;
return info;
}*/
public String displayGene()
{
String geneP = "|";
for(int i = 0; i < gene.length; i++)
{
for(int j = 0; j < gene[i].length(); j++)
{
switch (gene[i].charAt(j))
{
case '0': geneP = geneP + 'A';
break;
case '1': geneP = geneP + 'T';
break;
case '2': geneP = geneP + 'C';
break;
case '3': geneP = geneP + 'G';
break;
}
}
geneP = geneP + "|";
}
return geneP;
}
public void mutate()
{
Random rand = new Random();
int i = rand.nextInt(10000) + 1;
int affected;
if(i > 9999)
{
affected = rand.nextInt(gene.length);
i = rand.nextInt(gene[affected].length());
int j = rand.nextInt(4);
gene[affected] = gene[affected].substring(0,i)+j+gene[affected].substring(i+1);
}
}
public void hungerCheck()
{
hunger = hunger - (size / 10 + 1);
if(hunger <= 0)
{
health = health - 1;
}
if(hunger > (maxHunger * 3)/4)
{
health = health + 1;
}
}
public void validate()
{
if(x > maxX)
{
x = 100;
}
if(x < 0)
{
x = 0;
}
if(y > maxY)
{
y = 100;
}
if(y < 0)
{
y = 0;
}
if(hunger > maxHunger)
{
hunger = maxHunger;
}
if(hunger <= 0)
{
hunger = 0;
}
if(health <= 0)
{
isAlive = false;
}
if(health > maxHealth)
{
health = maxHealth;
}
}
}
You have to call the super method from the Creature.setStats() method
public class Creature extends Organism
public void setStats()
{
super.setStats(); // Call to Organism.setStats()
...
}
....
}

Categories