Events

A resource reacts to the game through events: players joining, chatting and fighting, NPCs dying, doors opening, as well as events from your own and other resources.

const { Events, Chat } = kcds.core;

Events.on('playerConnect', (player) => {
  console.info(`${player.nickname} is connecting`);
});

Events.on('playerReady', (player) => {
  Chat.sendToPlayer(player, 'Welcome!');
});

Events.on('playerDisconnect', (player) => {
  console.info(`${player.nickname} left`);
});

Events.on, Events.once and Events.off work the same for the game's events and your own. To raise your own events:

CallWho hears it
Events.emit(name, ...args)All resources on this side. Returns a promise.
Events.toResource(res, name, ...args)One resource, by name.
Events.fire(name, ...args)This resource only, through Events.listen.
Events.toServer(name, payload)The server's Events.fromClient, sent from a client.
Events.broadcast(name, payload)All players' client scripts, sent from the server.
player.emit(name, payload)One player's client scripts, sent from the server.

Client resources has more on talking between the server and clients.

A player's arrival

These fire in this order, and playerDisconnect fires when they leave.

EventWhen
playerConnectingSomeone asks to join. request.reject(reason) turns them away.
playerConnectThey joined. Their body and inventory exist, and they are still loading.
playerSpawningTheir game waits for a place to appear. Choose it with player.spawn(position, rotation).
playerSpawnedThey stand in the loaded world.
playerReadyTheir game took down its loading screen, so they can see and play.

Refusing an action

Some events ask before something happens. A handler that returns false, not a promise of it, refuses the action, and it is undone for everyone. All handlers still run, in the order added.

These events ask: cartEntering, craftingCompleting, craftingStarting, doorInteract, gatheringHarvest, horseGearChanging, horseMounting, npcHarvest, npcLoot, playerCarrying, playerCarryingItem, playerConsuming, playerConsumptionEffects, playerHit, playerLoot, playerPerkLearning, playerPickpocketStart, playerPoisonAbsorbing, playerPreparing, playerTreeChop, playerTreeFell, playerTrunkChop, playerTrunkCut, playerXpGaining, propPlaceConfirm, siegeEngineUse, siegeLadderUse, stashInteract, tradeItem, tradeOpen, treeRegrow and worldItemPickup.

const { Events } = kcds.core;
const { Area } = kcds.world;

// No picking locks in town.
Events.on('doorInteract', (player, door, action) => {
  if (action !== 'lockpick') {
    return;
  }
  const inTown = Area.aroundEntity(player).some((area) => area.labels.includes('town'));
  if (inTown) {
    return false;
  }
});

Chat and commands

playerChat(player, text) is an ordinary message. playerCommand(player, command, args) is a message starting with /, and goes to no other player. By default, a chat message reaches everyone before playerChat fires. To handle chat yourself, call Chat.setChatRelay(false).

All events

Each event with its arguments. The Events reference has its full description and an example. Server scripts hear these unless marked (client), or (both) for both sides.

Players: joining and leaving

EventArgumentsWhen
playerConnectingrequestSomeone asks to join, before their connection exists.
playerConnectplayerA player joined and is still loading.
playerSpawningplayerTheir game waits for a place to appear.
playerSpawnedplayerThey stand in the loaded world.
playerReady (both)playerTheir loading screen is down.
playerResourcesReadyplayerTheir game started the client resources.
playerDisconnectplayerA player left.
playerQueuedviewA player joined a full server's queue.
playerUnqueuedview, valueA player left the queue.
loadingProgress (client)stage, percentHow far the game has loaded (Web views).

Players: chat and commands

EventArgumentsWhen
consoleCommandcommand, partsA server console command the server does not handle.
playerChatplayer, textA player sent a chat message.
playerCommandplayer, command, partsA player typed a message starting with /.

Players: fighting, damage and knock-outs

EventArgumentsWhen
playerAttackplayer, opponentThe server accepted a melee swing at another player.
playerCombatCancelledplayer, opponentplayer.stopFight ended melee combat.
playerDamageplayer, attacker, amount, bodyPart, reasonA player's game took health off them.
playerDiedplayer, killer, reasonA player was knocked out.
playerHitplayer, attacker, hitAnother player's blow or shot is about to take health.
playerInjuredplayer, limbA limb was injured.
playerInjuryHealedplayer, limbA limb's injury healed.
playerWeaponHitplayer, hitA swing struck the world and not a character.
playerWhistleplayerA player whistled for their horse.

Players: carrying, cuffs and the pillory

EventArgumentsWhen
playerCarrycarrier, carriedA player lifted a knocked-out player.
playerCarryingcarrier, carriedA player is about to lift a knocked-out player.
playerCarryingItemplayer, item, stackA player is about to pick up a carryable ground item.
playerCarryItemplayer, item, stackA player now carries an item in their arms.
playerCuffedChangeplayer, cuffedplayer.setCuffed cuffed or uncuffed a player.
playerPilloryReleasedplayer, reasonA player left the pillory.
playerPutDowncarrier, carriedA carried player was put down.
playerPutDownItemplayer, item, stackA player stopped carrying an item and set it down.

Players: inventory, food and items

EventArgumentsWhen
playerConsumedplayer, consumedA player ate or drank something.
playerConsumingplayer, consumptionA player is about to eat or drink.
playerConsumptionEffectsplayer, consumptionFollows playerConsuming, and can stop the game's effects.
playerCustomItemUseplayer, item, revisionA player used a custom usable item.
playerInventoryChangedplayer, changeRows in their inventory changed.
playerInventoryReadyplayerTheir game shows the inventory the server holds.
playerItemUsedplayer, item, kind, amountA player used up units of an item.
playerLootplayer, victim, lineA player is about to take from a knocked-out body.
playerLootedplayer, victim, itemsA player took items from a knocked-out body.
playerPoisonAbsorbingplayer, consumption, poisonA player is about to get a poison they consumed.
playerPreparingplayer, preparingA player is about to cook, smoke or dry food.
playerPreparedplayer, preparationA preparation is over, with items the game converted.

Players: progression and buffs

EventArgumentsWhen
playerBuffAddedplayer, buff, sourceA status effect landed on a player.
playerBuffBlockedplayer, buffThe server's rules kept a status effect off.
playerBuffRemovedplayer, buff, reasonA status effect left a player.
playerCustomBuffApplyplayer, buffAn instance of a registered buff landed.
playerCustomBuffRemoveplayer, buff, reasonAn instance of a registered buff left.
playerCustomBuffTickplayer, buffA registered buff's tick.
playerLevelUpplayer, track, level, perkPointsA player reached a new level on a track.
playerPerkAddedplayer, perk, sourceA player got a perk.
playerPerkLearningplayer, perkA player chooses a perk.
playerPerkRemovedplayer, perk, sourceA player lost a perk.
playerProgressionRejectedplayer, reasonTheir game reported XP or perks the server did not grant.
playerStatsChangedplayer, changesStats in their report changed.
playerXpGainedplayer, track, xpA player gained XP on a track.
playerXpGainingplayer, track, xp, sourceTheir game is about to grant XP.

Players: pickpocketing and animations

EventArgumentsWhen
playerAnimationEndplayer, fragment, reasonAn animation from player.playAnimation ended.
playerPickpocketCaughtthief, victimA victim caught their pickpocket.
playerPickpocketedthief, victim, itemsA pickpocketing ended, with the items taken.
playerPickpocketStartthief, victimA player tries to pickpocket another.
propPickedUpplayer, propAn animation took a prop into the hand.
propPlacedplayer, propAn animation put a prop down.

NPCs and patrols

EventArgumentsWhen
npcAnimationEndnpc, fragment, reasonAn animation from npc.playAnimation ended.
npcDamagenpc, attacker, amount, bodyPart, reasonAn NPC lost health.
npcDeathnpc, killerAn NPC died.
npcDestroynpcAn NPC is being removed.
npcHarvestplayer, npcA player is about to get a carcass's harvest.
npcHarvestednpc, playerA player got a carcass's harvest.
npcIntentDonenpc, statusAn NPC finished a moveTo, a follow or a patrol leg.
npcInteractnpc, playerA player pressed use on an interactable NPC.
npcInventoryChangednpc, changeA spawned NPC's stock changed.
npcLootplayer, npc, lineA player is about to take from a dead NPC.
npcLootedplayer, npc, itemsA player took items from a dead NPC.
npcRevivenpcA dead NPC was revived.
npcSimulatorChangenpc, simulator, previousAnother player's game now simulates the NPC.
npcSpawnnpcAn NPC was spawned.
patrolFinishednpc, patrolA patrol ended: done, cancelled or given up.
patrolWaypointnpc, patrolAn NPC reached a waypoint, or a leg failed.

Horses and dogs

EventArgumentsWhen
dogDestroydogA dog is being removed.
dogModeChangeddog, modeA dog's mode changed.
dogOwnerChangeddog, ownerA dog got a new owner, or none.
dogSpawndogA dog was spawned.
horseDamagehorse, attacker, amount, reasonA horse lost health.
horseDeathhorse, killer, reasonA horse died.
horseDestroyhorseA horse is being removed.
horseDismounthorse, playerA rider left the saddle.
horseGearChangedhorse, player, gearA horse's tack changed on all clients.
horseGearChanginghorse, player, gearAn owner changed the tack, before the server takes it.
horseIntentDonehorse, statusA horse finished a moveTo or patrol order.
horseKnockedOuthorse, attacker, reasonA horse was knocked out.
horseMounthorse, playerA player sat in the saddle.
horseMountinghorse, playerA player mounts, before the server accepts it.
horseOwnerChangedhorse, ownerA horse got a new owner, or none.
horseRevivehorseA dead horse was revived.
horseSpawnhorseA horse was spawned.
horseWakehorseA knocked-out horse got up.

Doors, gates and containers

EventArgumentsWhen
doorInteractplayer, door, action, keySideA player is about to open, close, unlock or lockpick a door.
gateBarChangedgate, barredA gate's bar was put in or taken out.
gateChangedgate, stateA gate moved to another state.
graveDugplayer, graveA player dug out a grave.
stashClosestash, player, reasonA player closed a stash.
stashDestroystashA stash is being removed.
stashInteractplayer, stash, actionA player is about to open a stash.
stashInventoryChangedstash, player, changeA script changed a stash's contents.
stashOpenstash, playerA player opened a stash.
stashSpawnstashA chest, container or searchable body was created.
stashUnlockedstash, player, methodA player unlocked a locked stash.

Carts

EventArgumentsWhen
cartDestroycartA cart is being removed, with everyone let off first.
cartEntercart, player, seatA player took a seat.
cartEnteringcart, player, seatA player is about to take a seat.
cartExitcart, player, seatA player got off.
cartSpawncartA cart or wagon was spawned.

Props, effects and the ground

EventArgumentsWhen
groundItemDestroystackA ground item is being removed.
groundItemPickupstack, playerA player picked up a ground item.
groundItemRestingstackA ground item came to rest.
groundItemSpawnstackA stack of items appeared on the ground.
propDestroypropA prop is being removed.
propHitprop, speed, positionA rigid prop struck something, at speed m/s.
propPlaceCancelplayer, sessionA player cancelled a placement.
propPlaceConfirmplayer, session, placementA player confirmed a placement.
propPlaceEndplayer, sessionA placement session ended.
propPlaceMoveplayer, session, placement, validA player moved a PropPlacer preview.
propPlaceRejectedplayer, session, placementA placement was refused.
propRestprop, position, rotationA rigid prop came to rest.
propSpawnpropA prop was spawned.
vfxDestroyvfxA visual effect is being removed.
vfxSpawnvfxA visual effect was spawned.
worldItemPickupplayer, itemA player is about to pick up an item the level placed.

Markers and areas

EventArgumentsWhen
areaEnterarea, entity, matchingDimensionA player, horse or NPC entered an area.
areaExitarea, entity, matchingDimensionA player, horse or NPC left an area.
markerEntermarker, playerA player walked into a trigger marker.
markerExitmarker, playerA player left a trigger marker.
markerPlacemarkerA marker was placed.
markerRemovemarkerA marker is being removed.

Crafting and gathering

EventArgumentsWhen
craftingCompletedplayer, detailsA craft gave its product.
craftingCompletingplayer, proposalA craft is about to give its product.
craftingEndedplayer, detailsA session ended: 'success', 'failed' or 'cancelled'.
craftingRecipeLearnedplayer, detailsA player learned a custom recipe.
craftingRefundingplayer, details, refundAn unfinished craft is settling.
craftingStartedplayer, detailsA player started crafting.
craftingStartingplayer, proposalA player is about to start crafting.
craftingStationUsedplayer, detailsA player used a station with more than one recipe.
gatheringHarvestplayer, proposalA player picked a plant and is about to get it.
gatheringHarvestedplayer, detailsA player got what they picked.

Trees

EventArgumentsWhen
playerTreeChopplayer, tree, blowAn axe blow on a standing tree counts.
playerTreeFellplayer, tree, fallA last blow fells a tree.
playerTrunkChopplayer, tree, blowAn axe blow on a felled trunk counts.
playerTrunkCutplayer, tree, itemsA last blow cuts a trunk into items.
treeChop (client)tree, blowAny player's counted blow on a standing tree here.
treeFalling (client)tree, fallA tree here starts to fall.
treeFelled (both)treeA felled trunk came to rest.
treeRegrowtreeA tree is about to grow back.
treeRegrown (both)treeA felled tree stands again.
trunkCut (client)tree, itemsA felled trunk here was cut into items.

Dice

EventArgumentsWhen
diceBadgeeventA badge took effect on a throw.
diceMatchEndmatch, first, second, winner, reason, firstScore, secondScoreA dice match ended.
diceMatchStartmatch, first, second, targetA dice match began.
diceMoveeventA player held dice and continued or passed.
diceRolleventDice were thrown.
diceTableUseplayer, table, matchA player used a dice table.
diceTurnEndeventA turn ended.
diceTurnStarteventA player's turn began.

Trade, shops and conversations

EventArgumentsWhen
dialogueChoicesession, player, optionA player chose an option from Dialogue.open.
dialogueClosedsession, player, reasonA conversation ended.
tradeClosedseller, player, reasonA trade ended.
tradeDoneseller, buyer, boughtLines, soldLines, balanceA basket went through.
tradeItemseller, buyer, boughtLines, soldLines, balanceThe buyer confirmed a basket.
tradeOpenseller, buyerA trade is about to open.
vendorClosed (both)vendor, player, reasonA shop screen closed.
vendorOpened (client)session, npcA server vendor's shop screen opened.
vendorTradevendorId, player, bought, sold, balanceA player traded with a vendor.

Quests

EventArgumentsWhen
questTrackingChanged (both)quest, player, trackedA player started or stopped tracking a quest.

Siege

EventArgumentsWhen
siegeEngineDamageengine, amount, attackerA siege engine took damage.
siegeEngineDestroyengineA siege engine is being removed.
siegeEngineReadyengineA siege engine finished loading.
siegeEngineSpawnengineA siege engine was spawned.
siegeEngineUseplayer, engine, actionA player is about to operate an engine.
siegeEngineWreckengine, attackerA siege engine was wrecked.
siegeFireengine, attacker, targetA siege engine fired.
siegeImpactengine, position, attackerA siege engine's shot landed.
siegeLadderDestroyladderA siege ladder is being removed.
siegeLadderFallladder, pusherA ladder was pushed away and fell.
siegeLadderRaiseladderA ladder was raised against a wall.
siegeLadderSpawnladderA siege ladder was spawned.
siegeLadderUseplayer, ladder, actionA player is about to push away or raise a ladder.
stoneImpactpile, position, playerA thrown stone landed, hurting anyone near.
stonePileDestroypileA stone pile is being removed.
stonePileSpawnpileA stone pile was spawned.
stonePileThrowplayer, pileA player threw a stone from a pile.

World

EventArgumentsWhen
worldDayChangedayThe world's clock reached a new day.
worldResourcesReadyAll world resources have loaded.
worldWeatherChangepreset, previous, secondsWorld.setWeather started changing the weather.

Resources and state

EventArgumentsWhen
entityStateChangeentity, key, value, previousA value in an entity's shared state changed.
resourceStart (both)nameA resource's scripts have run.
resourceStop (both)nameA resource is stopping.

The camera

EventArgumentsWhen
cameraShotEnded (both)player, reasonA Camera.startShot ended by itself.

The player's own game (client)

EventArgumentsWhen
actionHintsChanged (client)The HUD's hints changed.
bookClosed (client)id, reasonA book closed.
bookOpened (client)idA Book opened.
bookTextChanged (client)id, text, reasonThe text in an open book changed.
bookWritingEnded (client)id, textThe player stopped writing in a book.
characterCreatorClosed (client)appearance, reasonThe character creator closed.
chatMessage (client)messageA chat message arrived.
followStarted (client)targetThe local player's scripted follow started.
followStopped (client)target, reasonThe local player's follow ended.
gameResolutionChanged (client)width, heightThe game's frame changed size.
locationDiscovered (client)locationIdThe player discovered a map location.
mapClosed (client)The local player closed the map.
mapOpened (client)The local player opened the map.
mapWaypointCleared (client)position, mapIdThe local player removed their waypoint.
mapWaypointSet (client)position, mapId, movedThe local player set or moved their waypoint.
monologueSuppressed (client)text, textKeyKCDS silenced one of the character's remarks.
noclipAllowedChanged (client)allowedThe server allowed or forbade NoClip.
noclipChanged (client)enabled, reasonNoClip went on or off.
poiDiscovered (client)poiIdThe player discovered a point of interest.
progressionLevelUp (client)track, level, perkPointsThe local player reached a new level.
progressionPerkAdded (client)perkThe local player got a perk.
progressionPerkRefused (client)perk, reasonThe server refused a perk they chose.
progressionPerkRemoved (client)perkThe local player lost a perk.
progressionXpGained (client)track, xpThe local player gained XP.
storyCutsceneSuppressed (client)cutsceneKCDS stopped a quest's story cutscene.
tutorialHintClosed (client)id, reasonA tutorial hint closed.
weaponHit (client)hitThe local player's weapon struck the world.