Newer
Older
ChallengeSystem / src / main / java / net / brennholz / challenges / RandomDrops.java
@fantahund fantahund on 18 Jan 2020 2 KB Fix2
package net.brennholz.challenges;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Random;
import java.util.stream.Collectors;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.configuration.file.FileConfiguration;

public class RandomDrops {
  private final ArrayList<Material> BLOCKS;
  
  private final ArrayList<Material> ITEM_DROPS;
  
  private HashMap<Material, Material> drops = new HashMap<>();
  
  public RandomDrops() {
    this.BLOCKS = (ArrayList<Material>)Arrays.<Material>stream(Material.values()).filter(mat -> mat.isBlock()).collect(Collectors.toList());
    this.ITEM_DROPS = (ArrayList<Material>)Arrays.<Material>stream(Material.values()).filter(mat -> (mat.isItem() || mat == Material.BEDROCK)).collect(Collectors.toList());
  }
  
  public void shuffleItems() {
    Collections.shuffle(this.ITEM_DROPS);
    ArrayList<Material> itemDropsCopy = new ArrayList<>();
    this.ITEM_DROPS.forEach(m -> itemDropsCopy.add(m));
    this.BLOCKS.forEach(mat -> {
          int r = (new Random()).nextInt(itemDropsCopy.size() - 1);
          this.drops.put(mat, itemDropsCopy.get(r));
          itemDropsCopy.remove(r);
        });
    saveItems();
  }
  
  public void saveItems() {
    FileConfiguration config = Challenges.getplugin().getRndDropsConfig();
    config.set("drops", this.drops.entrySet().stream().map(entry -> (new StringBuilder()).append(entry.getKey()).append(":").append(entry.getValue()).toString()).collect(Collectors.toList()));
  }
  
  public void loadItems() {
    this.drops.clear();
    FileConfiguration config = Challenges.getplugin().getRndDropsConfig();
    if (config.isList("drops")) {
      config.getStringList("drops").forEach(str -> {
            String[] materialSplitted = str.split(":");
            this.drops.put(Material.getMaterial(materialSplitted[0]), Material.getMaterial(materialSplitted[1]));
          });
    } else {
      shuffleItems();
    } 
  }
  
  public Material getMaterialFromBlock(Block block) {
    return this.drops.get(block.getType());
  }
}