Created
November 29, 2015 09:31
-
-
Save nielsutrecht/cbc04a039c9255970e9d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package droptable; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.List; | |
import java.util.Locale; | |
public class DropTable { | |
private List<DropChance> table; | |
private boolean sorted; | |
public DropTable() { | |
this.table = new ArrayList<>(); | |
} | |
public void add(double chance, Item item) { | |
sorted = false; | |
table.add(new DropChance(chance, item)); | |
} | |
public Item getDrop() { | |
if(!sorted) { | |
Collections.sort(table, (a, b) -> Double.compare(a.chance, b.chance)); | |
sorted = true; | |
} | |
double roll = Math.random(); | |
for(DropChance c : table) { | |
if(roll <= c.chance) { | |
return c.item; | |
} | |
} | |
return null; | |
} | |
public class DropChance { | |
private double chance; | |
private Item item; | |
public DropChance(double chance, Item item) { | |
this.chance = chance; | |
this.item = item; | |
} | |
} | |
public static class Item { | |
private String name; | |
private Rarity rarity; | |
public Item(String name, Rarity rarity) { | |
this.name = name; | |
this.rarity = rarity; | |
} | |
@Override | |
public String toString() { | |
return String.format(Locale.ROOT, "%s (%s)", name, rarity); | |
} | |
public enum Rarity { | |
JUNK, | |
COMMON, | |
MAGIC, | |
RARE, | |
EPIC, | |
LEGENDARY | |
} | |
} | |
public static void main(String... argv) { | |
Item mace = new Item("Source of Envy", Item.Rarity.LEGENDARY); | |
Item sword = new Item("Awesome Sword of Awesomeness", Item.Rarity.EPIC); | |
Item shield = new Item("Damn Fine Shield", Item.Rarity.RARE); | |
Item pants = new Item("Leggings +1", Item.Rarity.MAGIC); | |
Item common = new Item("Rusty Dagger", Item.Rarity.COMMON); | |
Item junk = new Item("Rat's ears", Item.Rarity.JUNK); | |
DropTable table = new DropTable(); | |
table.add(0.01, mace); | |
table.add(0.05, sword); | |
table.add(0.1, shield); | |
table.add(0.2, pants); | |
table.add(0.3, common); | |
table.add(0.8, junk); | |
for(int i = 0;i < 100;i++) { | |
Item item = table.getDrop(); | |
if(item == null) { | |
System.out.println("No drop :("); | |
} | |
else { | |
System.out.println(item); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment