下面列出了怎么用org.bukkit.entity.Villager的API类实例代码及写法,或者点击链接到github查看源代码。
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onInteract(PlayerInteractEntityEvent event) {
if (event.getRightClicked() instanceof Villager) {
// Fallback to once-at-a-time trading if multi trade does not work
if (ok) {
event.setCancelled(true);
} else {
return;
}
try {
InventoryUtils.openVillager((Villager) event.getRightClicked(), event.getPlayer());
} catch (NoSuchMethodError e) {
logger.log(Level.WARNING, "<multitrade/> is not compatible with your server version");
ok = false;
} catch (Throwable t) {
logger.log(
Level.WARNING,
String.format(
"Villager at (%s) has invalid NBT data",
event.getRightClicked().getLocation().toVector()),
t);
ok = false;
}
}
}
@Test
@Ignore // TODO fix this
public void villagerShouldNotSpawnIfAtMaxVillagers() {
RegionsTests.loadRegionTypeCobble();
Region region = RegionsTests.createNewRegion("cobble");
HashMap<String, String> effectMap = new HashMap<>();
effectMap.put("villager","");
region.setEffects(effectMap);
VillagerEffect villagerEffect = new VillagerEffect();
// Block block = TestUtil.createBlock(Material.CHEST, townLocation);
// doReturn(TestUtil.createBlock(Material.AIR, townLocation.add(0, 1,0))).when(block).getRelative(any(), anyInt());
// when(block.getWorld()).thenReturn(mock(World.class));
CommonScheduler.getLastTown().put(TestUtil.player.getUniqueId(), this.town);
villagerEffect.regionCreatedHandler(region);
Villager villager = VillagerEffect.spawnVillager(region);
assertNotNull(villager);
VillagerEffect.townCooldowns.clear();
villager = VillagerEffect.spawnVillager(region);
assertNull(villager);
}
@EventHandler
public void findSuperMob(ChunkLoadEvent event) {
for (Entity entity : event.getChunk().getEntities()) {
if (SuperMobProperties.isValidSuperMobType(entity))
if (((LivingEntity) entity).getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue() ==
SuperMobProperties.getDataInstance(entity).getSuperMobMaxHealth())
if (!EntityTracker.isSuperMob(entity))
EntityTracker.registerSuperMob((LivingEntity) entity);
else if (entity instanceof Villager) {
}
}
}
public CreatureType getCreatureType(EntityType entityType) {
if (Monster.class.isAssignableFrom(entityType.getEntityClass())
|| WaterMob.class.isAssignableFrom(entityType.getEntityClass())
|| Slime.class.isAssignableFrom(entityType.getEntityClass())
|| Ghast.class.isAssignableFrom(entityType.getEntityClass())
) {
return CreatureType.MONSTER;
} else if (Animals.class.isAssignableFrom(entityType.getEntityClass())) {
return CreatureType.ANIMAL;
} else if (Villager.class.isAssignableFrom(entityType.getEntityClass())) {
return CreatureType.VILLAGER;
} else if (Golem.class.isAssignableFrom(entityType.getEntityClass())) {
return CreatureType.GOLEM;
}
return CreatureType.UNKNOWN;
}
@Override
public BehaviourItem[] getDefaultMovementBehaviours() {
return new BehaviourItem[]{
new BehaviourItem(0, new BehaviourFloat(this)),
new BehaviourItem(1, new BehaviourAvoidEntity(this, Zombie.class, 8.0F, 0.6D, 0.6D)),
new BehaviourItem(1, new BehaviourTradeWithPlayer(this)),
new BehaviourItem(1, new BehaviourLookAtTradingPlayer(this)),
new BehaviourItem(2, new BehaviourMoveIndoors(this)),
new BehaviourItem(3, new BehaviourRestrictOpenDoor(this)),
new BehaviourItem(4, new BehaviourOpenDoor(this, true)),
new BehaviourItem(5, new BehaviourMoveTowardsRestriction(this, 0.6D)),
new BehaviourItem(6, new BehaviourMakeLove(this)),
new BehaviourItem(7, new BehaviourTakeFlower(this)),
new BehaviourItem(8, new BehaviourVillagerPlay(this, 0.32D)),
new BehaviourItem(9, new BehaviourInteract(this, HumanEntity.class, 3.0F, 1.0F)),
new BehaviourItem(9, new BehaviourInteract(this, Villager.class, 3.0F, 1.0F)),
new BehaviourItem(9, new BehaviourRandomStroll(this, 0.6D)),
new BehaviourItem(10, new BehaviourLookAtNearestEntity(this, InsentientEntity.class, 8.0F))
};
}
@ListenerScope(MatchScope.LOADED)
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void processItemRemoval(PlayerInteractEntityEvent event) {
if(event.getRightClicked() instanceof Villager) {
event.setCancelled(true);
event.getPlayer().openMerchantCopy((Villager) event.getRightClicked());
}
}
@Override
public boolean checkTrait(Entity original, Entity nearby) {
if(original instanceof Villager){
if (((Villager) original).getProfession() != ((Villager) nearby).getProfession()) {
return true;
}
return (((Villager) original).getCareer() != ((Villager) nearby).getCareer());
}
return false;
}
@Override
public void applyTrait(Entity original, Entity spawned) {
if(original instanceof Villager){
((Villager) original).setProfession(((Villager) original).getProfession());
((Villager) original).setCareer(((Villager) original).getCareer());
}
}
@Override
public boolean checkTrait(Entity original, Entity nearby) {
if(original instanceof Villager){
return ((Villager) original).getProfession() != ((Villager) nearby).getProfession();
}
return false;
}
@EventHandler
public void onVillagerDeath(EntityDeathEvent event) {
if (!(event.getEntity() instanceof Villager)) {
return;
}
Location location = event.getEntity().getLocation();
Town town = TownManager.getInstance().getTownAt(location);
if (town == null) {
return;
}
TownManager.getInstance().setTownPower(town,
town.getPower() - ConfigManager.getInstance().getPowerPerNPCKill());
}
@Test
public void villagerEffectShouldDecrementPower() {
VillagerEffect villagerEffect = new VillagerEffect();
Villager villager = mock(Villager.class);
when(villager.getLocation()).thenReturn(this.townLocation);
EntityDeathEvent entityDeathEvent = mock(EntityDeathEvent.class);
when(entityDeathEvent.getEntity()).thenReturn(villager);
villagerEffect.onVillagerDeath(entityDeathEvent);
assertEquals(296, this.town.getPower());
}
@Test
@Ignore // TODO fix this
public void villagerShouldSpawnNewVillager() {
CommonScheduler.getLastTown().put(TestUtil.player.getUniqueId(), this.town);
RegionsTests.loadRegionTypeCobble();
Region region = RegionsTests.createNewRegion("cobble");
HashMap<String, String> effectMap = new HashMap<>();
effectMap.put("villager","");
region.setEffects(effectMap);
VillagerEffect villagerEffect = new VillagerEffect();
villagerEffect.regionCreatedHandler(region);
Villager villager = VillagerEffect.spawnVillager(region);
assertNotNull(villager);
}
@Test
public void villagerShouldNotSpawnIfOnCooldown() {
RegionsTests.loadRegionTypeCobble();
Region region = RegionsTests.createNewRegion("cobble");
VillagerEffect.spawnVillager(region);
Villager villager = VillagerEffect.spawnVillager(region);
assertNull(villager);
}
@Override
public void set(final Villager entity) {
Profession prof = profession == null ? CollectionUtils.getRandom(professions) : profession;
assert prof != null;
entity.setProfession(prof);
if (HAS_NITWIT && profession == Profession.NITWIT)
entity.setRecipes(Collections.emptyList());
}
/**
* Spawns NPC based off of the values in the NPCConfig config file. Runs at startup and on reload.
*
* @param key Name of the config key for this NPC
*/
public NPCEntity(String key) {
this.key = key;
key += ".";
Configuration configuration = ConfigValues.npcConfig;
if (!setSpawnLocation(configuration.getString(key + NPCConfig.LOCATION))) return;
if (!configuration.getBoolean(key + NPCConfig.ENABLED)) return;
this.villager = (Villager) spawnLocation.getWorld().spawnEntity(spawnLocation, EntityType.VILLAGER);
this.villager.setRemoveWhenFarAway(true);
setName(configuration.getString(key + NPCConfig.NAME));
initializeRole(configuration.getString(key + NPCConfig.ROLE));
setProfession(configuration.getString(key + NPCConfig.TYPE));
setGreetings(configuration.getStringList(key + NPCConfig.GREETINGS));
setDialog(configuration.getStringList(key + NPCConfig.DIALOG));
setFarewell(configuration.getStringList(key + NPCConfig.FAREWELL));
setCanMove(configuration.getBoolean(key + NPCConfig.CAN_MOVE));
setCanTalk(configuration.getBoolean(key + NPCConfig.CAN_TALK));
setActivationRadius(configuration.getDouble(key + NPCConfig.ACTIVATION_RADIUS));
setDisappearsAtNight(configuration.getBoolean(key + NPCConfig.DISAPPEARS_AT_NIGHT));
setNpcInteractionType(configuration.getString(key + NPCConfig.INTERACTION_TYPE));
EntityTracker.registerNPCEntity(this);
addNPCEntity(this);
}
public CreatureType getCreatureType(LivingEntity creature) {
if (creature instanceof Monster
|| creature instanceof WaterMob
|| creature instanceof Slime
|| creature instanceof Ghast) {
return CreatureType.MONSTER;
} else if (creature instanceof Animals) {
return CreatureType.ANIMAL;
} else if (creature instanceof Villager) {
return CreatureType.VILLAGER;
} else if (creature instanceof Golem) {
return CreatureType.GOLEM;
}
return CreatureType.UNKNOWN;
}
/**
* @return Provides count of villagers within the protected island boundaries
*/
public int getPopulation() {
int result = 0;
for (int x = getMinProtectedX() /16; x <= (getMinProtectedX() + getProtectionSize() - 1)/16; x++) {
for (int z = getMinProtectedZ() /16; z <= (getMinProtectedZ() + getProtectionSize() - 1)/16; z++) {
for (Entity entity : world.getChunkAt(x, z).getEntities()) {
if (entity instanceof Villager && onIsland(entity.getLocation())) {
result++;
}
}
}
}
return result;
}
@EventHandler
public void handleRightClick(PlayerInteractEntityEvent event) {
if ((event.getRightClicked() instanceof Villager)) {
event.setCancelled(true);
event.getPlayer().openMerchantCopy((Villager)event.getRightClicked());
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
void onEntityInteract(PlayerInteractEntityEvent event) {
if (!(event.getRightClicked() instanceof Villager)) return;
Villager villager = (Villager) event.getRightClicked();
if (plugin.isShopkeeper(villager)) return; // shopkeeper interaction is handled elsewhere
Log.debug("Interaction with Non-shopkeeper villager ..");
if (villager.hasMetadata("NPC")) {
// ignore any interaction with citizens2 NPCs
Log.debug(" ignoring (probably citizens2) NPC");
return;
}
if (Settings.disableOtherVillagers) {
// don't allow trading with other villagers
event.setCancelled(true);
Log.debug(" trade prevented");
}
// only trigger hiring for main-hand events:
if (!NMSManager.getProvider().isMainHandInteraction(event)) return;
if (Settings.hireOtherVillagers) {
Player player = event.getPlayer();
// allow hiring of other villagers
Log.debug(" possible hire ..");
if (this.handleHireOtherVillager(player, villager)) {
// hiring was successful -> prevent normal trading
Log.debug(" ..success (normal trading prevented)");
event.setCancelled(true);
} else {
// hiring was not successful -> no preventing of normal villager trading
Log.debug(" ..failed");
}
}
}
@Override
public BehaviourItem[] getDefaultMovementBehaviours() {
return new BehaviourItem[]{
new BehaviourItem(0, new BehaviourFloat(this)),
new BehaviourItem(1, new BehaviourBreakDoor(this, false)),
new BehaviourItem(2, new BehaviourMeleeAttack(this, HumanEntity.class, false, 1.0D)),
new BehaviourItem(4, new BehaviourMeleeAttack(this, Villager.class, true, 1.0D)),
new BehaviourItem(5, new BehaviourMoveTowardsRestriction(this, 1.0D)),
new BehaviourItem(6, new BehaviourMoveThroughVillage(this, false, 1.0D)),
new BehaviourItem(7, new BehaviourRandomStroll(this, 1.0D)),
new BehaviourItem(8, new BehaviourLookAtNearestEntity(this, HumanEntity.class, 8.0F)),
new BehaviourItem(8, new BehaviourLookAtRandom(this))
};
}
@Override
public BehaviourItem[] getDefaultTargetingBehaviours() {
return new BehaviourItem[]{
new BehaviourItem(1, new BehaviourHurtByTarget(this, true)),
new BehaviourItem(2, new BehaviourMoveTowardsNearestAttackableTarget(this, HumanEntity.class, 0, true)),
new BehaviourItem(2, new BehaviourMoveTowardsNearestAttackableTarget(this, Villager.class, 0, false))
};
}
@Override
public BehaviourItem[] getDefaultMovementBehaviours() {
return new BehaviourItem[]{
new BehaviourItem(0, new BehaviourFloat(this)),
new BehaviourItem(2, new BehaviourMeleeAttack(this, HumanEntity.class, false, 1.0D)),
new BehaviourItem(4, new BehaviourMeleeAttack(this, Villager.class, true, 1.0D)),
new BehaviourItem(5, new BehaviourMoveTowardsRestriction(this, 1.0D)),
new BehaviourItem(6, new BehaviourMoveThroughVillage(this, false, 1.0D)),
new BehaviourItem(7, new BehaviourRandomStroll(this, 1.0D)),
new BehaviourItem(8, new BehaviourLookAtNearestEntity(this, HumanEntity.class, 8.0F)),
new BehaviourItem(8, new BehaviourLookAtRandom(this))
};
}
@Override
public BehaviourItem[] getDefaultTargetingBehaviours() {
return new BehaviourItem[]{
new BehaviourItem(1, new BehaviourHurtByTarget(this, true)),
new BehaviourItem(2, new BehaviourMoveTowardsNearestAttackableTarget(this, HumanEntity.class, 0, true)),
new BehaviourItem(2, new BehaviourMoveTowardsNearestAttackableTarget(this, Villager.class, 0, false))
};
}
@CommandCompletion("@gdentityids @gddummy")
@CommandAlias("claimclear")
@Description("Allows clearing of entities within one or more claims.")
@Syntax("<entity_id> [claim_uuid]")
@Subcommand("claim clear")
public void execute(Player player, String target, @Optional String claimId) {
World world = player.getWorld();
if (!GriefDefenderPlugin.getInstance().claimsEnabledForWorld(world.getUID())) {
GriefDefenderPlugin.sendMessage(player, MessageCache.getInstance().CLAIM_DISABLED_WORLD);
return;
}
UUID claimUniqueId = null;
GDClaim targetClaim = null;
if (claimId == null) {
targetClaim = GriefDefenderPlugin.getInstance().dataStore.getClaimAt(player.getLocation());
final Component result = targetClaim.allowEdit(player);
if (result != null) {
GriefDefenderPlugin.sendMessage(player, result);
return;
}
claimUniqueId = targetClaim.getUniqueId();
} else {
if (!player.hasPermission(GDPermissions.COMMAND_DELETE_CLAIMS)) {
GriefDefenderPlugin.sendMessage(player, MessageCache.getInstance().COMMAND_CLAIMCLEAR_UUID_DENY);
return;
}
try {
claimUniqueId = UUID.fromString(claimId);
} catch (IllegalArgumentException e) {
return;
}
}
if (targetClaim.isWilderness()) {
GriefDefenderPlugin.sendMessage(player, GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.CLAIM_ACTION_NOT_AVAILABLE,
ImmutableMap.of("type", TextComponent.of("the wilderness"))));
return;
}
int count = 0;
String[] parts = target.split(":");
if (parts.length > 1) {
target = parts[1];
}
for (Chunk chunk : targetClaim.getChunks()) {
for (Entity entity : chunk.getEntities()) {
if (entity instanceof Player) {
continue;
}
if (entity instanceof Villager || !(entity instanceof LivingEntity)) {
continue;
}
if (entity instanceof Tameable) {
final UUID ownerUniqueId = NMSUtil.getInstance().getTameableOwnerUUID(entity);
if (ownerUniqueId != null && !ownerUniqueId.equals(player.getUniqueId())) {
continue;
}
}
LivingEntity livingEntity = (LivingEntity) entity;
String entityName = entity.getType().getName().toLowerCase();
if (target.equalsIgnoreCase("any") || target.equalsIgnoreCase("all") || target.equalsIgnoreCase("minecraft") || target.equalsIgnoreCase(entityName)) {
livingEntity.setHealth(0);
count++;
}
}
}
if (count == 0) {
GriefDefenderPlugin.sendMessage(player, GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.COMMAND_CLAIMCLEAR_NO_ENTITIES,
ImmutableMap.of("type", TextComponent.of(target, TextColor.GREEN))));
} else {
GriefDefenderPlugin.sendMessage(player, GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.COMMAND_CLAIMCLEAR_NO_ENTITIES,
ImmutableMap.of(
"amount", count,
"type", TextComponent.of(target, TextColor.GREEN))));
}
}
public static void openVillager(Villager villager, Player viewer) throws Throwable {
// An exception can be thrown if the Villager's NBT is invalid
// or if the server does not support for this patch.
// TODO: Newer versions of Bukkit can use HumanEntity#openMerchant(Merchant, boolean)
viewer.openMerchantCopy(villager);
}
public VillagerAcquireTradeEvent(Villager what, MerchantRecipe recipe) {
super(what);
this.recipe = recipe;
}
@Override
public Villager getEntity() {
return (Villager) super.getEntity();
}
public VillagerReplenishTradeEvent(Villager what, MerchantRecipe recipe, int bonus) {
super(what);
this.recipe = recipe;
this.bonus = bonus;
}
@Override
public Villager getEntity() {
return (Villager) super.getEntity();
}
@Override
public Villager.Profession getVillagerProfession() {
return Villager.Profession.values()[getHandle().getProfession() + Villager.Profession.FARMER.ordinal()];
}