#help-development
1 messages Ā· Page 2106 of 1
then whomever was implementing could then create an enum?
Either way should work
wait
In an API? Probably not
I think it's a good idea to try and build my foundation as an API
For sure
keeps it modular
Feels like enum here would be way too inflexible, especially since you work with some sort of game type hierarchy
yeah
mhm
if its an interface
I'll do the registery thing
though on this
if I say registered "skywars", SkywarsFactory
then I got the GameType by id
I'd then have to cast it back to SkywarsFactory wouldn't I?
yeah but its useful to have the id stored in the game type too
you can do generics trick
oh?
@SupressWarnings("unchecked")
public <T extends GameType> getType(String id) {
return (T) typesById.get(id);
}
where does the T come from?
Feels like you want a type token as well then
from what you need
the compiler decides it
SkywarsGameType skywars = manager.getType("skywars");
now T is SkywarsGameType
^ altho it becomes a little bit hard to keep track of the casts that way as you don't have anything that confirms it
That's pretty cool
?
you need to add T after iut
returns T as well
you havent specified the return type yet
you can also do
<T extends GameType<?>> T getType(String id, Class<T> tClass)
``` for explicit type specification
then getType("skywars", SkywarsGameType.class) will return SkywarsGameType
YESSS just spent 2 hours coding a plugin and it worked first time
noice
actually now i can revise for more important tings
the cursed class
indeed, not sure how i like it tbh
my death messages plugin works
it's as fun as it is a pain in the ass to remember the syntax for
oh
that was about the generics thing
why
you mean at GameManager
its not my design
the game type class is meant to be extended
oh yeah forgot abstract
why tho
Is there any way to detect if a falling block with the tag "beacon" droped as item?
i honestly wouldnt care it makes more sense than a random registry
having a GameManager with running games and game types makes more sense to me than some random Registry<GameType<?>>
and then a List<Game>
yeah it depends per person
Id actually disagree to some extent there
only the sith deal in absolutes
lol
I mean the best part about managers is the fact that they are very abstract
so it can serve as high abstraction layer point
where it delegates to registries, observers etc
tastes like my MatchInstance class
anyone?
i wanna set the ObjectID of the _id of a document in mongodb to a player UUID, idk how to elaborate
i was told it's a little too much for my small knowledge
i barely know what i'm doing
For disabling hitbox of an armor stand, setMarker() should be true or false?
Definitely move to Morphia. I was just using plain old Mongo and Morphia was a massive help: halves the amount of boilerplate code you have to write, avoids a load of NPEs - what's not to love? To set the ObjectID you can just use the @Id annotation on one of the entity fields.
you just said a lot of things that i do not understand
Haha sorry :P
There are definitely tutorials somewhere that'll help, lemme find one
?
https://morphia.dev/morphia/2.2/quicktour.html will help - MAKE SURE YOU SHADE THE MORPHIA & MONGODB DEPENDENCIES CORRECTLY! If you don't you'll get a crapton of ClassNotFoundExceptions when you try to start the plugin.
can using pdc on a player cause the playerfile to get corrupted?
i had the following: i stored an extra inventory in the player file using pdc
and then i killed myself to test it
went to title screen instead of respawn
and when i went back in
i was in an infinite loading terrain loop
when i deleted my playerfile i was able to login again
however since then i wasnt able to replicate the issue
public static void onPlayerJoin(main plugin, Player p)
{
File invDir = new File(Utils.getOwnDir + "inv");
if (invDir.exists())
{
if (new File(invDir.getPath() + '/' + p.getUniqueId().toString() + ".bin").exists())
{
@SuppressWarnings("unchecked")
HashMap<String, ItemStack[]> invs = (HashMap<String, ItemStack[]>) NonReflectables.deserializeBukkitObjectFromFile(invDir.getPath() + '/' + p.getUniqueId().toString() + ".bin");
p.getInventory().setContents(invs.get("inv_main"));
p.getEnderChest().setContents(invs.get("inv_chest"));
if (invs.containsKey("inv_admin")) p.getPersistentDataContainer().set(new NamespacedKey(plugin, "inv_admin"), PersistentDataType.BYTE_ARRAY, NonReflectables.serializeBukkitObjectToByteArray(invs.get("inv_admin")));
}
}
}
public static void onPlayerQuit(main plugin, Player p)
{
File invDir = new File(Utils.getOwnDir + "inv");
if (!invDir.exists()) invDir.mkdir();
HashMap<String, ItemStack[]> invs = new HashMap<String, ItemStack[]>();
invs.put("inv_main", p.getInventory().getContents());
invs.put("inv_chest", p.getEnderChest().getContents());
if (p.getPersistentDataContainer().has(new NamespacedKey(plugin, "inv_admin"), PersistentDataType.BYTE_ARRAY)) invs.put("inv_admin", (ItemStack[]) NonReflectables.deserializeBukkitObjectFromByteArray(p.getPersistentDataContainer().get(new NamespacedKey(plugin, "inv_admin"), PersistentDataType.BYTE_ARRAY)));
NonReflectables.serializeBukkitObjectToFile(invs, invDir.getPath() + '/' + p.getUniqueId().toString() + ".bin");
}
mhm
just some basic pdc
using byte arrays
to store the invs
everything works fine
is there a vanilla bug regarding dying/+going to title screen?
Is there any way to get structures to spawn in custom worlds?
we have a earth server and want it to have villages, ruined portals etc
i wanna recreate the buildmart plugin from mcc with my friend. idk what to start with tho. teams?
What does the doesbounce do to a projectile
it tells you in the javadoc
guys i have a problem.
so i m using this :
public void playersList(String UUID){
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("playerlist.txt"));
writer.write("\n" + UUID);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
to write in a file.
The problem is, if there is already smth in the file, it will delete it andjust write what i tell it to
i want it to add what i tell him to
new FileWriter("playerlist.txt", true)
BufferedWriter writer = new BufferedWriter(new FileWriter("playerlist.txt", true));
like this?
try with resources is a thing š
Hello, I use intellij and i need a lil bit help. Is this the right place?
Whats up?
Is it possible to do item event (compass), where you right click and it opens a gui, and it shows online people heads who have specific /team from minecraft, and when you select that player, the compass tracks the player? I already have an item made.
Hello!
I use getProxy().getPlayer(UUID.fromString(s)) method to get a ProxiedPlayer from my UUID that I stored in a database.
The plugin throws me even though my server is in online mode & string S isn't null.
Can you help?
Thanks
Is gravity disabled or is the ArmorStand a marker?
marker yes
Show the exception or we cant help
NullPointerException sorry
so what should i do ?
so object is null
Marker dont get ticked. Have a runnable that teleports armorstands.
But I don't know why
^^
Show the exception or we cant help
Is it even possible?
Sure. Just open an Inventory, loop over all online players, filter out the ones with a specific team, listen to the InventoryClickEvent and set the compass target.
15:12:08 [GRAVE] java.lang.NullPointerException 15:12:08 [GRAVE] at fr.pr11dev.getsupport.bungeecord.getsupportBungee.onEnable(getsupportBungee.java:82) 15:12:08 [GRAVE] at net.md_5.bungee.api.plugin.PluginManager.enablePlugins(PluginManager.java:265) 15:12:08 [GRAVE] at net.md_5.bungee.BungeeCord.start(BungeeCord.java:287) 15:12:08 [GRAVE] at net.md_5.bungee.BungeeCordLauncher.main(BungeeCordLauncher.java:67) 15:12:08 [GRAVE] at net.md_5.bungee.Bootstrap.main(Bootstrap.java:15) 15:12:08 [INFOS] Enabled plugin getsupport version 0.1.2 by pr11dev
but i need to armor stand be non hitable ( sorry for my bad English )
Okay, thank you so muchh
Have a runnable that teleports armorstands.
getsupportBungee is a very bad name for a class...
Anyways whats line 82?
getProxy().getPlayer(UUID.fromString(s)).getDisplayName();
It's this method.
it's main class, for bungee part of the plugin
Top tier naming
Ok then find out which object in there is null. Im suspecting that getPlayer(...) returns null.
Hi, does someone know ServerTickStartEvent alternative for 1.12.2?
Btw if you use the latest java version then NPEs are way easier to debug.
Thats a paper event.
What do you need it for? You shouldnt run any logic in there.
yeah, I'm looking for an alternative
just to have an action before a tick happens
yeah it's that
Which action and why does it have to happen when the tick starts?
it is possible to save two different economies with vault? i want it to be able to save xp and coins for my KP-PVP plugin
I'm using java 8, i'm coding in MC 1.12.
Upgrading to java 17/18 will fix the bug & will not impact my code?
and why does it have to be an event when the scheduler exists?
Run a task that runs every tick
Not to mention, that's a Paper-exclusive event
Because the order of runnables are not determined. Ive used it to track the exact timestamp when a tick starts so that i know how many milliseconds my runnables are allowed to take.
For example if my runnable starts 32.5 ms after the tick started and they are only allowed to take 40 ms max then i know i can run them at least 2.5 more ms.
it is possible to save two different economies with vault? i want it to be able to save xp and coins for my KP-PVP plugin
to check player's positions, make timers, etc.
Then use a runnable
Right, yeah, you don't need the start of a tick for that
That's more or less what I was getting at. The use-case for calculating the start of a tick are far and few between
Only reasonable one I can think of is Spark's profiler
actually i use playerpoints for XP
and vault for coins
but i want to use only vault for both
if I have a lot of listener classes with ServerTickStartEvent and ServerTickEndEvent, should I just make a runnable in the constructor? But I'm not quite sure how I distinguish tick start from tick end
Do you need offline data?
Anti cheat for example
i think that the XP will only be used for levelling up. so i dont think that i need offline data
Just run the cleanup of the previous tick on the start of the next one.
and coins for purchase kits in shop
pls help
ok, thanks
java 17 is only for 1.18 not for 1.12. use java 8
but i think i could use java 11, as plugins need java 11 in 1.12
well yeah then use java 11
java 8 works too
yeah but java 11 is newer
Certainly not required and few plugins did actually compile against 11 then
But if you can run 11, go for it
someone can awnser me
Something like this:
public class SomeTaskRunnable implements Runnable {
@Override
public void run() {
Collection<? extends Player> players = Bukkit.getOnlinePlayers();
players.forEach(this::cleanUp);
players.forEach(this::execute);
}
private void execute(Player player) {
}
private void cleanUp(Player player) {
}
}
it should look something like this, right?
Bukkit.getScheduler().sheduleSyncRepeatingTask(this, new Runnable() {
public void run() {
// code from ServerTickEndEvent
// code from ServerTickStartEvent
}
}, 1L);
got it, thanks
Last I recall, Vault only supported one currency.
actually i use playerpoints for XP
and vault for coins
but i want to use only vault for both
how i put a second
i use playerpoints. but i dont want to force people to install it
i think in 1.12.2 a code a long time ago, was not like this, u can use marker true and give potions for flying ...
Can you register a command on a specific server using BungeeCord?
or do I have to make a separate plugin
import com.ignelis.tracker.items.ItemManager;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
public class events implements Listener {
@EventHandler
public static void onRightClick(PlayerInteractEvent event) {
if (event.getItem().getItemMeta().equals(ItemManager.kompasas.getItemMeta())) {
Inventory inv = Bukkit.createInventory(null, 6 * 9);
inv.addItem(new ItemStack(Material.APPLE, 64));
HumanEntity player = event.getPlayer();
player.openInventory(inv);
}
}
}
i think im doing something really wrong
you could just check the server the command was used at, but if itās only for one server i donāt see why you would use a bungee plugin
I found a documentation from 2014
where is the inv title?
its enabled/disable for a specific server
ah, i forgot
the thing is I am already doing everything, is there a way to HIDE a command on serverA but not serverB
put it then
Dont check custom items like this. Rather use the PDC of the ItemStack.
like in the tab executor? you could just manually just make it say āunknown command type /helpā if not
yeah when you do / and it shows commands
im only 1 week in plugin create, i don't understand ;-;
Inventory inv = Bukkit.createInventory(null, 6 * 9, "GUI" );
is this good?
Sure this works.
so when i right click compass, it should open?
keep forgetting how useful pdc is
1.8 plugin making is pain
TabCompleteResponseEvent is a thing, how can I check which command? (Bungeecord)
it doesn't work
package com.ignelis.tracker.events;
import com.ignelis.tracker.items.ItemManager;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
public class events implements Listener {
@EventHandler
public static void onRightClick(PlayerInteractEvent event) {
if (event.getItem().getItemMeta().equals(ItemManager.kompasas.getItemMeta())) {
Inventory inv = Bukkit.createInventory(null, 6 * 9, "GUI" );
inv.addItem(new ItemStack(Material.APPLE, 64));
HumanEntity player = event.getPlayer();
player.openInventory(inv);
}
}
}
public class CompassItem {
private static final NamespacedKey COMPASS_KEY = NamespacedKey.fromString("someplugin:custom-compass");
public static ItemStack create() {
ItemStack compass = new ItemStack(Material.COMPASS);
ItemMeta meta = compass.getItemMeta();
PersistentDataContainer container = meta.getPersistentDataContainer();
container.set(COMPASS_KEY, PersistentDataType.BYTE, (byte) 0);
compass.setItemMeta(meta);
return compass;
}
public static boolean is(ItemStack itemStack) {
if (itemStack == null || itemStack.getType() != Material.COMPASS) {
return false;
}
return itemStack.getItemMeta().getPersistentDataContainer().has(COMPASS_KEY, PersistentDataType.BYTE);
}
}
public class CompassEvents implements Listener {
@EventHandler
public void onClick(PlayerInteractEvent event) {
if (CompassItem.is(event.getItem())) {
openCompassInventory(event.getPlayer());
}
}
private void openCompassInventory(Player player) {
}
}
And giving a player the compass item is as easy as:
player.getInventory().addItem(CompassItem.create());
š„ 
You should take a look at this:
?pdc
There are several ways. One would be to listen for the packet that tells the player the list of commands when he joins.
TabCompleteResponseEvent might also work
I only need it to not show when you type / yk
That's really it
just wondering, how does the pdc on itemstacks work? if i had 1 item without a container and another one with it then i stacked them together, do they both get the container?
I don't believe you can stack two items that have value in their containers
They dont stack. The NBT data differs. You cant stack them like you couldnt stack items with lore or different names.
If the value they hold is the same, they can stack, right?
Yes
Its also one way to make an ItemStack unstackable: Just give them a PDC entry with a random UUID as value.
how i put a second
i use playerpoints. but i dont want to force people to install it
If you want a quick approach: Use the PDC of the Player to store their XP
what is PDC
?pdc
it only works for 1.14?
Yes. 1.14+ But everything else is ancient anyways.
I mean 1.16.5 community is still decently big. Bigger than 1.8 and 1.12
not bigger than 1.8
lol yes
1.12 1.16 1.17 1.18 are (on their own) all bigger than 1.8
Because 1.8 is a bubble where everybody thinks they are the biggest community while in fact they are vanishingly small.
fair but like, they are only alive because of hyp
I donāt even know if Hypixel can be considered 1.8
Theyāve probably built their own server from the ground up
what is the best? Vault or https://www.spigotmc.org/resources/treasury.99531/
1.8 is increasingly getting smaller, only amplified from pvp montage and strictly hypixel YouTubers
to plugin developement
nah
probs use some spigot fork
doubt that it will be a replacement for vault. Vault (this old garbage) is just too sticky.
One of the hyp admins was coding on a stream and it looked like spigot
do you recommend switching to Treasury?
is there a way to see vanish insta msgs on pc
Treasury seems neat
Treasury is compatible with vault plugins? Like EssentialsX
how does Container#getContents work? Does it return empty item stacks for empty slots
Never heard of Treasury before, it actually looks really cool
It returns an ItemStack[] with null values on empty slots.
Ok. Will changes to the array be reflected or do I need to setContents
how can I paste a schematic?
Itās definitely built on bukkit/spigot, but I believe the base game has been altered a ton
Programmatically?
of course
?
I've been looking for the best way but web's full of deprecate methods n stuff I wanna know the current best method
What are you trying to do? You can do an index iteration and Inventory implements Iterable<ItemStack>.
You can do a lot without the getContents() overhead.
I'm trying to filter out items with illegal enchantments, so I think I will just turn the result of getContents into a stream and then flatten it back down to an array and put it back into the container with setContents
Are ItemStacks mutable?
This is a lot faster than doing any stream fuckery:
public void removeAll(Inventory inventory, Predicate<ItemStack> filter) {
for (int index = 0; index < inventory.getSize(); index++) {
if (filter.test(inventory.getItem(index))) {
inventory.setItem(index, null);
}
}
}
yep
Yes. The underlying truth is a bit more complicated but they are mutable.
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
public class komanda implements CommandExecutor{
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (sender instanceof Player){
Player player = (Player) sender;
Inventory gui = Bukkit.createInventory(player, 9, ChatColor.RED + "Žmogžudžių gaudytojas");
player.openInventory(gui);
}
return true;
}
}
I made this as a command, how can I make it as a right click event?
wait, so I could've just done itemStack.setAmount(itemStack.getAmount() - 1); and it would update in the inv?!

because most of the times, the implementation copies your ItemStack instance to an identical CraftItemStack instance
why can't it just be consistant.... le sad
It opens inventory, how can i make inventory open when i right click a compass
Listen for the PlayerInteractEvent and open the inventory if the conditions are met
is the map returned by item.getEnchantments mutable
hi, for some reason when i try to add a component to JFrame outside the main function, it doesent get added.
The javadocs are not conclusive on this one. I would just use a combination of
containsEnchantment(Enchantment ench) and removeEnchantment(Enchantment ench)
I want to modify enchantments. Not remove them
In which way? Reduce their level?
yes
it seems like i cant attach a file to this channel: https://www.mediafire.com/file/0cwgcq47841jtfz/code.txt/file
After I modify the ItemStack do I need to set it back into the Inventory or does it just update automatically
or
you can
otherwise
code
getEnchantmentLevel(Enchantment ench) (returns 0 if not present)
addEnchantment(Enchantment ench, int level) <- replaces the level
But you can also try using the map. Tell me if it worked in that case.
well you get an immutable copy
so the map is immutable?
nah
n o
but getEnchantments and ItemMeta::getEnchants will return immutable copies
can you answer this
you need to set it back
ok
sometimes
pretty much always
i wanna remake the buildmart minigame from mcc with my friend. what should i start with? I have already imported WG and WE api
@EventHandler
public static void onRightClick(PlayerInteractEvent event) {
if (event.getItem().getItemMeta().equals(ItemManager.kompasas.getItemMeta())) {
Player player = event.getPlayer();
Inventory gui = Bukkit.createInventory(player, 9, ChatColor.RED + "Žmogžudžių gaudytojas");
player.openInventory(gui);
}
}
}
Should this work? Sorry for being dumb, as i said im only a week into a programming
How can I set an item's durability? The whole damageable interface thing is very confusing to me and I can't find any examples online
mind elaborating how that mingame of yours works
?tas :3
well
get the itemmeta
so, you have a schematic that server tells you to remake, once it remade, you get points :)
Yeah I've got that
and check if it instanceof Damageable
if so, cast it to Damageable and set the durability
so i have this code : ```java
public boolean containsPlayer(String name){
try {
BufferedReader reader = new BufferedReader(new FileReader("playerlist.txt"));
String line;
List<String> listToWrite = Collections.emptyList();
while((line = reader.readLine()) != null) {
listToWrite.add(line);
}
reader.close();
if (listToWrite.contains(name)){
return true;
}else{
return false;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
and
```java
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event){
Player player = event.getPlayer();
System.out.printf("0");
if (!containsPlayer(player.getDisplayName())){
playersList(player.getDisplayName());
playersData(player.getDisplayName(), "CITOYEN", 0);
setjobs(player, Job.CITOYEN);
setmoneyInt(player, 0);
}
}
``` but when i run it, i get an error :
```[14:44:59] [Server thread/ERROR]: Could not pass event PlayerJoinEvent to LunaRpDev v1.0-SNAPSHOT
org.bukkit.event.EventException: null```
https://paste.md-5.net/lenoqusiqu.bash
@scarlet sun are you lithuanian?
yea, why
@EventHandler
public static void onRightClick(PlayerInteractEvent event) {
if (event.getItem().getItemMeta().equals(ItemManager.kompasas.getItemMeta())) {
Player player = event.getPlayer();
Inventory gui = Bukkit.createInventory(player, 9, ChatColor.RED + "Žmogžudžių gaudytojas");
player.openInventory(gui);
}
}
}
Anyways, this is not working
What am I doing wrong
Don't I need to save this back to the item meta?
?paste
I don't think I am doing the right
@ivory sleet so you gotta remake the schematic given on the left square on the square to the right
and so plugin checks if ur done it, if yes, give points, else, do nothing and wait
var stack = ...;
if (stack.getItemMeta() instanceof Damageable damageable) {
damageable.setDamage(4);
stack.setItemMeta((ItemMeta)damageable);
}
or sth
Only works on newer versions of Java :)
With a couple thousand unique players this will single-handedly lag out your server.
the server isnt big
How new? What's oldest version it works on
Even with a few hundred if people log in a bit more often.
sure it isnt. what if it explodes in popularity during the night?
Smthn like Java 16
Ok thx
Besides, you should really only code in either Java 8 or Java 16 since those are the two versions Minecraft uses :p
its a PRIVATE server
so anyone knows about the error?
Then dont write/read to/from a file that often. When the server starts -> Load every entry in a Set<UUID>
and only use this Set during runtime. Then when the server stops you simply write the whole Set to a File again.
ik but thats just a test for smth else, but do you pls know the error?
still looking for where to start btw
reminder i have we and wg api already installed
Yes. Collections.emptyList() returns an immutable collection (like stated in the javadocs and the error)
Use new ArrayList<>() instead
can someone help?
oh yeah
Im suspecting that the UUID is simply not connected on the proxy.
how would I make a message send every time someone shoots a bow using EntityShootBowEvent
Use the EntityShootBowEvent and send a message... lol
but like how would I get the players name my b
ah yeah.
So how can I store a "player identity" in a DB?
^ Like this. You can check if the shooter is a Player by using instanceof
it's fetching data that was saved when the server closed
Use their UUID as primary key
there si still an error
https://paste.md-5.net/wicodekozi.bash
the 2 lines are the same
the code changed a bit :
public boolean containsPlayer(String name){
try {
BufferedReader reader = new BufferedReader(new FileReader("playerlist.txt"));
String line;
String[] listArray = {};
List<String> listToGet = Arrays.asList(listArray);
while((line = reader.readLine()) != null) {
listToGet.add(line);
}
reader.close();
if (listToGet.contains(name)){
return true;
}else{
return false;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
it's what I do. But when the servers restarts, it "rebuilds" the data that was saved when it stopped. And I need to get the ProxiedPlayer object, so what can I do? And the player isn't online when it does that
Arrays.asList(listArray); returns an immutable List. As stated by the javadocs and the exception.
and so what should i do?
Please. Just create a new instance of an ArrayList like its taught in java 101
The ProxiedPlayer is session scoped. It only exists if a user is connected to the proxy.
like that
ArrayList<String> listToGet = new ArrayList<String>(Arrays.asList());
Wouldn't it be super fucking slow to re-read the player list per method call...?
Okay I feel like
You're just trolling
He did not tell you to use the copy constructor of the list
ah ok
He told you to make a new list
Learn how the fuck to make a list because it's one of the most common things in Java
bro like why do you want me to create an other list one is created with that no?
Nah okay you're trolling
BRO
if i m doing smth wrong just explain to me
i dont quite get what you want me to do
Im also getting troll vibes to be honest. The list is completely useless to begin with.
This is like legitimately the worst code you could write
oh nvm i think i get it
wait why is there a hashtag?
Violates LSP, explicit righthand type parameter, empty Arrays.asList as the parameter of a collection's copy constructor.
hi, for some reason when i try to add components to a JFrame outside the main method it wont be added to the frame.
it just means that getEntity is a member of EntityShootBowEvent
i m stupid
i get it
so sry
so I would do
Entity Shooter = EntityShootBowEvent#getEntity;
i created an array but not a list
Okay listen lemme point the shit out for you
calm down bro i created a list and it worked
- You should declare your variable as
List<String> listToGetinstead ofArrayList<String> listToGetbecause of conventions that are semi-complicated to explain. - You do not need to declare the
Stringinnew ArrayList<String>because of the "diamond operator," you can refactor this to justnew ArrayList<>. - It is pointless to create an empty
Arrays.asListwithin the "copy constructor" of anArrayList, the copy constructor copies the contents of another list into the list you're creating. You should remove this parameter to create a new emptyArrayList.
So
In other words
Now this is setting the item durability to 0 š¤
List<String> listToGet = new ArrayList<>();
That's all you need to do.
Uhh
Well the style comes from javadocs
Javadoc conventions state that you should declare parentheses if it is actually important
e.g. if you're differentiating between two overloads
how would i get the itemstack that is in a specific slot in an inventory from an inventoryclickevent?
What are some cool money making plugins?
essentialsX
what is a way to make a Listener that listens for if a bow was shot
listen to the EntityShootBowEvent
yeah but it wont work
Yes it will
public class ArrowShot implements Listener{
@EventHandler
public void EntityShootBowEvent(org.bukkit.event.entity.EntityShootBowEvent event2) {
if(event2.getEntity() instanceof Player) {
Bukkit.broadcastMessage(event2.getEntity().getName() + " threw the ball");
}
}
}
this wont work for some reason
Did you register the listener? Also import your packages instead of using them like this.
lemme check if i did it right though
ok how do I register a listener that is not the Main class?
because I do not need @Override right?
is Collections.emptyList() mutable? šš
thats essentials, not a money making plugin like guishop
No
i beleive Essentials comes with a money thing
methods shouldnt start with a uppercase letter
They do but it suks, everyone uses vault
and thats just a currency holding thing
Write your own plugin then
Im not a femboy coder
Then move to #help-server
how do I register a listener that is not the main class?
How does this at all relate to being a femboy?
Bukkit.getPluginManager().registerEvents(new ListenerClass(), plugin)
or plugin, listener idk
how would i set the time for a ban using target.getServer().getBanList(BanList.Type.NAME).addBan method, i know you need to do target.getServer().getBanList(BanList.Type.NAME).addBan(player, banReason, <time>, mod) how would i make the time 14 days, would i just put 14d otrrr
Create an instance of it and call PluginManager#registerEvents(...) with it
it requires a Data object or smth
so look at the methods in that class
how can i filter out the ones with a specific team online players?
:dynoError: The AFK module is disabled in this server.
Scoreboard team?
no, like /team
Just use epoch seconds for that
it has to be a Date object
ms can be directed converted into date object?
So then its posible to get the hours, seconds, etc from the date?
would this be an issue because this is 14 days in milliseconds: 1.21e+9
yeah it wants it to be a Long not a Date
yep that works, thank you :)
he means heās a femboy but not a femboy coderš
So? why would you say that? It's just so out of context
lmao what
trolling
hey , i have this code to check if smth from a file is smth
:
if(containsPlayer(player.getDisplayName())){
int index = getIndexOfPlayer(player.getDisplayName());
String text = readerFile("file.txt", index + 1);
System.out.println(text);
if (text == "CITOYEN"){
System.out.printf("is");
setjobs(player , Job.CITOYEN);
}
if (text == "STAFF"){
System.out.printf("is");
setjobs(player , Job.STAFF);
}
if (text == "VISITEUR"){
System.out.printf("is");
setjobs(player , Job.VISITEUR);
}
setmoneyInt(player , 0);
}
The output in the console is CITOYEN, but the condition if (text == "CITOYEN"){ doesnt work
anyone knows why?
the output :
yes
How do you like that browser?
the output : [16:26:32] [Server thread/INFO]: CITOYEN
yeah but i like the look of it
String comparisons should be done with .equals() not ==.
Dont compare Strings with ==
It checks for identity not equality.
get ninja'd
20L = 1 second?
There are 20 ticks in a second yes.
apparently firefox is top 1 but i havent used it since the stone ages
im usin firefox rn
š©
chromium was behaving weird š
Btw this is a very, very bad approach to whatever you are doing. And its also way more complicated than it needs to be.
Constantly reading and writing from/to files on the main thread is just super bad.
Same. Def not gonna shove more data down googles throat than i already do.
I dont understand the shity schedules, because the methods args are named bad. So its said: runTaskLater(plugin, runnable, l, l1);
So i dont know what shity means l and l1
Download sources and documentations in your maven project.
sources?
Isnt suppoused to be done once you run the build tools?
š¤
The first one is the delay, second one is the interval in which it will repeat.
Also, I thought that #runTaskLater() only had one parameter which was the delay. Are you sure you didn't mean #runTaskTimer()?
wondering the same thing
Yes lmao im stressed to be using apis that doesnt contain good methods, arguments
so you there is your explaination :)
Oh yeah, sorry my mistake. I mean runTaskTimer()
Oh nice getting an NPE when comparing item displayname with config displayname. Amazing hahahaa
š
No worries. You just have to remember that both the delay and the interval period for the bukkit scheduler are in ticks instead of milliseconds. So 20 ticks is 1 second.
Oh so they are in ms, ticks?
Because long can be anything hour, seconds, etc
No, they are just ticks. You would have to do the math if you wanted it to be something like seconds or minutes.
That what i hate from the apis that are not good coumented
Yes, it takes a long as the parameter, but it's interpreted as game ticks.
But its okay its not a paid api
If im paying for the api of course i will argue
But thanks Shadow and sorry for fucking you
whats the other approach
I can't find any of the working docs where how i should get all online players and add their skulls to gui
is there a way to do it?
Using classes and collections on runtime and only reading/writing data when the server starts/stops.
You should catch the file data on memory and then yes do what ever
the item probably doesnt have a displayname so getDIsplayeName is returnin null? or it is annotated notnull?
That's one of the things that annoys me about item comparisons.
The method #hasDisplayName() can thrown an NPE instead of just returning false.
Split up the task into smaller sub-tasks. First problem you need to solve: How to create a Skull ItemStack from a Player.
Implement the following method:
public ItemStack createPlayerHeadItem(Player player)
I have done a debug when player interact and the displays its there. So maybe my fault its when catching the data
If it's on the player interact event, then the item could be null in certain cases. Or the wrong one.
Thats because there is a single type of material that doesnt have an ItemMeta: air
Allr i dint know that
in eventhandler?
I dont have another way to compare my items
sorry for ping btw
Or atleast i dont kno
@EventHandler
public void onBlockExplode(final BlockExplodeEvent event) {
event.blockList().forEach(x -> {
...
}
}
Would this be a good way to deal with blocks that are being destroyed by tnt or creeper?
I tried it but i think it did not fire up :/
Do you decompile the method?
The PlayerInteractEvent is fine for comparisons, you just need a few more null checks in place to prevent errors from being thrown.
I just wrote it for my plugin, I need to do some special actions when blocks are exploded
No the class this method is in doesnt matter. You should decouple your concerns. Your first is: "How to convert a Player to a Skull ItemStack"
and this method tries to solve this task.
does anyone know how to get all of the permissions of what a user has in a string format
String playerPermissions = Bukkit.getServer().getPluginManager().getPermissions();
getEffectivePermissions() only returned it in an object and someone told me to loop with getPermissions, however, I have no clue how to start
Did you register the listener?
Ah, okay, i did it, what now? I should just add the item to gui?
First show your implementation
Allr thanks, could you check this? Im not so good with sections maybe there its the issue:
ConfigurationSection section = getPlugin().getConfig().getConfigurationSection("Items");
section.getKeys(false).forEach(name -> {
getPlugin().getLogger().info("Item " + name + " (Display: " + section.getString("Display") + ")" + " loaded");
});
I added @EventHandler anotation I think thats all I did for other events
I can share screen if that would help to show
take a look at https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/permissions/Permissible.html#getEffectivePermissions()
declaration: package: org.bukkit.permissions, interface: Permissible
You must use the @EventHandler annotation when listening to events
I did that however, the output is always ```java
[org.bukkit.permissions.PermissionAttachmentInfo@333d287f, org.bukkit.permissions.PermissionAttachmentInfo@3c8e3f0d,
and its never in string format
That's not enough for the events to be registered. You need to register them with PluginManager#registerEvents().
You can get an instance of PluginManager in your main class through #getServer()#getPluginManager().
oh I have this on my main class:
this.getServer().getPluginManager().registerEvents(new Events(),this);
PermissionAttachmentInfo has a method called getPermission() which returns the String representation.
should i just copy what you wrote?
public ItemStack createPlayerHeadItem(Player player)
bruh thanks
wait would it print to console if i use regular System.out.println?
did you call getPermission on it?
Then put some output in the event to see if it's being fired. If it is, then it's a problem with the code for the event. Otherwise, it's not registering properly.
Sure. But that is only a method stub. You need to properly implement it. Thats your first task.
The value should be true (if active) and false (f not active) right?
If you are looping though a configuration section, you need to make sure that you pay attention to the paths.
Nope. This is already solved.
nope I was just using .toString()or wrapping it with String.ValueOf() or parsing it to json, or gson, etc. I tried for like 5 hours not knowing there was a method
public class .... implements ....
something like this?
@lost matrix
Oh i have this path:
# Custom items configuration
Items:
test:
Display: "&6Test"
Material: Compass
Lore:
- "&7This is a test item."
- "&7It has a lore line."
- "&7It has another lore line."
Slot: 1
Command: ""
Not even close.
ah, im sorry
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.
Agree
Will there be more than one item that you can loop through?
yes
Because im looping over each item and creating a memory object for each item
Ok, so you need to pay close attention to how you format your string.
You will want to loop through the config section Items using #getConfigurationSection("Items").getKeys(false) It will return the names of every sub item in the list. So in your case it would just return test.
If you had more, it would be part of the list.
You can use that to then build your string.
If you wanted to get the display name: "Items." + sectionName + ".Display"
If you wanted to get the slot: "Items." + sectionName + ".Slot"
Im sorry if it will look funny, but should i just import import org.bukkit.inventory.ItemStack? I don't really understand..
oh nvm
nvm
sorry
Ohh ok
Ive sent you a method stub. Meaning a method with a specific purpose but no implementation.
Your task is to write code that makes the method do what its supposed to do.
public ItemStack createPlayerHeadItem(Player player) {
// Write your code here
}
In other words (Shadow):
section.getKeys(false).forEach((name) -> {
getPlugin().getLogger().info("Item " + name + " (Display: " + section.getString("Display") + ")" + " loaded");
Item item = new Item(name, getPlugin().getConfig().getString("Items." + name + ".Display"));
item.setSlot(getPlugin().getConfig().getInt("Items." + name + ".Slot"));
item.setCommand(getPlugin().getConfig().getString("Items." + name + ".Command"));
ItemBuilder material = new ItemBuilder().of(Material.valueOf(getPlugin().getConfig().getString("Items." + name + ".Material")));
material.name(getPlugin().getConfig().getString("Items." + name + ".Display"));
material.lore(getPlugin().getConfig().getStringList("Items." + name + ".Lore"));
item.setItem(material.build());
});
Your items would be created properly, but your console output wouldn't be what you expect.
This naming looks scuffed
my eyes
look at the docs
I am confused even if do this and exploded tnt nothing is being send to players:
@EventHandler
public void onBlockExplode(final BlockExplodeEvent event) {
App.plugin.getServer().getOnlinePlayers().forEach(y -> y.sendMessage("Lasagna!"));
}
Did you register the Listener class?
Then it seems that your listener isn't properly registered.
What class is that method in?
main class š
In my Events class which implements Listener and on main class I have:
public void onEnable() {
App.plugin = this;
App.config = App.plugin.getConfig();
this.getServer().getPluginManager().registerEvents(new Events(),this);
}
I sure hope App.plugin and App.config are not, [public static non-final] variables...
Well, that looks right to me. How are you trying to trigger the event? TNT, Creeper?
TNT
why having a config field
Oh yeah. btw: BlockExplodeEvent only triggers when a Bed explodes
whole main class:
package lt.lucy.lucyutils;
import org.bukkit.block.Block;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
public final class App extends JavaPlugin {
public static FileConfiguration config;
public static App plugin;
public void onEnable() {
App.plugin = this;
App.config = App.plugin.getConfig();
this.getServer().getPluginManager().registerEvents(new Events(),this);
}
public void onDisable() {}
}
do a sysout before the player looping
You need the EntityExplodeEvent for TNT and Creepers
@tardy delta
https://gyazo.com/94e2a240f616351d31a905c1fde02237
That is the output after using getPermission
Wouldn't the BlockExplodeEvent also apply to Respawn Anchors if it goes by that logic?
*For the respawn anchor it also fires now i suppose
oh and permissions is a string field not a array
MongoDB. What do you use for serialization? Because this looks scuffed.
An individual permission node sure, but players will have more than one. So it will likely be that they have an array of permissions.
https://prnt.sc/FHl0AKhiqP3q https://prnt.sc/rO2V_xyHl3Lw Why subscriber is a Object and not a PlayerAccount
it makes sense now, i did not realsie that blockexplode is about block exploding not block being blown up by explotion and primed tnt and creeper are both enitities
not sure how to use serialization in mongodb
Hello guys, do you guys have any idea of how i could, possibly modify a line of a file?
Here is an exemple.
For instance, guys, if i have a file where the first line is x and the second one is y.
i want it so that, i can modify the second line by saying that it is the second line that i want to modify and , for instance , replace the y with a z
Document CS1 = new Document("Name", playername)
.append("UUID", uuid);
for (PermissionAttachmentInfo attachment : p.getEffectivePermissions()) {
String permission = attachment.getPermission();
CS1.append("Permissions", permission);
}
in the docs it says that it return the permission name, this wouldnt really make sense
actually one other thing i wanted to ask for now, how do i change block type's blast resistance?
https://prnt.sc/FHl0AKhiqP3q https://prnt.sc/rO2V_xyHl3Lw Why subscriber is a Object and not a PlayerAccount
Looks fine to me. Is there an issue with that code?
Do you want a streaming approach that also works for huge files or do you just have a couple of hundred lines max?
yes there is https://gyazo.com/94e2a240f616351d31a905c1fde02237
it only outputs my permissions as if it were an object surrounded with a string š¤£
depends on the signature of the asFuture method
This wont work. it would only save the last permission.
im trying to use Treasury api
Have you tried outputting it to console? Just to see if it returns what you are looking for?
well could you show the asFuture method?
Document CS1 = new Document("Name", playername).append("UUID", uuid);
List<String> permissionList = new ArrayList<>();
for (PermissionAttachmentInfo attachment : p.getEffectivePermissions()) {
permissionList.add(attachment.getPermission());
}
CS1.append("Permissions", permissionList);
I think its ?learnjava moment
how i change subsbriber to a EconomySubscriber(PlayerAccount)
Because what your code does and what you are doing don't look like they match.
it is a API from a public plugin
Do you want a streaming approach that also works for huge files or do you just have a couple of hundred lines max?
Is your retrievePlayerAccount method generic?
If not you then you need to cast it
I can't, I don't understand what should I do but I really do wan't to learn java, but I don't know from where to start :/
Cast your lambda to Consumer<EconomySubscriber<PlayerAccount>>
?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.
Those are some helpful links.
Yes, but how to find things I need
https://prnt.sc/Y_g-VyU1KzBQ like this?
Search engine
https://www.youtube.com/c/CodingwithJohn this guy has also helped me a lot in understanding basic things. maybe its easier to start with videos @scarlet sun
Nope. The whole lambda.
i guess java doesnt know what T is
mye do what 7smile7 said
public ItemStack createPlayerHeadItem(Player player) {
return .addTexture(new ItemStack(Material.LEGACY_SKULL_ITEM, 1);
}
Is this even the right thing? Probably not
...asFuture((Consumer<EconomySubscriber<PlayerAccount>>) subscriber -> )
This is not even valid java.
So that line = everything's wrong
Hey! does anyone know how to make a random chance that something happens off of a listenr. So like if someone is hit there is a 1% chance that a messege appears when they are hit
new Random().nextDouble()
ok
you can compare that to another number in order to see wether it should do what you want or not
and make the random a field
how to show title/subtitle to player?
player.showTitle(Title.title("Tesxt", "test")); it expects components
Random random = ThreadLocalRandom.current()
Yes sure. Random is your best firend. But dont create a new Random like Shreb suggested. Use the thread bound Random instance
ThreadLocalRandom random = ThreadLocalRandom.current();
get ninjad
alr
is that vanilla java? š
vanilla java lol
I would downcast as ThreadLocalRandom has a ton of extra methods.
Yes
damn, never seen that, thanks š
never took a look at them
what are the downsides to making a new Random()?
I am kinda confused
can you gimme a example of how to use that?
Does anyone have any ideas what the issue is with this: java.lang.NullPointerException: Cannot invoke "org.bukkit.inventory.ItemStack.getType()" because the return value of "org.bukkit.event.inventory.InventoryClickEvent.getCurrentItem()" is null here is the code for the event listener that is causing it: ```java
package dev.jamieisgeek.bangui.events;
import dev.jamieisgeek.bangui.utils.BanMenuUtils;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
public class PunishMenuListener implements Listener {
@EventHandler
public void onMenuClick(InventoryClickEvent e) {
Player p = (Player) e.getWhoClicked();
if(e.getView().getTitle().equalsIgnoreCase(ChatColor.RED + "Pick a punishment")) {
if(e.getCurrentItem().getType() == Material.BOOK) {
String reason = e.getCurrentItem().getItemMeta().getDisplayName();
String player = p.getInventory().getItem(50).getItemMeta().getDisplayName();
Player whoToBan = p.getServer().getPlayerExact(player);
BanMenuUtils.openConfirmMenu(p, whoToBan, reason);
e.setCancelled(true);
} else {
return;
}
} else {
return;
}
}
}
?paste
This exception is as clear as it gets:
return value of "org.bukkit.event.inventory.InventoryClickEvent.getCurrentItem()" is null
What else do you need? š¤·
well i am clicking on an item, so why is it null?
public static boolean roll(double chance) {
return ThreadLocalRandom.current().nextDouble() < chance;
}
Call this method with a value between 0.0 and 1.0 where 1.0 is 100.0%
ty
Because you clicked on an empty slot. What else do you expect to be in there?
else return isnt really a good practice writin that
i didn't i am clicking a book not an empty slot
so it shouldn't be null
just make a check for null and return
it doesnt really matter what it should be if it isnt that
just add a null check, it can be null and you dont want exceptions
you aren't clicking anywhere else on the screen? not even to make the mc window your active window?
Your server tells you otherwise. Make a null check or dont click on an empty slot.
that counts as a click too
wait but where do I put the chance?
method parameter
sorry I am new but where is that š
?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.
you have to call the method and give it that parameter
33.33% chance to say hi:
if (roll(0.3333)) {
System.out.println("Hi");
}
now i have a different error https://prnt.sc/klmURTJHjiud https://prnt.sc/rgZU6s6Sx_Ys
someone knows what i need to cast to solve that
hope this clears it up
where are your brackets >_<
brackets arent in the budget
grr
This is too referential and i never used that plugin. You need to have a really good understanding of how generics work to use futures like this.
Ask the plugin dev.
i think i fixed
My SonarLint would just
at me and add all the brackets as soon as i would clone that.
my eyes cant handle that theme
thats one thing I'm not getting rid of š doesn't hurt to leave out the brackets for easily readable statements and stuff
Honestly this looks a bit like bad API design because you can enforce type safety for stuff like that by keeping the casts internal.
i only leave my brackets out for returns
thats fair
I never leave any brackets out. Ever. Helps me detect code smell much better and if i where to add more later i wouldnt have to first add the brackets in.
if (yes) {
return;
}``` doesnt look good for the brain
issa doin me a brain hurt
does this look like im clicking on nothing
no
i saw people codin like
if (no) {
return;
}
if (no2) {
return;
}
if (no3) {
return;
}```
did you make the check or is it still throwing the exception?
Hold up. Is that bedrock?
yeah using geyser
works for the other menus im using
just
and im using the same code with a different item
soo
cancel the evennt btw
and why bedrock
What's your event code look like?
I see no problem here
hurts my brain
the event gets cancelled after the code is run, but it wont run because it says im clicking on nothing
the IDE would definitely give you a warning with that. At least IntelliJ does
just the version i've use for the longest time, plus dont have a working pc so i use bedrock
people usin eclipse smh
wha
no idea
event code is liked here along with the exception
do you still have an exception or not
Make a null check
what help would that be
Why would you even come here if you wont listen to peoples advise
lmao add a null check to prevent errors
Prevents the nullpointer you are having
Lmao, what help a null pointer would be.
?
Clearly, a null pointer here is just useless!!
gson.toJson() and gson.fromJson will use the @ SerializedName by default without any other code, right?
this.sarcasm = sarcasm * 0.75
Yes
nice
if i add to the nbt of an entity, will that data stay there until the entity has died
It should.
pdc?
Is it alright to read other plugin config file or there is better way to read essentials spawn location?
Nothing's stopping you, it's just recommended that you use APIs instead if they are available.
nope like i suspected adding a null check did fuck all
?
Then you did it wrong
it got rid of the error being in console, no?
Can you please share your code?
hmm thats right it probably has some api, I just need to figure houw to to check if essentials exist so I can integrate with it
well i made it if it was null to just return but it doesn't run any of the code for if it isn't null
.
your code changed, we need to see how you changed the code in order to properly help with it
ask it to the pluginmanager
i mean.. by code...
is 32kb for a database good enough to hold 10,000+ players in it?
player data related
uuid, name, permissions
no
how much space would I need then
lol what question is that
see it like this, if you wanted to have 10000 players in a 32kb database you would have 3.2 bytes for each player. I dont think thats enough
Potentially Infinite? It all depends on how the data is stored.
How it's converted and accessed via memory.
I'm going to guess your NPE happens when you go to drop an item in to a slot
Hm I guess so
A uuid might be stored as a string, or a binary blob, or maybe it could be encoded. Resulting in different sizes of data.
yeah
Names will likely be strings, so they will be relatively large.
Same with permission nodes.
You'd probably want at minimum 10GB of storage for a large database.
I mean, I did the math a while ago for YAML storage and holy shit can it grow to absurd numbers quickly.
I'm talking about Gigabyte range in storage and ram usage.
Yeah I think its best to have some code to delete some rows of users who haven't played in months, unless they donated or have special perms
Databases will obviously be smaller in size, but you could be working with a gigabyte of data if the database is large enough.
how many lines?
Lines didn't matter that much. The file sizes were about 1-5KB so assuming the worst at 5KB per player, it gets large quickly.
But, that's really due to how YAML stores its data.
It's all one big string.
Yea, the base player file is ~1KB and I wanted to keep track of unique stats. So I needed to log several interactions with the player. Resulting in an ever growing file.
jesus
god I'm glad for my plugins I dont have to save player data
Maybe so, but that shouldn't be an excuse to ignore the benefits of smaller file sizes.
5MB is 5MB and could be used in other places if youre able to make the files smaller
It's a real challenge to make small programs. Just take a look at the really old school programs/games that had to be made with less than 5KB of storage.
@EventHandler
public void onRightClick(PlayerInteractEvent e) {
Player p = (Player) e.getPlayer();
ArrayList<Player> list = (ArrayList<Player>) p.getServer().getOnlinePlayers();
Inventory oplayers = Bukkit.createInventory(p, 9, ChatColor.RED + "Žmogžudžių gaudytojas");
for (int i = 0; i < list.size(); i++) {
ItemStack playerHead = new ItemStack(Material.PLAYER_HEAD, 1);
ItemMeta meta = playerHead.getItemMeta();
meta.setDisplayName(list.get(i).getDisplayName());
ArrayList<String> lore = new ArrayList<>();
lore.add(ChatColor.GOLD + "GyvybÄs:" + ChatColor.RED + list.get(i).getHealth());
meta.setLore(lore);
playerHead.setItemMeta(meta);
oplayers.addItem(playerHead);
p.openInventory(oplayers);
}
}
}
what's wrong here?
what isn't working?
GUI isn't opening
[21:09:18 ERROR]: Could not pass event PlayerInteractEvent to Tracker v1.0
java.lang.ClassCastException: class java.util.Collections$UnmodifiableRandomAccessList cannot be cast to class java.util.ArrayList (java.util.Collections$UnmodifiableRandomAccessList and java.util.ArrayList are in module java.base of loader 'bootstrap')
I get this error in console
this is the error
cant cast the getOnlinePlayers to an ArrayList I believe
instead you should make a new ArrayList<>(p.getServer().getOnlinePlayers())
That's because #getOnlinePlayers() returns a Collection.
You need to make a new arraylist instead of casting.
which is immutable
In minigame addons such as bedwars, skywars, can a map be in only one game?
Probably. They likely use copies of a map and remove them once the game is over.
If you only had one map, then you could only have one game running at a time.
something like this?
You could do that, or you could use what Shreb suggested.
I tried, but idk what to change else to make it work, because then how it will find list name
oh nvm
something like this?
Ik it's wrong but what do i need to fix
Collection<? extends Player> players = Bukkit.getOnlinePlayers();
If you sit down and properly learn 2h of java each day for the next 2 weeks then you will have a much greater progress
than dabbling with random java code in Spigot. You wont be able to write a plugin on your own in 3 Months if you keep doing this.
make a proprietary file extension with a very overthought byte scheme
Still not quite right š
No not the same thing
extend pp
Yours wont compile
i mean theres no point in using a wildcard, its just like
more explicit for no reason
Got a bit of a design question. As of right now I have an interface called PlayerDataManager. It's currently responsible for handling everything related to the player. Data, preferences, etc.
My question is should I split the interface up into multiple different interfaces? Something like, PlayerDataManager, PlayerPreferencesManager, etc.
As of right now, it's a bit annoying having to update implementations with the new methods even though they don't really apply to them. However, it's real simple to work with as everything is consistent in the one class.
How can I check this cast?
lmao true.
You cant. You need to provide a generic context. One solution would be to provide a Class<T> as a method parameter.
I see
You could use unsafe casts and keep them internal.
custom
I could yeah, though I'd prefer to make it safe if possible
can I not do a try catch?
It really depends on how you structure your data. For player related data i have a single class: PlayerData that has a ton of sub-data fields like LevelData etc.
Nope
wow I don't have to pay for mongodb storage if im only keeping track of this data because this data is just a few bytes and I have about 282 bytes on free cluster
wait so what happens if it the cast isn't safe?
(500 megabytes) / (300 bytes) =1,666,666 users/w/userdata
Its safe if you strongly encapsulate the casts.
ItemBuilder b = new ItemBuilder(item).setName(name).setLore(description + ChatColor.GOLD + "\nCost: " + ChatColor.GRAY + "$" + price);
The "setLore" class only gets the first element of what I gave it (description) to output, any way I can fix this?
what do you mean by this?
It throws an uncaught exception. Even try catch Exception wont catch it.
Java solos
Ill give you an example
its a Collection<? extends Player> :p
x)
What extends Player?
Well, it kind of does everything at the moment. It was originally for storage systems. YAMLPlayerDataManager, MySQLPlayerDataManager, and so on. So it contained methods for creating, loading, and removing players. Then it got a little bigger with methods for data and user preferences.
Alhamdurillah
CraftPlayer ye
if the max stack size allows it
what
declaration: package: org.bukkit.inventory, interface: Inventory
idk how this works
alr lets say the max stack size is default
but it exists š¤·šæāāļø
and i set an item amount to 65 and give it to a player
will the player get a stack and one item
well that sucks
No. I think the method has a safeguard that puts it to the max size. Either that or it throws an exception.
the docs dont mention an exception
declaration: package: org.bukkit.inventory, class: ItemStack
oh
"in this stack"
probably throws an error
i was looking at the code
/**
* Sets the amount of items in this stack
*
* @param amount New amount of items in this stack
*/
public void setAmount(int amount) {
this.amount = amount;
}
try it
imma just make a loop and fill all the required spaces
its probably an internal error
If you pass in ItemStacks which exceed the maximum stack size for the Material, first they will be added to partial stacks where Material.getMaxStackSize() is not exceeded, up to Material.getMaxStackSize(). When there are no partial stacks left stacks will be split on Inventory.getMaxStackSize() allowing you to exceed the maximum stack size for that material.
alright
Example for a registry using the class as key for internal type safety.
First some product class:
public abstract class Game {
}
Then a factory class for this product:
public abstract class GameFactory<T extends Game> {
public abstract Class<T> getGameClass();
public abstract Game createGame();
}
Now we want to have a registry for centralised access to those factories:
public class GameRegistry {
private static final Map<Class<? extends Game>, GameFactory<? extends Game>> gameFactoryMap = new HashMap<>();
@SuppressWarnings("unchecked")
public static <T extends Game> GameFactory<T> getFactoryForGame(Class<T> gameClass) {
return (GameFactory<T>) gameFactoryMap.get(gameClass);
}
public static <T extends Game> void registerGameFactory(GameFactory<T> gameFactory) {
gameFactoryMap.put(gameFactory.getGameClass(), gameFactory);
}
}
You can see here that i suppressed the warnings for unchecked casts because the only way to add elements to the internal
map is my calling the registerGameFactory method which assures type safety. This is called strong encapsulation. All the casts happen internally
and you assure type safety by that.
Example for registering factories:
public static void registerGames() {
GameRegistry.registerGameFactory(new SkyWarsFactory());
GameRegistry.registerGameFactory(new OneBlockFactory());
}
And here you can see the type safe usage with everyone outside this class not having to do any unsafe casts:
public static void createSomeGames() {
SkyWars skyWars = GameRegistry.getFactoryForGame(SkyWars.class).createGame();
OneBlock oneBlock = GameRegistry.getFactoryForGame(OneBlock.class).createGame();
}
aaah
kk
so I'd done all that expect I was using an id as the key not the class
so there could theoretically be duplicates
or they pass in a string which isn't registered
but yeah by using the class itself there will never be an error
The problem with your approach is that the String doesnt provide any type context...
I tried to make it so that blocking your sword Will make you take 0 damage instead of 0.5 but it didnt work. Can someone help me?
Im guessing you are using a spigot version that is half a decade old?
yeah
No its just i'm not good at coding
well, it would to the user
What spigot version are you using?
cause if I had a game called skywars the id would be "skywars" or similar
1.8.8
but that's a very different thing
Well... this is half a decade old. Anyways: Listen to the EntityDamageEvent and check if the defender is of type Player, then cast, then check if the player is blocking.
If so -> set the damage to 0.
7smile7: Are you using 1.8?
Fawwazpow3145: No
7smile7: Then what are you using?
Fawwazpow3145: 1.8
lmao
He said what version i'm using
he was referring to 1.8 here
lol dw
Should be something in the lines of
@EventHandler
public void onDamage(EntityDamageEvent event) {
if (event.getEntity() instanceof Player player && player.isBlocking()) {
event.setDamage(0);
}
}
THANKS
java 16 in 1.8, yeah right
Just with old java and the isBlocking() might not exists
I just learn coding 2 days ago lol
Yea i tried that before
what exactly did you try?
Who, me?
no, not you
also had you seen what I was doing earlier?
cause this is eerily similar lol
which is probably a good sign
I am rying to detect if a arrow hits a block
and I am wondering how to check if it hits a certain block
also @lost matrix can I register with the GameFactory class instead?
though I'm guessing not considering this..?
I already checked here it does not answer the question
This looks weird. Why is GameType not an enum? Does it need to be dynamic?
GameType is equivalent to GameFactory
what do you mean? seems to me like it's perfectly apt to check the block that's been hit?
gameType.getClass() is not what you want here.
public static abstract class GameFactory<T extends Game> {
public abstract Class<T> getGameClass(); // <- This is the extra method that returns the Class<T>
public abstract Game createGame();
}
why not?
it checks if a block that has been hit not if a certain block has been hit
like how do I check WHICH block is hit