Advertisement
Guest User

Untitled

a guest
Apr 25th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.28 KB | None | 0 0
  1. import java.util.Random;
  2. import java.util.List;
  3. import java.util.Collections;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. import java.awt.Color;
  7. /**
  8.  * Responsible for populating a field with foxes and rabbits.
  9.  * It also knows the colors of the animals.
  10.  *
  11.  * @author Poul Henriksen
  12.  * @version 2005.03.13
  13.  */
  14. public class PopulationGenerator
  15. {
  16.  
  17.     // The probability that a fox will be created in any given grid position.
  18.     private static final double FOX_CREATION_PROBABILITY = 0.02;
  19.     // The probability that a rabbit will be created in any given grid position.
  20.     private static final double RABBIT_CREATION_PROBABILITY = 0.08;
  21.    
  22.     // Mapping from classes to colors
  23.     private Map colorMap;
  24.    
  25.     // The colors of the animals
  26.     private Color FOX_COLOR = Color.BLUE;
  27.     private Color RABBIT_COLOR = Color.ORANGE;    
  28.    
  29.    
  30.     /**
  31.      * Constructor for objects of class PopulationGenerator
  32.      */
  33.     public PopulationGenerator()
  34.     {        
  35.         colorMap = new HashMap();
  36.         colorMap.put(Fox.class, FOX_COLOR);
  37.         colorMap.put(Rabbit.class, RABBIT_COLOR);        
  38.     }
  39.        
  40.     /**
  41.      * Populate a field with foxes and rabbits.
  42.      * @param field The field to be populated.
  43.      * @param animals The list of animals.
  44.      */
  45.     public void populate(Field field, List animals)
  46.     {
  47.         Random rand = new Random();
  48.         field.clear();
  49.         for(int row = 0; row < field.getDepth(); row++) {
  50.             for(int col = 0; col < field.getWidth(); col++) {
  51.                
  52.                 if(rand.nextDouble() <= FOX_CREATION_PROBABILITY) {
  53.                     Fox fox = new Fox(true);
  54.                     fox.setLocation(row, col);
  55.                     animals.add(fox);
  56.                     field.place(fox);
  57.                 }
  58.                 else if(rand.nextDouble() <= RABBIT_CREATION_PROBABILITY) {
  59.                     Rabbit rabbit = new Rabbit(true);
  60.                     rabbit.setLocation(row, col);
  61.                     animals.add(rabbit);
  62.                     field.place(rabbit);
  63.                 }
  64.                 // else leave the location empty.
  65.             }
  66.         }
  67.         Collections.shuffle(animals);
  68.     }
  69.    
  70.     public Map getColors() {
  71.         return colorMap;
  72.     }
  73.    
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement