Skip to content
Snippets Groups Projects
Select Git revision
  • 3f5fae36beefdc29de7d1fe814d18f4adc584340
  • master default protected
2 results

ExercicesConditionnelle.java

Blame
  • Code owners
    Assign users and groups as approvers for specific file changes. Learn more.
    EntitySpawner.java 10.45 KiB
    package model;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Map;
    import java.util.Random;
    import java.util.Set;
    
    import util.Direction;
    import util.Position;
    import util.PositionUtil;
    
    public class EntitySpawner {
        private final Board<Square> board;
        private final Random random = new Random();
    
        public EntitySpawner(Board<Square> board) {
            this.board = board;
        }
    
        public void spawnEntities(Map<EntityFactory, Integer> entityCounts) {
            Map<EntityFactory, Integer> counts = new HashMap<>();
            for (EntityFactory factory : entityCounts.keySet()) {
                counts.put(factory, 0);
            }
    
            int totalEntitiesToPlace = entityCounts.values().stream().mapToInt(Integer::intValue).sum();
            int totalEntitiesPlaced = 0;
    
            int chance = 5;
            List<Position> positions = generateAllPositions();
    
            while (totalEntitiesPlaced < totalEntitiesToPlace) {
                Collections.shuffle(positions);
    
                for (Position pos : positions) {
                    if (board.getStates(pos).isEmpty()) {
                        for (EntityFactory factory : entityCounts.keySet()) {
                            int desiredCount = entityCounts.get(factory);
                            int currentCount = counts.get(factory);
    
                            if (currentCount < desiredCount && random.nextInt(100) < chance) {
                                Entity entity = factory.create(pos, board);
                                board.setSquare(new Square(pos, entity));
                                counts.put(factory, currentCount + 1);
                                totalEntitiesPlaced++;
    
                                if (totalEntitiesPlaced == totalEntitiesToPlace) {
                                    return;
                                }
    
                                break; // Move to the next position
                            }
                        }
                    }
                }
    
                // Increase chance after each full traversal
                chance = Math.min(chance + 5, 100);
            }
        }
    
        private List<Position> generateAllPositions() {
            List<Position> positions = new ArrayList<>();
            for (int x = 0; x < board.rowCount(); x++) {
                for (int y = 0; y < board.columnCount(); y++) {