Готовые механики
Копируй в свою игру: каждый блок кода компилируется как есть. Раунд и босс встроены целиком из docs/recipes*.jc (компилируются без предупреждений).
Вывод по правилам Текста и интерфейса: уведомления — action bar со звуком, большие моменты — title, топы — табло, не чат.
Координаты — заглушки
location(0.5, 64, 0.5, ...) и y < 50 — из старого тестового мира. Высоту пола не угадывай, а измерь (jmvcc client world-profile или рецепт в теме look-and-feel, llms.txt и темы). Не телепортируй игрока туда, где под ним пусто.
Монеты игрока
Что делает: у каждого игрока свой сохранённый счётчик монет, у новичка 0.
save var %player%_coins
event<player_join> {
%player%_coins ??= 0
player::action_bar("&6Монет: &e${%player%_coins}")
}%player%в имени — своя переменная у каждого игрока (Steve_coins).save var— живёт между перезапусками мира.??=— присвоить, только если переменной ещё нет.save var x = 0наверху нельзя: сбросится при каждом старте мира. Подробнее — Переменные.
Перезарядка (кулдаун)
Что делает: способность на ПКМ не чаще раза в 3 секунды; пока перезаряжается, видно, сколько осталось.
save var %player%_last_use
inline var CD = 3000 // мс
event<player_right_click> {
if (value::event_equipment_slot != "hand") { return }
line var now = value::timestamp
if (now < %player%_last_use + CD) {
player::action_bar("&cПерезарядка: &f${ceil((%player%_last_use + CD - now) / 1000)} с")
player::play_sound(sound("entity.villager.no"))
return
}
%player%_last_use = now
player::action_bar("&aСработало!")
player::play_sound(sound("entity.experience_orb.pickup", 0.3, 1.8))
}value::timestamp— UNIX-время в мс.returnзавершает событие.player_right_clickидёт один раз на клик (проверено с пустой второй рукой). Фильтр по руке — дешёвая страховка.- ПКМ пустой рукой в воздух события не даёт: клиент ничего не шлёт.
Нажимная плита-телепорт
Что делает: наступил на каменную нажимную плиту — перенёсся в точку.
event<player_interact> {
if (value::event_interaction == "physical" && world::event_block_equals([item("stone_pressure_plate")])) {
player::teleport(location(0.5, 64, 0.5, 0, 0), keep_rotation = false)
player::play_sound(sound("entity.enderman.teleport", 0.5, 1.2))
}
}Тип блока — только через event_block_equals
value::event_block_type — полное состояние блока ("minecraft:light_weighted_pressure_plate[power=0]"), == с id всегда ложь. Тип — через world::event_block_equals([item("id")]).
Пока стоишь на плите, событие идёт ~2 раза в секунду. Не нужен повтор — кулдаун или реакция только на новую плиту (как в паркуре).
Награда за убийство
Что делает: убийца получает 10 монет и уведомление.
event<player_kill_player> {
save var %killer%_coins
%killer%_coins += 10
player::action_bar<killer_player>("&a+10 монет &7за &c%victim%")
player::play_sound<killer_player>(sound("entity.experience_orb.pickup", 0.5, 1.5))
}Кто игрок по умолчанию в player_kill_player (убийца или жертва) — неизвестно, поэтому явно: %killer%, <killer_player>. %killer%_coins — та же переменная, что %player%_coins этого игрока.
Случайный шанс
Что делает: сломал блок — 25% на алмаз, награда растёт с серией.
save var %player%_coins
save var %player%_streak
function reward_for(streak) {
if (streak >= 10) { return 50 }
if (streak >= 3) { return 20 }
return 5
}
event<player_break_block> {
line var roll = variable::random_in_range(1, 100)
if (roll <= 25) {
%player%_streak += 1
player::give_item(item("diamond"), 1)
%player%_coins += reward_for(%player%_streak)
player::action_bar("&bАлмаз! &7Серия: &f${%player%_streak}")
player::play_sound(sound("entity.player.levelup", 0.4, 1.6))
} else {
%player%_streak = 0
}
}Функция возвращает значение на каждом пути, иначе вызывающий получит старое. Подробнее — События, функции, процессы.
Отсчёт перед стартом
Что делает: крупные цифры 5…1 всем, потом старт раунда.
game var round_running = 0
function countdown() {
repeat::on_range(0, 4) { i -> // on_range включает конец: 0..4 — это 5 шагов
player::title<all_players>("&e${5 - i}", "&7Приготовься", 0, 25, 0)
player::play_sound<all_players>(sound("block.note_block.hat"))
code::wait(1, time_unit = "seconds")
}
player::title<all_players>("&a&lВПЕРЁД!", "", 0, 30, 10)
round_running = 1
}
event<player_join> {
if (round_running == 0) { countdown() }
}- Время
titleв тиках:fade_in,stay,fade_out. stay= 25 тиков — чуть дольше шага в 1 с, чтобы цифра не гасла до следующей.- В настоящей игре отсчёт запускает мировой цикл, а не вход игрока (Раунд).
Цикл игрока без дублей
Что делает: у каждого игрока цикл раз в секунду; повторный /play не плодит второй.
game var %player%_loop
save var %player%_coins
event<player_join> {
%player%_loop = value::timestamp
line var my = %player%_loop
repeat::forever() {
code::wait(1, time_unit = "seconds")
if (%player%_loop != my) { code::stop_repeat() } // новый вход забрал цикл себе
%player%_coins += 1
}
}/play в уже запущенном мире снова зовёт player_join, старый цикл живёт — двойные монеты. Метка поколения в %player%_loop гасит старый цикл (проверено). При выходе игрока цикл кончается сам.
Магазин через меню
Что делает: компас в последнем слоте хотбара; ПКМ — меню-магазин, клик по товару — покупка.
save var %player%_coins
inline var SHOP = "shop"
// компас в слот 8 (последний в хотбаре, слоты с 0). set_slot_item ЗАТИРАЕТ этот слот.
// has_item сначала: если игрок переложил компас, второй не выдаём
function give_menu_item() {
if (player::has_item(item("compass"), comparison_mode = "TYPE_ONLY")) { return }
player::set_slot_item(item("compass", "&aМагазин &7(ПКМ)"), 8)
}
event<player_join> {
%player%_coins ??= 100
give_menu_item() // последним: ошибка в нём не должна сорвать выдачу монет
}
// смерть выкидывает компас вместе с инвентарём
event<player_respawn> {
code::wait(1)
give_menu_item()
}
// не даём выбросить его на Q (что cancel_event останавливает выброс, не проверено — проверь один раз)
event<player_drop_item> {
if (world::event_item_equals(item("compass"), comparison_mode = "TYPE_ONLY")) { world::cancel_event() }
}
event<player_right_click> {
if (value::event_equipment_slot != "hand") { return }
if (player::is_holding(item("compass"), comparison_mode = "TYPE_ONLY")) {
player::show_menu([
item("bread", "&aХлеб", lore = ["&75 монет"]),
item("iron_sword", "&bМеч", lore = ["&750 монет"])
], "&8Магазин", inventory_type = "CHEST", custom_id = SHOP)
}
}
// клик: отменить (чтобы ничего не утащили), потом ОДНА строка на кнопку: слот → вызов, return
event<player_click_inventory> {
if (value::open_inventory_custom_id != SHOP) { return }
world::cancel_event()
line var slot = value::event_slot
if (slot == 0) { buy(item("bread"), 5); return }
if (slot == 1) { buy(item("iron_sword"), 50); return }
}
// параметры — общие переменные с вызывающим: не называй так свои var
function buy(goods, price) {
if (%player%_coins < price) {
player::action_bar("&cНе хватает монет: &f${%player%_coins}&7/&f$price")
player::play_sound(sound("entity.villager.no"))
return
}
%player%_coins -= price
player::give_item(goods, 1)
player::action_bar("&aКуплено! &7Осталось &e${%player%_coins}")
player::play_sound(sound("entity.experience_orb.pickup", 0.3, 1.8))
}Проверено на сервере:
show_menuкладёт предметы со слота 0 по порядку.value::event_slotтоже с 0.custom_idприходит вvalue::open_inventory_custom_id— так своё меню отличают от чужих.player_click_inventory— только клики по меню. Клики по своему инвентарю при открытом меню —player_click_own_inventory.
Не пиши код кнопок прямо в событии клика: длинный else if трудно чинить. Каждой кнопке — своя функция без параметров: if (slot == 2) { buy_axe(); return }. Кнопок много — диспетчер по списку (Оптимизатор).
Паркур на время
Что делает: каменная плита — старт, золотые — чекпоинты, железная — финиш. Упал — на последний чекпоинт, на финише — время.
game var %player%_running // 1, пока идёт забег
game var %player%_start // время старта (мс)
game var %player%_cp // куда вернуть после падения
game var %player%_cp_block // плита последнего чекпоинта (чтобы не считать её дважды)
game var %player%_cp_n // сколько новых чекпоинтов с начала забега
inline var CHECKPOINTS = 3 // золотых плит на трассе
event<player_interact> {
if (value::event_interaction != "physical") { return }
if (world::event_block_equals([item("stone_pressure_plate")])) {
run_start()
} else if (world::event_block_equals([item("light_weighted_pressure_plate")])) {
run_checkpoint()
} else if (world::event_block_equals([item("heavy_weighted_pressure_plate")])) {
run_finish()
}
}
function run_start() {
%player%_running = 1
%player%_start = value::timestamp // пока стоишь на плите, время сбрасывается: отсчёт с момента, как сошёл
%player%_cp = value::location
%player%_cp_block = value::event_block
%player%_cp_n = 0
player::action_bar("&aВперёд!")
}
function run_checkpoint() {
if (%player%_running == 0) { return }
if (value::event_block == %player%_cp_block) { return } // та же плита — уже засчитана
%player%_cp = value::location
%player%_cp_block = value::event_block
%player%_cp_n++
player::action_bar("&eЧекпоинт &f${%player%_cp_n}&7/&f$CHECKPOINTS")
player::play_sound(sound("block.note_block.pling", 0.5, 1.5))
}
function run_finish() {
if (%player%_running == 0) { return }
if (%player%_cp_n < CHECKPOINTS) {
player::action_bar("&cПропущен чекпоинт: &f${%player%_cp_n}&7/&f$CHECKPOINTS")
player::play_sound(sound("entity.villager.no"))
return
}
%player%_running = 0 // следующий забег — снова со старта
player::title("&6&lФИНИШ", "&f${std::mmss(value::timestamp - %player%_start)}", 5, 60, 10)
player::play_sound(sound("ui.toast.challenge_complete"))
}
// player_move идёт каждый тик, пока игрок движется: самая дешёвая проверка (число) — первой
event<player_move> {
if (value::y_coord < 50) {
if (%player%_running == 1) {
player::teleport(%player%_cp, keep_rotation = false) // _cp всегда задан, пока идёт забег
} else {
player::teleport(location(0.5, 64, 0.5, 0, 0), keep_rotation = false)
}
player::action_bar("&cУпал!")
return
}
}Почему так:
- Таймер запускает только стартовая плита. Иначе после финиша шагнул на последний чекпоинт — и «пришёл» за 2 секунды.
- Две
value::event_blockодной плиты равны через==(проверено): повтор на той же плите — не новый чекпоинт. CHECKPOINTSне спасает от срезов между чекпоинтами. Настоящая защита — трасса без обходов.std::mmss— мс вмм:ссодним действием.
Топ на табло
Что делает: результаты в сохранённом словаре, топ-5 на табло в мире.
save var top_scores // словарь: имя → очки
save var board_u // uuid табло
inline var EMPTY = "&8—"
// словарь сначала создать: set на неприсвоенной переменной — ошибка сервера, строка встанет
function save_score(score) {
top_scores ??= variable::create_map_from_values([], [])
top_scores["%player%"] = score
code::start_process("upd_board", target_mode = "NO_TARGET")
}
// строки табло: 5 мест, пустые — прочерк. sort у словаря сохраняет порядок для get_map_key_by_index
process upd_board() {
top_scores ??= variable::create_map_from_values([], [])
line var rows = [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY]
line var sorted = top_scores.sort(sort_order = "DESCENDING", sort_type = "VALUES")
line var size = sorted.length()
if (size > 5) { size = 5 }
if (size > 0) {
repeat::on_range(0, size - 1) { i ->
line var name = sorted.get_map_key_by_index(i)
rows[i] = "&e${i + 1}. &f$name &7— &6${sorted[name]}"
}
}
select::entity_by_name([board_u])
entity::set_text_display_text(["&#FFB300&lТОП-5", rows[0], rows[1], rows[2], rows[3], rows[4]], merging_mode = "SEPARATE_LINES")
select::reset()
}
// мировой код: табло ставим один раз (дисплеи переживают /play), потом заполняем
board_u ??= ""
if (!world::has_entity([board_u])) {
world::spawn_text_display(location(0.5, 6, -10.5, 0, 0), "top", merging_mode = "SEPARATE_LINES", displayed_text = ["&#FFB300&lТОП-5"])
board_u = value::uuid<last_entity>
entity::set_display_billboard<last_entity>("VERTICAL")
entity::set_text_display_background<last_entity>("#000000", 55)
entity::set_text_display_text_shadow<last_entity>(true)
}
code::start_process("upd_board", target_mode = "NO_TARGET")
event<player_break_block> {
save var %player%_mined
%player%_mined += 1
save_score(%player%_mined)
}sort_any_mapсохраняет порядок дляget_map_key_by_indexиfor_each(проверено).on_rangeвключает конец — цикл доsize - 1.- Табло обновляет отдельный процесс без цели: его ошибка, скорее всего, не оборвёт событие игрока (своя строка кода; вывод, не проверялось). Действия без
<селектора>в нём бьют по выбранной сущности (select::entity_by_name). - Здесь обновление на каждый блок. Частые события — обновляй раз в несколько секунд из мирового цикла: смена текста — одно из самых дорогих изменений дисплея (≈12 мкс за строку).
- Вид и фон табло — Текст и интерфейс → Табло в мире. Словари — Списки и словари.
Частицы на грани блока
Что делает: клик по золотому блоку — частицы на этой грани, видно от первого лица с любой стороны.
event<player_interact> {
if (value::event_equipment_slot != "hand") { return }
if (!variable::equals(value::event_interaction, ["left_click_block", "right_click_block"], compare_type = "ANY")) { return }
if (world::event_block_equals([item("gold_block")])) {
player::play_sound(sound("entity.experience_orb.pickup", 0.3, 1.8))
line var face = variable::get_vector_from_block_face(value::event_block_face)
line var at = variable::align_location(value::event_block, "KEEP", "ALL", "BLOCK_CENTER")
at = variable::shift_location_on_vector(at, face, 0.6) // центр блока + 0.6 наружу
player::display_particle(particle("crit", 6, 0.25, 0.25), at)
}
}Кусок из нашего кликера, проверен вживую. Клик в воздух отсекается до event_block_equals (у него нет блока). variable::equals(..., compare_type = "ANY") дешевле двух ==.
Фейерверк
Что делает: фейерверк над игроком (финиш, победа).
event<player_join> {
var fw = variable::set_item_component(item("firework_rocket"), "fireworks", "{flight_duration:1b,explosions:[{shape:\"large_ball\",colors:[I;16766720]}]}")
world::launch_firework(fw, value::location, "UPWARDS", instant = false)
}Компонент — SNBT, цвета — массив [I;...] чисел (16766720 = #FFD700). Проверено на сервере.
Компас в boss bar
Что делает: полоса сверху показывает стороны света по взгляду, как в шутерах. Из examples/compass.
function update_compass(yaw) {
inline var BOSS_BAR_ID = "compass";
inline var SOUTH = 0;
inline var EAST = 90;
inline var NORTH = 180;
inline var WEST = 270;
inline var N = "&7N";
inline var E = "&7E";
inline var S = "&7S";
inline var W = "&7W";
inline var BLANK = "&8◦";
var final = "";
var length = 0;
var needed_length = 35;
var correct_yaw = (yaw + 180).round();
var snapped_yaw =
180 - ((correct_yaw - correct_yaw % 5) + 5 * floor((correct_yaw % 5) / 2.5));
var half_of_length = floor(needed_length / 2);
repeat::while(length.less(needed_length)) {
var char = (snapped_yaw - (length - half_of_length) * 5).warp(0, 360);
if (char.equals(NORTH)) { char = N }
if (char.equals([SOUTH, 360])) { char = S }
if (char.equals(EAST)) { char = E }
if (char.equals(WEST)) { char = W }
if not (char.equals([N, S, E, W])) { char = BLANK }
final = variable::set_text([final, char])
length = (final.regex_replace_text("[\s\p{Z}]|&.", "")).get_text_length()
}
player::set_boss_bar(
BOSS_BAR_ID,
final,
progress = 0,
color = "WHITE",
sky_effect = "FOG_AND_DARK_SKY"
)
}
event<player_join> {
repeat::forever() {
update_compass(value::yaw);
code::wait(1);
}
}Старый пример из jmcc: при progress = 0 boss bar — просто надпись. Но дорого: каждый тик у каждого игрока repeat::while на 35 шагов с regex_replace_text. Обновляй реже (code::wait(5)) или при повороте головы, цикл защити меткой поколения.
Ковка с мягкой остановкой
Что делает: ковка 10 секунд; ушёл мир на /build — руда возвращается.
save var %player%_ore
save var %player%_forging
event<player_right_click> {
if (value::event_equipment_slot != "hand") { return }
if (%player%_ore < 3) {
player::action_bar("&cНужно 3 руды")
player::play_sound(sound("entity.villager.no"))
return
}
std::session("ковка") {
%player%_ore -= 3
%player%_forging = 1 // взяли: с этого момента jmvcc_stop должен вернуть
player::action_bar("&7Куём...")
code::wait(10, time_unit = "SECONDS")
if (%player%_forging == 1) { // jmvcc_stop мог вернуть руду во время ожидания
%player%_forging = 0
player::give_item(item("diamond"), 1)
player::action_bar("&bГотово!")
player::play_sound(sound("entity.player.levelup", 0.5, 1.4))
}
}
}
event<jmvcc_stop> { // без code::wait; идёт при каждом выходе — только под флагом
if (%player%_forging == 1) { %player%_ore += 3; %player%_forging = 0 }
}Флаг не даёт случиться возврату и награде вместе. Подробно — Мягкая остановка.
Раунд «последний выживший»
Что делает: ждёт игроков, отсчёт, каждому свой спавн и набор, объявляет победителя, победы сохраняются. Это docs/recipes-round.jc целиком: копируй, меняй спавны и набор.
Устройство:
- Один мировой цикл в верхнем коде ведёт игру через
game var state: 0 ожидание → 1 отсчёт → 2 бой → 3 итоги и перерыв → 0. События только меняют состояние: поток игрока умирает посреди кода, когда тот выходит. alive— имена бойцов. Каждый тик цикл оставляет только тех, кто онлайн:player_quitможет не успеть доработать.- Свой спавн:
select::player_by_name(name), действия без<селектора>, в концеselect::reset(). - Победа — через имя в обратных кавычках:
save var `${w}_wins`— та же переменная, что%player%_winsэтого игрока. player_respawnв бою: умер в раунде — зритель. Ещё вalive(умер до раунда, в лобби) — в бой, иначе убийца в лобби получил бы бесплатную победу.
docs/recipes-round.jc целиком
// Round-based mini-game: last player alive wins. Compiles as is (jmvcc check docs/recipes-round.jc).
// Design: ALL round flow lives in ONE world loop in top-level code (world_start, no target).
// A thread bound to a player stops mid-execution when that player quits, so events only
// change shared state (game vars); the world loop decides what happens next.
// enum State and struct Stats are compile-time only: the JSON is the same as with plain numbers and %player%_wins.
// Verified: value::players / value::all_players_names work in world code with no target.
// FLOOR_Y — the top floor block of YOUR world (measure it: F3 / jmvcc client export; never guess, never y=64).
// Players stand at FLOOR_Y + 1; every teleport / spawn below is on the floor. Owner's world: 32x32 floor, x,z -16..15, top y=3.
inline var FLOOR_Y = 3
enum State { WAITING, COUNTDOWN, RUNNING, OVER } // numbers 0..3; OVER = results and the break
struct Stats { wins = 0 } // saved per player: %player%.wins IS save var %player%_wins ("Steve_wins")
save var %player%: Stats
game var state: State = State.WAITING
game var alive = [] // names of fighters still in the round
inline var MIN_PLAYERS = 2
// fighter spawn points: SEPARATE spots, standing ON the ground (y = floor + 1), never a drop
// that can kill. The spectator spot is somewhere else (spectators cannot take damage).
game var spawns = [location(10, FLOOR_Y + 1, 0, 90, 0), location(-10, FLOOR_Y + 1, 0, -90, 0), location(0, FLOOR_Y + 1, 10, 180, 0), location(0, FLOOR_Y + 1, -10, 0, 0)]
function to_lobby() {
player::set_gamemode("ADVENTURE")
player::teleport(location(0, FLOOR_Y + 1, 14, 180, 0), keep_rotation = false)
}
function to_spectator() {
player::set_gamemode("SPECTATOR")
player::teleport(location(0, FLOOR_Y + 12, 0, 0, 90), keep_rotation = false)
}
// player_join also fires for players already in the world when the game starts (/play) — verified
event<player_join> {
%player% ??= Stats() // new players get wins = 0, old ones keep theirs
if (state == State.RUNNING) {
to_spectator()
player::message("&7A round is running, you are spectating")
} else {
to_lobby()
}
// permanent HUD: the action bar fades after a few seconds, so refresh it every 20 ticks
// (this per-player loop ends by itself when the player quits)
repeat::forever() {
player::action_bar("&eWins: ${%player%.wins} &7Alive: ${alive.get_list_length()}")
code::wait(20)
}
}
// death -> out of the round. %player% here is the player who died. Capture the name in a line var:
// whose name %player% becomes inside a <all_players> text is NOT verified (open question #9).
event<player_death> {
if (state != State.RUNNING) { return }
line var who = "%player%"
if (variable::list_contains_value(alive, who)) {
alive.remove_list_value(who, remove_mode = "ALL")
player::message<all_players>("&c$who &7is out")
}
}
// a player who died IN the round was already removed from alive (player_death) and comes back as a
// spectator until the round ends. A player still in alive died BEFORE the round (lobby PvP, a fall, AFK on the
// death screen when start_round copied all_players_names): start_round could not place them, so they respawn
// INTO the fight with the kit. Removing them instead would hand a free win to whoever killed them in the lobby.
// state is read BEFORE the wait: if start_round runs during that tick, it has already placed this player.
// (A player who stays on the death screen keeps the round going until they respawn or quit.)
event<player_respawn> {
line var who = "%player%"
line var was = state
code::wait(1) // let the respawn finish before changing mode and position
if (state != State.RUNNING) {
to_lobby()
} else if (!variable::list_contains_value(alive, who)) {
to_spectator()
} else if (was == State.RUNNING) {
line var n = alive.get_list_index_of_value(who)
player::teleport(spawns[n % spawns.get_list_length()], keep_rotation = false)
player::set_gamemode("SURVIVAL")
player::heal(20)
player::clear_inventory("ENTIRE")
player::give_items(item("stone_sword"), 1)
}
// else: start_round ran during the wait and already placed this player
}
// keep only fighters that are still online: player_quit code may be cut off when the player
// leaves, so the world loop re-syncs every tick instead of trusting a quit handler
function sync_alive() {
line var online = value::all_players_names
line var kept = []
repeat::for_each_in_list(alive) { i, name ->
if (variable::list_contains_value(online, name)) {
kept.list_append_value(name)
}
}
alive = kept
}
// 10 s countdown; stops if players leave. on_range includes the end: 0..9 is 10 steps
function countdown() {
state = State.COUNTDOWN
repeat::on_range(0, 9) { i ->
if (value::players < MIN_PLAYERS) {
player::message<all_players>("&cNot enough players, countdown stopped")
state = State.WAITING
return
}
player::title<all_players>("&e${10 - i}", "&7Round starts", 0, 25, 0)
player::play_sound<all_players>(sound("block.note_block.hat"))
code::wait(1, time_unit = "seconds")
}
start_round()
}
// every fighter gets its own spawn: select the player by name, actions without <selector>
// then act on the selection (reset it afterwards). Verified with one player (server-check-5 №5a).
function start_round() {
// someone may have left during the last second of the countdown: no free win for the one left
if (value::players < MIN_PLAYERS) {
state = State.WAITING
return
}
alive = value::all_players_names
repeat::for_each_in_list(alive) { i, name ->
select::player_by_name(name)
player::teleport(spawns[i % spawns.get_list_length()], keep_rotation = false)
player::set_gamemode("SURVIVAL")
player::heal(20)
player::clear_inventory("ENTIRE")
player::give_items(item("stone_sword"), 1)
}
select::reset()
player::title<all_players>("&aFIGHT!", "&7Last one standing wins", 0, 30, 10)
state = State.RUNNING
}
// last alive wins: +1 saved win through a backtick name. It must be declared (save var = saved
// scope) and is the SAME storage as %player%.wins for that player.
// State.OVER while results and the break run: events see "not running" and nothing can start a new
// countdown before the break is over (also if you ever run end_round as a separate process).
function end_round() {
state = State.OVER
if (alive.get_list_length() == 1) {
line var w = alive[0]
save var `${w}`: Stats
`${w}`.wins += 1
player::message<all_players>("&6$w &ewins! &7Total wins: ${`${w}`.wins}")
player::title<all_players>("&6$w", "&ewins the round", 0, 60, 10)
} else {
player::message<all_players>("&7Round over: nobody survived")
}
alive = []
code::wait(3, time_unit = "seconds")
player::clear_inventory<all_players>("ENTIRE")
player::set_gamemode<all_players>("ADVENTURE")
player::teleport<all_players>(location(0, FLOOR_Y + 1, 14, 180, 0), keep_rotation = false)
code::wait(5, time_unit = "seconds") // short break before the next countdown
state = State.WAITING
}
// the world loop (top-level code = world_start): waiting -> countdown -> running -> over -> waiting
repeat::forever() {
if (state == State.WAITING) {
if (value::players >= MIN_PLAYERS) { countdown() }
} else if (state == State.RUNNING) {
sync_alive()
if (alive.get_list_length() <= 1) { end_round() }
}
code::wait(1)
}Чат в рецепте
Рецепт объявляет выбывших и победителя в чат (player::message<all_players>). Красивее — title и action bar со звуком, счёт побед — на табло (Топ на табло).
Босс
Что делает: ПКМ звездой Незера — босс с полосой здоровья для всех. Зовёт ограниченное число прислужников, урон игроков пишется в таблицу, в финале — лучший игрок и алмаз всем. Это docs/recipes-boss.jc целиком.
Устройство:
- Призыв из события игрока:
world::spawn_entity(item("vindicator_spawn_egg"), loc, 200, "&4&lThe King"), сразуboss = value::uuid<last_entity>. Только если!world::has_entity([boss]), плюс кулдаун. - Мобы переживают
/play, game-переменные — нет. uuid босса и прислужников — вsave var; при старте мира и в конце боя процесс без цели удаляет их. - Один цикл на бой, метка поколения: призыв делает
boss_gen += 1, цикл помнитmy = boss_genи выходит, еслиboss_gen != myили босса нет. Два быстрых призыва не дадут двух циклов. - Значения босса — в отдельном процессе:
select::entity_by_name([boss]), затемvalue::health<current>. Там же «поводок»: увели дальшеLEASHблоков — телепорт на арену. - Полоса — в
entity_take_damage:value::healthтам — здоровье до удара, поэтомуboss_hp = max(0, value::health - value::event_final_damage). Прогресс 0–100. - Финал — в
entity_death: поток переживаетcode::wait, хотя сущность мертва.
docs/recipes-boss.jc целиком
// Boss fight: right-click with a nether star summons the King, a boss bar for everyone, capped minions,
// a damage table and a finale. Compiles as is (jmvcc check docs/recipes-boss.jc). Change the arena spots.
// Built on server-verified facts (server-check-5, bench/sneak/sel-read.jc, bench/sneak/cleanup.jc):
// - world::spawn_mob(..., health = 200, name) gives 200 health without set_max_health; right after it
// value::uuid<last_entity> is that mob's uuid (verified in a player event, so we spawn from player events)
// - world::has_entity([uuid]) is the liveness check; has_entity([""]) is false
// - mobs SURVIVE /play, game vars do not: without cleanup the old boss stands there with no loop or bar
// - in a NO_TARGET thread actions without <selector> go to the selection; value::x<current> reads the
// selection (value::x WITHOUT a selector does not)
// - in entity_take_damage value::health is the damaged entity's, BEFORE the hit; value::event_final_damage is
// what it takes; value::uuid in entity_take_damage / entity_death is that entity (this recipe was run live:
// summon, bar, damage table, finale — bench/sneak/boss-test.jc)
// - the entity_death thread survives code::wait; boss bar progress is 0..100, & colors in its title work
// NOT verified, inferred (each spot has a uuid guard, so a wrong guess skips code instead of breaking the fight):
// - value::uuid<victim_entity> in player_damage_entity: not used, so a hit on ANY mob during a fight counts.
// - has_entity for a mob in an unloaded chunk: if it is false there, a boss lured far away counts as gone.
// The leash in boss_tick keeps it near the arena.
// Error isolation: a server error stops the rest of ITS code line (the loop after it, functions it calls).
// The fight loop holds only cheap verified actions; boss abilities and cleanup run as their own processes.
inline var BOSS_HP = 200
inline var BAR = "king"
inline var MAX_MINIONS = 4
inline var MINION_CD = 5000 // ms between minion calls
inline var SUMMON_CD = 60000 // ms between summons: the star is not used up and every kill gives diamonds
inline var LEASH = 24 // blocks from the arena; a boss lured farther is teleported back
// FLOOR_Y — the top floor block of YOUR world (measure it: F3 / jmvcc client export; never guess, never y=64).
// Players stand at FLOOR_Y + 1; every teleport / spawn below is on the floor. Owner's world: 32x32 floor, x,z -16..15, top y=3.
inline var FLOOR_Y = 3
game var arena = location(0.5, FLOOR_Y + 1, 0.5, 0, 0)
game var boss = "" // current boss uuid; "" = none
game var boss_gen = 0 // +1 per summon: a loop started for another number is stale and stops
game var boss_hp = 0 // for the bar
game var dmg // map: player name -> damage dealt during the fight (created on summon)
game var minions = [] // uuids of the current boss's living minions (pruned with has_entity)
game var last_minion = 0 // timestamp of the last minion call
game var last_summon = 0 // timestamp of the last summon
save var boss_mobs // uuids of the boss and its minions: a SAVE var survives /play like the mobs do
// world code: only variable setup above; the leftover cleanup runs in its own process
code::start_process("remove_boss_mobs", target_mode = "NO_TARGET")
event<player_join> {
if (!player::has_item(item("nether_star"), comparison_mode = "TYPE_ONLY")) {
player::give_items(item("nether_star", "&dSummon the King", lore = ["&7Right-click"]))
}
}
// summon only if there is no boss. has_entity, not a flag: a boss killed or removed outside our events is
// noticed. A boss left from before /play is NOT seen here (game var boss resets to ""): remove_boss_mobs
// removes it on world start.
event<player_right_click> {
if (value::event_equipment_slot != "hand") { return }
if (!player::is_holding(item("nether_star"), hand_slot = "MAIN_HAND", comparison_mode = "TYPE_ONLY")) { return }
if (world::has_entity([boss])) {
player::action_bar("&cThe King is already here")
return
}
if (value::timestamp < last_summon + SUMMON_CD) {
player::action_bar("&cThe King is not ready to come back yet")
return
}
summon_boss()
}
function summon_boss() {
last_summon = value::timestamp
world::spawn_mob(item("vindicator_spawn_egg"), arena, BOSS_HP, "&4&lThe King", main_hand = item("iron_axe"))
boss = value::uuid<last_entity>
boss_mobs ??= []
boss_mobs.list_append_value(boss)
boss_hp = BOSS_HP
boss_gen += 1
dmg = variable::create_map_from_values([], [])
minions = []
line var who = "%player%"
player::message<all_players>("&c$who &7summoned &4&lThe King")
code::start_process("boss_loop", target_mode = "NO_TARGET")
}
// ONE loop per fight. my = the generation it was started for: if the boss dies and a new one is summoned
// during this loop's 1 s wait, the old loop sees boss_gen != my and stops, so two loops never run at once.
// remove_boss_mobs is safe to start at any time: it keeps the live boss and its minions.
process boss_loop() {
line var my = boss_gen
line var t = 0
repeat::forever() {
code::wait(1, time_unit = "seconds")
if (boss_gen != my) {
code::start_process("remove_boss_mobs", target_mode = "NO_TARGET") // the old fight's minions
break
}
if (!world::has_entity([boss])) { // died (entity_death does the finale) or was removed
player::remove_boss_bar<all_players>(BAR)
code::start_process("remove_boss_mobs", target_mode = "NO_TARGET")
break
}
show_bar() // every second: players who join mid-fight get it too
t++
if (t % 5 == 0) { code::start_process("boss_tick", target_mode = "NO_TARGET") }
}
}
// select the boss, read it with value::x<current> (verified), act on it with actions without <selector>.
// Put abilities here, not in the loop: a server error stops this run only, the fight loop goes on.
process boss_tick() {
if (!world::has_entity([boss])) { return }
select::entity_by_name([boss])
boss_hp = value::health<current> // re-sync (regeneration, damage the event missed)
if (variable::locations_distance(value::location<current>, arena) > LEASH) {
entity::teleport(arena) // leash: no luring it off the arena or into lava
}
select::reset()
}
function show_bar() {
player::set_boss_bar<all_players>(BAR, "&4&lThe King &f${ceil(boss_hp)}/$BOSS_HP", boss_hp / BOSS_HP * 100, color = "RED", style = "NOTCHED_10")
}
// value::health here is the damaged entity's, BEFORE the hit; value::uuid is the damaged entity (both verified)
event<entity_take_damage> {
if (value::uuid != boss) { return }
boss_hp = max(0, value::health - value::event_final_damage)
show_bar()
}
// damage table: %player% is the attacker, event_final_damage is filled (verified). Which entity was hit is
// NOT checked: value::uuid<victim_entity> is not verified, so during a fight a hit on ANY mob (a minion, a cow,
// another game's mob) adds to the table AND may call a minion. Once victim_entity is verified, return early
// unless it is the boss.
// entity::damage(n, "Name") from code also lands here as that player's hit.
event<player_damage_entity> {
if (!world::has_entity([boss])) { return }
line var who = "%player%"
line var cur = dmg.get_map_value(who) // missing key -> 0 (verified)
dmg.set_map_value(who, cur + value::event_final_damage)
call_minion()
}
// minions answer the players' hits: at most one per MINION_CD and MAX_MINIONS alive. Spawned in this player
// thread, where spawn_mob -> value::uuid<last_entity> is verified. Husks do not burn by day (zombies do).
function call_minion() {
line var now = value::timestamp
if (now < last_minion + MINION_CD) { return }
line var kept = []
repeat::for_each_in_list(minions) { i, u ->
if (world::has_entity([u])) { kept.list_append_value(u) }
}
minions = kept
// boss_mobs is a save var: drop dead uuids so a long fight does not grow it without bound
line var live = []
repeat::for_each_in_list(boss_mobs) { i, u ->
if (world::has_entity([u])) { live.list_append_value(u) }
}
boss_mobs = live
if (minions.get_list_length() >= MAX_MINIONS) { return }
last_minion = now
world::spawn_mob(item("husk_spawn_egg"), location(4.5, FLOOR_Y + 1, 0.5, 0, 0), 20, "&7Servant")
line var m = value::uuid<last_entity>
minions.list_append_value(m)
boss_mobs.list_append_value(m)
}
// finale: this thread survives code::wait; value::uuid is the dead entity (both verified).
// No cleanup here: boss_loop notices the death within 1 s and starts remove_boss_mobs.
event<entity_death> {
if (value::uuid != boss) { return }
player::remove_boss_bar<all_players>(BAR)
player::title<all_players>("&6The King has fallen!", "&eEveryone gets a diamond", 10, 60, 20)
line var sorted = variable::sort_any_map(dmg, sort_order = "DESCENDING", sort_type = "VALUES")
code::wait(2, time_unit = "seconds")
if (sorted.get_map_size() > 0) {
line var top = sorted.get_map_key_by_index(0)
line var amount = sorted.get_map_value(top)
player::message<all_players>("&eTop damage: &f$top &7(${round(amount, 1)})")
}
player::give_items<all_players>(item("diamond"))
}
// remove the boss's mobs by uuid: on world start (leftovers from the last session) and when a fight ends
// (boss_loop). Each step is verified: has_entity(uuid); select::entity_by_name([uuid]) picks that mob;
// entity::remove() without <selector> acts on the selection in a NO_TARGET thread.
// The list is copied and cleared FIRST (list assignment copies, verified): mobs spawned meanwhile go to the
// fresh list. A live boss and its minions are put back, never removed, so this is safe at any time.
// Blunt alternative (verified, bench/sneak/cleanup.jc): select::all_mobs() + entity::remove() in world code
// removes EVERY mob in the world (animals, villagers, other games' mobs). Selecting by custom name or tag
// is not verified (the name comes back with § codes), so it is not used here.
process remove_boss_mobs() {
boss_mobs ??= []
line var old = boss_mobs
boss_mobs = []
code::wait(1, time_unit = "seconds") // the verified world-start cleanup waited 1 s too
repeat::for_each_in_list(old) { i, u ->
line var keep = 0
if (world::has_entity([boss])) {
if (u == boss || variable::list_contains_value(minions, u)) { keep = 1 }
}
if (keep == 1) {
boss_mobs.list_append_value(u) // the live fight's mobs stay tracked
} else if (world::has_entity([u])) {
select::entity_by_name([u])
entity::remove()
}
}
select::reset()
}Что в боссе не проверено
Не проверены value::uuid<victim_entity> в player_damage_entity (поэтому в бою засчитывается удар по любому мобу) и has_entity для моба в незагруженном чанке. Всё это за проверкой uuid: догадка неверна — код пропустится, бой не сломается.
Где ещё смотреть
docs/recipes*.jc— исходники рецептов с комментариями (на английском).examples/—compass,generator.jc(шум Перлина),nwo(режим New World Order, файлы черезimport).- Действия и аргументы — справочник, в терминале
jmvcc search <слова>иjmvcc sig <имя>. - Подводные камни — Грабли и факты сервера.