#help-development
1 messages Β· Page 2104 of 1
It doesn't clone or modify the location
poke
try to find which event creates them, then check that even if it is connected to the dragon, if yes, cancel the correct event
it depends on your use case.
im filling in mostly similar classes that all extend a preset
I'm doing events that have effects in the world and chain together
anyone know why this is still just a string?
should it not be separated into ["plugins", "JetCore"]
oh whoops nvm I did dumb stuff
I'd use separate args myself, for readability.
Just multiple constructors
so Player#getLocation().getBlock.getRelative(Blockface.DOWN) isn't working do i need to inport something to make that work?
Player is a Class, you need to use the player object
if its written big followed by a # it means that
so it's, here, player.getLocation()...
ah so i need to get the player class set up
so it doesnt noticeably impact performance?
nope
anyone?
void move(PlayerMoveEvent event) {
Player player = event.getPlayer();
Player.class
Player.getLocation().getBlock().getRelative(BlockFace.DOWN);
}``` did i do it right?
it doesn't bring up any errors now
kk
and change Player.getLoc to player.getLoc
then you have to do somethign with the block you are getting
This line returns a Block player.getLocation().getBlock().getRelative(BlockFace.DOWN);
i want it to be that the block they are standing on which for now is clay and latter will include mud.
Block block = player.getLocation().getBlock().getRelative(BlockFace.DOWN);
kk
Player#getLocation() is an instance method, meaning we are referring to <player object>.getLocation() the way we are writing it is just java notation
if it was a static method, it would be Player.getLocation()
referencing the class
instead of an instance
ah ok
if (block.getType() == Material.CLAY)
that makes sence
aight thanks for that i did know that one from my learning of tracking what block a player is mining
Can anyone help me understand the process of structures being built, I've got a void world chunk generator, and just did
@Override
public boolean shouldGenerateStructures() {
return true;
}
to generate structures, but it didn't work. How do structures generate and how would I do it so that it can?
minecraft does extra checks per structure, and basically all of them need at least some blocks underneath or around them
hmmm
so i dont think you will be able to generate structures by just setting that to true
what is the base walk speed of the player? or is there a way i can just use math to increase speed by 5%?
yeah it sounds like it, not sure how I could force it then, and I doubt searching through the nms is gonna help me
using attribute modifiers
i am useing player.setWalkspeed()
i recommend using attribute modifiers
also with that function the base speed is always 1
i have no idea what those are
they will work with like effects
they modify attributes
gtk
do attributes get reset on relog?
i ment i have no idea how to code those
ill look it up
thx
could i just do something like player.setWalkspeed(2) else player.setWalkspeed(1) or something like that?
private static final AttributeModifier SPEED_MODIFIER = new AttributeModifier("name", 2f, AttributeModifier.Operation.ADD_NUMBER);
// ^ added to the base speed, adjust to modify the strength of the effect
public void speedUpPlayer(Player player) {
// get walk speed attribute
AttributeInstance walkSpeed = player.getAttribute(Attribute.GENERIC_MOVEMENT_SPEED);
// activate modifier
walkSpeed.addModifier(SPEED_MODIFIER);
}
public void slowPlayerBackDown(Player player) {
// get walking speed attribute
AttributeInstance walkSpeed = player.getAttribute(Attribute.GENERIC_MOVEMENT_SPEED);
// deactivate modifier
walkSpeed.removeModifier(SPEED_MODIFIER);
}
idk but it might conflict with other plugins
or effects
ah
then call speedUpPlayer(player) when you want the effect to start
and slowPlayerBackDown(player) when you want it to stop
so when someone leaves an area or somethign
ok
so its permanent?
they'd start falling
dont disable flying
give player pdc the time until they can fly then chck if the system time is over that time, if yes, disable flying
yea if you do that with permissions or timings set flying faslse if the times run out
you can give them a few seconds of resistance after login
i believe that's already in the game for like a second or so too
afaik it does but im not 100% sure
ofc you need to apply a level of resistance that actually grants full damage immunity
that didn't work i think i might have implemented it wrong or smth
you can alternatively store the time of login and cancel all damage events that occur within 10 seconds of login
thugh that might get exploited
same
void move(PlayerMoveEvent event) {
Player player = event.getPlayer();
Block block = player.getLocation().getBlock().getRelative(BlockFace.DOWN);
if (block.getType() == Material.CLAY);
player.speedUpPlayer(player);
//else if (block.getType() == Material.MUD);
//player.speedUpPlayer(player);
else
player.speedPlayerBackDown(player);``` i dont think this works. the way i thought it did.
; ends the line if (block.getType() == Material.CLAY);
you need to learn the java syntax
also the function is not a member of Player
so just do speedUpPlayer(player) and slowPlayerBackDown(player)
without the player. in front
ah
its also called slowPlayerBackDown, not speedPlayerBackDown
oops
yeah it gives full spawn protection too
ah
you could also cancel the fall damage
using some damage event
fixed it. missed somthing else in the code that was not letting it call the speedUpPlayer and slowPlayerBackDown.
thx
couldn't you also just cancel the EntityDamageEvent after checking it's a player and has all the requirements that you want?
Player p
pain.
hey, i have a rank system made like this :
public enum Job {
CITOYEN(""),
STAFF(""),
VISITEUR("");
Job(String prefix) {
}
}
public HashMap<Player, Job> jobs = new HashMap<Player, Job>();
public void setjobs(Player player, Job job) {
jobs.put(player, job);
}
public Job getjobs(Player player) {
return jobs.get(player);
}
The thing is, when a player leaves, or the server restarts, their role gets wiped out. How can i solve that?
Are you french? π€ π²π«
I noticed the VISITEUR π
i tried doing that :
public class PlayerClass {
private String name;
private int money;
public PlayerClass(String aName, int aMoney){
name = aName;
money = aMoney;
}
public int getMoney(){
return money;
}
}
public void main(String[] args) throws FileNotFoundException, IOException {
PlayerClass p1 = new PlayerClass("none", 0);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("Person.txt"));
out.writeObject(p1);
}
(for the money)
Ah no ;-;
ok so HOW can i do it pls
you know OOP at all? If not that's cool I can explain basics
i have kits in a yamlconfiguration like this:
kitname:
delay:
permission:
items:
...``` how can i loop through all the kits?
for loop
no shit
yeah, cool huh???
omfg
get the config section of kits, loop through all the keys of that section and get the config section of that key from the config section of kits
yes im asking how to do that
then you can do like get(βdelayβ)
im trying to do that but its not working
show code then
for (String kit : KitData.get().getStringList("kits")){
no
no
lol
ok ty
sommin like that
i did say how but you didn't listen π€·ββοΈ
iβm on phone so
if anyone takes my dumb comments seriously you're hella boring at parties aren't you
some people are actually like that
i try to make fun of stressful times and usually it works out π€·ββοΈ
https://www.spigotmc.org/wiki/create-your-first-bungeecord-plugin-proxy-spigotmc/
is this api also available for 1.8.8?
The home of Spigot a high performance, no lag customized CraftBukkit Minecraft server API, and BungeeCord, the cloud server proxy.
just update lol
yea ik but for the project im working on I need the 1.8.8
nope you can do it in 1.18 fine π
bungeecord's api is not bound to the minecraft server version
so they fucked up that api?
wat
oh
it is
:kekw:
Anyway bungeecord existed in 1.8
you will just have to go on a little adventure
to find it
True, but poor people want their clicking to go fast
just add plugins to emulate it lol
Ssshh let them run unmaintained software known to contain bugs
no
imagine having to remember 89 as glowstone π·
we shouldnt give bad advice
This is the spigot discord, isn't bad advise like, the motto :kappa:
nononoono listen listen
karen incoming?
whats the correct parse arg to turn a Object into a HashSet<HashSet<Object>>[]?
actually no. That's a Array of all itemGroups over all blocks of a certain type in a certain radius. The array indicates the block type, the outer HashSets contains the blocks, and each inner HashSet the group of entities over that block
now mind answering my question?
HashSet<HashSet<Object>>[] is a signature that just should not exist. Write proper wrapper classes
anyway, what kind of object do you have
Object
bruh
cool
object can be anything
what kind of question is "how do I transform anything into this specific type"
where does it come from
no i know that that Object was originally of that signature
im just not sure how to turnit back
cast ?
if you know an object is of said type you cast
() those
You are writing HashSet<HashSet<Object>>[] types and don't know how to cast ?
i am unsure if just writing the signature is enough here
Anyway, this is still garbage. You are breaking the type system for no reason
why do you only have an object
final PacketContainer container = event.getPacket();
final StructureModifier<WrappedChatComponent> components = container.getChatComponents();
final WrappedChatComponent chat = components.read(0);
plugin.sendMessage(chat.getJson());
final IChatBaseComponent base = ChatSerializer.a(chat.getJson());
final String message = base.getText();
plugin.sendMessage(message);```
why the next message is a blank field
Is this some kind of object output stream trash ?
spigot wraps their string messages in a parent without text
you are just getting said parents text, which is empty
so
It's a parser class. I shove everything in a hashMap<String, Object> then nulll check it in the super(hashMap) constructor
You need a proper component serializer
Well if you know the object has that type 100% you can cast it. But again, this just does not sound like good object oriented staticly typed code
im forking a older plugin, he use reflection to use IBaseComponent using objects, message = this.plugin.getMessageMethod().invoke(chat.getHandle(), new Object[0]);
what part of that is static
i dont know what the method c do
java isn't javascript. You should care about your types and not just Object everything
im aware of that but in this instance its necessary
the purpose of that map is to transfer data of different types between objects that have no connection to each other
hence its position in the constructor and the super(hashMap) stuff
interfaces π
probably serializes the component xD
but I have no idea either
you are working with server internals
lemme see if I can find you the method
Can you somehow disable soul sand effect to certain players?
Yeah that could work I guess.
I can't test right now but does the player's movement speed got reduced when they walk in soul sand?
It would be decreased I guess?
Ah okay, so what I would do is increasing the walk speed when player walks in soul sand and revert it back if player is no longer walking in soul sand?
Too many checks smh
File file = Paths.get(scanner.next().replaceAll(" ", "%20")).toFile(); Does NOT work??? I have a path like this: C:\Users\First Last\Desktop\files
Anyways, thanks for this, gonna research more If I can.
unchecked cast lets goo
Player p = (Player) cs;
Youve been here for years...
the command sender may be the console
or a command block
but bro they can still execute the command
if the console executes that command, you will get a classcast exception
you do an instanceOf check
p.getAllowFlight() == true is also a classic
Float speed = (float) Double.parseDouble("" + 0.03f);
also the logic wont work if i read it correctly
if cmd name == "fly" and has permission { execute command }
else { execute other flying stuff }
lemm paste that in an ide lol
the else part will execute for every other command
vscode isnt an ide shhh
nesting the cmd name check and then another if else for the fly checks would look better /_/
It's the best glorified text editor that has similar functionality that just happens to be the best tool that can function as an ide replacement
i dont have intellij on linux π
I don't like intellij
dont tell me you're using eclipse
I use vscode
Ahh see that's the cool thing about vscode I don't need 5 ides
Intellij is free
Yea
You need plugins but it supports pretty much any language
No I just made a maven archetype for that so I just run a Linux command and it's all set up
Imagine writing java in vs...
so?
mappings?
spigot mappings ?
Curious what your issue is with it
have you considered using craftbukkits CraftChatMessage.fromJSON
instead of whatever you are using
It works fine unit tests work fine so wheres your complaint minus the fact it's nowhere near as bloated as intellij with features I'll never use
jetbrains fleet hopefully just fixes that
i haver only those methods
what version are you on
1.12.2
considering im forking a 1.5 plugin
Why is the question
Just rewrite it at that point lol
okay should sound more like a rewrite
check this out: https://www.spigotmc.org/resources/messageremover.1400/
Message remove is always such a funny concept because the only thing that does is replay the chat
isnt the ChatComponent api enough?
yes
no nms
but why not just recode that ?
what do you mean
I don't see how that needs packets
just listen to the chat event on highest priority
and then cancel it and send either the same message
or one with the x at the end
to the players online
in fact, this was one of the only plugins I've found that does this functionality without the chat go up rising sharply
I wish this Wait cooldown would always be down you know
wait 2.1926805 seconds π€
I mean, the plugin you are "forking" can also just replay the chat
it is just a matter of how many empty lines you throw
100
Is there a way to create fake fps lag with packets for a single player?
no i lie, 9
but not crash a user just create fake fps lag
I'm creating a minigame
I need this
delta seconds
what kind of minigame wants to lag a player
but I guess you can spam the player with packets ?
yes but what packets? I don't want to crash a user
just make it so the fps decreases
I mean, spawn a lot of invisible armor stands or something
with packets
Β―_(γ)_/Β―
will that lag a server?
if you can create a reader system for all messages sent to the player, and resend them without the player noticing that the chat has been changed
also invisible packet based armor stands would be visible only to that player?
Hmm
well not all messages no
only chat
But eek, I don't have any idea what methods were available in 1.12
i mean all versions too
Why not sending a big explosion packet
tried this, this'd crash a user
i just want to cause fps lag
Oh fps ?
i have found that plugin too, but is bad https://www.spigotmc.org/resources/chat-cleaner-remove-messages-from-chat.48518/
100 armor stands in one location
Thank you, will try
Yeah gl with that
Not just that the plugin is 1.5, there's a high chance the plugin design is bullshit since it's way too old
that doesn't always apply, but it does most of the time in spigot plugins
at least to my experience
Rewriting it from 0 would be a better option imo
i rewrited my plugin twice
((CraftPlayer) player).getHandle().playerConnection.sendPacket(new PacketPlayOutMapChunk(Bukkit.getWorld(player.getWorld()).getChunkAt(X +3, Z +3), 65535, 100));
}```
Like this?
you're only sending one packet
Z
and
Can I get the default hit cooldown of each material?
can anyone help me im completley stumped on this
the plugin becomes null when method is called from another???
java.lang.NullPointerException: Cannot invoke "org.bukkit.plugin.Plugin.getServer()" because "plugin" is null
caused by this
plugin.getServer().getPluginManager().registerEvents(handlerInstance, plugin);
}```
It's random?
Oh attack speed
why
so plugin is null
probably never instantiated
ye but it runs ```public static JavaPlugin getPlugin() {
return JavaPlugin.getPlugin(WhMain.class);
}
but after load it dissapears but i dont think it should be getting garbage collected
when I send playerlist plugin message on BungeeCord channel it automatically send to the plugin incoming message with players on BungeeCord channel?
try using the string method instead maybe? Bukkit.getPluginManager().getPlugin()
So I need to get the attack speed attribute of the item?
nvm found a workaround
hey whats the difference between using the NMS versions of entities?
like Player and CraftPlayer
or Creature/CraftCreature, Fireball/CraftLargeFireball
oh well that thing
CraftPlayer is the implementation of that interface
that grabs the friendly methods and calls the NMS methods
Try passing this from your main plugin file to the classes that need it
Hi guys, i need help with finding a tnt plugin, i am creating the anarhy server, and i need a plugin which can customize the dynamite and the strength of its explosion
u can just send xp to
too
or explosions
which are simpler to do
and idk why would u want to lag a player
and?
he wants to lag the client
not the server
Eitherway
do you guys know
how did spigot
provide a dependency for people to depend on (spigot-api) that only contains the abstraction, but the implementation is in the server jar
i want to do that for a plugin
so that devs can access only interfaces and such
Why
Send exp? Wdym? I just want that player to see it
That is true
yuh
yuh
yo so I have a listener that checks if a player was hit. that works fine. But hoiw do I make it detect if a player was hit by an arrow and who shot the arrow?
i think you can get the projectile
and get the shooter from there
to check if it is an arrow, you can use projectile.getType() == EntityType.ARROW i guess
idk
I have tried it but it wont work well
?
lemme try it again ig idk
Yuh check EntityDamageByEntityEvent, get the damager, ensure its a projectile, ensure the projectile is an arrow, and ensure its shooter is a player pretty much
ok
and yeah, ofc check if the damagee is a player in ur case
how would I find if the damager is a arrow
hi i don't now what but my plugin crash the server after some hours
overload of errors?
possibly
got anything to go on? like perhaps some timings or just a profiler sample instance?
if (event.getDamager() instanceof Arrow arrow) {
arrow.getShooter() //etc
}
ahh ok
No useful info
but how do I get the projectile i9tself
if my class A implements B, i want the user to only see B, not A
cause that brings an error
I mean you grab the projectile from the event
make it 2 packages?
yeah then?
conclure what happened with your name?
and let the player depend on the api one
dunno how the maven dependency thing works but that should be possible no?
i got a message that sends every hour
I truncated the help thing cuz people were pinging me for ridiculous reasons also I am quite busy w/ a mod
I mean the java module system might assist you here
understandableπ₯Ί
what even is that
that seems like pain
I mean its quite powerful
since it works similarly to the bukkit ServicesManager system in a way
(ServiceLoader) but ye
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (sender instanceof Player player) {
sendPlayerToServer(player, "hub");
return true;
}
return false;
}
private void sendPlayerToServer(@NotNull Player player, String server) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
try {
dataOutputStream.writeUTF("Connect");
dataOutputStream.writeUTF(server);
} catch (IOException e) {
e.printStackTrace();
}
player.sendPluginMessage(XEssentials.getInstance(), "BungeeCord", byteArrayOutputStream.toByteArray());
}``````java
@EventHandler
public void onJoin(@NotNull PlayerJoinEvent event) {
Test.sendPlayerList(event.getPlayer());
}``````java
getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
getServer().getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new Test());```Why it doesn't print all players when is only one player on the server? When join another player it works.
is there some guide of it that you know
google java modules, I believe there should be plenty of resources regarding this topic :3
any reason this wouldnt work?
@EventHandler
public void EntityDamageByEntityEvent(EntityDamageByEntityEvent e) {
if(e.getCause() != EntityDamageByEntityEvent.DamageCause.PROJECTILE) {
Projectile projectile = (Projectile)e.getDamager();
if(((projectile.getShooter() instanceof Player)) && ((e.getEntity() instanceof Player))) {
Bukkit.broadcastMessage(e.getEntity().getName() + " was shot");
}
}
}
well it wont work
let me test
ok
yeah im testing sth rn :3
debug it by putting print statements after every if statement
then you know which check fails
new Listener() {
@EventHandler void epic(EntityDamageByEntityEvent event) {
if (!(event.getEntity() instanceof Player damagee)) {
return;
}
if (!(event.getDamager() instanceof Projectile projectile)) {
return;
}
if (!(projectile.getShooter() instanceof Player damager)) {
return;
}
System.out.printf("%s damaged %s",damager,damagee);
}
}
testing this with breakpoints rn
any ideas? ^
Hello everyone, I just have a basic java question.
Do you have a code more optimised than mine ?
...
int timeLeftLong = (int) (module.getTimeLeft() / 1000); // Seconds left
int day = timeLeftLong / 86400; // Days left
timeLeftLong %= 86400; // I rmove these days
int hours = timeLeftLong / 3600; // Hours left
timeLeftLong %= 3600; // I remove these hours
int minutes = timeLeftLong / 60; // Minutes left
return String.format("%dd, %dh, %dmins", day, hours, minutes);
does anyone know how to make a command that toggles a mode. (this is for the plugin that I was using where it broadcasts the message) instead I want it to only do it when a mode is toggled
Ok, works, thank you!
uhhhhhhhhhhhhhhhhhhhhhhh
I need help with a thing if yall dont mind me asking
Im making this taser plugin and i cant figure out how to make it affect other entities and i cant figure out how to make it work within 5 blocks
This is what i have and no it doesn't work:
@EventHandler
public void onInteract(PlayerInteractEvent e) {
Player p = e.getPlayer();
if (e instanceof LivingEntity) {
LivingEntity.add((LivingEntity) e);
}
if (p.getItemInHand().getType() == Material.CARROT_ON_A_STICK) {
p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 100, 250));
p.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 100, 250));
p.addPotionEffect(new PotionEffect(PotionEffectType.GLOWING, 100, 250));
Location origin = p.getEyeLocation();
Vector direction = origin.getDirection();
}
}
}```
Im not the smartest and google wont help me
wait do you want it to work with all entitys or just players
cause just players would work easier
preferably just players yeah
than do instead of LivingEntity do Player
sorry for asking but the add part is still invalid and idk why
any errors?
Cannot resolve method 'add' in 'Player'
hmm gimme a minute
How to use PacketPlayOutMapChunk to get nearby player's chunks?
if you do e.getPlayer, doesn't it get the player that did the event in the first place?
I cant find anything. But all ik is that "add" is not valid in player try finding another way
how would i get the location of the enitity being attacked from an EntityDamageEvent method
e will never be a LivingEntity. Also you're trying to call a non-static method? Actually what's add even supposed to be
okay, thank you
Hey ! Which packet is sended when a player interact ?
Why do you want the packet? You can use the event
hey, i have this code that gives a player a Job (its an enum) :
public enum Job {
CITOYEN(""),
STAFF(""),
VISITEUR("");
Job(String prefix) {
}
}
public HashMap<Player, Job> jobs = new HashMap<Player, Job>();
public void setjobs(Player player, Job job) {
jobs.put(player, job);
}
public Job getjobs(Player player) {
return jobs.get(player);
}
the thing is, if i give job to a player like : setjobs (player, STAFF)
When the player disconects or the server restarts, they have no rank anymore.
How could i fix that
Because I use NMS entities π
use storage solutions use as yml files (inefficienct imo) or a database and store the jobs there instead of an array
You should be able to use the event anyways. Unless you're talking about packet entities
do u have a good tutorial to learn files? cuz thats the only thing i dont know how to do
Thats a packet entity
Thats why the listener don't works
i would learn databases if I were you, more applicable to different programming outside of spigot
okey ! any good tutorials?
I will check again so, thanks
Hey im using the EntityDamageEvent method, how would i get the loction of the entity that has been attacked?
AWS is good database service, the documentation is also good. I recommend redis as it allows you to cache certain bits of data https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/GettingStarted.html
Get started with ElastiCache by following these steps to launch your cluster.
event.getEntity().getLocation();
if ur talking about entities being attacked, it would be entitydamagebyentity event
does this method also work when its a player attacking an entity
If you want to look into where a player is looking at, you may want to work using vectors. Vectors, if you didn't have it in physics, hold a direction and a value. I.e a Vector could be going in straight X direction with a value of 4, meaning it goes 4 in X direction. You need to compare the direction a player is looking at with the location of an entity, like this https://bukkit.org/threads/get-entity-player-is-looking.300661/
yes
if you want only players
then just do if(event.getDamager() instanceof Player)
How do i get the playercount of an server in the same bungeecord network?
the plugin i code is an Bukkit plugin, not an Bungeecord Plugin. but i want to get the playercount of an different server in my Bungeecord network.
is there any way?
How does hypixel skyblock do mob spawning?
oh okay thanks
is it possible to modify the explosion size of primed tnt or does it have to be a creeper
i dont want it for all of the primed tnt tho i just want it for the one im spawning
Any way to optimize this class? If Yes tell me https://gitlab.com/k3310/kp-pvp/-/blob/1.8-1.12/src/me/RafaelAulerDeMeloAraujo/Coins/XP.java
does anyone know of a simple way to make it so players can pull their bows and shoot without having arrows in their inventory?
I have this written in my config.yml, how can I read it?
Like, is it a list, a map?
I meant through the items
It's like this:
items:
cactus: 0
And I want to read all of the key,values in items
I want people to add what they want to the config
Like, every item to the list and it'll be added
Because I will never be able to know the path to each one of them
This is the code for the config file but idk how to find the required thing to get it
public static HashMap<String, Integer> getAllForbidden(Xpdestroyer instance) {
Object map = instance.getConfig().get("items");
HashMap<String, Integer> hashMap = new HashMap<>();
System.out.println(map);
return hashMap;
}
Like, there's nothing for now I'm trying to test and read it but I need to get the configured list
Any way to optimize this class? If Yes tell me https://gitlab.com/k3310/kp-pvp/-/blob/1.8-1.12/src/me/RafaelAulerDeMeloAraujo/Coins/XP.java
?paste
i am trying to save an Object in a file :
https://paste.md-5.net/oqifekoqar.java
https://paste.md-5.net/zeramepaxa.java#L22
i have an error while doing it
https://paste.md-5.net/xiruxitulu.bash
Tnx
make the return type a Map and not a HashMap
why Double.valueOf?
i wouldnt load the file every time you call that method
and i wouldnt save the whole file if you only add one thing
my main class i think
yeah
and ?
oh
yeah but i have an error
if i dont put that
if i dont put the listeneer thing
i have an error
in wich class
which
oh
yeah
i can barely read that
ok its done
lemme try it rn
well idk i thought u needed to implement a class like that
mye
technically you could use a map
and then you pretty much listen to AsyncPlayerChatEvent if you're using spigot
nw :3
How can i remove mob drops from zombies?
clear the drop list https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/event/entity/EntityDeathEvent.html#getDrops()
declaration: package: org.bukkit.event.entity, class: EntityDeathEvent
Thank you
What theme is that?
Which should i use? i know stream would be worse for performance but i think its cleaner
Dont mind the messy code but for some reason I am getting this error in my IDE
Code
@EventHandler
public void onPlayerLeave(PlayerBedLeaveEvent event) {
if (event.getPlayer().getGameMode() == GameMode.ADVENTURE) {
System.out.println(event.getPlayer().getDisplayName() + "was killed because they were in Adventure mode.. soooo");
BukkitTask task = new BukkitRunnable() {
@Override
public void run() {
if (event.getPlayer().isDead() == true) {
Bukkit.getScheduler().cancelTask(task.getTaskId());
} else {
event.getPlayer().setHealth(event.getPlayer().getHealth() - 1);
}
}
}.runTaskTimer(this, 1, 20);
}
else {
System.out.println(event.getPlayer().getDisplayName() + "was not killed because they were in" + event.getPlayer().getGameMode() + "mode.");
}
}
Error
Variable 'task' might not have been initialized```
try removing this exact part BukkitTask task =
Instead of Bukkit.getScheduler().cancelTask(task.getTaskId()) use this.cancel()
since you're inside the run method of a BukkitRunnable
there a reason to use this.cancel() over just cancel()?
this is just cool π
I mean I'd advocate using this whenever possible as you can then see the caller
hey i have this code
public static void main(String[] args){
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"));
writer.write("98lop");
writer.write("\nDev");
writer.close();
} catch (IOException e){
e.printStackTrace();
}
}
to write smth in a file
why
doesnt it work
like i make it run, the file isnt created
and if i put it on ther server
it doesnt either
creating the file is something you do manually
did ya flush the buffer
.flush()
writer.flush() ?
Got it working thank you
yes
where?
prior to closing
still doesnt write
are you sure the file.txt file is the right one ?
I presume FileWriter(String) just uses the user.dir
so any idea why?
no file extensions smh
.?
idk ```java
try (final BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"))){
writer.write("File content!");
} catch (IOException e) {
throw new RuntimeException(e);
}
works well for me
ye works for me as well
I mean final good :3
idk my intellij just finals everything
people are just missing a keyword
how can i change 'Not authenticated with minecraft.net' message to something else
yeah i click on "run"
I mean
the run thing is a mvn build
not a java run
from the looks of it
m8 if your issue was that you just did not execute your code π
π₯²
the long time without a response worries me I was right
well
thing is
that main method does not execute out of thin air
you gotta call it somewhere
in onenable
for instance in your onEnable
yes
and how do i call it in onEnable
do i do it like mains() ?
main();
^that too
the main method is the entry point when executing that jar using java -jar
which you won't do
but pass null might be enough for your so called test
true that
main(null);
k
ye
I read your full question, dont think you need a main method like @eternal night said, call your file writing in the onEnable? Calling main(null) for something like this i never seen
I mean yea, that was mainly for testing
cartierbass is right tho, you don't want/need a main method
Have a method for your file writing > call it in onenable, would save headache
is it possible to add custom suggestions when player is typing a normal chat message?
with packets i think
No, the client will auto complete player names
only with commands i think
So, whatever players are online according to the player (e.g. player info packet -> add player) is what the client will suggest in a chat message
I mean, yeah, you could do that, but that comes with other implications ;p
couldnt you send a command tab completion packet but instead for normal chat?
No, the client won't know what to do with that ;p
Again, it only tab completes player names
When did PDC get added to the API?
Gotchu. Thanks.
?pdc
1.14
aight
1.13 had the CustomItemTag thing
1.14 if Iβm not mistaken
should subcommands be written as dumpReport, dumpreport or dump_report
because usually its like adduser instead of addUser
but dumpreport looks kinda weird or something
but idk
im confused whether or not youre talking about java now
with the convention it would be dumpReport
hmm
but dumpreport looks cleaner
we need a minecraft command naming standard
yes
Heyhey, goed evening π
Is there a way to disable certain minecraft commands such as /pl ?
yes
easiest way is to download luckperms
oke cool π
do people even use google?
That was in my mind but I was also strugling in my code π
imo u shoulnt mess with setting perms in ur own code
better off just using lp indeed
π thanks
can anyone link me to an example of a how to make a subcommand without using an api, im not sure how to create one.
Use the args[] array that's passed in onCommand
args[] being the subcommand.
that was what i was thinking but how would i then have a sub command of a sub command?
args is just an array of everything after the main command
So, for example if they did /tp Player1 Player2, args would be [Player1, Player2]
oh ok i didnt know that
yeah that makes sense thanks π
That is the exact same way all the CLI abstraction APIs work.
Who can help me?
Just ask
Kind of specific
Im creating a bukkit.inv that is useable by the player
the player can put certain itemstacks inside this inventory and it exchanges via exp
how would I go about iterating through the objects placed in that inventory without using a click event?
Like a inventoryCloseevent
Or something along those lines.
CloseEvent could be problematic
Doesn't InventoryClickEvent fit your needs?
When do you want to iterate over the items?
After olayer closes inventory
InventoryCloseEvent
Sorry to interfere, but I have another question.
I'm currently looking into nicer UI varients and I noticed the use of clickable chat components, which I'd like to use.
Problem is, I can't seem to get it working with the 1.12.2 api.
Most, if not all versions that I've seen implementing this used
Player#sendMessage(TextComponent) that aparently doesn't exist for me ?
Also tried using a json formated string, which doesnt seem to work with either
Player#sendMessage(String) or Player#sendRawMessage(String)
I hate events lmao, but I guess I could try
Player#spigot()#sendMessage
...
Very much thank you <3
to toggle a boolean just do boolean = !boolean
then I can run a command if it is true
ok
way too simple. Better use a BooleanTogglerFactory:
public class BooleanToggler {
private final boolean bool;
private BooleanToggler(boolean bool) {
this.bool = bool;
}
public boolean toggle() {
return !bool;
}
public static class BooleanTogglerFactory {
private final BooleanToggler toggler;
public BooleanTogglerFactory(boolean bool) {
this.toggler = new BooleanToggler(bool);
}
public BooleanToggler bake() {
return toggler;
}
}
}
now you can easily do
boolean toggledBool = new BooleanToggler.BooleanTogglerFactory(myBoolean).bake().toggle();
I think that's too simplified for me
bool = bool != !Boolean.TRUE ? new boolean[] {Double.NaN == Double.NaN}[0] : Float.NaN != Float.NaN;
I think we can agree that this is the industry standard to toggle booleans
im trying to get generics better but i need to ask you a question
public static <E> E puanHesapla(E e1, E e2) {
return e1 + e2;
}```
why is this not true
"not true"?
it throws exception
no, it won't even compile
yes
because the Operator "+" is not defined for every kind of object
E can be ANY kind of class
it could be "java.lang.Object"
and "+" is not defined for "Object"
I mean just imagine you'd do this:
Location newLoc = puanHesapla(location1, location2);
this makes no sense. you cannot apply "+" on a Location object
Now that code will lag people servers? https://gitlab.com/k3310/kp-pvp/-/blob/1.8-1.12/src/me/RafaelAulerDeMeloAraujo/Coins/XP.java
I have replaced all my systems to vault and playerpoints
why in god's name are you using static for that
Sorry, I was speaking to Rafael
I have no idea what you're using static for lol
π
static abuse
Horribly terribly wrong
You really need to learn Java and how it works
That's my only advice
fix that indentation too
what is this even supposed to do btw?
Why the compiler give error when i dont make it static
I need to calculate if the input is double or int
because you have no idea what "static" does
Because you don't know what you're doing
because you need to create an instance of the class to call non-static methods
then let people pass an int or a double instead of E
btw generics cannot handle primitives anyway
tbh I don't see anything wrong with those methods being static as they obviously are utility methods. what I'd be upset though would be that you have toe same 2 lines of code 4 times in those methods
if you have the exact same code more than once, you're doing something wrong
BasicDBObject query = new BasicDBObject();
try{
Bson projection = fields(include("name"), exclude("_id"));
col.find(query).projection(projection).forEach(doc ->
System.out.println(doc.toJson()));
cursor.close();
} catch(Exception e) {
System.out.println(e.getMessage());
}
Essentially this is a query that finds all of the fields that include the name "name" for whatever is in my columns, my output for each name is usually
{"name": "WhateverNameIs"}
How can I only access the name inside the actual field itself, so I can compare that string name with something else.
so if name is equal to user online then do whatever next
using mongodb
what even is "col" or "cursor"?
col represents the collection of whatβs in my database
col is a mongodb collection
JsonObject obj = new JsonParser().parse(doc.toJson()).getAsJsonObject(); String name = obj.get("name").getAsString();
could be a temporary solution
So that gets the string inside the field?
my output is usually {βname: βnameHereβ} but Iβm just trying to access βnameHereβ
yeah, do what joestr said
requires GSON though
So what Iβm doing is just formatting an object into json but what you did was format it into a string so I could access whatever is inside the field?
Okay Iβll try that in a sec
public static void main( String[] args ) {
String json = "{\"name\": \"mfnalex\"}";
JsonObject obj = JsonParser.parseString(json).getAsJsonObject();
String name = obj.get("name").getAsString();
System.out.println(name);
}
this prints "mfnalex"
Can someone guide me on where to look for custom enchants. When searching it's normally outdated.
just identify your custom enchants by adding PDC tags to the item meta
I just looked it up. It's a BSON document you could also try calling doc.get("name") directly.
BSON, GSON no wonder everbody is confused
Someone help in pm?
If you have a question, please just ask it. Don't look for staff or topic experts. Don't ask to ask or ask if people are awake or available. Just ask the question to the channel straight out, and wait patiently for a reply. Make sure you use the right channel regarding the topic of your question. Create a thread in case the channel is already in use!
Thanks your previous way worked, I would have to try that as well
Basically, it's a bukkit inventory that opens and takes in certain items (ingame currency items) and iterates through them and sends amounts of exp based on whats put in
How do I store the items in the inventory so I can stick the contents into an array?
Im using InventoryCloseEvent right now but I think that a player putting in the item into the inventory doesn't add it to it's contents
It's empty because it's contents havent been set, but I only need to set whats put within the inventory
Inventy#getContents() returns an ItemStack[] containing all the items that were put into the inventory
Well yes, but like I said the inventory contents aren't put in.
It is simply opening a null inventory for the player to put in certain items
I just need a way for the items put into the null inventory opened for the player via command to be added to a itemstack[]
I have no idea what you mean
if a player puts sth into the inventory, then it's inside the inventory
also what is a "null inventory"? You mean an inventory with no holder?
as I said, that's what Inventory#getContents() is for
I can just send code.
@Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ if (sender instanceof Player){ Player player = (Player) sender; Inventory exchangeGui = Bukkit.createInventory(player, 27, ChatColor.YELLOW + "Exp Exchanger"); player.openInventory(exchangeGui); } return true; }
|| @EventHandler public static void rewardExp(InventoryCloseEvent e){ if (e.getInventory().getSize() == 27){ ItemStack[] inv = e.getInventory().getContents(); Player player = (Player) e.getPlayer(); for (ItemStack item : inv) if(item != null) switch(item.getType()){ case GOLD_NUGGET -> player.setExp(player.getTotalExperience() + 100); case REDSTONE -> player.setExp(player.getTotalExperience() + 1000); case EMERALD -> player.setExp(player.getTotalExperience() + 10000); } } }||
what exactly isn't working? does the first if statement eveluate to true?
What event is triggered when player gets kicked for having invalid session
Command is ran than blank inventory is opened for a player to put in certain items in.
Then a listener listens for when that specific inventory closes
then gets the items in an itemstack array that the player put in
hm not sure, try AsyncPlayerPreLoginEvent and check if the result is KICK_OTHER
Kk
Console is throwing lots of errors
?paste
it's empty?
remove trailing slash
spigot-1.12.2.jar π
Caused by: java.lang.IllegalArgumentException: Experience progress must be between 0.0 and 1.0 (1000.0)
you can only set Exp to a value between 0 and 1
you have to use giveExp(amount)
sorry to hear that
Im creating this for someone else, so I don't really have a choice in the matter
it does exist
even in your 5 year old MC version it exists: https://helpch.at/docs/1.12.2/org/bukkit/entity/Player.html
wants me to switch to java 14
that's fine I guess, maybe because its embedded in a switch statement.
you are using the enhanced switch
just use a regular switch
I see my issue now, I just switched the version. For some reason intellij wasn't initially telling me
until I did getExp
Works fine, thank you all for the help.
for(ItemStack item : myInv.getContents()) {
if(item == null) continue;
switch (item.getType()) {
case GOLD_INGOT:
event.getPlayer().giveExp(10);
break;
// etc...
}
}
how can i control what type input for
i mean if its int, double?
why do you need an "add" method anyway?
why don't you just do number1 + number2 ?
Who the heck needs a method for that
also obviously all you need is this
public static int sum(int num1, int num2) {
return num1 + num2;
}
public static double sum(double num1, double num2) {
return num1 + num2;
}
?paste
cant we do this in one method?
if you are fine with it returning a double, then yes
public static double sum(double num1, double num2) {
return num1 + num2;
}
this works for all kinds of numbers
but it will always return a double
as I already said, generics do not support primitives
f*ck generics
Are you sending this in reply to me?
Because if so I am very confused and I think you have a misunderstanding of the point and functionality of the program.
why? you are trying to create a totally useless method
just directly add your numbers
why do you need a method for this
how is add(1,2) easier than 1+2?
how do you get the itemstack that a player picked up? EntityPickupItemEvent doesn't give you an itemstack, but just an item reference.
there are no generics for primitives because primitives are not objects
it makes no sense for them to be allowed in generics
π thank you for explaining
you can do weird stuff like this
public static Number sum(Number num1, Number num2) {
return new BigDecimal( num1.toString() ).add( new BigDecimal( num2.toString() ) );
}
but now that will always be a boxed "Number" and you can't just do
int result = sum(1,2);
By chance does this look stupid as hell
the java number interface is really strange
its really dumb how you cant perform operations on it
come the day where operator overloading exists, the number interface will be useful
true but I also don't see a reason for when this would be needed
i'd just make overloaded functions for int, double, etc. personally this is easier
I still wonder why someone would need a "sum" function
fair x + y + z + h is far simpler
nice I made my own permissions core, 70% done
hey is there anyway to add in multiple outcomes for 1 crafting recipe? for example the converting logs to wood
https://github.com/JEFF-Media-GbR/MorePersistentDataTypes/blob/master/src/main/java/com/jeff_media/morepersistentdatatypes/datatypes/collections/MapDataType.java
This is probably the most complicated I ever did in generics and I've learnt a LOT from this. many stuff seems random at first in generics but in the end, it all makes sense
maybe a static add function for x amount of custom objects would be useful since operator overloading isnt a thing
IIRC you can have multiple input choices (RecipeChoice) but you cannot do that for the output, IIRC
dam, that sucks
every Recipe always only has one output ItemStack
isnt there stream.sum
yeah of course but you could also just register the recipe X times. but it won't show up as neatly in the crafting book as it does for vanilla recipes
IntStream.sum
idk. lol. java isn't my primary language.
alright, is this pfp better? lol
When initializing a class using reflection, I'm wanting to provide dependency injection if a class's constructor has a typeof JavaPlugin as the constructor argument
When using newInstance(theJavaPlugin) I get the warning I get "No arguments expected" is this warning safe to ignore or am I doing this all wrong for providing a constructor argument for said class?
SO just to confirm making something shown in the images below isnt possible with spigot?
You can. Recipe groups
So long as they have the same group, they'll show up like that
didn't know either, nice. but still requires multiple recipes to be registered
Yes it does
cool thank you ill look more into that
The use of RecipeChoice will cycle the item types in the single recipe
it's weird though
but a group will show that little category thing
why doesn't setGroup take a namespacedkey
No real reason for it to
well two plugins could use the same group name and then you have two unrelated things grouped
everyone now uses the literal yourplugin string
wait so if I put them in a group will it cycle through like the door does? or would I have like 5 differnet recepies that can all be right clicked to see the group?
You would have to register 5 different recipes
Set their group to the same string, it will show like the doors do
okay cool ill try that out right now thank you π
is it on purpose that EntityPickupItemEvent doesn't contain the itemstack that was picked up?
so just get the itemstack?
ive seen Item#getItemStack but how tf does that work?
ok, im going to try it and see if im just stupid
an Item is basically an "ItemStack" laying around in the world
Item = ItemStack tile entity
rotating 2 sided sprite
βΉοΈ
i like that one mod that makes the item drops realistic
adds more life to the game
well you learn somethin new every day
i did not realize that you could get a valid ItemStack from Item
π€¦ββοΈ :)
yipee! it worked!
https://paste.md-5.net/bibetomena.php
Update learned you need to get the constructor with a JavaPlugin argument itself, 
that is broken. lol
how come if you set an entities velocity they go super fast for like 1 tick and then just fall
It may be something to do with that one gamerule. It might show once you make it once.
I crafted it once and I also send that recipe to every player