Hallo Leute Ich wollte ein Minecraft Plugin Programmieren,
dabei ist mir ein Fehler auf gefallen.
Hello I wanted to program a Minecraft plugin, and I noticed a mistake.
public void onIteract(PlayerInteractEvent e) {
try {
if(e.getAction().equals(Action.RIGHT_CLICK_AIR)|| e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
Player p = e.getPlayer();
ItemStack bowl = new ItemStack(Material.BOWL);
if(e.getMaterial() == Material.MUSHROOM_SOUP) {
double i = p.getHealth();
if(i != 20) {
if(i > 11) {
p.setHealth(20);
p.getInventory().setItemInHand(bowl);
p.playSound(p.getLocation(), Sound.EAT, 1, 1);
} else {
p.setHealth(i + 8);
p.getInventory().setItemInHand(bowl);
p.playSound(p.getLocation(), Sound.EAT, 1, 1);
}
}
}
}
}catch (Exception exception) {
}
}
und zwar funktioniert dieser code ohne Probleme aber wen ich die soup "MUSHROOM_SOUP" in der Luft rechst klick funktioniert p.getInventory().setItemInHand(bowl); nicht zumindest bekomme ich sie nicht gesetzt.
this code works without problems but when I right click the soup "MUSHROOM_SOUP" in the air it works p.getInventory().setItemInHand(bowl); at least I don't get it set.
Danke bei der Hilfe ;)
MC-Version: 1.8.9 / Spigot
Here are the issues with your code:
Don't catch all exceptions without a reason to. If an exception is thrown in your onInteract method, then there is something wrong with your code.
a.equals(b) is to compare Strings, use a == b for objects other than Strings.
You spelt onInteract incorrectly.
More of a nitpick, but you should name variables with words, not just letters.
e.getMaterial() isn't a valid method. You need to access the player's inventory, get the ItemStack in their hand, and get the Material (type) of the item.
The big block limiting the health to 20 is unnecessary, when you can set the health to Math.min(20, value). This forces the health to be set no higher than 20.
I haven't tested this, but I believe this will work.
public void onInteract(final PlayerInteractEvent event) {
if(event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
final Player player = event.getPlayer();
if(player.getInventory().getItemInHand().getType() == Material.MUSHROOM_SOUP) {
player.setHealth(Math.min(20, player.getHealth() + 8));
player.playSound(player.getLocation(), Sound.EAT, 1, 1);
p.getInventory().setItemInHand(new ItemStack(Material.BOWL, 1));
}
}
}
Ways you can improve this further:
Instead of using the number 20, get the player's max health, as it could be higher than 20 on some servers.
Play a particle, i.e. the one from mushroom soup, when it is consumed.
Add hunger points to the player.
Feel free to contact me on SpigotMC (#lokka30) if you wish to contact me - I rarely check this website.
Related
I've been trying to wrap my head around this for a few days now.. I really have no idea why this isn't working. I looked up online to see if I'm missing something but as far as I know everything should be working perfectly. I don't see any errors but the bot just isn't moving anyone.
The API I am using is located here: https://www.spigotmc.org/resources/discord-bot-api-jda.49783/ running on SPIGOTMC 1.16.5
Everything on the bot I made works perfectly but this.
public void MoveUsers(boolean toChannel) {
if(toChannel) {
//Move players to channel and mute them.
for(VoiceChannel vc : bot.getBot().getVoiceChannels()) {
if(vc.getManager() != null) {
for(Member m : vc.getMembers()) {
if(m != null && m.getUser().getIdLong() != 813656916076527688L) {
if(channel != null && m.getGuild() != null)
botMove(m);
}
}
}else {
Main.getInstance().console.sendMessage("...");
}
}
}else {
//Move players out of channel and unmute them.
}
}
public void botMove(Member m) {
Main.getInstance().console.sendMessage(m.getUser().getName());
m.getGuild().getController().moveVoiceMember(m, channel);
}
In botMove, I print out the username of the person I am trying to move and all of that calls. However the bot itself is not moving the user. Anyone have any solutions to this?
I am developing a multiplayer game in Java built around my own client-server architecture. In short, the client requests a copy of the server's World object 30 times a second and, upon receiving it, sets its client-side copy to the response. This is all done using Java's standard net API.
The issue I am having is that I also store an ArrayList of Player objects in the world, and when I add a Player to this list, the client doesn't get the update. It still receives a copy of the world from the server, but its not up to date.
I experienced a similar problem in a past project that was caused by write/readObject and fixed it by using write/readUnshared, but even that isn't working.
Here's the important stuff from the server end of the communication:
String message;
int sum = 0;
while(active)
{
message = "";
try {
message = in.readUTF();
} catch (IOException e) {
active = false;
System.out.println("Lost connection with client " + socket.getInetAddress());
}
if(message.equals("GETWORLD"))
{
try {
sum++;
if(sum == 100)
main.world.addPlayer(999, 2, 2);
System.out.println("Client requested world (#" + sum + ")");
System.out.println(main.world.players.size());
out.writeUnshared(main.world);
out.flush();
System.out.println("Sent client world (#" + sum + ")");
} catch (IOException e) {
active = false;
System.out.println("Lost connection with client " + socket.getInetAddress());
}
}
if(message.equals("DISCONNECT"))
{
active = false;
System.out.println("Client " + socket.getInetAddress() + " requested disconnect");
}
}
And then the client end:
Object read = null;
int sum = 0;
while(active)
{
try {
Thread.sleep((long)(1000 / 30.0));
if(connected)
{
sum++;
System.out.println("Asking server for world (#" + sum + ")");
out.writeUTF("GETWORLD");
out.flush();
read = in.readUnshared();
if(read instanceof World)
{
World temp = (World)read;
System.out.println(temp.players.size());
frame.panel.updateWorld((World)read);
System.out.println("Got world from server (#" + sum + ")");
}
}
} catch (InterruptedException | ClassNotFoundException e1) {
active = false;
e1.printStackTrace();
} catch (IOException e2) {
active = false;
System.out.println("Lost connection with server # " + socket.getInetAddress());
frame.dispose();
System.exit(0);
}
}
Obviously the sum variable is for debugging.
I further tested this with some output, here's what is scaring me:
Client log:
...
Asking server for world (#99)
1
Got world from server (#99)
Asking server for world (#100)
1
Got world from server (#100)
Asking server for world (#101)
1
Got world from server (#101)
...
Server log:
...
Client requested world (#99)
1
Sent client world (#99)
Client requested world (#100)
2
Sent client world (#100)
Client requested world (#101)
2
Sent client world (#101)
...
You can see here that even though the request numbers match up, there's a clear discrepancy between the number of Player objects in the World object.
Here's the important stuff from the World and Player classes for those curious:
public class World implements Serializable
{
public ArrayList<Room> rooms;
public ArrayList<Player> players;
private QuickMaths qm;
...
public class Player implements Serializable
{
private double xPos;
private double yPos;
private Color color;
int id;
...
I apologize if this is a long yet easy problem. I'm not sure if it's a referencing issue or some other network quirk, but it's really driving me nuts. Thanks in advance.
Your problem is with writeUnshared which is a little misleading.
Read here:
"Note that the rules described above only apply to the base-level
object written with writeUnshared, and not to any transitively
referenced sub-objects in the object graph to be serialized. "
This means that the player object will not be written twice but the old reference to that object in the serialization tree will be used.
The solution to this would be to call the reset method after each write call to ensure that the old written objects will not be referenced again.
So:
out.writeUnshared(main.world);
out.flush();
out.reset();
Hello so I have a question to Java (I'm new so dont excpext too much).
I want to just print everything from the method once and not the whole time.
The method is called 'kuehlschrankInformationen'.
So my question is, how do I just run the methode once and then he starts me asking again, what I want to do. Here is the code(the text is german but I guess it wont make any difference):
System.out.println("Geben Sie ein, was Sie mit dem Kühlschrank machen wollen:");
USER_INPUT = input.nextLine();
while(true){
if (USER_INPUT.equalsIgnoreCase("Ich möchte meinen Kühlschrank schließen")){
TimeUnit.SECONDS.sleep(1);
System.out.println("Das System wird nun herunter gefahren, bis bald");
TimeUnit.SECONDS.sleep(3);
System.exit(0);
}
else if (USER_INPUT.equalsIgnoreCase("Was ist die derzeitige Temperatur im Kühlschrank")){
kuehlschrankTemperatur();
}
else if (USER_INPUT.equalsIgnoreCase("Zeigen Sie mir Informationen über den Kühlschrank an")){
kuehlschrankInformationen();
}
}
And here is the methods code:
public void kuehlschrankInformationen(){
dimensionen = "Die Breite beträgt 178cm, die Höhe 66,8cm & die Länge 59,5cm";
verbrauch = 157;
volumen = 707.5; // in liter
name = "Build Your Body Fat";
gewicht = 63;
try{
System.out.println(name);
System.out.println(gewicht);
System.out.println(volumen +" Liter");
System.out.println("Der Kühlschrank verbraucht " + verbrauch + "kWh");
System.out.println(dimensionen);
TimeUnit.SECONDS.sleep(5);
I would be pretty thankful, if you could help me out
If you want to stop executing the method you put the return statement in the end of this method, if you want to skip an iteration you put continue in your loop skipping one iteration. And if you put break your loop stops and not the method.
I believe you're looking for break
Read the docs while loop
I am working on Parrot AR. Drone project. The libraries are downloaded and implemented in this project from JavaDrone website (https://code.google.com/p/javadrone/downloads/list). However, although I did included the all the correct libraries and make the right class call to get the method, it still cannot return me the correct information. All the results returned appeared to be "false". Any idea what happening on this code? Please help me :(
So what I did is I have 2 buttons : (i) connect (ii) take off buttons. The Connect button function is for establish connection to drone while Take off button is used for make the drone fly move a bit and return me the drone's NAV navigation data. Sadly all the returned NAV data appears not working.
Note : This code is working fine upon code compilation. But it just cannot return me the correct & valid NAV data from drone.
private void jButtonConnectActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("Connect?");
drone = new ARDrone();
data = new NavData();
drone.playLED(10,10,10);
drone.connect();
drone.clearEmergencySignal();
System.err.println("Ready to connect!!");
// Wait until drone is ready
drone.waitForReady(CONNECT_TIMEOUT);
System.err.println("Drone State: " + drone.getState());
// do TRIM operation
drone.trim();
System.err.println("Congratulation! You have connected to Drone!");
System.out.println("You can issue flight commands now!");
batteryStatus.setText("0" + "%");
batteryStatus.setForeground(Color.ORANGE);
batteryStatus.setText("" + data.getBattery());
}
private void jButtonTakeOffActionPerformed(java.awt.event.ActionEvent evt) {
System.err.println("Current Drone State : " + drone.getState().toString());
System.err.println("Taking off");
drone.takeOff();
Thread.sleep(4000);
System.err.println("**********\nMOVE\n**********");
drone.move(0.0f, 150.5f, 500.0f, 0.0f);
Thread.sleep(1000);
System.err.println("******************************************");
System.err.println("Drone Infomation");
System.err.println("Battery Too High ? " + data.isBatteryTooHigh());
System.err.println("Battery Too Low ? " + data.isBatteryTooLow());
System.err.println("Drone Flying ? " + data.isFlying());
System.err.println("Control Received ? " + data.isControlReceived());
System.err.println("Motor Down ? " + data.isMotorsDown());
System.err.println("Not Enough Power ?" + data.isNotEnoughPower());
System.err.println("Trim Received ? " + data.isTrimReceived());
System.err.println("Trim Running? " + data.isTrimRunning());
System.err.println("Trim succeded? " + data.isTrimSucceeded());
System.err.println("PIC Number OK? "+ data.isPICVersionNumberOK());
System.err.println("******************************************");
Thread.sleep(5000);
drone.sendAllNavigationData();
drone.land();
}
Output :
******************************************
Drone Infomation
Battery Life: 0.0%
Battery Too High ? false
Battery Too Low ? false
Drone Flying ? false
Control Received ? false
Motor Down ? false
Not Enough Power ?false
Trim Received ? false
Trim Running? false
Trim succeded? false
PIC Number OK? false
********************************************
Update:
What I did was followed John's suggestion. I did implemented all the neccessary methods and NavDataListener for getting the NavData from drone.
import com.codeminders.ardrone.ARDrone;
import com.codeminders.ardrone.ARDrone.VideoChannel;
import com.codeminders.ardrone.NavData;
import com.codeminders.ardrone.NavDataListener;
public class arDrone extends javax.swing.JFrame implements Runnable, NavDataListener{
public ARDrone drone;
public NavData data = new NavData();
public arDrone(String text) {
//FreeTTS speech text
this.text=text;
}
public arDrone() {
initComponents();
setIcon();
initDrone();
}
private void initDrone() {
try {
drone = new ARDrone();
data = new NavData();
drone.addNavDataListener(this);
} catch (UnknownHostException ex) {
System.err.println(ex);
return;
}
}
public void navDataReceived(NavData nd) {
System.err.println("Testing navDataReceived is running...");
updateBatteryStatus(nd.getBattery());
this.flying.set(nd.isFlying());
}
private void updateBatteryStatus(final int value) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
batteryStatus.setText(value + "%");
if (value < 15) {
batteryStatus.setForeground(Color.RED);
} else if (value < 50) {
batteryStatus.setForeground(Color.ORANGE);
} else {
batteryStatus.setForeground(Color.GREEN);
}
}
});
}
The problem is that you are not doing anything to actually get navdata. You can't just create a NavData object and hope it gets filled in with valid data--It won't.
You need to use the com.codeminders.ardrone.NavDataListener interface.
Implement the NavDataListener interface, and the
navDataReceived method.
Add your listener using the ARDrone
method addNavDataListener.
In your navDataRecieved method
you will receive a NavData object with valid telemetry data.
Do you set the Drone IP address? According to sources the default IP for the drone is 192.168.1.1.
You can call another constructor to set the IP:
drone = new ARDrone(InetAddress.getByName("xxx.xxx.xxx.xxx"));
replace xxx.xxx.xxx.xxx with the actual drone IP.
I have an aplication where is picture with SIN, COS..
TextArea1 will tell somebody: "Click in picture where SIN"
if user do this, textArea2 tell him: "It is corect"
After that, textArea1.append "Click in picture where COS"
-but program is still waiting for clicking to SIN :(
Can you help me and give a little advice to me please?
There is some code:
private class KlikaniMysi implements MouseListener {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getX() + " " + e.getY());
//for finding coordinates (by console)
//textArea2 = "try" at start !!
//textArea1 = "Find SIN" at start !!!!!!!!
if(textArea2.equals("try")){
if( (((e.getX()) > 420)&&((e.getX()) < 580)) && ( ((e.getY()) > 164)&&((e.getY()) < 178) )){
textArea2.setText("");
textArea2.append("RIGHT1");
textArea1.append("Find COS"); //!!!! work!!
//How to stop the IF cycle here and run class KlikaniMysi (mouselistener) again ?
}
else{
textArea1.setText("");
textArea1.append("try again");
}
}else{
if( (((e.getX()) > 586)&&((e.getX()) < 594)) && ( ((e.getY()) > 174)&&((e.getY()) < 282) )){
//This isnt nice, but I dont know how to expres range better.
textArea1.setText("");
textArea2.append("Right2");
textArea1.append("Find TAN");
}
else{
vystup.setText("");
textArea1.append("Try again");
}
}
}
There are many more aspects about this code that are 'suboptimal' but I think your problem is here:
if(textArea2.equals("try"))
You want to test the content of that area, not the area itself, hence change it to
if(textArea2.getText().equals("try"))