#help-development
1 messages ยท Page 611 of 1
wtf (respectfully)
we needed a simple system to make animations without hardcoding shit ยฏ_(ใ)_/ยฏ
So I made it in a week
im sorry but i didn't understand nothing, but thanks for trying helping me
Yeah you might need to learn a bit more before uhh
Doing stuff
The idea is to read the string and split it into left, right and operator
Based on the operator you do comparisons between your left and right (the OPERATORS map in my sample is responsible for that)
Replace any placeholders or variables in both your left and right arguments
And run the operator on them
ngl i copied your Hologram class over top of mine and im using it as a base
im even using lambdas n shit to try keeping your simplicity and proness
kek
lambdas are fun
they look pro
eh
They have their use-case
I abuse them in my minigame lib
but I also abuse extending a class
?paste
https://paste.md-5.net/yadeligeqi.js currently the code lol basic and easy to read
Mhm no this is a bit too hardcoded
Let's start by breaking this down a bit
What would the full line look like
same as yours lol
like if !player_sneaking then [break] 3x3 <= Currently this last part i don't know how to "style" it
Ppl bully me for using protocollib so im gonna try not to anymore, so would changing your PacketContainer to private final ClientboundRemoveEntitiesPacket destroyPacket; be bad practice?
No, that's how you'd do it
dope
Following this
Your condition is a bit tricky
And it can be broken down into
[!]<state>[<>=]<other>
As in
!player_sneaking
player_level=3
wtf is this? pattern?
I'm just breaking this down
oh ok
= is optional too
holy shit thats an amazing use for gpt
i didn't know chatgpt could write regex for you
if\s*(!)?\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*(<|>|=)?\s*([a-zA-Z0-9_]+)?\s*then
WTF IS THIS
Group 1 will be the ! if it's present
Group 2 will be the left side
Group 3 will be the operator, if present
Group 4 will be the right side, if present
so what i do, im really lost
Put that into a pattern
In java code, create a matcher
Basically
Let's structure this in a funky way
Pattern pattern = Pattern.compile("if\\s*(!)?\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*(<|>|=)?\\s*([a-zA-Z0-9_]+)?\\s*then");
public class Condition {
private static final Pattern REGEX = Pattern.compile("if\\s*(!)?\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*(<|>|=)?\\s*([a-zA-Z0-9_]+)?\\s*then");
private boolean negated;
private String left;
@Nullable private String operator;
@Nullable private String right;
public Condition(String input) {
parse(input);
}
private void parse(String input) {
Matcher matcher = REGEX.matcher(input);
}
public boolean isMet(Player player) {
}
}
Let's start with this
ok
Let's start with this
On our Parse method we can write some sanity checks
If 3 is undefined yet 4 is defined, it's illegal
Which represents trying to compare 2 variables with no operator
in theory
We'll also need to make some sort of placeholder system
As well as a comparison system
Because comparing 2 booleans isn't the same as comparing 2 strings or something
But we can just use comparators
public interface PlayerPlaceholder<T extends Comparable<T>> {
String getName();
T fetch(Player player);
}
This will be our supplier thing
one thing im gonna ask you "What is T"?
It's a generic type
oh ok
Basically if we say PlayerPlaceholder<Boolean>
The method returns boolean
It's the thing that powers lists
private final Packet<ClientGamePacketListener> spawnPacket;
private final Packet<ClientGamePacketListener> metadataPacket;
private final Packet<ClientGamePacketListener> destroyPacket;
private void sendPacket(Player player, Packet<ClientGamePacketListener> packet) {
((CraftPlayer) player).getHandle().connection.send(packet);
}
private Packet<ClientGamePacketListener> prepareSpawnPacket() {
ClientboundAddEntityPacket packet = new ClientboundAddEntityPacket(entityId,
UUID.randomUUID(),
hologramLocation.getX(),
hologramLocation.getY(),
hologramLocation.getZ(),
0.5f,
0.5f,
EntityType.TEXT_DISPLAY,
1,
new Vec3(0,0,0),
0.25
);
return packet;
}
This seem legit...? the metadata packet probably cant be final since its gonna be updating the text to whatever I need as it needs it...
Anyways back to our class, we can do a basic
private final Map<String, PlayerPlaceholder<?>> placeholders = new ConcurrentHashMap<>();
public void registerPlaceholder(PlayerPlaceholder<?> placeholder) {
this.placeholders.put(placeholder.getName(), placeholder);
}
in another class?
same class?
that class is gonna be 30000 lines
registerPlaceholder(new PlayerPlaceholder("player_shift", Player::isShifting));
Let me write this up actually
inside the isMet conditions
no
are you alright?
oh
Think I'll use strings for this
not after dealing with us
for real
i think im gonna quit coding in java after this, i don't know nothing about java this man is superiour
Everyone is at a different stage with it.
Lol, us regulars are like this ๐
public class Condition {
private static final Pattern REGEX = Pattern.compile("if\\s*(!)?\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*(<|>|=)?\\s*([a-zA-Z0-9_]+)?\\s*then");
private final List<PlayerPlaceholder> placeholders = new ArrayList<>();
private static final Map<Character, BiPredicate<String, String>> OPERATORS = Map.of(
'=', String::equalsIgnoreCase,
'>', (a, b) -> a.compareTo(b) > 0,
'<', (a, b) -> a.compareTo(b) < 0
);
private boolean negated;
private String left;
private String operator;
private String right;
public Condition(String input) {
parse(input);
}
public void registerPlaceholder(PlayerPlaceholder placeholder) {
placeholders.add(placeholder);
}
private void parse(String input) {
Matcher matcher = REGEX.matcher(input);
if (!matcher.matches()) {
throw new IllegalArgumentException("Invalid condition: " + input);
}
negated = matcher.group(1) != null;
left = matcher.group(2);
operator = matcher.group(3);
right = matcher.group(4);
boolean validOp = (operator != null) == (right != null); // XOR
if (!validOp) {
throw new IllegalArgumentException("Invalid condition: " + input);
}
}
public boolean isMet(Player player) {
String left = replace(this.left, player);
if (operator == null) {
return left.equalsIgnoreCase("true") || left.equalsIgnoreCase("1");
}
String right = replace(this.right, player);
BiPredicate<String, String> predicate = OPERATORS.get(operator.charAt(0));
if (predicate == null) {
throw new IllegalArgumentException("Invalid operator: " + operator);
}
return predicate.test(left, right) != negated;
}
private String replace(String original, Player player) {
String whatever = original;
for (PlayerPlaceholder placeholder : placeholders) {
whatever = whatever.replace(placeholder.getName(), placeholder.get(player));
}
return whatever;
}
}
public interface PlayerPlaceholder {
String get(Player player);
String getName();
}
This might just work
nah dude im quitting after this he did a code faster than light
Don't get discouraged
yeah if you have a proper IDE open its not hard
I've done this before
and I have years of experience under my belt
a bit over a decade of coding
You have to realize some of us have years of doing this stuff like illusion said
me too and I still suck
ive been on/off though not constant
Doing about like 6 years of constant plugin dev
provide me a twist tea
bruh
what would be the most efficient way of setting up this metadata packet since the text is gonna change a lot..?
honestly I hate the nms entity data thing
as you require a real entity
not spawned
And it makes copies
well.. if I spawn it with a packet and modify the data with a packet it should be fine..
But yeah just have a final entity and create the packet on the fly ig
nah it makes copies
sorry for asking but the registerPlacehoder where should be used and how i can use it in my code?
deadass?
ugh
im really sorry
It's okay
public class SimplePlaceholder implements PlayerPlaceholder {
private final String name;
private final Function<Player, ?> function;
public SimplePlaceholder(String name, Function<Player, ?>> function) {
this.function = function;
}
@Override
public String get(Player player) {
Object result = function.apply(player);
if(result == null) {
return "null";
}
return result.toString();
}
@Override
public String getName() {
return name;
}
}
paste this bitch in
Oh wait, in theory I think I can initialize the metaDataPacket with all the values set. Then in #setText, I can grab the existing metadata packet, ONLY modify 22 (text) and re-send it..
registerPlaceholder(new SimplePlaceholder("player_sneaking", Player::isSneaking));
Should work
where do i put it litteraly inside inside the isMet or inside the Constructor?
No
Outside somewhere
I usually make a registerDefaultConditions method and register a bunch of them
and call them somewhere
This list can also be static
on start so its easier
But it'd be a bit annoying for more complex things
You can also just implement the interface and make your own getter
For things like custom name
really thanks man, im shaking, im reconsidering my life choices and crying on the floor after this
im no that deep
i made many complicated code for my api but not this level
Read about lambdas if you don't know enough about them
ok so for recapture everything
Now i need to makea new class
for reading each line checks like
if(new Condition(script).isMet(player)) {
actionsSystem.run(player)
}
If anything wrong im sorry
https://i.imgur.com/sQjQPkL.png Since ClientboundSetEntityDataPacket requires a List<DataValue> instead of List<WrappedDataValue>, is there an easy way of modify my data value list to work with this method?
Just saw this but no don't ask me I know jackshit about thread pools and executors
n o
You create a condition in your enchant object
inside the event?
yes that's something i was doing already
Basically you "primed" the check by running the parser
Which is heavy
isMet can be called plenty times but only create the condition once basically
You can have for example an enchantment registry where each custom enchant has a condition
And you just check for that condition and then run the enchant
but the purpose of this system is the player makes action and if one string as if then runs the conditions
and then recalls the action system to run it
or else stops
Oh yeah we need to modify this a little bit
so should be something like
actions:
- if !player_sneaking then break block
- POTION:SPEED:30:2
that's pretty much my scripting engine lma
an example im making, the client is really stupid and im making even a docs at the same time
idk why not buying a plugin similar to the one im making but he is paying me so nice
my paypal now has 7 dollars lol
U did stuff with papers thread thingy and i took a wild guess you would prob know
? I didn't
I don't intentionally play with paper
I've written code before that does multithreaded shit but I just stick with forkcommon
dead chat
p much
yea dude
im switching back to protocollib..
๐
dont think i can do what I need to without it.
imIllusion sorry for asking but in the code is already implemented the last part of taking after then or is not done?
in case im gonna implement it by myself, i mean it gives you after the then
Taking what?
You can just add an extra group to the regex that'll be the action
And making a attemptApply(Player player) method that just does an isMet -> runAction
hey illusion bbg

๐ณ
public void run(Player player) {
if(isMet(player)) {
//run action?
}
}
?
ok
yes?
private final Map<String, Function<String, Action>> initializers = new HashMap<>();
public void registerInitializer(String name, Function<String, Action>> initializer) {
this.initializers.put(name, initializer);
}
public Action parse(String input) {
for(Map.Entry<String, Function<String, Action>> entry : initializers.entrySet()) {
String word = entry.getKey();
Function<String, Action> initializer = entry.getValue();
if(!input.startsWith(word)) {
continue;
}
return initializer.apply(input);
}
return null;
}
public interface Action {
public void applyTo(Player player);
}
public class ConditionalAction implements Action {
private final Condition condition;
private final Action action;
public ConditionalAction(String input, ActionRegistry registry) {
int index = input.indexOf("then") + 4;
String conditionText = input.substring(0, index); // include the word
String actionText = input.subString(index + 1);
this.condition = new Condition(conditionText);
this.action = registry.parse(actionText);
}
@Override
public void applyTo(Player player) {
if(condition.isMet(player)) {
action.applyTo(player);
}
}
}
Something like this
And you register this action as well
registerAction("if", (text) -> new ConditionalAction(text, this));
registerAction("potion", (text) -> new PotionAction(text));
something to ask what's actionRegistry the first code?
this
ok
It's just a place where you register actions
So the idea is you can create "actions" from the lines in your config
The conditional action is just a regular action that only runs is a specific condition that's specified in the action itself is met
Basically a sort of filter
sorry but what ide are you using? intelli?
Yeah
idk why but intelli says im doing wrong the implements, privates and applyTo
but not sure why
private PacketContainer prepareSpawnPacket() {
PacketContainer spawnPacket = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY);
List<WrappedDataValue> dataValues = List.of(
new WrappedDataValue(22, WrappedDataWatcher.Registry.getChatComponentSerializer(), CraftChatMessage.fromStringOrNull(ColorUtil.translateColorCodes(String.valueOf(this.text)))),
new WrappedDataValue(14, WrappedDataWatcher.Registry.get(Byte.class), (byte) 3),
new WrappedDataValue(24, WrappedDataWatcher.Registry.get(Integer.class), 0),
new WrappedDataValue(26, WrappedDataWatcher.Registry.get(Byte.class), (byte) 0)
);
spawnPacket.getModifier().write(0, entityId);
}
Do you know what the indices need to be for spawning..? I had this at one point and lost it ๐ heres the bitmasks and such https://i.imgur.com/cpsobGG.png
Look at the nms packet
metadata values are part of the metadata packet
I might be an idiot
the ConditionalAction is a class and not an interface**
. you wrote implements Action etcs
Action is an interface
yes
i changed one name and now works everything wtf?
Go figure
OOHHH i probably understand inside my api there's an Action system for mongodb so that's why lol
they had the same name
so i made a class like this and put it on OnEnable that should be fine?
public static void loader() {
//Actions Loader
new ActionRegistry().registerInitializer("if", (text) -> new ConditionalAction(text, new ActionRegistry()));
//Conditions Loader
new Condition("").registerPlaceholder(new SimplePlaceholder("player_sneaking", Player::isSneaking));
}
ded chat again
what the actual fuck
n o
Make the placeholder list on your Condition class static and register them all at once
In a static method somewhere
ActionRegistry registry = new ActionRegistry();
registry.registerInitializer("if", (text) -> new ConditionalAction(text, registry));
Your registerPlaceholder can be static too
And you can remove the run method
That's part of the action system now
for registring the condition i need to do new Condition("").register()
because is not outside or how can i do it?
SimplePlaceholder IS_SNEAKING;
static {
IS_SNEAKING = registerPlaceholder(new SimplePlaceholder("player_sneaking", Player::isSneaking));
}
inside the condition class
You can just register it in another class
take a moment to look at what you've achieved
And think about it
the only thing i can think is by making a new Constructor like
new Condition("").register()
Nothing else comes in my mind
Okay so
Forget about the idea of creating new conditions
Forget half of what I said
The main focus is the action system
You register placeholders for the conditions with your static registerPlaceholder method
Let's say onEnable
public void onEnable() {
Condition.registerPlaceholder(new SimplePlaceholder("player_sneaking", Player::isSneaking));
}
i can't because i need to pass a parameter inside the condition?
No
Sorry for the small question, but is there an way to check, if a player is breaking a block? (like in the break animation)
Uhh great question
There might be a tracker for it somewhere but I'm not aware of an API method
https://www.spigotmc.org/threads/check-if-player-is-breaking-block.387738/ something i found that can help
That was my first intention. I think with packets it is possible, but the reading of it is very complicated for me.
If you're comfortable with packets it's really easy
With packets, the client sends packets for:
- When it starts breaking a block
- Arm swing for every tick the block is being broken
- When it finishes breaking a block
- When it cancels a block break
I try it. But can i check too, if the player holding in this moment an specific item like an pickaxe with an custom name or an specific itemstack?
last and only question, ActionRegistry.parse(everystring) to get everything done inside an event? i figured out that of static i didn't know was possible
Yeah
You convert the stringlist into a list of actions
And run those actions n the event
with a for
Yes
so i need to ActionRegistry.parse() to run the actions
No, you parse them onEnable and convert them to a list
Here's the packet you need
The player sends this to the server
You can intercept it with ProtocolLib
but the registerInitializer is for that?
You'll have to make an initializer for each type of action
So it knows what to read
The idea is you grab an action (if ... = ...) and parse it against the initializer map
In this case we have an initializer for "if", which creates a ConditionalAction
And we also have one for "potion" that creates a PotionAction
Those actions then run on the player to run whatever fancy logic
but it has already everything so i just pick the string
ActionRegistry.parse("if !player_sneaking then POTION")
In the case of potion it gives a potion to the player
Yeah
probably we miss understood each others
This structure is neat but a little confusing
im not great explaining what i meant
Can take a bit to understand but once you do, you'll like it
i really thank you without you i wouldn't made it without crying
paypal email my 7 dollars lol
nothing else
i have only that, in rl i have 200 euros but that something else
yea
I might go get some myself
should I really spend 20 bucks on breakfast
when I can just sleep through it
now i understand
nah this is oversimplified
is worst?
the system at work is a bit more advanced
what job do you work?
I make plugins
for a living
But yeah so at work
It looks like this
and you can do this
I can also do tab completion in real time
for commands
And it also does automatic filtering and smart checks
at dinner table for Christmas,
random dude in your family: "what you do for living"?
you: "making something for a cube game, but it pays really well"
pretty much
I once had to explain to this little kid
that loved minecraft
that minecraft sucks
how part of my job is making plugins for youtube videos
lol
and then I gave him a tnt mug from my collection
and when the kid's parents asked how much money I made
you crushed the kid dream to meet herobrine
in a country where people make 4$ an hour
I just replied "I've made 8 grand on a good month"
I didn't learn java through a tutorial
i know someone who has your "same experience" and makes code worst than mine lol
and he get paid even more
i mean for years like 13 years
too much
yeah checks out but was it really 13 active years
where you try to beat your competition
i mean im making 2 years of full and i started by coding exploits for mc
and after i made a big exploit, i just stop it and now im coding plugins lol
I got about ~13 years coding, 6 of those are in minecraft
An associate's degree in systems management and programming
And some other minor qualifications and achievements
Like fully rebuilding and setting up a cisco-certified computer lab from scratch but that's minor
im currently at school and learning law but probably quitting for human studies
But like
Education and experience years don't mean shit if you're just standing around instead of doing something cool
yes for sure, i mean one of my other friend code ("A GIRL THAT CODE") and they made her learn shit from html etc.. but not javascript and she made a website "a sort of e-commerce" without javascript
because they didn't made her learn REAL coding and i made the entire backend for her
but I was also that clown at some point
but in my defense I was like 6
playing around with html tags lmao
i was like 10 when i just started making websites and i skidded too much, sometimes even now, or go to stackoverflow to do that (praise the one who made stackoverflow he is the savior of all developers)
olivio typing and then no message
@echo basalt i know thought something im making a plugin for customenchants and i didn't even think about the random numbers
to chance them
for that only a simple placeholder because the operators are already added
I'm not gonna be making your entire enchants plugin damn
did somebody say custom enchants
no i mean im not asking that, but the operators should work with numbers
yes
they do, pretty sure
elaborate on your problem plz
no problem, already solved after 1 hour of code
something, i was testing and thought how can i pass the player. Because on the ActionHandler no player is passed and nowhere is passed and by testing the script does not give error but even works
i made a simple SendMessage to debug on simpleAction
https://paste.md-5.net/okusutotor.java
ActionRegistry.parse("if !player_sneaking then message");
The action handler just creates an action from a string
You gotta then run the action in context
im running it on a command
Yeah so
Outside your command you create the action list
And when the player runs the command
you loop through the list and run each action on each player
Easiest way to test is just a runnable each tick and a conditional action
wait, im testing and i used the ActionRegistry.parse() to run that line to "simulate", but the lines doesn't run and debuging the Conditional doesn't even display a player
๐คฆ
List<String> script = List.of(
"if !player_sneaking then message"
);
List<Action> compiled = new ArrayList<>();
for(String line : script) {
compiled.add(registry.parse(line));
}
...
on Command
for(Action action : compiled) {
action.applyTo(player);
}
im stupid
Where is this Packet inside? In ProtocolLib or in the net.minecraft package?
Nms
I need the BuildTools to use nms right?
Somewhat
I mean, i dont have the nms in my source. I use the 1.20.1 for my plugin.
i'm doing a 1.8.8 commission and i'm experiencing extreme pain
i hoped i would never come back to that api
oh god you poor soul
nice pfp
thank you im very peas'd with it
don't tell me you only use it for this pun
๐ญ
anyway, i have a plugin that registers a bunch of new smithing recipes using custom ingredients. most of them are a tool/armor + a material, these recipes use RecipeChoice.ExactChoice for the material and MaterialChoice for the tool/armor. Though ever since 1.20 these recipes no longer register to the server and I assume this is because of the armor trimming recipes, that my recipes are now considered duplicates. My recipes don't require a template though and since they use an exact meta requirement they should take priority, could this be a bug?
and does anyone know of a way to make these recipes register anyway
Show code
i mean what code specifically
the recipes themselves are data driven so i cant really show that practically
public boolean register(DynamicSmithingTableRecipe recipe){
if (allRecipes.contains(recipe.getName())) return false;
smithingRecipes.put(recipe.getName(), recipe);
smithingRecipesByKey.put(recipe.getKey(), recipe);
allRecipes.add(recipe.getName());
plugin.getServer().removeRecipe(recipe.getKey());
if (!plugin.getServer().addRecipe(recipe.generateRecipe())) plugin.logWarning("Could not register recipe " + recipe.getKey().getKey());
return true;
}
this is what's used for registering the recipes themselves
and yeah the smithing recipes using some type of armor + a material will not register
generateRecipe will just take the base and addition of the recipe and return a new smithingrecipe with an exact choice if an exact meta is required or a materialchoice if not
you mean you wanna get the player inventory?
did you register the event listener
client side inventory is unknown by the server
them pressing e to open their inventory will not trigger anything on the server
oh i guess that makes sense
what do you want to do with that inventory though because you can easily just interact with the player's inventory
doesn't the event happen on the server like with the f or q button
no
there are item drop events and item swap events yes
pressing f means the server has to be informed by the client that the item is getting swapped
they are considered interact events and not inventory events
pressing q means the server has to drop an item
pressing e means the server doesn't have to know anything ๐
button presses are not sent
the client does something because you pressed a button
yeah sneaking is also known to the server
that might include the server getting some packet
and the server then calling some event
you should refer to these buttons with actions and not their key
but the button press itself is unknown to the server
bukkit api what a crutch api

so many restrictions
litearlly no plugin api can do this 
without modifying the client
the client simply does not inform the server, what do you want the server to do ๐
(
how can i get all the player permissions?
Player#getEffectivePermissions()?
that's a very weird design choice though
because it allows for cheats like moving while in an inventory
because the server does not know that the player has an inventory open
How do u get a player's current scoreboard team
scoreboard.getEntityTeam(player)
dd
plugins {
id 'com.github.johnrengelman.shadow' version '8.1.1'
id 'java'
}
group = 'de.marvn.alphablock'
version = '1.0'
jar {
destinationDirectory.set(file("C:\\Users\\Killi\\Desktop\\TestServer\\plugins"))
}
repositories {
mavenCentral()
maven {
name = "spigotmc-repo"
url = "https://hub.spigotmc.org/nexus/content/repositories/snapshots/"
}
maven {
name = "sonatype"
url = "https://oss.sonatype.org/content/groups/public/"
}
maven { url "https://repo.dmulloy2.net/repository/public/" }
}
dependencies {
compileOnly "org.spigotmc:spigot-api:1.8.8-R0.1-SNAPSHOT"
compileOnly 'com.comphenix.protocol:ProtocolLib:5.0.0'
}
def targetJavaVersion = 8
java {
def javaVersion = JavaVersion.toVersion(targetJavaVersion)
sourceCompatibility = javaVersion
targetCompatibility = javaVersion
if (JavaVersion.current() < javaVersion) {
toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion)
}
}
tasks.withType(JavaCompile).configureEach {
if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) {
options.release = targetJavaVersion
}
}
processResources {
def props = [version: version]
inputs.properties props
filteringCharset 'UTF-8'
filesMatching('plugin.yml') {
expand props
}
}
I am back bitches
HEY
got the problem
I registered my Serializables after I get the Config xD
And the next Problem is , that my world wasnt loaded
this hurts
you have the shadow plugin, but dont use it and modify the dest dir in the wrong place to make it work with shadow
yeah I just added the shadow polugin after I sent it
Average gradle moment
xD
hi md
gradle is good
what was up with couldflare stealing buttons yesterday
But maven is better
cloudflare couldflare
debatable
True but i am internally cooking when I have to deal with a gradle project
public ArenaUtils(Plugin plugin, String path) {
this(plugin.getDataFolder().getAbsolutePath() + "/" + path);
}
public ArenaUtils(String path) {
this.file = new File(path);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
this.config = YamlConfiguration.loadConfiguration(this.file);
}```
This is how I load one
You can get all files using new File("MyFolder").listFiles()
But now I want to load a full directory because there could be multiple Arena.yml
list the files, check if its a yml and load it to a map or something with its file name to its yaml config value
It'd be easier if you'd accept a File instead of the path as a parameter
^^
someone give me site for read code
what
i want give code for some help
?paste
HashMap<File, FileConfiguration> arenas = new HashMap<>();
public ArenaUtils(Plugin plugin) {
this(plugin.getDataFolder().getAbsolutePath() + "/arena/");
}
public ArenaUtils(String path) {
if (new File(path).listFiles() == null) return;
try {
Arrays.stream(new File(path).listFiles()).forEach(file -> arenas.put(file, YamlConfiguration.loadConfiguration(file)));
} catch (NullPointerException e ) {
System.out.println("No arenas found!");
}
}``` You mean like that?
string to yaml config
I check the directory if there is any yml and if yes it load all into the Map
right?
you dnt check if its a yaml
https://paste.md-5.net/ejipexigob.cs - why this serialization does not also take into account the number of itemsStack - for example, if there are 2 apples in the inventory, then they are combined into 1
show the itemToString(ItemStack) method
How can I check which format that file has?
just split the file by "." and get the last element
Also don't catch npe
yeah idk unfortunately
demm
id do something like this
in theory, it should take into account another slot in the inventory, but for some reason it does not take into account
I pretty much got the same
public ArenaUtils(String path) {
if (new File(path).listFiles() == null) return;
try {
Arrays.stream(new File(path).listFiles()).forEach(file -> {
if (!file.getName().endsWith("yml")) return;
arenas.put(file, YamlConfiguration.loadConfiguration(file));
});
} catch (NullPointerException e ) {
System.out.println("No arenas found!");
}
}```
that's a normal output from the weird mc dev plugin
that isnt a great use for stream api
it was mainly the jar {destdir} part that hurt
they have shadow plugin, so shadowjar
but what does shadow have to do with the output?
it outputs the uber jar
public ArenaUtils(String path) {
try {
for (File file : new File(path).listFiles()) {
if (!file.getName().endsWith("yml")) return;
arenas.put(file, YamlConfiguration.loadConfiguration(file));
}
} catch (NullPointerException e ) {
System.out.println("No arenas found!");
}
}```
So like this?
at least in maven, shade comes after compile, and before package
it wouldnt make any sense to first create a .jar, and then manually add the shaded stuff to it. shadow should definitely run before jar
in everything i do shadowjar depends on build
and i change the output in shadowjar
?paste
is there any way to simplify this?
return if (requiredLevel == null) object: Kit {
override fun getHelmet(): ItemStack? = helmet
override fun getChestplate(): ItemStack? = chestplate
override fun getLeggings(): ItemStack? = leggings
override fun getBoots(): ItemStack? = boots
override fun getPrimaryWeapon(): ItemStack? = primaryWeapon
override fun shouldGiveSpecial(): Boolean = shouldGiveSpecial
override fun getInventory(): List<ItemStack> = inventory
override fun getKitName(): String = kitName
override fun getKitDescription(): List<String> = kitDescription
override fun getRepresentativeGUIItem(): ItemStack = representativeItem
override fun getHealth(): Double = health
override fun getPotionEffects(): List<PotionEffect> = effects
} else object: LevelRestrictedKit {
override fun getHelmet(): ItemStack? = helmet
override fun getChestplate(): ItemStack? = chestplate
override fun getLeggings(): ItemStack? = leggings
override fun getBoots(): ItemStack? = boots
override fun getPrimaryWeapon(): ItemStack? = primaryWeapon
override fun shouldGiveSpecial(): Boolean = shouldGiveSpecial
override fun getInventory(): List<ItemStack> = inventory
override fun getKitName(): String = kitName
override fun getKitDescription(): List<String> = kitDescription
override fun getRepresentativeGUIItem(): ItemStack = representativeItem
override fun getHealth(): Double = health
override fun getPotionEffects(): List<PotionEffect> = effects
override fun getRequiredLevel(): Int = requiredLevel
}
it feels too clunky to repeat the same stuff twice just to add one value
you mean build dependson shadowjar
LevelRestrictedKit extends Kit
which means that shadowjar runs before build
Hey, I want to ask which event in BungeeCord API is called when player successfully switched server to another ? I see, there is ServerConnectedEvent & ServerSwitchEvent but I don't see difference between them
ye
12:36:55: Executing 'build'...
Starting Gradle Daemon...
Gradle Daemon started in 1 s 812 ms
> Task :generateEffectiveLombokConfig UP-TO-DATE
> Task :compileJava UP-TO-DATE
> Task :processResources UP-TO-DATE
> Task :classes UP-TO-DATE
> Task :jar UP-TO-DATE
> Task :assemble UP-TO-DATE
> Task :shadowJar UP-TO-DATE
> Task :generateTestEffectiveLombokConfig UP-TO-DATE
> Task :compileTestJava NO-SOURCE
> Task :processTestResources NO-SOURCE
> Task :testClasses UP-TO-DATE
> Task :test NO-SOURCE
> Task :check UP-TO-DATE
> Task :build UP-TO-DATE
BUILD SUCCESSFUL in 16s
6 actionable tasks: 6 up-to-date
12:37:12: Execution finished 'build'.
very weird that jar runs before shadowJar lol. that makes little to no sense
anyone?
public boolean save() {
try {
for (Map.Entry<File, FileConfiguration> entry : arenas.entrySet()) {
File file = entry.getKey();
FileConfiguration config = entry.getValue();
config.save(file);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}```
And this is how I would save the whole list
is there any way to simplify this
now i have tried
perms.get(player.getUniqueId()).unsetPermission("permission);
and its not working
so whats the solution
its from 1.8 btw
?notworking
"Does not working" is a useless statement. Please describe what exactly is not working, what you expect it to do, and what actually happens. If you get any console errors, also ?paste the entire stacktrace.
as im developing a pvp server
have you tried literally this line of code?
its not an error
i hope not
you're missing a "
what even is "perms"
no with creating the hasmap
https://paste.md-5.net/gahocuvoqi.coffeescript help with CompletableFuture please)) https://cdn.discordapp.com/attachments/1090648704387665930/1127907242264510525/image.png
no like, did you copy your line of code as is
or did you just send pseudocode
HashMap<UUID, PermissionAttachment> perms = new HashMap<UUID, PermissionAttachment>();
can just be Map<UUID, PermissionAttachment> perms = new HashMap<>();
yeah
and what is "not working"?
in the code i have it but also doesnt remove the permission
why would removing something from a random unrelated map change any actual permissions?
ok just show your actual code and describe the problem properly
it doesn't remove the permission
public HashMap<UUID, PermissionAttachment> perms = new HashMap<UUID, PermissionAttachment>();
public HashMap<UUID, PermissionAttachment> Permissions(Player player) {
this.attachment = player.addAttachment(this);
perms.put(player.getUniqueId(), attachment);
return this.perms;
}```
?conventions your method should be in lowerCamelCase to increase readability
i have no clue what that even is supposed to do
you might think we're nitpicking with shit like this and that
you sound like a bot
but good coding practices reduce bugs significantly
lmao
I thought Permissions(Player) is a constructor
same
hmm
that's why conventions are needed
but why it doesn't remove the permissions
why would this particular snippet of code remove anything
because you are not removing it
i tried it several times and removed the op
because you never remove any permission
it literally says add
all you do is to create a hashmap
?learnjava
Here are some links to get you started on learning Java:
- https://www.codecademy.com/learn/learn-java
- https://www.sololearn.com/learning/1068
- https://www.learnjavaonline.org/
- https://programmingbydoing.com/
- https://docs.oracle.com/javase/tutorial/java/index.html
The last one is the only official one, however some of those concepts assume that you already know a bit about programming.
i really don't get why you'd think this would unset any permission
yeah probably that
i learnt it from sololearn
for how long
java indermediate and introduction to java
a day?
i hope sololearn doesn't teach to implicitly specify the arguments like this
and yet you have no clue what you are doing
the should i make player.removeattachment ?
to remove a permission you call setPermission(somePermission, false) on the existing attachment
or what
i will try this
what happened to my server whenever i join there is no world i just fall forever
i know but stuck at something
im at like -4000 on the y coordinate
i think this is lag
also this message literally gives 0 information
is this a development question?
we know nothing about your server
try restarting the server or your router
if anyone has experience with kotlin, please take a look at my thread, much appreciated ๐
i did restart the server
this is for #help-server
ok
and this what eclipse gave me after removing the arguments
Type safety: The expression of type HashMap needs unchecked conversion to conform to HashMap<UUID,PermissionAttachment>
show the line of code you have now
HashMap<UUID, PermissionAttachment> perms = new HashMap();
HashMap<>()
and it's a good practice to just specify the most parent type, e.g.
Map<UUID, PermissionAttachment> perms = new HashMap<>();
instead of
HashMap<UUID, PermissionAttachment> perms = new HashMap<>();
yeah solo learn teachs it like
HashMap<meow, meow> meow = new HashMap<meow, meow>();
lol
yep it worked !
thx
sololearn doesnt seem very good
the correct way is Map<Woof, Meow> map = new HashMap<>();
sololearn is on older java version still
i dont think it teaches things like streams
Why would it teach streams, this isn't twitch smh
\j
Hey i get following error:
[12:57:21 WARN]: java.io.IOException: The system cannot find the path specified
public boolean saveArena(String name, Arena obj) {
try {
File file = new File(this.path + "\\" + name);
if (!file.exists()) {
file.createNewFile();
}
FileConfiguration fileConfiguration = YamlConfiguration.loadConfiguration(file);
fileConfiguration.save(file);
arenas.put(file, fileConfiguration);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}```
this is my code
what do you supply for this.path
plugin.getDataFolder().getAbsolutePath() + "\\arena"
oh and instead of "\\" use File.separator
i'm not sure but it could be that the file variable isn't updated after you call file.createNewFile() and it still thinks that the file is nonexistent when you try to load the configuration
if that's not the case, then the arena folder is not existent
In the end the file poathname is \plugins\AlphaWars\arena\name
it was non existant but should it create one if I create a file with that path?
not sure
File arenaFolder = new File(getDataFolder(), "arena");
File nameFile = new File(arenaFolder, "name");
do it like this
just check for the file existence
yeah
and if (!arenaFolder.exists()) arenaFolder.mkdir();
I cant follow
wdym
what is getDataFolder
plugin.getDataFolder()
Plugin#getDataFolder
declaration: package: org.bukkit.plugin.java, class: JavaPlugin
What directories does the plugin have access to?
everything the server has access to
yeah from plugin.getDataFolder() you can navigate to anywhere
or if you create a file without using plugin.getDataFolder() (e.g. new File("abc")), it is created in whenever the start script is running from
it works
great thanks
but it isnt a yml
its just a file
public boolean saveArena(String name, Arena obj) {
try {
File file = new File(arenaFolder, name);
if (!file.exists()) {
file.createNewFile();
}
FileConfiguration fileConfiguration = YamlConfiguration.loadConfiguration(file);
fileConfiguration.set("Arena", obj);
fileConfiguration.save(file);
arenas.put(file, fileConfiguration);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}```
This is my save method
append ".yml" to the end of the name
I am quite rusty with exceptions.. shouldn't he catch IOException instead of just any Exception ?
Yes
Catch specific exceptions if possible
Much more precise and expressive error handling
this is getting stupid
It indeed is
i cant write more than 2 lines of code without it freezing and doing that
ok
how the christ do i fix this shti
[13:10:17 WARN]: java.io.IOException: The system cannot find the path specified
again
public boolean saveArena(String name, Arena obj) {
try {
File file = new File(arenaFolder, name + ".yml");
if (!file.exists()) {
file.createNewFile();
}
FileConfiguration fileConfiguration = YamlConfiguration.loadConfiguration(file);
fileConfiguration.set("Arena", obj);
fileConfiguration.save(file);
arenas.put(file, fileConfiguration);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}```
Is it because the directory arena doesnt exist again?
I think somebody said they needed to disable the bytecode decompiler or something like that
and i do that how?
Ask the person who said that, not me
well who said it...
Hmm
How can I create a directory from a file?
call mkDirs on arenaFolder if it does not exist
Seems like this should be it
HAhahha
Relatable
hi thats me
yea did that fix the stupid crashing thing
mostly
why wouldn't you download sources immediately? intellij prompts you with it
do i have to add the lore manually for custom enchantments?
just note you cant control click classes to see their impl and more
gradle and mavenlocal
and how do i make custom enchants work with books?
1.8.8 is a stupid bitch and has none though
like how do i get a book of my custom enchant
EnchantedBookMeta or something
add the enchantment there and then add the lore to the book
public static ItemStack customEnchantBook(CustomEnchant customEnchant) {
ItemStack book = new ItemStack(Material.ENCHANTED_BOOK);
EnchantmentStorageMeta meta = (EnchantmentStorageMeta) book.getItemMeta();
meta.addStoredEnchant(customEnchant, customEnchant.getMaxLevel(), true);
book.setItemMeta(meta);
return book;
}
got that
seems to give me the right book
and lore
feeling bored
might make a custom enchants api
but you can reference it
I mean yeah sorta
U have to make sure the parent file exists
the reason for that is because normally when enchantments are added they use a translatable key so that you can enchant an item while using punjabi and it'll be displayed in punjabi for you, but with custom enchants the game does not know any translations for it
so id have to do this aswell?
your choice, maybe you can figure something out
actually wait
the "can't apply" is a case of
?notworking
"Does not working" is a useless statement. Please describe what exactly is not working, what you expect it to do, and what actually happens. If you get any console errors, also ?paste the entire stacktrace.
if you mean that the lore does not appear on the item, it's because it shouldn't, you have to apply it manually
but the enchantment should probably appear, you can check with /data get entity @s SelectedItem
with cant apply i mean
hm perhaps the anvil does not support custom enchants either
well try writing an anvil handler
you have to rewrite the anvil impl for custom encahnts
lovely
yeah
will do
Well, *** p a i n ***
i have just been informed, no need for anvils
custom way it is
they dont want any vanilla enchants
How do i get which group a player is in with luckperms?
Is there a nice GUI framework or should I generate all this myself?
wdym?
TriumphGUI
I want to display some GUIs if you click on some ItemsโฆAnd either I build those GUIs myself or I use a nice framework which makes it a bit easier
i really like it
Ok thx let me try that hehe
Look at the luckperms api reference
You can be in multiple groups
but i haven't tried it
I cant find a method for getting the players group i can only find a method for checking if a player is in any group
Where did you find it? i need to method to get it to work
opened the javadocs and looked at the user class
https://paste.md-5.net/rudohipuyo.cs
how do i give the skull a random rotation?
or better yet the rotation the player has
Check Material docs to see what blockdata skull has (Rotatable iirc) and set accordingly
Hey, I want to get if a sign is glowing, how do i get it ?
It dosent work for me?
is it common to use reflection during serialization/deserialization?
class LocaleDeserializer : JsonDeserializer<Locale> {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): Locale {
val messages = json?.asJsonArray ?: throw IllegalArgumentException("A locale must be an array of messages.")
val locale = Locale()
for (message in messages) {
val messageObject = message.asJsonObject
val terms = messageObject["term"].asString.split("-")
terms.forEach { it.replaceFirstChar { char -> if (char.isLowerCase()) char.titlecase() else char.toString() } }
val term = terms.joinToString("")
val definition = messageObject["definition"].asString
locale::class.java.getDeclaredField(term).set(locale, definition)
}
return locale
}
}
Join luckperms discord
implement Vault over a specific permission plugin API
I am in it
Ask them
I have
youre asking on a spigot discord a lp question
Ask in the api help channel or general help channel
Did you shade jda
What does that mean?
You need to include it in your jar
I have
Otherwise you wonโt have access to it at runtime
<dependency>
<groupId>net.dv8tion</groupId>
<artifactId>JDA</artifactId>
<version>4.2.1_253</version>
</dependency>
how do i cancel the block drop even after blockbreakevent
Why are you using jda4 use jda 5
So version 5.2.1_253?
Reflection is a core thing of most serializer libraries
https://jda.wiki top right of this
You can set drops in the block break event
My database query looks correct, but I get an error about incorrect syntax: https://cdn.discordapp.com/attachments/1090648704387665930/1127938207292604577/image.png
maybe im asking a dumb question but how can i configure my pom.xml to import several versions of nms mappings
im using jeff media's plugin archetype builder thingy
how should i
Do i need the -beta.12?
Yes
And what does that do?
How do i add tye?
declaration: package: org.bukkit.event.block, class: BlockBreakEvent
Look at the docs
Ohhh lol
poof, i'm not weird
that's good
I cant find the dependency
Reload maven
WHERE leader = ? AND member = ?
Conditions are AND and OR, nor ,
thanks
Should probs be caching that data aswell
does anyone happen to know if alex is ok with someone messaging him for a question or does he find that annoying
jeff media alex that is
Ask him first
i did but since he developed the thing i thought he would know best
Isit a lib or plugin
using his plugin archetype builder thing which configures mojang mappings in an easier way, but only for 1 version
wanted to know if you could configure a range of versions for it
or if i would have to make several subprojects for it with individual poms
Modules
yeah i mean modules mb
Is it possible to pass TextComponent to player between servers?
But i don't think it has module support so either loads of projects made with it in ur main folder or make a feature reqest
You probably can but why not just send it to the player through the proxy
makes sense
Send the uuid and component to proxy and get the proxy to send it
Anyways if you want to you'll have to serialize the component into a json string then send it through plugin messaging with the username
Then deseralize it back into a component and send it to the UUId you sent it with
I want to, but how to convert it in string? toString() will be work?
Depends on the component library you're using
Both BungeeChat and Adventure have component serializers
ComponentSerializer for BungeeChat, GsonComponentSerializer for Adventure
Ty choco
thank you very much
Is ther also a nice Scoraboard framework?
Thanks
But my error isnt getting patched
Here it says Exception 'javax.security.auth.login.loginException' is never thrown in the corresponding try block at LoginException
@Override
public void onEnable() {
saveDefaultConfig();
String botToken = getConfig().getString("bot-token");
try {
jda = JDABuilder.createDefault(botToken)
.build()
.awaitReady();
} catch (InterruptedException | LoginException e) {
e.printStackTrace();
}
Hey, I want to get if a sign is glowing, how do i get it ?
https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/block/sign/SignSide.html#setGlowingText(boolean)
declaration: package: org.bukkit.block.sign, interface: SignSide
oh wait, what do you mean with "how do I get it"
you get a block's BlockState, cast it to Sign, get the sign's side, then you can check if it's glowing with SignSide#isGlowingText
I wanna say nms but would probably get flamed for it
Else spigot api allows u to do everything, no?
i am coding a plugin when a specific sign is clicked (the glowing sign) a player gets teleported
Kinda not related to spigot but is there a api similar to quick.db (JavaScript) in Java?
Yeah sorta
Its a high level minimalistic database abstraction framework sorta
and how to derealize? i give a json string in chat
Same classes
#parse() for BungeeChat, #deserialize() for Adventure
You've gotta use Javadocs or at least your IDE, man
ok
Why does it say Cannot resolve method 'sendMessage(MessageEmbed)'?
chatChannel.sendMessage(builder.build()).queue();
sendMEssage
I wrote wrong in discord
you haven'T even mentioned what "chatChannel" is
Can I give a sign a "thing" so I can identify it as the "thing sign"?
PDC
what is chatChannel?
Its the channel where the messages is getting send on discord
text channel
probs part of jda
Yee
any of you guys worked w custom chunkgenerators? my generatecaves isn't called ever
Thanks
Got any code?
I've tried this code, but for some reason it does not work. Neither the entity, nor the player are uncollidable. When I checked the data using the /data command it didn't show anything about collidability
JavaScript simple database that does some similar methods from hash maps
(Late)
I have a class extending ChunkGenerator. I set an instance of this class as generator in the WorldCreator used to create the world. The other methods (generate noise/surface/bedrock) are all called
When i am trying to build my project i am getting 1 error with the dependency shaded thing i added
Do you override the boolean shouldGenerateCaves method?
With no arguments
as per the docs overriding those methods merely indicates that the vanilla generator should also be used
Some entities are exempt
besides haven't done that for the others and they still work
exempt?
From what I know
You must override both
The one with no arguments and the one with
However
You can return false I believe to prevent vanilla cave generation, no?
Wait fuck
they return false by default
when they are ready to make babies ig
example when you feed wheat to horse or whatever
when they're about to fuck
lmao
The weird thing right, is that shouldGenerateBedrock() or whatever is deprecated
but caves should work fine as far as I know
Hello, how can I get the player who caused the generation of a mob ?
hello, i have created a team thing, that saves all kind of stuff, including the players
the problem is, when a player leaves, and relogs, the old player instance stays in that team, though for some reason that old instance is not the same as the player instance that has relogged,
Any idea's why this is and how to fix it
Saved the uuid to the team, not player instance
please help
you need to do 'a' before
how, not work on 1.20.1
can you help me
I'm not very good at nms, but using 'a' before should work
but idk how sorry
hmm okay
lol
you can use reflection to access 'b'
Use mojmaps
Look if 'b' has a getter method first
Also I recommend using mojmaps
?switchmappings
okay thanks lemme try
@worldly ingot can you add a ?mappings thar has the mappings.cpehx link, idk what the actual link is. The new screaming sandles
Kek
?mappings
Compare different mappings with this website: https://mappings.cephx.dev
choco have you experimented w custom worldgen?
Not particularly. At least not since recent overhauls
;-;
Never had much reason to
Go get a job doing world gen
Meh
Real
Hello, how can I raytrace between a player and a Entity ? (raytrace in green, direction of Player in black)
you want the green direction from player to entity?
yes
entity.getLocation().toVector().subtract(player.getLocation().toVector()).normalize()
thanks ๐
I'm making my own chat formatter but some of our ranks have custom hex codes as the color, I want them to show the color ingame but I have no clue how to do that :/ (first image is how it looks, second is how it should look)
I thing I found out
do I need to use legacy hex colors
&x&f&b&6&9&0&0
Cache the pattern for the love of god
I got a simple regex
Are you using the minecraft dev plugin? I think theres a memory leak in it tbh
Do you always criticize other peoples code lol

