# Upcoming changes
+Make it possible to open the client-config from the Mod-list GUI.
+
+Port to NeoForge 21.1.69 (Minecraft 1.21.1).
+
Fix volume handling of battle/silly music. (Previous implementation did not
properly reduce volume based on Minecraft's "music volume" setting.)
Simply invoke `./gradlew build` in the mod directory and after some time the
finished jar will be saved at
-`build/libs/TurnBasedMinecraft-NeoForge-1.26.0-all.jar`
+`build/libs/TurnBasedMinecraft-NeoForge-1.27.0-all.jar`
# Reproducibility
plugins {
- id 'eclipse'
- id 'idea'
+ id 'java-library'
id 'maven-publish'
- id 'net.neoforged.gradle.userdev' version '7.0.80'
+ id 'net.neoforged.moddev' version '1.0.20'
+}
+
+tasks.named('wrapper', Wrapper).configure {
+ // Define wrapper values here so as to not have to always do so when updating gradlew.properties.
+ // Switching this to Wrapper.DistributionType.ALL will download the full gradle sources that comes with
+ // documentation attached on cursor hover of gradle classes and methods. However, this comes with increased
+ // file size for Gradle. If you do switch this to ALL, run the Gradle wrapper task twice afterwards.
+ // (Verify by checking gradle/wrapper/gradle-wrapper.properties to see if distributionUrl now points to `-all`)
+ distributionType = Wrapper.DistributionType.BIN
}
version = mod_version
group = mod_group_id
-archivesBaseName = "TurnBasedMinecraft-NeoForge"
-java.toolchain.languageVersion = JavaLanguageVersion.of(17)
-println('Java: ' + System.getProperty('java.version') + ' JVM: ' + System.getProperty('java.vm.version') + '(' + System.getProperty('java.vendor') + ') Arch: ' + System.getProperty('os.arch'))
+repositories {
+ mavenLocal()
-jarJar.enable()
-
-// Default run configurations.
-// These can be tweaked, removed, or duplicated as needed.
-runs {
- // applies to all the run configs below
- configureEach {
- // Recommended logging data for a userdev environment
- // The markers can be added/remove as needed separated by commas.
- // "SCAN": For mods scan.
- // "REGISTRIES": For firing of registry events.
- // "REGISTRYDUMP": For getting the contents of all registries.
- systemProperty 'forge.logging.markers', 'REGISTRIES'
-
- // Recommended logging level for the console
- // You can set various levels here.
- // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
- systemProperty 'forge.logging.console.level', 'debug'
-
- modSource project.sourceSets.main
+ flatDir {
+ dir 'libs'
}
+}
- client {
- // Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
- systemProperty 'forge.enabledGameTestNamespaces', project.mod_id
- }
+base {
+ archivesName = "TurnBasedMinecraft-NeoForge"
+}
- server {
- systemProperty 'forge.enabledGameTestNamespaces', project.mod_id
- programArgument '--nogui'
- }
+// Mojang ships Java 21 to end users starting in 1.20.5, so mods should target Java 21.
+java.toolchain.languageVersion = JavaLanguageVersion.of(21)
+println('Java: ' + System.getProperty('java.version') + ' JVM: ' + System.getProperty('java.vm.version') + '(' + System.getProperty('java.vendor') + ') Arch: ' + System.getProperty('os.arch'))
- // This run config launches GameTestServer and runs all registered gametests, then exits.
- // By default, the server will crash when no gametests are provided.
- // The gametest system is also enabled by default for other run configs under the /test command.
- gameTestServer {
- systemProperty 'forge.enabledGameTestNamespaces', project.mod_id
+neoForge {
+ // Specify the version of NeoForge to use.
+ version = project.neo_version
+
+ parchment {
+ mappingsVersion = project.parchment_mappings_version
+ minecraftVersion = project.parchment_minecraft_version
}
- data {
- // example of overriding the workingDirectory set in configureEach above, uncomment if you want to use it
- // workingDirectory project.file('run-data')
+ // This line is optional. Access Transformers are automatically detected
+ // accessTransformers = project.files('src/main/resources/META-INF/accesstransformer.cfg')
+
+ // Default run configurations.
+ // These can be tweaked, removed, or duplicated as needed.
+ runs {
+ client {
+ client()
+
+ // Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
+ systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id
+ }
+
+ server {
+ server()
+ programArgument '--nogui'
+ systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id
+ }
+
+ // This run config launches GameTestServer and runs all registered gametests, then exits.
+ // By default, the server will crash when no gametests are provided.
+ // The gametest system is also enabled by default for other run configs under the /test command.
+ gameTestServer {
+ type = "gameTestServer"
+ systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id
+ }
+
+ data {
+ data()
+
+ // example of overriding the workingDirectory set in configureEach above, uncomment if you want to use it
+ // gameDirectory = project.file('run-data')
+
+ // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
+ programArguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath()
+ }
+
+ // applies to all the run configs above
+ configureEach {
+ // Recommended logging data for a userdev environment
+ // The markers can be added/remove as needed separated by commas.
+ // "SCAN": For mods scan.
+ // "REGISTRIES": For firing of registry events.
+ // "REGISTRYDUMP": For getting the contents of all registries.
+ systemProperty 'forge.logging.markers', 'REGISTRIES'
+
+ // Recommended logging level for the console
+ // You can set various levels here.
+ // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
+ logLevel = org.slf4j.event.Level.DEBUG
+ }
+ }
- // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
- programArguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath()
+ mods {
+ // define mod <-> source bindings
+ // these are used to tell the game which sources are for which mod
+ // mostly optional in a single mod project
+ // but multi mod projects should define one per mod
+ "${mod_id}" {
+ sourceSet(sourceSets.main)
+ }
}
}
// Include resources generated by data generators.
sourceSets.main.resources { srcDir 'src/generated/resources' }
-repositories {
- flatDir {
- dir 'libs'
- }
+// Sets up a dependency configuration called 'localRuntime'.
+// This configuration should be used instead of 'runtimeOnly' to declare
+// a dependency that will be present for runtime testing but that is
+// "optional", meaning it will not be pulled by dependents of this mod.
+configurations {
+ runtimeClasspath.extendsFrom localRuntime
}
dependencies {
- // Specify the version of Minecraft to use.
- // Depending on the plugin applied there are several options. We will assume you applied the userdev plugin as shown above.
- // The group for userdev is net.neoforged, the module name is neoforge, and the version is the same as the neoforge version.
- // You can however also use the vanilla plugin (net.neoforged.gradle.vanilla) to use a version of Minecraft without the neoforge loader.
- // And its provides the option to then use net.minecraft as the group, and one of; client, server or joined as the module name, plus the game version as version.
- // For all intends and purposes: You can treat this dependency as if it is a normal library you would use.
- implementation "net.neoforged:neoforge:${neo_version}"
+ // Example optional mod dependency with JEI
+ // The JEI API is declared for compile time use, while the full JEI artifact is used at runtime
+ // compileOnly "mezz.jei:jei-${mc_version}-common-api:${jei_version}"
+ // compileOnly "mezz.jei:jei-${mc_version}-neoforge-api:${jei_version}"
+ // We add the full version to localRuntime, not runtimeOnly, so that we do not publish a dependency on it
+ // localRuntime "mezz.jei:jei-${mc_version}-neoforge:${jei_version}"
+
+ // Example mod dependency using a mod jar from ./libs with a flat dir repository
+ // This maps to ./libs/coolmod-${mc_version}-${coolmod_version}.jar
+ // The group id is ignored when searching -- in this case, it is "blank"
+ // implementation "blank:coolmod-${mc_version}:${coolmod_version}"
+
+ // Example mod dependency using a file as dependency
+ // implementation files("libs/coolmod-${mc_version}-${coolmod_version}.jar")
+
+ // Example project dependency using a sister or child project:
+ // implementation project(":myproject")
+
+ // For more info:
+ // http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
+ // http://www.gradle.org/docs/current/userguide/dependency_management.html
+
+
+// implementation "net.neoforged:neoforge:${neo_version}"
// implementation files('libs/javamp3-1.0.3.jar')
implementation 'fr.delthas:javamp3:1.0.3'
implementation 'com.github.stephengold:j-ogg-vorbis:1.0.4'
- jarJar(group: 'fr.delthas', name: 'javamp3', version: '[1.0.0,2.0.0)') {
- jarJar.pin(it, '1.0.3')
+ jarJar(implementation("fr.delthas:javamp3")) {
+ version {
+ strictly '[1.0.0,2.0.0)'
+ prefer '1.0.3'
+ }
}
- jarJar(group: 'com.github.stephengold', name: 'j-ogg-vorbis', version: '[1.0.4, 2.0.0)') {
- jarJar.pin(it, '1.0.4')
+ jarJar(implementation("com.github.stephengold:j-ogg-vorbis")) {
+ version {
+ strictly '[1.0.4,2.0.0)'
+ prefer '1.0.4'
+ }
}
}
// This block of code expands all declared replace properties in the specified resource targets.
// A missing property will result in an error. Properties are expanded using ${} Groovy notation.
-// When "copyIdeResources" is enabled, this will also run before the game launches in IDE environments.
-// See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html
-tasks.withType(ProcessResources).configureEach {
+var generateModMetadata = tasks.register("generateModMetadata", ProcessResources) {
var replaceProperties = [
- minecraft_version : minecraft_version, minecraft_version_range: minecraft_version_range,
- neo_version : neo_version, neo_version_range: neo_version_range,
- loader_version_range: loader_version_range,
- mod_id : mod_id, mod_name: mod_name, mod_license: mod_license, mod_version: mod_version,
- mod_authors : mod_authors, mod_description: mod_description,
+ minecraft_version : minecraft_version,
+ minecraft_version_range: minecraft_version_range,
+ neo_version : neo_version,
+ neo_version_range : neo_version_range,
+ loader_version_range : loader_version_range,
+ mod_id : mod_id,
+ mod_name : mod_name,
+ mod_license : mod_license,
+ mod_version : mod_version,
+ mod_authors : mod_authors,
+ mod_description : mod_description
]
inputs.properties replaceProperties
-
- filesMatching(['META-INF/mods.toml']) {
- expand replaceProperties + [project: project]
- }
+ expand replaceProperties
+ from "src/main/templates"
+ into "build/generated/sources/modMetadata"
}
+// Include the output of "generateModMetadata" as an input directory for the build
+// this works with both building through Gradle and the IDE.
+sourceSets.main.resources.srcDir generateModMetadata
+// To avoid having to run "generateModMetadata" manually, make it run on every project reload
+neoForge.ideSyncTask generateModMetadata
// Example for how to get properties into the manifest for reading by the runtime..
jar {
- archiveClassifier = 'slim'
+ archiveClassifier = 'all'
manifest {
attributes([
"Specification-Title": "TurnBasedMinecraftMod",
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
}
+
+// IDEA no longer automatically downloads sources/javadoc jars for dependencies, so we need to explicitly enable the behavior.
+idea {
+ module {
+ downloadSources = true
+ downloadJavadoc = true
+ }
+}
-org.gradle.jvmargs=-Xmx4096m
+# Sets default memory used for gradle commands. Can be overridden by user or command line properties.
+org.gradle.jvmargs=-Xmx1G
org.gradle.daemon=false
-org.gradle.debug=false
+org.gradle.parallel=true
+org.gradle.caching=true
+org.gradle.configuration-cache=true
-#read more on this at https://github.com/neoforged/NeoGradle/blob/NG_7.0/README.md#apply-parchment-mappings
+#read more on this at https://github.com/neoforged/ModDevGradle?tab=readme-ov-file#better-minecraft-parameter-names--javadoc-parchment
# you can also find the latest versions at: https://parchmentmc.org/docs/getting-started
-neogradle.subsystems.parchment.minecraftVersion=1.20.3
-neogradle.subsystems.parchment.mappingsVersion=2023.12.31
+parchment_minecraft_version=1.21
+parchment_mappings_version=2024.07.28
+
# Environment Properties
# You can find the latest versions here: https://projects.neoforged.net/neoforged/neoforge
# The Minecraft version must agree with the Neo version to get a valid artifact
-minecraft_version=1.20.4
+minecraft_version=1.21.1
+
# The Minecraft version range can use any release version of Minecraft as bounds.
# Snapshots, pre-releases, and release candidates are not guaranteed to sort properly
# as they do not follow standard versioning conventions.
-minecraft_version_range=[1.20.4,1.21)
+minecraft_version_range=[1.21.1, 1.22)
+
# The Neo version must agree with the Minecraft version to get a valid artifact
-neo_version=20.4.146-beta
+neo_version=21.1.69
# The Neo version range can use any version of Neo as bounds
-neo_version_range=[20.4,)
+neo_version_range=[21.1.0,)
# The loader version range can only use the major version of FML as bounds
-loader_version_range=[2,)
+loader_version_range=[4,)
## Mod Properties
# The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default.
mod_license=MIT
# The mod version. See https://semver.org/
-mod_version=1.26.0
+mod_version=1.27.0
# The group ID for the mod. It is only important when publishing as an artifact to a Maven repository.
# This should match the base package used for the mod sources.
# See https://maven.apache.org/guides/mini/guide-naming-conventions.html
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
networkTimeout=10000
+validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
# See the License for the specific language governing permissions and
# limitations under the License.
#
+# SPDX-License-Identifier: Apache-2.0
+#
##############################################################################
#
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
-# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
-APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
-
-# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
+' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
fi
else
JAVACMD=java
- which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+ if ! command -v java >/dev/null 2>&1
+ then
+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
+ fi
fi
# Increase the maximum file descriptors if we can.
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
- # shellcheck disable=SC3045
+ # shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
- # shellcheck disable=SC3045
+ # shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
done
fi
-# Collect all arguments for the java command;
-# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
-# shell script including quotes and variable substitutions, so put them in
-# double quotes to make sure that they get re-expanded; and
-# * put everything else in single quotes, so that it's not re-expanded.
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Collect all arguments for the java command:
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+# and any embedded shellness will be escaped.
+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-@rem
-@rem Copyright 2015 the original author or authors.
-@rem
-@rem Licensed under the Apache License, Version 2.0 (the "License");
-@rem you may not use this file except in compliance with the License.
-@rem You may obtain a copy of the License at
-@rem
-@rem https://www.apache.org/licenses/LICENSE-2.0
-@rem
-@rem Unless required by applicable law or agreed to in writing, software
-@rem distributed under the License is distributed on an "AS IS" BASIS,
-@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-@rem See the License for the specific language governing permissions and
-@rem limitations under the License.
-@rem
-
-@if "%DEBUG%"=="" @echo off
-@rem ##########################################################################
-@rem
-@rem Gradle startup script for Windows
-@rem
-@rem ##########################################################################
-
-@rem Set local scope for the variables with windows NT shell
-if "%OS%"=="Windows_NT" setlocal
-
-set DIRNAME=%~dp0
-if "%DIRNAME%"=="" set DIRNAME=.
-@rem This is normally unused
-set APP_BASE_NAME=%~n0
-set APP_HOME=%DIRNAME%
-
-@rem Resolve any "." and ".." in APP_HOME to make it shorter.
-for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
-
-@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
-
-@rem Find java.exe
-if defined JAVA_HOME goto findJavaFromJavaHome
-
-set JAVA_EXE=java.exe
-%JAVA_EXE% -version >NUL 2>&1
-if %ERRORLEVEL% equ 0 goto execute
-
-echo.
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:findJavaFromJavaHome
-set JAVA_HOME=%JAVA_HOME:"=%
-set JAVA_EXE=%JAVA_HOME%/bin/java.exe
-
-if exist "%JAVA_EXE%" goto execute
-
-echo.
-echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:execute
-@rem Setup the command line
-
-set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
-
-
-@rem Execute Gradle
-"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
-
-:end
-@rem End local scope for the variables with windows NT shell
-if %ERRORLEVEL% equ 0 goto mainEnd
-
-:fail
-rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
-rem the _cmd.exe /c_ return code!
-set EXIT_CODE=%ERRORLEVEL%
-if %EXIT_CODE% equ 0 set EXIT_CODE=1
-if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
-exit /b %EXIT_CODE%
-
-:mainEnd
-if "%OS%"=="Windows_NT" endlocal
-
-:omega
+@rem\r
+@rem Copyright 2015 the original author or authors.\r
+@rem\r
+@rem Licensed under the Apache License, Version 2.0 (the "License");\r
+@rem you may not use this file except in compliance with the License.\r
+@rem You may obtain a copy of the License at\r
+@rem\r
+@rem https://www.apache.org/licenses/LICENSE-2.0\r
+@rem\r
+@rem Unless required by applicable law or agreed to in writing, software\r
+@rem distributed under the License is distributed on an "AS IS" BASIS,\r
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+@rem See the License for the specific language governing permissions and\r
+@rem limitations under the License.\r
+@rem\r
+@rem SPDX-License-Identifier: Apache-2.0\r
+@rem\r
+\r
+@if "%DEBUG%"=="" @echo off\r
+@rem ##########################################################################\r
+@rem\r
+@rem Gradle startup script for Windows\r
+@rem\r
+@rem ##########################################################################\r
+\r
+@rem Set local scope for the variables with windows NT shell\r
+if "%OS%"=="Windows_NT" setlocal\r
+\r
+set DIRNAME=%~dp0\r
+if "%DIRNAME%"=="" set DIRNAME=.\r
+@rem This is normally unused\r
+set APP_BASE_NAME=%~n0\r
+set APP_HOME=%DIRNAME%\r
+\r
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.\r
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi\r
+\r
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\r
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"\r
+\r
+@rem Find java.exe\r
+if defined JAVA_HOME goto findJavaFromJavaHome\r
+\r
+set JAVA_EXE=java.exe\r
+%JAVA_EXE% -version >NUL 2>&1\r
+if %ERRORLEVEL% equ 0 goto execute\r
+\r
+echo. 1>&2\r
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2\r
+echo. 1>&2\r
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2\r
+echo location of your Java installation. 1>&2\r
+\r
+goto fail\r
+\r
+:findJavaFromJavaHome\r
+set JAVA_HOME=%JAVA_HOME:"=%\r
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe\r
+\r
+if exist "%JAVA_EXE%" goto execute\r
+\r
+echo. 1>&2\r
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2\r
+echo. 1>&2\r
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2\r
+echo location of your Java installation. 1>&2\r
+\r
+goto fail\r
+\r
+:execute\r
+@rem Setup the command line\r
+\r
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar\r
+\r
+\r
+@rem Execute Gradle\r
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*\r
+\r
+:end\r
+@rem End local scope for the variables with windows NT shell\r
+if %ERRORLEVEL% equ 0 goto mainEnd\r
+\r
+:fail\r
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of\r
+rem the _cmd.exe /c_ return code!\r
+set EXIT_CODE=%ERRORLEVEL%\r
+if %EXIT_CODE% equ 0 set EXIT_CODE=1\r
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%\r
+exit /b %EXIT_CODE%\r
+\r
+:mainEnd\r
+if "%OS%"=="Windows_NT" endlocal\r
+\r
+:omega\r
pluginManagement {\r
repositories {\r
+ mavenLocal()\r
gradlePluginPortal()\r
maven {\r
url = 'https://maven.neoforged.net/releases'\r
}\r
\r
plugins {\r
- id 'org.gradle.toolchains.foojay-resolver-convention' version '0.5.0'\r
+ id 'org.gradle.toolchains.foojay-resolver-convention' version '0.8.0'\r
}\r
setState(MenuState.ATTACK_TARGET);
break;
case DEFEND:
- PacketDistributor.SERVER.noArg().send(new PacketBattleDecision(
- TurnBasedMinecraftMod.proxy.getLocalBattle().getId(), Battle.Decision.DEFEND, 0));
+ PacketDistributor.sendToServer(new PacketBattleDecision(
+ TurnBasedMinecraftMod.proxy.getLocalBattle().getId(), Battle.Decision.DEFEND.getValue(), 0));
setState(MenuState.WAITING);
break;
case ITEM:
setState(MenuState.ITEM_ACTION);
break;
case FLEE:
- PacketDistributor.SERVER.noArg().send(new PacketBattleDecision(
- TurnBasedMinecraftMod.proxy.getLocalBattle().getId(), Battle.Decision.FLEE, 0));
+ PacketDistributor.sendToServer(new PacketBattleDecision(
+ TurnBasedMinecraftMod.proxy.getLocalBattle().getId(), Battle.Decision.FLEE.getValue(), 0));
setState(MenuState.WAITING);
break;
case ATTACK_TARGET:
protected void entityButtonActionEvent(EntitySelectionButton button, ButtonAction action) {
if (action.equals(ButtonAction.ATTACK_TARGET)) {
- PacketDistributor.SERVER.noArg().send(
+ PacketDistributor.sendToServer(
new PacketBattleDecision(TurnBasedMinecraftMod.proxy.getLocalBattle().getId(),
- Battle.Decision.ATTACK, ((EntitySelectionButton) button).getID()));
+ Battle.Decision.ATTACK.getValue(), ((EntitySelectionButton) button).getID()));
setState(MenuState.WAITING);
} else {
setState(MenuState.MAIN_MENU);
protected void itemButtonActionEvent(ItemSelectionButton button, ButtonAction action) {
switch (action) {
case DO_ITEM_SWITCH:
- PacketDistributor.SERVER.noArg().send(
+ PacketDistributor.sendToServer(
new PacketBattleDecision(TurnBasedMinecraftMod.proxy.getLocalBattle().getId(),
- Battle.Decision.SWITCH_ITEM, button.getID()));
+ Battle.Decision.SWITCH_ITEM.getValue(), button.getID()));
if (button.getID() >= 0 && button.getID() < 9) {
Minecraft.getInstance().player.getInventory().selected = button.getID();
}
setState(MenuState.WAITING);
break;
case DO_USE_ITEM:
- PacketDistributor.SERVER.noArg().send(
+ PacketDistributor.sendToServer(
new PacketBattleDecision(TurnBasedMinecraftMod.proxy.getLocalBattle().getId(),
- Battle.Decision.USE_ITEM, button.getID()));
+ Battle.Decision.USE_ITEM.getValue(), button.getID()));
setState(MenuState.WAITING);
break;
default:
package com.burnedkirby.TurnBasedMinecraft.client;
import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod;
-import net.minecraft.client.Minecraft;
-import net.minecraft.client.gui.GuiGraphics;
-import net.minecraft.client.gui.components.*;
-import net.minecraft.client.gui.screens.Screen;
-import net.minecraft.network.chat.Component;
import net.neoforged.neoforge.common.ModConfigSpec;
import org.apache.commons.lang3.tuple.Pair;
//builder.pop();
}
-
- public static class CliConfGui extends Screen {
- private final int widget_height = 20;
- private boolean dirtyFlag;
- private boolean accepted;
- private EditBox battleListEditBox = null;
- private EditBox sillyListEditBox = null;
- private SliderPercentage sillyMusicThresholdSlider = null;
- private Checkbox affectedByMasterVolCheckbox = null;
- private Checkbox affectedByMusicVolCheckbox = null;
- private SliderPercentage volumeSlider = null;
-
- public CliConfGui() {
- super(Component.literal("TurnBasedMC Client Config"));
-
- dirtyFlag = true;
-
- accepted = false;
- }
-
- public void onDirty() {
- clearWidgets();
-
- // Initialize GUI elements.
- int widget_x_offset = 5;
- int widget_width = this.width / 2 - widget_x_offset * 2;
- int top_offset = 5;
-
- addRenderableWidget(
- new StringWidget(this.width / 2 - widget_width + widget_x_offset, top_offset,
- widget_width, widget_height, Component.literal("Battle Music Categories"),
- font));
- if (battleListEditBox == null) {
- battleListEditBox =
- new EditBox(font, this.width / 2 + widget_x_offset, top_offset, widget_width,
- widget_height, Component.literal("Battle Music Categories Edit Box"));
- } else {
- battleListEditBox.setPosition(this.width / 2 + widget_x_offset, top_offset);
- battleListEditBox.setSize(widget_width, widget_height);
- }
- String tempString = "";
- for (String category : CLIENT.battleMusicList.get()) {
- if (tempString.isEmpty()) {
- tempString = category;
- } else {
- tempString += "," + category;
- }
- }
- battleListEditBox.setMaxLength(128);
- battleListEditBox.setValue(tempString);
- addRenderableWidget(battleListEditBox);
-
- top_offset += widget_height;
-
- addRenderableWidget(
- new StringWidget(this.width / 2 - widget_width + widget_x_offset, top_offset,
- widget_width, widget_height, Component.literal("Silly Music Categories"),
- font));
- if (sillyListEditBox == null) {
- sillyListEditBox =
- new EditBox(font, this.width / 2 + widget_x_offset, top_offset, widget_width,
- widget_height, Component.literal("Silly Music Categories Edit Box"));
- } else {
- sillyListEditBox.setPosition(this.width / 2 + widget_x_offset, top_offset);
- sillyListEditBox.setSize(widget_width, widget_height);
- }
- tempString = "";
- for (String category : CLIENT.sillyMusicList.get()) {
- if (tempString.isEmpty()) {
- tempString = category;
- } else {
- tempString += "," + category;
- }
- }
- sillyListEditBox.setMaxLength(128);
- sillyListEditBox.setValue(tempString);
- addRenderableWidget(sillyListEditBox);
-
- top_offset += widget_height;
-
- StringWidget stringWidget =
- new StringWidget(this.width / 2 - widget_width + widget_x_offset, top_offset,
- widget_width, widget_height, Component.literal("Silly Music Threshold"), font);
- stringWidget.setTooltip(Tooltip.create(
- Component.literal("Ratio of minimum of silly mobs in battle to play silly music")));
- addRenderableWidget(stringWidget);
- if (sillyMusicThresholdSlider == null) {
- sillyMusicThresholdSlider =
- new SliderPercentage(this.width / 2 + widget_x_offset, top_offset, widget_width,
- widget_height, Component.literal("Silly Music Threshold: " +
- String.format("%.1f%%", CLIENT.sillyMusicThreshold.get() * 100.0)),
- CLIENT.sillyMusicThreshold.get(), "Silly Music Threshold: ");
- } else {
- sillyMusicThresholdSlider.setPosition(this.width / 2 + widget_x_offset, top_offset);
- sillyMusicThresholdSlider.setSize(widget_width, widget_height);
- }
- addRenderableWidget(sillyMusicThresholdSlider);
-
- top_offset += widget_height;
-
- stringWidget =
- new StringWidget(this.width / 2 - widget_width + widget_x_offset, top_offset,
- widget_width, widget_height, Component.literal("Affected by Master Vol."),
- font);
- stringWidget.setTooltip(Tooltip.create(
- Component.literal("If enabled, volume is affected by global master volume.")));
- addRenderableWidget(stringWidget);
- if (affectedByMasterVolCheckbox == null) {
- affectedByMasterVolCheckbox = Checkbox.builder(Component.literal(""), font)
- .pos(this.width / 2 + widget_x_offset, top_offset).build();
- } else {
- affectedByMasterVolCheckbox.setPosition(this.width / 2 + widget_x_offset,
- top_offset);
- }
- if ((CLIENT.volumeAffectedByMasterVolume.get() &&
- !affectedByMasterVolCheckbox.selected()) ||
- (!CLIENT.volumeAffectedByMasterVolume.get() &&
- affectedByMasterVolCheckbox.selected())) {
- affectedByMasterVolCheckbox.onPress();
- }
- addRenderableWidget(affectedByMasterVolCheckbox);
-
- top_offset += widget_height;
-
- stringWidget =
- new StringWidget(this.width / 2 - widget_width + widget_x_offset, top_offset,
- widget_width, widget_height, Component.literal("Affected by Music Vol."), font);
- stringWidget.setTooltip(Tooltip.create(
- Component.literal("If enabled, volume is affected by global music volume.")));
- addRenderableWidget(stringWidget);
- if (affectedByMusicVolCheckbox == null) {
- affectedByMusicVolCheckbox = Checkbox.builder(Component.literal(""), font)
- .pos(this.width / 2 + widget_x_offset, top_offset).build();
- } else {
- affectedByMusicVolCheckbox.setPosition(this.width / 2 + widget_x_offset,
- top_offset);
- }
- if ((CLIENT.volumeAffectedByMusicVolume.get() &&
- !affectedByMusicVolCheckbox.selected()) ||
- (!CLIENT.volumeAffectedByMusicVolume.get() &&
- affectedByMusicVolCheckbox.selected())) {
- affectedByMusicVolCheckbox.onPress();
- }
- addRenderableWidget(affectedByMusicVolCheckbox);
-
- top_offset += widget_height;
-
- stringWidget =
- new StringWidget(this.width / 2 - widget_width + widget_x_offset, top_offset,
- widget_width, widget_height, Component.literal("Music Volume"), font);
- stringWidget.setTooltip(
- Tooltip.create(Component.literal("Volume of battle/silly music")));
- addRenderableWidget(stringWidget);
- if (volumeSlider == null) {
- volumeSlider =
- new SliderPercentage(this.width / 2 + widget_x_offset, top_offset, widget_width,
- widget_height, Component.literal(
- "Volume: " + String.format("%.1f%%", CLIENT.musicVolume.get() * 100.0)),
- CLIENT.musicVolume.get(), "Volume: ");
- } else {
- volumeSlider.setPosition(this.width / 2 + widget_x_offset, top_offset);
- volumeSlider.setSize(widget_width, widget_height);
- }
- addRenderableWidget(volumeSlider);
-
- addRenderableWidget(Button.builder(Component.literal("Cancel"),
- (b) -> Minecraft.getInstance().setScreen(null))
- .bounds(this.width / 2 - widget_width + widget_x_offset,
- this.height - widget_height, widget_width, widget_height).build());
- addRenderableWidget(Button.builder(Component.literal("Accept"), (b) -> {
- accepted = true;
- }).bounds(this.width / 2 + widget_x_offset, this.height - widget_height, widget_width,
- widget_height).build());
-
- dirtyFlag = false;
- }
-
- private void doAccepted() {
- String temp = battleListEditBox.getValue();
- {
- List<String> battleList = new ArrayList<String>();
- for (String category : temp.split(",")) {
- battleList.add(category.strip());
- }
- CLIENT.battleMusicList.set(battleList);
- }
-
- temp = sillyListEditBox.getValue();
- {
- List<String> sillyList = new ArrayList<String>();
- for (String category : temp.split(",")) {
- sillyList.add(category.strip());
- }
- CLIENT.sillyMusicList.set(sillyList);
- }
-
- CLIENT.sillyMusicThreshold.set(sillyMusicThresholdSlider.percentage);
-
- CLIENT.volumeAffectedByMasterVolume.set(affectedByMasterVolCheckbox.selected());
-
- CLIENT.volumeAffectedByMusicVolume.set(affectedByMusicVolCheckbox.selected());
-
- CLIENT.musicVolume.set(volumeSlider.percentage);
- }
-
- @Override
- public boolean isPauseScreen() {
- return true;
- }
-
- @Override
- public void render(GuiGraphics pGuiGraphics, int pMouseX, int pMouseY, float pPartialTick) {
- if (accepted) {
- doAccepted();
- Minecraft.getInstance().setScreen(null);
- return;
- }
- if (dirtyFlag) {
- onDirty();
- }
- super.render(pGuiGraphics, pMouseX, pMouseY, pPartialTick);
- }
-
- @Override
- public void resize(Minecraft pMinecraft, int pWidth, int pHeight) {
- dirtyFlag = true;
- super.resize(pMinecraft, pWidth, pHeight);
- }
-
- private static class SliderPercentage extends AbstractSliderButton {
- private final String messagePrefix;
- private double percentage;
-
- public SliderPercentage(int x, int y, int width, int height, Component message, double percentage, String messagePrefix) {
- super(x, y, width, height, message, percentage);
- this.percentage = percentage;
- this.messagePrefix = messagePrefix;
- }
-
- @Override
- protected void updateMessage() {
- setMessage(
- Component.literal(messagePrefix + String.format("%.1f%%", percentage * 100.0)));
- }
-
- @Override
- protected void applyValue() {
- percentage = value;
- }
- }
- }
}
--- /dev/null
+package com.burnedkirby.TurnBasedMinecraft.client;
+
+import net.minecraft.client.Minecraft;
+import net.minecraft.client.gui.GuiGraphics;
+import net.minecraft.client.gui.components.*;
+import net.minecraft.client.gui.screens.Screen;
+import net.minecraft.network.chat.Component;
+import net.neoforged.fml.ModContainer;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ClientConfigGui extends net.minecraft.client.gui.screens.Screen {
+ private final int widget_height = 20;
+ private boolean dirtyFlag;
+ private boolean accepted;
+ private EditBox battleListEditBox = null;
+ private EditBox sillyListEditBox = null;
+ private SliderPercentage sillyMusicThresholdSlider = null;
+ private Checkbox affectedByMasterVolCheckbox = null;
+ private Checkbox affectedByMusicVolCheckbox = null;
+ private SliderPercentage volumeSlider = null;
+
+ public ClientConfigGui(ModContainer container, Screen parent) {
+ super(Component.literal("TurnBasedMC Client Config"));
+
+ dirtyFlag = true;
+
+ accepted = false;
+ }
+
+ public void onDirty() {
+ clearWidgets();
+
+ // Initialize GUI elements.
+ int widget_x_offset = 5;
+ int widget_width = this.width / 2 - widget_x_offset * 2;
+ int top_offset = 5;
+
+ addRenderableWidget(
+ new StringWidget(this.width / 2 - widget_width + widget_x_offset, top_offset,
+ widget_width, widget_height, Component.literal("Battle Music Categories"),
+ font));
+ if (battleListEditBox == null) {
+ battleListEditBox =
+ new EditBox(font, this.width / 2 + widget_x_offset, top_offset, widget_width,
+ widget_height, Component.literal("Battle Music Categories Edit Box"));
+ } else {
+ battleListEditBox.setPosition(this.width / 2 + widget_x_offset, top_offset);
+ battleListEditBox.setSize(widget_width, widget_height);
+ }
+ String tempString = "";
+ for (String category : ClientConfig.CLIENT.battleMusicList.get()) {
+ if (tempString.isEmpty()) {
+ tempString = category;
+ } else {
+ tempString += "," + category;
+ }
+ }
+ battleListEditBox.setMaxLength(128);
+ battleListEditBox.setValue(tempString);
+ addRenderableWidget(battleListEditBox);
+
+ top_offset += widget_height;
+
+ addRenderableWidget(
+ new StringWidget(this.width / 2 - widget_width + widget_x_offset, top_offset,
+ widget_width, widget_height, Component.literal("Silly Music Categories"),
+ font));
+ if (sillyListEditBox == null) {
+ sillyListEditBox =
+ new EditBox(font, this.width / 2 + widget_x_offset, top_offset, widget_width,
+ widget_height, Component.literal("Silly Music Categories Edit Box"));
+ } else {
+ sillyListEditBox.setPosition(this.width / 2 + widget_x_offset, top_offset);
+ sillyListEditBox.setSize(widget_width, widget_height);
+ }
+ tempString = "";
+ for (String category : ClientConfig.CLIENT.sillyMusicList.get()) {
+ if (tempString.isEmpty()) {
+ tempString = category;
+ } else {
+ tempString += "," + category;
+ }
+ }
+ sillyListEditBox.setMaxLength(128);
+ sillyListEditBox.setValue(tempString);
+ addRenderableWidget(sillyListEditBox);
+
+ top_offset += widget_height;
+
+ StringWidget stringWidget =
+ new StringWidget(this.width / 2 - widget_width + widget_x_offset, top_offset,
+ widget_width, widget_height, Component.literal("Silly Music Threshold"), font);
+ stringWidget.setTooltip(Tooltip.create(
+ Component.literal("Ratio of minimum of silly mobs in battle to play silly music")));
+ addRenderableWidget(stringWidget);
+ if (sillyMusicThresholdSlider == null) {
+ sillyMusicThresholdSlider =
+ new SliderPercentage(this.width / 2 + widget_x_offset, top_offset, widget_width,
+ widget_height, Component.literal("Silly Music Threshold: " +
+ String.format("%.1f%%", ClientConfig.CLIENT.sillyMusicThreshold.get() * 100.0)),
+ ClientConfig.CLIENT.sillyMusicThreshold.get(), "Silly Music Threshold: ");
+ } else {
+ sillyMusicThresholdSlider.setPosition(this.width / 2 + widget_x_offset, top_offset);
+ sillyMusicThresholdSlider.setSize(widget_width, widget_height);
+ }
+ addRenderableWidget(sillyMusicThresholdSlider);
+
+ top_offset += widget_height;
+
+ stringWidget =
+ new StringWidget(this.width / 2 - widget_width + widget_x_offset, top_offset,
+ widget_width, widget_height, Component.literal("Affected by Master Vol."),
+ font);
+ stringWidget.setTooltip(Tooltip.create(
+ Component.literal("If enabled, volume is affected by global master volume.")));
+ addRenderableWidget(stringWidget);
+ if (affectedByMasterVolCheckbox == null) {
+ affectedByMasterVolCheckbox = Checkbox.builder(Component.literal(""), font)
+ .pos(this.width / 2 + widget_x_offset, top_offset).build();
+ } else {
+ affectedByMasterVolCheckbox.setPosition(this.width / 2 + widget_x_offset,
+ top_offset);
+ }
+ if ((ClientConfig.CLIENT.volumeAffectedByMasterVolume.get() &&
+ !affectedByMasterVolCheckbox.selected()) ||
+ (!ClientConfig.CLIENT.volumeAffectedByMasterVolume.get() &&
+ affectedByMasterVolCheckbox.selected())) {
+ affectedByMasterVolCheckbox.onPress();
+ }
+ addRenderableWidget(affectedByMasterVolCheckbox);
+
+ top_offset += widget_height;
+
+ stringWidget =
+ new StringWidget(this.width / 2 - widget_width + widget_x_offset, top_offset,
+ widget_width, widget_height, Component.literal("Affected by Music Vol."), font);
+ stringWidget.setTooltip(Tooltip.create(
+ Component.literal("If enabled, volume is affected by global music volume.")));
+ addRenderableWidget(stringWidget);
+ if (affectedByMusicVolCheckbox == null) {
+ affectedByMusicVolCheckbox = Checkbox.builder(Component.literal(""), font)
+ .pos(this.width / 2 + widget_x_offset, top_offset).build();
+ } else {
+ affectedByMusicVolCheckbox.setPosition(this.width / 2 + widget_x_offset,
+ top_offset);
+ }
+ if ((ClientConfig.CLIENT.volumeAffectedByMusicVolume.get() &&
+ !affectedByMusicVolCheckbox.selected()) ||
+ (!ClientConfig.CLIENT.volumeAffectedByMusicVolume.get() &&
+ affectedByMusicVolCheckbox.selected())) {
+ affectedByMusicVolCheckbox.onPress();
+ }
+ addRenderableWidget(affectedByMusicVolCheckbox);
+
+ top_offset += widget_height;
+
+ stringWidget =
+ new StringWidget(this.width / 2 - widget_width + widget_x_offset, top_offset,
+ widget_width, widget_height, Component.literal("Music Volume"), font);
+ stringWidget.setTooltip(
+ Tooltip.create(Component.literal("Volume of battle/silly music")));
+ addRenderableWidget(stringWidget);
+ if (volumeSlider == null) {
+ volumeSlider =
+ new SliderPercentage(this.width / 2 + widget_x_offset, top_offset, widget_width,
+ widget_height, Component.literal(
+ "Volume: " + String.format("%.1f%%", ClientConfig.CLIENT.musicVolume.get() * 100.0)),
+ ClientConfig.CLIENT.musicVolume.get(), "Volume: ");
+ } else {
+ volumeSlider.setPosition(this.width / 2 + widget_x_offset, top_offset);
+ volumeSlider.setSize(widget_width, widget_height);
+ }
+ addRenderableWidget(volumeSlider);
+
+ addRenderableWidget(Button.builder(Component.literal("Cancel"),
+ (b) -> Minecraft.getInstance().setScreen(null))
+ .bounds(this.width / 2 - widget_width + widget_x_offset,
+ this.height - widget_height, widget_width, widget_height).build());
+ addRenderableWidget(Button.builder(Component.literal("Accept"), (b) -> {
+ accepted = true;
+ }).bounds(this.width / 2 + widget_x_offset, this.height - widget_height, widget_width,
+ widget_height).build());
+
+ dirtyFlag = false;
+ }
+
+ private void doAccepted() {
+ String temp = battleListEditBox.getValue();
+ {
+ List<String> battleList = new ArrayList<String>();
+ for (String category : temp.split(",")) {
+ battleList.add(category.strip());
+ }
+ ClientConfig.CLIENT.battleMusicList.set(battleList);
+ }
+
+ temp = sillyListEditBox.getValue();
+ {
+ List<String> sillyList = new ArrayList<String>();
+ for (String category : temp.split(",")) {
+ sillyList.add(category.strip());
+ }
+ ClientConfig.CLIENT.sillyMusicList.set(sillyList);
+ }
+
+ ClientConfig.CLIENT.sillyMusicThreshold.set(sillyMusicThresholdSlider.percentage);
+
+ ClientConfig.CLIENT.volumeAffectedByMasterVolume.set(affectedByMasterVolCheckbox.selected());
+
+ ClientConfig.CLIENT.volumeAffectedByMusicVolume.set(affectedByMusicVolCheckbox.selected());
+
+ ClientConfig.CLIENT.musicVolume.set(volumeSlider.percentage);
+ }
+
+ @Override
+ public boolean isPauseScreen() {
+ return true;
+ }
+
+ @Override
+ public void render(GuiGraphics pGuiGraphics, int pMouseX, int pMouseY, float pPartialTick) {
+ if (accepted) {
+ doAccepted();
+ Minecraft.getInstance().setScreen(null);
+ return;
+ }
+ if (dirtyFlag) {
+ onDirty();
+ }
+ super.render(pGuiGraphics, pMouseX, pMouseY, pPartialTick);
+ }
+
+ @Override
+ public void resize(Minecraft pMinecraft, int pWidth, int pHeight) {
+ dirtyFlag = true;
+ super.resize(pMinecraft, pWidth, pHeight);
+ }
+
+ private static class SliderPercentage extends AbstractSliderButton {
+ private final String messagePrefix;
+ private double percentage;
+
+ public SliderPercentage(int x, int y, int width, int height, Component message, double percentage, String messagePrefix) {
+ super(x, y, width, height, message, percentage);
+ this.percentage = percentage;
+ this.messagePrefix = messagePrefix;
+ }
+
+ @Override
+ protected void updateMessage() {
+ setMessage(
+ Component.literal(messagePrefix + String.format("%.1f%%", percentage * 100.0)));
+ }
+
+ @Override
+ protected void applyValue() {
+ percentage = value;
+ }
+ }
+}
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.Level;
-import net.neoforged.neoforge.network.handling.PlayPayloadContext;
+import net.neoforged.neoforge.network.handling.IPayloadContext;
public class ClientProxy extends CommonProxy {
private BattleGui battleGui = null;
}
@Override
- public <MSG> void handlePacket(final MSG msg, final PlayPayloadContext ctx) {
+ public <MSG> void handlePacket(final MSG msg, final IPayloadContext ctx) {
if (msg.getClass() == PacketBattleMessage.class) {
PacketBattleMessage pkt = (PacketBattleMessage) msg;
Entity fromEntity = getEntity(pkt.getEntityIDFrom(), pkt.getDimension());
}
}
}
+
+ @Override
+ public void showClientConfigGui() {
+ Minecraft.getInstance().setScreen(new ClientConfigGui(null, null));
+ }
}
package com.burnedkirby.TurnBasedMinecraft.common;
-import java.util.Iterator;
-
import com.burnedkirby.TurnBasedMinecraft.common.networking.PacketBattleMessage;
-
import com.burnedkirby.TurnBasedMinecraft.common.networking.PacketEditingMessage;
import com.burnedkirby.TurnBasedMinecraft.common.networking.PacketGeneralMessage;
+import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.damagesource.DamageTypes;
import net.minecraft.world.entity.monster.Creeper;
-import net.minecraft.server.level.ServerPlayer;
-import net.neoforged.neoforge.event.entity.living.LivingAttackEvent;
+import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.neoforge.event.entity.living.LivingChangeTargetEvent;
+import net.neoforged.neoforge.event.entity.living.LivingIncomingDamageEvent;
import net.neoforged.neoforge.network.PacketDistributor;
-import net.neoforged.bus.api.SubscribeEvent;
+
+import java.util.Iterator;
public class AttackEventHandler
{
- private boolean isAttackerValid(LivingAttackEvent event)
+ private boolean isAttackerValid(LivingIncomingDamageEvent event)
{
if(event.getSource().getEntity() == null)
{
}
@SubscribeEvent
- public void entityAttacked(LivingAttackEvent event)
+ public void entityAttacked(LivingIncomingDamageEvent event)
{
if(event.getEntity().level().isClientSide)
{
if(!event.getEntity().hasCustomName())
{
TurnBasedMinecraftMod.logger.error("Cannot edit custom name from entity without custom name");
- PacketDistributor.PLAYER.with((ServerPlayer)editingInfo.editor).send(new PacketGeneralMessage("Cannot edit custom name from entity without custom name"));
+ PacketDistributor.sendToPlayer((ServerPlayer)editingInfo.editor, new PacketGeneralMessage("Cannot edit custom name from entity without custom name"));
return;
}
editingInfo.entityInfo = config.getCustomEntityInfo(event.getEntity().getCustomName().getString());
editingInfo.entityInfo = new EntityInfo();
editingInfo.entityInfo.customName = event.getEntity().getCustomName().getString();
}
- PacketDistributor.PLAYER.with((ServerPlayer)editingInfo.editor).send(new PacketGeneralMessage("Editing custom name \"" + event.getEntity().getCustomName().getString() + "\""));
+ PacketDistributor.sendToPlayer((ServerPlayer)editingInfo.editor, new PacketGeneralMessage("Editing custom name \"" + event.getEntity().getCustomName().getString() + "\""));
TurnBasedMinecraftMod.logger.info("Begin editing custom \"" + event.getEntity().getCustomName().getString() + "\"");
- PacketDistributor.PLAYER.with((ServerPlayer)editingInfo.editor).send(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
+ PacketDistributor.sendToPlayer((ServerPlayer)editingInfo.editor, new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
}
else
{
{
editingInfo.entityInfo = editingInfo.entityInfo.clone();
}
- PacketDistributor.PLAYER.with((ServerPlayer)editingInfo.editor).send(new PacketGeneralMessage("Editing entity \"" + editingInfo.entityInfo.classType.getName() + "\""));
+ PacketDistributor.sendToPlayer((ServerPlayer)editingInfo.editor, new PacketGeneralMessage("Editing entity \"" + editingInfo.entityInfo.classType.getName() + "\""));
TurnBasedMinecraftMod.logger.info("Begin editing \"" + editingInfo.entityInfo.classType.getName() + "\"");
- PacketDistributor.PLAYER.with((ServerPlayer)editingInfo.editor).send(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
+ PacketDistributor.sendToPlayer((ServerPlayer)editingInfo.editor, new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
}
return;
}
if(event.getEntity().level().isClientSide
|| config.isOldBattleBehaviorEnabled()
|| (event.getEntity() != null && battleManager.isRecentlyLeftBattle(event.getEntity().getId()))
- || (event.getNewTarget() != null && battleManager.isRecentlyLeftBattle(event.getNewTarget().getId()))
- || (event.getEntity() != null && event.getNewTarget() != null && Utility.distanceBetweenEntities(event.getEntity(), event.getNewTarget()) > (double)config.getAggroStartBattleDistance()))
+ || (event.getNewAboutToBeSetTarget() != null && battleManager.isRecentlyLeftBattle(event.getNewAboutToBeSetTarget().getId()))
+ || (event.getEntity() != null && event.getNewAboutToBeSetTarget() != null && Utility.distanceBetweenEntities(event.getEntity(), event.getNewAboutToBeSetTarget()) > (double)config.getAggroStartBattleDistance()))
{
return;
}
else if(event.getEntity() != null
- && event.getNewTarget() != null
+ && event.getNewAboutToBeSetTarget() != null
&& !config.getBattleIgnoringPlayers().contains(event.getEntity().getId())
- && !config.getBattleIgnoringPlayers().contains(event.getNewTarget().getId())
- && event.getEntity().level().dimension().equals(event.getNewTarget().level().dimension()))
+ && !config.getBattleIgnoringPlayers().contains(event.getNewAboutToBeSetTarget().getId())
+ && event.getEntity().level().dimension().equals(event.getNewAboutToBeSetTarget().level().dimension()))
{
TurnBasedMinecraftMod.proxy.getBattleManager().checkTargeted(event);
}
}
PacketBattleInfo infoPacket = new PacketBattleInfo(getSideAIDs(), getSideBIDs(), timer, TurnBasedMinecraftMod.proxy.getConfig().getDecisionDurationNanos(), !TurnBasedMinecraftMod.proxy.getConfig().isBattleDecisionDurationForever());
for (Combatant p : players.values()) {
- PacketDistributor.PLAYER.with((ServerPlayer)p.entity).send(infoPacket);
+ PacketDistributor.sendToPlayer((ServerPlayer)p.entity, infoPacket);
}
}
PacketBattleMessage packet = new PacketBattleMessage(type, from, to, dimension, amount, custom);
for (Combatant p : players.values()) {
if (p.entity.isAlive()) {
- PacketDistributor.PLAYER.with((ServerPlayer)p.entity).send(packet);
+ PacketDistributor.sendToPlayer((ServerPlayer)p.entity, packet);
}
}
}
private void removeCombatantPostRemove(Combatant c) {
if (c.entity instanceof Player) {
- PacketDistributor.PLAYER.with((ServerPlayer)c.entity).send(new PacketBattleMessage(PacketBattleMessage.MessageType.ENDED, 0, 0, dimension, 0));
+ PacketDistributor.sendToPlayer((ServerPlayer)c.entity, new PacketBattleMessage(PacketBattleMessage.MessageType.ENDED, 0, 0, dimension, 0));
}
battleManager.addRecentlyLeftBattle(c);
}
final Entity targetEntity = target.entity;
final float yawDirection = Utility.yawDirection(next.entity.getX(), next.entity.getZ(), target.entity.getX(), target.entity.getZ());
final float pitchDirection = Utility.pitchDirection(next.entity.getX(), next.entity.getY(), next.entity.getZ(), target.entity.getX(), target.entity.getY(), target.entity.getZ());
- final int randomTimeLeft = random.nextInt(heldItemStack.getItem().getUseDuration(heldItemStack) / 3);
+ final int randomTimeLeft = random.nextInt(heldItemStack.getItem().getUseDuration(heldItemStack, (LivingEntity)next.entity) / 3);
if (TurnBasedMinecraftMod.proxy.getConfig().isFreezeCombatantsEnabled()) {
next.yaw = yawDirection;
next.pitch = pitchDirection;
debugLog += " null";
sendMessageToAllPlayers(PacketBattleMessage.MessageType.USED_ITEM, next.entity.getId(), 0, PacketBattleMessage.UsedItemAction.USED_NOTHING.getValue());
break;
- } else if (targetItem.isEdible()) {
+ } else if (Utility.isItemEdible(targetItemStack, (LivingEntity)next.entity)) {
debugLog += " food";
sendMessageToAllPlayers(PacketBattleMessage.MessageType.USED_ITEM, next.entity.getId(), 0, PacketBattleMessage.UsedItemAction.USED_FOOD.getValue(), targetItemStack.getDisplayName().getString());
final Entity nextEntity = next.entity;
} else {
// then check vanilla foods
final CreativeModeTab foodAndDrinksTab = CreativeModeTabRegistry.getTab(CreativeModeTabs.FOOD_AND_DRINKS.location());
- if (foodAndDrinksTab.contains(targetItemStack) && targetItem.isEdible()) {
+ if (foodAndDrinksTab.contains(targetItemStack) && Utility.isItemEdible(targetItemStack, (LivingEntity)next.entity)) {
debugLog += " food";
sendMessageToAllPlayers(PacketBattleMessage.MessageType.USED_ITEM, next.entity.getId(), 0, PacketBattleMessage.UsedItemAction.USED_FOOD.getValue(), targetItemStack.getDisplayName().getString());
final Entity nextEntity = next.entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import net.neoforged.neoforge.common.NeoForge;
-import net.neoforged.neoforge.event.entity.living.LivingAttackEvent;
import net.neoforged.neoforge.event.entity.living.LivingChangeTargetEvent;
+import net.neoforged.neoforge.event.entity.living.LivingIncomingDamageEvent;
import net.neoforged.neoforge.network.PacketDistributor;
import org.apache.logging.log4j.Logger;
* @param event
* @return True if event should be canceled
*/
- public boolean checkAttack(final LivingAttackEvent event)
+ public boolean checkAttack(final LivingIncomingDamageEvent event)
{
Config config = TurnBasedMinecraftMod.proxy.getConfig();
String receiverClassName = event.getEntity().getClass().getName();
{
// Check if "player_only_battles" is enabled and if both entities are players.
if (TurnBasedMinecraftMod.proxy.getConfig().isPlayerOnlyBattlesEnabled() &&
- (!(event.getEntity() instanceof Player) || !(event.getNewTarget() instanceof Player))) {
+ (!(event.getEntity() instanceof Player) || !(event.getNewAboutToBeSetTarget() instanceof Player))) {
return;
}
String targetedCustomName;
try {
- targetedCustomName = event.getNewTarget().getCustomName().getString();
+ targetedCustomName = event.getNewAboutToBeSetTarget().getCustomName().getString();
} catch (NullPointerException e) {
targetedCustomName = null;
}
}
EntityInfo targetedInfo;
- if(event.getNewTarget() instanceof Player)
+ if(event.getNewAboutToBeSetTarget() instanceof Player)
{
targetedInfo = null;
}
targetedInfo = TurnBasedMinecraftMod.proxy.getConfig().getCustomEntityInfoReference(targetedCustomName);
if(targetedInfo == null)
{
- targetedInfo = TurnBasedMinecraftMod.proxy.getConfig().getMatchingEntityInfo(event.getNewTarget());
+ targetedInfo = TurnBasedMinecraftMod.proxy.getConfig().getMatchingEntityInfo(event.getNewAboutToBeSetTarget());
}
}
- if((event.getNewTarget() instanceof Player && ((Player)event.getNewTarget()).isCreative())
+ if((event.getNewAboutToBeSetTarget() instanceof Player && ((Player)event.getNewAboutToBeSetTarget()).isCreative())
|| attackerInfo == null
|| attackerInfo.ignoreBattle
|| TurnBasedMinecraftMod.proxy.getConfig().isIgnoreBattleType(attackerInfo.category)
if(attackerBattle != null && !attackerBattle.hasCombatant(event.getEntity().getId())) {
attackerBattle = null;
}
- Battle defenderBattle = battleMap.get(entityToBattleMap.get(new EntityIDDimPair(event.getNewTarget())));
- if(defenderBattle != null && !defenderBattle.hasCombatant(event.getNewTarget().getId())) {
+ Battle defenderBattle = battleMap.get(entityToBattleMap.get(new EntityIDDimPair(event.getNewAboutToBeSetTarget())));
+ if(defenderBattle != null && !defenderBattle.hasCombatant(event.getNewAboutToBeSetTarget().getId())) {
defenderBattle = null;
}
return;
} else if(attackerBattle == null && defenderBattle == null) {
// neither in battle
- if(event.getEntity() instanceof Player || event.getNewTarget() instanceof Player)
+ if(event.getEntity() instanceof Player || event.getNewAboutToBeSetTarget() instanceof Player)
{
// at least one is a player, create battle
Collection<Entity> sideA = new ArrayList<Entity>(1);
Collection<Entity> sideB = new ArrayList<Entity>(1);
sideA.add(event.getEntity());
- sideB.add(event.getNewTarget());
+ sideB.add(event.getNewAboutToBeSetTarget());
createBattle(sideA, sideB, event.getEntity().level().dimension());
logger.debug("neither in battle, at least one is player, creating new battle");
}
// battle max reached, cannot add to battle
return;
} else if (attackerBattle.hasCombatantInSideA(event.getEntity().getId())) {
- attackerBattle.addCombatantToSideB(event.getNewTarget());
+ attackerBattle.addCombatantToSideB(event.getNewAboutToBeSetTarget());
} else {
- attackerBattle.addCombatantToSideA(event.getNewTarget());
+ attackerBattle.addCombatantToSideA(event.getNewAboutToBeSetTarget());
}
- entityToBattleMap.put(new EntityIDDimPair(event.getNewTarget()), attackerBattle.getId());
+ entityToBattleMap.put(new EntityIDDimPair(event.getNewAboutToBeSetTarget()), attackerBattle.getId());
} else {
if (defenderBattle.getSize() >= TurnBasedMinecraftMod.proxy.getConfig().getMaxInBattle()) {
// battle max reached, cannot add to battle
return;
- } else if (defenderBattle.hasCombatantInSideA(event.getNewTarget().getId())) {
+ } else if (defenderBattle.hasCombatantInSideA(event.getNewAboutToBeSetTarget().getId())) {
defenderBattle.addCombatantToSideB(event.getEntity());
} else {
defenderBattle.addCombatantToSideA(event.getEntity());
c.time = System.nanoTime();
Config config = TurnBasedMinecraftMod.proxy.getConfig();
if(c.entity instanceof ServerPlayer) {
- PacketDistributor.PLAYER.with((ServerPlayer)c.entity).send(new PacketGeneralMessage("You just left battle! " + config.getLeaveBattleCooldownSeconds() + " seconds until you can attack/be-attacked again!"));
+ PacketDistributor.sendToPlayer((ServerPlayer)c.entity, new PacketGeneralMessage("You just left battle! " + config.getLeaveBattleCooldownSeconds() + " seconds until you can attack/be-attacked again!"));
}
recentlyLeftBattle.put(c.entity.getId(), c);
entityToBattleMap.remove(new EntityIDDimPair(c.entity));
iter.remove();
if(entry.getValue().entity instanceof ServerPlayer)
{
- PacketDistributor.PLAYER.with((ServerPlayer)entry.getValue().entity).send(new PacketGeneralMessage("Timer ended, you can now attack/be-attacked again."));
+ PacketDistributor.sendToPlayer((ServerPlayer)entry.getValue().entity, new PacketGeneralMessage("Timer ended, you can now attack/be-attacked again."));
}
}
}
import net.neoforged.bus.api.SubscribeEvent;
-import net.neoforged.neoforge.event.TickEvent;
+import net.neoforged.neoforge.event.tick.ServerTickEvent;
import java.util.concurrent.atomic.AtomicBoolean;
}
@SubscribeEvent
- public void update(TickEvent.ServerTickEvent tickEvent) {
- if(tickEvent.phase != TickEvent.Phase.START && isRunning.get() && ++tick > tickLimit) {
+ public void update(ServerTickEvent.Post tickEvent) {
+ //if(tickEvent.phase != TickEvent.Phase.START && isRunning.get() && ++tick > tickLimit) {
+ if(isRunning.get() && ++tick > tickLimit) {
tick = 0;
manager.battleMap.entrySet().removeIf(entry -> entry.getValue().update());
manager.updateRecentlyLeftBattle();
package com.burnedkirby.TurnBasedMinecraft.common;
-import java.util.Comparator;
-
+import net.minecraft.world.effect.MobEffectInstance;
+import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
-import net.minecraft.world.effect.MobEffectInstance;
-import net.minecraft.world.effect.MobEffects;
+
+import java.util.Comparator;
public class Combatant
{
package com.burnedkirby.TurnBasedMinecraft.common;
+import io.netty.buffer.ByteBuf;
import net.minecraft.network.chat.Component;
+import net.minecraft.network.codec.ByteBufCodecs;
+import net.minecraft.network.codec.StreamCodec;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
-import net.neoforged.neoforge.network.handling.PlayPayloadContext;
+import net.neoforged.neoforge.network.handling.IPayloadContext;
import net.neoforged.neoforge.server.ServerLifecycleHooks;
import org.apache.logging.log4j.Logger;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
public class CommonProxy
{
return ServerLifecycleHooks.getCurrentServer().getLevel(dim).getEntity(id);
}
- public <MSG> void handlePacket(final MSG msg, final PlayPayloadContext ctx) {}
+ public <MSG> void handlePacket(final MSG msg, final IPayloadContext ctx) {}
+
+ public static final StreamCodec<ByteBuf, Collection<Integer>> COLLECTION_INT_CODEC = ByteBufCodecs.INT.apply(ByteBufCodecs.collection(ArrayList::new));
+
+ public void showClientConfigGui() {}
}
package com.burnedkirby.TurnBasedMinecraft.common;
-import java.io.*;
-import java.time.LocalDateTime;
-import java.time.format.DateTimeFormatter;
-import java.util.*;
-
import com.electronwill.nightconfig.core.file.CommentedFileConfig;
+import com.electronwill.nightconfig.core.file.FileConfig;
import com.electronwill.nightconfig.toml.TomlFormat;
import net.minecraft.core.registries.Registries;
import net.minecraft.data.registries.VanillaRegistries;
import org.apache.logging.log4j.Logger;
-import com.electronwill.nightconfig.core.file.FileConfig;
+import java.io.*;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.*;
public class Config
{
import com.burnedkirby.TurnBasedMinecraft.common.networking.PacketGeneralMessage;
import net.minecraft.server.level.ServerPlayer;
-import net.neoforged.neoforge.event.entity.EntityTravelToDimensionEvent;
import net.neoforged.bus.api.SubscribeEvent;
+import net.neoforged.neoforge.event.entity.EntityTravelToDimensionEvent;
import net.neoforged.neoforge.network.PacketDistributor;
public class DimensionChangedHandler {
}
if(TurnBasedMinecraftMod.proxy.getBattleManager().forceLeaveBattle(new EntityIDDimPair(event.getEntity()))
&& event.getEntity() instanceof ServerPlayer) {
- PacketDistributor.PLAYER.with((ServerPlayer)event.getEntity()).send(new PacketGeneralMessage("Left battle due to moving to a different dimension"));
+ PacketDistributor.sendToPlayer((ServerPlayer)event.getEntity(), new PacketGeneralMessage("Left battle due to moving to a different dimension"));
}
}
}
package com.burnedkirby.TurnBasedMinecraft.common;
+import io.netty.buffer.ByteBuf;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.LivingEntity;
+import java.nio.charset.StandardCharsets;
+
public class EntityInfo
{
public Class classType;
{
if(this == FIRE)
{
- entity.setSecondsOnFire(duration / 20);
+ entity.setRemainingFireTicks(duration / 2);
return;
}
else if(this != UNKNOWN)
decisionFlee = 10;
customName = new String();
}
+
+ public EntityInfo(Class classType, boolean ignoreBattle, int attackPower, int attackProbability, int attackVariance,
+ Effect attackEffect, int attackEffectProbability, int defenseDamage, int defenseDamageProbability,
+ int evasion, int speed, String category, int decisionAttack, int decisionDefend, int decisionFlee,
+ String customName) {
+ this.classType = classType;
+ this.ignoreBattle = ignoreBattle;
+ this.attackPower = attackPower;
+ this.attackProbability = attackProbability;
+ this.attackVariance = attackVariance;
+ this.attackEffect = attackEffect;
+ this.attackEffectProbability = attackEffectProbability;
+ this.defenseDamage = defenseDamage;
+ this.defenseDamageProbability = defenseDamageProbability;
+ this.evasion = evasion;
+ this.speed = speed;
+ this.category = category;
+ this.decisionAttack = decisionAttack;
+ this.decisionDefend = decisionDefend;
+ this.decisionFlee = decisionFlee;
+ this.customName = customName;
+ }
public EntityInfo clone()
{
newEntityInfo.customName = new String(customName);
return newEntityInfo;
}
+
+ public EntityInfo(ByteBuf buffer) {
+ int name_bytes_len = buffer.readInt();
+ if (name_bytes_len > 0) {
+ ByteBuf name_bytes = buffer.readBytes(name_bytes_len);
+ try {
+ classType = Class.forName(name_bytes.toString(StandardCharsets.UTF_8));
+ } catch (ClassNotFoundException e) {
+ TurnBasedMinecraftMod.logger.warn("Failed to decode EntityInfo.classType", e);
+ classType = null;
+ }
+ } else {
+ classType = null;
+ }
+
+ ignoreBattle = buffer.readBoolean();
+ attackPower = buffer.readInt();
+ attackProbability = buffer.readInt();
+ attackVariance = buffer.readInt();
+
+ int effect_len = buffer.readInt();
+ ByteBuf effect_bytes = buffer.readBytes(effect_len);
+ attackEffect = Effect.fromString(effect_bytes.toString(StandardCharsets.UTF_8));
+
+ attackEffectProbability = buffer.readInt();
+ defenseDamage = buffer.readInt();
+ defenseDamageProbability = buffer.readInt();
+ evasion = buffer.readInt();
+ speed = buffer.readInt();
+
+ int category_len = buffer.readInt();
+ ByteBuf category_bytes = buffer.readBytes(category_len);
+ category = category_bytes.toString(StandardCharsets.UTF_8);
+
+ decisionAttack = buffer.readInt();
+ decisionDefend = buffer.readInt();
+ decisionFlee = buffer.readInt();
+
+ int custom_len = buffer.readInt();
+ if (custom_len > 0) {
+ ByteBuf custom_bytes = buffer.readBytes(custom_len);
+ customName = custom_bytes.toString(StandardCharsets.UTF_8);
+ } else {
+ customName = "";
+ }
+ }
+
+ public void encode(ByteBuf buffer) {
+ if (classType == null) {
+ buffer.writeInt(0);
+ } else {
+ String name = classType.getName();
+ byte[] name_bytes = name.getBytes(StandardCharsets.UTF_8);
+ buffer.writeInt(name_bytes.length);
+ buffer.writeBytes(name_bytes);
+ }
+
+ buffer.writeBoolean(ignoreBattle);
+ buffer.writeInt(attackPower);
+ buffer.writeInt(attackProbability);
+ buffer.writeInt(attackVariance);
+
+ String effect_name = attackEffect.toString();
+ byte[] effect_bytes = effect_name.getBytes(StandardCharsets.UTF_8);
+ buffer.writeInt(effect_bytes.length);
+ buffer.writeBytes(effect_bytes);
+
+ buffer.writeInt(attackEffectProbability);
+ buffer.writeInt(defenseDamage);
+ buffer.writeInt(defenseDamageProbability);
+ buffer.writeInt(evasion);
+ buffer.writeInt(speed);
+
+ byte[] category_bytes = category.getBytes(StandardCharsets.UTF_8);
+ buffer.writeInt(category_bytes.length);
+ buffer.writeBytes(category_bytes);
+
+ buffer.writeInt(decisionAttack);
+ buffer.writeInt(decisionDefend);
+ buffer.writeInt(decisionFlee);
+
+ if (customName.isEmpty()) {
+ buffer.writeInt(0);
+ } else {
+ byte[] custom_bytes = customName.getBytes(StandardCharsets.UTF_8);
+ buffer.writeInt(custom_bytes.length);
+ buffer.writeBytes(custom_bytes);
+ }
+ }
}
package com.burnedkirby.TurnBasedMinecraft.common;
import net.neoforged.bus.api.SubscribeEvent;
-import net.neoforged.neoforge.event.entity.living.LivingHurtEvent;
+import net.neoforged.neoforge.event.entity.living.LivingIncomingDamageEvent;
public class HurtEventHandler {
@SubscribeEvent
- public void handleHurtEvent(LivingHurtEvent event) {
+ public void handleHurtEvent(LivingIncomingDamageEvent event) {
CommonProxy proxy = TurnBasedMinecraftMod.proxy;
if (event.getEntity().level().isClientSide || proxy.getBattleManager() == null) {
return;
--- /dev/null
+package com.burnedkirby.TurnBasedMinecraft.common;
+
+import com.burnedkirby.TurnBasedMinecraft.client.ClientConfig;
+import com.burnedkirby.TurnBasedMinecraft.client.ClientConfigGui;
+import net.neoforged.api.distmarker.Dist;
+import net.neoforged.fml.ModContainer;
+import net.neoforged.fml.common.Mod;
+import net.neoforged.neoforge.client.gui.IConfigScreenFactory;
+
+@Mod(value = TurnBasedMinecraftMod.MODID, dist = Dist.CLIENT)
+public class TBMM_Client {
+ public TBMM_Client(ModContainer container) {
+ container.registerExtensionPoint(IConfigScreenFactory.class, ClientConfigGui::new);
+ }
+}
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
-import net.neoforged.bus.api.IEventBus;
import net.neoforged.bus.api.SubscribeEvent;
-import net.neoforged.fml.ModLoadingContext;
+import net.neoforged.fml.ModContainer;
+import net.neoforged.fml.common.Mod;
import net.neoforged.fml.config.ModConfig;
+import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent;
+import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent;
+import net.neoforged.fml.event.lifecycle.FMLDedicatedServerSetupEvent;
import net.neoforged.fml.loading.FMLEnvironment;
+import net.neoforged.neoforge.client.gui.IConfigScreenFactory;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.event.RegisterCommandsEvent;
import net.neoforged.neoforge.event.server.ServerStartingEvent;
import net.neoforged.neoforge.event.server.ServerStoppingEvent;
-import net.neoforged.fml.common.Mod;
-import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent;
-import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent;
-import net.neoforged.fml.event.lifecycle.FMLDedicatedServerSetupEvent;
-import net.neoforged.neoforge.network.event.RegisterPayloadHandlerEvent;
-import net.neoforged.neoforge.network.registration.IPayloadRegistrar;
import net.neoforged.neoforge.network.PacketDistributor;
+import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent;
+import net.neoforged.neoforge.network.registration.PayloadRegistrar;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class TurnBasedMinecraftMod {
public static final String MODID = "com_burnedkirby_turnbasedminecraft";
public static final String NAME = "Turn Based Minecraft Mod";
- public static final String VERSION = "1.26.0";
+ public static final String VERSION = "1.27.0";
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 MUSIC_BATTLE = MUSIC_ROOT + "battle/";
private static final String PROTOCOL_VERSION = Integer.toString(3);
- private static final ResourceLocation HANDLER_ID = new ResourceLocation(MODID, "main_channel");
+ private static final ResourceLocation HANDLER_ID = ResourceLocation.fromNamespaceAndPath(MODID, "main_channel");
protected static Logger logger = LogManager.getLogger();
public static ResourceLocation getNetResourceLocation() {
public static CommonProxy proxy;
- public TurnBasedMinecraftMod(IEventBus eventBus) {
- eventBus.addListener(this::firstInit);
- eventBus.addListener(this::secondInitClient);
- eventBus.addListener(this::secondInitServer);
- eventBus.addListener(this::registerNetwork);
+ public TurnBasedMinecraftMod(ModContainer container) {
+ container.getEventBus().addListener(this::firstInit);
+ container.getEventBus().addListener(this::secondInitClient);
+ container.getEventBus().addListener(this::secondInitServer);
+ container.getEventBus().addListener(this::registerNetwork);
NeoForge.EVENT_BUS.register(this);
- ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, ClientConfig.CLIENT_SPEC);
+ container.registerConfig(ModConfig.Type.CLIENT, ClientConfig.CLIENT_SPEC);
}
- private void registerNetwork(final RegisterPayloadHandlerEvent event) {
- final IPayloadRegistrar registrar = event.registrar(MODID);
+ private void registerNetwork(final RegisterPayloadHandlersEvent event) {
+ final PayloadRegistrar registrar = event.registrar(PROTOCOL_VERSION);
- registrar.play(PacketBattleDecision.ID, PacketBattleDecision::new, handler -> handler
- .server(PacketBattleDecision.PayloadHandler.getInstance()::handleData));
+ registrar.playToServer(PacketBattleDecision.TYPE, PacketBattleDecision.STREAM_CODEC, new PacketBattleDecision.PayloadHandler());
- registrar.play(PacketBattleInfo.ID, PacketBattleInfo::new, handler -> handler
- .client(PacketBattleInfo.PayloadHandler.getInstance()::handleData));
+ registrar.playToClient(PacketBattleInfo.TYPE, PacketBattleInfo.STREAM_CODEC, new PacketBattleInfo.PayloadHandler());
- registrar.play(PacketBattleMessage.ID, PacketBattleMessage::new, handler -> handler
- .client(PacketBattleMessage.PayloadHandler.getInstance()::handleData));
+ registrar.playToClient(PacketBattleMessage.TYPE, PacketBattleMessage.STREAM_CODEC, new PacketBattleMessage.PayloadHandler());
- registrar.play(PacketBattleRequestInfo.ID, PacketBattleRequestInfo::new, handler -> handler
- .server(PacketBattleRequestInfo.PayloadHandler.getInstance()::handleData));
+ registrar.playToServer(PacketBattleRequestInfo.TYPE, PacketBattleRequestInfo.STREAM_CODEC, new PacketBattleRequestInfo.PayloadHandler());
- registrar.play(PacketEditingMessage.ID, PacketEditingMessage::new, handler -> handler
- .client(PacketEditingMessage.PayloadHandler.getInstance()::handleData));
+ registrar.playToClient(PacketEditingMessage.TYPE, PacketEditingMessage.STREAM_CODEC, new PacketEditingMessage.PayloadHandler());
- registrar.play(PacketGeneralMessage.ID, PacketGeneralMessage::new, handler -> handler
- .client(PacketGeneralMessage.PayloadHandler.getInstance()::handleData));
+ registrar.playToClient(PacketGeneralMessage.TYPE, PacketGeneralMessage.STREAM_CODEC, new PacketGeneralMessage.PayloadHandler());
- registrar.play(PacketClientGUI.ID, PacketClientGUI::new, handler -> handler
- .client(PacketClientGUI.PayloadHandler.getInstance()::handleData));
+ registrar.playToClient(PacketClientGUI.TYPE, PacketClientGUI.STREAM_CODEC, new PacketClientGUI.PayloadHandler());
logger.debug("Register packets com_burnedkirby_turnbasedminecraft");
}
proxy.getConfig().setBattleDisabledForAll(true);
for (ServerPlayer player : c.getSource().getServer().getPlayerList().getPlayers()) {
proxy.getConfig().addBattleIgnoringPlayer(player.getId());
- PacketDistributor.PLAYER.with(player).send(new PacketGeneralMessage("OP disabled turn-based-combat for everyone"));
+ PacketDistributor.sendToPlayer(player, new PacketGeneralMessage("OP disabled turn-based-combat for everyone"));
+ PacketDistributor.sendToPlayer(player, new PacketGeneralMessage("OP disabled turn-based-combat for everyone"));
}
return 1;
}));
proxy.getConfig().setBattleDisabledForAll(false);
proxy.getConfig().clearBattleIgnoringPlayers();
for (ServerPlayer player : c.getSource().getServer().getPlayerList().getPlayers()) {
- PacketDistributor.PLAYER.with(player).send(new PacketGeneralMessage("OP enabled turn-based-combat for everyone"));
+ PacketDistributor.sendToPlayer(player, new PacketGeneralMessage("OP enabled turn-based-combat for everyone"));
}
return 1;
}));
.then(Commands.argument("targets", EntityArgument.players()).executes(c -> {
for (ServerPlayer player : EntityArgument.getPlayers(c, "targets")) {
proxy.getConfig().addBattleIgnoringPlayer(player.getId());
- PacketDistributor.PLAYER.with(player).send(new PacketGeneralMessage("OP enabled turn-based-combat for you"));
+ PacketDistributor.sendToPlayer(player, new PacketGeneralMessage("OP enabled turn-based-combat for you"));
c.getSource().sendSuccess(() -> Component.literal("Enabled turn-based-combat for " + player.getDisplayName().getString()), true);
}
return 1;
.then(Commands.argument("targets", EntityArgument.players()).executes(c -> {
for (ServerPlayer player : EntityArgument.getPlayers(c, "targets")) {
proxy.getConfig().removeBattleIgnoringPlayer(player.getId());
- PacketDistributor.PLAYER.with(player).send(new PacketGeneralMessage("OP disabled turn-based-combat for you"));
+ PacketDistributor.sendToPlayer(player, new PacketGeneralMessage("OP disabled turn-based-combat for you"));
c.getSource().sendSuccess(() -> Component.literal("Disabled turn-based-combat for " + player.getDisplayName().getString()), true);
}
return 1;
ServerPlayer player = c.getSource().getPlayerOrException();
EditingInfo editingInfo = proxy.getEditingInfo(player.getId());
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
proxy.setEditingPlayer(player);
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
logger.info("Begin editing TBM Entity for player \"" + player.getDisplayName().getString() + "\" (\"" + c.getSource().getDisplayName() + "\")");
}
return 1;
EditingInfo editingInfo = TurnBasedMinecraftMod.proxy.getEditingInfo(player.getId());
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
if (!proxy.getConfig().editEntityEntry(editingInfo.entityInfo)) {
- PacketDistributor.PLAYER.with(player).send(new PacketGeneralMessage("An error occurred while attempting to save an entry to the config"));
+ PacketDistributor.sendToPlayer(player, new PacketGeneralMessage("An error occurred while attempting to save an entry to the config"));
proxy.removeEditingInfo(player.getId());
} else {
proxy.removeEditingInfo(player.getId());
- PacketDistributor.PLAYER.with(player).send(new PacketGeneralMessage("Entity info saved in config and loaded."));
+ PacketDistributor.sendToPlayer(player, new PacketGeneralMessage("Entity info saved in config and loaded."));
}
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
EditingInfo editingInfo = TurnBasedMinecraftMod.proxy.getEditingInfo(player.getId());
if (editingInfo != null) {
proxy.removeEditingInfo(player.getId());
- PacketDistributor.PLAYER.with(player).send(new PacketGeneralMessage("Cancelled editing entry."));
+ PacketDistributor.sendToPlayer(player, new PacketGeneralMessage("Cancelled editing entry."));
}
return 1;
}))
Message exceptionMessage = new LiteralMessage("Invalid action for tbm-edit");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
proxy.setEditingPlayer(player);
proxy.getEditingInfo(player.getId()).isEditingCustomName = true;
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
logger.info("Begin editing custom TBM Entity for player \"" + player.getDisplayName().getString() + "\" (\"" + c.getSource().getDisplayName() + "\")");
}
return 1;
ServerPlayer player = c.getSource().getPlayerOrException();
EditingInfo editingInfo = TurnBasedMinecraftMod.proxy.getEditingInfo(player.getId());
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
ServerPlayer player = c.getSource().getPlayerOrException();
EditingInfo editingInfo = TurnBasedMinecraftMod.proxy.getEditingInfo(player.getId());
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.EDIT_IGNORE_BATTLE));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.EDIT_IGNORE_BATTLE));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
boolean ignoreBattle = BoolArgumentType.getBool(c, "ignoreBattle");
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
editingInfo.entityInfo.ignoreBattle = ignoreBattle;
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
ServerPlayer player = c.getSource().getPlayerOrException();
EditingInfo editingInfo = TurnBasedMinecraftMod.proxy.getEditingInfo(player.getId());
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.EDIT_ATTACK_POWER));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.EDIT_ATTACK_POWER));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
}
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
editingInfo.entityInfo.attackPower = attackPower;
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
ServerPlayer player = c.getSource().getPlayerOrException();
EditingInfo editingInfo = TurnBasedMinecraftMod.proxy.getEditingInfo(player.getId());
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.EDIT_ATTACK_PROBABILITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.EDIT_ATTACK_PROBABILITY));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
}
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
editingInfo.entityInfo.attackProbability = attackProbability;
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
ServerPlayer player = c.getSource().getPlayerOrException();
EditingInfo editingInfo = TurnBasedMinecraftMod.proxy.getEditingInfo(player.getId());
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.EDIT_ATTACK_VARIANCE));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.EDIT_ATTACK_VARIANCE));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
}
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
editingInfo.entityInfo.attackVariance = attackVariance;
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
ServerPlayer player = c.getSource().getPlayerOrException();
EditingInfo editingInfo = TurnBasedMinecraftMod.proxy.getEditingInfo(player.getId());
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.EDIT_ATTACK_EFFECT));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.EDIT_ATTACK_EFFECT));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
EntityInfo.Effect effect = EntityInfo.Effect.fromString(StringArgumentType.getString(c, "attackEffect"));
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
editingInfo.entityInfo.attackEffect = effect;
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
ServerPlayer player = c.getSource().getPlayerOrException();
EditingInfo editingInfo = TurnBasedMinecraftMod.proxy.getEditingInfo(player.getId());
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.EDIT_ATTACK_EFFECT_PROBABILITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.EDIT_ATTACK_EFFECT_PROBABILITY));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
}
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
editingInfo.entityInfo.attackEffectProbability = attackEffectProbability;
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
ServerPlayer player = c.getSource().getPlayerOrException();
EditingInfo editingInfo = TurnBasedMinecraftMod.proxy.getEditingInfo(player.getId());
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.EDIT_DEFENSE_DAMAGE));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.EDIT_DEFENSE_DAMAGE));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
}
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
editingInfo.entityInfo.defenseDamage = defenseDamage;
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
ServerPlayer player = c.getSource().getPlayerOrException();
EditingInfo editingInfo = TurnBasedMinecraftMod.proxy.getEditingInfo(player.getId());
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.EDIT_DEFENSE_DAMAGE_PROBABILITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.EDIT_DEFENSE_DAMAGE_PROBABILITY));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
}
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
editingInfo.entityInfo.defenseDamageProbability = defenseDamageProbability;
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
ServerPlayer player = c.getSource().getPlayerOrException();
EditingInfo editingInfo = TurnBasedMinecraftMod.proxy.getEditingInfo(player.getId());
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.EDIT_EVASION));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.EDIT_EVASION));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
}
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
editingInfo.entityInfo.evasion = evasion;
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
ServerPlayer player = c.getSource().getPlayerOrException();
EditingInfo editingInfo = TurnBasedMinecraftMod.proxy.getEditingInfo(player.getId());
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.EDIT_SPEED));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.EDIT_SPEED));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
}
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
editingInfo.entityInfo.speed = speed;
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
ServerPlayer player = c.getSource().getPlayerOrException();
EditingInfo editingInfo = TurnBasedMinecraftMod.proxy.getEditingInfo(player.getId());
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.EDIT_CATEGORY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.EDIT_CATEGORY));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
String category = StringArgumentType.getString(c, "category");
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
editingInfo.entityInfo.category = category;
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
ServerPlayer player = c.getSource().getPlayerOrException();
EditingInfo editingInfo = TurnBasedMinecraftMod.proxy.getEditingInfo(player.getId());
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.EDIT_DECISION_ATTACK));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.EDIT_DECISION_ATTACK));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
}
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
editingInfo.entityInfo.decisionAttack = decisionAttack;
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
ServerPlayer player = c.getSource().getPlayerOrException();
EditingInfo editingInfo = TurnBasedMinecraftMod.proxy.getEditingInfo(player.getId());
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.EDIT_DECISION_DEFEND));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.EDIT_DECISION_DEFEND));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
}
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
editingInfo.entityInfo.decisionDefend = decisionDefend;
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
ServerPlayer player = c.getSource().getPlayerOrException();
EditingInfo editingInfo = TurnBasedMinecraftMod.proxy.getEditingInfo(player.getId());
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.EDIT_DECISION_FLEE));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.EDIT_DECISION_FLEE));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
int decisionFlee = IntegerArgumentType.getInteger(c, "decisionFlee");
if (editingInfo != null && !editingInfo.isPendingEntitySelection) {
editingInfo.entityInfo.decisionFlee = decisionFlee;
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.PICK_EDIT, editingInfo.entityInfo));
} else if (editingInfo != null) {
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.ATTACK_ENTITY));
} else {
Message exceptionMessage = new LiteralMessage("Cannot edit entity without starting editing (use \"/tbm-edit\").");
throw new CommandSyntaxException(new SimpleCommandExceptionType(exceptionMessage), exceptionMessage);
.requires(c -> c.hasPermission(2))
.executes(c -> {
ServerPlayer player = c.getSource().getPlayerOrException();
- PacketDistributor.PLAYER.with(player).send(new PacketEditingMessage(PacketEditingMessage.Type.SERVER_EDIT));
+ PacketDistributor.sendToPlayer(player, new PacketEditingMessage(PacketEditingMessage.Type.SERVER_EDIT));
return 1;
})
.then(Commands.literal("leave_battle_cooldown").executes(c -> {
event.getDispatcher().register(
Commands.literal("tbm-client-edit").executes(c -> {
ServerPlayer player = c.getSource().getPlayerOrException();
- PacketDistributor.PLAYER.with(player).send(new PacketClientGUI());
+ PacketDistributor.sendToPlayer(player, new PacketClientGUI(0));
return 1;
})
);
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.Entity;
+import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ArrowItem;
+import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
+import javax.annotation.Nullable;
+
public class Utility
{
public static float yawDirection(double posX, double posZ, double targetX, double targetZ)
}
public static ResourceKey<Level> deserializeDimension(String dimString) {
- ResourceLocation dimRes = new ResourceLocation(dimString);
+ ResourceLocation dimRes = ResourceLocation.parse(dimString);
return ResourceKey.create(Registries.DIMENSION, dimRes);
}
+
+ public static boolean isItemEdible(ItemStack itemStack, @Nullable LivingEntity entity) {
+ return itemStack.getFoodProperties(entity) != null;
+ }
}
import com.burnedkirby.TurnBasedMinecraft.common.Battle;
import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod;
-import com.burnedkirby.TurnBasedMinecraft.common.Battle.Decision;
-
+import io.netty.buffer.ByteBuf;
import net.minecraft.network.chat.Component;
+import net.minecraft.network.codec.ByteBufCodecs;
+import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
-import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Player;
-import net.neoforged.neoforge.network.handling.PlayPayloadContext;
+import net.neoforged.neoforge.network.handling.IPayloadContext;
+import net.neoforged.neoforge.network.handling.IPayloadHandler;
+import org.jetbrains.annotations.NotNull;
-public class PacketBattleDecision implements CustomPacketPayload
+public record PacketBattleDecision(int battleID, int decision, int targetIDorItemID) implements CustomPacketPayload
{
- public static final ResourceLocation ID = new ResourceLocation(TurnBasedMinecraftMod.MODID, "network_packetbattledecision");
-
- private int battleID;
- private Battle.Decision decision;
- private int targetIDOrItemID;
-
- public PacketBattleDecision() {}
-
- public PacketBattleDecision(int battleID, Battle.Decision decision, int targetIDOrItemID)
- {
- this.battleID = battleID;
- this.decision = decision;
- this.targetIDOrItemID = targetIDOrItemID;
- }
-
- public PacketBattleDecision(final FriendlyByteBuf buf) {
- this.battleID = buf.readInt();
- this.decision = Decision.valueOf(buf.readInt());
- this.targetIDOrItemID = buf.readInt();
- }
+ public static final CustomPacketPayload.Type<PacketBattleDecision> TYPE = new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(TurnBasedMinecraftMod.MODID, "network_packetbattledecision"));
+
+ public static final StreamCodec<ByteBuf, PacketBattleDecision> STREAM_CODEC = StreamCodec.composite(
+ ByteBufCodecs.INT,
+ PacketBattleDecision::battleID,
+ ByteBufCodecs.VAR_INT,
+ PacketBattleDecision::decision,
+ ByteBufCodecs.INT,
+ PacketBattleDecision::targetIDorItemID,
+ PacketBattleDecision::new
+ );
@Override
- public void write(FriendlyByteBuf buf) {
- buf.writeInt(battleID);
- buf.writeInt(decision.getValue());
- buf.writeInt(targetIDOrItemID);
+ public Type<? extends CustomPacketPayload> type() {
+ return TYPE;
}
- @Override
- public ResourceLocation id() {
- return ID;
- }
-
- public static class PayloadHandler {
- private static final PayloadHandler INSTANCE = new PayloadHandler();
-
- public static PayloadHandler getInstance() {
- return INSTANCE;
- }
-
- public void handleData(final PacketBattleDecision pkt, final PlayPayloadContext ctx) {
- ctx.workHandler().submitAsync(() -> {
- Battle b = TurnBasedMinecraftMod.proxy.getBattleManager().getBattleByID(pkt.battleID);
- if(b != null)
- {
- Player player = ctx.player().get();
- b.setDecision(player.getId(), pkt.decision, pkt.targetIDOrItemID);
- }
- }).exceptionally(e -> {
- ctx.packetHandler().disconnect(Component.literal("Exception handling PacketBattleDecision! " + e.getMessage()));
- return null;
- });
+ public static class PayloadHandler implements IPayloadHandler<PacketBattleDecision> {
+ @Override
+ public void handle(final @NotNull PacketBattleDecision pkt, final IPayloadContext ctx) {
+ ctx.enqueueWork(() -> {
+ Battle b = TurnBasedMinecraftMod.proxy.getBattleManager().getBattleByID(pkt.battleID);
+ if(b != null) {
+ Player player = ctx.player();
+ b.setDecision(player.getId(), Battle.Decision.valueOf(pkt.decision), pkt.targetIDorItemID);
+ }
+ }).exceptionally(e -> {
+ ctx.disconnect(Component.literal("Exception handling PacketBattleDecision! " + e.getMessage()));
+ return null;
+ });
}
}
}
package com.burnedkirby.TurnBasedMinecraft.common.networking;
-import java.util.ArrayList;
-import java.util.Collection;
-
+import com.burnedkirby.TurnBasedMinecraft.common.CommonProxy;
import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod;
-
+import io.netty.buffer.ByteBuf;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
+import net.minecraft.network.codec.ByteBufCodecs;
+import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.Entity;
-import net.minecraft.network.FriendlyByteBuf;
-import net.neoforged.neoforge.network.handling.PlayPayloadContext;
-
-public class PacketBattleInfo implements CustomPacketPayload
-{
- public static final ResourceLocation ID = new ResourceLocation(TurnBasedMinecraftMod.MODID, "network_packetbattleinfo");
- private Collection<Integer> sideA;
- private Collection<Integer> sideB;
- private long decisionNanos;
+import net.neoforged.neoforge.network.handling.IPayloadContext;
+import net.neoforged.neoforge.network.handling.IPayloadHandler;
+import org.jetbrains.annotations.NotNull;
- private long maxDecisionNanos;
- private boolean turnTimerEnabled;
-
- public PacketBattleInfo()
- {
- sideA = new ArrayList<Integer>();
- sideB = new ArrayList<Integer>();
- decisionNanos = TurnBasedMinecraftMod.proxy.getConfig().getDecisionDurationNanos();
- maxDecisionNanos = decisionNanos;
- turnTimerEnabled = false;
- }
-
- public PacketBattleInfo(Collection<Integer> sideA, Collection<Integer> sideB, long decisionNanos, long maxDecisionNanos, boolean turnTimerEnabled)
- {
- this.sideA = sideA;
- this.sideB = sideB;
- this.decisionNanos = decisionNanos;
- this.maxDecisionNanos = maxDecisionNanos;
- this.turnTimerEnabled = turnTimerEnabled;
- }
+import java.util.Collection;
- public PacketBattleInfo(final FriendlyByteBuf buf) {
- int sideACount = buf.readInt();
- int sideBCount = buf.readInt();
- this.sideA = new ArrayList<>(sideACount);
- this.sideB = new ArrayList<>(sideBCount);
- for (int i = 0; i < sideACount; ++i) {
- this.sideA.add(buf.readInt());
- }
- for (int i = 0; i < sideBCount; ++i) {
- this.sideB.add(buf.readInt());
- }
- this.decisionNanos = buf.readLong();
- this.maxDecisionNanos = buf.readLong();
- this.turnTimerEnabled = buf.readBoolean();
- }
+public record PacketBattleInfo(Collection<Integer> sideA, Collection<Integer> sideB, long decisionNanos, long maxDecisionNanos, boolean turnTimerEnabled) implements CustomPacketPayload
+{
+ public static final CustomPacketPayload.Type<PacketBattleInfo> TYPE = new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(TurnBasedMinecraftMod.MODID, "network_packetbattleinfo"));
- @Override
- public void write(FriendlyByteBuf 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);
- buf.writeLong(maxDecisionNanos);
- buf.writeBoolean(turnTimerEnabled);
- }
+ public static final StreamCodec<ByteBuf, PacketBattleInfo> STREAM_CODEC = StreamCodec.composite(
+ CommonProxy.COLLECTION_INT_CODEC,
+ PacketBattleInfo::sideA,
+ CommonProxy.COLLECTION_INT_CODEC,
+ PacketBattleInfo::sideB,
+ ByteBufCodecs.VAR_LONG,
+ PacketBattleInfo::decisionNanos,
+ ByteBufCodecs.VAR_LONG,
+ PacketBattleInfo::maxDecisionNanos,
+ ByteBufCodecs.BOOL,
+ PacketBattleInfo::turnTimerEnabled,
+ PacketBattleInfo::new
+ );
@Override
- public ResourceLocation id() {
- return ID;
+ public Type<? extends CustomPacketPayload> type() {
+ return TYPE;
}
- public static class PayloadHandler {
- private static final PayloadHandler INSTANCE = new PayloadHandler();
-
- public static PayloadHandler getInstance() {
- return INSTANCE;
- }
-
- public void handleData(final PacketBattleInfo pkt, final PlayPayloadContext ctx) {
- ctx.workHandler().submitAsync(() -> {
+ public static class PayloadHandler implements IPayloadHandler<PacketBattleInfo> {
+ @Override
+ public void handle(final @NotNull PacketBattleInfo pkt, final IPayloadContext ctx) {
+ ctx.enqueueWork(() -> {
if(TurnBasedMinecraftMod.proxy.getLocalBattle() == null)
{
return;
TurnBasedMinecraftMod.proxy.setBattleGuiTurnTimerEnabled(pkt.turnTimerEnabled);
TurnBasedMinecraftMod.proxy.setBattleGuiTurnTimerMax((int)(pkt.maxDecisionNanos / 1000000000L));
}).exceptionally(e -> {
- ctx.packetHandler().disconnect(Component.literal("Exception handling PacketBattleInfo! " + e.getMessage()));
+ ctx.disconnect(Component.literal("Exception handling PacketBattleInfo! " + e.getMessage()));
return null;
});
}
package com.burnedkirby.TurnBasedMinecraft.common.networking;
-import java.util.HashMap;
-import java.util.Map;
-
import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod;
-
import com.burnedkirby.TurnBasedMinecraft.common.Utility;
-import net.minecraft.network.FriendlyByteBuf;
+import io.netty.buffer.ByteBuf;
import net.minecraft.network.chat.Component;
+import net.minecraft.network.codec.ByteBufCodecs;
+import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.Level;
import net.neoforged.fml.loading.FMLEnvironment;
-import net.neoforged.neoforge.network.handling.PlayPayloadContext;
+import net.neoforged.neoforge.network.handling.IPayloadContext;
+import net.neoforged.neoforge.network.handling.IPayloadHandler;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.HashMap;
+import java.util.Map;
public class PacketBattleMessage implements CustomPacketPayload
{
- public static final ResourceLocation ID = new ResourceLocation(TurnBasedMinecraftMod.MODID, "network_packetbattlemessage");
-
- @Override
- public void write(FriendlyByteBuf buf) {
- buf.writeInt(messageType.getValue());
- buf.writeInt(entityIDFrom);
- buf.writeInt(entityIDTo);
- buf.writeUtf(Utility.serializeDimension(dimension));
- buf.writeInt(amount);
- buf.writeUtf(custom);
- }
+ public static final CustomPacketPayload.Type<PacketBattleMessage> TYPE = new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(TurnBasedMinecraftMod.MODID, "network_packetbattlemessage"));
+
+ public static final StreamCodec<ByteBuf, PacketBattleMessage> STREAM_CODEC = StreamCodec.composite(
+ ByteBufCodecs.VAR_INT.map(MessageType::valueOf, MessageType::getValue),
+ PacketBattleMessage::getMessageType,
+ ByteBufCodecs.INT,
+ PacketBattleMessage::getEntityIDFrom,
+ ByteBufCodecs.INT,
+ PacketBattleMessage::getEntityIDTo,
+ ByteBufCodecs.STRING_UTF8.map(Utility::deserializeDimension, Utility::serializeDimension),
+ PacketBattleMessage::getDimension,
+ ByteBufCodecs.INT,
+ PacketBattleMessage::getAmount,
+ ByteBufCodecs.STRING_UTF8,
+ PacketBattleMessage::getCustom,
+ PacketBattleMessage::new
+ );
@Override
- public ResourceLocation id() {
- return ID;
+ public Type<? extends CustomPacketPayload> type() {
+ return TYPE;
}
public enum MessageType
public ResourceKey<Level> getDimension() {
return dimension;
}
+
+ public String getDimensionSerialized() {
+ return Utility.serializeDimension(dimension);
+ }
+
public PacketBattleMessage() { custom = new String(); }
public PacketBattleMessage(MessageType messageType, int entityIDFrom, int entityIDTo, ResourceKey<Level> dimension, int amount)
this.custom = custom;
}
- public PacketBattleMessage(final FriendlyByteBuf buf) {
- this.messageType = MessageType.valueOf(buf.readInt());
- this.entityIDFrom = buf.readInt();
- this.entityIDTo = buf.readInt();
- this.dimension = Utility.deserializeDimension(buf.readUtf());
- this.amount = buf.readInt();
- this.custom = buf.readUtf();
- }
-
- public static class PayloadHandler {
- private static final PayloadHandler INSTANCE = new PayloadHandler();
-
- public static PayloadHandler getInstance() {
- return INSTANCE;
- }
-
- public void handleData(final PacketBattleMessage pkt, final PlayPayloadContext ctx) {
- ctx.workHandler().submitAsync(() -> {
+ public static class PayloadHandler implements IPayloadHandler<PacketBattleMessage> {
+ @Override
+ public void handle(final @NotNull PacketBattleMessage pkt, final IPayloadContext ctx) {
+ ctx.enqueueWork(() -> {
if (FMLEnvironment.dist.isClient()) {
TurnBasedMinecraftMod.proxy.handlePacket(pkt, ctx);
}
}).exceptionally(e -> {
- ctx.packetHandler().disconnect(Component.literal("Exception handling PacketBattleMessage! " + e.getMessage()));
+ ctx.disconnect(Component.literal("Exception handling PacketBattleMessage! " + e.getMessage()));
return null;
});
}
import com.burnedkirby.TurnBasedMinecraft.common.Battle;
import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod;
-
-import net.minecraft.network.FriendlyByteBuf;
+import io.netty.buffer.ByteBuf;
import net.minecraft.network.chat.Component;
+import net.minecraft.network.codec.ByteBufCodecs;
+import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
-import net.neoforged.neoforge.network.handling.PlayPayloadContext;
+import net.neoforged.neoforge.network.handling.IPayloadContext;
+import net.neoforged.neoforge.network.handling.IPayloadHandler;
+import org.jetbrains.annotations.NotNull;
-public class PacketBattleRequestInfo implements CustomPacketPayload
+public record PacketBattleRequestInfo(int battleID) implements CustomPacketPayload
{
- public static final ResourceLocation ID = new ResourceLocation(TurnBasedMinecraftMod.MODID, "network_packetbattlerequestinfo");
+ public static final CustomPacketPayload.Type<PacketBattleRequestInfo> TYPE = new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(TurnBasedMinecraftMod.MODID, "network_packetbattlerequestinfo"));
+
+ public static final StreamCodec<ByteBuf, PacketBattleRequestInfo> STREAM_CODEC = StreamCodec.composite(
+ ByteBufCodecs.INT,
+ PacketBattleRequestInfo::battleID,
+ PacketBattleRequestInfo::new
+ );
- private int battleID;
-
- public PacketBattleRequestInfo() {}
-
public PacketBattleRequestInfo(int battleID)
{
this.battleID = battleID;
}
- public PacketBattleRequestInfo(final FriendlyByteBuf buf) {
- battleID = buf.readInt();
- }
-
- @Override
- public void write(FriendlyByteBuf buf) {
- buf.writeInt(battleID);
- }
-
@Override
- public ResourceLocation id() {
- return ID;
+ public Type<? extends CustomPacketPayload> type() {
+ return TYPE;
}
- public static class PayloadHandler {
- private static final PayloadHandler INSTANCE = new PayloadHandler();
-
- public static PayloadHandler getInstance() {
- return INSTANCE;
- }
-
- public void handleData(final PacketBattleRequestInfo pkt, final PlayPayloadContext ctx) {
- ctx.workHandler().submitAsync(() -> {
+ public static class PayloadHandler implements IPayloadHandler<PacketBattleRequestInfo> {
+ @Override
+ public void handle(final @NotNull PacketBattleRequestInfo pkt, final IPayloadContext ctx) {
+ ctx.enqueueWork(() -> {
Battle b = TurnBasedMinecraftMod.proxy.getBattleManager().getBattleByID(pkt.battleID);
if(b == null) {
return;
}
- ctx.replyHandler().send(new PacketBattleInfo(
- b.getSideAIDs(),
- b.getSideBIDs(),
- b.getTimerNanos(),
- TurnBasedMinecraftMod.proxy.getConfig().getDecisionDurationNanos(),
- !TurnBasedMinecraftMod.proxy.getConfig().isBattleDecisionDurationForever()));
+ ctx.reply(new PacketBattleInfo(
+ b.getSideAIDs(),
+ b.getSideBIDs(),
+ b.getTimerNanos(),
+ TurnBasedMinecraftMod.proxy.getConfig().getDecisionDurationNanos(),
+ !TurnBasedMinecraftMod.proxy.getConfig().isBattleDecisionDurationForever()));
}).exceptionally(e -> {
- ctx.packetHandler().disconnect(Component.literal("Exception handling PacketBattleRequestInfo! " + e.getMessage()));
+ ctx.disconnect(Component.literal("Exception handling PacketBattleRequestInfo! " + e.getMessage()));
return null;
});
}
package com.burnedkirby.TurnBasedMinecraft.common.networking;
-import com.burnedkirby.TurnBasedMinecraft.client.ClientConfig;
import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod;
-import net.minecraft.client.Minecraft;
-import net.minecraft.network.FriendlyByteBuf;
+import io.netty.buffer.ByteBuf;
import net.minecraft.network.chat.Component;
+import net.minecraft.network.codec.ByteBufCodecs;
+import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.neoforged.fml.loading.FMLEnvironment;
-import net.neoforged.neoforge.network.handling.PlayPayloadContext;
+import net.neoforged.neoforge.network.handling.IPayloadContext;
+import net.neoforged.neoforge.network.handling.IPayloadHandler;
+import org.jetbrains.annotations.NotNull;
-public class PacketClientGUI implements CustomPacketPayload {
- public static final ResourceLocation ID = new ResourceLocation(TurnBasedMinecraftMod.MODID, "network_packetclientgui");
+public record PacketClientGUI(int reserved) implements CustomPacketPayload {
+ public static final CustomPacketPayload.Type<PacketClientGUI> TYPE = new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(TurnBasedMinecraftMod.MODID, "network_packetclientgui"));
- int reserved;
-
- public PacketClientGUI() {
- reserved = 0;
- }
-
- public PacketClientGUI(FriendlyByteBuf buf) {
- reserved = buf.readInt();
- }
+ public static final StreamCodec<ByteBuf, PacketClientGUI> STREAM_CODEC = StreamCodec.composite(
+ ByteBufCodecs.VAR_INT,
+ PacketClientGUI::reserved,
+ PacketClientGUI::new
+ );
@Override
- public void write(FriendlyByteBuf buf) {
- buf.writeInt(0);
+ public Type<? extends CustomPacketPayload> type() {
+ return TYPE;
}
- @Override
- public ResourceLocation id() {
- return ID;
- }
-
- public static class PayloadHandler {
- private static final PayloadHandler INSTANCE = new PayloadHandler();
-
- public static PayloadHandler getInstance() { return INSTANCE; }
-
- public void handleData(final PacketClientGUI pkt, final PlayPayloadContext ctx) {
- ctx.workHandler().submitAsync(() -> {
+ public static class PayloadHandler implements IPayloadHandler<PacketClientGUI> {
+ @Override
+ public void handle(final @NotNull PacketClientGUI pkt, final IPayloadContext ctx) {
+ ctx.enqueueWork(() -> {
if (FMLEnvironment.dist.isClient()) {
- Minecraft.getInstance().setScreen(new ClientConfig.CliConfGui());
+ TurnBasedMinecraftMod.proxy.showClientConfigGui();
}
}).exceptionally(e -> {
- ctx.packetHandler().disconnect(Component.literal("Exception handling PacketClientGUI! " + e.getMessage()));
+ ctx.disconnect(Component.literal("Exception handling PacketClientGUI! " + e.getMessage()));
return null;
});
}
import com.burnedkirby.TurnBasedMinecraft.common.EntityInfo;
import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod;
+import io.netty.buffer.ByteBuf;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
+import net.minecraft.network.codec.ByteBufCodecs;
+import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.neoforged.fml.loading.FMLEnvironment;
-import net.neoforged.neoforge.network.handling.PlayPayloadContext;
+import net.neoforged.neoforge.network.handling.IPayloadContext;
+import net.neoforged.neoforge.network.handling.IPayloadHandler;
+import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
public class PacketEditingMessage implements CustomPacketPayload
{
- public static final ResourceLocation ID = new ResourceLocation(TurnBasedMinecraftMod.MODID, "network_packeteditingmessage");
+ public static final CustomPacketPayload.Type<PacketEditingMessage> TYPE = new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(TurnBasedMinecraftMod.MODID, "network_packeteditingmessage"));
- @Override
- public void write(FriendlyByteBuf buf) {
- buf.writeInt(type.getValue());
- if(entityInfo.classType != null) {
- buf.writeUtf(entityInfo.classType.getName());
- } else {
- buf.writeUtf("unknown");
- }
- buf.writeBoolean(entityInfo.ignoreBattle);
- buf.writeInt(entityInfo.attackPower);
- buf.writeInt(entityInfo.attackProbability);
- buf.writeInt(entityInfo.attackVariance);
- buf.writeUtf(entityInfo.attackEffect.toString());
- buf.writeInt(entityInfo.attackEffectProbability);
- buf.writeInt(entityInfo.defenseDamage);
- buf.writeInt(entityInfo.defenseDamageProbability);
- buf.writeInt(entityInfo.evasion);
- buf.writeInt(entityInfo.speed);
- buf.writeUtf(entityInfo.category);
- buf.writeInt(entityInfo.decisionAttack);
- buf.writeInt(entityInfo.decisionDefend);
- buf.writeInt(entityInfo.decisionFlee);
- buf.writeUtf(entityInfo.customName);
- }
+ public static final StreamCodec<ByteBuf, PacketEditingMessage> STREAM_CODEC = StreamCodec.composite(
+ ByteBufCodecs.INT.map(Type::valueOf, Type::getValue),
+ PacketEditingMessage::getType,
+ StreamCodec.ofMember(EntityInfo::encode, EntityInfo::new),
+ PacketEditingMessage::getEntityInfo,
+ PacketEditingMessage::new
+ );
@Override
- public ResourceLocation id() {
- return ID;
+ public CustomPacketPayload.Type<? extends CustomPacketPayload> type() {
+ return TYPE;
}
public enum Type
this.entityInfo.customName = buf.readUtf();
}
- public static class PayloadHandler {
- private static final PayloadHandler INSTANCE = new PayloadHandler();
-
- public static PayloadHandler getInstance() {
- return INSTANCE;
- }
-
- public void handleData(final PacketEditingMessage pkt, final PlayPayloadContext ctx) {
- ctx.workHandler().submitAsync(() -> {
+ public static class PayloadHandler implements IPayloadHandler<PacketEditingMessage> {
+ @Override
+ public void handle(final @NotNull PacketEditingMessage pkt, final IPayloadContext ctx) {
+ ctx.enqueueWork(() -> {
if (FMLEnvironment.dist.isClient()) {
TurnBasedMinecraftMod.proxy.handlePacket(pkt, ctx);
}
}).exceptionally(e -> {
- ctx.packetHandler().disconnect(Component.literal("Exception handling PacketEditingMessage! " + e.getMessage()));
+ ctx.disconnect(Component.literal("Exception handling PacketEditingMessage! " + e.getMessage()));
return null;
});
}
package com.burnedkirby.TurnBasedMinecraft.common.networking;
import com.burnedkirby.TurnBasedMinecraft.common.TurnBasedMinecraftMod;
-
-import net.minecraft.network.FriendlyByteBuf;
+import io.netty.buffer.ByteBuf;
import net.minecraft.network.chat.Component;
+import net.minecraft.network.codec.ByteBufCodecs;
+import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.neoforged.fml.loading.FMLEnvironment;
-import net.neoforged.neoforge.network.handling.PlayPayloadContext;
+import net.neoforged.neoforge.network.handling.IPayloadContext;
+import net.neoforged.neoforge.network.handling.IPayloadHandler;
+import org.jetbrains.annotations.NotNull;
-public class PacketGeneralMessage implements CustomPacketPayload
+public record PacketGeneralMessage(String message) implements CustomPacketPayload
{
- public static final ResourceLocation ID = new ResourceLocation(TurnBasedMinecraftMod.MODID, "network_packetgeneralmessage");
+ public static final CustomPacketPayload.Type<PacketGeneralMessage> TYPE = new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(TurnBasedMinecraftMod.MODID, "network_packetgeneralmessage"));
- String message;
+ public static final StreamCodec<ByteBuf, PacketGeneralMessage> STREAM_CODEC = StreamCodec.composite(
+ ByteBufCodecs.STRING_UTF8,
+ PacketGeneralMessage::message,
+ PacketGeneralMessage::new
+ );
public String getMessage() {
return message;
}
-
- public PacketGeneralMessage()
- {
- message = new String();
- }
-
+
public PacketGeneralMessage(String message)
{
this.message = message;
}
- public PacketGeneralMessage(final FriendlyByteBuf buf) {
- this.message = buf.readUtf();
- }
-
@Override
- public void write(FriendlyByteBuf buf) {
- buf.writeUtf(message);
+ public Type<? extends CustomPacketPayload> type() {
+ return TYPE;
}
- @Override
- public ResourceLocation id() {
- return ID;
- }
-
- public static class PayloadHandler {
- private static final PayloadHandler INSTANCE = new PayloadHandler();
-
- public static PayloadHandler getInstance() {
- return INSTANCE;
- }
-
- public void handleData(final PacketGeneralMessage pkt, final PlayPayloadContext ctx) {
- ctx.workHandler().submitAsync(() -> {
+ public static class PayloadHandler implements IPayloadHandler<PacketGeneralMessage> {
+ @Override
+ public void handle(final @NotNull PacketGeneralMessage pkt, final IPayloadContext ctx) {
+ ctx.enqueueWork(() -> {
if (FMLEnvironment.dist.isClient()) {
TurnBasedMinecraftMod.proxy.handlePacket(pkt, ctx);
}
}).exceptionally(e -> {
- ctx.packetHandler().disconnect(Component.literal("Exception handling PacketGeneralMessage! " + e.getMessage()));
+ ctx.disconnect(Component.literal("Exception handling PacketGeneralMessage! " + e.getMessage()));
return null;
});
}
+++ /dev/null
-# This is an example mods.toml file. It contains the data relating to the loading mods.
-# There are several mandatory fields (#mandatory), and many more that are optional (#optional).
-# The overall format is standard TOML format, v0.5.0.
-# Note that there are a couple of TOML lists in this file.
-# Find more information on toml format here: https://github.com/toml-lang/toml
-# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
-modLoader="javafml" #mandatory
-# A version range to match for said mod loader - for regular FML @Mod it will be the forge version
-loaderVersion="${loader_version_range}" #mandatory (34 is current forge version)
-# A URL to refer people to when problems occur with this mod
-issueTrackerURL="https://github.com/Stephen-Seo/TurnBasedMinecraftMod/issues" #optional
-license="${mod_license}"
-# A list of mods - how many allowed here is determined by the individual mod loader
-[[mods]] #mandatory
-# The modid of the mod
-modId="${mod_id}" #mandatory
-# The version number of the mod - there's a few well known ${} variables useable here or just hardcode it
-version="${mod_version}" #mandatory
- # A display name for the mod
-displayName="${mod_name}" #mandatory
-# A URL to query for updates for this mod. See the JSON update specification <here>
-#updateJSONURL="" #optional
-# A URL for the "homepage" for this mod, displayed in the mod UI
-displayURL="https://github.com/Stephen-Seo/TurnBasedMinecraftMod" #optional
-# A file name (in the root of the mod JAR) containing a logo for display
-#logoFile="" #optional
-# A text field displayed in the mod UI
-credits="Thanks for this mod goes to Java" #optional
-# A text field displayed in the mod UI
-authors="${mod_authors}" #optional
-# The description text for the mod (multi line!) (#mandatory)
-description='''${mod_description}'''
-
-logoFile="assets/com_burnedkirby_turnbasedminecraft/tbmm_icon.png"
-
-# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional.
-[[dependencies.com_burnedkirby_turnbasedminecraft]] #optional
- # the modid of the dependency
- modId="neoforge" #mandatory
- # Does this dependency have to exist - if not, ordering below must be specified
- type="required" #mandatory
- # The version range of the dependency
- versionRange="${neo_version_range}" #mandatory
- # An ordering relationship for the dependency - BEFORE or AFTER required if the relationship is not mandatory
- ordering="NONE"
- # Side this dependency is applied on - BOTH, CLIENT or SERVER
- side="BOTH"
-# Here's another dependency
-[[dependencies.com_burnedkirby_turnbasedminecraft]]
- modId="minecraft"
- type="required"
- versionRange="${minecraft_version_range}"
- ordering="NONE"
- side="BOTH"
--- /dev/null
+# This is an example neoforge.mods.toml file. It contains the data relating to the loading mods.
+# There are several mandatory fields (#mandatory), and many more that are optional (#optional).
+# The overall format is standard TOML format, v0.5.0.
+# Note that there are a couple of TOML lists in this file.
+# Find more information on toml format here: https://github.com/toml-lang/toml
+# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
+modLoader="javafml" #mandatory
+
+# A version range to match for said mod loader - for regular FML @Mod it will be the FML version. This is currently 2.
+loaderVersion="${loader_version_range}" #mandatory
+
+# The license for you mod. This is mandatory metadata and allows for easier comprehension of your redistributive properties.
+# Review your options at https://choosealicense.com/. All rights reserved is the default copyright stance, and is thus the default here.
+license="${mod_license}"
+
+# A URL to refer people to when problems occur with this mod
+#issueTrackerURL="https://change.me.to.your.issue.tracker.example.invalid/" #optional
+
+# A list of mods - how many allowed here is determined by the individual mod loader
+[[mods]] #mandatory
+
+# The modid of the mod
+modId="${mod_id}" #mandatory
+
+# The version number of the mod
+version="${mod_version}" #mandatory
+
+# A display name for the mod
+displayName="${mod_name}" #mandatory
+
+# A URL to query for updates for this mod. See the JSON update specification https://docs.neoforged.net/docs/misc/updatechecker/
+#updateJSONURL="https://change.me.example.invalid/updates.json" #optional
+
+# A URL for the "homepage" for this mod, displayed in the mod UI
+#displayURL="https://change.me.to.your.mods.homepage.example.invalid/" #optional
+
+# A file name (in the root of the mod JAR) containing a logo for display
+#logoFile="examplemod.png" #optional
+logoFile="assets/com_burnedkirby_turnbasedminecraft/tbmm_icon.png"
+
+# A text field displayed in the mod UI
+#credits="" #optional
+
+# A text field displayed in the mod UI
+authors="${mod_authors}" #optional
+
+# The description text for the mod (multi line!) (#mandatory)
+description='''${mod_description}'''
+
+# The [[mixins]] block allows you to declare your mixin config to FML so that it gets loaded.
+#[[mixins]]
+#config="${mod_id}.mixins.json"
+
+# The [[accessTransformers]] block allows you to declare where your AT file is.
+# If this block is omitted, a fallback attempt will be made to load an AT from META-INF/accesstransformer.cfg
+#[[accessTransformers]]
+#file="META-INF/accesstransformer.cfg"
+
+# The coremods config file path is not configurable and is always loaded from META-INF/coremods.json
+
+# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional.
+[[dependencies.${mod_id}]] #optional
+ # the modid of the dependency
+ modId="neoforge" #mandatory
+ # The type of the dependency. Can be one of "required", "optional", "incompatible" or "discouraged" (case insensitive).
+ # 'required' requires the mod to exist, 'optional' does not
+ # 'incompatible' will prevent the game from loading when the mod exists, and 'discouraged' will show a warning
+ type="required" #mandatory
+ # Optional field describing why the dependency is required or why it is incompatible
+ # reason="..."
+ # The version range of the dependency
+ versionRange="${neo_version_range}" #mandatory
+ # An ordering relationship for the dependency.
+ # BEFORE - This mod is loaded BEFORE the dependency
+ # AFTER - This mod is loaded AFTER the dependency
+ ordering="NONE"
+ # Side this dependency is applied on - BOTH, CLIENT, or SERVER
+ side="BOTH"
+
+# Here's another dependency
+[[dependencies.${mod_id}]]
+ modId="minecraft"
+ type="required"
+ # This version range declares a minimum of the current minecraft version up to but not including the next major version
+ versionRange="${minecraft_version_range}"
+ ordering="NONE"
+ side="BOTH"
+
+# Features are specific properties of the game environment, that you may want to declare you require. This example declares
+# that your mod requires GL version 3.2 or higher. Other features will be added. They are side aware so declaring this won't
+# stop your mod loading on the server for example.
+#[features.${mod_id}]
+#openGLVersion="[3.2,)"