Files
src
manifest.kod
Code
4 474
src/client/java/com/kodari/songcaptcha/SongCaptcha.java
package com.kodari.songcaptcha;
import io.wispforest.owo.ui.base.BaseOwoScreen;
import io.wispforest.owo.ui.component.LabelComponent;
import io.wispforest.owo.ui.component.TextBoxComponent;
import io.wispforest.owo.ui.component.UIComponents;
import io.wispforest.owo.ui.container.FlowLayout;
import io.wispforest.owo.ui.container.UIContainers;
import io.wispforest.owo.ui.core.Color;
import io.wispforest.owo.ui.core.HorizontalAlignment;
import io.wispforest.owo.ui.core.Insets;
import io.wispforest.owo.ui.core.OwoUIAdapter;
import io.wispforest.owo.ui.core.Sizing;
import io.wispforest.owo.ui.core.Surface;
import io.wispforest.owo.ui.core.VerticalAlignment;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.rendering.v1.hud.HudElementRegistry;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerChunkEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.fabricmc.fabric.api.event.player.AttackBlockCallback;
import net.fabricmc.fabric.api.event.player.PlayerBlockBreakEvents;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.client.MinecraftClient;
import net.minecraft.registry.Registries;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.sound.SoundEvents;
import net.minecraft.text.Text;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Identifier;
import net.minecraft.util.WorldSavePath;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.GameMode;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.ChunkSection;
import net.minecraft.world.chunk.ChunkStatus;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
public final class SongCaptcha implements ClientModInitializer {
private static final long TIME_LIMIT = 20_000_000_000L;
private static final int SCAN_BUDGET = 32768;
private static final List<Question> QUESTIONS = List.of(
new Question("3 сентября, день прощания, день когда горят костры...", "рябин"),
new Question("Батарейка: О-ой-и-я-и-ё!...", "батарейка"),
new Question("Знаешь ли ты, вдоль ночных дорог шла босиком, не жалея...", "ног"),
new Question("Малиновая лада, малиновый закат, твои глаза...", "магнит"),
new Question("Группа крови на рукаве, мой порядковый...", "номер")
);
private static final Map<UUID, Set<Block>> WHITELIST = new HashMap<>();
private static final Set<Block> REMOVED = new HashSet<>();
private static final Map<UUID, Challenge> ACTIVE = new HashMap<>();
private static final ArrayDeque<Scan> SCANS = new ArrayDeque<>();
private static MinecraftServer runningServer;
private static long nextId;
private static volatile Notice notice;
@Override
public void onInitializeClient() {
ServerLifecycleEvents.SERVER_STARTING.register(server -> {
runningServer = server;
WHITELIST.clear();
REMOVED.clear();
ACTIVE.clear();
SCANS.clear();
load(server);
});
ServerLifecycleEvents.SERVER_STOPPED.register(server -> {
if (runningServer == server) {
runningServer = null;
WHITELIST.clear();
REMOVED.clear();
ACTIVE.clear();
SCANS.clear();
}
});
AttackBlockCallback.EVENT.register((player, world, hand, pos, direction) -> {
if (!(player instanceof ServerPlayerEntity serverPlayer) || !(world instanceof ServerWorld serverWorld))
return ActionResult.PASS;
return start(serverPlayer, serverWorld, pos) ? ActionResult.FAIL : ActionResult.PASS;
});
PlayerBlockBreakEvents.BEFORE.register((world, player, pos, state, blockEntity) -> {
if (!(player instanceof ServerPlayerEntity serverPlayer) || !(world instanceof ServerWorld serverWorld))
return true;
return !start(serverPlayer, serverWorld, pos);
});
ServerChunkEvents.CHUNK_LOAD.register((world, chunk) -> {
if (!REMOVED.isEmpty()) {
ChunkPos pos = chunk.getPos();
SCANS.addLast(new Scan(world, pos.x, pos.z));
}
});
ServerTickEvents.END_SERVER_TICK.register(SongCaptcha::tickServer);
HudElementRegistry.addLast(Identifier.of("songcaptcha", "overlay"), (context, tickCounter) -> {
MinecraftClient client = MinecraftClient.getInstance();
if (client.player == null || client.world == null)
return;
int center = context.getScaledWindowWidth() / 2;
context.drawCenteredTextWithShadow(client.textRenderer, "ЦЕЛЬ: Добыть Алмаз 💎", center, 12, 0xFFFFFFFF);
if (client.currentScreen instanceof CaptchaScreen) {
context.drawCenteredTextWithShadow(client.textRenderer, "[УГАДАЙ ТРЕК!]", center, 24, 0xFFFF4040);
}
Notice current = notice;
if (current != null && System.nanoTime() < current.until()) {
int y = client.getWindow().getScaledHeight() / 2 - 20;
context.fill(center - 70, y, center + 70, y + 40, current.success() ? 0xF0124827 : 0xF0801717);
context.drawCenteredTextWithShadow(client.textRenderer,
current.success() ? "БЛОК РАЗБЛОКИРОВАН!" : "БЛОК УДАЛЕН!", center, y + 7, 0xFFFFFFFF);
if (!current.success()) {
context.drawCenteredTextWithShadow(client.textRenderer, "Правильный ответ:", center, y + 18, 0xFFFFFFFF);
context.drawCenteredTextWithShadow(client.textRenderer, current.answer(), center, y + 28, 0xFFFFFFFF);
}
}
});
}
private static boolean start(ServerPlayerEntity player, ServerWorld world, BlockPos pos) {
if (player.getGameMode() != GameMode.SURVIVAL)
return false;
UUID uuid = player.getUuid();
if (ACTIVE.containsKey(uuid))
return true;
Block block = world.getBlockState(pos).getBlock();
if (block == Blocks.AIR || WHITELIST.getOrDefault(uuid, Set.of()).contains(block))
return false;
Question question = QUESTIONS.get(ThreadLocalRandom.current().nextInt(QUESTIONS.size()));
Challenge challenge = new Challenge(++nextId, world, block, question,
player.getX(), player.getY(), player.getZ(), System.nanoTime() + TIME_LIMIT);
ACTIVE.put(uuid, challenge);
player.setVelocity(0, 0, 0);
MinecraftClient client = MinecraftClient.getInstance();
MinecraftServer server = runningServer;
client.execute(() -> {
if (client.getServer() == server && client.player != null && client.player.getUuid().equals(uuid)) {
notice = null;
client.setScreen(new CaptchaScreen(challenge.id(), question.prompt(), challenge.deadline()));
}
});
return true;
}
private static void tickServer(MinecraftServer server) {
if (server != runningServer)
return;
for (UUID uuid : List.copyOf(ACTIVE.keySet())) {
Challenge challenge = ACTIVE.get(uuid);
ServerPlayerEntity player = server.getPlayerManager().getPlayer(uuid);
if (player == null || !player.isAlive() || player.getEntityWorld() != challenge.world()) {
ACTIVE.remove(uuid);
closeScreen(server, uuid, challenge.id(), null);
continue;
}
if (System.nanoTime() >= challenge.deadline()) {
finish(server, player, challenge, false);
continue;
}
player.setVelocity(0, 0, 0);
if (Math.abs(player.getX() - challenge.x()) > 0.001
|| Math.abs(player.getY() - challenge.y()) > 0.001
|| Math.abs(player.getZ() - challenge.z()) > 0.001) {
player.requestTeleport(challenge.x(), challenge.y(), challenge.z());
}
}
int budget = SCAN_BUDGET;
while (budget > 0 && !SCANS.isEmpty()) {
Scan scan = SCANS.peekFirst();
int used = scan.step(budget);
budget -= Math.max(used, 1);
if (scan.done)
SCANS.removeFirst();
}
}
private static void answer(long id, String input) {
MinecraftClient client = MinecraftClient.getInstance();
MinecraftServer server = client.getServer();
if (server == null || client.player == null)
return;
UUID uuid = client.player.getUuid();