Free Essay

Java

In:

Submitted By Homeworlstallion
Words 2671
Pages 11
public abstract class Animal extends Organism { boolean ateThisTurn; boolean wantsToMove; public void wasIJustFed(boolean ateOrNot) { if (ateOrNot == true) { ateThisTurn = true; } else { ateThisTurn = false; } } public void resetHunger() { ateThisTurn = false; } public void wasIJustMoved(boolean movedOrNot) { if (movedOrNot) { wantsToMove = false; } else { wantsToMove = true; } } public String toString() { String deadOrAlive = new String(); if (isAlive) { deadOrAlive = "A Living "; } else { deadOrAlive = "A Dead "; } return "[" + deadOrAlive + organismType + ": " + currentHP + "/" + maxHP + " | " + lastReproduced + "/" + reproduceEvery + " - ateThisTurn = " + ateThisTurn + "\n"; } public boolean justAte() { return ateThisTurn; } public boolean moveThisTurn() { return wantsToMove && isAlive; } public boolean isReadyToReproduce() { return super.isReadyToReproduce() && maxHP == currentHP && ateThisTurn && isAlive; } public boolean isBurning() { return false; }
}

import java.awt.*; import java.util.ArrayList; public class Breeder { public Breeder() { } public static void breed(Organism breedingOrganism, WorldWorker environment, Point pointHolder) { try { if (breedingOrganism.isReadyToReproduce()) { breedingOrganism.resetLastReproducedCounter(); boolean hadRoom = false; Organism babyOrganism = breedingOrganism.getClass().newInstance(); if (breedingOrganism instanceof Animal) { hadRoom = environment.putOrganismAtPoint(babyOrganism, pointHolder); } else if (breedingOrganism instanceof Vegetation) { Point burningPoint = Wildfire.getBurningPoint(); ArrayList possiblePoints = environment.getAdjacentCoordinates(pointHolder); possiblePoints.add(pointHolder); if (possiblePoints.contains(burningPoint)) { possiblePoints.remove(burningPoint); } while (!possiblePoints.isEmpty()) { Point pointToMoveTo = possiblePoints.get(Randomizer.getRandom().nextInt(possiblePoints.size())); if (environment.putOrganismAtPoint(babyOrganism, pointToMoveTo)) { hadRoom = true; break; } possiblePoints.remove(pointToMoveTo); } } if (hadRoom) { System.out.println(babyOrganism.organismName() + " was born at " + pointHolder.x + "," + pointHolder.y); } else if (!hadRoom) { babyOrganism.killMe(); System.out.println(babyOrganism.organismName() + " was born at " + pointHolder.x + "," + pointHolder.y + " but died due to over crowding."); } } } catch (Exception couldNotReproduce) { System.out.println("There was a problem with breeding organisms at point: " + pointHolder.x + "," + pointHolder.y); } }
}

public class Deer extends Animal { public Deer() { maxHP = 8; currentHP = maxHP; reproduceEvery = 4; lastReproduced = 0; organismType = "Deer"; isAlive = true; ateThisTurn = false; wantsToMove = true; }

public Deer(boolean isRandom) { maxHP = 8; currentHP = maxHP; reproduceEvery = 4; lastReproduced = 0; organismType = "Deer"; isAlive = true; ateThisTurn = false; wantsToMove = true; if (isRandom) { lastReproduced = rnd.nextInt(reproduceEvery) + 1; } }
}

import java.awt.*; import java.util.ArrayList; public class Feeder { public Feeder() { } public static void feed(Organism feedingOrganism, ArrayList foodOrganisms, Point pointHolder) { if (feedingOrganism instanceof Deer && feedingOrganism.getLifeStatus()) { boolean wasIFed = false; if (feedingOrganism.needsToEatThisTurn()) { for (Organism food : foodOrganisms) { if (food instanceof Vegetation && food.getLifeStatus()) { food.decreaseHealthByOne(); feedingOrganism.wasIJustFed(true); feedingOrganism.increaseHealthByOne(); wasIFed = true; System.out.println("" + feedingOrganism.organismType + " ate: " + food.organismType + " at " + pointHolder.x + "," + pointHolder.y + " and now has " + feedingOrganism.getCurrentHP() + " HP"); break; } } } if (!wasIFed) { feedingOrganism.wasIJustFed(false); feedingOrganism.decreaseHealthByOne();

System.out.println("" + feedingOrganism.organismType + " didn't eat at " + pointHolder.x + "," + pointHolder.y +

" and now has " + feedingOrganism.getCurrentHP() + " HP"); } } }
}

public class Grass extends Vegetation { public Grass() { maxHP = 1; currentHP = maxHP; reproduceEvery = 2; lastReproduced = 0; organismType = "Grass"; isAlive = true; chanceToGetHitByFire = 0.75; }

public Grass(boolean isRandom) { maxHP = 1; currentHP = maxHP; reproduceEvery = 2; lastReproduced = 0; organismType = "Grass"; isAlive = true; chanceToGetHitByFire = 0.75; if (isRandom) { lastReproduced = rnd.nextInt(reproduceEvery) + 1; } }
}

public class MotherNature { private int gridWidth; private int gridHeight; private WorldBuilder worldMap; private WorldWorker worldWorker; private int roundNumber = 0; private boolean wasThereFire = false; public MotherNature(int[] mapSize, int grass, int tree, int deer) { gridWidth = mapSize[0]; gridHeight = mapSize[1]; worldMap = new WorldBuilder(gridWidth, gridHeight); worldWorker = new WorldWorker(worldMap.generateCoordinates(), worldMap.getPointList(), gridWidth, gridHeight, grass, tree, deer); EcosystemGUI gui1 = new EcosystemGUI(gridWidth, gridHeight, this, this.worldWorker, worldMap.getPointList()); } public MotherNature(int[] mapSize, int grass, int tree, int deer, boolean notFirstTurn) { this(mapSize, grass, tree, deer); SoundWorker soundsOfNature = new SoundWorker(); Thread soundThread = new Thread(soundsOfNature); soundThread.start(); } public void performNextTurn() { roundNumber++; worldWorker.resetOrganisms(); wasThereFire = false; if (Wildfire.burn()) { Wildfire.burnAPoint(worldWorker); wasThereFire = true; } System.out.println(Wildfire.getBurningPoint()); worldWorker.feedOrganisms(); System.out.println(); worldWorker.moveOrganisms(); System.out.println(); worldWorker.breedOrganisms(); System.out.println("----- End of turn -----"); } public int getRoundNumber() { return roundNumber; } public boolean wasThereFireThisTurn() { return wasThereFire; }
}

import java.awt.*; import java.util.ArrayList; import java.util.Collections; public class Mover { public Mover() { } public static boolean move(Organism movingOrganism, WorldWorker environment, Point pointHolder) { ArrayList adjacentPoints = environment.getAdjacentCoordinates(pointHolder); Collections.shuffle(adjacentPoints, Randomizer.getRandom adjacentPoints.add(0, pointHolder); Point burningPoint = Wildfire.getBurningPoint(); if(adjacentPoints.contains(burningPoint)){ adjacentPoints.remove(burningPoint); } int bestFood = 0; Point bestPoint = null; for(Point possiblePoint : adjacentPoints) { int foodCountAtNextPoint = environment.getNumberOfVegetablesAtPoint(possiblePoint); if(foodCountAtNextPoint > bestFood) { bestPoint = possiblePoint; bestFood = foodCountAtNextPoint; } }

Point nextPoint;

if(bestPoint == null){ adjacentPoints.remove(pointHolder); nextPoint = adjacentPoints.get(Randomizer.getRandom().nextInt(adjacentPoints.size())); } else { if(bestPoint.equals(pointHolder)){ nextPoint = null; }else { nextPoint = bestPoint; } } if(nextPoint !=null){ environment.putOrganismAtPoint(movingOrganism, nextPoint); movingOrganism.wasIJustMoved(true); System.out.println("" + movingOrganism.organismName() + " moved from " + pointHolder.x + "," + pointHolder.y + " to " + nextPoint.x + "," + nextPoint.y + " where there are: [" + bestFood + "] vegetables and [" + environment.getNumberOfFoodUnitsAtPoint(nextPoint) + "] food units."); return true; }else { movingOrganism.wasIJustMoved(true); System.out.println("" + movingOrganism.organismName() + " stayed at " + pointHolder.x + "," + pointHolder.y + " where there are: [" + bestFood + "] vegetables and [" + environment.getNumberOfFoodUnitsAtPoint(pointHolder) + "] food units."); return false; } }
}

import java.util.Random; public abstract class Organism { int maxHP; int currentHP; int reproduceEvery; int lastReproduced; String organismType; boolean isAlive; Random rnd = Randomizer.getRandom(); public void increaseHealthByOne() { if ((currentHP > 0) && (currentHP < maxHP)) { currentHP++; } else { } } public void decreaseHealthByOne() { if (currentHP > 0) { currentHP--; if (currentHP == 0) isAlive = false; } else { } } public String organismName() { return organismType; } public boolean getLifeStatus() { return isAlive; } public int turnsSinceLastReproduction() { return lastReproduced; } public boolean isReadyToReproduce() { return lastReproduced == reproduceEvery; } public void killMe() { isAlive = false; currentHP = 0; } public void addTurn() { if (lastReproduced < reproduceEvery) { lastReproduced++; } } public void resetLastReproducedCounter() { if (getLifeStatus()) { lastReproduced = 0; } } public boolean needsToEatThisTurn() { return getLifeStatus() && !justAte(); } public int getCurrentHP() { return currentHP; } abstract public boolean justAte(); abstract public void wasIJustFed(boolean ateOrNot); abstract public void wasIJustMoved(boolean movedOrNot); abstract public boolean moveThisTurn(); abstract public void resetHunger();

abstract public boolean isBurning();
}

import java.util.Random; public class Randomizer { private static final int SEED = 1111; private static final Random rand = new Random(SEED); private static final boolean useShared = true; public Randomizer() { } public static Random getRandom() { if (useShared) { return rand; } else { return new Random(); } } public static void reset() { if (useShared) { rand.setSeed(SEED); } }
}

import javax.sound.sampled.*; import java.io.IOException; import java.net.URL; public class SoundWorker implements Runnable { public void run() { try { URL url = getClass().getResource("/resources/nature.wav"); AudioInputStream audioIn = AudioSystem.getAudioInputStream(url); Clip clip = AudioSystem.getClip(); clip.open(audioIn); FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); gainControl.setValue(-25.0f); clip.loop(Clip.LOOP_CONTINUOUSLY); } catch (UnsupportedAudioFileException | LineUnavailableException | IOException e) { e.printStackTrace(); } }
}

import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.border.MatteBorder; import java.awt.*; import java.awt.event.*; import java.util.Random; public class StartupGUI { private final int MAXDIMENSION = 25; private final int MAXORGANISM = 100; private final int LOWLIMIT = 2; private boolean FirstTurn = false; private int[] mapSize = new int[2]; private int numGrass; private int numTree; private int numDeer; private int randGrass; private int randTree; private int randDeer; private JFrame frame = new JFrame(); private JTextField mapWidthInput = new JTextField("12"); private JTextField mapHeightInput = new JTextField("12"); private JTextField grassInput = new JTextField(); private JTextField treeInput = new JTextField(); private JTextField deerInput = new JTextField(); private JButton submitButton; private KeyStroke enterPressed; public StartupGUI() { EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { System.out.println("An error has occurred on startup"); } frame.setTitle("Ecosystem Project : Team Awesome"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); randomOrganismFillers(); frame.setLayout(new BorderLayout()); frame.add(new StartupPane()); frame.pack(); enterPressed = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false); Action keyEnterAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { submitButton.doClick(); } }; frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(enterPressed, "Enter"); frame.getRootPane().getActionMap().put("Enter", keyEnterAction);

frame.setLocationRelativeTo(null); frame.setSize(500, 300); frame.setResizable(false); frame.setVisible(true); } }); } public StartupGUI(boolean FirstTurn) { this(); this.FirstTurn = FirstTurn; } private void randomOrganismFillers() { Random randomOrganismAmount = new Random(); randGrass = randomOrganismAmount.nextInt(MAXORGANISM); randTree = randomOrganismAmount.nextInt(MAXORGANISM); randDeer = randomOrganismAmount.nextInt(MAXORGANISM); } private class StartupPane extends JPanel { private StartupPane() { setLayout(new BorderLayout()); add(splashScreen(), BorderLayout.CENTER); } private JPanel splashScreen() { JPanel splashPanel = new JPanel(new GridLayout(4, 0)); splashPanel.setBorder(new EmptyBorder(10, 10, 10, 10)); splashPanel.setBackground(Color.GRAY); JPanel mapInputPanel = new JPanel(new GridLayout(0, 2, 80, 0)); mapInputPanel.setBorder(new EmptyBorder(15, 15, 0, 15)); JLabel mapWidth = new JLabel("Map Width"); JLabel mapHeight = new JLabel("Map Height"); mapWidth.setHorizontalAlignment(JLabel.CENTER); mapHeight.setHorizontalAlignment(JLabel.CENTER); mapWidthInput.setHorizontalAlignment(JLabel.CENTER); mapHeightInput.setHorizontalAlignment(JLabel.CENTER); mapWidthInput.addFocusListener(new mapWidthFocus()); mapHeightInput.addFocusListener(new mapHeightFocus()); mapWidthInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.DARK_GRAY)); mapHeightInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.DARK_GRAY)); mapInputPanel.add(mapWidth); mapInputPanel.add(mapHeight); mapInputPanel.add(mapWidthInput); mapInputPanel.add(mapHeightInput); JPanel organismInputPanel = new JPanel(new GridLayout(0, 3, 30, 0)); organismInputPanel.setBorder(new EmptyBorder(15, 15, 0, 15)); JLabel grassLabel = new JLabel("Grass Organisms"); JLabel treeLabel = new JLabel("Tree Organisms"); JLabel deerLabel = new JLabel("Deer Organisms"); grassLabel.setHorizontalAlignment(JLabel.CENTER); treeLabel.setHorizontalAlignment(JLabel.CENTER); deerLabel.setHorizontalAlignment(JLabel.CENTER); grassInput.setHorizontalAlignment(JLabel.CENTER); treeInput.setHorizontalAlignment(JLabel.CENTER); deerInput.setHorizontalAlignment(JLabel.CENTER); grassInput.addFocusListener(new organismGrassFocus()); treeInput.addFocusListener(new organismTreeFocus()); deerInput.addFocusListener(new organismDeerFocus()); grassInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.DARK_GRAY)); treeInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.DARK_GRAY)); deerInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.DARK_GRAY)); grassInput.setText("" + randGrass); treeInput.setText("" + randTree); deerInput.setText("" + randDeer); organismInputPanel.add(grassLabel); organismInputPanel.add(treeLabel); organismInputPanel.add(deerLabel); organismInputPanel.add(grassInput); organismInputPanel.add(treeInput); organismInputPanel.add(deerInput); JPanel messageBarPanel = new JPanel(new GridLayout(3, 1, 0, 5)); messageBarPanel.setBorder(new EmptyBorder(25, 0, 0, 0)); JLabel messageLabel = new JLabel("Please specify the dimensions and organism counts you would like!"); JLabel messageLabel2 = new JLabel("Some random values have been provided for you, change them as you wish!"); JLabel messageLabel3 = new JLabel("Max dimensions: 25x25. Max organism type each: 100"); messageLabel.setHorizontalAlignment(JLabel.CENTER); messageLabel2.setHorizontalAlignment(JLabel.CENTER); messageLabel3.setHorizontalAlignment(JLabel.CENTER); messageBarPanel.add(messageLabel); messageBarPanel.add(messageLabel2); messageBarPanel.add(messageLabel3); JPanel bottomButtonBarPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 125, 15)); submitButton = new JButton("Submit"); Button exitButton = new Button("Exit"); submitButton.addActionListener(new submitButtonAction()); exitButton.addActionListener(new exitButtonAction()); bottomButtonBarPanel.add(submitButton); bottomButtonBarPanel.add(exitButton); splashPanel.add(mapInputPanel); splashPanel.add(organismInputPanel); splashPanel.add(messageBarPanel); splashPanel.add(bottomButtonBarPanel); return splashPanel; } private class submitButtonAction implements ActionListener { public void actionPerformed(ActionEvent actionEvent) { boolean canProceed = testInputs(); if (canProceed) { frame.setVisible(false); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING)); if (!FirstTurn) { MotherNature divinity1 = new MotherNature(mapSize, numGrass, numTree, numDeer); } else { MotherNature divinity1 = new MotherNature(mapSize, numGrass, numTree, numDeer, true); } } } private boolean testInputs() { boolean mapSuccess; boolean organismSuccess; boolean everythingIsGood; mapSuccess = testMapInputs(); organismSuccess = testOrganismInputs(); everythingIsGood = mapSuccess && organismSuccess; return everythingIsGood; } private boolean testMapInputs() { boolean tempBoolean1; boolean tempBoolean2; boolean returnBoolean; try { mapSize[0] = Integer.parseInt(mapWidthInput.getText()); mapWidthInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.DARK_GRAY)); tempBoolean1 = true; if (mapSize[0] > MAXDIMENSION) { mapWidthInput.setText("Too big!"); mapWidthInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.YELLOW)); tempBoolean1 = false; } if (mapSize[0] < LOWLIMIT) { mapWidthInput.setText("Too small!"); mapWidthInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.YELLOW)); tempBoolean1 = false; } } catch (Exception e) { mapWidthInput.setText("Try again!"); mapWidthInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.RED)); tempBoolean1 = false; } try { mapSize[1] = Integer.parseInt(mapHeightInput.getText()); mapHeightInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.DARK_GRAY)); tempBoolean2 = true; if (mapSize[1] > MAXDIMENSION) { mapHeightInput.setText("Too big!"); mapHeightInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.YELLOW)); tempBoolean2 = false; } if (mapSize[1] < LOWLIMIT) { mapHeightInput.setText("Too small!"); mapHeightInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.YELLOW)); tempBoolean2 = false; } } catch (Exception e) { mapHeightInput.setText("Try again!"); mapHeightInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.RED)); tempBoolean2 = false; } returnBoolean = tempBoolean1 && tempBoolean2; return returnBoolean; } private boolean testOrganismInputs() { boolean tempBoolean1; boolean tempBoolean2; boolean tempBoolean3; boolean returnBoolean; try { numGrass = Integer.parseInt(grassInput.getText()); grassInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.DARK_GRAY)); tempBoolean1 = true; if (numGrass > MAXORGANISM) { grassInput.setText("Too big!"); grassInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.YELLOW)); tempBoolean1 = false; } if (numGrass < LOWLIMIT) { grassInput.setText("Too small!"); grassInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.YELLOW)); tempBoolean1 = false; } } catch (Exception e) { grassInput.setText("Try again!"); grassInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.RED)); tempBoolean1 = false; } try { numTree = Integer.parseInt(treeInput.getText()); treeInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.DARK_GRAY)); tempBoolean2 = true; if (numTree > MAXORGANISM) { treeInput.setText("Too big!"); treeInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.YELLOW)); tempBoolean2 = false; } if (numTree < LOWLIMIT) { treeInput.setText("Too small!"); treeInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.YELLOW)); tempBoolean2 = false; } } catch (Exception e) {

treeInput.setText("Try again!"); treeInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.RED)); tempBoolean2 = false; } try { numDeer = Integer.parseInt(deerInput.getText()); deerInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.DARK_GRAY)); tempBoolean3 = true; if (numDeer > MAXORGANISM) { deerInput.setText("Too big!"); deerInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.YELLOW)); tempBoolean3 = false; } if (numDeer < LOWLIMIT) { deerInput.setText("Too small!"); deerInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.YELLOW)); tempBoolean3 = false; } } catch (Exception e) { deerInput.setText("Try again!"); deerInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.RED)); tempBoolean3 = false; } returnBoolean = tempBoolean1 && tempBoolean2 && tempBoolean3; return returnBoolean; } } private class exitButtonAction implements ActionListener { public void actionPerformed(ActionEvent actionEvent) { System.exit(0); } } private class mapWidthFocus implements FocusListener { public void focusGained(FocusEvent e) { try { int tempWidth = Integer.parseInt(mapWidthInput.getText()); } catch (Exception ex) { mapWidthInput.setText(""); mapWidthInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.DARK_GRAY)); } } public void focusLost(FocusEvent e) { } } private class mapHeightFocus implements FocusListener { public void focusGained(FocusEvent e) { try { int tempHeight = Integer.parseInt(mapHeightInput.getText()); } catch (Exception ex) { mapHeightInput.setText("");

mapHeightInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.DARK_GRAY)); } } public void focusLost(FocusEvent e) { } } private class organismGrassFocus implements FocusListener { public void focusGained(FocusEvent e) { try { int tempGrass = Integer.parseInt(grassInput.getText()); } catch (Exception ex) { grassInput.setText(""); grassInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.DARK_GRAY)); } } public void focusLost(FocusEvent e) { } } private class organismTreeFocus implements FocusListener { public void focusGained(FocusEvent e) { try { int tempTree = Integer.parseInt(treeInput.getText()); } catch (Exception ex) { treeInput.setText(""); treeInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.DARK_GRAY)); } } public void focusLost(FocusEvent e) { } } private class organismDeerFocus implements FocusListener { public void focusGained(FocusEvent e) { try { int tempDeer = Integer.parseInt(deerInput.getText()); } catch (Exception ex) { deerInput.setText(""); deerInput.setBorder(new MatteBorder(1, 1, 1, 1, Color.DARK_GRAY)); } } public void focusLost(FocusEvent e) { } } }
}

public class TheCreator { public TheCreator() { StartupGUI startup = new StartupGUI(); }

public TheCreator(boolean FirstTurn) { StartupGUI startup = new StartupGUI(FirstTurn); } public static void main(String[] args) { TheCreator ecosystem1 = new TheCreator(true); }
}

public class Tree extends Vegetation { private int healthRegenerator; public Tree() { maxHP = 4; currentHP = maxHP; reproduceEvery = 5; lastReproduced = 0; healthRegenerator = 0; organismType = "Tree"; isAlive = true; chanceToGetHitByFire = 0.6; } public Tree(boolean isRandom) { maxHP = 4; currentHP = maxHP; reproduceEvery = 5; lastReproduced = 0; healthRegenerator = 0; organismType = "Tree"; isAlive = true; chanceToGetHitByFire = 0.6; if (isRandom) { lastReproduced = rnd.nextInt(reproduceEvery) + 1; } } public void addTurn() { if (lastReproduced < reproduceEvery) { lastReproduced++; } if (currentHP != maxHP) { healthRegenerator++; } if (healthRegenerator % 2 == 0) { increaseHealthByOne(); if (currentHP == maxHP) { healthRegenerator = 0; } } }
}

public abstract class Vegetation extends Organism { double chanceToGetHitByFire; public String toString() { String deadOrAlive = new String(); if (isAlive) { deadOrAlive = "A Living "; } else { deadOrAlive = "A Dead "; } return "[" + deadOrAlive + organismType + ": " + currentHP + "/" + maxHP + " | " + lastReproduced + "/" + reproduceEvery + " No food requierd.\n"; } public boolean isBurning() { return rnd.nextDouble() -1) { organismCount += organismCount; } if (deerCount > -1) { organismCount += organismCount; } if (grassCount == -1) { if (RANDOMCAP - organismCount > 0) { grassCount = randomGenerator.nextInt(RANDOMCAP - organismCount); } else { grassCount = randomGenerator.nextInt(SOFTCAP); } } if (treeCount == -1) { if (RANDOMCAP - organismCount > 0) { treeCount = randomGenerator.nextInt(RANDOMCAP - organismCount); } else { treeCount = randomGenerator.nextInt(SOFTCAP); } } if (deerCount == -1) { if (RANDOMCAP - organismCount > 0) { deerCount = randomGenerator.nextInt(RANDOMCAP - organismCount); } else { deerCount = randomGenerator.nextInt(SOFTCAP); } } generateInitialInputOrganisms(); } } private void generateInitialOrganisms(int maxInitialOrganisms) { for (int i = 1; i = 0) { adjacentPoints.add(new Point(holdX - 1, holdY)); } if (holdX + 1 < worldWidth) { adjacentPoints.add(new Point(holdX + 1, holdY)); } if (holdY - 1 >= 0) { adjacentPoints.add(new Point(holdX, holdY - 1)); } if (holdY + 1 < worldHeight) { adjacentPoints.add(new Point(holdX, holdY + 1)); } if (holdX - 1 >= 0 && holdY - 1 >= 0) { adjacentPoints.add(new Point(holdX - 1, holdY - 1)); } if (holdX + 1 < worldWidth && holdY - 1 >= 0) { adjacentPoints.add(new Point(holdX + 1, holdY - 1)); } if (holdX - 1 >= 0 && holdY + 1 < worldHeight) { adjacentPoints.add(new Point(holdX - 1, holdY + 1)); } if (holdX + 1 < worldWidth && holdY + 1 < worldHeight) { adjacentPoints.add(new Point(holdX + 1, holdY + 1)); } return adjacentPoints; } public Point getRandomPointAround(Point pointGiven) { Point pointToMoveTo = new Point(); Random randomPoint = new Random(); ArrayList adjacentPoints = getAdjacentCoordinates(pointGiven); int randomChosenPoint = randomPoint.nextInt(adjacentPoints.size()); pointToMoveTo = adjacentPoints.get(randomChosenPoint); return pointToMoveTo; } public int getTotalOrganisms() { int totalOrganisms = 0; for (Point pointHolder : pointList) { totalOrganisms += coordinateWorker.get(pointHolder).size(); } return totalOrganisms; } public int getTotalOrganismsAtAPoint(Point pointHolder) { int totalOrganisms; totalOrganisms = coordinateWorker.get(pointHolder).size(); return totalOrganisms; } public int getSpecificOrganismCountAtPoint(Point pointHolder, String organismName) { int organismCount = 0; for (Organism organismHolder : coordinateWorker.get(pointHolder)) { if (organismHolder.organismType.equals(organismName)) { organismCount++; } } return organismCount; } public int getNumberOfVegetablesAtPoint(Point pointHolder) { return getSpecificOrganismCountAtPoint(pointHolder, "Grass") + getSpecificOrganismCountAtPoint(pointHolder, "Tree"); } public int getNumberOfFoodUnitsAtPoint(Point pointHolder) { int biteCounter = 0; for (Organism organism : coordinateWorker.get(pointHolder)) { if (organism instanceof Vegetation) { biteCounter += organism.getCurrentHP(); } } return biteCounter; } public ArrayList getOrganismsListAtPoint(Point organismsAtPoint) { return coordinateWorker.get(organismsAtPoint); } public Point getRandomPoint() { return pointList.get(randomGenerator.nextInt(pointList.size())); }
}

Similar Documents

Premium Essay

Java and Java Script

...and lastly to the Internet, one thing has been a constant, different languages evolved based on a need. For these two languages, the Internet was a perfect fit, and without them the Internet would be a less dynamic and vibrant highway. As the Internet grew, more and more people found it a more viable place to do business. With that came a need for languages that were fairly easy to learn, dynamic, secure, portable, and maintainable. The industry answered that call with languages such as Java and JavaScript. This paper will perform an analysis of both Java and JavaScript. In order for the reader to gain a better understanding of these languages, the history of these languages with overviews will be presented along with a discussion of the benefits and drawbacks. The History of Java In the middle of May 1995 Java was introduced into the world, and along with Netscape it would be the new way for Internet users to access this new information superhighway. But before it got to this point, Java technology was developed almost by accident. Back in 1991, Sun Microsystems was looking into the future in anticipation of the future of computing, and they tasked a team that became know as the “Green Project”. Their main focus was to come up with a plan for the future of computing, but what they came out with was something quite unexpected. Under the guidance of James Gosling, a team was locked away in an external site to work on the project that would define Sun’s technology direction...

Words: 1329 - Pages: 6

Premium Essay

Java

...Software Design Introduction to the Java Programming Language Material drawn from [JDK99,Sun96,Mitchell99,Mancoridis00] Software Design (Java Tutorial) © SERG Java Features • “Write Once, Run Anywhere.” • Portability is possible because of Java virtual machine technology: – Interpreted – JIT Compilers • Similar to C++, but “cleaner”: – No pointers, typedef, preprocessor, structs, unions, multiple inheritance, goto, operator overloading, automatic coercions, free. Software Design (Java Tutorial) © SERG Java Subset for this Course • We will focus on a subset of the language that will allow us to develop a distributed application using CORBA. • Input and output will be character (terminal) based. • For detailed treatment of Java visit: – http://java.sun.com/docs/books/tutorial/index.html Software Design (Java Tutorial) © SERG Java Virtual Machine • Java programs run on a Java Virtual Machine. • Features: – – – – – Security Portability Superior dynamic resource management Resource location transparency Automatic garbage collection Software Design (Java Tutorial) © SERG The Java Environment Java Source File (*.java) Java Compiler (javac) Java Bytecode File (*.class) Java Virtual Machine (java) Software Design (Java Tutorial) © SERG Program Organization Source Files (.java) Running Application Running Applet JAVA BYTECODE COMPILER Class Files (.class) JAVA VIRTUAL MACHINE WEB BROWSER Software Design (Java Tutorial) © SERG Program Organization Standards •...

Words: 5230 - Pages: 21

Premium Essay

Java

...we're continuing our Java security research series by analyzing other plug-ins, browser extensions and rich internet applications that are commonly exploited. Our previous research indicated that the current state of Java affairs isn't pretty. At that time, ninety-three percent of enterprises were vulnerable to known Java exploits. Nearly 50 percent of enterprise traffic used a Java version that was more than two years out of date. Through Websense ThreatSeeker Intelligence Cloud analysis we now discover: Only 19 percent of enterprise Windows-based computers ran the latest version of Java (7u25) between August 1-29, 2013. More than 40 percent of enterprise Java requests are from browsers still using outdated Java 6. As a result, more than 80 percent of Java requests are susceptible to two popular new Java exploits: CVE-2013-2473 and CVE-2013-2463. 83.86 percent of enterprise browsers have Java enabled. Nearly 40 percent of users are not running the most up-to-date versions of Flash. In fact, nearly 25 percent of Flash installations are more than six months old, close to 20 percent are outdated by a year and nearly 11 percent are two years old. Our in-depth analysis ran for one month, across multiple verticals and industries. We surveyed millions of real-world web requests for Java usage through our global Websense ThreatSeeker Intelligence Cloud. New Java Exploits and the Neutrino Exploit Kit New Java exploits CVE-2013-2473...

Words: 1745 - Pages: 7

Premium Essay

Java

...that has made his work popular with programmers for many years. Michael Schidlowsky and Sedgewick have developed concise new Java implementations that both express the methods in a natural and direct manner and also can be used in real applications. Algorithms in Java, Third Edition, Part 5: Graph Algorithms is the second book in Sedgewick's thoroughly revised and rewritten series. The first book, Parts 1-4, addresses fundamental algorithms, data structures, sorting, and searching. A forthcoming third book will focus on strings, geometry, and a range of advanced algorithms. Each book's expanded coverage features new algorithms and implementations, enhanced descriptions and diagrams, and a wealth of new exercises for polishing skills. The natural match between Java classes and abstract data type (ADT) implementations makes the code more broadly useful and relevant for the modern object-oriented programming environment. The Web site for this book (www.cs.princeton.edu/~rs/) provides additional source code for programmers along with a variety of academic support materials for educators. Coverage includes: A complete overview of graph properties and types Diagraphs and DAGs Minimum spanning trees Shortest paths Network flows Diagrams, sample Java code, and detailed algorithm descriptions A landmark revision, Algorithms in Java, Third Edition, Part 5 provides a complete tool set for programmers to implement, debug, and use graph algorithms...

Words: 281 - Pages: 2

Premium Essay

Java

...deliver this program, Accenture is partnering with Udacity, an online university focused on bridging the gap between real-world skills, relevant education, and employment. Participants are awarded scholarships for the Accenture Veteran Technology Training Program, which grants access to Udacity’s Intro to Java Programming online program. Accenture is offering the premium version of the course, where coaches actively support students and students earn a Verified Certificate. In this introductory course, you'll learn and practice essential computer science concepts using the Java programming language. You'll learn about Object Oriented Programming, a technique that allows you to use code written by other programmers in your own programs. You'll put your new Java programming skills to the test by solving real-world problems faced by software engineers. Upon successful completion of the training course, participants will be granted an interview with Accenture for the Entry Level Software Engineering Associate position, which is part of our global network of technology experts. If ultimately hired for this full-time position, you will apply your military background and new Java skills to assist with the development, delivery and management of technology-based business solutions. You will continue to develop new skills, through Accenture’s robust training...

Words: 264 - Pages: 2

Premium Essay

Java

...Mohammad Doush Mr. Matthew Robert English 103 13 April 2013 Java the Programming Language Computer is very important in our live, we use computer in everywhere on our live. The doctor uses the computer to see file or pictures of his patients. Also, each engineer uses it in many ways of his work. The teacher in the classroom, employees in the offices and student in their study all of them use computer in them daily live. They are not using the mouse, the keyboard or the scream. They are using the applications by them these applications in the computer are like the soul in the body. The only way to build these applications is programming. To program we need to know one of the programming languages which are very similar each other. If you are professional in one of these languages you can be professional in the other language in a short period of time. It is acceptable if you have the same application written with Java once and with C++ or C sharp at the same time. So for this reason you cannot say that a programming language is better than others. There are three types of programming languages procedural, functional and object-oriented languages. The most uses of these languages are object-oriented and one of these languages is Java you can write any application you need using it. Also you can translate any application to its word. The message of the High-Level programming languages such as Algol and Pascal in first programming revolution was...

Words: 2352 - Pages: 10

Premium Essay

Java

...Release Team[oR] 2001 [x] java Java 2: The Complete Reference by Patrick Naughton and Herbert Schildt Osborne/McGraw-Hill © 1999, 1108 pages ISBN: 0072119764 This thorough reference reads like a helpful friend. Includes servlets, Swing, and more. Table of Contents Back Cover Synopsis by Rebecca Rohan Java 2: The Complete Reference blends the expertise found in Java 1: The Complete Reference with Java 2 topics such as "servlets" and "Swing." As before, there's help with Java Beans and migrating from C++ to Java. A special chapter gives networking basics and breaks out networking-related classes. This book helps you master techniques by doing as well as reading. Projects include a multi-player word game with attention paid to network security. The book is updated where appropriate throughout, and the rhythm of text, code, tables, and illustrations is superb. It's a valuable resource for the developer who is elbow-deep in demanding projects. Table of Contents Java 2 Preface - 7 Part l The Java Language - The Complete Reference - 4 Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 hapter 10 - The Genesis of Java - 9 - An Overview of Java - 20 - Data Types, Variables, and Arrays - 36 - Operators - 57 - Control Statements - 75 - Introducing Classes - 94 - A Closer Look at Methods and Classes - 111 - Inheritance - 134 - Packages and Interfaces - 156 - Exception Handling - 174 Chapter 11 - Multithreaded Programming...

Words: 78285 - Pages: 314

Premium Essay

Java

...JMaster list of Java interview questions - 115 questions By admin | July 18, 2005 115 questions total, not for the weak. Covers everything from basics to JDBC connectivity, AWT and JSP. 1. What is the difference between procedural and object-oriented programs?- a) In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code. b) In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code. 2. What are Encapsulation, Inheritance and Polymorphism?- Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse. Inheritance is the process by which one object acquires the properties of another object. Polymorphism is the feature that allows one interface to be used for general class actions. 3. What is the difference between Assignment and Initialization?- Assignment can be done as many times as desired whereas initialization can be done only once. 4. What is OOPs?- Object oriented programming organizes a program around its data, i. e. , objects and a set of well defined interfaces to that data. An object-oriented program can be characterized as data controlling 5. access to code. What are Class, Constructor...

Words: 6762 - Pages: 28

Premium Essay

Java

...tutorial explains the installation and usage of the Java programming language. It also contains examples for standard programming tasks. 1. Introduction to Java 1.1. History Java is a programming language created by James Gosling from Sun Microsystems in 1991. The first publicly available version of Java (Java 1.0) was released in 1995. Over time new enhanced versions of Java have been released. The current version of Java is Java 1.7 which is also known as Java 7. From the Java programming language the Java platform evolved. The Java platform allows that the program code is written in other languages than the Java programming language and still runs on the Java virtual machine. 1.2. Java Virtual machine The Java virtual machine (JVM) is a software implementation of a computer that executes programs like a real machine. The Java virtual machine is written specifically for a specific operating system, e.g. for Linux a special implementation is required as well as for Windows. Java programs are compiled by the Java compiler into so-called bytecode. The Java virtual machine interprets this bytecode and executes the Java program. 1.3. Java Runtime Environment vs. Java Development Kit Java comes in two flavors, the Java Runtime Environment (JRE) and the Java Development Kit (JDK). The Java runtime environment (JRE) consists of the JVM and the Java class libraries and contains the necessary functionality to start Java programs. The JDK contains in addition the...

Words: 662 - Pages: 3

Premium Essay

Java

...A Comparison between Java and .Net Languages Introduction Java and .Net provide technologies that enable skilled developers to build quality enterprise applications. These technologies are rarely picked based on performance alone. There are many factors to consider when choosing Java or .Net. These considerations are often the deciding factor when choosing one or both of these platforms. Java Java is kenned as both a programming language and a development platform. It was first developed by Sun Microsystems in 1991 and subsequently relinquished in 1995. To help to make the language more accepted and accessible, Sun Microsystems developed it as an object oriented language with a syntax that is very similar to C++. (Java vs. .NET, 2007) Sun Microsystems decided to create this new platform out of a desire to be able to write programs only once that could be run on any system. (James) The Java 2 platform was launched in December 1998. This was a major amelioration of the platform, and included incipient graphics, user interface, and enterprise capabilities. This upgrade was over seven times as large as the initial Java 1.0 release and marked the maturity of the Java platform. (What is java?) Within the Java 2 platform there are 3 editions: • The Java 2 Standard Edition (J2SE) Provides the essential compiler, tools, runtimes, and APIs for writing, deploying, and running applets and applications. • The Java 2 Enterprise Edition (J2EE) Defines a standard for developing multi-tier...

Words: 2279 - Pages: 10

Premium Essay

Java

...November 30, 2011 Java Security Jessica Shaw: 628 Robert Grimsley: 596 Java is a programming language developed by Sun Microsystems in 1995, which is now called Oracle. The language itself is derived from the languages C and C++. Java is a simple language compared to C and C++; however they are all object-oriented languages. The language was designed to help minimize the amount of space and take up as little of your computer’s hardware resources as possible. The language was designed upon five key goals, and they are as followed: * It should be "simple, object-oriented and familiar" * It should be "robust and secure" * It should be "architecture-neutral and portable" * It should execute with "high performance" * It should be "interpreted, threaded, and dynamic" Java is used for a multitude of things. Java allows one to play virtual video games, view and design 3D photos, and many other interactive topics on the internet. Java is the main programming language for mobile devices as well as smart phones such as Android by google. Java is a very secure and reliable language that is used by over 800 billion people. Without the Java languages there are millions of applets and interactive applications on websites that wouldn’t preform properly without it. Java is compiled by byte code that allows for the program to be run through the Java Virtual Machine, or JVM. The compiling method allows for...

Words: 2557 - Pages: 11

Free Essay

Java

...Eclipse and Java for Total Beginners Tutorial Companion Document Eclipse And Java For Total Beginners Companion Tutorial Document By Mark Dexter Table of Contents Introduction........................................................................................................... .............................2 . Tutorial Target Audience.....................................................................................................................2 Tutorial Objectives..............................................................................................................................2 Why learn Java with Eclipse?.............................................................................................................3 Topics Covered...................................................................................................................................3 Tutorial Approach............................................................................................................... ................3 . Getting The Most From This Tutorial..................................................................................................3 Sample Java Application – Personal Lending Library........................................................................4 Downloading and Installing Eclipse ...................................................................................................4 Playing the Lessons...........................

Words: 7556 - Pages: 31

Free Essay

Java

...1. Lab Exercise for Core Java Section A: a) Write a program to find HCF of two number reading inputs as command line argument. b) Write a program to display all prime numbers between two limits. c) Write a program to implement below diamond pattern. * *** ***** d) Write a program to implement string concatenation, finding string length, find sub string and check the given string is palindrome or not? e) Write a program to implement constructor overloading by passing different number of parameter of different types. f) Write a program to find area of Square and rectangle figures using method. g) Write a program to calculate bonus for different departments using method overriding. h) Write a program to perform the different arithmetic operation show the exception handling. i) Write a program to implement thread priorities. j) Write a program to create a linked list using LinkedList class of Collection Framework k) Write a program, to create a Frame Window in an applet. l) Write a program to create simple student registration using applet, read the input using text boxes and display the output once user click on the button. m) Write a program to draw different polygon by using AWT supported Graphics method n) Write a program to implement the appropriate interface in the key listener so that it will receive the type of event. ASSIGNMENT EXCEPTION Exception and exception handling -introduction, types of errors...

Words: 275 - Pages: 2

Premium Essay

Java for Dummies

...Programming Languages/Java ™ Jumpin’ Java! The bestselling Java beginner’s book is now fully updated for Java 7! Open the book and find: ava J • Definitions of the many terms you’ll encounter ® • The grammar of Java • How to save time by reusing code • All about if, for, switch, and while statements • An overview of object-oriented programming • Building blocks — learn to work with Java classes and methods and add comments • Hints about handling exceptions • How to write Java applets ® • The Java scoop — get an overview of Java, the enhancements in Java 7, and the software tools you need • Get loopy — understand the value of variables and learn to control program flow with loops or decision-making statements 5th Edition 5th Edition Java Java, the object-oriented programming language that works on almost any computer, is what powers many of those cool multimedia applications. Thousands have learned Java programming from previous editions of this book — now it’s your turn! Whether you’re new to programming or already know a little Visual Basic or C++, you’ll be doing Java in a jiffy. g Easier! Making Everythin • Ten ways to avoid mistakes • Class it up — explore classes and objects, constructors, and subclasses, and see how to reuse your code • A click ahead — experiment with variables and methods, use arrays and collections to juggle values, and create programs that respond to mouse clicks Learn...

Words: 34460 - Pages: 138

Free Essay

Java Basics

...1 Learn Java/J2EE core concepts and key areas With Java/J2EE Job Interview Companion By K.Arulkumaran & A.Sivayini Technical Reviewers Craig Malone Stuart Watson Arulazi Dhesiaseelan Lara D’Albreo Cover Design, Layout, & Editing A.Sivayini Acknowledgements A. Sivayini Mr. & Mrs. R. Kumaraswamipillai 2 Java/J2EE Job Interview Companion Copy Right 2005-2007 ISBN 978-1-4116-6824-9 The author has made every effort in the preparation of this book to ensure the accuracy of the information. However, information in this book is sold without warranty either expressed or implied. The author will not be held liable for any damages caused or alleged to be caused either directly or indirectly by this book. Please e-mail feedback & corrections (technical, grammatical and/or spelling) to java-interview@hotmail.com First Edition (220+ Q&A): Dec 2005 Second Edition (400+ Q&A): March 2007 3 Outline SECTION DESCRIPTION What this book will do for you? Motivation for this book Key Areas index SECTION 1 Interview questions and answers on: Java Fundamentals Swing Applet Performance and Memory issues Personal and Behavioral/Situational Behaving right in an interview Key Points SECTION 2 Interview questions and answers on: Enterprise Java J2EE Overview Servlet JSP JDBC / JTA JNDI / LDAP RMI EJB JMS XML SQL, Database, and O/R mapping RUP & UML Struts Web and Application servers. Best practices and performance considerations. Testing and deployment. Personal and...

Words: 23255 - Pages: 94