-
-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathOneBlocksManager.java
More file actions
878 lines (811 loc) · 34.6 KB
/
OneBlocksManager.java
File metadata and controls
878 lines (811 loc) · 34.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
package world.bentobox.aoneblock.oneblocks;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.Objects;
import java.util.Optional;
import java.util.TreeMap;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
import org.apache.commons.lang3.math.NumberUtils;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.Registry;
import org.bukkit.block.Biome;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemStack;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import com.google.common.base.Enums;
import com.google.common.io.Files;
import world.bentobox.aoneblock.AOneBlock;
import world.bentobox.aoneblock.dataobjects.OneBlockIslands;
import world.bentobox.aoneblock.oneblocks.OneBlockObject.Rarity;
import world.bentobox.aoneblock.oneblocks.Requirement.ReqType;
import world.bentobox.bentobox.util.ItemParser;
import world.bentobox.bentobox.util.Util;
/**
* Provides a manager for all phases
*
* @author tastybento
*
*/
public class OneBlocksManager {
private static final String ONE_BLOCKS_YML = "oneblocks.yml";
private static final String NAME = "name";
private static final String BIOME = "biome";
private static final String FIRST_BLOCK = "firstBlock";
private static final String ICON = "icon";
private static final String FIXED_BLOCKS = "fixedBlocks";
private static final String HOLOGRAMS = "holograms";
private static final String CHESTS = "chests";
private static final String RARITY = "rarity";
private static final String CONTENTS = "contents";
private static final String MOBS = "mobs";
private static final String BLOCKS = "blocks";
private static final String PHASES = "phases";
private static final String GOTO_BLOCK = "gotoBlock";
private static final String START_COMMANDS = "start-commands";
private static final String END_COMMANDS = "end-commands";
private static final String END_COMMANDS_FIRST_TIME = "end-commands-first-time";
private static final String REQUIREMENTS = "requirements";
private static final String BLOCK = "Block ";
private static final String BUT_ALREADY_SET_TO = " but already set to ";
private static final String DUPLICATE = " Duplicate phase file?";
private final AOneBlock addon;
private TreeMap<Integer, OneBlockPhase> blockProbs;
/**
* @param addon - addon
*/
public OneBlocksManager(AOneBlock addon) {
this.addon = addon;
// Initialize block probabilities
blockProbs = new TreeMap<>();
}
/**
* Loads the game phases
*
* @throws IOException - if config file has bad syntax or migration fails
*/
public void loadPhases() throws IOException {
// Clear block probabilities
blockProbs = new TreeMap<>();
// Check for folder
File check = new File(addon.getDataFolder(), PHASES);
if (check.mkdirs()) {
addon.log(check.getAbsolutePath() + " does not exist, made folder.");
// Check for oneblock.yml
File oneblockFile = new File(addon.getDataFolder(), ONE_BLOCKS_YML);
if (oneblockFile.exists()) {
// Migrate to new folders
File renamedFile = new File(check, ONE_BLOCKS_YML);
Files.move(oneblockFile, renamedFile);
loadPhase(renamedFile);
this.saveOneBlockConfig();
java.nio.file.Files.delete(oneblockFile.toPath());
java.nio.file.Files.delete(renamedFile.toPath());
blockProbs.clear();
} else {
// Copy files from JAR
copyPhasesFromAddonJar(check);
}
}
// Get files in folder
// Filter for files ending with .yml
FilenameFilter ymlFilter = (dir, name) -> name.toLowerCase(java.util.Locale.ENGLISH).endsWith(".yml");
for (File phaseFile : Objects.requireNonNull(check.listFiles(ymlFilter))) {
loadPhase(phaseFile);
}
}
/**
* Copies phase files from the addon jar to the file system
*
* @param file - the file to copy
*/
void copyPhasesFromAddonJar(File file) {
try (JarFile jar = new JarFile(addon.getFile())) {
// Obtain any locale files, save them and update
Util.listJarFiles(jar, PHASES, ".yml").forEach(lf -> addon.saveResource(lf, file, false, true));
} catch (Exception e) {
addon.logError(e.getMessage());
}
}
private void loadPhase(File phaseFile) throws IOException {
addon.log("Loading " + phaseFile.getName());
// Load the config file
YamlConfiguration oneBlocks = new YamlConfiguration();
try {
oneBlocks.load(phaseFile);
} catch (Exception e) {
addon.logError(e.getMessage());
return;
}
for (String phaseStartBlockNumKey : oneBlocks.getKeys(false)) {
Integer phaseStartBlockNum = Integer.valueOf(phaseStartBlockNumKey);
OneBlockPhase obPhase = blockProbs.computeIfAbsent(phaseStartBlockNum,
k -> new OneBlockPhase(phaseStartBlockNumKey));
// Get config Section
ConfigurationSection phaseConfig = oneBlocks.getConfigurationSection(phaseStartBlockNumKey);
// goto
if (phaseConfig.contains(GOTO_BLOCK)) {
obPhase.setGotoBlock(phaseConfig.getInt(GOTO_BLOCK, 0));
continue;
}
initBlock(phaseStartBlockNumKey, obPhase, phaseConfig);
// Blocks
addBlocks(obPhase, phaseConfig);
// Mobs
addMobs(obPhase, phaseConfig);
// Chests
addChests(obPhase, phaseConfig);
// Commands
addCommands(obPhase, phaseConfig);
// Requirements
addRequirements(obPhase, phaseConfig);
// Add to the map
blockProbs.put(phaseStartBlockNum, obPhase);
}
}
/**
* Load in the phase's init
*
* @param blockNumber string representation of this phase's block number
* @param obPhase OneBlockPhase
* @param phaseConfig configuration section being read
* @throws IOException if there's an error in the config file
*/
void initBlock(String blockNumber, OneBlockPhase obPhase, ConfigurationSection phaseConfig) throws IOException {
// Set name
if (phaseConfig.contains(NAME, true)) {
if (obPhase.getPhaseName() != null) {
throw new IOException(
BLOCK + blockNumber + ": Phase name trying to be set to " + phaseConfig.getString(NAME)
+ BUT_ALREADY_SET_TO + obPhase.getPhaseName() + ". Duplicate phase file?");
}
obPhase.setPhaseName(phaseConfig.getString(NAME, blockNumber));
}
// Set biome
if (phaseConfig.contains(BIOME, true)) {
if (obPhase.getPhaseBiome() != null) {
throw new IOException(BLOCK + blockNumber + ": Biome trying to be set to "
+ phaseConfig.getString(BIOME) + BUT_ALREADY_SET_TO + obPhase.getPhaseBiome() + DUPLICATE);
}
obPhase.setPhaseBiome(getBiome(phaseConfig.getString(BIOME)));
}
// Set first block
if (phaseConfig.contains(FIRST_BLOCK)) {
if (obPhase.getFirstBlock() != null) {
throw new IOException(
BLOCK + blockNumber + ": First block trying to be set to " + phaseConfig.getString(FIRST_BLOCK)
+ BUT_ALREADY_SET_TO + obPhase.getFirstBlock() + DUPLICATE);
}
addFirstBlock(obPhase, phaseConfig.getString(FIRST_BLOCK));
}
// Set icon
if (phaseConfig.contains(ICON)) {
ItemStack icon = ItemParser.parse(phaseConfig.getString(ICON));
if (icon == null) {
throw new IOException("ItemParser failed to parse icon: '" + phaseConfig.getString(ICON)
+ "' for phase " + obPhase.getFirstBlock() + ". Can you check if it is correct?");
}
obPhase.setIconBlock(icon);
}
// Add fixed blocks
if (phaseConfig.contains(FIXED_BLOCKS)) {
if (!obPhase.getFixedBlocks().isEmpty()) {
throw new IOException(BLOCK + blockNumber + ": Fixed blocks trying to be set to "
+ phaseConfig.getString(FIXED_BLOCKS) + BUT_ALREADY_SET_TO + obPhase.getFixedBlocks()
+ DUPLICATE);
}
addFixedBlocks(obPhase, phaseConfig.getConfigurationSection(FIXED_BLOCKS));
}
// Add holograms
if (phaseConfig.contains(HOLOGRAMS)) {
if (!obPhase.getHologramLines().isEmpty()) {
throw new IOException(
BLOCK + blockNumber + ": Hologram Lines trying to be set to " + phaseConfig.getString(HOLOGRAMS)
+ BUT_ALREADY_SET_TO + obPhase.getHologramLines() + DUPLICATE);
}
addHologramLines(obPhase, phaseConfig.getConfigurationSection(HOLOGRAMS));
}
}
private void addFixedBlocks(OneBlockPhase obPhase, ConfigurationSection firstBlocksConfig) {
if (firstBlocksConfig == null) {
return;
}
Map<Integer, OneBlockObject> result = parseFirstBlocksConfig(firstBlocksConfig);
// Set the first block if it exists
if (result.containsKey(0)) {
addon.log("Found firstBlock in fixedBlocks.");
obPhase.setFirstBlock(result.get(0));
}
// Store the remainder
obPhase.setFixedBlocks(result);
}
private Map<Integer, OneBlockObject> parseFirstBlocksConfig(ConfigurationSection firstBlocksConfig) {
Map<Integer, OneBlockObject> result = new HashMap<>();
for (String key : firstBlocksConfig.getKeys(false)) {
if (!NumberUtils.isCreatable(key)) {
addon.logError("Fixed block key must be an integer. " + key);
continue;
}
int k = Integer.parseInt(key);
parseBlock(result, firstBlocksConfig, key, k);
}
return result;
}
private void parseBlock(Map<Integer, OneBlockObject> result, ConfigurationSection firstBlocksConfig, String key,
int k) {
if (firstBlocksConfig.isConfigurationSection(key)) {
parseObjectBlock(result, firstBlocksConfig, key, k);
} else {
parseStringBlock(result, firstBlocksConfig, key, k);
}
}
/**
* This method handles the case where the block's value is a configuration
* section, indicating that the block is defined as an object.
*
* @param result the resulting map
* @param firstBlocksConfig config
* @param key key
* @param k integer value of key
*/
private void parseObjectBlock(Map<Integer, OneBlockObject> result, ConfigurationSection firstBlocksConfig,
String key, int k) {
// Object block parsing logic
Map<String, Object> map = firstBlocksConfig.getConfigurationSection(key).getValues(false);
Optional<OneBlockCustomBlock> customBlock = OneBlockCustomBlockCreator.create(map);
if (customBlock.isPresent()) {
result.put(k, new OneBlockObject(customBlock.get(), 0));
} else {
addon.logError("Fixed block key " + key + " material is not a valid custom block. Ignoring.");
}
}
/**
* This method handles the case where the block's value is a string, which could
* either be a custom block or a standard Minecraft material.
*
* @param result the resulting map
* @param firstBlocksConfig config
* @param key key
* @param k integer value of key
*/
private void parseStringBlock(Map<Integer, OneBlockObject> result, ConfigurationSection firstBlocksConfig,
String key, int k) {
// String block parsing logic
String mat = firstBlocksConfig.getString(key);
if (mat == null) {
return;
}
Optional<OneBlockCustomBlock> customBlock = OneBlockCustomBlockCreator.create(mat);
if (customBlock.isPresent()) {
result.put(k, new OneBlockObject(customBlock.get(), 0));
} else {
Material m = Material.matchMaterial(mat);
if (m != null && m.isBlock()) {
result.put(k, new OneBlockObject(m, 0));
} else {
addon.logError("Fixed block key " + key + " material is invalid or not a block. Ignoring.");
}
}
}
private void addHologramLines(OneBlockPhase obPhase, ConfigurationSection fb) {
if (fb == null)
return;
Map<Integer, String> result = new HashMap<>();
for (String key : fb.getKeys(false)) {
if (!NumberUtils.isCreatable(key)) {
addon.logError("Fixed block key must be an integer. " + key);
continue;
}
int k = Integer.parseInt(key);
String line = fb.getString(key);
if (line != null) {
result.put(k, line);
}
}
// Set Hologram Lines
obPhase.setHologramLines(result);
}
private Biome getBiome(String string) {
if (string == null) {
return Biome.PLAINS;
}
NamespacedKey key = NamespacedKey.fromString(string.toLowerCase(Locale.ENGLISH));
Biome result = Registry.BIOME.get(key);
if (result == null) {
addon.logError("Biome " + string + " is invalid! Use one of these...");
Registry.BIOME.stream().sorted(Comparator.comparing(biome -> biome.getKey().getKey()))
.forEach(biome -> addon.logError(biome.getKey().getKey()));
return Biome.PLAINS;
}
return result;
}
void addFirstBlock(OneBlockPhase obPhase, @Nullable String material) {
if (material == null) {
return;
}
Material m = Material.matchMaterial(material);
if (m == null || !m.isBlock()) {
addon.logError("Bad firstBlock material: " + material);
} else {
obPhase.setFirstBlock(new OneBlockObject(m, 0));
}
}
void addCommands(OneBlockPhase obPhase, ConfigurationSection phase) {
if (phase.contains(START_COMMANDS)) {
obPhase.setStartCommands(phase.getStringList(START_COMMANDS));
}
if (phase.contains(END_COMMANDS)) {
obPhase.setEndCommands(phase.getStringList(END_COMMANDS));
}
if (phase.contains(END_COMMANDS_FIRST_TIME)) {
obPhase.setFirstTimeEndCommands(phase.getStringList(END_COMMANDS_FIRST_TIME));
}
}
void addRequirements(OneBlockPhase obPhase, ConfigurationSection phase) {
List<Requirement> reqList = new ArrayList<>();
if (!phase.isConfigurationSection(REQUIREMENTS)) {
return;
}
ConfigurationSection reqs = phase.getConfigurationSection(REQUIREMENTS);
for (ReqType key : Requirement.ReqType.values()) {
if (reqs.contains(key.getKey())) {
Requirement r;
if (key.getClazz().equals(Double.class)) {
r = new Requirement(key, reqs.getDouble(key.getKey()));
} else if (key.getClazz().equals(Long.class)) {
r = new Requirement(key, reqs.getLong(key.getKey()));
} else {
r = new Requirement(key, reqs.getString(key.getKey()));
}
reqList.add(r);
}
}
obPhase.setRequirements(reqList);
}
void addChests(OneBlockPhase obPhase, ConfigurationSection phase) throws IOException {
if (!phase.isConfigurationSection(CHESTS)) {
return;
}
if (!obPhase.getChests().isEmpty()) {
throw new IOException(obPhase.getPhaseName() + ": Chests cannot be set more than once. Duplicate file?");
}
ConfigurationSection chests = phase.getConfigurationSection(CHESTS);
for (String chestId : chests.getKeys(false)) {
ConfigurationSection chest = chests.getConfigurationSection(chestId);
Rarity rarity = Rarity.COMMON;
try {
rarity = OneBlockObject.Rarity.valueOf(chest.getString(RARITY, "COMMON").toUpperCase());
} catch (Exception e) {
addon.logError(
"Rarity value of " + chest.getString(RARITY, "UNKNOWN") + " is invalid! Use one of these...");
addon.logError(Arrays.stream(Rarity.values()).map(Rarity::name).collect(Collectors.joining(",")));
rarity = Rarity.COMMON;
}
Map<Integer, ItemStack> items = new HashMap<>();
ConfigurationSection contents = chest.getConfigurationSection(CONTENTS);
if (contents != null) {
for (String index : contents.getKeys(false)) {
int slot = Integer.parseInt(index);
ItemStack item = contents.getItemStack(index);
if (item != null) {
items.put(slot, item);
}
}
}
obPhase.addChest(items, rarity);
}
}
void addMobs(OneBlockPhase obPhase, ConfigurationSection phase) throws IOException {
if (!phase.isConfigurationSection(MOBS)) {
return;
}
if (!obPhase.getMobs().isEmpty()) {
throw new IOException(obPhase.getPhaseName() + ": Mobs cannot be set more than once. Duplicate file?");
}
ConfigurationSection mobs = phase.getConfigurationSection(MOBS);
for (String entity : mobs.getKeys(false)) {
String name = entity.toUpperCase(Locale.ENGLISH);
EntityType et = null;
// Pig zombie handling
if (name.equals("PIG_ZOMBIE") || name.equals("ZOMBIFIED_PIGLIN")) {
et = Enums.getIfPresent(EntityType.class, "ZOMBIFIED_PIGLIN")
.or(Enums.getIfPresent(EntityType.class, "PIG_ZOMBIE").or(EntityType.PIG));
} else {
et = Enums.getIfPresent(EntityType.class, name).orNull();
}
if (et == null) {
// Does not exist
addon.logError("Bad entity type in " + obPhase.getPhaseName() + ": " + entity);
addon.logError("Try one of these...");
addon.logError(Arrays.stream(EntityType.values()).filter(EntityType::isSpawnable)
.filter(EntityType::isAlive).map(EntityType::name).collect(Collectors.joining(",")));
return;
}
if (et.isSpawnable() && et.isAlive()) {
if (mobs.getInt(entity) > 0) {
obPhase.addMob(et, mobs.getInt(entity));
} else {
addon.logWarning("Bad entity weight for " + obPhase.getPhaseName() + ": " + entity
+ ". Must be positive number above 1.");
}
} else {
addon.logError("Entity type is not spawnable " + obPhase.getPhaseName() + ": " + entity);
}
}
}
void addBlocks(OneBlockPhase obPhase, ConfigurationSection phase) {
if (phase.isConfigurationSection(BLOCKS)) {
ConfigurationSection blocks = phase.getConfigurationSection(BLOCKS);
for (String material : blocks.getKeys(false)) {
addMaterial(obPhase, material, Objects.toString(blocks.get(material)));
}
} else if (phase.isList(BLOCKS)) {
List<Map<?, ?>> blocks = phase.getMapList(BLOCKS);
for (Map<?, ?> map : blocks) {
if (map.size() == 1) {
Map.Entry<?, ?> entry = map.entrySet().iterator().next();
if (addMaterial(obPhase, Objects.toString(entry.getKey()), Objects.toString(entry.getValue()))) {
continue;
}
}
int probability = Integer.parseInt(Objects.toString(map.get("probability"), "0"));
Optional<OneBlockCustomBlock> customBlock = OneBlockCustomBlockCreator.create(map);
if (customBlock.isPresent()) {
obPhase.addCustomBlock(customBlock.get(), probability);
} else {
addon.logError("Bad custom block in " + obPhase.getPhaseName() + ": " + map);
}
}
}
}
private boolean addMaterial(OneBlockPhase obPhase, String material, String probability) {
int prob;
try {
prob = Integer.parseInt(probability);
} catch (Exception e) {
return false;
}
if (prob < 1) {
addon.logWarning("Bad item weight for " + obPhase.getPhaseName() + ": " + material
+ ". Must be positive number above 1.");
return false;
}
// Register if the material is a valid custom block and can be created from the
// short creator from OneBlockCustomBlockCreator
Optional<OneBlockCustomBlock> optionalCustomBlock = OneBlockCustomBlockCreator.create(material);
if (optionalCustomBlock.isPresent()) {
obPhase.addCustomBlock(optionalCustomBlock.get(), prob);
return true;
}
// Otherwise, register the material as a block
Material m = Material.matchMaterial(material);
if (m == null || !m.isBlock()) {
addon.logError("Bad block material in " + obPhase.getPhaseName() + ": " + material);
return false;
}
obPhase.addBlock(m, prob);
return true;
}
/**
* Return the current phase for the block count
*
* @param blockCount - number of blocks mined
* @return the one block phase based on blockCount or null if there is none
*/
@Nullable
public OneBlockPhase getPhase(int blockCount) {
Entry<Integer, OneBlockPhase> en = blockProbs.floorEntry(blockCount);
return en != null ? en.getValue() : null;
}
/**
* @return list of phase names with spaces replaced by underscore so they are
* one word
*/
public List<String> getPhaseList() {
return blockProbs.values().stream().map(OneBlockPhase::getPhaseName).filter(Objects::nonNull)
.map(n -> n.replace(" ", "_")).collect(Collectors.toList());
}
/**
* @return the blockProbs
*/
public NavigableMap<Integer, OneBlockPhase> getBlockProbs() {
return blockProbs;
}
/**
* Get phase by name. Name should have any spaces converted to underscores. Case
* insensitive.
*
* @param name - name to search
* @return optional OneBlockPhase
*/
public Optional<OneBlockPhase> getPhase(String name) {
return blockProbs.values().stream()
.filter(p -> p.getPhaseName() != null && (p.getPhaseName().equalsIgnoreCase(name)
|| p.getPhaseName().replace(" ", "_").equalsIgnoreCase(name)))
.findFirst();
}
/**
* Save all the phases in memory to disk.
*
* @return true if saved
*/
public boolean saveOneBlockConfig() {
// Go through each phase
boolean success = true;
for (OneBlockPhase p : blockProbs.values()) {
success = savePhase(p);
}
return success;
}
/**
* Save a phase
*
* @param p OneBlockPhase
* @return true if successfully saved
*/
public boolean savePhase(OneBlockPhase p) {
if (!saveMainPhase(p)) {
// Failure
return false;
}
// No chests in goto phases
if (p.isGotoPhase()) {
// Done
return true;
}
return saveChestPhase(p);
}
private boolean saveMainPhase(OneBlockPhase p) {
YamlConfiguration oneBlocks = new YamlConfiguration();
ConfigurationSection phSec = oneBlocks.createSection(p.getBlockNumber());
// Check for a goto block
if (p.isGotoPhase()) {
phSec.set(GOTO_BLOCK, p.getGotoBlock());
} else {
phSec.set(NAME, p.getPhaseName());
if (p.getIconBlock() != null) {
phSec.set(ICON, p.getIconBlock().getType().name());
}
if (p.getFirstBlock() != null) {
phSec.set(FIRST_BLOCK, p.getFirstBlock().getMaterial().name());
}
if (p.getPhaseBiome() != null) {
phSec.set(BIOME, p.getPhaseBiome().name());
}
saveBlocks(phSec, p);
saveEntities(phSec, p);
saveHolos(phSec, p);
saveCommands(phSec, p);
}
try {
// Save
File phaseFile = new File(addon.getDataFolder() + File.separator + PHASES, getPhaseFileName(p) + ".yml");
oneBlocks.save(phaseFile);
} catch (IOException e) {
addon.logError("Could not save phase " + p.getPhaseName() + " " + e.getMessage());
return false;
}
return true;
}
private void saveCommands(ConfigurationSection phSec, OneBlockPhase p) {
phSec.set(START_COMMANDS, p.getStartCommands());
phSec.set(END_COMMANDS, p.getEndCommands());
}
private void saveHolos(ConfigurationSection phSec, OneBlockPhase p) {
if (p.getHologramLines() == null)
return;
ConfigurationSection holos = phSec.createSection(HOLOGRAMS);
p.getHologramLines().forEach((k, v) -> holos.set(String.valueOf(k), v));
}
private boolean saveChestPhase(OneBlockPhase p) {
YamlConfiguration oneBlocks = new YamlConfiguration();
ConfigurationSection phSec = oneBlocks.createSection(p.getBlockNumber());
saveChests(phSec, p);
try {
// Save
File phaseFile = new File(addon.getDataFolder() + File.separator + PHASES,
getPhaseFileName(p) + "_chests.yml");
oneBlocks.save(phaseFile);
} catch (IOException e) {
addon.logError("Could not save chest phase " + p.getPhaseName() + " " + e.getMessage());
return false;
}
return true;
}
private String getPhaseFileName(OneBlockPhase p) {
if (p.isGotoPhase()) {
return p.getBlockNumber() + "_goto_" + p.getGotoBlock();
}
return p.getBlockNumber() + "_"
+ (p.getPhaseName() == null ? "" : p.getPhaseName().toLowerCase().replace(' ', '_'));
}
private void saveChests(ConfigurationSection phSec, OneBlockPhase phase) {
ConfigurationSection chests = phSec.createSection(CHESTS);
int index = 1;
for (OneBlockObject chest : phase.getChests()) {
ConfigurationSection c = chests.createSection(String.valueOf(index++));
c.set(CONTENTS, chest.getChest());
c.set(RARITY, chest.getRarity().name());
}
}
private void saveEntities(ConfigurationSection phSec, OneBlockPhase phase) {
ConfigurationSection mobs = phSec.createSection(MOBS);
phase.getMobs().forEach((k, v) -> mobs.set(k.name(), v));
}
private void saveBlocks(ConfigurationSection phSec, OneBlockPhase phase) {
ConfigurationSection fixedBlocks = phSec.createSection(FIXED_BLOCKS);
phase.getFixedBlocks().forEach((k, v) -> fixedBlocks.set(String.valueOf(k), v.getMaterial().name()));
ConfigurationSection blocks = phSec.createSection(BLOCKS);
phase.getBlocks().forEach((k, v) -> blocks.set(k.name(), v));
}
/**
* Get the phase after this one
*
* @param phase - one block phase
* @return next phase or null if there isn't one
*/
@SuppressWarnings("WrapperTypeMayBePrimitive")
@Nullable
public OneBlockPhase getNextPhase(@NonNull OneBlockPhase phase) {
// These are Integer objects because GSON can yield nulls if they do not exist
Integer blockNum = phase.getBlockNumberValue();
Integer nextKey = blockProbs.ceilingKey(blockNum + 1);
return nextKey != null ? this.getPhase(nextKey) : null;
}
/**
* Get the number of blocks until the next phase after this one
*
* @param obi - one block island
* @return number of blocks to the next phase. If there is no phase after -1 is
* returned.
*/
public int getNextPhaseBlocks(@NonNull OneBlockIslands obi) {
Integer blockNum = obi.getBlockNumber();
Integer nextKey = blockProbs.ceilingKey(blockNum + 1);
if (nextKey == null) {
return -1;
}
OneBlockPhase nextPhase = this.getPhase(nextKey);
return nextPhase == null ? -1 : (nextPhase.getBlockNumberValue() - obi.getBlockNumber());
}
/**
* Get the number of blocks for this phase
*
* @param obi - one block island
* @return number of blocks for this current phase. If there is no phase after
* -1 is returned.
*/
public int getPhaseBlocks(@NonNull OneBlockIslands obi) {
Integer blockNum = obi.getBlockNumber();
Integer nextKey = blockProbs.ceilingKey(blockNum + 1);
if (nextKey == null) {
return -1;
}
OneBlockPhase thisPhase = this.getPhase(blockNum);
if (thisPhase == null)
return -1;
OneBlockPhase nextPhase = this.getPhase(nextKey);
return nextPhase == null ? -1 : (nextPhase.getBlockNumberValue() - thisPhase.getBlockNumberValue());
}
/**
* Get the percentage done of this phase
*
* @param obi - one block island
* @return percentage done. If there is no next phase then return 0
*/
public double getPercentageDone(@NonNull OneBlockIslands obi) {
int blockNum = obi.getBlockNumber();
OneBlockPhase thisPhase = this.getPhase(blockNum);
if (thisPhase == null) {
return 0;
}
Integer nextKey = blockProbs.ceilingKey(blockNum + 1);
if (nextKey == null) {
return 0;
}
OneBlockPhase nextPhase = this.getPhase(nextKey);
if (nextPhase == null) {
return 0;
}
int phaseSize = nextPhase.getBlockNumberValue() - thisPhase.getBlockNumberValue();
return 100 - (100 * (double) (nextPhase.getBlockNumberValue() - obi.getBlockNumber()) / phaseSize);
}
public void getProbs(OneBlockPhase phase) {
// Find the phase after this one
Integer blockNum = Integer.valueOf(phase.getBlockNumber());
Integer nextKey = blockProbs.ceilingKey(blockNum + 1);
if (nextKey != null) {
// This is the size of the phase in blocks
int phaseSize = nextKey - blockNum;
int blockTotal = phase.getBlockTotal();
int likelyChestTotal = 0;
double totalBlocks = 0;
// Now calculate the relative block probability
for (Entry<Material, Integer> en : phase.getBlocks().entrySet()) {
double chance = (double) en.getValue() / blockTotal;
double likelyNumberGenerated = chance * phaseSize;
totalBlocks += likelyNumberGenerated;
String report = en.getKey() + " likely generated = " + Math.round(likelyNumberGenerated) + " = "
+ Math.round(likelyNumberGenerated * 100 / phaseSize) + "%";
if (likelyNumberGenerated < 1) {
addon.logWarning(report);
} else {
addon.log(report);
}
if (en.getKey().equals(Material.CHEST)) {
likelyChestTotal = (int) Math.round(likelyNumberGenerated);
}
}
addon.log("Total blocks generated = " + totalBlocks);
// Get the specific chest probability
if (likelyChestTotal == 0) {
addon.logWarning("No chests will be generated");
return;
}
addon.log("**** A total of " + likelyChestTotal + " chests will be generated ****");
// Now calculate chest chances
double lastChance = 0;
for (Entry<Double, Rarity> en : OneBlockPhase.CHEST_CHANCES.entrySet()) {
// Get the number of chests in this rarity group
int num = phase.getChestsMap().getOrDefault(en.getValue(), Collections.emptyList()).size();
double likelyNumberGenerated = (en.getKey() - lastChance) * likelyChestTotal;
lastChance = en.getKey();
String report = num + " " + en.getValue() + " chests in phase. Likely number generated = "
+ Math.round(likelyNumberGenerated);
if (num > 0 && likelyNumberGenerated < 1) {
addon.logWarning(report);
} else {
addon.log(report);
}
}
// Mobs
addon.log("-=-=-=-= Mobs -=-=-=-=-");
double totalMobs = 0;
// Now calculate the relative block probability
for (Entry<EntityType, Integer> en : phase.getMobs().entrySet()) {
double chance = (double) en.getValue() / phase.getTotal();
double likelyNumberGenerated = chance * phaseSize;
totalMobs += likelyNumberGenerated;
String report = en.getKey() + " likely generated = " + Math.round(likelyNumberGenerated) + " = "
+ Math.round(likelyNumberGenerated * 100 / phaseSize) + "%";
if (likelyNumberGenerated < 1) {
addon.logWarning(report);
} else {
addon.log(report);
}
}
addon.log("**** A total of " + Math.round(totalMobs) + " mobs will likely be generated ****");
}
}
/**
* Get all the probs for each phases and log to console
*/
public void getAllProbs() {
blockProbs.values().forEach(this::getProbs);
}
/**
* Get the next phase name
*
* @param obi - one block island
* @return next phase name or an empty string
*/
public String getNextPhase(@NonNull OneBlockIslands obi) {
return getPhase(obi.getPhaseName()).map(this::getNextPhase) // Next phase or null
.filter(Objects::nonNull).map(OneBlockPhase::getPhaseName).orElse("");
}
}