#help-development
1 messages ยท Page 186 of 1
is the item made by a player or given by a player trough a command, or found in chests?
well I was planning for it to be crafted
oh!
okay
so I got an idea
Assign to each item a pdc entry called "binding" or whatever you want, and set it to a random UUID
Then in the database use that same UUID to store a list of items
Then whenever an item is clicked, fetch the data and display it (maybe also cache it)
that way the items are stored in a database, but bound to a uuid
oh shit thats actually a pretty good idea
yeah
my idea was actually semi similar accept without the database
I was going to just store the item stacks in PDC
That would be worse
๐ ik lol which is why I asked
if the item got deleted the items would be deleted as well, in this way you can have a recovery period
so like delete items after a week, so you can do other stuff in case
like refunding in case of a glitch
not sure why you are trying to avoid a database
I wasn't
pdc isn't going to be better, the only advantage it would provide in using that is convenience but nothing more
yeah
I asked here because I figured that was a bad solution and wanted to know a good way to link the items to the DB as far as storage goes
I've never touched SQL in my life do you have any learning materials
w3schools
Everything I've done has always used mongo lol
mongon't
depends how dependent the item is in relation to the inventory
is there going to be different items for different inventories
or does this one item just open their inventories in general
click item -> load inventory
^
then just store in the metadata that is the item to open inventory
nothing more needs to be done other then that lol
mmm DB would be needed so we have persists over restarts though can't afford contents dissapearing in this case
my plugin concept is like a pouch for specific items
sqlite is pretty stable
you could use redis
it has a backup feature
(unlike what most people say, redis is also a disk db, not only in memory)
if you were needing to tie specific items to specific inventories then you could go the route of storing in the item's pdc a UUID you generate ๐
@wet breach
okay thanks my 3am brain makes me like 1000x more slower than normal xD
the unique thing of doing that is you would introduce the concept of being able to lose inventory
even further you could introduce a feature in being able to break into inventories as well
yep :) what I'm going for Cool project I'm really into working on right now
I sat down for 3 hours today and came up with like 10 plugin ideas
I can't wait to release it even though it prob won't get many downloads
So I have a shop GUI in which every item has the "Price" tag as the last element in lore:
I want that price tag to disappear upon player purchasing an item
I made this code but it removes price tag from the placeholder item as well
How do I make it remove last element from lore just from an item that I will give to player, not an actual placeholder?
List<String> lore = meta.getLore();
meta.setLore(lure.subList(0, lore.length() - 1));
meta.setLore(lore);
I think
The issue is, it will update both item in player's inventory and the one in shop that should stay the same
clone the item stack
Yeah I did that
Hold up
sounds like you are not obtaining the correct instance of the item
๐
I have 3 doubles
double requiredAmount;
double actualAmount = 0;
double progress = 0;
//code
progress += (actualAmount/requiredAmount)*100;
I get actual amount from player statistics
and then I use a formatter to format it to 2 decimal places
DecimalFormat f = new DecimalFormat("##.00");
progress = (double) f.parse(f.format(progress));
Nice
But I get an exception
Caused by: java.lang.ClassCastException: class java.lang.Long cannot be cast to class java.lang.Double (java.lang.Long and java.lang.Double are in module java.base of loader 'bootstrap')
?paste
I don't use longs?
please paste your entire class :D
Ok
can I just paste the method?
Ill try provide as much info to understand the context
https://pastebin.com/aW3u1mwU
Merchant","Playtime*2*hours|Pick*13*lily_of_the_valley:Walk*2.2*km:Mine*2500*stone:Mine*2500*logs
Merchant is the rank and then the requirements are after the | and the format is "task:amount:material"
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I really hope that isn't the config format you chose
loll
no I am not using config file
map.put("Merchant","Playtime*2*hours|Pick*13*lily_of_the_valley:Walk*2.2*km:Mine*2500*stone:Mine*2500*logs");
Using a map
also thats not part of the code i sent ๐
If you're not going for a config format then why would you store it like that ๐
import com.cryptomorin.xseries.XMaterial;
import lombok.Builder;
import lombok.Getter;
import net.kyori.adventure.text.Component;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import java.util.List;
public class BookUtil {
@Getter private ItemStack itemStack;
private List<Component> lore;
private List<Component> pages;
private Component title;
private Component author;
@Builder
private static BookUtil of(List<Component> pages, Component title, Component author, List<Component> lore) {
BookUtil bookUtil = new BookUtil();
bookUtil.pages = pages;
bookUtil.title = title;
bookUtil.author = author;
bookUtil.lore = lore;
writeBook(bookUtil);
return bookUtil;
}
private static void writeBook(BookUtil bookUtil) {
ItemStack stack = XMaterial.WRITTEN_BOOK.parseItem();
BookMeta meta = (BookMeta) stack.getItemMeta();
meta.author(bookUtil.author).title(bookUtil.title).pages(bookUtil.pages.toArray(new Component[0]));
meta.lore(bookUtil.lore);
stack.setItemMeta(meta);
bookUtil.itemStack = stack;
}
}```
First time using lombok builder, is this the best way?
you can just do it on the overarching class
wdym
Replace new Component[0] with Component[]::new
d
How does the code look? How can I improve it?
(edit: I changed the code as you said)
You can add the @Data annotation to BookUtil and remove that Getter
huh, nice!
I've recently discovered that lombok also has other functions besides getter and setter, and I am abusing them heavily hahaha
Yeah Lombok can remove a lot of boilerplate code
Do you use it a lot in your projects?
Idk just cause I needed a rank with requirements without storing in a file
how would u suggest storing it without using config?
So you are going to make it a config??
?paste
no?
how are you storing it then
In a linked hashmap
what about restarts
I don't add or remove anything from the map
So you don't need to store it to a file?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
No i don't
Then there's no reason to store stuff in strings like that
since its a private plugin and when the owner wants to add sum ill just do it inside the code
Ok so should i rather have sum like map<String,List>
it is 100% easier to just create a config
wrong probably 110% easier
They already said they don't need one
Just store a map of String, Group
Group being an object that has requirements and such
Olivo, would you have any alternative ideas for this?
For each type of CreditCard there are limits described in this code. This map should take care of performing these limits and, every 24 hours reset them. This seems to me to be one of the worst codes I could make
https://paste.md-5.net/uxerimesut.cs
so i should make my own class ok
but then how would i know what requirements to go with which rank using String,Group
You put the requirements in the group object
Wouldn't it make sense to have a requirements object then?
that can return task, material and amount
and have Map<String(group), Requirements>
Looks like bad static usage. Anyways you could probably create some methods in the LimitsType class.
limitType.withMaxBalance(value);
Can I safely convert long to double, I use long for getting play time counted in ticks and * by 50 to get to seconds so would that be too long for a double?
also in your map what is <String> is that going to be the group name?
What's an effective method of making multiblocks?
Since cheking surrounding blocks one by one for each orientation doesn't sound too efficient as it would be quite a lot of if statements.
Yeah
You are going to have to check every block in one way or another
You can always see how multiblocks work in Forge and Fabric mods
and if you're worries about lag don't check for multiblocks every block place but instead something like a right click with a specific item and give it a cooldown. When detecting someone breaking a multiblock you can store block locations in a map
When the chunk unloads save the locations (that are in the chunk) in the map to the chunks PDC
hi, how can i make an updated scoreboard? I mean, I have a coins value that takes the value from a database, I want that when the db changes it automatically changes also in the score
Ok makes sense
without having to go out and back
thats why i was thinking wouldn't it make sense for your group object to be named requirements?
How you structure things is up to you
I would keep a group object and have requirement objects in it
This way you can add group methods and such
Alr ty for the suggestion ill structure it properly
Pls
sorry i have never worked with scoreboards before
time to break my head with more reflection
Scoreboards doesnt really need reflections... I guess....
Just some... braincells....
aint talking bout scoreboards
Yeet the c.... I mean whistle XD
How?
its... hard to explain xd
i mean
its good to just
blabla.setScoreboard(asdwdasdasdasdasdassdadsadsa)
but
it gonna kill scoreboard teams
(teams are in scoreboards for some reason)
I will try on youtube
like, you "refresh" your scoreboard with that code, and then you had prefixes. now you dont
only if you used custom prefixes from your own plugin
using NTE will fix it xd
They are enums, it's nothing too bad I assume.
I was attempting this to be able to make it update the overall value of a specific player action (Max balance, TransactionPerDay, ...)
They shouldn't be enums if the values change
guys how can i create baby npc ?
You set the entity meta
breed two of the big NPCs
I'd like an unique method
something like this...
updateLimit(Limit.TRANSACTION_PER_DAY, updateValue, UUID)
(irony)
hum
hm
humhm
limitsType = switch (limit) {
case MAX_BALANCE -> new LimitsType(value, limitsType.maxWithdraw(), limitsType.maxTransactionPerDay(), limitsType.maxDepositPerDay(), limitsType.transferLimitPerDay());
case MAX_WITHDRAW -> new LimitsType(limitsType.maxBalance(), value, limitsType.maxTransactionPerDay(), limitsType.maxDepositPerDay(), limitsType.transferLimitPerDay());
case MAX_TRANSACTION_PER_DAY -> new LimitsType(limitsType.maxBalance(), limitsType.maxWithdraw(), value, limitsType.maxDepositPerDay(), limitsType.transferLimitPerDay());
case MAX_DEPOSIT_PER_DAY -> new LimitsType(limitsType.maxBalance(), limitsType.maxWithdraw(), limitsType.maxTransactionPerDay(), value, limitsType.transferLimitPerDay());
case TRANSFER_LIMIT_PER_DAY -> new LimitsType(limitsType.maxBalance(), limitsType.maxWithdraw(), limitsType.maxTransactionPerDay(), limitsType.maxDepositPerDay(), value);
};```
This should do the trick
public void setup() {
try {
c = DriverManager.getConnection("jdbc:sqlite:" + (Utils.file == null ? ":memory:" : Utils.file.getAbsolutePath()));
Statement statement = c.createStatement();
statement.execute("CREATE TABLE IF NOT EXISTS players" +
"uuid varchar(255) PRIMARY KEY" +
"muted varchar(255) NOT NULL" +
"mutereason varchar(255) NOT NULL" +
"banned varchar(255) NOT NULL" +
"banreason varchar(255) NOT NULL;");
statement.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
public boolean isMuted(OfflinePlayer p) throws SQLException {
Statement statement = c.createStatement();
String uuid = p.getUniqueId().toString();
ResultSet result = statement.executeQuery("SELECT * FROM players WHERE id = '" + uuid + "';");
statement.close();
return result.getBoolean("muted");
}
public boolean isBanned(OfflinePlayer p) throws SQLException {
Statement statement = c.createStatement();
String uuid = p.getUniqueId().toString();
ResultSet result = statement.executeQuery("SELECT * FROM players WHERE id = '" + uuid + "';");
statement.close();
return result.getBoolean("banned");
}``` is this a good way of doing it?
why do people do conn.createStatement(); statement.execute(sql) rather than conn.createStatement(sql); statement.execute()
I understood what you meant, thank you
uh
idk
does it make a difference?
i was thinking i would make a user and it would extend player
and i would put the banned and muted inside of it
so i wouldnt have to get it from the sql file every time
also use preparedstatement
The home of Spigot a high performance, no lag customized CraftBukkit Minecraft server API, and BungeeCord, the cloud server proxy.
?
doesnt matter actually
whats a preparedstatement
i meen like armor stand but the small not the big (: and is there an API
connection::prepareStatement returns a PreparedStatement anyways
brb
so assigning it to a Statement has no effect
How does it matter ๐ค I've always using just prepared
declaration: package: org.bukkit.entity, interface: ArmorStand
connection().prepareStatement("MYSQLCODE HERE");
like SELECT * FROM players WHERE UUID = ?
ok
thanks (:
read the link i sent
why should i use preparedStatement?
lol
Not using statements = not having the ability to manage the data in your MySQL
using statements = having the ability to manage your MySQL
Olivo, did you mean this?
```java
LimitsType limitsType = limitsMap.get(UUID.fromString("123456789"));
limitsMap.put(UUID.fromString("123456789"), limitsType.withMaxBalance(1000));```
anyways can i use methodhandles to gain a lil performance in a situation where i need reflection?
private Connection c;
public void setup() {
try {
c = DriverManager.getConnection("jdbc:sqlite:" + (Utils.file == null ? ":memory:" : Utils.file.getAbsolutePath()));
PreparedStatement statement = c.prepareStatement(("CREATE TABLE IF NOT EXISTS players " +
"uuid varchar(255) PRIMARY KEY " +
"muted varchar(255) NOT NULL " +
"mutereason varchar(255) NOT NULL " +
"banned varchar(255) NOT NULL " +
"banreason varchar(255) NOT NULL;"));
statement.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
public boolean isMuted(OfflinePlayer p) throws SQLException {
String uuid = p.getUniqueId().toString();
PreparedStatement statement = c.prepareStatement("SELECT * FROM players WHERE id = '" + uuid + "';");
ResultSet result = statement.executeQuery();
statement.close();
return result.getBoolean("muted");
}
public boolean isBanned(OfflinePlayer p) throws SQLException {
String uuid = p.getUniqueId().toString();
PreparedStatement statement = c.prepareStatement("SELECT * FROM players WHERE id = '" + uuid + "';");
ResultSet result = statement.executeQuery();
statement.close();
return result.getBoolean("banned");
}``` like this?
yes
did you read any of the link i sent
little bit
when you use prepared statement, you dont inject data into query yourself
i will the basics first
also this probably wont return anything, you have to move cursor iirc
yes
ResultSet#next
a preparedstatement is used like this:
try (PreparedStatement ps = conn.prepareStatement("DELETE FROM players WHERE id = ?;")) {
ps.setInt(1, someId);
ps.execute();
} catch ...```
basically using ? as placeholders and setting them later on
sqlite doesnt support uuid tho, use a BLOB type to store the uuid and not a string
i can give you the code if you'd like
why blob ?
you can use just binary
spoonfeed me pls
it is iirc
error:
Caused by: java.lang.NullPointerException
at net.polarlabs.methods.database.update(database.java:30) ~[?:?]
at net.polarlabs.Commands.Clan.onCommand(Clan.java:53) ~[?:?]
code: database.java
private static FileConfiguration config;
private static File database;
public database() {
database = Main.getDatabase();
config = YamlConfiguration.loadConfiguration(database);
}
public static void update(String path, Object data) {
config.set(path, data);
try {
config.save(database);
} catch (IOException e) {
System.out.println("could not update database" + e.getMessage());
}
}
whenever i call update to update some data from a YML file, it returns NULL ...
to call them ouside of that file
mb, looks like its not in sqlite
ig you havent called your constructor
I just woke up, saw this and now I regret waking up
well anyways, if you wanna save uuid as a blob you can use this
then doing ps.setBytes(uuidToBytes(uuid))
or UUID id = uuid.fromBytes(rs.getBytes("some_column"))
how would that work
why are you initializing static variables in a constructor tho
you wish you could write code this sexy
so should I just remove the constructor ?
go back to bed, today is not the day you surpass the master
can i nest try statememts
yes
Yup
ok
how would I be able to set those varibles then ?
database = Main.getDatabase();
config = YamlConfiguration.loadConfiguration(database);
thenCompose is like a stream#map
in each void methods ?
imma just do a runAsync and join em all internally
also where are your naming conventions smh
Why do they need to be static anyway
a database class which wraps a yaml file ๐ค
Oh my
Lowercase class name 
i have no idea what im looking at
Main class
None of those methods should be static
how would I call them ouside of that class ?
Use the class instance
whats the point of wrapping a yaml file tho
how on earth am I suppose to access these methods without static
?di
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
fuck that
This is basic java man
im not doing dep injection
Alr keep static abusing ๐คท๐พโโ๏ธ
public <classname> <variable> = new <classname>();
yup
thats what i was looking for
example: public MySQL sql = new MySQL(<plugin (only if it depends on it)>);
if your class contains
public JavaPlugin plugin;
public <classname>(JavaPlugin plugin) {
this.plugin = plugin;
}
you will need to do it like
public MySQL sql = new MySQL(plugin);
meanwhile my storage thingie https://github.com/FourteenBrush/xKingdoms/tree/master/src/main/java/me/fourteendoggo/xkingdoms/storage/persistence
(with the code above you basically allow your class to get info from your Loader (Main), so like in BukkitSchedulers you will be able to use plugin, or with plugin.getConfig or something, you can access default config)
?di
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
yea i've used these solution before, but I dont get why that would solve the Null response whenever i call update method
import java.nio.ByteBuffer;?
i've got a command listener, I want to call the database class to update a yaml file
ye
hows that returning an object
magic
when are you calling the update void?
if i dont do the flip() then it returns byte[]
database.search was meant to be database.update()
wait...
yea just gave you an updated screenshot
Trying to save an ItemStack?
yea
have you tried ItemStack item instead of Object item?
uh sure, but if I set itemstack in the update parameters, I would only be allowed to pass in itemstack type of objects ... but I also call the update method to update strings etc ...
uhh... making another update method then? ๐ฅด
like updateString(), updateItem(), etc?
when i removed the static keyword from the update method
it aint the best idea, but is a bit better sometimes to just mess with "harder code you dont know"
ahhhh
yep fixed
yeah I'd give that a try and see if the null exception goes away, thanks ๐
i'm wondering if a ClassValue<T> is just something like a IdentityHashMap<Class<T>, T>?
hmm more like a weakhashmap essentially
Yes
Essentially
But none of the elements can be gced until the map is
With the hash map*
So itโs a teeny tiny bit more efficient
does anyone out there who is good at math know how to get the middle of a cube, which can be rotated up to 90 degrees, but having the corners and the middle between those corners?
I tried to get the x, and the y of these ways but it wouldn't work
So you only have yhe red square locations?
i just want the middle location
hmm 70 lines of reflections to create a db table based on a class
i blended the middle of these corners by taking the x and y and adding to get the middle, but that only works if it was at 0 degrees, now at 45 degrees it wouldn't work
not too bad
What
What do the red marks signify
You arent giving us much info
And what info is there to work with
seems to work
Laughs in mongo
I just keep this information to know if there is a possibility of acquiring the middle of the cube through the red marker
Just make it into a triangle
Get the hypotenuse length
Half it
Or use a linear equation between the two corners
laugh at it https://paste.md-5.net/aviyucizat.cs
i so bad on maths but ok
Y=mx+b type shi
what points do you have?
when I say bad at math I mean even in formulas xd
middlePoint = point between corner3 and corner2
. thoses
wait
or middlecorner - middleLocation
but i dont have the middleLocation
aka corner2 + ((corner3 - corner2) / 2)
hm let me see
if (!(args.length == 1)) {
Utils.sendMessage(p, "&cUsage: /friend list");
return true;
}
List<String> uuids = plugin.config.getStringList("Data."+p.getUniqueId().toString()+".Friends");
if (uuids.isEmpty()) {
Utils.sendMessage(p, "&cYou don't have any friends yet! Add some with /friend add player");
return true;
}
Utils.sendMessage(p, "&aFriends list: &b"+String.join(", ", uuids));
}```
Why is this sub-command not working?
(other sub commands is working well)
i mean
it just sends nothing to me
no messages
no errors
nothing
so for this method i need transform the location#toVector?
plugin.config ๐ค
i just added debugs:
if (!(args.length == 1)) {
System.out.println("1");
Utils.sendMessage(p, "&cUsage: /friend list");
return true;
} else {
System.out.println("5");
}
List<String> uuids = plugin.config.getStringList("Data."+p.getUniqueId().toString()+".Friends");
if (uuids.isEmpty()) {
System.out.println("2");
Utils.sendMessage(p, "&cYou don't have any friends yet! Add some with /friend add player");
return true;
} else {
System.out.println("4");
}
System.out.println("3");
Utils.sendMessage(p, "&aFriends list: &b"+String.join(", ", uuids));
}```
and its working now lol
but why
๐ค
shared instance
uuh magic
lol
no need for, if you have a plugin instance, just use plugin.getCOnfig()
why? cant i use plugin.config?
wdym
plugin.getConfig()???
you can but managing it yourself is unnecessary when you have a perfectly fine method for retrieving it already in the instance
How can I cast long to double? I have 2 long numbers to work out the percentage from, and I get Long cannot be cast to class Double
I see double has a method .longBitsAsDouble would that work in my case?
try using the primitive data types?
help
you initialized the names as null
pff
where
its a NPE I assume
Hello there. I'm trying to make a Flying/Floating sign. I call the BlockPhysicsEvent and I cancel it. But my sign still broke. Do you have any idea why that thing happen ?
My code here
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onSurroundBlockSignBreak(BlockPhysicsEvent e) {
System.out.println(e.getChangedType()); // Debug
if(e.getChangedType().equals(Material.AIR)) {
if(SignShop.getShops().containsKey(e.getBlock().getLocation())) {
SignShop shop = SignShop.getShops().get(e.getBlock().getLocation());
// Check if still item in the shop
if(shop.getAmount() > 0) {
System.out.println("Event cancelled !"); // Debug
e.setCancelled(true);
return;
}
// Remove the shop
SignShop.getShops().remove(e.getBlock().getLocation());
System.out.println("Removed by" + e.getEventName()); // Debug
}
}
}
(In my code, the debug message "event canceled" is fired but the sign break)
damn, use ?paste XD
doesnt that code means its just empty?
exchange the null for "new ArrayList();"
ok
Yes, I write this message to another discord, but I want to use the bukkit api and not another thing
it means that its null and not a list at all, so you cannot add anything to it
ok simple enough ๐
ill try that
you are using #getPlayer(String) both times
it will actually look for player with that name, not uuid
a
How can I check at ProjectileHitEvent if the entity is a player?
Nope doesn't work
long actualTime = player.getStatistic(Statistic.PLAY_ONE_MINUTE)*50;
long requiredTime = timeToLong(requirement);
double time = (double) (actualTime/requiredTime)*100;
percent += time;
still gives an error
any way to improve this? https://paste.md-5.net/aviyucizat.cs
When I'll try to give a player a potion effect is the duration ticks or seconds?
ive been thinking of refactoring some of my projects into different folders and need some inspiration
currently i have events and commands
what other stuff do you have
i usually do things like commands, listeners, storage etc and an utils package with some general stuff
what would storage be for?
storing data
persistence and cache
you want to get division of two longs with decimal ?
current setup is like this
current setup
like player values? (eg. money)
yup I do
you should just cast dividend to double, there is no point in casting after the operation
if youre using the objects and not primitives you can do myLong.doubleValue()
i think
can I do the operation inside of that method?
I've set some lore (text) into a book, how can I remove the lore I added and keep the book vanilla with it's vanilla lore ?
wym the dividend?
dividend/divisor = quotient
Can I use config.getLocation(key) without yaw and pitch?
stringbuilder lmfao
Oh ok makes sense
forgot basic maths
what if the dividend is too long for a double?
anyone ?
I don't think that it could be the case?
How so?
It can maybe loose some least significant bits as it's widening conversion
But I don't think it should matter
alr ty
Someone correct me if I'm wrong
Apparently it's a narrowing conversion
just googled that
๐ค
A widening conversion of an int or a long value to float, or of a long value to double, may result in loss of precision - that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode
I try to do custom mobs but whenever I try they are invisible
Custom Entity:
https://paste.md-5.net/yupopufolo.java
Spawning:
(((CraftWorld) event.getPlayer().getWorld()).getHandle()).addEntity(new WoodWorm(event.getBlock().getLocation()));```
Registering:
```java
new WoodWorm(Bukkit.getWorld("world").getSpawnLocation()).registerEntity("woodworm", 39, EntitySilverfish.class, WoodWorm.class);```
It hits me but I can hit it and its invisible
I sent you oracle docs, conversion from double to long is narrowing
u said its widening
from long to double is widening lol
double foo = 5.2;
long bar = (long) foo; //narrowing
long foo = 1200;
double bar = (double) foo; //widening
according to oracle docs i sent you
Oh so it's the opposite i read that wrong
sorry
from double to long
๐คฆ
Imagine using default command system
Anyone know how to prevent these symbols from coming up when using formatting code in pages?
Im setting the bookmeta to have the pages and wherever it uses a formatting code well you can see what it does
? ๐
bump\
Is there any reason why the HoverEvent doesn't work, and the click event does?
private void addConfirmButton(BookPage page, BookComponent component) {
if (!component.isClickable()) {
throw new IllegalArgumentException("Component must be a button component");
}
String command = String.format("/hybook %s", this.view.getBook(1).getId());
component.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, command));
component.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text("Hello")));
System.out.println(component.getHoverEvent());
// Add to a book
page.addComponent(component);
}
This is the output
HoverEvent(action=SHOW_TEXT, contents=[Text(value=Hello)], legacy=false)
I don't see you spawning the mob anywhere?
Also don't register the entity as a real entity type
That might mess things up when the server tries to send data to the client
is it safe to store stuff like passcodes (temporary) in a hashmap and if no, whats better
Hi all! I have a question how to make it so that when crafting an ItemStack, the name contains not only the name that is in SetDisplayName, but also the nickname of the player who crafted this item
reflection can be wonderful
Use persistent data container
just an annotated class
?pdc
If you want the data shown use lore or sum
How can I use the LocalDate in day month year format?
hmm 302 ms to create a db table with reflections
well ye taking into account that the table already exists
just don't store passwords in string
everything else is fine
just set the player's name in displayname or lore
30 ms now lol
unbelibubul
dunno why it would take less time lol
hu knows
public int findLastUsedID(final JavaPlugin plugin) {
final File newsDirectory = new File(plugin.getDataFolder(), "news");
final File closedNewsDirectory = new File(plugin.getDataFolder(), "closed-news");
int lastUsedID = 0;
if (!newsDirectory.exists() && !closedNewsDirectory.exists()) return lastUsedID;
if (newsDirectory.exists()) {
for (final File file : Objects.requireNonNull(newsDirectory.listFiles())) {
if (file.getName().endsWith(".yml") || file.getName().endsWith(".yaml")) {
final int id = Integer.parseInt(file.getName().replace(".yml", "").replace(".yaml", ""));
if (id > lastUsedID) lastUsedID = id;
}
}
}
if (closedNewsDirectory.exists()) {
for (final File file : Objects.requireNonNull(closedNewsDirectory.listFiles())) {
if (file.getName().endsWith(".yml") || file.getName().endsWith(".yaml")) {
final int id = Integer.parseInt(file.getName().replace(".yml", "").replace(".yaml", ""));
if (id > lastUsedID) lastUsedID = id;
}
}
}
return lastUsedID;
}
is there a more efficient and elegant way to do this? I am walking through all the YML files in 2 directories to fetch the last used id. maybe this can be better with something from Apache IO, or Files.walk, anything?
do not assume dir.listFiles will return smth notnull
lastUsedID = Math.max(lastUsedID, Integer.parseInt(file.getName().replace(".yml", "").replace(".yaml", ""))) but lets not do that ig
it just looks bloat
i guess so
but you made it 10 times faster
kinda confused but when i drop table before, then do create table if not exists, its just 30ms but when idont drop before its like 300ms
if (!newsDirectory.exists() && !closedNewsDirectory.exists()) return lastUsedID;
if (!newsDirectory.isDirectory() && !closedNewsDirectory.isDirectory()) return lastUsedID;
if (newsDirectory.exists()) {
for (final File file : Objects.requireNonNull(newsDirectory.listFiles())) {
if (file.getName().endsWith(".yml") || file.getName().endsWith(".yaml")) {
final int id = Integer.parseInt(file.getName().replace(".yml", "").replace(".yaml", "").replace("id", ""));
if (id > lastUsedID) lastUsedID = id;
}
}
}
if (closedNewsDirectory.exists()) {
for (final File file : Objects.requireNonNull(closedNewsDirectory.listFiles())) {
if (file.getName().endsWith(".yml") || file.getName().endsWith(".yaml")) {
final int id = Integer.parseInt(file.getName().replace(".yml", "").replace(".yaml", "").replace("id", ""));
if (id > lastUsedID) lastUsedID = id;
}
}
}
is this better? by the documentation of listFiles, now this should never be null
Stream.of(newsDirectory.listFiles())
.filter(f -> f.getName().endsWith(".yml") || f.getName().endsWith(".yaml"))
.map(f -> Integer.parseInt(f.getName().replace(".yml", "").replace(".yaml", "")))
.mapToInt(Integer::intValue).max().getAsInt();
maybe cuz connection was already opened before
๐
im closing it after every statement so idk
this could be readable if i were to format it well
i guess
thanks
done
mye time has to do with whether the conn has been opened before or not
now a stable 30ms3
setting up two tables 35ms
even without registering it doesnt show up its invisible
and its spawning
cuz i can get hurt
and hear it
how might I set a radius around a user in chunks?
your question is kinda abstract
wdym
circular?
public abstract void setARadius(player);
square works, but ircular is fine
get chunk XY and subtract radius from both for point 1, then add radius to both for point 2
and you got your square
wheres your return type noob
what?
that's not java
whats point 1?
now it is
point 1 is a chunk
loc.getChunk();
loc is my variable for location of a player
yea
so loc.getChunk() - loc2.getChunk();???
no, yuo want to create 2 more chunk variables. one subtracts radius from the playerchunk pos
and the other adds radius
Could I have an example, I didn't get that lmao
im so bored aaa
sure.
hi
private List<Chunk> getChunksInRadius(Player player, int radius) {
Chunk playerChunk = player.getLocation().getChunk();
int cx = playerChunk.getX();
int cy = playerChunk.getZ();
List<Chunk> chunks = new ArrayList<>();
for (int x = (cx - radius); x < (cx + radius); x++) {
for (int y = (cy - radius); y < (cy + radius); y++) {
chunks.add(playerChunk.getWorld().getChunkAt(x, y));
}
}
return chunks;
}
does this make sense ^ ?
yea, but getting quite a few errors
huh?
Trying to implement it into a pasting logic for world edits API
yea, but I still need to find a radius from a user
calculate the distance from the radius to the user
and paste schematics to fill it
@grim ice
help me if bored
pls
nvm
sowwy
uwu
Hello, how can I let players with specific versions join, even if they don't have exactly the required version. (A solution without Protocollib would be nice)
For example, I want to let somebody join with 1.19, although the server is on 1.19.2 .
via version
via backwards too
- I want to do the plugin on my own.
- I don't want to use Protocollib, which viaversion does.
but uses protocol lib
they use protocol lib
i mean you can still see which packets they use
yes, and I don't want to read the whole protocollib source just to understand how they do it
nah it is very branched
can i ask why you dont want to use viaversion and/or protocol lib
I don't want to use any lib on my server in general / keep as much performance as I can (protocollib also has functionalities that I don't need)
Sounds like you're over optimizing
maybe, but I like it clean with only own plugins
sure. but stuff like viaversion is tough to get right
and viaversion is battle tested
you probably can, just with a hell of a lot of trial and error
it might be possible. but i would have no idea how
ye, I mean I wouldn't care for possible blocks that do not exist in higher version, because I only want to let players with 1.19 join on 1.19.2
so it already should be easier
but still hard, obviously
okay, but if I would use protocol lib, how would I allow players with 1.19 join the 1.19.2 server?
Just use ViaVersion
What version of Minecraft are you making the plugin for?
1.19
Set Java version to 17 and use toList instead of collect
Because im trying to recommend each argument name when args is 1, and if args is more than 1 recommend each List<String> completions from the Argument obj
๐ก
thats a strream
So how would i do it?
.toList()
I need help!
I need a List<String> not List<List<String>> (what said when use toList())
then why doing ::tabcomplete
tabcomplete is a List<String>
๐คฆโโ๏ธ
I mean you were helping me yesterday
But i never could do it
get the argument based on the args and call ::tabcomplete on it?
Hmnn
I dont understand when people talk without examples sorry
how i change the value on a list? example:
spawn-location:
-x: 12
-z: 12
-y: 12
i want change x on 130, how?
hi, i'm trying to run something after left clicking air/block, but idk why event only triggers when clicking block
hey! can somebody help me please? i am trying to skid the code from this video, and for some reason, my plugin doesnt recognize the vault plugin, so it disables. https://www.youtube.com/watch?v=fRxpx0fz_Nc&t
?paste
for loop
i write this
getConfig().set("spawn-location.x", 130);
saveConfig();
and me ๐
thats not even a list
how
no need for a list
maybe just remove -?
and also, if you want to have it as list, you're missing space between - and text
no
shitty
list:
- something
also, vault placeholders arent working, only if i put essentials into to the plugins
just use ```xml
whatever:
x: 1
y: 34
z: 12
^
config.set("whatever.x", 12)
and how i can write the same things on a different method?
wha
Location location = config.getLocation("what-ever");
config.set("what-ever", location);
No need to complicate yourself!!
๐
uhm yes
He just need to get the location with Config#getLocation("path/to/location") and then use Config#set("path/for/location", location here)
Hi all! How to make an item from an ItemStack impossible to rename
Detect when it's renamed and cancel the event
if you want to detect a specific item you can store pdc on it
?pdc
dunno how your stuff works
Help with what?
well what you pasted is really bad
you either need
spawn-location:
- 12
- 12
- 12
or
spawn-location:
x: 12
y: 12
z: 12
Because im trying to recommend each argument name when args is 1, and if args is more than 1 recommend each List<String> completions from the Argument obj
That is what im actually trying to do
also Location is serializable
you can do getConfig().getLocation("spawn-location");
and getConfig().set("spawn-location", location);
what i told him
ye
Because im trying to recommend each argument name when args is 1, and if args is more than 1 recommend each List<String> completions from the Argument obj
But do you know how to recommend the arguments "list" and "info" when you enter /faction. And when you enter /faction info it will recommend the factions "topOne, etc".
always nice when having such exceptions with reflection
hehe
You didnt help me really nice from you
i dont know how your stuff works
return List.of("list", "help");
and you didnt explain very well
But do you know how to recommend the arguments "list" and "info" when you enter /faction. And when you enter /faction info it will recommend the factions "topOne, etc".
I have explained really well LMAo
i know yes
return StringUtil.copyPartialMatches(args[0], Arrays.asList("list", "info"), new ArrayList<>())
And its simple i have 2 classes:
BukkitCommand which extends BukkitComand class (bukkit one)
BukkitArgument
I cannot do that!!!
why not
if (args.length == 1) return List.of("list", "help");
if (args.length == 2 && args[0].equals("help")) return getFactionListOfYourPlugin;
:(
why don't you use CommandExecutor from default spigot api
well get the bukkitargument thing based on the input and call tabcomplete
because it really shity to manage commands
well i don't give a fuck
it's spigot channel
helping with spigot api
not with random API i don't even know name of
that what i was asking here
3rd time i sent the code
this.getNavigation().createPath(new BlockPos(-1, 67, -7), 0);
new BukkitRunnable() {
@Override
public void run() {
getNavigation().tick();
}
}.runTaskTimer(this.plugin, 0L, 1L);
Is this not a way to make an entity move with nms?
Its my own api LMAo
Don't force it to tick like that?
yeah i guess
Im doing a command framework based on BukkitCommand class
PathfinderGoals
well it doesn't move
you said it's not the way
well ye streaming wont work
i answered yeah it's not
you need if statements on that
ifs/switches
is there a pathfindergoal for moving to a specific block?
I forgot how to do it. Take a look at one of the goals
cuz I can't seem to figure out MoveToBlockGoal or smth like that
im wondering if my sql primary key is a varchar, can i use autoincrement?
just debugging
ok, exampl?
I dont catch what you want me to try
if (args[0].intern() == "bruh".intern())
;/
Don't compare strings with ==
send the code on the following link and ill send one
?paste
hmm looks like sql (?, ?, ?) without setting values defaults to null
ok thanks for helping
@chrome beacon
Not reliable
why not
== is instance checking
BukkitCommand - https://paste.md-5.net/iwadomiwug.java
BukkitArgument - https://paste.md-5.net/ofazatinal.java
haha you don't get it
look at the changed code
me corrupting database
two strings may have the same contents but not the same instance
as i said look at the changed code
can you use a generic type as persistentdatatype?
You can create own persistentdatatype
I don;t care about any code. Just answering your question as to why not use ==
to use it later
you can easily compare strings with ==
with true result
literals yes
by placing .intern() method
assuming they have been interned smh
so the == would refer to string pool address for both
EpicBic i also have 3rd class whcih register all my custom command obj into the CommandMap
you know what we're talking about ๐ฅบ
Is it with this goal?
@Override
public List<String> tabComplete(CommandSender sender, String label, String[] args) {
if (args.legnth = 1) return StringUtils.copyPartialMatches(args[0], Arrays.asList("tab one", "tab 2"), new ArrayList<>());
}
Elgar really thinks i don't know about == ๐
it still will not work
why not
Because i wont know the tab one, etc
I want to achieve the completion system, so that when you use a command and it has an argument or sub command, it will recommend it to you. But at the same time it will recommend you completions of the arguments/sub commands.
You recommended someone to use == to compare string. I'm correcting that mistake is all.
That is the perfect message
if (args[0].equals("tab one")) do stuff here
how i know tab one?
๐
None of you have understand how it orks
im telling you how to do it
i pasted the code which allows == for string comparison
its pretty simple what i need to do: if args[0] == 0 recommend each argument name and if args[1] != null, recommend the command argument completations
heres something i made before just go off what it says and change it to your need
i was already corrected by olivo
shit my brains doesnt work they are not linking what you explain nor examples with mine code
spoonfeeded guy
i can barely understand half the stuff you type and that isnt that hard to change to what you need
upgrade your brain
Using a goal is optional. Look at how the goal moves the entity
wait i will use translator so you udnerstand ๐ฎโ๐จ
and?
he legit told you what to do.
i dont understand the problem here
Ha, I've done this and it was a bitch to make
Not too hard just annoying
how can I set the persistentdatatype as a generic type ?
rn i have something like this
But you catch what i want to do right?
alex see what I have told you
Yes
Let me show you my solution
where naming conventions
I was reading that haha
JB ๐
I'm forcing myself to use Fleet
?
fleet goes brr tbh
is ur ram okay
Yea, it runs about the same as iJ
use vs code
I want to make an auto complete system for mi class BukkitCommand and BukkitArgument.
In BukkitCommand it will work like this:
-
When you enter the /test command and args[0] is null, it recommends you the names of each known argument (Which is already done).
-
When you enter the command /test info and its parameter/argument is null, it will recommend a List<String>
use notepad
real fellas use notepad
use nano
use vim
I use iJ daily
alex I sent u solution already just apply
use irl paper
Fleet is shit
other stone
i will try it
but does anyone know or do i keep looking?
a load of us have sent you ways to do this but you cant just apply it yourself, none of us are going to type it all out for you
read
Generics cant be used that way. Just use Class<?> type
?spoon
Spoonfeed a newbie for a day and they'll come back with more questions. Teach them to find their own answers and you'll both be better off: you won't get stuck answering the easy questions and they'll be much more productive than before.
Fancy but use Logger not println
i don't understand, I just want the method to be generic not the class?
im not seeing a pdc datatype in that method
thats because they're trying to assume the type using generics.
you cant
what does it expect
it has to be class<?>
Is there a way to split a List with player in it into 2 lists?
yea
How?
Depends on how you want it split
Just that booth sides are balanced
one has 2 objects and the other as well
Localdate.now gives me 2022-10-16 date but how can I get 16-10-2022?
public static JavaPlugin plugin;
public static HashMap<UUID, PermissionAttachment> playerPermissions = new HashMap<>();
@SuppressWarnings("static-access")
public SQLiteManager(JavaPlugin plugin) {
this.plugin = plugin;
}
public static void setupPermissions(Player player) {
PermissionAttachment attachment = player.addAttachment(plugin);
playerPermissions.put(player.getUniqueId(), attachment);
BukkitScheduler scheduler = Bukkit.getScheduler();
scheduler.runTaskLater(plugin, () ->{
permissionsSetter(player.getUniqueId(), player);
}, 1L);
}
My question: why is plugin null...?
All I get... is an IllegalArgumentException... saying plugin cannot be null
use time format?
heading over those codes
isnt java plugn meant to be your main class name
Hi a friend told me to use a Map<name, argument> instead of list. Amd this is the final code
Doin... its job... Now only doing permissions...
I think I should rename it to PermissionManager haha
My main class is called Loader
but you can call it whatever you want
that is a hell of a lot more jank than all the methods we all told you
heh Nuumber.class.isAssignableFrom(int.class) should return true, no?
jank?
I mean my goal was to make it on less lines
๐
weird
wish i had
fake
ive been meant to be coding pretty much all day ive just been finding things to not have to doit
to not have to doit?
bruh the type is int and yet the 2nd one fails
hows this false System.out.println(Number.class.isAssignableFrom(int.class));
or is it the other way around
nop
so i wanna know what my target player is inside the listener,
so i would open a gui with a player as target so that when i click something in the gui, it would open up gui2 and that will also have the same player as targer. but how do i make the onInventoryClick event listener recognise what the target player is
bruh is there a dif between INT and INTEGER now too in sql
mye doesnt error anymore
looks like some bug with primary keys
myes reopening connection every time for 8 queries ๐
using batch?
i might but ii cannot interpret that the user is doing things like this and therefore the connection can stay opened
turns out removing static doesnt helps as well at atll xd
oh i see now
for what, you generally shouldnt use arrays tho
list or set
accidentally put public
list
and uhh storing player references isnt the best thing too in terms of gc
store an uuid or a weakref<player> if youre really mad ||like me||
this is my class
i would want to do
luike
public static Pmine getPmine(String name) {
return pmine;
}```
without using a map to get the pmine
or would i have to use a map?
isnt pmineMap.put(name, this); already workin?
yes but, i would have to create a new one everytime
i want to get the pmine later
so i can edit locations, players, ect
you cant get a pmine without instantiating it?
or a singleton?
im not understanding
wdym by that ๐
im just wondering if i could get the pmine with the name without using a map to do that
because ram
uh no?
you shouldnt be wondering about the ram usage of a map lookup too lol
server does already so much map lookups for basic things
hehe fun thing about working with a db is that you shouldnt care too much about slow code
I would like to know why is plugin null... Or how is it null...?
Seriusly I tried lots of things. Once it said config doesn't exists, once it said attachment is null. Now what?
public static JavaPlugin plugin;
@SuppressWarnings("static-access")
public SQLiteManager(JavaPlugin plugin) {
this.plugin = plugin;
}
public void setupPermissions(Player player) {
PermissionAttachment attachment = player.addAttachment(plugin); // error occurred at this line
playerPermissions.put(player.getUniqueId(), attachment);
BukkitScheduler scheduler = Bukkit.getScheduler();
scheduler.runTaskLater(plugin, () ->{
permissionsSetter(player.getUniqueId(), player);
}, 1L);
}
Using either static or non-static, doesn't helps at all btw xd
btw here is an errorlog
java.lang.IllegalArgumentException: Plugin cannot be null
at org.bukkit.permissions.PermissibleBase.addAttachment(PermissibleBase.java:131) ~[paper-api-1.18.1-R0.1-SNAPSHOT.jar:?]
at org.bukkit.craftbukkit.v1_18_R1.entity.CraftHumanEntity.addAttachment(CraftHumanEntity.java:227) ~[paper-1.18.1.jar:git-Paper-152]
at neonowlgery.*************.core.managers.SQLiteManager.setupPermissions(SQLiteManager.java:149) ~[AmariaCore.jar:?]
at neonowlgery.*************.core.managers.SQLiteManager.onJoin(SQLiteManager.java:73) ~[AmariaCore.jar:?]
don't be using statics if you don't know the implications of it
second, instead of using JavaPlugin plugin, just put (main class plugin) instead
unless you are expecting other plugins to be using your methods
Recently I killed that second method completely, because it was breaking stuff
Now to put it back
will kill some things again
so put JavaPlugin plugin instead of plugin?
put YourMainClass
Declaration goes to public JavaPlugin plugin btw
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.
Well
you obviously dont know java
so he recommended you the act of learning java
pretty simple isnt it
or at least take FREE JAVA LESSONS from me
and stop using static when there is no need for it
how would i convert a sentence into each induvidual word