diff --git a/build.gradle b/build.gradle index 7feaeb8..a3b4d91 100644 --- a/build.gradle +++ b/build.gradle @@ -1,93 +1,150 @@ buildscript { repositories { - jcenter() maven { url = "http://files.minecraftforge.net/maven" } + jcenter() + mavenCentral() } dependencies { - classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT' - classpath 'com.github.jengelman.gradle.plugins:shadow:4.0.1' + classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '3.+', changing: true } } -apply plugin: 'net.minecraftforge.gradle.forge' -apply plugin: 'com.github.johnrengelman.shadow' +apply plugin: 'net.minecraftforge.gradle' +apply plugin: 'eclipse' +//apply plugin: 'maven-publish' -version = "1.8" +version = "1.9" group = "com.seodisparate.TurnBasedMinecraft" archivesBaseName = "TurnBasedMinecraft" -sourceCompatibility = targetCompatibility = '1.8' // Need this here so eclipse task generates correctly. -compileJava { - sourceCompatibility = targetCompatibility = '1.8' -} +sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = '1.8' // Need this here so eclipse task generates correctly. minecraft { - version = "1.12.2-14.23.5.2768" - runDir = "run" - - // the mappings can be changed at any time, and must be in the following format. - // snapshot_YYYYMMDD snapshot are built nightly. - // stable_# stables are built at the discretion of the MCP team. + // The mappings can be changed at any time, and must be in the following format. + // snapshot_YYYYMMDD Snapshot are built nightly. + // stable_# Stables are built at the discretion of the MCP team. // Use non-default mappings at your own risk. they may not always work. - // simply re-run your setup task after changing the mappings to update your workspace. - mappings = "snapshot_20171003" + // Simply re-run your setup task after changing the mappings to update your workspace. + mappings channel: 'snapshot', version: '20190719-1.14.3' // makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable. + + // accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') + + // Default run configurations. + // These can be tweaked, removed, or duplicated as needed. + runs { + client { + workingDirectory project.file('run') + + // Recommended logging data for a userdev environment + property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP' + + // Recommended logging level for the console + property 'forge.logging.console.level', 'debug' + + mods { + TurnBasedMinecraftMod { + source sourceSets.main + } + } + } + + server { + workingDirectory project.file('run') + + // Recommended logging data for a userdev environment + property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP' + + // Recommended logging level for the console + property 'forge.logging.console.level', 'debug' + + mods { + TurnBasedMinecraftMod { + source sourceSets.main + } + } + } + + data { + workingDirectory project.file('run') + + // Recommended logging data for a userdev environment + property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP' + + // Recommended logging level for the console + property 'forge.logging.console.level', 'debug' + + args '--mod', 'TurnBasedMinecraftMod', '--all', '--output', file('src/generated/resources/') + + mods { + TurnBasedMinecraftMod { + source sourceSets.main + } + } + } + } } dependencies { - // you may put jars on which you depend on in ./libs - // or you may define them like so.. - //compile "some.group:artifact:version:classifier" - //compile "some.group:artifact:version" + // Specify the version of Minecraft to use, If this is any group other then 'net.minecraft' it is assumed + // that the dep is a ForgeGradle 'patcher' dependency. And it's patches will be applied. + // The userdev artifact is a special name and will get all sorts of transformations applied to it. + minecraft 'net.minecraftforge:forge:1.14.4-28.1.0' - // toml parser - compile "net.consensys.cava:cava-toml:0.3.1" - - // real examples - //compile 'com.mod-buildcraft:buildcraft:6.0.8:dev' // adds buildcraft to the dev env - //compile 'com.googlecode.efficient-java-matrix-library:ejml:0.24' // adds ejml to the dev env + // You may put jars on which you depend on in ./libs or you may define them like so.. + // compile "some.group:artifact:version:classifier" + // compile "some.group:artifact:version" - // the 'provided' configuration is for optional dependencies that exist at compile-time but might not at runtime. - //provided 'com.mod-buildcraft:buildcraft:6.0.8:dev' + // Real examples + // compile 'com.mod-buildcraft:buildcraft:6.0.8:dev' // adds buildcraft to the dev env + // compile 'com.googlecode.efficient-java-matrix-library:ejml:0.24' // adds ejml to the dev env - // the deobf configurations: 'deobfCompile' and 'deobfProvided' are the same as the normal compile and provided, - // except that these dependencies get remapped to your current MCP mappings - //deobfCompile 'com.mod-buildcraft:buildcraft:6.0.8:dev' - //deobfProvided 'com.mod-buildcraft:buildcraft:6.0.8:dev' + // The 'provided' configuration is for optional dependencies that exist at compile-time but might not at runtime. + // provided 'com.mod-buildcraft:buildcraft:6.0.8:dev' - // for more info... + // These dependencies get remapped to your current MCP mappings + // deobf 'com.mod-buildcraft:buildcraft:6.0.8:dev' + + // For more info... // http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html // http://www.gradle.org/docs/current/userguide/dependency_management.html + compile files('src/main/resources/META-INF/libraries/javamp3-1.0.3.jar') } -processResources { - // this will ensure that this task is redone when the versions change. - inputs.property "version", project.version - inputs.property "mcversion", project.minecraft.version - - // replace stuff in mcmod.info, nothing else - from(sourceSets.main.resources.srcDirs) { - include 'mcmod.info' - - // replace version and mcversion - expand 'version':project.version, 'mcversion':project.minecraft.version - } - - // copy everything else except the mcmod.info - from(sourceSets.main.resources.srcDirs) { - exclude 'mcmod.info' +// Example for how to get properties into the manifest for reading by the runtime.. +jar { + manifest { + attributes([ + "Specification-Title": "TurnBasedMinecraftMod", + "Specification-Vendor": "TurnBasedMinecraftMod_SS", + "Specification-Version": "1", // We are version 1 of ourselves + "Implementation-Title": project.name, + "Implementation-Version": "${version}", + "Implementation-Vendor" :"TurnBasedMinecraftMod_SS", + "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"), + "ContainedDeps": "javamp3-1.0.3.jar" + ]) } } -shadowJar { - classifier "" - - relocate 'net.consensys.cava', 'shadow.turnbasedmc.net.consensys.cava' - relocate 'org.antlr.v4', 'shadow.turnbasedmc.org.antlr.v4' - relocate 'javax.annotation', 'shadow.turnbasedmc.javax.annotation' - - relocate 'fr.delthas', 'shadow.turnbasedmc.fr.delthas' +// Example configuration to allow publishing using the maven-publish task +// we define a custom artifact that is sourced from the reobfJar output task +// and then declare that to be published +// Note you'll need to add a repository here +def reobfFile = file("$buildDir/reobfJar/output.jar") +def reobfArtifact = artifacts.add('default', reobfFile) { + type 'jar' + builtBy 'reobfJar' } - -reobf { shadowJar { mappingType = "SEARGE" } } -tasks.reobfShadowJar.mustRunAfter shadowJar +//publishing { +// publications { +// mavenJava(MavenPublication) { +// artifact reobfArtifact +// } +// } +// repositories { +// maven { +// url "file:///${project.projectDir}/mcmodsrepo" +// } +// } +//} diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/client/BattleGui.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/client/BattleGui.java index 44e97d0..b6cdc72 100644 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/client/BattleGui.java +++ b/src/main/java/com/seodisparate/TurnBasedMinecraft/client/BattleGui.java @@ -1,6 +1,5 @@ package com.seodisparate.TurnBasedMinecraft.client; -import java.io.IOException; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.Map; @@ -13,370 +12,334 @@ import com.seodisparate.TurnBasedMinecraft.common.TurnBasedMinecraftMod; import com.seodisparate.TurnBasedMinecraft.common.networking.PacketBattleDecision; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.client.gui.widget.button.Button; +import net.minecraft.util.text.StringTextComponent; -public class BattleGui extends GuiScreen -{ - private AtomicInteger timeRemaining; - private long lastInstant; - private long elapsedTime; - private MenuState state; - private boolean stateChanged; - private String info; - - private enum MenuState - { - MAIN_MENU(0), - ATTACK_TARGET(1), - ITEM_ACTION(2), - WAITING(3), - SWITCH_ITEM(4), - USE_ITEM(5); - - private int value; - - MenuState(int value) - { - this.value = value; - } - - public int getValue() - { - return value; - } - - private static Map map; - - static - { - map = new HashMap(); - for(MenuState state : MenuState.values()) - { - map.put(state.getValue(), state); - } - } - - public static MenuState valueOf(int value) - { - return map.get(value); - } - } - - private enum ButtonAction - { - ATTACK(0), - DEFEND(1), - ITEM(2), - FLEE(3), - ATTACK_TARGET(4), - SWITCH_HELD_ITEM(5), - DECIDE_USE_ITEM(6), - CANCEL(7), - DO_ITEM_SWITCH(8), - DO_USE_ITEM(9); - - private int value; - - ButtonAction(int value) - { - this.value = value; - } - - public int getValue() - { - return value; - } - - private static Map map; - static - { - map = new HashMap(); - for(ButtonAction action : ButtonAction.values()) - { - map.put(action.getValue(), action); - } - } - - public static ButtonAction valueOf(int value) - { - return map.get(value); - } - } - - public BattleGui() - { - timeRemaining = new AtomicInteger((int)(Config.BATTLE_DECISION_DURATION_NANO_DEFAULT / 1000000000L)); - lastInstant = System.nanoTime(); - elapsedTime = 0; - state = MenuState.MAIN_MENU; - stateChanged = true; - } - - private void setState(MenuState state) - { - this.state = state; - stateChanged = true; - } - - public void turnBegin() - { - if(TurnBasedMinecraftMod.proxy.getLocalBattle() != null) - { - TurnBasedMinecraftMod.proxy.getLocalBattle().setState(Battle.State.ACTION); - } - setState(MenuState.WAITING); - } - - public void turnEnd() - { - if(TurnBasedMinecraftMod.proxy.getLocalBattle() != null) - { - TurnBasedMinecraftMod.proxy.getLocalBattle().setState(Battle.State.DECISION); - } - timeRemaining.set(TurnBasedMinecraftMod.proxy.getConfig().getDecisionDurationSeconds()); - elapsedTime = 0; - lastInstant = System.nanoTime(); - setState(MenuState.MAIN_MENU); - } - - public void battleChanged() - { - stateChanged = true; - } - - public void updateState() - { - if(!stateChanged) - { - return; - } - - stateChanged = false; - buttonList.clear(); - switch(state) - { - case MAIN_MENU: - info = "What will you do?"; - buttonList.add(new GuiButton(ButtonAction.ATTACK.getValue(), width*3/7 - 25, 40, 50, 20, "Attack")); - buttonList.add(new GuiButton(ButtonAction.DEFEND.getValue(), width*4/7 - 25, 40, 50, 20, "Defend")); - buttonList.add(new GuiButton(ButtonAction.ITEM.getValue(), width*3/7 - 25, 60, 50, 20, "Item")); - buttonList.add(new GuiButton(ButtonAction.FLEE.getValue(), width*4/7 - 25, 60, 50, 20, "Flee")); - break; - case ATTACK_TARGET: - info = "Who will you attack?"; - int y = 30; - try - { - for(Map.Entry e : TurnBasedMinecraftMod.proxy.getLocalBattle().getSideAEntrySet()) - { - if(e.getValue().entity != null) - { - buttonList.add(new EntitySelectionButton(ButtonAction.ATTACK_TARGET.getValue(), width/4 - 60, y, 120, 20, e.getValue().entity.getName(), e.getKey(), true)); - } - else - { - buttonList.add(new EntitySelectionButton(ButtonAction.ATTACK_TARGET.getValue(), width/4 - 60, y, 120, 20, "Unknown", e.getKey(), true)); - } - y += 20; - } - } catch (ConcurrentModificationException e) - { - // ignored - } - y = 30; - try - { - for(Map.Entry e : TurnBasedMinecraftMod.proxy.getLocalBattle().getSideBEntrySet()) - { - if(e.getValue().entity != null) - { - buttonList.add(new EntitySelectionButton(ButtonAction.ATTACK_TARGET.getValue(), width*3/4 - 60, y, 120, 20, e.getValue().entity.getName(), e.getKey(), false)); - } - else - { - buttonList.add(new EntitySelectionButton(ButtonAction.ATTACK_TARGET.getValue(), width*3/4 - 60, y, 120, 20, "Unknown", e.getKey(), false)); - } - y += 20; - } - } catch (ConcurrentModificationException e) - { - // ignored - } - buttonList.add(new GuiButton(ButtonAction.CANCEL.getValue(), width/2 - 30, height - 120, 60, 20, "Cancel")); - break; - case ITEM_ACTION: - info = "What will you do with an item?"; - buttonList.add(new GuiButton(ButtonAction.SWITCH_HELD_ITEM.getValue(), width*1/4 - 40, height - 120, 80, 20, "Switch Held")); - buttonList.add(new GuiButton(ButtonAction.DECIDE_USE_ITEM.getValue(), width*2/4 - 40, height - 120, 80, 20, "Use")); - buttonList.add(new GuiButton(ButtonAction.CANCEL.getValue(), width*3/4 - 40, height - 120, 80, 20, "Cancel")); - break; - case WAITING: - info = "Waiting..."; - break; - case SWITCH_ITEM: - info = "To which item will you switch to?"; - for(int i = 0; i < 9; ++i) - { - buttonList.add(new ItemSelectionButton(ButtonAction.DO_ITEM_SWITCH.getValue(), width/2 - 88 + i * 20, height - 19, 16, 16, "", i)); - } - buttonList.add(new GuiButton(ButtonAction.CANCEL.getValue(), width/2 - 40, height - 120, 80, 20, "Cancel")); - break; - case USE_ITEM: - info = "Which item will you use?"; - for(int i = 0; i < 9; ++i) - { - buttonList.add(new ItemSelectionButton(ButtonAction.DO_USE_ITEM.getValue(), width/2 - 88 + i * 20, height - 19, 16, 16, "", i)); - } - buttonList.add(new GuiButton(ButtonAction.CANCEL.getValue(), width/2 - 40, height - 120, 80, 20, "Cancel")); - break; - } - } +public class BattleGui extends Screen { + private AtomicInteger timeRemaining; + private long lastInstant; + private long elapsedTime; + private MenuState state; + private boolean stateChanged; + private String info; - @Override - public void drawScreen(int mouseX, int mouseY, float partialTicks) - { - if(TurnBasedMinecraftMod.proxy.getLocalBattle() == null) - { - drawHoveringText("Waiting...", width / 2 - 50, height / 2); - return; - } - if(TurnBasedMinecraftMod.proxy.getLocalBattle().getState() == Battle.State.DECISION && timeRemaining.get() > 0) - { - long nextInstant = System.nanoTime(); - elapsedTime += nextInstant - lastInstant; - lastInstant = nextInstant; - while(elapsedTime > 1000000000) - { - elapsedTime -= 1000000000; - timeRemaining.decrementAndGet(); - } - } - - updateState(); - - super.drawScreen(mouseX, mouseY, partialTicks); - - String timeRemainingString = "Time remaining: "; - int timeRemainingInt = timeRemaining.get(); - if(timeRemainingInt > 8) - { - timeRemainingString += "\u00A7a"; - } - else if(timeRemainingInt > 4) - { - timeRemainingString += "\u00A7e"; - } - else - { - timeRemainingString += "\u00A7c"; - } - timeRemainingString += Integer.toString(timeRemainingInt); - int stringWidth = Minecraft.getMinecraft().fontRenderer.getStringWidth(timeRemainingString); - drawRect(width/2 - stringWidth/2, 5, width/2 + stringWidth/2, 15, 0x70000000); - Minecraft.getMinecraft().fontRenderer.drawString(timeRemainingString, width/2 - stringWidth/2, 5, 0xFFFFFFFF); - stringWidth = Minecraft.getMinecraft().fontRenderer.getStringWidth(info); - drawRect(width/2 - stringWidth/2, 20, width/2 + stringWidth/2, 30, 0x70000000); - Minecraft.getMinecraft().fontRenderer.drawString(info, width/2 - stringWidth/2, 20, 0xFFFFFFFF); - } + private enum MenuState { + MAIN_MENU(0), ATTACK_TARGET(1), ITEM_ACTION(2), WAITING(3), SWITCH_ITEM(4), USE_ITEM(5); - @Override - protected void actionPerformed(GuiButton button) throws IOException - { - switch(ButtonAction.valueOf(button.id)) - { - case ATTACK: - setState(MenuState.ATTACK_TARGET); - break; - case DEFEND: - TurnBasedMinecraftMod.NWINSTANCE.sendToServer(new PacketBattleDecision(TurnBasedMinecraftMod.proxy.getLocalBattle().getId(), Battle.Decision.DEFEND, 0)); - setState(MenuState.WAITING); - break; - case ITEM: - setState(MenuState.ITEM_ACTION); - break; - case FLEE: - TurnBasedMinecraftMod.NWINSTANCE.sendToServer(new PacketBattleDecision(TurnBasedMinecraftMod.proxy.getLocalBattle().getId(), Battle.Decision.FLEE, 0)); - setState(MenuState.WAITING); - break; - case ATTACK_TARGET: - if(button instanceof EntitySelectionButton) - { - TurnBasedMinecraftMod.NWINSTANCE.sendToServer(new PacketBattleDecision(TurnBasedMinecraftMod.proxy.getLocalBattle().getId(), Battle.Decision.ATTACK, ((EntitySelectionButton)button).entityID)); - setState(MenuState.WAITING); - } - else - { - setState(MenuState.MAIN_MENU); - } - break; - case SWITCH_HELD_ITEM: - setState(MenuState.SWITCH_ITEM); - break; - case DECIDE_USE_ITEM: - setState(MenuState.USE_ITEM); - break; - case CANCEL: - setState(MenuState.MAIN_MENU); - break; - case DO_ITEM_SWITCH: - if(button instanceof ItemSelectionButton) - { - TurnBasedMinecraftMod.NWINSTANCE.sendToServer(new PacketBattleDecision(TurnBasedMinecraftMod.proxy.getLocalBattle().getId(), Battle.Decision.SWITCH_ITEM, ((ItemSelectionButton)button).itemStackID)); - if(((ItemSelectionButton)button).itemStackID >= 0 && ((ItemSelectionButton)button).itemStackID < 9) - { - Minecraft.getMinecraft().player.inventory.currentItem = ((ItemSelectionButton)button).itemStackID; - } - setState(MenuState.WAITING); - } - else - { - setState(MenuState.MAIN_MENU); - } - break; - case DO_USE_ITEM: - if(button instanceof ItemSelectionButton) - { - TurnBasedMinecraftMod.NWINSTANCE.sendToServer(new PacketBattleDecision(TurnBasedMinecraftMod.proxy.getLocalBattle().getId(), Battle.Decision.USE_ITEM, ((ItemSelectionButton)button).itemStackID)); - setState(MenuState.WAITING); - } - else - { - setState(MenuState.MAIN_MENU); - } - break; - } - } + private int value; - @Override - public void initGui() - { - super.initGui(); - } + MenuState(int value) { + this.value = value; + } - @Override - public void onGuiClosed() - { - super.onGuiClosed(); - } + public int getValue() { + return value; + } - @Override - public boolean doesGuiPauseGame() - { - return false; - } + private static Map map; - @Override - protected void keyTyped(char typedChar, int keyCode) throws IOException - { - if(Minecraft.getMinecraft().player.isCreative()) - { - super.keyTyped(typedChar, keyCode); - } - } - - public void setTimeRemaining(int remaining) - { - timeRemaining.set(remaining); - } + static { + map = new HashMap(); + for (MenuState state : MenuState.values()) { + map.put(state.getValue(), state); + } + } + + public static MenuState valueOf(int value) { + return map.get(value); + } + } + + private enum ButtonAction { + ATTACK(0), DEFEND(1), ITEM(2), FLEE(3), ATTACK_TARGET(4), SWITCH_HELD_ITEM(5), DECIDE_USE_ITEM(6), CANCEL(7), + DO_ITEM_SWITCH(8), DO_USE_ITEM(9); + + private int value; + + ButtonAction(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + + private static Map map; + static { + map = new HashMap(); + for (ButtonAction action : ButtonAction.values()) { + map.put(action.getValue(), action); + } + } + + public static ButtonAction valueOf(int value) { + return map.get(value); + } + } + + public BattleGui() { + super(new StringTextComponent("Battle Gui")); + timeRemaining = new AtomicInteger((int) (Config.BATTLE_DECISION_DURATION_NANO_DEFAULT / 1000000000L)); + lastInstant = System.nanoTime(); + elapsedTime = 0; + state = MenuState.MAIN_MENU; + stateChanged = true; + } + + private void setState(MenuState state) { + this.state = state; + stateChanged = true; + } + + public void turnBegin() { + if (TurnBasedMinecraftMod.proxy.getLocalBattle() != null) { + TurnBasedMinecraftMod.proxy.getLocalBattle().setState(Battle.State.ACTION); + } + setState(MenuState.WAITING); + } + + public void turnEnd() { + if (TurnBasedMinecraftMod.proxy.getLocalBattle() != null) { + TurnBasedMinecraftMod.proxy.getLocalBattle().setState(Battle.State.DECISION); + } + timeRemaining.set(TurnBasedMinecraftMod.proxy.getConfig().getDecisionDurationSeconds()); + elapsedTime = 0; + lastInstant = System.nanoTime(); + setState(MenuState.MAIN_MENU); + } + + public void battleChanged() { + stateChanged = true; + } + + public void updateState() { + if (!stateChanged) { + return; + } + + stateChanged = false; + buttons.clear(); + children.clear(); + switch (state) { + case MAIN_MENU: + info = "What will you do?"; + addButton(new Button(width * 3 / 7 - 25, 40, 50, 20, "Attack", (button) -> { + buttonActionEvent(button, ButtonAction.ATTACK); + })); + addButton(new Button(width * 4 / 7 - 25, 40, 50, 20, "Defend", (button) -> { + buttonActionEvent(button, ButtonAction.DEFEND); + })); + addButton(new Button(width * 3 / 7 - 25, 60, 50, 20, "Item", (button) -> { + buttonActionEvent(button, ButtonAction.ITEM); + })); + addButton(new Button(width * 4 / 7 - 25, 60, 50, 20, "Flee", (button) -> { + buttonActionEvent(button, ButtonAction.FLEE); + })); + break; + case ATTACK_TARGET: + info = "Who will you attack?"; + int y = 30; + try { + for (Map.Entry e : TurnBasedMinecraftMod.proxy.getLocalBattle() + .getSideAEntrySet()) { + if (e.getValue().entity != null) { + addButton(new EntitySelectionButton(width / 4 - 60, y, 120, 20, e.getValue().entity.getName().getString(), e.getKey(), true, (button) -> { + buttonActionEvent(button, ButtonAction.ATTACK_TARGET); + })); + } else { + addButton(new EntitySelectionButton(width / 4 - 60, y, 120, 20, "Unknown", e.getKey(), true, (button) -> { + buttonActionEvent(button, ButtonAction.ATTACK_TARGET); + })); + } + y += 20; + } + } catch (ConcurrentModificationException e) { + // ignored + } + y = 30; + try { + for (Map.Entry e : TurnBasedMinecraftMod.proxy.getLocalBattle() + .getSideBEntrySet()) { + if (e.getValue().entity != null) { + addButton(new EntitySelectionButton(width * 3 / 4 - 60, y, 120, 20, e.getValue().entity.getName().getString(), e.getKey(), false, (button) -> { + buttonActionEvent(button, ButtonAction.ATTACK_TARGET); + })); + } else { + addButton(new EntitySelectionButton(width * 3 / 4 - 60, y, 120, 20, "Unknown", e.getKey(), false, (button) -> { + buttonActionEvent(button, ButtonAction.ATTACK_TARGET); + })); + } + y += 20; + } + } catch (ConcurrentModificationException e) { + // ignored + } + addButton(new Button(width / 2 - 30, height - 120, 60, 20, "Cancel", (button) -> { + buttonActionEvent(button, ButtonAction.CANCEL); + })); + break; + case ITEM_ACTION: + info = "What will you do with an item?"; + addButton(new Button(width * 1 / 4 - 40, height - 120, 80, 20, "Switch Held", (button) -> { + buttonActionEvent(button, ButtonAction.SWITCH_HELD_ITEM); + })); + addButton(new Button(width * 2 / 4 - 40, height - 120, 80, 20, "Use", (button) -> { + buttonActionEvent(button, ButtonAction.DECIDE_USE_ITEM); + })); + addButton(new Button(width * 3 / 4 - 40, height - 120, 80, 20, "Cancel", (button) -> { + buttonActionEvent(button, ButtonAction.CANCEL); + })); + break; + case WAITING: + info = "Waiting..."; + break; + case SWITCH_ITEM: + info = "To which item will you switch to?"; + for (int i = 0; i < 9; ++i) { + addButton(new ItemSelectionButton(width / 2 - 88 + i * 20, height - 19, 16, 16, "", i, (button) -> { + buttonActionEvent(button, ButtonAction.DO_ITEM_SWITCH); + })); + } + addButton(new Button(width / 2 - 40, height - 120, 80, 20, "Cancel", (button) -> { + buttonActionEvent(button, ButtonAction.CANCEL); + })); + break; + case USE_ITEM: + info = "Which item will you use?"; + for (int i = 0; i < 9; ++i) { + addButton(new ItemSelectionButton(width / 2 - 88 + i * 20, height - 19, 16, 16, "", i, (button) -> { + buttonActionEvent(button, ButtonAction.DO_USE_ITEM); + })); + } + addButton(new Button(width / 2 - 40, height - 120, 80, 20, "Cancel", (button) -> { + buttonActionEvent(button, ButtonAction.CANCEL); + })); + break; + } + } + + @Override + public void render(int mouseX, int mouseY, float partialTicks) { + if (TurnBasedMinecraftMod.proxy.getLocalBattle() == null) { + // drawHoveringText("Waiting...", width / 2 - 50, height / 2); + getMinecraft().fontRenderer.drawString("Waiting...", width / 2 - 50, height / 2, 0xFFFFFFFF); + return; + } + if (TurnBasedMinecraftMod.proxy.getLocalBattle().getState() == Battle.State.DECISION + && timeRemaining.get() > 0) { + long nextInstant = System.nanoTime(); + elapsedTime += nextInstant - lastInstant; + lastInstant = nextInstant; + while (elapsedTime > 1000000000) { + elapsedTime -= 1000000000; + timeRemaining.decrementAndGet(); + } + } + + updateState(); + + super.render(mouseX, mouseY, partialTicks); + + String timeRemainingString = "Time remaining: "; + int timeRemainingInt = timeRemaining.get(); + if (timeRemainingInt > 8) { + timeRemainingString += "\u00A7a"; + } else if (timeRemainingInt > 4) { + timeRemainingString += "\u00A7e"; + } else { + timeRemainingString += "\u00A7c"; + } + timeRemainingString += Integer.toString(timeRemainingInt); + int stringWidth = getMinecraft().fontRenderer.getStringWidth(timeRemainingString); + fill(width / 2 - stringWidth / 2, 5, width / 2 + stringWidth / 2, 15, 0x70000000); + getMinecraft().fontRenderer.drawString(timeRemainingString, width / 2 - stringWidth / 2, 5, 0xFFFFFFFF); + stringWidth = getMinecraft().fontRenderer.getStringWidth(info); + fill(width / 2 - stringWidth / 2, 20, width / 2 + stringWidth / 2, 30, 0x70000000); + getMinecraft().fontRenderer.drawString(info, width / 2 - stringWidth / 2, 20, 0xFFFFFFFF); + } + + protected void buttonActionEvent(Button button, ButtonAction action) { + switch (action) { + case ATTACK: + setState(MenuState.ATTACK_TARGET); + break; + case DEFEND: + TurnBasedMinecraftMod.getHandler().sendToServer(new PacketBattleDecision( + TurnBasedMinecraftMod.proxy.getLocalBattle().getId(), Battle.Decision.DEFEND, 0)); + setState(MenuState.WAITING); + break; + case ITEM: + setState(MenuState.ITEM_ACTION); + break; + case FLEE: + TurnBasedMinecraftMod.getHandler().sendToServer(new PacketBattleDecision( + TurnBasedMinecraftMod.proxy.getLocalBattle().getId(), Battle.Decision.FLEE, 0)); + setState(MenuState.WAITING); + break; + case ATTACK_TARGET: + if (button instanceof EntitySelectionButton) { + TurnBasedMinecraftMod.getHandler() + .sendToServer(new PacketBattleDecision(TurnBasedMinecraftMod.proxy.getLocalBattle().getId(), + Battle.Decision.ATTACK, ((EntitySelectionButton) button).getID())); + setState(MenuState.WAITING); + } else { + setState(MenuState.MAIN_MENU); + } + break; + case SWITCH_HELD_ITEM: + setState(MenuState.SWITCH_ITEM); + break; + case DECIDE_USE_ITEM: + setState(MenuState.USE_ITEM); + break; + case CANCEL: + setState(MenuState.MAIN_MENU); + break; + case DO_ITEM_SWITCH: + if (button instanceof ItemSelectionButton) { + TurnBasedMinecraftMod.getHandler() + .sendToServer(new PacketBattleDecision(TurnBasedMinecraftMod.proxy.getLocalBattle().getId(), + Battle.Decision.SWITCH_ITEM, ((ItemSelectionButton) button).getID())); + if (((ItemSelectionButton) button).getID() >= 0 && ((ItemSelectionButton) button).getID() < 9) { + Minecraft.getInstance().player.inventory.currentItem = ((ItemSelectionButton) button).getID(); + } + setState(MenuState.WAITING); + } else { + setState(MenuState.MAIN_MENU); + } + break; + case DO_USE_ITEM: + if (button instanceof ItemSelectionButton) { + TurnBasedMinecraftMod.getHandler() + .sendToServer(new PacketBattleDecision(TurnBasedMinecraftMod.proxy.getLocalBattle().getId(), + Battle.Decision.USE_ITEM, ((ItemSelectionButton) button).getID())); + setState(MenuState.WAITING); + } else { + setState(MenuState.MAIN_MENU); + } + break; + } + } + + @Override + protected void init() { + } + + @Override + public boolean isPauseScreen() { + return false; + } + + @Override + public boolean keyPressed(int a, int b, int c) { + if (getMinecraft().player.isCreative()) { + return super.keyPressed(a, b, c); + } + return false; // TODO verify return value + } + + public void setTimeRemaining(int remaining) { + timeRemaining.set(remaining); + } } diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/client/BattleMusic.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/client/BattleMusic.java index a021495..0c2d47c 100644 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/client/BattleMusic.java +++ b/src/main/java/com/seodisparate/TurnBasedMinecraft/client/BattleMusic.java @@ -2,9 +2,6 @@ package com.seodisparate.TurnBasedMinecraft.client; import java.io.*; import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import javax.sound.midi.MidiSystem; @@ -186,9 +183,7 @@ public class BattleMusic if(initialized && next != null) { logger.debug("play called with file " + next.getName() + " and vol " + volume); - Minecraft.getMinecraft().addScheduledTask(() -> { - Minecraft.getMinecraft().getSoundHandler().pauseSounds(); - }); + Minecraft.getInstance().getSoundHandler().pause(); String suffix = next.getName().substring(next.getName().length() - 3).toLowerCase(); if(suffix.equals("mid")) { @@ -305,7 +300,7 @@ public class BattleMusic } if(resumeMCSounds) { - Minecraft.getMinecraft().addScheduledTask(() -> Minecraft.getMinecraft().getSoundHandler().resumeSounds() ); + Minecraft.getInstance().getSoundHandler().resume(); } isPlaying = false; } diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/client/ClientProxy.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/client/ClientProxy.java index e848231..834f77c 100644 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/client/ClientProxy.java +++ b/src/main/java/com/seodisparate/TurnBasedMinecraft/client/ClientProxy.java @@ -3,12 +3,12 @@ package com.seodisparate.TurnBasedMinecraft.client; import com.seodisparate.TurnBasedMinecraft.common.Battle; import com.seodisparate.TurnBasedMinecraft.common.CommonProxy; +import net.minecraft.client.GameSettings; import net.minecraft.client.Minecraft; -import net.minecraft.client.settings.GameSettings; import net.minecraft.entity.Entity; import net.minecraft.util.SoundCategory; import net.minecraft.util.text.ITextComponent; -import net.minecraft.util.text.TextComponentString; +import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TextFormatting; public class ClientProxy extends CommonProxy @@ -44,13 +44,11 @@ public class ClientProxy extends CommonProxy @Override public void setBattleGuiAsGui() { - Minecraft.getMinecraft().addScheduledTask(() -> { - if(Minecraft.getMinecraft().currentScreen != battleGui) - { - battleGui.turnEnd(); - Minecraft.getMinecraft().displayGuiScreen(battleGui); - } - }); + if(Minecraft.getInstance().currentScreen != battleGui) + { + battleGui.turnEnd(); + Minecraft.getInstance().displayGuiScreen(battleGui); + } } @Override @@ -75,10 +73,7 @@ public class ClientProxy extends CommonProxy public void battleEnded() { localBattle = null; - Minecraft.getMinecraft().addScheduledTask(() -> { - Minecraft.getMinecraft().displayGuiScreen(null); - Minecraft.getMinecraft().setIngameFocus(); - }); + Minecraft.getInstance().displayGuiScreen(null); stopMusic(true); battleMusicCount = 0; sillyMusicCount = 0; @@ -93,14 +88,14 @@ public class ClientProxy extends CommonProxy @Override public void playBattleMusic() { - GameSettings gs = Minecraft.getMinecraft().gameSettings; + GameSettings gs = Minecraft.getInstance().gameSettings; battleMusic.playBattle(gs.getSoundLevel(SoundCategory.MUSIC) * gs.getSoundLevel(SoundCategory.MASTER)); } @Override public void playSillyMusic() { - GameSettings gs = Minecraft.getMinecraft().gameSettings; + GameSettings gs = Minecraft.getInstance().gameSettings; battleMusic.playSilly(gs.getSoundLevel(SoundCategory.MUSIC) * gs.getSoundLevel(SoundCategory.MASTER)); } @@ -160,24 +155,24 @@ public class ClientProxy extends CommonProxy @Override public void displayString(String message) { - ITextComponent prefix = new TextComponentString("TBM: "); + ITextComponent prefix = new StringTextComponent("TBM: "); prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); - ITextComponent text = new TextComponentString(message); + ITextComponent text = new StringTextComponent(message); prefix.appendSibling(text); text.getStyle().setColor(TextFormatting.WHITE).setBold(false); - Minecraft.getMinecraft().player.sendMessage(prefix); + Minecraft.getInstance().player.sendMessage(prefix); } @Override public void displayTextComponent(ITextComponent text) { - Minecraft.getMinecraft().player.sendMessage(text); + Minecraft.getInstance().player.sendMessage(text); } @Override public Entity getEntityByID(int id) { - return Minecraft.getMinecraft().world.getEntityByID(id); + return Minecraft.getInstance().world.getEntityByID(id); } private void checkBattleTypes() diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/client/EntitySelectionButton.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/client/EntitySelectionButton.java index 8b07fc5..febeff9 100644 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/client/EntitySelectionButton.java +++ b/src/main/java/com/seodisparate/TurnBasedMinecraft/client/EntitySelectionButton.java @@ -1,92 +1,77 @@ package com.seodisparate.TurnBasedMinecraft.client; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.widget.button.Button; import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.LivingEntity; -public class EntitySelectionButton extends GuiButton +public class EntitySelectionButton extends Button { - public int entityID; + private int entityID; private boolean isSideA; - public EntitySelectionButton(int buttonId, int x, int y, String buttonText, int entityID, boolean isSideA) - { - super(buttonId, x, y, buttonText); + + public EntitySelectionButton(int x, int y, int widthIn, int heightIn, String buttonText, int entityID, boolean isSideA, Button.IPressable onPress) { + super(x, y, widthIn, heightIn, buttonText, onPress); this.entityID = entityID; this.isSideA = isSideA; } - public EntitySelectionButton(int buttonId, int x, int y, int widthIn, int heightIn, String buttonText, int entityID, boolean isSideA) - { - super(buttonId, x, y, widthIn, heightIn, buttonText); - this.entityID = entityID; - this.isSideA = isSideA; + public int getID() { + return entityID; + } + + public boolean getIsSideA() { + return isSideA; } @Override - public void drawButton(Minecraft mc, int mouseX, int mouseY, float partialTicks) - { - super.drawButton(mc, mouseX, mouseY, partialTicks); - Entity e = Minecraft.getMinecraft().world.getEntityByID(entityID); - if(e != null && e instanceof EntityLivingBase && ((EntityLivingBase)e).isEntityAlive()) - { - int health = (int)(((EntityLivingBase)e).getHealth() + 0.5f); + public void render(int mouseX, int mouseY, float partialTicks) { + super.render(mouseX, mouseY, partialTicks); + Entity e = Minecraft.getInstance().world.getEntityByID(entityID); + if(e != null && e instanceof LivingEntity && ((LivingEntity)e).isAlive()) { + int health = (int)(((LivingEntity)e).getHealth() + 0.5f); int xpos = x; int xoffset; - if(isSideA) - { + if(isSideA) { xpos += width + 4; xoffset = 4; - } - else - { + } else { xpos -= 6; xoffset = -4; } - if(health > 200) - { - drawRect(xpos, y + height * 4 / 5, xpos + 2, y + height , 0xFFFF0000); - drawRect(xpos, y + height * 3 / 5, xpos + 2, y + height * 4 / 5, 0xFFFFFF00); - drawRect(xpos, y + height * 2 / 5, xpos + 2, y + height * 3 / 5, 0xFF00FF00); - drawRect(xpos, y + height / 5, xpos + 2, y + height * 2 / 5, 0xFF00FFFF); - drawRect(xpos, y , xpos + 2, y + height / 5, 0xFF0000FF); + if(health > 200) { + fill(xpos, y + height * 4 / 5, xpos + 2, y + height , 0xFFFF0000); + fill(xpos, y + height * 3 / 5, xpos + 2, y + height * 4 / 5, 0xFFFFFF00); + fill(xpos, y + height * 2 / 5, xpos + 2, y + height * 3 / 5, 0xFF00FF00); + fill(xpos, y + height / 5, xpos + 2, y + height * 2 / 5, 0xFF00FFFF); + fill(xpos, y , xpos + 2, y + height / 5, 0xFF0000FF); int healthHeight = ((health - 200) * height / 100); - drawRect(xpos + xoffset, y + height - healthHeight, xpos + xoffset + 2, y + height, 0xFFFFFFFF); - } - else if(health > 100) - { - drawRect(xpos, y + height * 4 / 5, xpos + 2, y + height , 0xFFFF0000); - drawRect(xpos, y + height * 3 / 5, xpos + 2, y + height * 4 / 5, 0xFFFFFF00); - drawRect(xpos, y + height * 2 / 5, xpos + 2, y + height * 3 / 5, 0xFF00FF00); - drawRect(xpos, y + height / 5, xpos + 2, y + height * 2 / 5, 0xFF00FFFF); + fill(xpos + xoffset, y + height - healthHeight, xpos + xoffset + 2, y + height, 0xFFFFFFFF); + } else if(health > 100) { + fill(xpos, y + height * 4 / 5, xpos + 2, y + height , 0xFFFF0000); + fill(xpos, y + height * 3 / 5, xpos + 2, y + height * 4 / 5, 0xFFFFFF00); + fill(xpos, y + height * 2 / 5, xpos + 2, y + height * 3 / 5, 0xFF00FF00); + fill(xpos, y + height / 5, xpos + 2, y + height * 2 / 5, 0xFF00FFFF); int healthHeight = ((health - 100) * height / 100); - drawRect(xpos + xoffset, y + height - healthHeight, xpos + xoffset + 2, y + height, 0xFF0000FF); - } - else if(health > 50) - { - drawRect(xpos, y + height * 4 / 5, xpos + 2, y + height , 0xFFFF0000); - drawRect(xpos, y + height * 3 / 5, xpos + 2, y + height * 4 / 5, 0xFFFFFF00); - drawRect(xpos, y + height * 2 / 5, xpos + 2, y + height * 3 / 5, 0xFF00FF00); + fill(xpos + xoffset, y + height - healthHeight, xpos + xoffset + 2, y + height, 0xFF0000FF); + } else if(health > 50) { + fill(xpos, y + height * 4 / 5, xpos + 2, y + height , 0xFFFF0000); + fill(xpos, y + height * 3 / 5, xpos + 2, y + height * 4 / 5, 0xFFFFFF00); + fill(xpos, y + height * 2 / 5, xpos + 2, y + height * 3 / 5, 0xFF00FF00); int healthHeight = ((health - 50) * height / 50); - drawRect(xpos + xoffset, y + height - healthHeight, xpos + xoffset + 2, y + height, 0xFF00FFFF); - } - else if(health > 20) - { - drawRect(xpos, y + height * 4 / 5, xpos + 2, y + height , 0xFFFF0000); - drawRect(xpos, y + height * 3 / 5, xpos + 2, y + height * 4 / 5, 0xFFFFFF00); + fill(xpos + xoffset, y + height - healthHeight, xpos + xoffset + 2, y + height, 0xFF00FFFF); + } else if(health > 20) { + fill(xpos, y + height * 4 / 5, xpos + 2, y + height , 0xFFFF0000); + fill(xpos, y + height * 3 / 5, xpos + 2, y + height * 4 / 5, 0xFFFFFF00); int healthHeight = ((health - 20) * height / 30); - drawRect(xpos + xoffset, y + height - healthHeight, xpos + xoffset + 2, y + height, 0xFF00FF00); - } - else if(health > 10) - { - drawRect(xpos, y + height * 4 / 5, xpos + 2, y + height, 0xFFFF0000); + fill(xpos + xoffset, y + height - healthHeight, xpos + xoffset + 2, y + height, 0xFF00FF00); + } else if(health > 10) { + fill(xpos, y + height * 4 / 5, xpos + 2, y + height, 0xFFFF0000); int healthHeight = ((health - 10) * height / 10); - drawRect(xpos + xoffset, y + height - healthHeight, xpos + xoffset + 2, y + height, 0xFFFFFF00); - } - else - { + fill(xpos + xoffset, y + height - healthHeight, xpos + xoffset + 2, y + height, 0xFFFFFF00); + } else { int healthHeight = (health * height / 10); - drawRect(xpos + xoffset, y + height - healthHeight, xpos + xoffset + 2, y + height, 0xFFFF0000); + fill(xpos + xoffset, y + height - healthHeight, xpos + xoffset + 2, y + height, 0xFFFF0000); } } } diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/client/ItemSelectionButton.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/client/ItemSelectionButton.java index f5fe250..1b9a80c 100644 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/client/ItemSelectionButton.java +++ b/src/main/java/com/seodisparate/TurnBasedMinecraft/client/ItemSelectionButton.java @@ -1,37 +1,28 @@ package com.seodisparate.TurnBasedMinecraft.client; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.widget.button.Button; -public class ItemSelectionButton extends GuiButton +public class ItemSelectionButton extends Button { - int itemStackID; + private int itemStackID; - public ItemSelectionButton(int buttonId, int x, int y, int widthIn, int heightIn, String buttonText, int itemStackID) - { - super(buttonId, x, y, widthIn, heightIn, buttonText); + public ItemSelectionButton(int x, int y, int widthIn, int heightIn, String buttonText, int itemStackID, Button.IPressable onPress) { + super(x, y, widthIn, heightIn, buttonText, onPress); this.itemStackID = itemStackID; } - - public ItemSelectionButton(int buttonId, int x, int y, String buttonText, int itemStackID) - { - super(buttonId, x, y, buttonText); - this.itemStackID = itemStackID; + + public int getID() { + return itemStackID; } @Override - public void drawButton(Minecraft mc, int mouseX, int mouseY, float partialTicks) - { - if(visible) - { - hovered = mouseX >= x && mouseY >= y && mouseX < x + width && mouseY < y + height; - if(hovered) - { - drawRect(x, y, x + width, y + height, 0x80FFFFFF); - } - else - { - drawRect(x, y, x + width, y + height, 0x20707070); + public void render(int mouseX, int mouseY, float partialTicks) { + if(visible) { + boolean hovered = mouseX >= x && mouseY >= y && mouseX < x + width && mouseY < y + height; + if(hovered) { + fill(x, y, x + width, y + height, 0x80FFFFFF); + } else { + fill(x, y, x + width, y + height, 0x20707070); } } } diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/AttackEventHandler.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/AttackEventHandler.java index 1c83f31..adbf8cd 100644 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/AttackEventHandler.java +++ b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/AttackEventHandler.java @@ -6,10 +6,11 @@ import com.seodisparate.TurnBasedMinecraft.common.networking.PacketBattleMessage import com.seodisparate.TurnBasedMinecraft.common.networking.PacketEditingMessage; import com.seodisparate.TurnBasedMinecraft.common.networking.PacketGeneralMessage; -import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraftforge.event.entity.living.LivingAttackEvent; import net.minecraftforge.event.entity.living.LivingSetAttackTargetEvent; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.network.NetworkDirection; public class AttackEventHandler { @@ -77,21 +78,31 @@ public class AttackEventHandler event.setCanceled(true); if(editingInfo.isEditingCustomName) { - if(event.getEntity().getCustomNameTag().isEmpty()) + if(!event.getEntity().hasCustomName()) { TurnBasedMinecraftMod.logger.error("Cannot edit custom name from entity without custom name"); - TurnBasedMinecraftMod.NWINSTANCE.sendTo(new PacketGeneralMessage("Cannot edit custom name from entity without custom name"), (EntityPlayerMP) editingInfo.editor); + TurnBasedMinecraftMod.getHandler().sendTo( + new PacketGeneralMessage("Cannot edit custom name from entity without custom name"), + ((ServerPlayerEntity)editingInfo.editor).connection.netManager, + NetworkDirection.PLAY_TO_CLIENT); return; } - editingInfo.entityInfo = config.getCustomEntityInfo(event.getEntity().getCustomNameTag()); + //editingInfo.entityInfo = config.getCustomEntityInfo(event.getEntity().getCustomNameTag()); + editingInfo.entityInfo = config.getCustomEntityInfo(event.getEntity().getCustomName().getString()); if(editingInfo.entityInfo == null) { editingInfo.entityInfo = new EntityInfo(); - editingInfo.entityInfo.customName = event.getEntity().getCustomNameTag(); + editingInfo.entityInfo.customName = event.getEntity().getCustomName().getString(); } - TurnBasedMinecraftMod.NWINSTANCE.sendTo(new PacketGeneralMessage("Editing custom name \"" + event.getEntity().getCustomNameTag() + "\""), (EntityPlayerMP) editingInfo.editor); - TurnBasedMinecraftMod.logger.info("Begin editing custom \"" + event.getEntity().getCustomNameTag() + "\""); - TurnBasedMinecraftMod.NWINSTANCE.sendTo(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo), (EntityPlayerMP) editingInfo.editor); + TurnBasedMinecraftMod.getHandler().sendTo( + new PacketGeneralMessage("Editing custom name \"" + event.getEntity().getCustomName().getString() + "\""), + ((ServerPlayerEntity)editingInfo.editor).connection.netManager, + NetworkDirection.PLAY_TO_CLIENT); + TurnBasedMinecraftMod.logger.info("Begin editing custom \"" + event.getEntity().getCustomName().getString() + "\""); + TurnBasedMinecraftMod.getHandler().sendTo( + new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo), + ((ServerPlayerEntity)editingInfo.editor).connection.netManager, + NetworkDirection.PLAY_TO_CLIENT); } else { @@ -105,9 +116,15 @@ public class AttackEventHandler { editingInfo.entityInfo = editingInfo.entityInfo.clone(); } - TurnBasedMinecraftMod.NWINSTANCE.sendTo(new PacketGeneralMessage("Editing entity \"" + editingInfo.entityInfo.classType.getName() + "\""), (EntityPlayerMP) editingInfo.editor); + TurnBasedMinecraftMod.getHandler().sendTo( + new PacketGeneralMessage("Editing entity \"" + editingInfo.entityInfo.classType.getName() + "\""), + ((ServerPlayerEntity)editingInfo.editor).connection.netManager, + NetworkDirection.PLAY_TO_CLIENT); TurnBasedMinecraftMod.logger.info("Begin editing \"" + editingInfo.entityInfo.classType.getName() + "\""); - TurnBasedMinecraftMod.NWINSTANCE.sendTo(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo), (EntityPlayerMP) editingInfo.editor); + TurnBasedMinecraftMod.getHandler().sendTo( + new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo), + ((ServerPlayerEntity)editingInfo.editor).connection.netManager, + NetworkDirection.PLAY_TO_CLIENT); } return; } diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/CommonProxy.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/CommonProxy.java index e0d6a67..ea2f77f 100644 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/CommonProxy.java +++ b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/CommonProxy.java @@ -2,10 +2,11 @@ package com.seodisparate.TurnBasedMinecraft.common; import java.util.*; -import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.text.ITextComponent; import org.apache.logging.log4j.Logger; +import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraftforge.fml.common.FMLCommonHandler; @@ -152,7 +153,7 @@ public class CommonProxy return editingPlayers.get(id); } - protected final EditingInfo setEditingPlayer(EntityPlayer player) + protected final EditingInfo setEditingPlayer(PlayerEntity player) { return editingPlayers.put(player.getEntityId(), new EditingInfo(player)); } diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/Config.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/Config.java index 0949e0c..a5e5279 100644 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/Config.java +++ b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/Config.java @@ -3,21 +3,23 @@ package com.seodisparate.TurnBasedMinecraft.common; import java.io.*; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; -import net.consensys.cava.toml.*; +import com.electronwill.nightconfig.core.file.CommentedFileConfig; import org.apache.logging.log4j.Logger; +import com.electronwill.nightconfig.core.file.FileConfig; + public class Config { - public static final long BATTLE_DECISION_DURATION_NANO_MIN = 5000000000L; - public static final long BATTLE_DECISION_DURATION_NANO_MAX = 60000000000L; - public static final long BATTLE_DECISION_DURATION_NANO_DEFAULT = 15000000000L; + public static final long BATTLE_DECISION_DURATION_SEC_MIN = 5L; + public static final long BATTLE_DECISION_DURATION_SEC_MAX = 60L; + public static final long BATTLE_DECISION_DURATION_SEC_DEFAULT = 15L; + public static final long BATTLE_DECISION_DURATION_NANO_MIN = BATTLE_DECISION_DURATION_SEC_MIN * 1000000000L; + public static final long BATTLE_DECISION_DURATION_NANO_MAX = BATTLE_DECISION_DURATION_SEC_MAX * 1000000000L; + public static final long BATTLE_DECISION_DURATION_NANO_DEFAULT = BATTLE_DECISION_DURATION_SEC_DEFAULT * 1000000000L; private long battleDecisionDurationNanos = BATTLE_DECISION_DURATION_NANO_DEFAULT; private Map entityInfoMap; private Map customEntityInfoMap; @@ -55,79 +57,61 @@ public class Config musicSillyTypes = new HashSet(); battleIgnoringPlayers = new HashSet(); - int internalVersion = getConfigFileVersion(getClass().getResourceAsStream(TurnBasedMinecraftMod.CONFIG_INTERNAL_PATH)); + writeDefaultConfig(getClass().getResourceAsStream(TurnBasedMinecraftMod.CONFIG_INTERNAL_PATH)); - if(internalVersion == 0) - { + int internalVersion = getConfigFileVersion(new File(TurnBasedMinecraftMod.DEFAULT_CONFIG_FILE_PATH)); + + if(internalVersion == 0) { logger.error("Failed to check version of internal config file"); - } - else - { + } else { configVersion = internalVersion; } - try - { + try { File testLoad = new File(TurnBasedMinecraftMod.CONFIG_FILE_PATH); - if(!testLoad.exists()) - { + if(!testLoad.exists()) { writeConfig(); } } - catch (Throwable t) - { + catch (Throwable t) { logger.error("Failed to check/create-new config file"); } // parse config File configFile = new File(TurnBasedMinecraftMod.CONFIG_FILE_PATH); - if(!configFile.exists() || !configFile.canRead()) - { + if(!configFile.exists() || !configFile.canRead()) { logger.error("Failed to read/parse config file " + TurnBasedMinecraftMod.CONFIG_FILE_PATH); return; } int configVersion = getConfigFileVersion(configFile); - if(configVersion < this.configVersion) - { + if(configVersion < this.configVersion) { logger.warn("Config file " + TurnBasedMinecraftMod.CONFIG_FILENAME + " is older version, renaming..."); moveOldConfig(); - try - { + try { writeConfig(); - } catch (Throwable t) - { + } catch (Throwable t) { logger.error("Failed to write config file!"); } } - try - { + try { parseConfig(configFile); - } catch (Throwable t) - { + } catch (Throwable t) { logger.error("Failed to parse config file!"); } } private void writeConfig() throws IOException { - File configFile = new File(TurnBasedMinecraftMod.CONFIG_FILE_PATH); - File dirs = configFile.getParentFile(); - dirs.mkdirs(); - InputStream configStream = this.getClass().getResourceAsStream(TurnBasedMinecraftMod.CONFIG_INTERNAL_PATH); - FileOutputStream configOutput = new FileOutputStream(configFile); - byte[] buf = new byte[4096]; - int read = 0; - while(read != -1) - { - read = configStream.read(buf); - if(read > 0) - { - configOutput.write(buf, 0, read); - } + InputStream is = getClass().getResourceAsStream(TurnBasedMinecraftMod.CONFIG_INTERNAL_PATH); + FileOutputStream fos = new FileOutputStream(TurnBasedMinecraftMod.CONFIG_FILE_PATH); + byte[] buf = new byte[1024]; + int read; + while((read = is.read(buf)) > 0) { + fos.write(buf, 0, read); } - configStream.close(); - configOutput.close(); + fos.close(); + is.close(); } private void moveOldConfig() @@ -144,463 +128,561 @@ public class Config private boolean parseConfig(File configFile) throws IOException { - TomlParseResult parseResult = Toml.parse(configFile.toPath(), TomlVersion.V0_5_0); + CommentedFileConfig conf = CommentedFileConfig + .builder(configFile) + .defaultResource(TurnBasedMinecraftMod.DEFAULT_CONFIG_FILE_PATH) + .build(); + conf.load(); - // client_config - { - TomlArray battleMusicCategories = parseResult.getArray("client_config.battle_music"); - if(battleMusicCategories != null) - { - for (int i = 0; i < battleMusicCategories.size(); ++i) - { - musicBattleTypes.add(battleMusicCategories.getString(i)); + // client config + try { + Collection battle_music_categories = conf.get("client_config.battle_music"); + if (battle_music_categories != null) { + for (String category : battle_music_categories) { + musicBattleTypes.add(category); } - } - else - { + } else { musicBattleTypes.add("monster"); musicBattleTypes.add("animal"); musicBattleTypes.add("boss"); musicBattleTypes.add("player"); logNotFound("client_config.battle_music"); } + } catch (ClassCastException e) { + musicBattleTypes.add("monster"); + musicBattleTypes.add("animal"); + musicBattleTypes.add("boss"); + musicBattleTypes.add("player"); + logTOMLInvalidValue("client_config.battle_music"); } - { - TomlArray sillyMusicCategories = parseResult.getArray("client_config.silly_music"); - if(sillyMusicCategories != null) - { - for (int i = 0; i < sillyMusicCategories.size(); ++i) - { - musicSillyTypes.add(sillyMusicCategories.getString(i)); + + try { + Collection silly_music_categories = conf.get("client_config.silly_music"); + if (silly_music_categories != null) { + for (String category : silly_music_categories) { + musicSillyTypes.add(category); } - } - else - { + } else { musicSillyTypes.add("passive"); logNotFound("client_config.silly_music"); } + } catch (ClassCastException e) { + musicSillyTypes.add("passive"); + logTOMLInvalidValue("client_config.silly_music"); } - try - { - sillyMusicThreshold = parseResult.getLong("client_config.silly_music_threshold").intValue(); - } - catch (NullPointerException e) - { - sillyMusicThreshold = 40; - logNotFound("client_config.silly_music_threshold", "40"); + try { + OptionalInt silly_music_threshold = conf.getOptionalInt("client_config.silly_music_threshold"); + if(silly_music_threshold.isPresent()) { + this.sillyMusicThreshold = silly_music_threshold.getAsInt(); + } else { + this.sillyMusicThreshold = 40; + logNotFound("client_config.silly_music_threshold", "40"); + } + } catch (ClassCastException e) { + this.sillyMusicThreshold = 40; + logTOMLInvalidValue("client_config.silly_music_threshold", "40"); } // server_config - try - { - leaveBattleCooldownSeconds = parseResult.getLong("server_config.leave_battle_cooldown").intValue(); - if (leaveBattleCooldownSeconds < 1) - { - leaveBattleCooldownSeconds = 1; - } else if (leaveBattleCooldownSeconds > 10) - { - leaveBattleCooldownSeconds = 10; + try { + OptionalInt leave_battle_cooldown = conf.getOptionalInt("server_config.leave_battle_cooldown"); + if (leave_battle_cooldown.isPresent()) { + this.leaveBattleCooldownSeconds = leave_battle_cooldown.getAsInt(); + if (this.leaveBattleCooldownSeconds < 1) { + logClampedValue("server_config.leave_battle_cooldown", Integer.toString(this.leaveBattleCooldownSeconds), "1"); + this.leaveBattleCooldownSeconds = 1; + } else if (this.leaveBattleCooldownSeconds > 10) { + logClampedValue("server_config.leave_battle_cooldown", Integer.toString(this.leaveBattleCooldownSeconds), "10"); + this.leaveBattleCooldownSeconds = 10; + } + } else { + this.leaveBattleCooldownSeconds = 5; + logNotFound("server_config.leave_battle_cooldown", "5"); } - } - catch (NullPointerException e) - { - leaveBattleCooldownSeconds = 5; - logNotFound("server_config.leave_battle_cooldown", "5"); + } catch (ClassCastException e) { + this.leaveBattleCooldownSeconds = 5; + logTOMLInvalidValue("server_config.leave_battle_cooldown", "5"); } - try - { - aggroStartBattleDistance = parseResult.getLong("server_config.aggro_start_battle_max_distance").intValue(); - if (aggroStartBattleDistance < 5) - { - aggroStartBattleDistance = 5; - } else if (aggroStartBattleDistance > 50) - { - aggroStartBattleDistance = 50; + try { + OptionalInt aggro_start_battle_max_distance = conf.getOptionalInt("server_config.aggro_start_battle_max_distance"); + if (aggro_start_battle_max_distance.isPresent()) { + this.aggroStartBattleDistance = aggro_start_battle_max_distance.getAsInt(); + if (this.aggroStartBattleDistance < 5) { + logClampedValue("server_config.aggro_start_battle_max_distance", Integer.toString(this.aggroStartBattleDistance), "5"); + this.aggroStartBattleDistance = 5; + } else if (this.aggroStartBattleDistance > 50) { + logClampedValue("server_config.aggro_start_battle_max_distance", Integer.toString(this.aggroStartBattleDistance), "50"); + this.aggroStartBattleDistance = 50; + } + } else { + this.aggroStartBattleDistance = 8; + logNotFound("server_config.aggro_start_battle_max_distance", "8"); } - } - catch (NullPointerException e) - { - aggroStartBattleDistance = 8; - logNotFound("server_config.aggro_start_battle_max_distance", "8"); + } catch (ClassCastException e) { + this.aggroStartBattleDistance = 8; + logTOMLInvalidValue("server_config.aggro_start_battle_max_distance", "8"); } - try - { - oldBattleBehaviorEnabled = parseResult.getBoolean("server_config.old_battle_behavior"); - } - catch (NullPointerException e) - { - oldBattleBehaviorEnabled = false; - logNotFound("server_config.old_battle_behavior", "false"); - } - - try - { - onlyOPsSelfDisableTB = !parseResult.getBoolean("server_config.anyone_can_disable_tbm_for_self"); - } - catch (NullPointerException e) - { - onlyOPsSelfDisableTB = true; - logNotFound("server_config.anyone_can_disable_tbm_for_self", "false"); - } - - try - { - maxInBattle = parseResult.getLong("server_config.max_in_battle").intValue(); - if (maxInBattle < 2) - { - maxInBattle = 2; + try { + Boolean old_battle_behavior = conf.get("server_config.old_battle_behavior"); + if(old_battle_behavior != null) { + this.oldBattleBehaviorEnabled = old_battle_behavior; + } else { + this.oldBattleBehaviorEnabled = false; + logNotFound("server_config.old_battle_behavior", "false"); } + } catch (ClassCastException e) { + this.oldBattleBehaviorEnabled = false; + logTOMLInvalidValue("server_config.old_battle_behavior", "false"); } - catch (NullPointerException e) - { + + try { + Boolean anyone_can_disable_tbm_for_self = conf.get("server_config.anyone_can_disable_tbm_for_self"); + if(anyone_can_disable_tbm_for_self != null) { + this.onlyOPsSelfDisableTB = !anyone_can_disable_tbm_for_self; + } else { + this.onlyOPsSelfDisableTB = true; + logNotFound("server_config.anyone_can_disable_tbm_for_self", "false"); + } + } catch (ClassCastException e) { + this.onlyOPsSelfDisableTB = true; + logTOMLInvalidValue("server_config.anyone_can_disable_tbm_for_self", "false"); + } + + try { + OptionalInt max_in_battle = conf.getOptionalInt("server_config.max_in_battle"); + if(max_in_battle.isPresent()) { + this.maxInBattle = max_in_battle.getAsInt(); + if(this.maxInBattle < 2) { + logClampedValue("server_config.max_in_battle", Integer.toString(this.maxInBattle), "2"); + this.maxInBattle = 2; + } + } else { + maxInBattle = 8; + logNotFound("server_config.max_in_battle", "8"); + } + } catch (ClassCastException e) { maxInBattle = 8; - logNotFound("server_config.max_in_battle", "8"); + logTOMLInvalidValue("server_config.max_in_battle", "8"); } - try - { - freezeCombatantsInBattle = parseResult.getBoolean("server_config.freeze_battle_combatants"); - } - catch (NullPointerException e) - { - freezeCombatantsInBattle = false; - logNotFound("server_config.freeze_battle_combatants", "false"); - } - - try - { - TomlArray ignoreTypes = parseResult.getArray("server_config.ignore_battle_types"); - for(int i = 0; i < ignoreTypes.size(); ++i) - { - ignoreBattleTypes.add(ignoreTypes.getString(i)); + try { + Boolean freeze_battle_combatants = conf.get("server_config.freeze_battle_combatants"); + if(freeze_battle_combatants != null) { + this.freezeCombatantsInBattle = freeze_battle_combatants; + } else { + freezeCombatantsInBattle = false; + logNotFound("server_config.freeze_battle_combatants", "false"); } + } catch (ClassCastException e) { + freezeCombatantsInBattle = false; + logTOMLInvalidValue("server_config.freeze_battle_combatants", "false"); } - catch (NullPointerException e) - { + + try { + Collection ignore_battle_types = conf.get("server_config.ignore_battle_types"); + if(ignore_battle_types != null) { + this.ignoreBattleTypes.addAll(ignore_battle_types); + } else { + ignoreBattleTypes.add("passive"); + ignoreBattleTypes.add("boss"); + logNotFound("server_config.ignore_battle_types"); + } + } catch (ClassCastException e) { ignoreBattleTypes.add("passive"); ignoreBattleTypes.add("boss"); - logNotFound("server_config.ignore_battle_types"); + logTOMLInvalidValue("server_config.ignore_battle_types"); } - try - { - playerSpeed = parseResult.getLong("server_config.player_speed").intValue(); - } - catch (NullPointerException e) - { - playerSpeed = 50; - logNotFound("server_config.player_speed", "50"); - } - try - { - playerHasteSpeed = parseResult.getLong("server_config.player_haste_speed").intValue(); - } - catch (NullPointerException e) - { - playerHasteSpeed = 80; - logNotFound("server_config.player_haste_speed", "80"); - } - try - { - playerSlowSpeed = parseResult.getLong("server_config.player_slow_speed").intValue(); - } - catch (NullPointerException e) - { - playerSlowSpeed = 20; - logNotFound("server_config.player_slow_speed", "20"); - } - try - { - playerAttackProbability = parseResult.getLong("server_config.player_attack_probability").intValue(); - } - catch (NullPointerException e) - { - playerAttackProbability = 90; - logNotFound("server_config.player_attack_probability", "90"); - } - try - { - playerEvasion = parseResult.getLong("server_config.player_evasion").intValue(); - } - catch (NullPointerException e) - { - playerEvasion = 10; - logNotFound("server_config.player_evasion", "10"); - } - - try - { - defenseDuration = parseResult.getLong("server_config.defense_duration").intValue(); - } - catch (NullPointerException e) - { - defenseDuration = 1; - logNotFound("server_config.defense_duration", "1"); - } - - try - { - fleeGoodProbability = parseResult.getLong("server_config.flee_good_probability").intValue(); - } - catch (NullPointerException e) - { - fleeGoodProbability = 90; - logNotFound("server_config.flee_good_probability", "90"); - } - try - { - fleeBadProbability = parseResult.getLong("server_config.flee_bad_probability").intValue(); - } - catch (NullPointerException e) - { - fleeBadProbability = 35; - logNotFound("server_config.flee_bad_probability", "35"); - } - - try - { - minimumHitPercentage = parseResult.getLong("server_config.minimum_hit_percentage").intValue(); - if (minimumHitPercentage < 1) - { - minimumHitPercentage = 1; + try { + OptionalInt player_speed = conf.getOptionalInt("server_config.player_speed"); + if(player_speed.isPresent()) { + this.playerSpeed = player_speed.getAsInt(); + } else { + this.playerSpeed = 50; + logNotFound("server_config.player_speed", "50"); } - } - catch (NullPointerException e) - { - minimumHitPercentage = 4; - logNotFound("server_config.minimum_hit_percentage", "4"); + } catch (ClassCastException e) { + this.playerSpeed = 50; + logTOMLInvalidValue("server_config.player_speed", "50"); } - try - { - battleDecisionDurationNanos = parseResult.getLong("server_config.battle_turn_time_seconds") * 1000000000L; - if(battleDecisionDurationNanos < BATTLE_DECISION_DURATION_NANO_MIN) - { - battleDecisionDurationNanos = BATTLE_DECISION_DURATION_NANO_MIN; - logger.warn("Config \"server_config.battle_turn_time_seconds\" too low, defaulting to minimum \"5\""); + try { + OptionalInt player_haste_speed = conf.getOptionalInt("server_config.player_haste_speed"); + if(player_haste_speed.isPresent()) { + this.playerHasteSpeed = player_haste_speed.getAsInt(); + } else { + this.playerHasteSpeed = 80; + logNotFound("server_config.player_haste_speed", "80"); } - else if(battleDecisionDurationNanos > BATTLE_DECISION_DURATION_NANO_MAX) - { - battleDecisionDurationNanos = BATTLE_DECISION_DURATION_NANO_MAX; - logger.warn("Config \"server_config.battle_turn_time_seconds\" too high, defaulting to maximum \"60\""); - } - } - catch (NullPointerException e) - { - battleDecisionDurationNanos = BATTLE_DECISION_DURATION_NANO_DEFAULT; - logNotFound("server_config.battle_turn_time_seconds", "15"); + } catch (ClassCastException e) { + this.playerHasteSpeed = 80; + logTOMLInvalidValue("server_config.player_haste_speed", "80"); } - // entities - TomlArray entityArray = parseResult.getArray("server_config.entity"); - if(entityArray != null) - { - for(int i = 0; i < entityArray.size(); ++i) - { - TomlTable entity = entityArray.getTable(i); - EntityInfo eInfo = new EntityInfo(); - String name = null; - if(entity.contains("name") && entity.contains("custom_name")) - { - logger.error("Entity cannot have both \"name\" and \"custom_name\" entries"); - continue; + try { + OptionalInt player_slow_speed = conf.getOptionalInt("server_config.player_slow_speed"); + if(player_slow_speed.isPresent()) { + this.playerSlowSpeed = player_slow_speed.getAsInt(); + } else { + this.playerSlowSpeed = 20; + logNotFound("server_config.player_slow_speed", "20"); + } + } catch (ClassCastException e) { + this.playerSlowSpeed = 20; + logTOMLInvalidValue("server_config.player_slow_speed", "20"); + } + + try { + OptionalInt player_attack_probability = conf.getOptionalInt("server_config.player_attack_probability"); + if(player_attack_probability.isPresent()) { + this.playerAttackProbability = player_attack_probability.getAsInt(); + } else { + this.playerAttackProbability = 90; + logNotFound("server_config.player_attack_probability", "90"); + } + } catch (ClassCastException e) { + this.playerAttackProbability = 90; + logTOMLInvalidValue("server_config.player_attack_probability", "90"); + } + + try { + OptionalInt player_evasion = conf.getOptionalInt("server_config.player_evasion"); + if(player_evasion.isPresent()) { + this.playerEvasion = player_evasion.getAsInt(); + } else { + this.playerEvasion = 10; + logNotFound("server_config.player_evasion", "10"); + } + } catch (ClassCastException e) { + this.playerEvasion = 10; + logTOMLInvalidValue("server_config.player_evasion", "10"); + } + + try { + OptionalInt defense_duration = conf.getOptionalInt("server_config.defense_duration"); + if(defense_duration.isPresent()) { + this.defenseDuration = defense_duration.getAsInt(); + if(this.defenseDuration < 0) { + logClampedValue("server_config.defense_duration", Integer.toString(this.defenseDuration), "0"); + this.defenseDuration = 0; } - else if(entity.contains("name")) - { - try - { - eInfo.classType = Class.forName(entity.getString("name")); + } else { + this.defenseDuration = 1; + logNotFound("server_config.defense_duration", "1"); + } + } catch (ClassCastException e) { + this.defenseDuration = 1; + logTOMLInvalidValue("server_config.defense_duration", "1"); + } + + try { + OptionalInt flee_good_probability = conf.getOptionalInt("server_config.flee_good_probability"); + if(flee_good_probability.isPresent()) { + this.fleeGoodProbability = flee_good_probability.getAsInt(); + } else { + this.fleeGoodProbability = 90; + logNotFound("server_config.flee_good_probability", "90"); + } + } catch (ClassCastException e) { + this.fleeGoodProbability = 90; + logTOMLInvalidValue("server_config.flee_good_probability", "90"); + } + + try { + OptionalInt flee_bad_probability = conf.getOptionalInt("server_config.flee_bad_probability"); + if(flee_bad_probability.isPresent()) { + this.fleeBadProbability = flee_bad_probability.getAsInt(); + } else { + this.fleeBadProbability = 35; + logNotFound("server_config.flee_bad_probability", "35"); + } + } catch (ClassCastException e) { + this.fleeBadProbability = 35; + logTOMLInvalidValue("server_config.flee_bad_probability", "35"); + } + + try { + OptionalInt minimum_hit_percentage = conf.getOptionalInt("server_config.minimum_hit_percentage"); + if(minimum_hit_percentage.isPresent()) { + this.minimumHitPercentage = minimum_hit_percentage.getAsInt(); + if(this.minimumHitPercentage < 1) { + logClampedValue("server_config.minimum_hit_percentage", Integer.toString(this.minimumHitPercentage), "1"); + this.minimumHitPercentage = 1; + } + } else { + this.minimumHitPercentage = 4; + logNotFound("server_config.minimum_hit_percentage", "4"); + } + } catch (ClassCastException e) { + this.minimumHitPercentage = 4; + logTOMLInvalidValue("server_config.minimum_hit_percentage", "4"); + } + + try { + OptionalInt battle_turn_time_seconds = conf.getOptionalInt("server_config.battle_turn_time_seconds"); + if(battle_turn_time_seconds.isPresent()) { + this.battleDecisionDurationNanos = (long)battle_turn_time_seconds.getAsInt() * 1000000000L; + if(this.battleDecisionDurationNanos < BATTLE_DECISION_DURATION_NANO_MIN) { + this.battleDecisionDurationNanos = BATTLE_DECISION_DURATION_NANO_MIN; + logClampedValue("server_config.battle_turn_time_seconds", Integer.toString(battle_turn_time_seconds.getAsInt()), Long.toString(BATTLE_DECISION_DURATION_SEC_MIN)); + } else if(this.battleDecisionDurationNanos > BATTLE_DECISION_DURATION_NANO_MAX) { + this.battleDecisionDurationNanos = BATTLE_DECISION_DURATION_NANO_MAX; + logClampedValue("server_config.battle_turn_time_seconds", Integer.toString(battle_turn_time_seconds.getAsInt()), Long.toString(BATTLE_DECISION_DURATION_SEC_MAX)); + } + } else { + this.battleDecisionDurationNanos = BATTLE_DECISION_DURATION_NANO_DEFAULT; + logNotFound("server_config.battle_turn_time_seconds", "15"); + } + } catch (ClassCastException e) { + this.battleDecisionDurationNanos = BATTLE_DECISION_DURATION_NANO_DEFAULT; + logTOMLInvalidValue("server_config.battle_turn_time_seconds", "15"); + } + + Collection entities = null; + try { + entities = conf.get("server_config.entity"); + } catch (ClassCastException e) { + logTOMLInvalidValue("server_config.entity"); + } + if(entities != null) { + for(com.electronwill.nightconfig.core.Config nestedConf : entities) { + EntityInfo eInfo = new EntityInfo(); + String name; + if(nestedConf.contains("name") && nestedConf.contains("custom_name")) { + logger.error("Entity cannot have both \"name\" (" + nestedConf.get("name") + + ") and \"custom_name\" (" + nestedConf.get("custom_name") + ") entries"); + continue; + } else if(nestedConf.contains("name")) { + try { + eInfo.classType = Class.forName(nestedConf.get("name")); name = eInfo.classType.getName(); - } catch(ClassNotFoundException e) - { - logger.error("Entity with class name \"" + entity.getString("name") + "\" not found, skipping..."); + } catch (ClassNotFoundException e) { + logger.error("Entity with class name \"" + nestedConf.get("name") + "\" not found, skipping..."); continue; } - } - else if(entity.contains("custom_name")) - { - eInfo.customName = entity.getString("custom_name"); - name = eInfo.customName; - } - else - { + } else if(nestedConf.contains("custom_name")) { + try { + eInfo.customName = nestedConf.get("custom_name"); + name = eInfo.customName; + } catch (ClassCastException e) { + logger.error("Entity with invalid custom_name (must be a string), skipping..."); + continue; + } + } else { logger.error("Entity must have \"name\" or \"custom_name\" entry"); continue; } - try - { - eInfo.attackPower = entity.getLong("attack_power").intValue(); - if(eInfo.attackPower < 0) - { + try { + eInfo.attackPower = nestedConf.getInt("attack_power"); + if(eInfo.attackPower < 0) { + logClampedValueEntity("attack_power", name, Integer.toString(eInfo.attackPower), "0"); eInfo.attackPower = 0; - logEntityInvalidValue("attack_power", name, "0"); } - } - catch (NullPointerException e) - { - logEntityMissingRequiredValue("attack_power", name); - continue; + } catch (ClassCastException e) { + logEntityInvalidValue("attack_power", name, "3"); + eInfo.attackPower = 3; + } catch (NullPointerException e) { + logEntityMissingRequiredValue("attack_power", name, "3"); + eInfo.attackPower = 3; } - try - { - eInfo.attackProbability = entity.getLong("attack_probability").intValue(); - if(eInfo.attackProbability < 0 || eInfo.attackProbability > 100) - { - eInfo.attackProbability = 35; - logEntityInvalidValue("attack_probability", name, "35"); + try { + eInfo.attackProbability = nestedConf.getInt("attack_probability"); + if(eInfo.attackProbability < 0) { + logClampedValueEntity("attack_probability", name, Integer.toString(eInfo.attackProbability), "0"); + eInfo.attackProbability = 0; + } else if(eInfo.attackProbability > 100) { + logClampedValueEntity("attack_probability", name, Integer.toString(eInfo.attackProbability), "100"); + eInfo.attackProbability = 100; } - } - catch (NullPointerException e) - { - logEntityMissingRequiredValue("attack_probability", name); - continue; + } catch (ClassCastException e) { + logEntityInvalidValue("attack_probability", name, "30"); + eInfo.attackProbability = 30; + } catch (NullPointerException e) { + logEntityMissingRequiredValue("attack_probability", name, "30"); + eInfo.attackProbability = 30; } - try - { - eInfo.attackEffect = EntityInfo.Effect.fromString(entity.getString("attack_effect")); - if(eInfo.attackEffect != EntityInfo.Effect.UNKNOWN) - { - eInfo.attackEffectProbability = entity.getLong("attack_effect_probability").intValue(); - if(eInfo.attackEffectProbability < 0 || eInfo.attackEffectProbability > 100) - { - eInfo.attackEffectProbability = 35; - logEntityInvalidValue("attack_effect", name, "35"); + try { + eInfo.attackEffect = EntityInfo.Effect.fromString(nestedConf.get("attack_effect")); + if(eInfo.attackEffect != EntityInfo.Effect.UNKNOWN) { + try { + eInfo.attackEffectProbability = nestedConf.getInt("attack_effect_probability"); + if(eInfo.attackEffectProbability < 0) { + logClampedValueEntity("attack_effect_probability", name, Integer.toString(eInfo.attackEffectProbability), "1"); + eInfo.attackEffectProbability = 1; + } else if(eInfo.attackEffectProbability > 100) { + logClampedValueEntity("attack_effect_probability", name, Integer.toString(eInfo.attackEffectProbability), "100"); + eInfo.attackEffectProbability = 100; + } + } catch (ClassCastException e) { + eInfo.attackEffect = EntityInfo.Effect.UNKNOWN; + logger.warn("Entity \"" + name + "\" has specified attack_effect but attack_effect_probability is invalid, unsetting attack_effect"); + } catch (NullPointerException e) { + eInfo.attackEffect = EntityInfo.Effect.UNKNOWN; + logger.warn("Entity \"" + name + "\" has specified attack_effect but attack_effect_probability is missing, unsetting attack_effect"); } } - } - catch (NullPointerException e) - { + } catch (ClassCastException e) { + eInfo.attackEffect = EntityInfo.Effect.UNKNOWN; + logEntityInvalidValue("attack_effect", name, "unknown"); + } catch (NullPointerException e) { eInfo.attackEffect = EntityInfo.Effect.UNKNOWN; logEntityMissingOptionalValue("attack_effect", name, "unknown"); } - try - { - eInfo.attackVariance = entity.getLong("attack_variance").intValue(); - if(eInfo.attackVariance < 0) - { + try { + eInfo.attackVariance = nestedConf.getInt("attack_variance"); + if(eInfo.attackVariance < 0) { + logClampedValueEntity("attack_variance", name, Integer.toString(eInfo.attackVariance), "0"); eInfo.attackVariance = 0; - logEntityInvalidValue("attack_variance", name, "0"); } - } - catch (NullPointerException e) - { + } catch (ClassCastException e) { + eInfo.attackVariance = 0; + logEntityInvalidValue("attack_variance", name, "0"); + } catch (NullPointerException e) { eInfo.attackVariance = 0; logEntityMissingOptionalValue("attack_variance", name, "0"); } - try - { - eInfo.defenseDamage = entity.getLong("defense_damage").intValue(); - if(eInfo.defenseDamage < 0) - { + try { + eInfo.defenseDamage = nestedConf.getInt("defense_damage"); + if(eInfo.defenseDamage < 0) { + logClampedValueEntity("defense_damage", name, Integer.toString(eInfo.defenseDamage), "0"); eInfo.defenseDamage = 0; - logEntityInvalidValue("defense_damage", name, "0"); - } - else - { - eInfo.defenseDamageProbability = entity.getLong("defense_damage_probability").intValue(); - if(eInfo.defenseDamageProbability < 0 || eInfo.defenseDamageProbability > 100) - { - eInfo.defenseDamageProbability = 35; - logEntityInvalidValue("defense_damage_probability", name, "35"); + } else if(eInfo.defenseDamage != 0) { + try { + eInfo.defenseDamageProbability = nestedConf.getInt("defense_damage_probability"); + if(eInfo.defenseDamageProbability < 1) { + logClampedValueEntity("defense_damage_probability", name, Integer.toString(eInfo.defenseDamageProbability), "1"); + eInfo.defenseDamageProbability = 1; + } else if(eInfo.defenseDamageProbability > 100) { + logClampedValueEntity("defense_damage_probability", name, Integer.toString(eInfo.defenseDamageProbability), "100"); + eInfo.defenseDamageProbability = 100; + } + } catch (ClassCastException e) { + eInfo.defenseDamage = 0; + logger.warn("Entity \"" + name + "\" has specified defense_damage but defense_damage_probability is invalid, disabling defense_damage"); + } catch (NullPointerException e) { + eInfo.defenseDamage = 0; + logger.warn("Entity \"" + name + "\" has specified defense_damage but defense_damage_probability is missing, disabling defense_damage"); } } - } - catch (NullPointerException e) - { + } catch (ClassCastException e) { + eInfo.defenseDamage = 0; + logEntityInvalidValue("defense_damage", name, "0"); + } catch (NullPointerException e) { eInfo.defenseDamage = 0; logEntityMissingOptionalValue("defense_damage", name, "0"); } - try - { - eInfo.evasion = entity.getLong("evasion").intValue(); - if(eInfo.evasion < 0 || eInfo.evasion > 100) - { - eInfo.evasion = 20; - logEntityInvalidValue("evasion", name, "20"); + try { + eInfo.evasion = nestedConf.getInt("evasion"); + if(eInfo.evasion < 0) { + logClampedValueEntity("evasion", name, Integer.toString(eInfo.evasion), "0"); + eInfo.evasion = 0; + } else if(eInfo.evasion > 100) { + logClampedValueEntity("evasion", name, Integer.toString(eInfo.evasion), "100"); + eInfo.evasion = 100; } - } - catch (NullPointerException e) - { - logEntityMissingRequiredValue("evasion", name); - continue; + } catch (ClassCastException e) { + logEntityInvalidValue("evasion", name, "7"); + eInfo.evasion = 7; + } catch (NullPointerException e) { + logEntityMissingRequiredValue("evasion", name, "7"); + eInfo.evasion = 7; } - try - { - eInfo.speed = entity.getLong("speed").intValue(); - } - catch (NullPointerException e) - { - logEntityMissingRequiredValue("speed", name); - continue; + try { + eInfo.speed = nestedConf.getInt("speed"); + } catch (ClassCastException e) { + logEntityInvalidValue("speed", name, "49"); + eInfo.speed = 49; + } catch (NullPointerException e) { + logEntityMissingRequiredValue("speed", name, "49"); + eInfo.speed = 49; } - try - { - eInfo.ignoreBattle = entity.getBoolean("ignore_battle"); - } - catch (NullPointerException e) - { + try { + eInfo.ignoreBattle = nestedConf.get("ignore_battle"); + } catch (ClassCastException e) { + logEntityInvalidValue("ignore_battle", name, "false"); + eInfo.ignoreBattle = false; + } catch (NullPointerException e) { + logEntityMissingRequiredValue("ignore_battle", name, "false"); eInfo.ignoreBattle = false; - logEntityMissingOptionalValue("ignore_battle", name, "false"); } - eInfo.category = entity.getString("category"); - if(eInfo.category == null) - { - logEntityMissingRequiredValue("category", name); - continue; + try { + eInfo.category = nestedConf.get("category"); + } catch (ClassCastException e) { + logEntityInvalidValue("category", name, "unknown"); + eInfo.category = "unknown"; + } catch (NullPointerException e) { + logEntityMissingRequiredValue("category", name, "unknown"); + eInfo.category = "unknown"; } - try - { - eInfo.decisionAttack = entity.getLong("decision_attack_probability").intValue(); - } - catch (NullPointerException e) - { - logEntityMissingRequiredValue("decision_attack_probability", name); - continue; + try { + eInfo.decisionAttack = nestedConf.getInt("decision_attack_probability"); + if(eInfo.decisionAttack < 0) { + logClampedValueEntity("decision_attack_probability", name, Integer.toString(eInfo.decisionAttack), "0"); + eInfo.decisionAttack = 0; + } else if(eInfo.decisionAttack > 100) { + logClampedValueEntity("decision_attack_probability", name, Integer.toString(eInfo.decisionAttack), "100"); + eInfo.decisionAttack = 100; + } + } catch (ClassCastException e) { + logEntityInvalidValue("decision_attack_probability", name, "70"); + eInfo.decisionAttack = 70; + } catch (NullPointerException e) { + logEntityMissingRequiredValue("decision_attack_probability", name, "70"); + eInfo.decisionAttack = 70; } - try - { - eInfo.decisionDefend = entity.getLong("decision_defend_probability").intValue(); - } - catch (NullPointerException e) - { - logEntityMissingRequiredValue("decision_defend_probability", name); - continue; + try { + eInfo.decisionDefend = nestedConf.getInt("decision_defend_probability"); + if(eInfo.decisionDefend < 0) { + logClampedValueEntity("decision_defend_probability", name, Integer.toString(eInfo.decisionDefend), "0"); + eInfo.decisionDefend = 0; + } else if(eInfo.decisionDefend > 100) { + logClampedValueEntity("decision_defend_probability", name, Integer.toString(eInfo.decisionDefend), "100"); + eInfo.decisionDefend = 100; + } + } catch (ClassCastException e) { + logEntityInvalidValue("decision_defend_probability", name, "20"); + eInfo.decisionDefend = 20; + } catch (NullPointerException e) { + logEntityMissingRequiredValue("decision_defend_probability", name, "20"); + eInfo.decisionDefend = 20; } - try - { - eInfo.decisionFlee = entity.getLong("decision_flee_probability").intValue(); - } - catch (NullPointerException e) - { - logEntityMissingRequiredValue("decision_flee_probability", name); - continue; + try { + eInfo.decisionFlee = nestedConf.getInt("decision_flee_probability"); + if(eInfo.decisionFlee < 0) { + logClampedValueEntity("decision_flee_probability", name, Integer.toString(eInfo.decisionFlee), "0"); + eInfo.decisionFlee = 0; + } else if(eInfo.decisionFlee > 100) { + logClampedValueEntity("decision_flee_probability", name, Integer.toString(eInfo.decisionFlee), "100"); + eInfo.decisionFlee = 100; + } + } catch (ClassCastException e) { + logEntityInvalidValue("decision_flee_probability", name, "10"); + eInfo.decisionFlee = 10; + } catch (NullPointerException e) { + logEntityMissingRequiredValue("decision_flee_probability", name, "10"); + eInfo.decisionFlee = 10; } - if(eInfo.classType != null) - { + if(eInfo.classType != null) { entityInfoMap.put(eInfo.classType.getName(), eInfo); - } - else if(!eInfo.customName.isEmpty()) - { + } else if(!eInfo.customName.isEmpty()) { customEntityInfoMap.put(eInfo.customName, eInfo); - } - else - { + } else { logger.error("Cannot add entity to internal config, no \"name\" or \"custom_name\""); } } @@ -608,31 +690,42 @@ public class Config return true; } - private void logNotFound(String option) - { + private void logNotFound(String option) { logger.warn("Config option \"" + option + "\" not found, setting defaults"); } - private void logNotFound(String option, String defaultValue) - { + private void logNotFound(String option, String defaultValue) { logger.warn("Config option \"" + option + "\" not found, defaulting to \"" + defaultValue + "\""); } - private void logEntityInvalidValue(String option, String name, String defaultValue) - { - logger.warn("Invalid \"" + option + "\" for \"" + name + "\", defaulting to " + defaultValue); + private void logEntityInvalidValue(String option, String name, String defaultValue) { + logger.warn("Invalid \"" + option + "\" for \"" + name + "\", defaulting to \"" + defaultValue + "\""); } - private void logEntityMissingRequiredValue(String option, String name) - { - logger.error("Entity \"" + name + "\" does not have option \"" + option + "\", skipping..."); + private void logEntityMissingRequiredValue(String option, String name, String defaultValue) { + logger.warn("Entity \"" + name + "\" does not have option \"" + option + "\", defaulting to \"" + defaultValue + "\""); } - private void logEntityMissingOptionalValue(String option, String name, String defaultValue) - { + private void logEntityMissingOptionalValue(String option, String name, String defaultValue) { logger.info("Entity \"" + name + "\" does not have optional option \"" + option + "\", defaulting to \"" + defaultValue + "\"..."); } + private void logClampedValue(String option, String from, String clampedTo) { + logger.warn("Option \"" + option + "\" is out of bounds, clamping value from \"" + from + "\" to \"" + clampedTo + "\""); + } + + private void logClampedValueEntity(String option, String name, String from, String clampedTo) { + logger.warn("Option \"" + option + "\" is out of bounds for \"" + name + "\", clamping value from \"" + from + "\" to \"" + clampedTo + "\""); + } + + private void logTOMLInvalidValue(String option) { + logger.warn("Config option \"" + option + "\" is an invalid value, setting defaults"); + } + + private void logTOMLInvalidValue(String option, String defaultValue) { + logger.warn("Config option \"" + option + "\" is an invalid value, defaulting to \"" + defaultValue + "\""); + } + private String getRegexEntityName(String name) { String regex = "^\\s*name\\s*=\\s*"; @@ -727,108 +820,45 @@ public class Config protected boolean editEntityEntry(EntityInfo eInfo) { - try - { - String cached = new String(); - char buf[] = new char[1024]; - int read = 0; - File config = new File(TurnBasedMinecraftMod.CONFIG_FILE_PATH); - { - FileReader fr = new FileReader(config); - read = fr.read(buf); - while (read != -1) - { - cached += String.valueOf(buf, 0, read); - read = fr.read(buf); - } - fr.close(); - } + CommentedFileConfig conf = CommentedFileConfig.builder(TurnBasedMinecraftMod.CONFIG_FILE_PATH).build(); + conf.load(); - int nameIndex = -1; - if(eInfo.classType != null) - { - Pattern p = Pattern.compile(getRegexEntityName(eInfo.classType.getName()), Pattern.MULTILINE); - Matcher m = p.matcher(cached); - if(m.find()) - { - nameIndex = m.start(); - } - } - else if(!eInfo.customName.isEmpty()) - { - Pattern p = Pattern.compile(getRegexCustomEntityName(eInfo.customName), Pattern.MULTILINE); - Matcher m = p.matcher(cached); - if(m.find()) - { - nameIndex = m.start(); - } - } - else - { - logger.error("EntityInfo does not have classType or customName, cannot edit/add"); - return false; - } - int entryIndex = -1; - int nextIndex = -1; - if(nameIndex != -1) - { - { - Pattern p = Pattern.compile("^\\s*\\[\\[\\s*server_config\\s*\\.\\s*entity\\s*]]", Pattern.MULTILINE); - Matcher m = p.matcher(cached.substring(0, nameIndex)); - while(m.find()) - { - entryIndex = m.start(); - } - if(entryIndex == -1) - { - logger.warn("editEntityEntry: could not find header for entry \"" + eInfo.classType.getName() + "\", skipping to adding it..."); - return addEntityEntry(eInfo); - } - } - { - Pattern p = Pattern.compile("^\\s*\\[", Pattern.MULTILINE); - Matcher m = p.matcher(cached.substring(nameIndex)); - if(m.find()) - { - nextIndex = m.start() + nameIndex; - } - } - } - else - { - if(eInfo.classType != null) - { - logger.warn("editEntityEntry: could not find entry for \"" + eInfo.classType.getName() + "\", skipping to adding it..."); - } - else if(!eInfo.customName.isEmpty()) - { - logger.warn("editEntityEntry: could not find entry for \"" + eInfo.customName + "\", skipping to adding it..."); - } - return addEntityEntry(eInfo); - } - - String cut = null; - if(nextIndex != -1) - { - cut = cached.substring(0, entryIndex) + cached.substring(nextIndex); - } - else - { - cut = cached.substring(0, entryIndex); - } - - { - FileWriter fw = new FileWriter(config); - fw.write(cut); - fw.close(); - } - - return addEntityEntry(eInfo); - } - catch (Throwable t) - { + Collection entities; + try { + entities = conf.get("server_config.entity"); + } catch (Throwable t) { return false; } + + if(eInfo.classType != null || !eInfo.customName.isEmpty()) { + for(com.electronwill.nightconfig.core.Config entity: entities) { + if((eInfo.classType != null && entity.get("name").equals(eInfo.classType.getName())) + || (!eInfo.customName.isEmpty() && entity.get("custom_name").equals(eInfo.customName))) { + entity.set("attack_power", eInfo.attackPower); + entity.set("attack_probability", eInfo.attackProbability); + entity.set("attack_variance", eInfo.attackVariance); + entity.set("attack_effect", eInfo.attackEffect.toString()); + entity.set("attack_effect_probability", eInfo.attackEffectProbability); + entity.set("defense_damage", eInfo.defenseDamage); + entity.set("defense_damage_probability", eInfo.defenseDamageProbability); + entity.set("evasion", eInfo.evasion); + entity.set("speed", eInfo.speed); + entity.set("ignore_battle", eInfo.ignoreBattle); + entity.set("category", eInfo.category); + entity.set("decision_attack_probability", eInfo.decisionAttack); + entity.set("decision_defend_probability", eInfo.decisionDefend); + entity.set("decision_flee_probability", eInfo.decisionFlee); + break; + } + } + } else { + return false; + } + + conf.save(); + conf.close(); + + return true; } public int getPlayerSpeed() @@ -925,36 +955,34 @@ public class Config return customEntityInfoMap.get(customName); } - private int getConfigFileVersion(InputStream io) - { - int version = 0; - try - { - TomlParseResult result = Toml.parse(io, TomlVersion.V0_5_0); - version = result.getLong("version").intValue(); - } - catch (Throwable t) - { - // ignored - } - return version; - } - private int getConfigFileVersion(File configFile) { int version = 0; - try - { - TomlParseResult result = Toml.parse(configFile.toPath(), TomlVersion.V0_5_0); - version = result.getLong("version").intValue(); - } - catch (Throwable t) - { - // ignored - } + + FileConfig conf = FileConfig.of(configFile); + version = conf.getIntOrElse("version", 0); + conf.close(); + return version; } + private void writeDefaultConfig(InputStream io) { + try { + FileOutputStream fos = new FileOutputStream(TurnBasedMinecraftMod.DEFAULT_CONFIG_FILE_PATH); + byte[] buffer = new byte[1024]; + int count; + while((count = io.read(buffer)) > 0) { + fos.write(buffer, 0, count); + } + fos.close(); + io.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + public boolean isIgnoreBattleType(String type) { return ignoreBattleTypes.contains(type); diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/EditingInfo.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/EditingInfo.java index 6ae4178..8c958e9 100644 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/EditingInfo.java +++ b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/EditingInfo.java @@ -1,10 +1,10 @@ package com.seodisparate.TurnBasedMinecraft.common; -import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.PlayerEntity; public class EditingInfo { - public EntityPlayer editor; + public PlayerEntity editor; public EntityInfo entityInfo; public boolean isPendingEntitySelection; public boolean isEditingCustomName; @@ -17,7 +17,7 @@ public class EditingInfo isEditingCustomName = false; } - public EditingInfo(EntityPlayer player) + public EditingInfo(PlayerEntity player) { editor = player; entityInfo = null; diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/EntityInfo.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/EntityInfo.java index 5fc994a..4113eb1 100644 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/EntityInfo.java +++ b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/EntityInfo.java @@ -1,8 +1,8 @@ package com.seodisparate.TurnBasedMinecraft.common; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.init.MobEffects; -import net.minecraft.potion.PotionEffect; +import net.minecraft.entity.LivingEntity; +import net.minecraft.potion.EffectInstance; +import net.minecraft.potion.Effects; public class EntityInfo { @@ -43,120 +43,84 @@ public class EntityInfo WEAKNESS, POISON, WITHER, + HEALTH_BOOST, ABSORPTION, SATURATION, GLOWING, LEVITATION, LUCK, UNLUCK, + SLOW_FALLING, + CONDUIT_POWER, + DOLPHINS_GRACE, + BAD_OMEN, FIRE, UNKNOWN; public static Effect fromString(String c) { c = c.toLowerCase(); - if(c.equals("speed")) - { + if(c.equals("speed")) { return SPEED; - } - else if(c.equals("slow")) - { + } else if(c.equals("slow")) { return SLOW; - } - else if(c.equals("haste")) - { + } else if(c.equals("haste")) { return HASTE; - } - else if(c.equals("mining_fatigue") || c.equals("fatigue")) - { + } else if(c.equals("mining_fatigue") || c.equals("fatigue")) { return MINING_FATIGUE; - } - else if(c.equals("strength")) - { + } else if(c.equals("strength")) { return STRENGTH; - } - else if(c.equals("jump_boost")) - { + } else if(c.equals("jump_boost")) { return JUMP_BOOST; - } - else if(c.equals("nausea")) - { + } else if(c.equals("nausea")) { return NAUSEA; - } - else if(c.equals("regeneration")) - { + } else if(c.equals("regeneration")) { return REGENERATION; - } - else if(c.equals("resistance")) - { + } else if(c.equals("resistance")) { return RESISTANCE; - } - else if(c.equals("fire_resistance")) - { + } else if(c.equals("fire_resistance")) { return FIRE_RESISTANCE; - } - else if(c.equals("water_breathing")) - { + } else if(c.equals("water_breathing")) { return WATER_BREATHING; - } - else if(c.equals("invisibility")) - { + } else if(c.equals("invisibility")) { return INVISIBILITY; - } - else if(c.equals("blindness") || c.equals("blind")) - { + } else if(c.equals("blindness") || c.equals("blind")) { return BLINDNESS; - } - else if(c.equals("night_vision")) - { + } else if(c.equals("night_vision")) { return NIGHT_VISION; - } - else if(c.equals("hunger")) - { + } else if(c.equals("hunger")) { return HUNGER; - } - else if(c.equals("weakness")) - { + } else if(c.equals("weakness")) { return WEAKNESS; - } - else if(c.equals("poison")) - { + } else if(c.equals("poison")) { return POISON; - } - else if(c.equals("wither")) - { + } else if(c.equals("wither")) { return WITHER; - } - else if(c.equals("absorption")) - { + } else if(c.equals("health_boost")) { + return HEALTH_BOOST; + } else if(c.equals("absorption")) { return ABSORPTION; - } - else if(c.equals("saturation")) - { + } else if(c.equals("saturation")) { return SATURATION; - } - else if(c.equals("glowing")) - { + } else if(c.equals("glowing")) { return GLOWING; - } - else if(c.equals("levitation")) - { + } else if(c.equals("levitation")) { return LEVITATION; - } - else if(c.equals("luck")) - { + } else if(c.equals("luck")) { return LUCK; - } - else if(c.equals("unluck")) - { + } else if(c.equals("unluck")) { return UNLUCK; - } - else if(c.equals("fire")) - { + } else if(c.equals("slow_falling")) { + return SLOW_FALLING; + } else if(c.equals("conduit_power")) { + return CONDUIT_POWER; + } else if(c.equals("dolphins_grace")) { + return DOLPHINS_GRACE; + } else if(c.equals("bad_omen")) { + return BAD_OMEN; + } else if(c.equals("fire")) { return FIRE; - } - else - { + } else { return UNKNOWN; } } @@ -201,6 +165,8 @@ public class EntityInfo return "poison"; case WITHER: return "wither"; + case HEALTH_BOOST: + return "health_boost"; case ABSORPTION: return "absorption"; case SATURATION: @@ -213,6 +179,14 @@ public class EntityInfo return "luck"; case UNLUCK: return "unluck"; + case SLOW_FALLING: + return "slow_falling"; + case CONDUIT_POWER: + return "conduit_power"; + case DOLPHINS_GRACE: + return "dolphins_grace"; + case BAD_OMEN: + return "bad_omen"; case FIRE: return "fire"; default: @@ -220,63 +194,71 @@ public class EntityInfo } } - public PotionEffect getPotionEffect() + public EffectInstance getPotionEffect() { return getPotionEffect(20 * 7, 0); } - public PotionEffect getPotionEffect(int duration, int amplifier) - { - switch(this) - { + public EffectInstance getPotionEffect(int duration, int amplifier) { + switch(this) { case SPEED: - return new PotionEffect(MobEffects.SPEED, duration, amplifier); + return new EffectInstance(Effects.SPEED, duration, amplifier); case SLOW: - return new PotionEffect(MobEffects.SLOWNESS, duration, amplifier); + return new EffectInstance(Effects.SLOWNESS, duration, amplifier); case HASTE: - return new PotionEffect(MobEffects.HASTE, duration, amplifier); + return new EffectInstance(Effects.HASTE, duration, amplifier); case MINING_FATIGUE: - return new PotionEffect(MobEffects.MINING_FATIGUE, duration, amplifier); + return new EffectInstance(Effects.MINING_FATIGUE, duration, amplifier); case STRENGTH: - return new PotionEffect(MobEffects.STRENGTH, duration, amplifier); + return new EffectInstance(Effects.STRENGTH, duration, amplifier); case JUMP_BOOST: - return new PotionEffect(MobEffects.JUMP_BOOST, duration, amplifier); + return new EffectInstance(Effects.JUMP_BOOST, duration, amplifier); case NAUSEA: - return new PotionEffect(MobEffects.NAUSEA, duration, amplifier); + return new EffectInstance(Effects.NAUSEA, duration, amplifier); case REGENERATION: - return new PotionEffect(MobEffects.REGENERATION, duration, amplifier); + return new EffectInstance(Effects.REGENERATION, duration, amplifier); case RESISTANCE: - return new PotionEffect(MobEffects.RESISTANCE, duration, amplifier); + return new EffectInstance(Effects.RESISTANCE, duration, amplifier); case FIRE_RESISTANCE: - return new PotionEffect(MobEffects.FIRE_RESISTANCE, duration, amplifier); + return new EffectInstance(Effects.FIRE_RESISTANCE, duration, amplifier); case WATER_BREATHING: - return new PotionEffect(MobEffects.WATER_BREATHING, duration, amplifier); + return new EffectInstance(Effects.WATER_BREATHING, duration, amplifier); case INVISIBILITY: - return new PotionEffect(MobEffects.INVISIBILITY, duration, amplifier); + return new EffectInstance(Effects.INVISIBILITY, duration, amplifier); case BLINDNESS: - return new PotionEffect(MobEffects.BLINDNESS, duration, amplifier); + return new EffectInstance(Effects.BLINDNESS, duration, amplifier); case NIGHT_VISION: - return new PotionEffect(MobEffects.NIGHT_VISION, duration, amplifier); + return new EffectInstance(Effects.NIGHT_VISION, duration, amplifier); case HUNGER: - return new PotionEffect(MobEffects.HUNGER, duration, amplifier); + return new EffectInstance(Effects.HUNGER, duration, amplifier); case WEAKNESS: - return new PotionEffect(MobEffects.WEAKNESS, duration, amplifier); + return new EffectInstance(Effects.WEAKNESS, duration, amplifier); case POISON: - return new PotionEffect(MobEffects.POISON, duration, amplifier); + return new EffectInstance(Effects.POISON, duration, amplifier); case WITHER: - return new PotionEffect(MobEffects.WITHER, duration, amplifier); + return new EffectInstance(Effects.WITHER, duration, amplifier); + case HEALTH_BOOST: + return new EffectInstance(Effects.HEALTH_BOOST, duration, amplifier); case ABSORPTION: - return new PotionEffect(MobEffects.ABSORPTION, duration, amplifier); + return new EffectInstance(Effects.ABSORPTION, duration, amplifier); case SATURATION: - return new PotionEffect(MobEffects.SATURATION, duration, amplifier); + return new EffectInstance(Effects.SATURATION, duration, amplifier); case GLOWING: - return new PotionEffect(MobEffects.GLOWING, duration, amplifier); + return new EffectInstance(Effects.GLOWING, duration, amplifier); case LEVITATION: - return new PotionEffect(MobEffects.LEVITATION, duration, amplifier); + return new EffectInstance(Effects.LEVITATION, duration, amplifier); case LUCK: - return new PotionEffect(MobEffects.LUCK, duration, amplifier); + return new EffectInstance(Effects.LUCK, duration, amplifier); case UNLUCK: - return new PotionEffect(MobEffects.UNLUCK, duration, amplifier); + return new EffectInstance(Effects.UNLUCK, duration, amplifier); + case SLOW_FALLING: + return new EffectInstance(Effects.SLOW_FALLING, duration, amplifier); + case CONDUIT_POWER: + return new EffectInstance(Effects.CONDUIT_POWER, duration, amplifier); + case DOLPHINS_GRACE: + return new EffectInstance(Effects.DOLPHINS_GRACE, duration, amplifier); + case BAD_OMEN: + return new EffectInstance(Effects.BAD_OMEN, duration, amplifier); case FIRE: // FIRE is not a PotionEffect and must be applied directly to the Entity return null; @@ -285,12 +267,12 @@ public class EntityInfo } } - public void applyEffectToEntity(EntityLivingBase entity) + public void applyEffectToEntity(LivingEntity entity) { applyEffectToEntity(entity, 20 * 12, 0); } - public void applyEffectToEntity(EntityLivingBase entity, int duration, int amplifier) + public void applyEffectToEntity(LivingEntity entity, int duration, int amplifier) { if(this == FIRE) { @@ -343,6 +325,8 @@ public class EntityInfo return "poisoned"; case WITHER: return "withered"; + case HEALTH_BOOST: + return "given more health"; case ABSORPTION: return "given absorption"; case SATURATION: @@ -355,6 +339,12 @@ public class EntityInfo return "given luck"; case UNLUCK: return "made unlucky"; + case SLOW_FALLING: + return "falls slower"; + case CONDUIT_POWER: + return "made able to live underwater"; + case BAD_OMEN: + return "feels a bad omen"; case FIRE: return "set on fire"; default: diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/PlayerJoinEventHandler.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/PlayerJoinEventHandler.java index be06c38..a0832fe 100644 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/PlayerJoinEventHandler.java +++ b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/PlayerJoinEventHandler.java @@ -1,8 +1,8 @@ package com.seodisparate.TurnBasedMinecraft.common; -import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.PlayerEntity; import net.minecraftforge.event.entity.EntityJoinWorldEvent; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; public class PlayerJoinEventHandler { @@ -13,7 +13,7 @@ public class PlayerJoinEventHandler { return; } - if(event.getEntity() instanceof EntityPlayer && TurnBasedMinecraftMod.proxy.getConfig().getBattleDisabledForAll()) + if(event.getEntity() instanceof PlayerEntity && TurnBasedMinecraftMod.proxy.getConfig().getBattleDisabledForAll()) { TurnBasedMinecraftMod.proxy.getConfig().addBattleIgnoringPlayer(event.getEntity().getEntityId()); } diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/TurnBasedMinecraftMod.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/TurnBasedMinecraftMod.java index 6d17a75..70d3067 100644 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/TurnBasedMinecraftMod.java +++ b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/TurnBasedMinecraftMod.java @@ -1,99 +1,122 @@ package com.seodisparate.TurnBasedMinecraft.common; +import com.seodisparate.TurnBasedMinecraft.client.ClientProxy; import com.seodisparate.TurnBasedMinecraft.common.networking.*; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.DistExecutor; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; +import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; +import net.minecraftforge.fml.event.lifecycle.FMLDedicatedServerSetupEvent; +import net.minecraftforge.fml.event.server.FMLServerStartingEvent; +import net.minecraftforge.fml.event.server.FMLServerStoppingEvent; +import net.minecraftforge.fml.network.NetworkRegistry; +import net.minecraftforge.fml.network.simple.SimpleChannel; +import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.common.Mod.EventHandler; -import net.minecraftforge.fml.common.SidedProxy; -import net.minecraftforge.fml.common.event.FMLInitializationEvent; -import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; -import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; -import net.minecraftforge.fml.common.event.FMLServerStartingEvent; -import net.minecraftforge.fml.common.event.FMLServerStoppingEvent; -import net.minecraftforge.fml.common.network.NetworkRegistry; -import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; -import net.minecraftforge.fml.relauncher.Side; - -@Mod(modid = TurnBasedMinecraftMod.MODID, name = TurnBasedMinecraftMod.NAME, version = TurnBasedMinecraftMod.VERSION) +@Mod(value = TurnBasedMinecraftMod.MODID) public class TurnBasedMinecraftMod { public static final String MODID = "com.seodisparate.turnbasedminecraft"; public static final String NAME = "Turn Based Minecraft Mod"; public static final String VERSION = "1.8"; public static final String CONFIG_FILENAME = "TBM_Config.toml"; + public static final String DEFAULT_CONFIG_FILENAME = "TBM_Config_DEFAULT.toml"; public static final String CONFIG_DIRECTORY = "config/TurnBasedMinecraft/"; public static final String CONFIG_FILE_PATH = CONFIG_DIRECTORY + CONFIG_FILENAME; + public static final String DEFAULT_CONFIG_FILE_PATH = CONFIG_DIRECTORY + DEFAULT_CONFIG_FILENAME; public static final String CONFIG_INTERNAL_PATH = "/assets/TurnBasedMinecraft/" + CONFIG_FILENAME; public static final String MUSIC_ROOT = CONFIG_DIRECTORY + "Music/"; public static final String MUSIC_SILLY = MUSIC_ROOT + "silly/"; public static final String MUSIC_BATTLE = MUSIC_ROOT + "battle/"; - public static final SimpleNetworkWrapper NWINSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel("seodisparate.tbmc"); - protected static Logger logger; - private static int packetHandlerID = 0; + private static final String PROTOCOL_VERSION = Integer.toString(1); + private static final ResourceLocation HANDLER_ID = new ResourceLocation(MODID, "main_channel"); + private static final SimpleChannel HANDLER = NetworkRegistry.ChannelBuilder + .named(HANDLER_ID) + .clientAcceptedVersions(PROTOCOL_VERSION::equals) + .serverAcceptedVersions(PROTOCOL_VERSION::equals) + .networkProtocolVersion(() -> PROTOCOL_VERSION) + .simpleChannel(); + protected static Logger logger = LogManager.getLogger(); + + public static ResourceLocation getNetResourceLocation() { + return HANDLER_ID; + } + + public static SimpleChannel getHandler() { + return HANDLER; + } - @SidedProxy(modId=MODID, serverSide="com.seodisparate.TurnBasedMinecraft.common.CommonProxy", clientSide="com.seodisparate.TurnBasedMinecraft.client.ClientProxy") public static CommonProxy proxy; - @EventHandler - public void preInit(FMLPreInitializationEvent event) - { - logger = event.getModLog(); - proxy.setLogger(logger); - } - - @EventHandler - public void init(FMLInitializationEvent event) + @SubscribeEvent + public void firstInit(FMLCommonSetupEvent event) { + proxy = DistExecutor.runForDist(()->()->new ClientProxy(), ()->()->new CommonProxy()); proxy.initialize(); + proxy.setLogger(logger); // register packets - NWINSTANCE.registerMessage( - PacketBattleInfo.HandlerBattleInfo.class, - PacketBattleInfo.class, - packetHandlerID++, - Side.CLIENT); - NWINSTANCE.registerMessage( - PacketBattleRequestInfo.HandlerBattleRequestInfo.class, - PacketBattleRequestInfo.class, - packetHandlerID++, - Side.SERVER); - NWINSTANCE.registerMessage( - PacketBattleDecision.HandleBattleDecision.class, - PacketBattleDecision.class, - packetHandlerID++, - Side.SERVER); - NWINSTANCE.registerMessage( - PacketBattleMessage.HandlerBattleMessage.class, - PacketBattleMessage.class, - packetHandlerID++, - Side.CLIENT); - NWINSTANCE.registerMessage( - PacketGeneralMessage.HandlerGeneralMessage.class, - PacketGeneralMessage.class, - packetHandlerID++, - Side.CLIENT); - NWINSTANCE.registerMessage( - PacketEditingMessage.HandlerEditingMessage.class, - PacketEditingMessage.class, - packetHandlerID++, - Side.CLIENT - ); + int packetHandlerID = 0; + HANDLER.registerMessage( + packetHandlerID++, + PacketBattleInfo.class, + PacketBattleInfo::encode, + PacketBattleInfo::decode, + PacketBattleInfo.Handler::handle); + HANDLER.registerMessage( + packetHandlerID++, + PacketBattleRequestInfo.class, + PacketBattleRequestInfo::encode, + PacketBattleRequestInfo::decode, + PacketBattleRequestInfo.Handler::handle); + HANDLER.registerMessage( + packetHandlerID++, + PacketBattleDecision.class, + PacketBattleDecision::encode, + PacketBattleDecision::decode, + PacketBattleDecision.Handler::handle); + HANDLER.registerMessage( + packetHandlerID++, + PacketBattleMessage.class, + PacketBattleMessage::encode, + PacketBattleMessage::decode, + PacketBattleMessage.Handler::handle); + HANDLER.registerMessage( + packetHandlerID++, + PacketGeneralMessage.class, + PacketGeneralMessage::encode, + PacketGeneralMessage::decode, + PacketGeneralMessage.Handler::handle); + HANDLER.registerMessage( + packetHandlerID++, + PacketEditingMessage.class, + PacketEditingMessage::encode, + PacketEditingMessage::decode, + PacketEditingMessage.Handler::handle); // register event handler(s) MinecraftForge.EVENT_BUS.register(new AttackEventHandler()); MinecraftForge.EVENT_BUS.register(new PlayerJoinEventHandler()); } - - @EventHandler - public void postInit(FMLPostInitializationEvent event) + + @SubscribeEvent + public void secondInitClient(FMLClientSetupEvent event) { - proxy.postInit(); + proxy.postInit(); } - @EventHandler + @SubscribeEvent + public void secondInitServer(FMLDedicatedServerSetupEvent event) + { + proxy.postInit(); + } + + @SubscribeEvent public void serverStarting(FMLServerStartingEvent event) { logger.debug("About to initialize BattleManager"); @@ -113,7 +136,7 @@ public class TurnBasedMinecraftMod event.registerServerCommand(new CommandTBMEdit(proxy.getConfig())); } - @EventHandler + @SubscribeEvent public void serverStopping(FMLServerStoppingEvent event) { logger.debug("About to cleanup BattleManager"); diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/Utility.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/Utility.java index b54b853..203c93a 100644 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/Utility.java +++ b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/Utility.java @@ -1,8 +1,8 @@ package com.seodisparate.TurnBasedMinecraft.common; import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemArrow; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.item.ArrowItem; public class Utility { @@ -33,11 +33,11 @@ public class Utility } } - public static boolean doesPlayerHaveArrows(EntityPlayer player) + public static boolean doesPlayerHaveArrows(PlayerEntity player) { for(int i = 0; i < player.inventory.getSizeInventory(); ++i) { - if(player.inventory.getStackInSlot(i).getItem() instanceof ItemArrow) + if(player.inventory.getStackInSlot(i).getItem() instanceof ArrowItem) { return true; } diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketBattleDecision.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketBattleDecision.java index f2e31e6..3f5227d 100644 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketBattleDecision.java +++ b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketBattleDecision.java @@ -1,16 +1,16 @@ package com.seodisparate.TurnBasedMinecraft.common.networking; +import java.util.function.Supplier; + import com.seodisparate.TurnBasedMinecraft.common.Battle; import com.seodisparate.TurnBasedMinecraft.common.TurnBasedMinecraftMod; import com.seodisparate.TurnBasedMinecraft.common.Battle.Decision; -import io.netty.buffer.ByteBuf; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraftforge.fml.common.network.simpleimpl.IMessage; -import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; -import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; +import net.minecraft.entity.player.ServerPlayerEntity; +import net.minecraft.network.PacketBuffer; +import net.minecraftforge.fml.network.NetworkEvent; -public class PacketBattleDecision implements IMessage +public class PacketBattleDecision { private int battleID; private Battle.Decision decision; @@ -24,35 +24,28 @@ public class PacketBattleDecision implements IMessage this.decision = decision; this.targetIDOrItemID = targetIDOrItemID; } - - @Override - public void fromBytes(ByteBuf buf) - { - battleID = buf.readInt(); - decision = Decision.valueOf(buf.readInt()); - targetIDOrItemID = buf.readInt(); + + public static void encode(PacketBattleDecision pkt, PacketBuffer buf) { + buf.writeInt(pkt.battleID); + buf.writeInt(pkt.decision.getValue()); + buf.writeInt(pkt.targetIDOrItemID); } - - @Override - public void toBytes(ByteBuf buf) - { - buf.writeInt(battleID); - buf.writeInt(decision.getValue()); - buf.writeInt(targetIDOrItemID); + + public static PacketBattleDecision decode(PacketBuffer buf) { + return new PacketBattleDecision(buf.readInt(), Decision.valueOf(buf.readInt()), buf.readInt()); } - - public static class HandleBattleDecision implements IMessageHandler - { - @Override - public IMessage onMessage(PacketBattleDecision message, MessageContext ctx) - { - Battle b = TurnBasedMinecraftMod.proxy.getBattleManager().getBattleByID(message.battleID); - if(b != null) - { - EntityPlayerMP player = ctx.getServerHandler().player; - b.setDecision(player.getEntityId(), message.decision, message.targetIDOrItemID); - } - return null; - } + + public static class Handler { + public static void handle(final PacketBattleDecision pkt, Supplier ctx) { + ctx.get().enqueueWork(() -> { + Battle b = TurnBasedMinecraftMod.proxy.getBattleManager().getBattleByID(pkt.battleID); + if(b != null) + { + ServerPlayerEntity player = ctx.get().getSender(); + b.setDecision(player.getEntityId(), pkt.decision, pkt.targetIDOrItemID); + } + }); + ctx.get().setPacketHandled(true); + } } } diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketBattleInfo.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketBattleInfo.java index 5ccbc3a..d5aaf2c 100644 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketBattleInfo.java +++ b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketBattleInfo.java @@ -2,17 +2,16 @@ package com.seodisparate.TurnBasedMinecraft.common.networking; import java.util.ArrayList; import java.util.Collection; +import java.util.function.Supplier; import com.seodisparate.TurnBasedMinecraft.common.TurnBasedMinecraftMod; -import io.netty.buffer.ByteBuf; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; -import net.minecraftforge.fml.common.network.simpleimpl.IMessage; -import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; -import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; +import net.minecraft.network.PacketBuffer; +import net.minecraftforge.fml.network.NetworkEvent; -public class PacketBattleInfo implements IMessage +public class PacketBattleInfo { private Collection sideA; private Collection sideB; @@ -32,67 +31,61 @@ public class PacketBattleInfo implements IMessage this.decisionNanos = decisionNanos; } - @Override - public void fromBytes(ByteBuf buf) - { - int sideACount = buf.readInt(); - int sideBCount = buf.readInt(); - for(int i = 0; i < sideACount; ++i) - { - sideA.add(buf.readInt()); - } - for(int i = 0; i < sideBCount; ++i) - { - sideB.add(buf.readInt()); - } - decisionNanos = buf.readLong(); + public static void encode(PacketBattleInfo pkt, PacketBuffer buf) { + buf.writeInt(pkt.sideA.size()); + buf.writeInt(pkt.sideB.size()); + for(Integer id : pkt.sideA) { + buf.writeInt(id); + } + for(Integer id : pkt.sideB) { + buf.writeInt(id); + } + buf.writeLong(pkt.decisionNanos); } - - @Override - public void toBytes(ByteBuf buf) - { - buf.writeInt(sideA.size()); - buf.writeInt(sideB.size()); - for(Integer id : sideA) - { - buf.writeInt(id); - } - for(Integer id : sideB) - { - buf.writeInt(id); - } - buf.writeLong(decisionNanos); + + public static PacketBattleInfo decode(PacketBuffer buf) { + int sideACount = buf.readInt(); + int sideBCount = buf.readInt(); + Collection sideA = new ArrayList(sideACount); + Collection sideB = new ArrayList(sideBCount); + for(int i = 0; i < sideACount; ++i) { + sideA.add(buf.readInt()); + } + for(int i = 0; i < sideBCount; ++i) { + sideB.add(buf.readInt()); + } + long decisionNanos = buf.readLong(); + return new PacketBattleInfo(sideA, sideB, decisionNanos); } - - public static class HandlerBattleInfo implements IMessageHandler - { - @Override - public IMessage onMessage(PacketBattleInfo message, MessageContext ctx) - { - if(TurnBasedMinecraftMod.proxy.getLocalBattle() == null) - { - return null; - } - TurnBasedMinecraftMod.proxy.getLocalBattle().clearCombatants(); - for(Integer id : message.sideA) - { - Entity e = Minecraft.getMinecraft().world.getEntityByID(id); - if(e != null) + + public static class Handler { + public static void handle(final PacketBattleInfo pkt, Supplier ctx) { + ctx.get().enqueueWork(() -> { + if(TurnBasedMinecraftMod.proxy.getLocalBattle() == null) { - TurnBasedMinecraftMod.proxy.getLocalBattle().addCombatantToSideA(e); + return; } - } - for(Integer id : message.sideB) - { - Entity e = Minecraft.getMinecraft().world.getEntityByID(id); - if(e != null) + TurnBasedMinecraftMod.proxy.getLocalBattle().clearCombatants(); + for(Integer id : pkt.sideA) { - TurnBasedMinecraftMod.proxy.getLocalBattle().addCombatantToSideB(e); + Entity e = Minecraft.getInstance().world.getEntityByID(id); + if(e != null) + { + TurnBasedMinecraftMod.proxy.getLocalBattle().addCombatantToSideA(e); + } } - } - TurnBasedMinecraftMod.proxy.setBattleGuiTime((int)(message.decisionNanos / 1000000000L)); - TurnBasedMinecraftMod.proxy.setBattleGuiBattleChanged(); - return null; - } + for(Integer id : pkt.sideB) + { + Entity e = Minecraft.getInstance().world.getEntityByID(id); + if(e != null) + { + TurnBasedMinecraftMod.proxy.getLocalBattle().addCombatantToSideB(e); + } + } + TurnBasedMinecraftMod.proxy.setBattleGuiTime((int)(pkt.decisionNanos / 1000000000L)); + TurnBasedMinecraftMod.proxy.setBattleGuiBattleChanged(); + }); + ctx.get().setPacketHandled(true); + } } } diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketBattleMessage.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketBattleMessage.java index 6ee5400..eeda898 100644 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketBattleMessage.java +++ b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketBattleMessage.java @@ -2,19 +2,15 @@ package com.seodisparate.TurnBasedMinecraft.common.networking; import java.util.HashMap; import java.util.Map; +import java.util.function.Supplier; import com.seodisparate.TurnBasedMinecraft.common.TurnBasedMinecraftMod; -import io.netty.buffer.ByteBuf; import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.scoreboard.ScorePlayerTeam; -import net.minecraftforge.fml.common.network.ByteBufUtils; -import net.minecraftforge.fml.common.network.simpleimpl.IMessage; -import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; -import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; +import net.minecraft.network.PacketBuffer; +import net.minecraftforge.fml.network.NetworkEvent; -public class PacketBattleMessage implements IMessage +public class PacketBattleMessage { public enum MessageType { @@ -124,222 +120,175 @@ public class PacketBattleMessage implements IMessage this.amount = amount; this.custom = custom; } - - @Override - public void fromBytes(ByteBuf buf) - { - messageType = MessageType.valueOf(buf.readInt()); - entityIDFrom = buf.readInt(); - entityIDTo = buf.readInt(); - amount = buf.readInt(); - custom = ByteBufUtils.readUTF8String(buf); + + public static void encode(PacketBattleMessage pkt, PacketBuffer buf) { + buf.writeInt(pkt.messageType.getValue()); + buf.writeInt(pkt.entityIDFrom); + buf.writeInt(pkt.entityIDTo); + buf.writeInt(pkt.amount); + buf.writeString(pkt.custom); } - - @Override - public void toBytes(ByteBuf buf) - { - buf.writeInt(messageType.getValue()); - buf.writeInt(entityIDFrom); - buf.writeInt(entityIDTo); - buf.writeInt(amount); - ByteBufUtils.writeUTF8String(buf, custom); + + public static PacketBattleMessage decode(PacketBuffer buf) { + return new PacketBattleMessage( + MessageType.valueOf( + buf.readInt()), + buf.readInt(), + buf.readInt(), + buf.readInt(), + buf.readString()); } - - public static class HandlerBattleMessage implements IMessageHandler - { - @Override - public IMessage onMessage(PacketBattleMessage message, MessageContext ctx) - { - Entity fromEntity = TurnBasedMinecraftMod.proxy.getEntityByID(message.entityIDFrom); - String from = "Unknown"; - if(fromEntity != null) - { - if(fromEntity.hasCustomName()) - { - from = fromEntity.getCustomNameTag(); - } - else if(fromEntity instanceof EntityPlayer) - { - from = ScorePlayerTeam.formatPlayerName(fromEntity.getTeam(), fromEntity.getName()); - } - else - { - from = fromEntity.getName(); - } - } - else if(TurnBasedMinecraftMod.proxy.getLocalBattle() != null) - { - fromEntity = TurnBasedMinecraftMod.proxy.getLocalBattle().getCombatantEntity(message.entityIDFrom); + + public static class Handler { + public static void handle(final PacketBattleMessage pkt, Supplier ctx) { + ctx.get().enqueueWork(() -> { + Entity fromEntity = TurnBasedMinecraftMod.proxy.getEntityByID(pkt.entityIDFrom); + String from = "Unknown"; if(fromEntity != null) { - if(fromEntity.hasCustomName()) + from = fromEntity.getDisplayName().getFormattedText(); + } + else if(TurnBasedMinecraftMod.proxy.getLocalBattle() != null) + { + fromEntity = TurnBasedMinecraftMod.proxy.getLocalBattle().getCombatantEntity(pkt.entityIDFrom); + if(fromEntity != null) { - from = fromEntity.getCustomNameTag(); - } - else if(fromEntity instanceof EntityPlayer) - { - from = ScorePlayerTeam.formatPlayerName(fromEntity.getTeam(), fromEntity.getName()); - } - else - { - from = fromEntity.getName(); + from = fromEntity.getDisplayName().getFormattedText(); } } - } - Entity toEntity = TurnBasedMinecraftMod.proxy.getEntityByID(message.entityIDTo); - String to = "Unknown"; - if(toEntity != null) - { - if(toEntity.hasCustomName()) - { - to = toEntity.getCustomNameTag(); - } - else if(toEntity instanceof EntityPlayer) - { - to = ScorePlayerTeam.formatPlayerName(toEntity.getTeam(), toEntity.getName()); - } - else - { - to = toEntity.getName(); - } - } - else if(TurnBasedMinecraftMod.proxy.getLocalBattle() != null) - { - toEntity = TurnBasedMinecraftMod.proxy.getLocalBattle().getCombatantEntity(message.entityIDTo); + Entity toEntity = TurnBasedMinecraftMod.proxy.getEntityByID(pkt.entityIDTo); + String to = "Unknown"; if(toEntity != null) { - if(toEntity.hasCustomName()) + to = toEntity.getDisplayName().getFormattedText(); + } + else if(TurnBasedMinecraftMod.proxy.getLocalBattle() != null) + { + toEntity = TurnBasedMinecraftMod.proxy.getLocalBattle().getCombatantEntity(pkt.entityIDTo); + if(toEntity != null) { - to = toEntity.getCustomNameTag(); + to = toEntity.getDisplayName().getFormattedText(); } - else if(toEntity instanceof EntityPlayer) + } + + switch(pkt.messageType) + { + case ENTERED: + TurnBasedMinecraftMod.proxy.displayString(from + " entered battle!"); + if(TurnBasedMinecraftMod.proxy.getLocalBattle() == null || TurnBasedMinecraftMod.proxy.getLocalBattle().getId() != pkt.amount) { - to = ScorePlayerTeam.formatPlayerName(toEntity.getTeam(), toEntity.getName()); + TurnBasedMinecraftMod.proxy.createLocalBattle(pkt.amount); + } + TurnBasedMinecraftMod.proxy.battleStarted(); + TurnBasedMinecraftMod.proxy.typeEnteredBattle(pkt.custom); + break; + case FLEE: + if(pkt.amount != 0) + { + TurnBasedMinecraftMod.proxy.displayString(from + " fled battle!"); + TurnBasedMinecraftMod.proxy.typeLeftBattle(pkt.custom); } else { - to = toEntity.getName(); + TurnBasedMinecraftMod.proxy.displayString(from + " tried to flee battle but failed!"); } - } - } - - switch(message.messageType) - { - case ENTERED: - TurnBasedMinecraftMod.proxy.displayString(from + " entered battle!"); - if(TurnBasedMinecraftMod.proxy.getLocalBattle() == null || TurnBasedMinecraftMod.proxy.getLocalBattle().getId() != message.amount) - { - TurnBasedMinecraftMod.proxy.createLocalBattle(message.amount); - } - TurnBasedMinecraftMod.proxy.battleStarted(); - TurnBasedMinecraftMod.proxy.typeEnteredBattle(message.custom); - break; - case FLEE: - if(message.amount != 0) - { - TurnBasedMinecraftMod.proxy.displayString(from + " fled battle!"); - TurnBasedMinecraftMod.proxy.typeLeftBattle(message.custom); - } - else - { - TurnBasedMinecraftMod.proxy.displayString(from + " tried to flee battle but failed!"); - } - break; - case DIED: - TurnBasedMinecraftMod.proxy.displayString(from + " died in battle!"); - TurnBasedMinecraftMod.proxy.typeLeftBattle(message.custom); - break; - case ENDED: - TurnBasedMinecraftMod.proxy.displayString("Battle has ended!"); - TurnBasedMinecraftMod.proxy.battleEnded(); - break; - case ATTACK: - TurnBasedMinecraftMod.proxy.displayString(from + " attacked " + to + " and dealt " + message.amount + " damage!"); - break; - case DEFEND: - TurnBasedMinecraftMod.proxy.displayString(from + " blocked " + to + "'s attack!"); - break; - case DEFENSE_DAMAGE: - TurnBasedMinecraftMod.proxy.displayString(from + " retaliated from " + to + "'s attack and dealt " + message.amount + " damage!"); - break; - case MISS: - TurnBasedMinecraftMod.proxy.displayString(from + " attacked " + to + " but missed!"); - break; - case DEFENDING: - TurnBasedMinecraftMod.proxy.displayString(from + " is defending!"); - break; - case DID_NOTHING: - TurnBasedMinecraftMod.proxy.displayString(from + " did nothing!"); - break; - case USED_ITEM: - switch(UsedItemAction.valueOf(message.amount)) - { - case USED_NOTHING: - TurnBasedMinecraftMod.proxy.displayString(from + " tried to use nothing!"); break; - case USED_INVALID: - if(message.custom.length() > 0) + case DIED: + TurnBasedMinecraftMod.proxy.displayString(from + " died in battle!"); + TurnBasedMinecraftMod.proxy.typeLeftBattle(pkt.custom); + break; + case ENDED: + TurnBasedMinecraftMod.proxy.displayString("Battle has ended!"); + TurnBasedMinecraftMod.proxy.battleEnded(); + break; + case ATTACK: + TurnBasedMinecraftMod.proxy.displayString(from + " attacked " + to + " and dealt " + pkt.amount + " damage!"); + break; + case DEFEND: + TurnBasedMinecraftMod.proxy.displayString(from + " blocked " + to + "'s attack!"); + break; + case DEFENSE_DAMAGE: + TurnBasedMinecraftMod.proxy.displayString(from + " retaliated from " + to + "'s attack and dealt " + pkt.amount + " damage!"); + break; + case MISS: + TurnBasedMinecraftMod.proxy.displayString(from + " attacked " + to + " but missed!"); + break; + case DEFENDING: + TurnBasedMinecraftMod.proxy.displayString(from + " is defending!"); + break; + case DID_NOTHING: + TurnBasedMinecraftMod.proxy.displayString(from + " did nothing!"); + break; + case USED_ITEM: + switch(UsedItemAction.valueOf(pkt.amount)) { - TurnBasedMinecraftMod.proxy.displayString(from + " tried to consume " + message.custom + " and failed!"); + case USED_NOTHING: + TurnBasedMinecraftMod.proxy.displayString(from + " tried to use nothing!"); + break; + case USED_INVALID: + if(pkt.custom.length() > 0) + { + TurnBasedMinecraftMod.proxy.displayString(from + " tried to consume " + pkt.custom + " and failed!"); + } + else + { + TurnBasedMinecraftMod.proxy.displayString(from + " tried to consume an invalid item and failed!"); + } + break; + case USED_FOOD: + TurnBasedMinecraftMod.proxy.displayString(from + " ate a " + pkt.custom + "!"); + break; + case USED_POTION: + TurnBasedMinecraftMod.proxy.displayString(from + " drank a " + pkt.custom + "!"); + break; + } + break; + case TURN_BEGIN: + TurnBasedMinecraftMod.proxy.displayString("The turn begins!"); + TurnBasedMinecraftMod.proxy.battleGuiTurnBegin(); + break; + case TURN_END: + if(TurnBasedMinecraftMod.proxy.getLocalBattle() != null) + { + if(pkt.amount == 0) + { + TurnBasedMinecraftMod.proxy.displayString("The turn ended!"); + } + else + { + TurnBasedMinecraftMod.proxy.displayString("The turn ended (abnormally due to internal error)!"); + } + } + TurnBasedMinecraftMod.proxy.battleGuiTurnEnd(); + break; + case SWITCHED_ITEM: + if(pkt.amount != 0) + { + TurnBasedMinecraftMod.proxy.displayString(from + " switched to a different item!"); } else { - TurnBasedMinecraftMod.proxy.displayString(from + " tried to consume an invalid item and failed!"); + TurnBasedMinecraftMod.proxy.displayString(from + " switched to a different item but failed because it was invalid!"); } break; - case USED_FOOD: - TurnBasedMinecraftMod.proxy.displayString(from + " ate a " + message.custom + "!"); + case WAS_AFFECTED: + TurnBasedMinecraftMod.proxy.displayString(to + " was " + pkt.custom + " by " + from + "!"); break; - case USED_POTION: - TurnBasedMinecraftMod.proxy.displayString(from + " drank a " + message.custom + "!"); + case BECAME_CREATIVE: + TurnBasedMinecraftMod.proxy.displayString(from + " entered creative mode and left battle!"); + break; + case FIRED_ARROW: + TurnBasedMinecraftMod.proxy.displayString(from + " let loose an arrow towards " + to + "!"); + break; + case ARROW_HIT: + TurnBasedMinecraftMod.proxy.displayString(to + " was hit by " + from + "'s arrow!"); + break; + case BOW_NO_AMMO: + TurnBasedMinecraftMod.proxy.displayString(from + " tried to use their bow but ran out of ammo!"); break; } - break; - case TURN_BEGIN: - TurnBasedMinecraftMod.proxy.displayString("The turn begins!"); - TurnBasedMinecraftMod.proxy.battleGuiTurnBegin(); - break; - case TURN_END: - if(TurnBasedMinecraftMod.proxy.getLocalBattle() != null) - { - if(message.amount == 0) - { - TurnBasedMinecraftMod.proxy.displayString("The turn ended!"); - } - else - { - TurnBasedMinecraftMod.proxy.displayString("The turn ended (abnormally due to internal error)!"); - } - } - TurnBasedMinecraftMod.proxy.battleGuiTurnEnd(); - break; - case SWITCHED_ITEM: - if(message.amount != 0) - { - TurnBasedMinecraftMod.proxy.displayString(from + " switched to a different item!"); - } - else - { - TurnBasedMinecraftMod.proxy.displayString(from + " switched to a different item but failed because it was invalid!"); - } - break; - case WAS_AFFECTED: - TurnBasedMinecraftMod.proxy.displayString(to + " was " + message.custom + " by " + from + "!"); - break; - case BECAME_CREATIVE: - TurnBasedMinecraftMod.proxy.displayString(from + " entered creative mode and left battle!"); - break; - case FIRED_ARROW: - TurnBasedMinecraftMod.proxy.displayString(from + " let loose an arrow towards " + to + "!"); - break; - case ARROW_HIT: - TurnBasedMinecraftMod.proxy.displayString(to + " was hit by " + from + "'s arrow!"); - break; - case BOW_NO_AMMO: - TurnBasedMinecraftMod.proxy.displayString(from + " tried to use their bow but ran out of ammo!"); - break; - } - return null; - } + }); + ctx.get().setPacketHandled(true); + } } } diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketBattleRequestInfo.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketBattleRequestInfo.java index 552a3d7..9e2440e 100644 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketBattleRequestInfo.java +++ b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketBattleRequestInfo.java @@ -1,14 +1,15 @@ package com.seodisparate.TurnBasedMinecraft.common.networking; +import java.util.function.Supplier; + import com.seodisparate.TurnBasedMinecraft.common.Battle; import com.seodisparate.TurnBasedMinecraft.common.TurnBasedMinecraftMod; -import io.netty.buffer.ByteBuf; -import net.minecraftforge.fml.common.network.simpleimpl.IMessage; -import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; -import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; +import io.netty.buffer.Unpooled; +import net.minecraft.network.PacketBuffer; +import net.minecraftforge.fml.network.NetworkEvent; -public class PacketBattleRequestInfo implements IMessage +public class PacketBattleRequestInfo { private int battleID; @@ -19,29 +20,24 @@ public class PacketBattleRequestInfo implements IMessage this.battleID = battleID; } - @Override - public void fromBytes(ByteBuf buf) - { - battleID = buf.readInt(); + public static void encode(PacketBattleRequestInfo pkt, PacketBuffer buf) { + buf.writeInt(pkt.battleID); } - - @Override - public void toBytes(ByteBuf buf) - { - buf.writeInt(battleID); + + public static PacketBattleRequestInfo decode(PacketBuffer buf) { + return new PacketBattleRequestInfo(buf.readInt()); } - - public static class HandlerBattleRequestInfo implements IMessageHandler - { - @Override - public PacketBattleInfo onMessage(PacketBattleRequestInfo message, MessageContext ctx) - { - Battle b = TurnBasedMinecraftMod.proxy.getBattleManager().getBattleByID(message.battleID); - if(b == null) - { - return null; - } - return new PacketBattleInfo(b.getSideAIDs(), b.getSideBIDs(), b.getTimerSeconds()); - } + + public static class Handler { + public static void handle(final PacketBattleRequestInfo pkt, Supplier ctx) { + ctx.get().enqueueWork(() -> { + Battle b = TurnBasedMinecraftMod.proxy.getBattleManager().getBattleByID(pkt.battleID); + if(b == null) { + return; + } + TurnBasedMinecraftMod.getHandler().reply(new PacketBattleInfo(b.getSideAIDs(), b.getSideBIDs(), b.getTimerSeconds()), ctx.get()); + }); + ctx.get().setPacketHandled(true); + } } } diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketEditingMessage.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketEditingMessage.java index 621455d..04e0b4e 100644 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketEditingMessage.java +++ b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketEditingMessage.java @@ -2,21 +2,19 @@ package com.seodisparate.TurnBasedMinecraft.common.networking; import com.seodisparate.TurnBasedMinecraft.common.EntityInfo; import com.seodisparate.TurnBasedMinecraft.common.TurnBasedMinecraftMod; -import io.netty.buffer.ByteBuf; +import net.minecraft.network.PacketBuffer; import net.minecraft.util.text.ITextComponent; -import net.minecraft.util.text.TextComponentString; +import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.HoverEvent; -import net.minecraftforge.fml.common.network.ByteBufUtils; -import net.minecraftforge.fml.common.network.simpleimpl.IMessage; -import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; -import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; +import net.minecraftforge.fml.network.NetworkEvent; import java.util.HashMap; import java.util.Map; +import java.util.function.Supplier; -public class PacketEditingMessage implements IMessage +public class PacketEditingMessage { public enum Type { @@ -83,644 +81,636 @@ public class PacketEditingMessage implements IMessage this.entityInfo = entityInfo; } } - - @Override - public void fromBytes(ByteBuf buf) - { - type = Type.valueOf(buf.readInt()); - try - { - entityInfo.classType = getClass().getClassLoader().loadClass(ByteBufUtils.readUTF8String(buf)); - } - catch (ClassNotFoundException e) { /* ignored */ } - entityInfo.ignoreBattle = buf.readBoolean(); - entityInfo.attackPower = buf.readInt(); - entityInfo.attackProbability = buf.readInt(); - entityInfo.attackVariance = buf.readInt(); - entityInfo.attackEffect = EntityInfo.Effect.fromString(ByteBufUtils.readUTF8String(buf)); - entityInfo.attackEffectProbability = buf.readInt(); - entityInfo.defenseDamage = buf.readInt(); - entityInfo.defenseDamageProbability = buf.readInt(); - entityInfo.evasion = buf.readInt(); - entityInfo.speed = buf.readInt(); - entityInfo.category = ByteBufUtils.readUTF8String(buf); - entityInfo.decisionAttack = buf.readInt(); - entityInfo.decisionDefend = buf.readInt(); - entityInfo.decisionFlee = buf.readInt(); - entityInfo.customName = ByteBufUtils.readUTF8String(buf); + + public static void encode(PacketEditingMessage pkt, PacketBuffer buf) { + buf.writeInt(pkt.type.getValue()); + if(pkt.entityInfo.classType != null) { + buf.writeString(pkt.entityInfo.classType.getName()); + } else { + buf.writeString("unknown"); + } + buf.writeBoolean(pkt.entityInfo.ignoreBattle); + buf.writeInt(pkt.entityInfo.attackPower); + buf.writeInt(pkt.entityInfo.attackProbability); + buf.writeInt(pkt.entityInfo.attackVariance); + buf.writeString(pkt.entityInfo.attackEffect.toString()); + buf.writeInt(pkt.entityInfo.attackEffectProbability); + buf.writeInt(pkt.entityInfo.defenseDamage); + buf.writeInt(pkt.entityInfo.defenseDamageProbability); + buf.writeInt(pkt.entityInfo.evasion); + buf.writeInt(pkt.entityInfo.speed); + buf.writeString(pkt.entityInfo.category); + buf.writeInt(pkt.entityInfo.decisionAttack); + buf.writeInt(pkt.entityInfo.decisionDefend); + buf.writeInt(pkt.entityInfo.decisionFlee); + buf.writeString(pkt.entityInfo.customName); } - - @Override - public void toBytes(ByteBuf buf) - { - buf.writeInt(type.getValue()); - if(entityInfo.classType != null) - { - ByteBufUtils.writeUTF8String(buf, entityInfo.classType.getName()); - } - else - { - ByteBufUtils.writeUTF8String(buf, "unknown"); - } - buf.writeBoolean(entityInfo.ignoreBattle); - buf.writeInt(entityInfo.attackPower); - buf.writeInt(entityInfo.attackProbability); - buf.writeInt(entityInfo.attackVariance); - ByteBufUtils.writeUTF8String(buf, entityInfo.attackEffect.toString()); - buf.writeInt(entityInfo.attackEffectProbability); - buf.writeInt(entityInfo.defenseDamage); - buf.writeInt(entityInfo.defenseDamageProbability); - buf.writeInt(entityInfo.evasion); - buf.writeInt(entityInfo.speed); - ByteBufUtils.writeUTF8String(buf, entityInfo.category); - buf.writeInt(entityInfo.decisionAttack); - buf.writeInt(entityInfo.decisionDefend); - buf.writeInt(entityInfo.decisionFlee); - ByteBufUtils.writeUTF8String(buf, entityInfo.customName); + + public static PacketEditingMessage decode(PacketBuffer buf) { + Type type = Type.valueOf(buf.readInt()); + EntityInfo einfo = new EntityInfo(); + try { + einfo.classType = einfo.getClass().getClassLoader().loadClass(buf.readString()); + } catch (ClassNotFoundException e) { /* ignored */ } + einfo.ignoreBattle = buf.readBoolean(); + einfo.attackPower = buf.readInt(); + einfo.attackProbability = buf.readInt(); + einfo.attackVariance = buf.readInt(); + einfo.attackEffect = EntityInfo.Effect.fromString(buf.readString()); + einfo.attackEffectProbability = buf.readInt(); + einfo.defenseDamage = buf.readInt(); + einfo.defenseDamageProbability = buf.readInt(); + einfo.evasion = buf.readInt(); + einfo.speed = buf.readInt(); + einfo.category = buf.readString(); + einfo.decisionAttack = buf.readInt(); + einfo.decisionDefend = buf.readInt(); + einfo.decisionFlee = buf.readInt(); + einfo.customName = buf.readString(); + return new PacketEditingMessage(type, einfo); } - - public static class HandlerEditingMessage implements IMessageHandler - { - @Override - public IMessage onMessage(PacketEditingMessage message, MessageContext ctx) - { - switch(message.type) - { - case ATTACK_ENTITY: - { - ITextComponent prefix = new TextComponentString("TBM: "); - prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); - ITextComponent text = new TextComponentString("Attack the entity you want to edit for TurnBasedMinecraftMod. "); - text.getStyle().setColor(TextFormatting.WHITE).setBold(false); - - ITextComponent cancel = new TextComponentString("Cancel"); - cancel.getStyle().setColor(TextFormatting.RED).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit cancel")); - text.appendSibling(cancel); - - prefix.appendSibling(text); - TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); - break; - } - case PICK_EDIT: - { - ITextComponent prefix = new TextComponentString("TBM: "); - prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); - ITextComponent text = new TextComponentString("Edit what value? "); - text.getStyle().setColor(TextFormatting.WHITE).setBold(false); - - ITextComponent option = new TextComponentString("IgB"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit ignoreBattle")) - .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString("IgnoreBattle"))); - ITextComponent value = new TextComponentString("(" + message.entityInfo.ignoreBattle + ") "); - value.getStyle().setColor(TextFormatting.WHITE); - option.appendSibling(value); - text.appendSibling(option); - - option = new TextComponentString("AP"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackPower")) - .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString("AttackPower"))); - value = new TextComponentString("(" + message.entityInfo.attackPower + ") "); - value.getStyle().setColor(TextFormatting.WHITE); - option.appendSibling(value); - text.appendSibling(option); - - option = new TextComponentString("APr"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackProbability")) - .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString("AttackProbability"))); - value = new TextComponentString("(" + message.entityInfo.attackProbability + "%) "); - value.getStyle().setColor(TextFormatting.WHITE); - option.appendSibling(value); - text.appendSibling(option); - - option = new TextComponentString("AV"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackVariance")) - .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString("AttackVariance"))); - value = new TextComponentString("(" + message.entityInfo.attackVariance + ") "); - value.getStyle().setColor(TextFormatting.WHITE); - option.appendSibling(value); - text.appendSibling(option); - - option = new TextComponentString("AE"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackEffect")) - .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString("AttackEffect"))); - value = new TextComponentString("(" + message.entityInfo.attackEffect.toString() + ") "); - value.getStyle().setColor(TextFormatting.WHITE); - option.appendSibling(value); - text.appendSibling(option); - - option = new TextComponentString("AEPr"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackEffectProbability")) - .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString("AttackEffectProbability"))); - value = new TextComponentString("(" + message.entityInfo.attackEffectProbability + "%) "); - value.getStyle().setColor(TextFormatting.WHITE); - option.appendSibling(value); - text.appendSibling(option); - - option = new TextComponentString("DD"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit defenseDamage")) - .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString("DefenseDamage"))); - value = new TextComponentString("(" + message.entityInfo.defenseDamage + ") "); - value.getStyle().setColor(TextFormatting.WHITE); - option.appendSibling(value); - text.appendSibling(option); - - option = new TextComponentString("DDPr"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit defenseDamageProbability")) - .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString("DefenseDamageProbability"))); - value = new TextComponentString("(" + message.entityInfo.defenseDamageProbability + "%) "); - value.getStyle().setColor(TextFormatting.WHITE); - option.appendSibling(value); - text.appendSibling(option); - - option = new TextComponentString("E"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit evasion")) - .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString("Evasion"))); - value = new TextComponentString("(" + message.entityInfo.evasion + "%) "); - value.getStyle().setColor(TextFormatting.WHITE); - option.appendSibling(value); - text.appendSibling(option); - - option = new TextComponentString("S"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit speed")) - .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString("Speed"))); - value = new TextComponentString("(" + message.entityInfo.speed + ") "); - value.getStyle().setColor(TextFormatting.WHITE); - option.appendSibling(value); - text.appendSibling(option); - - option = new TextComponentString("C"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit category")) - .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString("Category"))); - value = new TextComponentString("(" + message.entityInfo.category + ") "); - value.getStyle().setColor(TextFormatting.WHITE); - option.appendSibling(value); - text.appendSibling(option); - - option = new TextComponentString("DecA"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit decisionAttack")) - .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString("DecisionAttack"))); - value = new TextComponentString("(" + message.entityInfo.decisionAttack + "%) "); - value.getStyle().setColor(TextFormatting.WHITE); - option.appendSibling(value); - text.appendSibling(option); - - option = new TextComponentString("DecD"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit decisionDefend")) - .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString("DecisionDefend"))); - value = new TextComponentString("(" + message.entityInfo.decisionDefend + "%) "); - value.getStyle().setColor(TextFormatting.WHITE); - option.appendSibling(value); - text.appendSibling(option); - - option = new TextComponentString("DecF"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit decisionFlee")) - .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString("DecisionFlee"))); - value = new TextComponentString("(" + message.entityInfo.decisionFlee + "%) "); - value.getStyle().setColor(TextFormatting.WHITE); - option.appendSibling(value); - text.appendSibling(option); - - option = new TextComponentString("Finished Editing"); - option.getStyle().setColor(TextFormatting.GREEN).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit finish")); - text.appendSibling(option).appendText(" "); - - option = new TextComponentString("Cancel"); - option.getStyle().setColor(TextFormatting.RED).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit cancel")); - text.appendSibling(option); - - prefix.appendSibling(text); - TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); - break; - } - case EDIT_IGNORE_BATTLE: - { - ITextComponent prefix = new TextComponentString("TBM: "); - prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); - ITextComponent text = new TextComponentString("ignoreBattle: "); - text.getStyle().setColor(TextFormatting.WHITE).setBold(false); - - ITextComponent option = new TextComponentString("true"); - option.getStyle().setColor(TextFormatting.GREEN).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit ignoreBattle true")); - text.appendSibling(option); - - text.appendText(" "); - - option = new TextComponentString("false"); - option.getStyle().setColor(TextFormatting.RED).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit ignoreBattle false")); - text.appendSibling(option); - - prefix.appendSibling(text); - TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); - break; - } - case EDIT_ATTACK_POWER: - { - ITextComponent prefix = new TextComponentString("TBM: "); - prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); - ITextComponent text = new TextComponentString("attackPower: "); - text.getStyle().setColor(TextFormatting.WHITE).setBold(false); - - for(int i = 0; i <= 15; ++i) + + public static class Handler { + public static void handle(final PacketEditingMessage pkt, Supplier ctx) { + ctx.get().enqueueWork(() -> { + switch(pkt.type) { - ITextComponent option = new TextComponentString(Integer.toString(i)); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackPower " + Integer.toString(i))); + case ATTACK_ENTITY: + { + ITextComponent prefix = new StringTextComponent("TBM: "); + prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); + ITextComponent text = new StringTextComponent("Attack the entity you want to edit for TurnBasedMinecraftMod. "); + text.getStyle().setColor(TextFormatting.WHITE).setBold(false); + + ITextComponent cancel = new StringTextComponent("Cancel"); + cancel.getStyle().setColor(TextFormatting.RED).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit cancel")); + text.appendSibling(cancel); + + prefix.appendSibling(text); + TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); + break; + } + case PICK_EDIT: + { + ITextComponent prefix = new StringTextComponent("TBM: "); + prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); + ITextComponent text = new StringTextComponent("Edit what value? "); + text.getStyle().setColor(TextFormatting.WHITE).setBold(false); + + ITextComponent option = new StringTextComponent("IgB"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit ignoreBattle")) + .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new StringTextComponent("IgnoreBattle"))); + ITextComponent value = new StringTextComponent("(" + pkt.entityInfo.ignoreBattle + ") "); + value.getStyle().setColor(TextFormatting.WHITE); + option.appendSibling(value); text.appendSibling(option); - if(i < 15) - { - text.appendText(", "); - } - } - text.appendText(" (or use command \"/tbm-edit edit attackPower \")"); - - prefix.appendSibling(text); - TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); - break; - } - case EDIT_ATTACK_PROBABILITY: - { - ITextComponent prefix = new TextComponentString("TBM: "); - prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); - ITextComponent text = new TextComponentString("attackProbability: "); - text.getStyle().setColor(TextFormatting.WHITE).setBold(false); - - for(int i = 10; i <= 100; i += 10) - { - ITextComponent option = new TextComponentString(Integer.toString(i) + "%"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackProbability " + Integer.toString(i))); + option = new StringTextComponent("AP"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackPower")) + .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new StringTextComponent("AttackPower"))); + value = new StringTextComponent("(" + pkt.entityInfo.attackPower + ") "); + value.getStyle().setColor(TextFormatting.WHITE); + option.appendSibling(value); text.appendSibling(option); - if(i < 100) - { - text.appendText(", "); - } - } - text.appendText(" (or use command \"/tbm-edit edit attackProbability \")"); - - prefix.appendSibling(text); - TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); - break; - } - case EDIT_ATTACK_VARIANCE: - { - ITextComponent prefix = new TextComponentString("TBM: "); - prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); - ITextComponent text = new TextComponentString("attackVariance: "); - text.getStyle().setColor(TextFormatting.WHITE).setBold(false); - - for(int i = 0; i <= 10; ++i) - { - ITextComponent option = new TextComponentString(Integer.toString(i)); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackVariance " + Integer.toString(i))); + option = new StringTextComponent("APr"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackProbability")) + .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new StringTextComponent("AttackProbability"))); + value = new StringTextComponent("(" + pkt.entityInfo.attackProbability + "%) "); + value.getStyle().setColor(TextFormatting.WHITE); + option.appendSibling(value); text.appendSibling(option); - if(i < 10) - { - text.appendText(", "); - } - } - text.appendText(" (or use command \"/tbm-edit edit attackVariance \")"); - - prefix.appendSibling(text); - TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); - break; - } - case EDIT_ATTACK_EFFECT: - { - ITextComponent prefix = new TextComponentString("TBM: "); - prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); - ITextComponent text = new TextComponentString("attackEffect: "); - text.getStyle().setColor(TextFormatting.WHITE).setBold(false); - - for(EntityInfo.Effect e : EntityInfo.Effect.values()) - { - ITextComponent option = new TextComponentString(e.toString()); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackEffect " + e.toString())); + option = new StringTextComponent("AV"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackVariance")) + .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new StringTextComponent("AttackVariance"))); + value = new StringTextComponent("(" + pkt.entityInfo.attackVariance + ") "); + value.getStyle().setColor(TextFormatting.WHITE); + option.appendSibling(value); text.appendSibling(option); - if(e != EntityInfo.Effect.UNKNOWN) - { - // TODO find a better way to handle printing comma for items before last - text.appendText(", "); - } - } - prefix.appendSibling(text); - TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); - break; - } - case EDIT_ATTACK_EFFECT_PROBABILITY: - { - ITextComponent prefix = new TextComponentString("TBM: "); - prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); - ITextComponent text = new TextComponentString("attackEffectProbability: "); - text.getStyle().setColor(TextFormatting.WHITE).setBold(false); - - for(int i = 0; i <= 100; i += 10) - { - ITextComponent option = new TextComponentString(Integer.toString(i) + "%"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackEffectProbability " + Integer.toString(i))); + option = new StringTextComponent("AE"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackEffect")) + .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new StringTextComponent("AttackEffect"))); + value = new StringTextComponent("(" + pkt.entityInfo.attackEffect.toString() + ") "); + value.getStyle().setColor(TextFormatting.WHITE); + option.appendSibling(value); text.appendSibling(option); - if(i < 100) - { - text.appendText(", "); - } - } - text.appendText(" (or use command \"/tbm-edit edit attackEffectProbability \")"); - - prefix.appendSibling(text); - TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); - break; - } - case EDIT_DEFENSE_DAMAGE: - { - ITextComponent prefix = new TextComponentString("TBM: "); - prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); - ITextComponent text = new TextComponentString("defenseDamage: "); - text.getStyle().setColor(TextFormatting.WHITE).setBold(false); - - for(int i = 0; i <= 15; ++i) - { - ITextComponent option = new TextComponentString(Integer.toString(i)); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit defenseDamage " + Integer.toString(i))); + option = new StringTextComponent("AEPr"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackEffectProbability")) + .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new StringTextComponent("AttackEffectProbability"))); + value = new StringTextComponent("(" + pkt.entityInfo.attackEffectProbability + "%) "); + value.getStyle().setColor(TextFormatting.WHITE); + option.appendSibling(value); text.appendSibling(option); - if(i < 15) - { - text.appendText(", "); - } - } - text.appendText(" (or use command \"/tbm-edit edit defenseDamage \")"); - - prefix.appendSibling(text); - TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); - break; - } - case EDIT_DEFENSE_DAMAGE_PROBABILITY: - { - ITextComponent prefix = new TextComponentString("TBM: "); - prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); - ITextComponent text = new TextComponentString("defenseDamageProbability: "); - text.getStyle().setColor(TextFormatting.WHITE).setBold(false); - - for(int i = 0; i <= 100; i += 10) - { - ITextComponent option = new TextComponentString(Integer.toString(i) + "%"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit defenseDamageProbability " + Integer.toString(i))); + option = new StringTextComponent("DD"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit defenseDamage")) + .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new StringTextComponent("DefenseDamage"))); + value = new StringTextComponent("(" + pkt.entityInfo.defenseDamage + ") "); + value.getStyle().setColor(TextFormatting.WHITE); + option.appendSibling(value); text.appendSibling(option); - if(i < 100) - { - text.appendText(", "); - } - } - text.appendText(" (or use command \"/tbm-edit edit defenseDamageProbability \")"); - - prefix.appendSibling(text); - TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); - break; - } - case EDIT_EVASION: - { - ITextComponent prefix = new TextComponentString("TBM: "); - prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); - ITextComponent text = new TextComponentString("evasion: "); - text.getStyle().setColor(TextFormatting.WHITE).setBold(false); - - for(int i = 0; i <= 100; i += 10) - { - ITextComponent option = new TextComponentString(Integer.toString(i) + "%"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit evasion " + Integer.toString(i))); + option = new StringTextComponent("DDPr"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit defenseDamageProbability")) + .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new StringTextComponent("DefenseDamageProbability"))); + value = new StringTextComponent("(" + pkt.entityInfo.defenseDamageProbability + "%) "); + value.getStyle().setColor(TextFormatting.WHITE); + option.appendSibling(value); text.appendSibling(option); - if(i < 100) - { - text.appendText(", "); - } - } - text.appendText(" (or use command \"/tbm-edit edit evasion \")"); - - prefix.appendSibling(text); - TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); - break; - } - case EDIT_SPEED: - { - ITextComponent prefix = new TextComponentString("TBM: "); - prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); - ITextComponent text = new TextComponentString("speed: "); - text.getStyle().setColor(TextFormatting.WHITE).setBold(false); - - for(int i = 0; i <= 100; i += 10) - { - ITextComponent option = new TextComponentString(Integer.toString(i)); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit speed " + Integer.toString(i))); + option = new StringTextComponent("E"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit evasion")) + .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new StringTextComponent("Evasion"))); + value = new StringTextComponent("(" + pkt.entityInfo.evasion + "%) "); + value.getStyle().setColor(TextFormatting.WHITE); + option.appendSibling(value); text.appendSibling(option); - if(i < 100) - { - text.appendText(", "); - } - } - text.appendText(" (or use command \"/tbm-edit edit speed \")"); - - prefix.appendSibling(text); - TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); - break; - } - case EDIT_CATEGORY: - { - ITextComponent prefix = new TextComponentString("TBM: "); - prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); - ITextComponent text = new TextComponentString("category: "); - text.getStyle().setColor(TextFormatting.WHITE).setBold(false); - - ITextComponent option = new TextComponentString("monster"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit category monster")); - if(TurnBasedMinecraftMod.proxy.getConfig().isIgnoreBattleType("monster")) - { - ITextComponent optionInfo = new TextComponentString("(battle-"); - optionInfo.getStyle().setColor(TextFormatting.WHITE); - ITextComponent optionInfoBool = new TextComponentString("disabled"); - optionInfoBool.getStyle().setColor(TextFormatting.RED); - optionInfo.appendSibling(optionInfoBool).appendText(")"); - option.appendSibling(optionInfo); - } - else - { - ITextComponent optionInfo = new TextComponentString("(battle-"); - optionInfo.getStyle().setColor(TextFormatting.WHITE); - ITextComponent optionInfoBool = new TextComponentString("enabled"); - optionInfoBool.getStyle().setColor(TextFormatting.GREEN); - optionInfo.appendSibling(optionInfoBool).appendText(")"); - option.appendSibling(optionInfo); - } - text.appendSibling(option).appendText(", "); - - option = new TextComponentString("animal"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit category animal")); - if(TurnBasedMinecraftMod.proxy.getConfig().isIgnoreBattleType("animal")) - { - ITextComponent optionInfo = new TextComponentString("(battle-"); - optionInfo.getStyle().setColor(TextFormatting.WHITE); - ITextComponent optionInfoBool = new TextComponentString("disabled"); - optionInfoBool.getStyle().setColor(TextFormatting.RED); - optionInfo.appendSibling(optionInfoBool).appendText(")"); - option.appendSibling(optionInfo); - } - else - { - ITextComponent optionInfo = new TextComponentString("(battle-"); - optionInfo.getStyle().setColor(TextFormatting.WHITE); - ITextComponent optionInfoBool = new TextComponentString("enabled"); - optionInfoBool.getStyle().setColor(TextFormatting.GREEN); - optionInfo.appendSibling(optionInfoBool).appendText(")"); - option.appendSibling(optionInfo); - } - text.appendSibling(option).appendText(", "); - - option = new TextComponentString("passive"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit category passive")); - if(TurnBasedMinecraftMod.proxy.getConfig().isIgnoreBattleType("passive")) - { - ITextComponent optionInfo = new TextComponentString("(battle-"); - optionInfo.getStyle().setColor(TextFormatting.WHITE); - ITextComponent optionInfoBool = new TextComponentString("disabled"); - optionInfoBool.getStyle().setColor(TextFormatting.RED); - optionInfo.appendSibling(optionInfoBool).appendText(")"); - option.appendSibling(optionInfo); - } - else - { - ITextComponent optionInfo = new TextComponentString("(battle-"); - optionInfo.getStyle().setColor(TextFormatting.WHITE); - ITextComponent optionInfoBool = new TextComponentString("enabled"); - optionInfoBool.getStyle().setColor(TextFormatting.GREEN); - optionInfo.appendSibling(optionInfoBool).appendText(")"); - option.appendSibling(optionInfo); - } - text.appendSibling(option).appendText(", "); - - option = new TextComponentString("boss"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit category boss")); - if(TurnBasedMinecraftMod.proxy.getConfig().isIgnoreBattleType("boss")) - { - ITextComponent optionInfo = new TextComponentString("(battle-"); - optionInfo.getStyle().setColor(TextFormatting.WHITE); - ITextComponent optionInfoBool = new TextComponentString("disabled"); - optionInfoBool.getStyle().setColor(TextFormatting.RED); - optionInfo.appendSibling(optionInfoBool).appendText(")"); - option.appendSibling(optionInfo); - } - else - { - ITextComponent optionInfo = new TextComponentString("(battle-"); - optionInfo.getStyle().setColor(TextFormatting.WHITE); - ITextComponent optionInfoBool = new TextComponentString("enabled"); - optionInfoBool.getStyle().setColor(TextFormatting.GREEN); - optionInfo.appendSibling(optionInfoBool).appendText(")"); - option.appendSibling(optionInfo); - } - text.appendSibling(option).appendText(", "); - - option = new TextComponentString("player"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit category player")); - if(TurnBasedMinecraftMod.proxy.getConfig().isIgnoreBattleType("player")) - { - ITextComponent optionInfo = new TextComponentString("(battle-"); - optionInfo.getStyle().setColor(TextFormatting.WHITE); - ITextComponent optionInfoBool = new TextComponentString("disabled"); - optionInfoBool.getStyle().setColor(TextFormatting.RED); - optionInfo.appendSibling(optionInfoBool).appendText(")"); - option.appendSibling(optionInfo); - } - else - { - ITextComponent optionInfo = new TextComponentString("(battle-"); - optionInfo.getStyle().setColor(TextFormatting.WHITE); - ITextComponent optionInfoBool = new TextComponentString("enabled"); - optionInfoBool.getStyle().setColor(TextFormatting.GREEN); - optionInfo.appendSibling(optionInfoBool).appendText(")"); - option.appendSibling(optionInfo); - } - text.appendSibling(option); - - text.appendText(" (or use command \"/tbm-edit edit category \")"); - - prefix.appendSibling(text); - TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); - break; - } - case EDIT_DECISION_ATTACK: - { - ITextComponent prefix = new TextComponentString("TBM: "); - prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); - ITextComponent text = new TextComponentString("decisionAttack: "); - text.getStyle().setColor(TextFormatting.WHITE).setBold(false); - - for(int i = 0; i <= 100; i += 10) - { - ITextComponent option = new TextComponentString(Integer.toString(i) + "%"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit decisionAttack " + Integer.toString(i))); + option = new StringTextComponent("S"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit speed")) + .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new StringTextComponent("Speed"))); + value = new StringTextComponent("(" + pkt.entityInfo.speed + ") "); + value.getStyle().setColor(TextFormatting.WHITE); + option.appendSibling(value); text.appendSibling(option); - if(i < 100) - { - text.appendText(", "); - } - } - prefix.appendSibling(text); - TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); - break; - } - case EDIT_DECISION_DEFEND: - { - ITextComponent prefix = new TextComponentString("TBM: "); - prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); - ITextComponent text = new TextComponentString("decisionDefend: "); - text.getStyle().setColor(TextFormatting.WHITE).setBold(false); - - for(int i = 0; i <= 100; i += 10) - { - ITextComponent option = new TextComponentString(Integer.toString(i) + "%"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit decisionDefend " + Integer.toString(i))); + option = new StringTextComponent("C"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit category")) + .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new StringTextComponent("Category"))); + value = new StringTextComponent("(" + pkt.entityInfo.category + ") "); + value.getStyle().setColor(TextFormatting.WHITE); + option.appendSibling(value); text.appendSibling(option); - if(i < 100) - { - text.appendText(", "); - } - } - prefix.appendSibling(text); - TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); - break; - } - case EDIT_DECISION_FLEE: - { - ITextComponent prefix = new TextComponentString("TBM: "); - prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); - ITextComponent text = new TextComponentString("decisionFlee: "); - text.getStyle().setColor(TextFormatting.WHITE).setBold(false); - - for(int i = 0; i <= 100; i += 10) - { - ITextComponent option = new TextComponentString(Integer.toString(i) + "%"); - option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit decisionFlee " + Integer.toString(i))); + option = new StringTextComponent("DecA"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit decisionAttack")) + .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new StringTextComponent("DecisionAttack"))); + value = new StringTextComponent("(" + pkt.entityInfo.decisionAttack + "%) "); + value.getStyle().setColor(TextFormatting.WHITE); + option.appendSibling(value); text.appendSibling(option); - if(i < 100) - { - text.appendText(", "); - } - } - prefix.appendSibling(text); - TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); - break; - } - default: - break; - } - return null; - } + option = new StringTextComponent("DecD"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit decisionDefend")) + .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new StringTextComponent("DecisionDefend"))); + value = new StringTextComponent("(" + pkt.entityInfo.decisionDefend + "%) "); + value.getStyle().setColor(TextFormatting.WHITE); + option.appendSibling(value); + text.appendSibling(option); + + option = new StringTextComponent("DecF"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit decisionFlee")) + .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new StringTextComponent("DecisionFlee"))); + value = new StringTextComponent("(" + pkt.entityInfo.decisionFlee + "%) "); + value.getStyle().setColor(TextFormatting.WHITE); + option.appendSibling(value); + text.appendSibling(option); + + option = new StringTextComponent("Finished Editing"); + option.getStyle().setColor(TextFormatting.GREEN).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit finish")); + text.appendSibling(option).appendText(" "); + + option = new StringTextComponent("Cancel"); + option.getStyle().setColor(TextFormatting.RED).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit cancel")); + text.appendSibling(option); + + prefix.appendSibling(text); + TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); + break; + } + case EDIT_IGNORE_BATTLE: + { + ITextComponent prefix = new StringTextComponent("TBM: "); + prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); + ITextComponent text = new StringTextComponent("ignoreBattle: "); + text.getStyle().setColor(TextFormatting.WHITE).setBold(false); + + ITextComponent option = new StringTextComponent("true"); + option.getStyle().setColor(TextFormatting.GREEN).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit ignoreBattle true")); + text.appendSibling(option); + + text.appendText(" "); + + option = new StringTextComponent("false"); + option.getStyle().setColor(TextFormatting.RED).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit ignoreBattle false")); + text.appendSibling(option); + + prefix.appendSibling(text); + TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); + break; + } + case EDIT_ATTACK_POWER: + { + ITextComponent prefix = new StringTextComponent("TBM: "); + prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); + ITextComponent text = new StringTextComponent("attackPower: "); + text.getStyle().setColor(TextFormatting.WHITE).setBold(false); + + for(int i = 0; i <= 15; ++i) + { + ITextComponent option = new StringTextComponent(Integer.toString(i)); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackPower " + Integer.toString(i))); + text.appendSibling(option); + if(i < 15) + { + text.appendText(", "); + } + } + + text.appendText(" (or use command \"/tbm-edit edit attackPower \")"); + + prefix.appendSibling(text); + TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); + break; + } + case EDIT_ATTACK_PROBABILITY: + { + ITextComponent prefix = new StringTextComponent("TBM: "); + prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); + ITextComponent text = new StringTextComponent("attackProbability: "); + text.getStyle().setColor(TextFormatting.WHITE).setBold(false); + + for(int i = 10; i <= 100; i += 10) + { + ITextComponent option = new StringTextComponent(Integer.toString(i) + "%"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackProbability " + Integer.toString(i))); + text.appendSibling(option); + if(i < 100) + { + text.appendText(", "); + } + } + + text.appendText(" (or use command \"/tbm-edit edit attackProbability \")"); + + prefix.appendSibling(text); + TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); + break; + } + case EDIT_ATTACK_VARIANCE: + { + ITextComponent prefix = new StringTextComponent("TBM: "); + prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); + ITextComponent text = new StringTextComponent("attackVariance: "); + text.getStyle().setColor(TextFormatting.WHITE).setBold(false); + + for(int i = 0; i <= 10; ++i) + { + ITextComponent option = new StringTextComponent(Integer.toString(i)); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackVariance " + Integer.toString(i))); + text.appendSibling(option); + if(i < 10) + { + text.appendText(", "); + } + } + + text.appendText(" (or use command \"/tbm-edit edit attackVariance \")"); + + prefix.appendSibling(text); + TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); + break; + } + case EDIT_ATTACK_EFFECT: + { + ITextComponent prefix = new StringTextComponent("TBM: "); + prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); + ITextComponent text = new StringTextComponent("attackEffect: "); + text.getStyle().setColor(TextFormatting.WHITE).setBold(false); + + for(EntityInfo.Effect e : EntityInfo.Effect.values()) + { + ITextComponent option = new StringTextComponent(e.toString()); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackEffect " + e.toString())); + text.appendSibling(option); + if(e != EntityInfo.Effect.UNKNOWN) + { + // TODO find a better way to handle printing comma for items before last + text.appendText(", "); + } + } + + prefix.appendSibling(text); + TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); + break; + } + case EDIT_ATTACK_EFFECT_PROBABILITY: + { + ITextComponent prefix = new StringTextComponent("TBM: "); + prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); + ITextComponent text = new StringTextComponent("attackEffectProbability: "); + text.getStyle().setColor(TextFormatting.WHITE).setBold(false); + + for(int i = 0; i <= 100; i += 10) + { + ITextComponent option = new StringTextComponent(Integer.toString(i) + "%"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit attackEffectProbability " + Integer.toString(i))); + text.appendSibling(option); + if(i < 100) + { + text.appendText(", "); + } + } + + text.appendText(" (or use command \"/tbm-edit edit attackEffectProbability \")"); + + prefix.appendSibling(text); + TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); + break; + } + case EDIT_DEFENSE_DAMAGE: + { + ITextComponent prefix = new StringTextComponent("TBM: "); + prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); + ITextComponent text = new StringTextComponent("defenseDamage: "); + text.getStyle().setColor(TextFormatting.WHITE).setBold(false); + + for(int i = 0; i <= 15; ++i) + { + ITextComponent option = new StringTextComponent(Integer.toString(i)); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit defenseDamage " + Integer.toString(i))); + text.appendSibling(option); + if(i < 15) + { + text.appendText(", "); + } + } + + text.appendText(" (or use command \"/tbm-edit edit defenseDamage \")"); + + prefix.appendSibling(text); + TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); + break; + } + case EDIT_DEFENSE_DAMAGE_PROBABILITY: + { + ITextComponent prefix = new StringTextComponent("TBM: "); + prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); + ITextComponent text = new StringTextComponent("defenseDamageProbability: "); + text.getStyle().setColor(TextFormatting.WHITE).setBold(false); + + for(int i = 0; i <= 100; i += 10) + { + ITextComponent option = new StringTextComponent(Integer.toString(i) + "%"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit defenseDamageProbability " + Integer.toString(i))); + text.appendSibling(option); + if(i < 100) + { + text.appendText(", "); + } + } + + text.appendText(" (or use command \"/tbm-edit edit defenseDamageProbability \")"); + + prefix.appendSibling(text); + TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); + break; + } + case EDIT_EVASION: + { + ITextComponent prefix = new StringTextComponent("TBM: "); + prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); + ITextComponent text = new StringTextComponent("evasion: "); + text.getStyle().setColor(TextFormatting.WHITE).setBold(false); + + for(int i = 0; i <= 100; i += 10) + { + ITextComponent option = new StringTextComponent(Integer.toString(i) + "%"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit evasion " + Integer.toString(i))); + text.appendSibling(option); + if(i < 100) + { + text.appendText(", "); + } + } + + text.appendText(" (or use command \"/tbm-edit edit evasion \")"); + + prefix.appendSibling(text); + TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); + break; + } + case EDIT_SPEED: + { + ITextComponent prefix = new StringTextComponent("TBM: "); + prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); + ITextComponent text = new StringTextComponent("speed: "); + text.getStyle().setColor(TextFormatting.WHITE).setBold(false); + + for(int i = 0; i <= 100; i += 10) + { + ITextComponent option = new StringTextComponent(Integer.toString(i)); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit speed " + Integer.toString(i))); + text.appendSibling(option); + if(i < 100) + { + text.appendText(", "); + } + } + + text.appendText(" (or use command \"/tbm-edit edit speed \")"); + + prefix.appendSibling(text); + TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); + break; + } + case EDIT_CATEGORY: + { + ITextComponent prefix = new StringTextComponent("TBM: "); + prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); + ITextComponent text = new StringTextComponent("category: "); + text.getStyle().setColor(TextFormatting.WHITE).setBold(false); + + ITextComponent option = new StringTextComponent("monster"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit category monster")); + if(TurnBasedMinecraftMod.proxy.getConfig().isIgnoreBattleType("monster")) + { + ITextComponent optionInfo = new StringTextComponent("(battle-"); + optionInfo.getStyle().setColor(TextFormatting.WHITE); + ITextComponent optionInfoBool = new StringTextComponent("disabled"); + optionInfoBool.getStyle().setColor(TextFormatting.RED); + optionInfo.appendSibling(optionInfoBool).appendText(")"); + option.appendSibling(optionInfo); + } + else + { + ITextComponent optionInfo = new StringTextComponent("(battle-"); + optionInfo.getStyle().setColor(TextFormatting.WHITE); + ITextComponent optionInfoBool = new StringTextComponent("enabled"); + optionInfoBool.getStyle().setColor(TextFormatting.GREEN); + optionInfo.appendSibling(optionInfoBool).appendText(")"); + option.appendSibling(optionInfo); + } + text.appendSibling(option).appendText(", "); + + option = new StringTextComponent("animal"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit category animal")); + if(TurnBasedMinecraftMod.proxy.getConfig().isIgnoreBattleType("animal")) + { + ITextComponent optionInfo = new StringTextComponent("(battle-"); + optionInfo.getStyle().setColor(TextFormatting.WHITE); + ITextComponent optionInfoBool = new StringTextComponent("disabled"); + optionInfoBool.getStyle().setColor(TextFormatting.RED); + optionInfo.appendSibling(optionInfoBool).appendText(")"); + option.appendSibling(optionInfo); + } + else + { + ITextComponent optionInfo = new StringTextComponent("(battle-"); + optionInfo.getStyle().setColor(TextFormatting.WHITE); + ITextComponent optionInfoBool = new StringTextComponent("enabled"); + optionInfoBool.getStyle().setColor(TextFormatting.GREEN); + optionInfo.appendSibling(optionInfoBool).appendText(")"); + option.appendSibling(optionInfo); + } + text.appendSibling(option).appendText(", "); + + option = new StringTextComponent("passive"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit category passive")); + if(TurnBasedMinecraftMod.proxy.getConfig().isIgnoreBattleType("passive")) + { + ITextComponent optionInfo = new StringTextComponent("(battle-"); + optionInfo.getStyle().setColor(TextFormatting.WHITE); + ITextComponent optionInfoBool = new StringTextComponent("disabled"); + optionInfoBool.getStyle().setColor(TextFormatting.RED); + optionInfo.appendSibling(optionInfoBool).appendText(")"); + option.appendSibling(optionInfo); + } + else + { + ITextComponent optionInfo = new StringTextComponent("(battle-"); + optionInfo.getStyle().setColor(TextFormatting.WHITE); + ITextComponent optionInfoBool = new StringTextComponent("enabled"); + optionInfoBool.getStyle().setColor(TextFormatting.GREEN); + optionInfo.appendSibling(optionInfoBool).appendText(")"); + option.appendSibling(optionInfo); + } + text.appendSibling(option).appendText(", "); + + option = new StringTextComponent("boss"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit category boss")); + if(TurnBasedMinecraftMod.proxy.getConfig().isIgnoreBattleType("boss")) + { + ITextComponent optionInfo = new StringTextComponent("(battle-"); + optionInfo.getStyle().setColor(TextFormatting.WHITE); + ITextComponent optionInfoBool = new StringTextComponent("disabled"); + optionInfoBool.getStyle().setColor(TextFormatting.RED); + optionInfo.appendSibling(optionInfoBool).appendText(")"); + option.appendSibling(optionInfo); + } + else + { + ITextComponent optionInfo = new StringTextComponent("(battle-"); + optionInfo.getStyle().setColor(TextFormatting.WHITE); + ITextComponent optionInfoBool = new StringTextComponent("enabled"); + optionInfoBool.getStyle().setColor(TextFormatting.GREEN); + optionInfo.appendSibling(optionInfoBool).appendText(")"); + option.appendSibling(optionInfo); + } + text.appendSibling(option).appendText(", "); + + option = new StringTextComponent("player"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit category player")); + if(TurnBasedMinecraftMod.proxy.getConfig().isIgnoreBattleType("player")) + { + ITextComponent optionInfo = new StringTextComponent("(battle-"); + optionInfo.getStyle().setColor(TextFormatting.WHITE); + ITextComponent optionInfoBool = new StringTextComponent("disabled"); + optionInfoBool.getStyle().setColor(TextFormatting.RED); + optionInfo.appendSibling(optionInfoBool).appendText(")"); + option.appendSibling(optionInfo); + } + else + { + ITextComponent optionInfo = new StringTextComponent("(battle-"); + optionInfo.getStyle().setColor(TextFormatting.WHITE); + ITextComponent optionInfoBool = new StringTextComponent("enabled"); + optionInfoBool.getStyle().setColor(TextFormatting.GREEN); + optionInfo.appendSibling(optionInfoBool).appendText(")"); + option.appendSibling(optionInfo); + } + text.appendSibling(option); + + text.appendText(" (or use command \"/tbm-edit edit category \")"); + + prefix.appendSibling(text); + TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); + break; + } + case EDIT_DECISION_ATTACK: + { + ITextComponent prefix = new StringTextComponent("TBM: "); + prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); + ITextComponent text = new StringTextComponent("decisionAttack: "); + text.getStyle().setColor(TextFormatting.WHITE).setBold(false); + + for(int i = 0; i <= 100; i += 10) + { + ITextComponent option = new StringTextComponent(Integer.toString(i) + "%"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit decisionAttack " + Integer.toString(i))); + text.appendSibling(option); + if(i < 100) + { + text.appendText(", "); + } + } + + prefix.appendSibling(text); + TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); + break; + } + case EDIT_DECISION_DEFEND: + { + ITextComponent prefix = new StringTextComponent("TBM: "); + prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); + ITextComponent text = new StringTextComponent("decisionDefend: "); + text.getStyle().setColor(TextFormatting.WHITE).setBold(false); + + for(int i = 0; i <= 100; i += 10) + { + ITextComponent option = new StringTextComponent(Integer.toString(i) + "%"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit decisionDefend " + Integer.toString(i))); + text.appendSibling(option); + if(i < 100) + { + text.appendText(", "); + } + } + + prefix.appendSibling(text); + TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); + break; + } + case EDIT_DECISION_FLEE: + { + ITextComponent prefix = new StringTextComponent("TBM: "); + prefix.getStyle().setColor(TextFormatting.GREEN).setBold(true); + ITextComponent text = new StringTextComponent("decisionFlee: "); + text.getStyle().setColor(TextFormatting.WHITE).setBold(false); + + for(int i = 0; i <= 100; i += 10) + { + ITextComponent option = new StringTextComponent(Integer.toString(i) + "%"); + option.getStyle().setColor(TextFormatting.YELLOW).setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/tbm-edit edit decisionFlee " + Integer.toString(i))); + text.appendSibling(option); + if(i < 100) + { + text.appendText(", "); + } + } + + prefix.appendSibling(text); + TurnBasedMinecraftMod.proxy.displayTextComponent(prefix); + break; + } + default: + break; + } + }); + ctx.get().setPacketHandled(true); + } } } diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketGeneralMessage.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketGeneralMessage.java index a731a2a..b49dac8 100644 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketGeneralMessage.java +++ b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketGeneralMessage.java @@ -1,14 +1,13 @@ package com.seodisparate.TurnBasedMinecraft.common.networking; +import java.util.function.Supplier; + import com.seodisparate.TurnBasedMinecraft.common.TurnBasedMinecraftMod; -import io.netty.buffer.ByteBuf; -import net.minecraftforge.fml.common.network.ByteBufUtils; -import net.minecraftforge.fml.common.network.simpleimpl.IMessage; -import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; -import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; +import net.minecraft.network.PacketBuffer; +import net.minecraftforge.fml.network.NetworkEvent; -public class PacketGeneralMessage implements IMessage +public class PacketGeneralMessage { String message; @@ -21,26 +20,21 @@ public class PacketGeneralMessage implements IMessage { this.message = message; } - - @Override - public void fromBytes(ByteBuf buf) - { - message = ByteBufUtils.readUTF8String(buf); + + public static void encode(PacketGeneralMessage pkt, PacketBuffer buf) { + buf.writeString(pkt.message); } - - @Override - public void toBytes(ByteBuf buf) - { - ByteBufUtils.writeUTF8String(buf, message); + + public static PacketGeneralMessage decode(PacketBuffer buf) { + return new PacketGeneralMessage(buf.readString()); } - - public static class HandlerGeneralMessage implements IMessageHandler - { - @Override - public IMessage onMessage(PacketGeneralMessage message, MessageContext ctx) - { - TurnBasedMinecraftMod.proxy.displayString(message.message); - return null; - } + + public static class Handler { + public static void handle(final PacketGeneralMessage pkt, Supplier ctx) { + ctx.get().enqueueWork(() -> { + TurnBasedMinecraftMod.proxy.displayString(pkt.message); + }); + ctx.get().setPacketHandled(true); + } } } diff --git a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketHandler.java b/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketHandler.java deleted file mode 100644 index f320a71..0000000 --- a/src/main/java/com/seodisparate/TurnBasedMinecraft/common/networking/PacketHandler.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.seodisparate.TurnBasedMinecraft.common.networking; - -import com.seodisparate.TurnBasedMinecraft.common.TurnBasedMinecraftMod; - -import net.minecraftforge.fml.common.network.NetworkRegistry; -import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; - -public class PacketHandler -{ - public static final SimpleNetworkWrapper INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel(TurnBasedMinecraftMod.MODID); -} diff --git a/libs/javamp3-1.0.3.jar b/src/main/resources/META-INF/libraries/javamp3-1.0.3.jar similarity index 100% rename from libs/javamp3-1.0.3.jar rename to src/main/resources/META-INF/libraries/javamp3-1.0.3.jar diff --git a/src/main/resources/META-INF/libraries/javamp3-1.0.3.jar.meta b/src/main/resources/META-INF/libraries/javamp3-1.0.3.jar.meta new file mode 100644 index 0000000..482c01f --- /dev/null +++ b/src/main/resources/META-INF/libraries/javamp3-1.0.3.jar.meta @@ -0,0 +1 @@ +Maven-Artifact: fr.delthas:javamp3:1.0.3 diff --git a/src/main/resources/assets/TurnBasedMinecraft/TBM_Config.toml b/src/main/resources/assets/TurnBasedMinecraft/TBM_Config.toml index 4ef75d5..b890aef 100644 --- a/src/main/resources/assets/TurnBasedMinecraft/TBM_Config.toml +++ b/src/main/resources/assets/TurnBasedMinecraft/TBM_Config.toml @@ -1,12 +1,12 @@ # Please do not change this option, the mod uses this to keep track of what new # changes to add to the config. -version = 1 +version = 2 [client_config] -# determines what categories use what type of music. -# Unknown categories sent by the server will default to "battle_music". +# What categories play this type of music (battle_music). Unknown categories will default to this type. battle_music = ["monster", "animal", "boss", "player"] +# What categories play this type of music (silly_music). silly_music = ["passive"] # Minimum percentage of silly entities in battle to use silly music. @@ -41,19 +41,23 @@ freeze_battle_combatants = false # Entity categories that will not initiate battle. ignore_battle_types = ["passive", "boss"] -# Stats that apply to all players +# speed stat of all players in battle player_speed = 50 +# speed stat of all players under the effects of haste player_haste_speed = 80 +# speed stat of all players under the effects of slow player_slow_speed = 20 +# attack probability stat for all players player_attack_probability = 90 +# evasion stat for all players player_evasion = 10 # Number of attacks that a "defend" move will block defense_duration = 1 -# If speed is greater than fastest speed of entity on opposing side, good -# probability is used. +# probability of fleeing from battle when speed is greater than fastest enemy's speed flee_good_probability = 90 +# probability of fleeing from battle when speed is less than fastest enemy's speed flee_bad_probability = 40 # Minimum hit percentage for everyone. If option is set to less than 1,