So, I'm fairly new to the Bukkit API, and to be honest, the Java class I took last year didn't help me as much as it should have.
I'm going to refer to a post from StackExchange[URL]Bukkit - Using static variables causing problems throughout this post.
The nice user who answered my question told me to use a HashMap, with the UUID of each pair of players for the keys and values. He said to not use Player variables, instead use their UUIDs.
My question is, how can I use methods on players by specifying their UUID? Is there some sort of UUID.toPlayer(UUID) method I could use?
Thanks in advance :D
--Noone has replied to this post on the Bukkit forums, that's why I'm here--
You could loop through all players on the server and try to match their UUID.
public Player getPlayerByUuid(UUID uuid) {
for(Player p : getServer().getOnlinePlayers()) {
if(p.getUniqueId().equals(uuid)
return p;
}
}
}
This was found here.
This will loop through all players online and match UUID.
You could store them in a hashmap of type UUID, Player or string to store the players' names. Then access by,
Player p = hashMap.get(uuid here (key) );
You'd probably add the players once they join and add to a hashmap.
hashMap.put(UUID (key), Player (value) );
If you want to access UUID by player, just switch it around.
A much simpler method works like this
UUID myUUID = myPlayer.getUniqueID();
String configLine = myUUID.toString();
Then
Player newPlayer = Bukkit.getPlayer(myUUID);
Or
Player newPlayer = Bukkit.getPlayer(UUID.fromString(configLine));
Player p = Bukkit.getPlayer(uuid);
source
You can use
UUID.fromString("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
or get it from player.getUUID()
Related
It's been a very long time since I touched object oriented programming, so I'm a bit rusty and would appreciate your insight.
Given a class, for example CDPlayer, that includes the field numberOfTracks and currentTrack and the methods getCurrentTrack and setCurrentTrack, where should I put the functionality to set the current track to a random track? In a method such as setRandomTrack inside this class, or in the application code outside this class (e.g. player1.setCurrentTrack(randomnumbergeneratingcode))?
What are the pros and cons of each of these approaches? Which is easier to use, change and maintain? The above example is quite simple, but how do things change when I want e.g. the random number generation to be flexible - one CDPlayer instance to use a normal distribution for randomising, another to use a flat distribution, another to use a distribution defined by some set of numbers, and so forth.
EDIT
Thanks for the three replies so far.
Consider an extension to the op... After a decent amount of coding it becomes clear that on numerous occasions we've had to, in the application code, change current the track to the track three before it but only on Thursdays (which potentially has non-trivial conditional logic to work properly). It's clear that we're going to have to do so many times more throughout the dev process. This functionality isn't going to be user facing (it's useless as far as users would be concerned), it's just something that we need to set on many occasions in the code for some reason.
Do we created a setThreeTracksBeforeOnThursdays method in the class and break the tight representative model of a CD player that this class has, or do we absolutely stick to the tight representative model and keep this functionality in the application code, despite the pain it adds to the application code? Should the design wag the developers or should the developers wag the design?
Well there is no real benefit to where the code is besides that its more readable.
But in some cases it could be less redundant to put the code in the class, it all depends on the language. For example:
C# code in the class:
private Random random = new Random();
public void setRandomTrack()
{
setCurrentTrack(random.NextInt());
}
C# code outside the class:
Random random = new Random();
CDPlayer player = new CDPlayer()
player.setCurrentTrack(random.NextInt());
The code outside has to create a Random Generator outside the class to generate a random integer, you might have to create the Random Generator more than once if its not visible to the class where you calling it from.
If it is a function that all CD players have, then it should be inside the CDPlayer class.
If it is a function that just a few CD players have, then you should inherit the CDPlayer class and put the function in the child class.
If it is a function that no CD player has, then there is no reason to include it in the class. Does it make sense for the CDPlayer class to know about picking random tracks? If not, it should be implemented outside the class.
The pro of putting it inside CDPlayer is that it will be a single method call, and that the function is pretty typical of CD players so it "feels right".
A con of putting it in your application is that it requires two calls, one to get the number of tracks so you can generate the random number, and one to set it.
A con of putting it in CDPlayer is that the class needs to know about random numbers. In this particular case, it's simple enough to use a standard library, but if this were some top security CIA CD player that could be an issue. (Just noticed youvedited your post to hint at something similar)
I'd put the code in CDPlayer, (and add a method to change the random number generator, the fancy term for this is Dependency Injection) but this post hopefully gives you a few of the pros and cons.
Let's try to implement this feature. What are requirements for playing random track?
it should be random (of course),
it should be not current track (nobody wants to hear current track five times in a row if there other tracks to play)
you should pick track from those which exist in player (track number should not exceed count of tracks).
I will use C#:
Random random = new Random();
CDPlayer player = new CDPlayer();
// creates list of track indexes, e.g. { 1, 2, 3, 4, 5, 6, 7 }
var tracksNotPlayed = Enumerable.Range(0, player.NumberOfTracks - 1).ToList();
if(tracksNotPlayed.Count == 0)
// initialize list again, or stop
int index = random.Next(tracksNotPlayed.Count);
int nextTrack = tracksNotPlayed[index];
player.SetCurrentTrack(nextTrack);
tracksNotPlayed.Remove(nextTrack);
That looks like feature envy to me - some other class uses data from player to implement this functionality. Not good. Let's do some refactoring - move all this stuff into player:
public void PlayRandomTrack() // Shuffle
{
if(tracksNotPlayed.Count == 0)
tracksNotPlayed = Enumerable.Range(0, numberOfTracks - 1).ToList();
int index = random.Next(tracksNotPlayed.Count);
int nextTrack = tracksNotPlayed[index];
SetCurrentTrack(nextTrack);
tracksNotPlayed.Remove(nextTrack);
}
It looks better and it's much easier to use outside:
CDPlayer player = new CDPlayer();
player.PlayRandomTrack();
Also if you are implementing something like Winamp (it has two modes - shuffle playing and sequential playing when it automatically plays songs one by one) then consider to move this logic into some Strategy (or it should be Iterator?), which will have two implementations - sequential and shuffle, and will know nothing about player - it's responsibility will be picking number in some range (number of tracks or collection being enumerated should be passed):
public abstract class CollectionIterator<T>
{
public CollectionIterator(IEnumerable<T> source)
{
// save source
}
abstract int GetNextItemIndex();
}
The player will use this iterators/strategies to play next item:
public void PlayTrack()
{
SetCurrentTrack(iterator.GetNextItemIndex());
}
So, we have clear separation of responsibilities here - client uses player to listen music, player knows how to play music, and iterator knows how to pick next item from collection. You can create ThursdaysCollectionIterator if you want some other sequences on Thursdays. That will keep your player and client code untouched.
I have a fairly simple model with two objects: Team and Game. The Team object has the name of the team, and the Game object looks-up to the Team object twice. One through the "away_team_id" and one through the "home_team_id" field.
Game ----home_team_id----> Team
|
+------away_team_id----> Team
I'm fairly new to ActiveJDBC, but have used PHP ActiveRecord for quite some time. I cannot for the life of me figure out how to reference each team through the Game object. I do have these annotations in my Game object:
#BelongsToParents({
#BelongsTo(foreignKeyName="home_team_id",parent=Team.class),
#BelongsTo(foreignKeyName="away_team_id",parent=Team.class)
})
public class Game extends Model {
}
In my test code, I have:
Team homeTeam = game.parent (Team.class);
But obviously that's only one of them, and I'm not even sure how it figures out which one it is! Any help would be greatly appreciated.
Thanks in advance!
This is an unusual case. I would suggest something like this:
public class Game extends Model{
public Team getHomeTeam(){
return Team.findFirst("id = ?", get("home_team_id"));
}
public Team getAwayTeam(){
return Team.findFirst("id = ?", get("home_away_id"));
}
}
I would suggest wrapping ActiveJDBC in semantic methods like this to help potential refactoring in the future.
tx
This question is probably pretty obvious to any person who knows how to use Bukkit properly, and I'm sorry if I missed a solution in the others, but this is really kicking my ass and I don't know what else to do, the tutorials have been utterly useless. There are really 2 things that I need help doing:
I need to learn how to create an indefinite number of instances of an object. I figure it'd be like this:
int num = 0;
public void create(){
String name = chocolate + num;
Thingy name = new Thingy();
}
So you see what I'm saying? I need to basically change the name that is given to each new instance so that it doesn't overwrite the last one when created. I swear I've looked everywhere, I've asked my Java professor and I can't get any answers.
2: I need to learn how to use the stupid scheduler, and I can't understand anything so far. Basically, when an event is detected, 2 things are called: one method which activates instantly, and one which needs to be given a 5 second delay, then called. The code is like this:
public onEvent(event e){
Thingy thing = new Thingy();
thing.method1();
thing.doOnDelay(method2(), 100 ticks);
}
Once again, I apologize if I am not giving too many specifics, but I cannot FOR THE LIFE OF ME find anything about the Bukkit event scheduler that I can understand.
DO NOT leave me links to the Bukkit official tutorials, I cannot understand them at all and it'll be a waste of an answer. I need somebody who can help me, I am a starting plugin writer.
I've had Programming I and II with focus in Java, so many basic things I know, I just need Bukkit-specific help for the second one.
The first one has had me confused since I started programming.
Ok, so for the first question I think you want to use a data structure. Depending on what you're doing, there are different data structures to use. A data structure is simply a container that you can use to store many instances of a type of object. The data structures that are available to you are:
HashMap
HashSet
TreeMap
List
ArrayList
Vector
There are more, but these are the big ones. HashMap, HashSet, and TreeMap are all part of the Map class, which is notable for it's speedy operations. To use the hashmap, you instantiate it with HashMap<KeyThing, ValueThingy> thing = new HashMap<KeyThing, ValueThing>(); then you add elements to it with thing.put(key, value). Thn when you want to get a value out of it, you just use thing.get(key) HashMaps use an algorithm that's super fast to get the values, but a consequence of this is that the HashMap doesn't store it's entries in any particular order. Therefore when you want to loop though it with a for loop, it randomly returns it's entries (Not truly random because memory and stuff). Also, it's important to note that you can only have one of each individual key. If you try to put in a key that already exists in the map, it will over-right the value for that key.
The HashSet is like a HashMap but without storing values to go with it. It's a pretty good container if all you need to use it for is to determine if an object is inside it.
The TreeMap is one of the only maps that store it's values in a particular order. You have to provide a Comparator (something that tells if an object is less than another object) so that it knows the order to put the values if it wants them to be in ascending order.
List and ArrayList are not maps. Their elements are put in with a index address. With the List, you have to specify the number of elements you're going to be putting into it. Lists do not change size. ArrayLists are like lists in that each element can be retrieved with arrayListThing.get(index) but the ArrayList can change size. You add elements to an ArrayList by arrayListThing.add(Thing).
The Vector is a lot like an ArrayList. It actually functions about the same and I'm not quite sure what the difference between them is.
At any rate, you can use these data structures to store a lot of objects by making a loop. Here's an example with a Vector.
Vector<Thing> thing = new Vector<Thing>();
int numberofthings = 100;
for(int i = 0; i < numberofthings; i++) {
thing.add(new Thing());
}
That will give you a vector full of things which you can then iterate through with
for(Thing elem:thing) {
thing.dostuff
}
Ok, now for the second problem. You are correct that you need to use the Bukkit Scheduler. Here is how:
Make a class that extends BukkitRunnable
public class RunnableThing extends BukkitRunnable {
public void run() {
//what you want to do. You have to make this method.
}
}
Then what you want to do when you want to execute that thing is you make a new BukkitTask object using your RunnableThing
BukkitTask example = new RunnableThing().runTaskLater(plugin, ticks)
You have to do some math to figure out how many ticks you want. 20 ticks = 1 second. Other than that I think that covers all your questions.
This is, I hope, probably quite obvious but I can't find an example that I think answers my issue.
I have an SQL database that I cant modify and within it are two tables, linked with primary/foreign keys (test_scenario and test_exec_queue respectively, so the PK value from test_scenario can show up many times within test_exec_queue) and when I display the data on screen I want it to, instead of displaying the FK value from test_exec_queue I want it to use that to get testScenarioName from the test_scenario table and display that instead.
So far my class looks like this but I've no idea what to put in to do the above logic, or do I do this somewhere else? In the controller? Any help appreciated
class TestExecQueue {
static constraints = {
testscenarioid(blank:false, editable:false)
myPriority(inList:[0,1,2,3,4], blank:false)
myState(inList:["READY"], blank:false)
}
static mapping = {
table "test_exec_queue"
version false
columns{
id column:"test_exec_queue_id"
testscenarioid column:"test_scenario_id"
myPriority column:"Priority"
myState column:"State"
}
}
Integer testscenarioid
Integer myPriority
String myState
}
You need to create a class which maps the test_scenario table in addition to the TestExecQueue class you've already implemented.
In your TestExecQueue class, you would link to the scenario by class, rather than by an integer field:
class TestExecQueue {
static mapping = {
scenario column:'test_scenario_id'
}
TestScenario scenario
}
Note: This is one example of mapping the relationship, you should review the Domain Modeling section of the Grails Documentation for other options.
The display of the classes is entirely dependent on your controllers and views, and that would need more elaboration on your part to answer clearly. One option is to set the public toString() methods on the classes that will be printed.
Some friends and colleagues of mine have a little running contest to find or write the longest class/variable/property/method names possible. Keep in mind, we try to be good boys and girls and keep the naming intelligible and concise, while still explaining what the thing does via its name.
Sometimes it just doesn't happen though. Have you run in to this? I'd just like to see what's out there. (Maybe my friends and I aren't as crazy as we think)
Note: I'm not looking for bad naming. That's already here. I'm looking for good naming that just got a little long.
This isn't a class name but an enum, but it's a lot longer:
VirtualMachineDeviceRuntimeInfoVirtualEthernetCardRuntimeStateVmDirectPathGen2InactiveReasonOther
from the VMware vSphere API. Google for it and you'll find the online documentation.
It isn't really long but my favorite variable name ever was to indicate that a user had opted in to receive email.
User.IsSpammable
I find it's nice to have long test names which describe the test. For instance:
testMapWithOneEntryAllowsDifferentEntryPreservingFirst
testMapWithOneEntryAllowsDuplicateEntryOverwritingFirst
(These are just examples off the top of my head... you get the idea though.)
org.aspectj.weaver.patterns;
public class HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor {
boolean ohYesItHas = false;
public boolean wellHasItThen/*?*/() {
return ohYesItHas;
}
... more methods...
}
Some times ago, I had a problem with Hibernate.
I got a NullPointerException in the method called findIntendedAliasedFromElementBasedOnCrazyJPARequirements !
protected virtual OcrBarcodeSymbologies GetSupportedBarcodeSymbologies() { }
The excellent GTK+ library "suffers" from this. It has very neatly named functions, but since the main API is C, and GTK+ is very object-oriented, it must encode class names in the functions name. The constructor for class X is X_new(), and so on. This leads to beaties such as gtk_recent_chooser_widget_new_for_manager().
I'm sure there are even longer function names in there, this was just one that I found quickly. :)
Long variable names don't bother me as long as there's not an obvious more concise name and the naming is sane. For instance, in Kamaelia, there's a class type named this:
threadedadaptivecommscomponent
A naming convention I've seen, years before fluent became en vogue
public DataSet SelectAllUsersWhereDobIsGreaterThan1980AndIsMaleOrderByNameAndAge()
Check out Apple's documentation. They're kings at that. Very descriptive, but sometimes miles long. A couple of examples from the NSString class:
NSString.completePathInfoString:caseSensitive:matchesToArray:filterType
NSString.stringByAddingPercentEscapesUsingEncoding
My favourite in the Microsoft world: SetProcessWorkingSetSize
bool instrumentAreaDockWidgetVisibilityFollowsChildPresence;
In the apple mail app:
_synchronouslyTellServicesToRegisterAndSync()
In a app I wrote:
User.CanViewRestrictedItems()
I an app a colleague wrote:
Profile.DisplayMyDraftOrPendingProfile()
Profile.DisplayMyApprovedProfile()
Just to get started.
new:
A foreign key constraint name:
constraint ReportCompanyReportTemplateIDVersionID_ReportTemplateVersionReportTemplateIDVersionIDFk foreign key (ReportTemplateID, VersionID) references customer_ReportTemplateVersion (ReportTemplateID, VersionID)
get the js items that will be retrieved and if page should display recommendations.