Files
BuildersBattle
Code
102 1,801
BuildersBattle/behavior_pack/scripts/main.js
import { world, system, ItemStack } from "@minecraft/server";
import { ActionFormData, ModalFormData, FormCancelationReason } from "@minecraft/server-ui";
import { MODE_RULES, applyModeSettings } from "./modes.js";
import { openVotingForm, topTeams } from "./voting.js";
import { openJudgeForm } from "./judge.js";
import { openSettingsForm } from "./settings.js";
import { getPlayerStats, openStatsForm, updateSidebar } from "./stats.js";
import { awardRound } from "./progression.js";
import { openSocialForm } from "./social.js";
const themes = ["Замок", "Дом будущего", "Пиратский корабль", "Подводная база", "Волшебный лес", "Мост", "Космическая станция", "Дерево-дом", "Средневековый рынок", "Зимняя деревня"];
const controlItems = ["bs:builder_hammer", "bs:theme_scroll", "bs:hourglass", "bs:voting_scroll", "bs:winner_cup", "bs:settings_book", "bs:judge_book", "bs:stats_book", "bs:shop_token"];
const lampBlocks = new Set(["bs:bedroom_lamp", "bs:floor_lamp", "bs:street_lamp", "bs:bridge_lamp", "bs:desk_lamp"]);
const bedBlocks = new Set(["bs:bed_red", "bs:bed_blue", "bs:bed_green"]);
const seatBlocks = new Set(["bs:sofa", "bs:sofa_blue", "bs:sofa_green", "bs:armchair", "bs:dining_chair", "bs:office_chair", "bs:bench"]);
const controlBlocks = new Set(["bs:computer", "bs:registration_block", "bs:theme_block", "bs:start_block", "bs:finish_block", "bs:timer_block", "bs:voting_block", "bs:judge_block", "bs:podium_block", "bs:reward_block", "bs:zone_block", "bs:barrier_zone", "bs:teleport_block", "bs:copy_block", "bs:glow_block", "bs:stats_block", "bs:leaderboard_block"]);
const furnitureCooldowns = new Map();
const defaults = {
settings: { duration: 300, teams: 2, zoneSize: 32, mode: "classic", judgeEnabled: true, judgeWeight: 3, viewerWeight: 1, allowForeignBreak: false, visibleResults: false, anonymous: true, pvp: false, tieBreak: "revote", minVotes: 1 },
round: { active: false, phase: "idle", theme: "", endTime: 0, startedAt: 0, votes: {}, judgeScores: [0, 0, 0, 0], judgeSubmissions: {}, submittedTeams: [], rewardClaims: {}, rerolls: 0, warned60: false },
stats: {}, respects: {}, reports: {}, origin: null, lastWinner: -1
};
const freshState = () => JSON.parse(JSON.stringify(defaults));
const isRecord = value => value !== null && typeof value === "object" && !Array.isArray(value);
let state = freshState();
let voteOpenedAt = 0;
function save() {
try {
world.setDynamicProperty("bb_state", JSON.stringify(state));
world.setDynamicProperty("bb_active", state.round.active);
world.setDynamicProperty("bb_theme", state.round.theme || "");
world.setDynamicProperty("bb_endTime", state.round.endTime || 0);
world.setDynamicProperty("bb_votes", JSON.stringify(state.round.votes));
world.setDynamicProperty("bb_stats", JSON.stringify(state.stats));
world.setDynamicProperty("bb_settings", JSON.stringify(state.settings));
} catch (error) {
console.warn(`BuildersBattle: save failed: ${error}`);
}
}
function load() {
try {
const stored = world.getDynamicProperty("bb_state");
if (typeof stored === "string") {
const parsed = JSON.parse(stored);
if (!isRecord(parsed)) throw new Error("Stored state is not an object.");
state = { ...freshState(), ...parsed };
state.settings = { ...defaults.settings, ...(isRecord(parsed.settings) ? parsed.settings : {}) };
state.round = { ...defaults.round, ...(isRecord(parsed.round) ? parsed.round : {}) };
state.round.votes = isRecord(state.round.votes) ? state.round.votes : {};
state.round.judgeScores = Array.isArray(state.round.judgeScores) ? state.round.judgeScores : [0, 0, 0, 0];
state.round.judgeSubmissions = isRecord(state.round.judgeSubmissions) ? state.round.judgeSubmissions : {};
state.round.submittedTeams = Array.isArray(state.round.submittedTeams) ? state.round.submittedTeams : [];
state.round.rewardClaims = isRecord(state.round.rewardClaims) ? state.round.rewardClaims : {};
state.stats = isRecord(parsed.stats) ? parsed.stats : {};
state.respects = isRecord(parsed.respects) ? parsed.respects : {};
state.reports = isRecord(parsed.reports) ? parsed.reports : {};
const origin = parsed.origin;
state.origin = isRecord(origin) && Number.isFinite(origin.x) && Number.isFinite(origin.y) && Number.isFinite(origin.z) && typeof origin.dimension === "string" ? origin : null;
state.lastWinner = Number.isInteger(parsed.lastWinner) ? parsed.lastWinner : -1;
applyModeSettings(state.settings);
}
} catch (error) {
console.warn(`BuildersBattle: load failed: ${error}`);
state = freshState();
}
}
const players = () => world.getAllPlayers();
const teamOf = player => {
for (let team = 0; team < 4; team++) if (player.hasTag(`bb_team_${team}`)) return team;
return -1;
};
const broadcast = message => world.sendMessage(message);
const ctx = { get state() { return state; }, save, players, teamOf, broadcast, world, system };
function giveControls(player) {
const inventory = player.getComponent("minecraft:inventory")?.container;
if (!inventory) return;
const existingTypes = new Set();
for (let slot = 0; slot < inventory.size; slot++) {
const item = inventory.getItem(slot);
if (item) existingTypes.add(item.typeId);
}
for (const typeId of controlItems) {
if (existingTypes.has(typeId)) continue;
try {
inventory.addItem(new ItemStack(typeId, 1));
existingTypes.add(typeId);
} catch (error) { console.warn(`BuildersBattle: cannot give ${typeId}: ${error}`); }
}
}
function teamCenter(team) {
const origin = state.origin;
const size = state.settings.zoneSize;
return { x: origin.x + (team + 0.5) * (size + 8), y: origin.y + 1, z: origin.z + size + 12 };
}
function assignTeam(player, registrationBlock) {
if (state.round.active) {
player.sendMessage("§cРегистрация закрыта до конца раунда.");
return;
}
if (teamOf(player) >= 0) {
player.sendMessage("§eВы уже зарегистрированы в команде.");
return;
}
if (!state.origin) state.origin = { x: registrationBlock.location.x, y: registrationBlock.location.y, z: registrationBlock.location.z, dimension: registrationBlock.dimension.id };
for (const tag of player.getTags()) if (tag.startsWith("bb_team_")) player.removeTag(tag);
const counts = Array(state.settings.teams).fill(0);
for (const online of players()) {
const team = teamOf(online);
if (team >= 0 && team < counts.length && online.id !== player.id) counts[team]++;
}
const team = counts.indexOf(Math.min(...counts));
player.addTag(`bb_team_${team}`);
player.sendMessage(`§aВы зарегистрированы в команде ${team + 1}.`);
save();
}
function teleportToPlots() {
if (!state.origin) return;
let dimension;
try { dimension = world.getDimension(state.origin.dimension); } catch { return; }
for (const player of players()) {
const team = teamOf(player);
if (team < 0 || team >= state.settings.teams) continue;
const center = teamCenter(team);
try { player.teleport(center, { dimension }); } catch { player.sendMessage("§cНе удалось телепортировать на участок."); }
}
}
function startRound(player) {
if (state.round.active) {
player.sendMessage("§eРаунд уже идёт.");
return;
}
if (state.settings.mode === "roulette" || !state.round.theme) state.round.theme = themes[Math.floor(Math.random() * themes.length)];
state.round = { ...defaults.round, active: true, phase: "countdown", theme: state.round.theme || themes[Math.floor(Math.random() * themes.length)], startedAt: Date.now(), endTime: Date.now() + 3000, votes: {}, judgeScores: [0, 0, 0, 0], judgeSubmissions: {}, submittedTeams: [], rewardClaims: {} };
voteOpenedAt = 0;
broadcast("§aБитва начнётся через 3 секунды!");
for (let second = 3; second > 0; second--) {
system.runTimeout(() => {
if (state.round.phase === "countdown") for (const online of players()) online.onScreenDisplay.setTitle(`${second}…`, { fadeInDuration: 0, stayDuration: 20, fadeOutDuration: 0 });
}, (4 - second) * 20);
}
save();
}
function openVotingPhase() {
state.round.phase = "voting";
state.round.endTime = Date.now() + 60000;
state.round.votes = {};
voteOpenedAt = Date.now();
broadcast("§6Строительство завершено! Зрители: используйте Свиток голосования или блок голосования.");
save();
}
function finishRound(winner) {
const elapsed = Math.max(0, Math.floor((Date.now() - state.round.startedAt) / 1000));
state.round.active = false;
state.round.phase = "complete";
state.round.endTime = 0;
state.lastWinner = winner;
broadcast(winner >= 0 ? `§6Победила команда ${winner + 1}! §eКубок вручён участникам онлайн.` : "§eРаунд завершён без победителя.");
for (const player of players()) {
const team = teamOf(player);
if (team < 0) continue;
const won = team === winner;
awardRound(ctx, player, won, elapsed);
player.sendMessage(won ? "§6Вы победили! Получено 50 XP и 25 монет." : "§7Утешительная награда: 20 XP и 10 монет.");
}
save();
}
function settleVote() {
const result = topTeams(ctx);
const totalVotes = result.counts.reduce((sum, value) => sum + value, 0);
let winner = result.teams.length === 1 ? result.teams[0] : -1;
if (totalVotes < state.settings.minVotes) winner = -1;
if (winner < 0 && state.settings.tieBreak === "revote" && state.round.rerolls < 1) {
state.round.rerolls++;
state.round.votes = {};
state.round.judgeSubmissions = {};
state.round.judgeScores = [0, 0, 0, 0];
state.round.endTime = Date.now() + 30000;
broadcast("§eНичья или не набран минимум голосов — переголосование 30 секунд.");
save();
return;
}
if (winner < 0 && state.settings.tieBreak === "judge" && state.settings.judgeEnabled) {
const scores = state.round.judgeScores.slice(0, state.settings.teams);
const max = Math.max(...scores);
if (max > 0 && scores.filter(score => score === max).length === 1) winner = scores.indexOf(max);
}
if (winner < 0) winner = Math.floor(Math.random() * state.settings.teams);
if (state.settings.visibleResults) {