initial commit

This commit is contained in:
trunksbomb
2026-03-23 00:25:54 -04:00
commit 65a0574ce3
58 changed files with 2594 additions and 0 deletions

View File

@@ -0,0 +1,28 @@
package com.trunksbomb.minetriad;
import org.slf4j.Logger;
import com.mojang.logging.LogUtils;
import com.trunksbomb.minetriad.registry.TriadBlocks;
import com.trunksbomb.minetriad.registry.TriadBlockEntities;
import com.trunksbomb.minetriad.registry.TriadCreativeTabs;
import com.trunksbomb.minetriad.registry.TriadDataComponents;
import com.trunksbomb.minetriad.registry.TriadItems;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.fml.ModContainer;
import net.neoforged.fml.common.Mod;
@Mod(MineTriad.MOD_ID)
public final class MineTriad {
public static final String MOD_ID = "minetriad";
public static final Logger LOGGER = LogUtils.getLogger();
public MineTriad(IEventBus modEventBus, ModContainer modContainer) {
TriadDataComponents.register(modEventBus);
TriadBlocks.register(modEventBus);
TriadBlockEntities.register(modEventBus);
TriadItems.register(modEventBus);
TriadCreativeTabs.register(modEventBus);
}
}

View File

@@ -0,0 +1,26 @@
package com.trunksbomb.minetriad;
import com.trunksbomb.minetriad.client.render.DuelTableBlockEntityRenderer;
import com.trunksbomb.minetriad.registry.TriadBlockEntities;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderers;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.Mod;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.client.event.EntityRenderersEvent;
@Mod(value = MineTriad.MOD_ID, dist = Dist.CLIENT)
public final class MineTriadClient {
public MineTriadClient(IEventBus modEventBus) {
}
@EventBusSubscriber(modid = MineTriad.MOD_ID, value = Dist.CLIENT, bus = EventBusSubscriber.Bus.MOD)
public static final class ClientModEvents {
@SubscribeEvent
public static void registerRenderers(EntityRenderersEvent.RegisterRenderers event) {
event.registerBlockEntityRenderer(TriadBlockEntities.DUEL_TABLE.get(), DuelTableBlockEntityRenderer::new);
}
}
}

View File

@@ -0,0 +1,176 @@
package com.trunksbomb.minetriad.blockentity;
import java.util.Optional;
import java.util.UUID;
import com.trunksbomb.minetriad.registry.TriadBlockEntities;
import com.trunksbomb.minetriad.registry.TriadItems;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.NonNullList;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.Connection;
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
import net.minecraft.world.ContainerHelper;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
public class DuelTableBlockEntity extends BlockEntity {
public static final int SLOT_COUNT = 9;
public static final int OWNER_NONE = 0;
public static final int OWNER_FIRST = 1;
public static final int OWNER_SECOND = 2;
private final NonNullList<ItemStack> boardCards = NonNullList.withSize(SLOT_COUNT, ItemStack.EMPTY);
private final int[] ownerSlots = new int[SLOT_COUNT];
private UUID firstParticipantId;
private UUID secondParticipantId;
public DuelTableBlockEntity(BlockPos pos, BlockState blockState) {
super(TriadBlockEntities.DUEL_TABLE.get(), pos, blockState);
}
public ItemStack getCard(int slot) {
return boardCards.get(slot);
}
public int ownerAt(int slot) {
return ownerSlots[slot];
}
public Optional<UUID> firstParticipantId() {
return Optional.ofNullable(firstParticipantId);
}
public Optional<UUID> secondParticipantId() {
return Optional.ofNullable(secondParticipantId);
}
public void setParticipants(UUID firstParticipantId, UUID secondParticipantId) {
this.firstParticipantId = firstParticipantId;
this.secondParticipantId = secondParticipantId;
sync();
}
public boolean setCard(int slot, ItemStack stack, int owner) {
if (slot < 0 || slot >= boardCards.size() || !boardCards.get(slot).isEmpty() || !stack.is(TriadItems.TRIAD_CARD.get())) {
return false;
}
boardCards.set(slot, stack.copyWithCount(1));
ownerSlots[slot] = owner;
sync();
return true;
}
public void setOwner(int slot, int owner) {
if (slot < 0 || slot >= ownerSlots.length || boardCards.get(slot).isEmpty()) {
return;
}
ownerSlots[slot] = owner;
sync();
}
public void clearBoard() {
for (int index = 0; index < boardCards.size(); index++) {
boardCards.set(index, ItemStack.EMPTY);
ownerSlots[index] = OWNER_NONE;
}
firstParticipantId = null;
secondParticipantId = null;
sync();
}
public void dropBoardCards(Level level, BlockPos pos) {
for (int slot = 0; slot < boardCards.size(); slot++) {
ItemStack stack = boardCards.get(slot);
if (!stack.isEmpty()) {
Block.popResource(level, pos, stack);
boardCards.set(slot, ItemStack.EMPTY);
ownerSlots[slot] = OWNER_NONE;
}
}
firstParticipantId = null;
secondParticipantId = null;
sync();
}
@Override
protected void saveAdditional(CompoundTag tag, HolderLookup.Provider registries) {
super.saveAdditional(tag, registries);
ContainerHelper.saveAllItems(tag, boardCards, registries);
tag.putIntArray("OwnerSlots", ownerSlots);
if (firstParticipantId != null) {
tag.putUUID("FirstParticipantId", firstParticipantId);
}
if (secondParticipantId != null) {
tag.putUUID("SecondParticipantId", secondParticipantId);
}
}
@Override
protected void loadAdditional(CompoundTag tag, HolderLookup.Provider registries) {
super.loadAdditional(tag, registries);
clearBoardContents();
ContainerHelper.loadAllItems(tag, boardCards, registries);
loadOwnerData(tag);
}
@Override
public CompoundTag getUpdateTag(HolderLookup.Provider registries) {
CompoundTag tag = super.getUpdateTag(registries);
ContainerHelper.saveAllItems(tag, boardCards, registries);
tag.putIntArray("OwnerSlots", ownerSlots);
if (firstParticipantId != null) {
tag.putUUID("FirstParticipantId", firstParticipantId);
}
if (secondParticipantId != null) {
tag.putUUID("SecondParticipantId", secondParticipantId);
}
return tag;
}
@Override
public ClientboundBlockEntityDataPacket getUpdatePacket() {
return ClientboundBlockEntityDataPacket.create(this);
}
@Override
public void onDataPacket(Connection connection, ClientboundBlockEntityDataPacket packet, HolderLookup.Provider registries) {
CompoundTag tag = packet.getTag();
if (tag != null) {
clearBoardContents();
ContainerHelper.loadAllItems(tag, boardCards, registries);
loadOwnerData(tag);
}
}
private void clearBoardContents() {
for (int index = 0; index < boardCards.size(); index++) {
boardCards.set(index, ItemStack.EMPTY);
ownerSlots[index] = OWNER_NONE;
}
firstParticipantId = null;
secondParticipantId = null;
}
private void loadOwnerData(CompoundTag tag) {
int[] loadedOwners = tag.getIntArray("OwnerSlots");
for (int index = 0; index < ownerSlots.length; index++) {
ownerSlots[index] = index < loadedOwners.length ? loadedOwners[index] : OWNER_NONE;
}
firstParticipantId = tag.hasUUID("FirstParticipantId") ? tag.getUUID("FirstParticipantId") : null;
secondParticipantId = tag.hasUUID("SecondParticipantId") ? tag.getUUID("SecondParticipantId") : null;
}
private void sync() {
setChanged();
if (level != null) {
level.sendBlockUpdated(worldPosition, getBlockState(), getBlockState(), Block.UPDATE_ALL);
}
}
}

View File

@@ -0,0 +1,27 @@
package com.trunksbomb.minetriad.card;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
public record CardDefinition(
ResourceLocation id,
Component name,
int top,
int right,
int bottom,
int left,
Rarity rarity) {
public CardDefinition {
validateRank("top", top);
validateRank("right", right);
validateRank("bottom", bottom);
validateRank("left", left);
}
private static void validateRank(String side, int rank) {
if (rank < 1 || rank > 10) {
throw new IllegalArgumentException(side + " rank must be between 1 and 10");
}
}
}

View File

@@ -0,0 +1,50 @@
package com.trunksbomb.minetriad.card;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.trunksbomb.minetriad.MineTriad;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
public final class CardRegistry {
private static final List<CardDefinition> CARD_DEFINITIONS = List.of(
define("slime", "Slime", 3, 5, 2, 4, Rarity.COMMON),
define("zombie", "Zombie", 5, 4, 6, 3, Rarity.COMMON),
define("skeleton", "Skeleton", 6, 5, 3, 2, Rarity.COMMON),
define("creeper", "Creeper", 2, 7, 5, 6, Rarity.UNCOMMON),
define("enderman", "Enderman", 8, 4, 7, 5, Rarity.RARE),
define("warden", "Warden", 9, 8, 7, 6, Rarity.LEGENDARY));
private static final Map<ResourceLocation, CardDefinition> CARD_LOOKUP = CARD_DEFINITIONS.stream()
.collect(Collectors.toUnmodifiableMap(CardDefinition::id, Function.identity()));
private CardRegistry() {
}
public static List<CardDefinition> all() {
return CARD_DEFINITIONS;
}
public static CardDefinition get(ResourceLocation id) {
CardDefinition definition = CARD_LOOKUP.get(id);
if (definition == null) {
throw new IllegalArgumentException("Unknown card id: " + id);
}
return definition;
}
private static CardDefinition define(String path, String displayName, int top, int right, int bottom, int left, Rarity rarity) {
return new CardDefinition(
ResourceLocation.fromNamespaceAndPath(MineTriad.MOD_ID, path),
Component.literal(displayName),
top,
right,
bottom,
left,
rarity);
}
}

View File

@@ -0,0 +1,18 @@
package com.trunksbomb.minetriad.card;
import java.util.List;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.resources.ResourceLocation;
public record CardStackData(ResourceLocation cardId) {
public static final CardStackData EMPTY = new CardStackData(ResourceLocation.withDefaultNamespace("air"));
public static final com.mojang.serialization.Codec<CardStackData> CODEC = ResourceLocation.CODEC
.xmap(CardStackData::new, CardStackData::cardId);
public static final StreamCodec<io.netty.buffer.ByteBuf, CardStackData> STREAM_CODEC =
ResourceLocation.STREAM_CODEC.map(CardStackData::new, CardStackData::cardId);
public List<String> validationErrors() {
return cardId == null ? List.of("cardId must not be null") : List.of();
}
}

View File

@@ -0,0 +1,20 @@
package com.trunksbomb.minetriad.card;
import net.minecraft.ChatFormatting;
public enum Rarity {
COMMON(ChatFormatting.WHITE),
UNCOMMON(ChatFormatting.GREEN),
RARE(ChatFormatting.AQUA),
LEGENDARY(ChatFormatting.GOLD);
private final ChatFormatting formatting;
Rarity(ChatFormatting formatting) {
this.formatting = formatting;
}
public ChatFormatting formatting() {
return formatting;
}
}

View File

@@ -0,0 +1,61 @@
package com.trunksbomb.minetriad.client.render;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.math.Axis;
import com.trunksbomb.minetriad.blockentity.DuelTableBlockEntity;
import com.trunksbomb.minetriad.game.BoardCell;
import com.trunksbomb.minetriad.game.BoardLocalSpace;
import com.trunksbomb.minetriad.world.DuelTableBlock;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderer;
import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider;
import net.minecraft.world.item.ItemStack;
public class DuelTableBlockEntityRenderer implements BlockEntityRenderer<DuelTableBlockEntity> {
public DuelTableBlockEntityRenderer(BlockEntityRendererProvider.Context context) {
}
@Override
public void render(DuelTableBlockEntity blockEntity, float partialTick, PoseStack poseStack, MultiBufferSource buffer, int packedLight, int packedOverlay) {
for (int slot = 0; slot < DuelTableBlockEntity.SLOT_COUNT; slot++) {
ItemStack stack = blockEntity.getCard(slot);
if (stack.isEmpty()) {
continue;
}
BoardCell cell = new BoardCell(slot / BoardCell.SIZE, slot % BoardCell.SIZE);
BoardLocalSpace.SlotCenter center = BoardLocalSpace.slotCenter(cell, blockEntity.getBlockState().getValue(DuelTableBlock.FACING));
poseStack.pushPose();
poseStack.translate(center.x(), 1.066F, center.z());
poseStack.mulPose(Axis.YP.rotationDegrees(BoardLocalSpace.cardYawDegrees(blockEntity.getBlockState().getValue(DuelTableBlock.FACING))));
poseStack.mulPose(Axis.XN.rotationDegrees(90.0F));
poseStack.scale(0.24F, 0.24F, 0.24F);
TriadCardItemRenderer.renderCard(stack, poseStack, buffer, perspectivePalette(blockEntity, blockEntity.ownerAt(slot)));
poseStack.popPose();
}
}
private static TriadCardItemRenderer.CardPalette perspectivePalette(DuelTableBlockEntity blockEntity, int owner) {
if (owner == DuelTableBlockEntity.OWNER_NONE || Minecraft.getInstance().player == null) {
return new TriadCardItemRenderer.CardPalette(
new float[] {0.88F, 0.84F, 0.72F},
new float[] {0.20F, 0.22F, 0.28F});
}
var playerId = Minecraft.getInstance().player.getUUID();
boolean ownerIsLocal = owner == DuelTableBlockEntity.OWNER_FIRST
? blockEntity.firstParticipantId().map(playerId::equals).orElse(false)
: owner == DuelTableBlockEntity.OWNER_SECOND && blockEntity.secondParticipantId().map(playerId::equals).orElse(false);
return ownerIsLocal
? new TriadCardItemRenderer.CardPalette(
new float[] {0.24F, 0.38F, 0.95F},
new float[] {0.08F, 0.16F, 0.62F})
: new TriadCardItemRenderer.CardPalette(
new float[] {0.92F, 0.24F, 0.24F},
new float[] {0.56F, 0.10F, 0.10F});
}
}

View File

@@ -0,0 +1,107 @@
package com.trunksbomb.minetriad.client.render;
import com.mojang.blaze3d.vertex.PoseStack;
import com.trunksbomb.minetriad.card.CardDefinition;
import com.trunksbomb.minetriad.card.CardRegistry;
import com.trunksbomb.minetriad.card.CardStackData;
import com.trunksbomb.minetriad.registry.TriadDataComponents;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.model.geom.EntityModelSet;
import net.minecraft.client.renderer.BlockEntityWithoutLevelRenderer;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderDispatcher;
import net.minecraft.client.renderer.LevelRenderer;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack;
import net.minecraft.util.FormattedCharSequence;
public final class TriadCardItemRenderer extends BlockEntityWithoutLevelRenderer {
private static TriadCardItemRenderer INSTANCE;
private static final CardPalette NEUTRAL_PALETTE = new CardPalette(
new float[] {0.88F, 0.84F, 0.72F},
new float[] {0.20F, 0.22F, 0.28F});
private TriadCardItemRenderer(BlockEntityRenderDispatcher blockEntityRenderDispatcher, EntityModelSet entityModelSet) {
super(blockEntityRenderDispatcher, entityModelSet);
}
public static TriadCardItemRenderer getInstance() {
if (INSTANCE == null) {
Minecraft minecraft = Minecraft.getInstance();
INSTANCE = new TriadCardItemRenderer(minecraft.getBlockEntityRenderDispatcher(), minecraft.getEntityModels());
}
return INSTANCE;
}
@Override
public void renderByItem(ItemStack stack, ItemDisplayContext displayContext, PoseStack poseStack, MultiBufferSource buffer, int packedLight, int packedOverlay) {
renderCard(stack, poseStack, buffer, NEUTRAL_PALETTE);
}
public static void renderCard(ItemStack stack, PoseStack poseStack, MultiBufferSource buffer, CardPalette palette) {
CardStackData cardData = stack.get(TriadDataComponents.CARD_DATA);
CardDefinition card = cardData == null || cardData.equals(CardStackData.EMPTY) ? null : CardRegistry.get(cardData.cardId());
poseStack.pushPose();
LevelRenderer.addChainedFilledBoxVertices(
poseStack,
buffer.getBuffer(RenderType.debugFilledBox()),
-0.42F,
-0.42F,
-0.015F,
0.42F,
0.42F,
-0.009F,
palette.border()[0],
palette.border()[1],
palette.border()[2],
1.0F);
LevelRenderer.addChainedFilledBoxVertices(
poseStack,
buffer.getBuffer(RenderType.debugFilledBox()),
-0.32F,
-0.32F,
-0.026F,
0.32F,
0.32F,
-0.016F,
palette.face()[0],
palette.face()[1],
palette.face()[2],
1.0F);
if (card != null) {
Font font = Minecraft.getInstance().font;
drawValue(poseStack, buffer, font, Integer.toString(card.top()), 0.0F, 0.13F);
drawValue(poseStack, buffer, font, Integer.toString(card.bottom()), 0.0F, -0.23F);
drawValue(poseStack, buffer, font, Integer.toString(card.left()), -0.16F, -0.04F);
drawValue(poseStack, buffer, font, Integer.toString(card.right()), 0.16F, -0.04F);
}
poseStack.popPose();
}
private static void drawValue(PoseStack poseStack, MultiBufferSource buffer, Font font, String value, float x, float y) {
poseStack.pushPose();
poseStack.translate(x, y, 0.03F);
poseStack.scale(0.03F, -0.03F, 0.03F);
float width = font.width(value);
FormattedCharSequence sequence = FormattedCharSequence.forward(value, net.minecraft.network.chat.Style.EMPTY);
font.drawInBatch8xOutline(
sequence,
-width / 2.0F,
0.0F,
0xFFFFFFFF,
0xFF101010,
poseStack.last().pose(),
buffer,
LightTexture.FULL_BRIGHT);
poseStack.popPose();
}
public record CardPalette(float[] border, float[] face) {
}
}

View File

@@ -0,0 +1,15 @@
package com.trunksbomb.minetriad.game;
public record BoardCell(int row, int column) {
public static final int SIZE = 3;
public BoardCell {
if (row < 0 || row >= SIZE || column < 0 || column >= SIZE) {
throw new IllegalArgumentException("Board cells must fit within a 3x3 board");
}
}
public int index() {
return row * SIZE + column;
}
}

View File

@@ -0,0 +1,69 @@
package com.trunksbomb.minetriad.game;
import net.minecraft.core.Direction;
import net.minecraft.world.phys.BlockHitResult;
public final class BoardLocalSpace {
private BoardLocalSpace() {
}
public static BoardCell cellForHit(BlockHitResult hitResult, Direction boardFacing) {
double localX = hitResult.getLocation().x - hitResult.getBlockPos().getX();
double localZ = hitResult.getLocation().z - hitResult.getBlockPos().getZ();
double rowProgress = projectProgress(localX, localZ, boardFacing);
double columnProgress = projectProgress(localX, localZ, rightDirection(boardFacing));
return new BoardCell(progressToIndex(rowProgress), progressToIndex(columnProgress));
}
public static SlotCenter slotCenter(BoardCell cell, Direction boardFacing) {
float rowProgress = (cell.row() + 0.5F) / BoardCell.SIZE;
float columnProgress = (cell.column() + 0.5F) / BoardCell.SIZE;
HorizontalVector bottomVector = vectorFor(boardFacing);
HorizontalVector rightVector = vectorFor(rightDirection(boardFacing));
float x = 0.5F + bottomVector.x() * (rowProgress - 0.5F) + rightVector.x() * (columnProgress - 0.5F);
float z = 0.5F + bottomVector.z() * (rowProgress - 0.5F) + rightVector.z() * (columnProgress - 0.5F);
return new SlotCenter(x, z);
}
public static float cardYawDegrees(Direction boardFacing) {
Direction topDirection = boardFacing.getOpposite();
return switch (topDirection) {
case SOUTH -> 180.0F;
case NORTH -> 0.0F;
case EAST -> -90.0F;
case WEST -> 90.0F;
default -> 0.0F;
};
}
private static double projectProgress(double localX, double localZ, Direction direction) {
HorizontalVector vector = vectorFor(direction);
double offsetX = localX - 0.5D;
double offsetZ = localZ - 0.5D;
return 0.5D + (offsetX * vector.x()) + (offsetZ * vector.z());
}
private static int progressToIndex(double progress) {
return Math.min(BoardCell.SIZE - 1, Math.max(0, (int) Math.floor(progress * BoardCell.SIZE)));
}
private static Direction rightDirection(Direction boardFacing) {
return boardFacing.getOpposite().getClockWise();
}
private static HorizontalVector vectorFor(Direction direction) {
return switch (direction) {
case NORTH -> new HorizontalVector(0.0F, -1.0F);
case SOUTH -> new HorizontalVector(0.0F, 1.0F);
case EAST -> new HorizontalVector(1.0F, 0.0F);
case WEST -> new HorizontalVector(-1.0F, 0.0F);
default -> throw new IllegalArgumentException("Only horizontal facings are supported");
};
}
private record HorizontalVector(float x, float z) {
}
public record SlotCenter(float x, float z) {
}
}

View File

@@ -0,0 +1,33 @@
package com.trunksbomb.minetriad.game;
public enum CardSide {
TOP(-1, 0),
RIGHT(0, 1),
BOTTOM(1, 0),
LEFT(0, -1);
private final int rowOffset;
private final int columnOffset;
CardSide(int rowOffset, int columnOffset) {
this.rowOffset = rowOffset;
this.columnOffset = columnOffset;
}
public int rowOffset() {
return rowOffset;
}
public int columnOffset() {
return columnOffset;
}
public CardSide opposite() {
return switch (this) {
case TOP -> BOTTOM;
case RIGHT -> LEFT;
case BOTTOM -> TOP;
case LEFT -> RIGHT;
};
}
}

View File

@@ -0,0 +1,248 @@
package com.trunksbomb.minetriad.game;
import java.util.Comparator;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import com.trunksbomb.minetriad.card.CardRegistry;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.core.BlockPos;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.phys.BlockHitResult;
public final class DuelSession {
private enum Phase {
PLAYING,
OVERVIEW
}
private final MatchParticipant playerParticipant;
private final MatchParticipant opponentParticipant;
private final TriadMatch match;
private final List<ResourceLocation> refundablePlayerCards;
private final boolean refundCardsOnEnd;
private final BlockPos tablePos;
private Phase phase;
public DuelSession(
UUID playerId,
String playerName,
List<GameCard> playerHand,
List<GameCard> opponentHand,
List<ResourceLocation> refundablePlayerCards,
boolean refundCardsOnEnd,
BlockPos tablePos) {
this.playerParticipant = new MatchParticipant(playerId, playerName);
this.opponentParticipant = new MatchParticipant(UUID.nameUUIDFromBytes(("opponent:" + playerId).getBytes()), "Training Duelist");
this.match = new TriadMatch(playerParticipant, opponentParticipant, playerHand, opponentHand, TriadRuleSet.CLASSIC_OPEN);
this.refundablePlayerCards = List.copyOf(refundablePlayerCards);
this.refundCardsOnEnd = refundCardsOnEnd;
this.tablePos = tablePos.immutable();
this.phase = Phase.PLAYING;
}
public Component startMessage() {
return Component.literal("Duel started against Training Duelist. Right-click a space on the table with a card from your hotbar to play.");
}
public boolean isPlayerTurn() {
return match.activeParticipant().equals(playerParticipant);
}
public boolean isComplete() {
return match.isComplete();
}
public boolean isInOverview() {
return phase == Phase.OVERVIEW;
}
public void enterOverview() {
phase = Phase.OVERVIEW;
}
public Component handSummary() {
MutableComponent component = Component.literal("Your hand: ");
List<GameCard> hand = match.handFor(playerParticipant);
for (int index = 0; index < hand.size(); index++) {
if (index > 0) {
component.append(Component.literal(", "));
}
component.append(hand.get(index).definition().name());
}
return component;
}
public MoveResult playPlayerCard(ResourceLocation cardId, BlockHitResult hitResult, boolean allowFallbackSelection, net.minecraft.core.Direction tableFacing) {
int handIndex = findHandIndex(cardId);
if (handIndex < 0 && allowFallbackSelection && !match.handFor(playerParticipant).isEmpty()) {
handIndex = 0;
}
if (handIndex < 0) {
return MoveResult.failure("That selected card is not in your current duel hand");
}
BoardCell targetCell = BoardLocalSpace.cellForHit(hitResult, tableFacing);
return match.play(new TriadMove(playerParticipant, handIndex, targetCell));
}
public BoardCell targetCell(BlockHitResult hitResult, net.minecraft.core.Direction tableFacing) {
return BoardLocalSpace.cellForHit(hitResult, tableFacing);
}
public MoveResult playOpponentTurn() {
int bestHandIndex = -1;
BoardCell bestCell = null;
int bestCaptures = -1;
List<GameCard> opponentHand = match.handFor(opponentParticipant);
for (int handIndex = 0; handIndex < opponentHand.size(); handIndex++) {
for (BoardCell cell : openCells()) {
TriadMatch probe = duplicateMatch();
MoveResult result = probe.play(new TriadMove(opponentParticipant, handIndex, cell));
if (!result.valid()) {
continue;
}
int captures = result.capturedCells().size();
if (captures > bestCaptures) {
bestCaptures = captures;
bestHandIndex = handIndex;
bestCell = cell;
}
}
}
if (bestHandIndex < 0 || bestCell == null) {
return MoveResult.failure("Opponent could not find a legal move");
}
return match.play(new TriadMove(opponentParticipant, bestHandIndex, bestCell));
}
public Component boardSummary() {
MutableComponent component = Component.literal("Board: ");
for (int row = 0; row < BoardCell.SIZE; row++) {
if (row > 0) {
component.append(Component.literal(" / "));
}
for (int column = 0; column < BoardCell.SIZE; column++) {
if (column > 0) {
component.append(Component.literal(" "));
}
PlacedCard placedCard = match.cardAt(new BoardCell(row, column));
if (placedCard == null) {
component.append(Component.literal("[ ]"));
} else {
String ownerInitial = placedCard.owner().equals(playerParticipant) ? "P" : "O";
String cardInitial = placedCard.card().definition().name().getString().substring(0, 1).toUpperCase();
component.append(Component.literal("[" + ownerInitial + cardInitial + "]"));
}
}
}
return component;
}
public Component resultSummary() {
int playerScore = match.scoreFor(playerParticipant);
int opponentScore = match.scoreFor(opponentParticipant);
if (playerScore > opponentScore) {
return Component.literal("Duel complete. You win " + playerScore + " to " + opponentScore + ".");
}
if (opponentScore > playerScore) {
return Component.literal("Duel complete. Training Duelist wins " + opponentScore + " to " + playerScore + ".");
}
return Component.literal("Duel complete. The match ends in a draw at " + playerScore + " to " + opponentScore + ".");
}
public Component overviewMessage() {
return Component.literal("Duel overview. Right-click the table to finish and return cards.");
}
public List<ResourceLocation> refundablePlayerCards() {
return refundablePlayerCards;
}
public List<ResourceLocation> playedPlayerCards() {
Map<ResourceLocation, Integer> remainingCounts = new HashMap<>();
for (ResourceLocation cardId : remainingPlayerCards()) {
remainingCounts.merge(cardId, 1, Integer::sum);
}
List<ResourceLocation> playedCards = new ArrayList<>();
for (ResourceLocation cardId : refundablePlayerCards) {
int remaining = remainingCounts.getOrDefault(cardId, 0);
if (remaining > 0) {
remainingCounts.put(cardId, remaining - 1);
} else {
playedCards.add(cardId);
}
}
return playedCards;
}
public List<ResourceLocation> remainingPlayerCards() {
return match.handFor(playerParticipant).stream()
.map(card -> card.definition().id())
.toList();
}
public boolean refundCardsOnEnd() {
return refundCardsOnEnd;
}
public boolean isAtTable(BlockPos blockPos) {
return tablePos.equals(blockPos);
}
public UUID playerParticipantId() {
return playerParticipant.id();
}
public UUID opponentParticipantId() {
return opponentParticipant.id();
}
private int findHandIndex(ResourceLocation cardId) {
List<GameCard> hand = match.handFor(playerParticipant);
for (int index = 0; index < hand.size(); index++) {
if (hand.get(index).definition().id().equals(cardId)) {
return index;
}
}
return -1;
}
private List<BoardCell> openCells() {
return java.util.stream.IntStream.range(0, BoardCell.SIZE * BoardCell.SIZE)
.mapToObj(index -> new BoardCell(index / BoardCell.SIZE, index % BoardCell.SIZE))
.filter(cell -> match.cardAt(cell) == null)
.toList();
}
private TriadMatch duplicateMatch() {
TriadMatch duplicate = new TriadMatch(
playerParticipant,
opponentParticipant,
match.handFor(playerParticipant),
match.handFor(opponentParticipant),
match.ruleSet());
for (int row = 0; row < BoardCell.SIZE; row++) {
for (int column = 0; column < BoardCell.SIZE; column++) {
BoardCell cell = new BoardCell(row, column);
PlacedCard placedCard = match.cardAt(cell);
if (placedCard != null) {
duplicate.forcePlace(cell, placedCard);
}
}
}
duplicate.forceActiveParticipant(match.activeParticipant());
return duplicate;
}
}

View File

@@ -0,0 +1,112 @@
package com.trunksbomb.minetriad.game;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import com.trunksbomb.minetriad.card.CardRegistry;
import com.trunksbomb.minetriad.card.CardDefinition;
import com.trunksbomb.minetriad.card.CardStackData;
import com.trunksbomb.minetriad.item.CardItem;
import com.trunksbomb.minetriad.registry.TriadDataComponents;
import com.trunksbomb.minetriad.registry.TriadItems;
import net.minecraft.core.BlockPos;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
public final class DuelSessionManager {
private static final Map<UUID, DuelSession> ACTIVE_DUELS = new ConcurrentHashMap<>();
private DuelSessionManager() {
}
public static DuelSession get(Player player) {
return ACTIVE_DUELS.get(player.getUUID());
}
public static DuelSession start(Player player, BlockPos tablePos) {
List<GameCard> playerHand = buildPlayerHand(player.getInventory());
if (playerHand.size() < 5) {
throw new IllegalStateException("A duel requires 5 Triad Cards in your inventory");
}
List<ResourceLocation> refundableCards = playerHand.stream()
.map(card -> card.definition().id())
.toList();
DuelSession session = new DuelSession(
player.getUUID(),
player.getName().getString(),
playerHand,
buildOpponentHand(),
refundableCards,
!player.getAbilities().instabuild,
tablePos);
ACTIVE_DUELS.put(player.getUUID(), session);
return session;
}
public static void end(Player player, boolean refundCards) {
DuelSession session = ACTIVE_DUELS.remove(player.getUUID());
if (session == null || !refundCards || !session.refundCardsOnEnd()) {
return;
}
for (ResourceLocation cardId : session.playedPlayerCards()) {
player.addItem(CardItem.createCardStack(cardId, TriadItems.TRIAD_CARD.get()));
}
}
public static boolean refundRemainingIfActiveAt(Player player, BlockPos tablePos) {
DuelSession session = ACTIVE_DUELS.remove(player.getUUID());
if (session == null || !session.isAtTable(tablePos) || !session.refundCardsOnEnd()) {
if (session != null && !session.isAtTable(tablePos)) {
ACTIVE_DUELS.put(player.getUUID(), session);
}
return false;
}
for (ResourceLocation cardId : session.remainingPlayerCards()) {
player.addItem(CardItem.createCardStack(cardId, TriadItems.TRIAD_CARD.get()));
}
return true;
}
public static boolean hasActiveAt(BlockPos tablePos) {
return ACTIVE_DUELS.values().stream().anyMatch(session -> session.isAtTable(tablePos));
}
public static List<ResourceLocation> endAndCollectRemainingAt(BlockPos tablePos) {
for (Map.Entry<UUID, DuelSession> entry : ACTIVE_DUELS.entrySet()) {
DuelSession session = entry.getValue();
if (session.isAtTable(tablePos)) {
ACTIVE_DUELS.remove(entry.getKey());
return session.remainingPlayerCards();
}
}
return List.of();
}
private static List<GameCard> buildPlayerHand(Inventory inventory) {
return inventory.items.stream()
.filter(stack -> stack.is(TriadItems.TRIAD_CARD.get()))
.map(stack -> stack.get(TriadDataComponents.CARD_DATA))
.filter(data -> data != null && !CardStackData.EMPTY.equals(data))
.map(CardStackData::cardId)
.limit(5)
.map(cardId -> new GameCard(CardRegistry.get(cardId)))
.toList();
}
private static List<GameCard> buildOpponentHand() {
return CardRegistry.all().stream()
.sorted(Comparator.comparingInt((CardDefinition card) -> card.top() + card.right() + card.bottom() + card.left()).reversed())
.limit(5)
.map(GameCard::new)
.toList();
}
}

View File

@@ -0,0 +1,14 @@
package com.trunksbomb.minetriad.game;
import com.trunksbomb.minetriad.card.CardDefinition;
public record GameCard(CardDefinition definition) {
public int value(CardSide side) {
return switch (side) {
case TOP -> definition.top();
case RIGHT -> definition.right();
case BOTTOM -> definition.bottom();
case LEFT -> definition.left();
};
}
}

View File

@@ -0,0 +1,6 @@
package com.trunksbomb.minetriad.game;
import java.util.UUID;
public record MatchParticipant(UUID id, String name) {
}

View File

@@ -0,0 +1,27 @@
package com.trunksbomb.minetriad.game;
import java.util.List;
import net.minecraft.resources.ResourceLocation;
public record MoveResult(
boolean valid,
String errorMessage,
List<BoardCell> capturedCells,
List<String> battleLog,
String playedCardName,
ResourceLocation playedCardId,
BoardCell playedCell) {
public static MoveResult success(
List<BoardCell> capturedCells,
List<String> battleLog,
String playedCardName,
ResourceLocation playedCardId,
BoardCell playedCell) {
return new MoveResult(true, "", List.copyOf(capturedCells), List.copyOf(battleLog), playedCardName, playedCardId, playedCell);
}
public static MoveResult failure(String errorMessage) {
return new MoveResult(false, errorMessage, List.of(), List.of(), "", null, null);
}
}

View File

@@ -0,0 +1,4 @@
package com.trunksbomb.minetriad.game;
public record PlacedCard(MatchParticipant owner, GameCard card) {
}

View File

@@ -0,0 +1,170 @@
package com.trunksbomb.minetriad.game;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public final class TriadMatch {
private final MatchParticipant firstParticipant;
private final MatchParticipant secondParticipant;
private final TriadRuleSet ruleSet;
private final List<GameCard> firstHand;
private final List<GameCard> secondHand;
private final PlacedCard[] board;
private MatchParticipant activeParticipant;
public TriadMatch(
MatchParticipant firstParticipant,
MatchParticipant secondParticipant,
List<GameCard> firstHand,
List<GameCard> secondHand,
TriadRuleSet ruleSet) {
this.firstParticipant = firstParticipant;
this.secondParticipant = secondParticipant;
this.ruleSet = ruleSet;
this.firstHand = validateHand(firstHand);
this.secondHand = validateHand(secondHand);
this.board = new PlacedCard[BoardCell.SIZE * BoardCell.SIZE];
this.activeParticipant = firstParticipant;
}
public MatchParticipant activeParticipant() {
return activeParticipant;
}
public boolean isComplete() {
return Arrays.stream(board).noneMatch(card -> card == null);
}
public int scoreFor(MatchParticipant participant) {
int boardScore = (int) Arrays.stream(board)
.filter(card -> card != null && card.owner().equals(participant))
.count();
int handScore = handFor(participant).size();
return boardScore + handScore;
}
public List<GameCard> handFor(MatchParticipant participant) {
if (participant.equals(firstParticipant)) {
return List.copyOf(firstHand);
}
if (participant.equals(secondParticipant)) {
return List.copyOf(secondHand);
}
throw new IllegalArgumentException("Participant is not part of this match");
}
public PlacedCard cardAt(BoardCell cell) {
return board[cell.index()];
}
public MoveResult play(TriadMove move) {
if (!activeParticipant.equals(move.participant())) {
return MoveResult.failure("It is not that participant's turn");
}
if (cardAt(move.targetCell()) != null) {
return MoveResult.failure("That board cell is already occupied");
}
List<GameCard> hand = mutableHandFor(move.participant());
if (move.handIndex() < 0 || move.handIndex() >= hand.size()) {
return MoveResult.failure("Hand index is out of bounds");
}
GameCard playedCard = hand.remove(move.handIndex());
board[move.targetCell().index()] = new PlacedCard(move.participant(), playedCard);
List<String> battleLog = new ArrayList<>();
List<BoardCell> capturedCells = resolveCaptures(move.targetCell(), move.participant(), playedCard, battleLog);
activeParticipant = otherParticipant(move.participant());
return MoveResult.success(capturedCells, battleLog, playedCard.definition().name().getString(), playedCard.definition().id(), move.targetCell());
}
private List<BoardCell> resolveCaptures(BoardCell origin, MatchParticipant owner, GameCard playedCard, List<String> battleLog) {
List<BoardCell> captured = new ArrayList<>();
for (CardSide side : CardSide.values()) {
BoardCell neighborCell = neighbor(origin, side);
if (neighborCell == null) {
continue;
}
PlacedCard neighbor = cardAt(neighborCell);
if (neighbor == null || neighbor.owner().equals(owner)) {
continue;
}
int attackValue = playedCard.value(side);
int defendValue = neighbor.card().value(side.opposite());
boolean capturedNeighbor = attackValue > defendValue;
battleLog.add(String.format(
"%s %s=%d vs %s %s=%d at [%d,%d] -> %s",
playedCard.definition().name().getString(),
side.name(),
attackValue,
neighbor.card().definition().name().getString(),
side.opposite().name(),
defendValue,
neighborCell.row(),
neighborCell.column(),
capturedNeighbor ? "flip" : "hold"));
if (capturedNeighbor) {
board[neighborCell.index()] = new PlacedCard(owner, neighbor.card());
captured.add(neighborCell);
}
}
return captured;
}
private BoardCell neighbor(BoardCell cell, CardSide side) {
int row = cell.row() + side.rowOffset();
int column = cell.column() + side.columnOffset();
if (row < 0 || row >= BoardCell.SIZE || column < 0 || column >= BoardCell.SIZE) {
return null;
}
return new BoardCell(row, column);
}
private List<GameCard> mutableHandFor(MatchParticipant participant) {
if (participant.equals(firstParticipant)) {
return firstHand;
}
if (participant.equals(secondParticipant)) {
return secondHand;
}
throw new IllegalArgumentException("Participant is not part of this match");
}
private MatchParticipant otherParticipant(MatchParticipant participant) {
if (participant.equals(firstParticipant)) {
return secondParticipant;
}
if (participant.equals(secondParticipant)) {
return firstParticipant;
}
throw new IllegalArgumentException("Participant is not part of this match");
}
private static List<GameCard> validateHand(List<GameCard> hand) {
if (hand.isEmpty()) {
return new ArrayList<>();
}
if (hand.size() > 5) {
throw new IllegalArgumentException("Triple Triad hands cannot contain more than 5 cards");
}
return new ArrayList<>(hand);
}
public TriadRuleSet ruleSet() {
return ruleSet;
}
void forcePlace(BoardCell cell, PlacedCard placedCard) {
board[cell.index()] = placedCard;
}
void forceActiveParticipant(MatchParticipant participant) {
this.activeParticipant = participant;
}
}

View File

@@ -0,0 +1,4 @@
package com.trunksbomb.minetriad.game;
public record TriadMove(MatchParticipant participant, int handIndex, BoardCell targetCell) {
}

View File

@@ -0,0 +1,9 @@
package com.trunksbomb.minetriad.game;
public record TriadRuleSet(
boolean openHands,
boolean sameRule,
boolean plusRule,
boolean elementalRule) {
public static final TriadRuleSet CLASSIC_OPEN = new TriadRuleSet(true, false, false, false);
}

View File

@@ -0,0 +1,65 @@
package com.trunksbomb.minetriad.item;
import java.util.List;
import java.util.function.Consumer;
import com.trunksbomb.minetriad.card.CardDefinition;
import com.trunksbomb.minetriad.card.CardRegistry;
import com.trunksbomb.minetriad.card.CardStackData;
import com.trunksbomb.minetriad.client.render.TriadCardItemRenderer;
import com.trunksbomb.minetriad.registry.TriadDataComponents;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.neoforged.neoforge.client.extensions.common.IClientItemExtensions;
public class CardItem extends Item {
public CardItem(Properties properties) {
super(properties);
}
@Override
public Component getName(ItemStack stack) {
CardStackData cardData = stack.get(TriadDataComponents.CARD_DATA);
if (cardData == null || cardData.equals(CardStackData.EMPTY)) {
return super.getName(stack);
}
CardDefinition card = CardRegistry.get(cardData.cardId());
return card.name().copy().withStyle(card.rarity().formatting());
}
@Override
public void appendHoverText(ItemStack stack, TooltipContext context, List<Component> tooltipComponents, TooltipFlag tooltipFlag) {
CardStackData cardData = stack.get(TriadDataComponents.CARD_DATA);
if (cardData == null || cardData.equals(CardStackData.EMPTY)) {
tooltipComponents.add(Component.literal("Unassigned card").withStyle(ChatFormatting.GRAY));
return;
}
CardDefinition card = CardRegistry.get(cardData.cardId());
tooltipComponents.add(Component.literal("Top " + card.top() + " Right " + card.right()).withStyle(ChatFormatting.GRAY));
tooltipComponents.add(Component.literal("Bottom " + card.bottom() + " Left " + card.left()).withStyle(ChatFormatting.GRAY));
tooltipComponents.add(Component.literal(card.rarity().name()).withStyle(card.rarity().formatting()));
}
@Override
public void initializeClient(Consumer<IClientItemExtensions> consumer) {
consumer.accept(new IClientItemExtensions() {
@Override
public net.minecraft.client.renderer.BlockEntityWithoutLevelRenderer getCustomRenderer() {
return TriadCardItemRenderer.getInstance();
}
});
}
public static ItemStack createCardStack(ResourceLocation cardId, Item item) {
ItemStack stack = new ItemStack(item);
stack.set(TriadDataComponents.CARD_DATA, new CardStackData(cardId));
return stack;
}
}

View File

@@ -0,0 +1,9 @@
package com.trunksbomb.minetriad.item;
import net.minecraft.world.item.Item;
public class DeckBoxItem extends Item {
public DeckBoxItem(Properties properties) {
super(properties);
}
}

View File

@@ -0,0 +1,25 @@
package com.trunksbomb.minetriad.registry;
import com.trunksbomb.minetriad.MineTriad;
import com.trunksbomb.minetriad.blockentity.DuelTableBlockEntity;
import net.minecraft.core.registries.Registries;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.neoforge.registries.DeferredHolder;
import net.neoforged.neoforge.registries.DeferredRegister;
public final class TriadBlockEntities {
private static final DeferredRegister<BlockEntityType<?>> BLOCK_ENTITY_TYPES = DeferredRegister.create(Registries.BLOCK_ENTITY_TYPE, MineTriad.MOD_ID);
public static final DeferredHolder<BlockEntityType<?>, BlockEntityType<DuelTableBlockEntity>> DUEL_TABLE = BLOCK_ENTITY_TYPES.register(
"duel_table",
() -> BlockEntityType.Builder.of(DuelTableBlockEntity::new, TriadBlocks.DUEL_TABLE.get()).build(null));
private TriadBlockEntities() {
}
public static void register(IEventBus eventBus) {
BLOCK_ENTITY_TYPES.register(eventBus);
}
}

View File

@@ -0,0 +1,30 @@
package com.trunksbomb.minetriad.registry;
import com.trunksbomb.minetriad.MineTriad;
import com.trunksbomb.minetriad.world.DuelTableBlock;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.SoundType;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.material.MapColor;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.neoforge.registries.DeferredBlock;
import net.neoforged.neoforge.registries.DeferredRegister;
public final class TriadBlocks {
public static final DeferredRegister.Blocks BLOCKS = DeferredRegister.createBlocks(MineTriad.MOD_ID);
public static final DeferredBlock<Block> DUEL_TABLE = BLOCKS.register(
"duel_table",
registryName -> new DuelTableBlock(BlockBehaviour.Properties.of()
.mapColor(MapColor.WOOD)
.strength(2.5F)
.sound(SoundType.WOOD)));
private TriadBlocks() {
}
public static void register(IEventBus eventBus) {
BLOCKS.register(eventBus);
}
}

View File

@@ -0,0 +1,41 @@
package com.trunksbomb.minetriad.registry;
import com.trunksbomb.minetriad.MineTriad;
import com.trunksbomb.minetriad.card.CardRegistry;
import com.trunksbomb.minetriad.item.CardItem;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.world.item.CreativeModeTab;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.neoforge.registries.DeferredHolder;
import net.neoforged.neoforge.registries.DeferredRegister;
public final class TriadCreativeTabs {
private static final DeferredRegister<CreativeModeTab> TABS = DeferredRegister.create(Registries.CREATIVE_MODE_TAB, MineTriad.MOD_ID);
public static final DeferredHolder<CreativeModeTab, CreativeModeTab> CARDS = TABS.register("cards", () -> CreativeModeTab.builder()
.title(Component.translatable("itemGroup.minetriad.cards"))
.icon(() -> CardItem.createCardStack(CardRegistry.all().getFirst().id(), TriadItems.TRIAD_CARD.get()))
.displayItems((parameters, output) -> {
CardRegistry.all().forEach(card -> output.accept(CardItem.createCardStack(card.id(), TriadItems.TRIAD_CARD.get())));
})
.build());
public static final DeferredHolder<CreativeModeTab, CreativeModeTab> GAMEPLAY = TABS.register("gameplay", () -> CreativeModeTab.builder()
.title(Component.translatable("itemGroup.minetriad.gameplay"))
.icon(() -> TriadBlocks.DUEL_TABLE.toStack())
.displayItems((parameters, output) -> {
output.accept(TriadItems.DECK_BOX.get());
output.accept(TriadItems.CARD_BINDER.get());
output.accept(TriadBlocks.DUEL_TABLE.toStack());
})
.build());
private TriadCreativeTabs() {
}
public static void register(IEventBus eventBus) {
TABS.register(eventBus);
}
}

View File

@@ -0,0 +1,24 @@
package com.trunksbomb.minetriad.registry;
import com.trunksbomb.minetriad.MineTriad;
import com.trunksbomb.minetriad.card.CardStackData;
import net.minecraft.core.component.DataComponentType;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.neoforge.registries.DeferredHolder;
import net.neoforged.neoforge.registries.DeferredRegister;
public final class TriadDataComponents {
private static final DeferredRegister.DataComponents COMPONENTS = DeferredRegister.createDataComponents(MineTriad.MOD_ID);
public static final DeferredHolder<DataComponentType<?>, DataComponentType<CardStackData>> CARD_DATA = COMPONENTS.registerComponentType(
"card_data",
builder -> builder.persistent(CardStackData.CODEC).networkSynchronized(CardStackData.STREAM_CODEC));
private TriadDataComponents() {
}
public static void register(IEventBus eventBus) {
COMPONENTS.register(eventBus);
}
}

View File

@@ -0,0 +1,29 @@
package com.trunksbomb.minetriad.registry;
import com.trunksbomb.minetriad.MineTriad;
import com.trunksbomb.minetriad.item.CardItem;
import com.trunksbomb.minetriad.item.DeckBoxItem;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.Item;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.neoforge.registries.DeferredItem;
import net.neoforged.neoforge.registries.DeferredRegister;
public final class TriadItems {
private static final Item.Properties DEFAULT_PROPERTIES = new Item.Properties();
public static final DeferredRegister.Items ITEMS = DeferredRegister.createItems(MineTriad.MOD_ID);
public static final DeferredItem<Item> TRIAD_CARD = ITEMS.register("triad_card", () -> new CardItem(DEFAULT_PROPERTIES.stacksTo(1)));
public static final DeferredItem<Item> DECK_BOX = ITEMS.register("deck_box", () -> new DeckBoxItem(DEFAULT_PROPERTIES.stacksTo(1)));
public static final DeferredItem<Item> CARD_BINDER = ITEMS.registerSimpleItem("card_binder", DEFAULT_PROPERTIES.stacksTo(1));
public static final DeferredItem<BlockItem> DUEL_TABLE = ITEMS.registerSimpleBlockItem("duel_table", TriadBlocks.DUEL_TABLE);
private TriadItems() {
}
public static void register(IEventBus eventBus) {
ITEMS.register(eventBus);
}
}

View File

@@ -0,0 +1,271 @@
package com.trunksbomb.minetriad.world;
import com.mojang.serialization.MapCodec;
import com.trunksbomb.minetriad.MineTriad;
import com.trunksbomb.minetriad.blockentity.DuelTableBlockEntity;
import com.trunksbomb.minetriad.card.CardStackData;
import com.trunksbomb.minetriad.game.DuelSession;
import com.trunksbomb.minetriad.game.DuelSessionManager;
import com.trunksbomb.minetriad.game.MoveResult;
import com.trunksbomb.minetriad.item.CardItem;
import com.trunksbomb.minetriad.registry.TriadItems;
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.network.chat.Component;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.ItemInteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.BaseEntityBlock;
import net.minecraft.world.level.block.HorizontalDirectionalBlock;
import net.minecraft.world.level.block.RenderShape;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.DirectionProperty;
import net.minecraft.world.phys.BlockHitResult;
public class DuelTableBlock extends BaseEntityBlock {
public static final MapCodec<DuelTableBlock> CODEC = simpleCodec(DuelTableBlock::new);
public static final DirectionProperty FACING = BlockStateProperties.HORIZONTAL_FACING;
public DuelTableBlock(Properties properties) {
super(properties);
registerDefaultState(stateDefinition.any().setValue(FACING, Direction.SOUTH));
}
@Override
protected MapCodec<? extends BaseEntityBlock> codec() {
return CODEC;
}
@Override
protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) {
if (level.isClientSide) {
return ItemInteractionResult.SUCCESS;
}
try {
if (hitResult.getDirection() != Direction.UP) {
player.displayClientMessage(Component.literal("Click the top face of the Duel Table to target a board space.").withStyle(ChatFormatting.YELLOW), false);
return ItemInteractionResult.CONSUME;
}
Direction tableFacing = state.getValue(FACING);
DuelTableBlockEntity table = getTableEntity(level, pos);
if (table == null) {
player.displayClientMessage(Component.literal("Duel table storage is unavailable.").withStyle(ChatFormatting.RED), false);
return ItemInteractionResult.CONSUME;
}
DuelSession session = DuelSessionManager.get(player);
if (session == null) {
try {
session = DuelSessionManager.start(player, pos);
} catch (IllegalStateException exception) {
player.displayClientMessage(Component.literal("You need 5 Triad Cards in your inventory to start a duel.").withStyle(ChatFormatting.YELLOW), false);
return ItemInteractionResult.CONSUME;
}
table.clearBoard();
table.setParticipants(session.playerParticipantId(), session.opponentParticipantId());
player.displayClientMessage(session.startMessage().copy().withStyle(ChatFormatting.GOLD), false);
player.displayClientMessage(session.handSummary(), false);
return ItemInteractionResult.CONSUME;
}
if (session.isInOverview()) {
completeOverview(level, pos, player, session);
return ItemInteractionResult.CONSUME;
}
if (!session.isPlayerTurn()) {
MoveResult opponentMove = session.playOpponentTurn();
if (!opponentMove.valid()) {
player.displayClientMessage(Component.literal(opponentMove.errorMessage()).withStyle(ChatFormatting.RED), false);
clearAndRefund(level, pos, player, true);
return ItemInteractionResult.CONSUME;
}
placeBoardCard(table, opponentMove, DuelTableBlockEntity.OWNER_SECOND);
applyCapturedOwnership(table, opponentMove, DuelTableBlockEntity.OWNER_SECOND);
player.displayClientMessage(Component.literal("Training Duelist takes a turn."), false);
sendBattleLog(player, opponentMove, ChatFormatting.GRAY);
player.displayClientMessage(session.boardSummary(), false);
finishIfComplete(level, pos, player, session);
return ItemInteractionResult.CONSUME;
}
if (!stack.is(TriadItems.TRIAD_CARD.get())) {
player.displayClientMessage(Component.literal("Hold a Triad Card from your duel hand to play your turn.").withStyle(ChatFormatting.YELLOW), false);
player.displayClientMessage(session.handSummary(), false);
return ItemInteractionResult.CONSUME;
}
CardStackData cardData = stack.get(com.trunksbomb.minetriad.registry.TriadDataComponents.CARD_DATA);
if (cardData == null || CardStackData.EMPTY.equals(cardData)) {
player.displayClientMessage(Component.literal("That card stack has no assigned card data.").withStyle(ChatFormatting.RED), false);
return ItemInteractionResult.CONSUME;
}
MoveResult playerMove = session.playPlayerCard(cardData.cardId(), hitResult, player.getAbilities().instabuild, tableFacing);
if (!playerMove.valid()) {
player.displayClientMessage(Component.literal("Move rejected: " + playerMove.errorMessage()).withStyle(ChatFormatting.RED), false);
player.displayClientMessage(session.boardSummary().copy().withStyle(ChatFormatting.DARK_GRAY), false);
player.displayClientMessage(session.handSummary(), false);
return ItemInteractionResult.CONSUME;
}
if (!placeBoardCard(table, playerMove, DuelTableBlockEntity.OWNER_FIRST)) {
player.displayClientMessage(Component.literal("That board slot is already occupied in the table inventory.").withStyle(ChatFormatting.RED), false);
clearAndRefund(level, pos, player, true);
return ItemInteractionResult.CONSUME;
}
applyCapturedOwnership(table, playerMove, DuelTableBlockEntity.OWNER_FIRST);
if (!player.getAbilities().instabuild) {
stack.consume(1, player);
}
player.displayClientMessage(Component.literal("You play " + playerMove.playedCardName() + "."), false);
sendBattleLog(player, playerMove, ChatFormatting.DARK_AQUA);
player.displayClientMessage(session.boardSummary(), false);
finishIfComplete(level, pos, player, session);
if (session.isComplete()) {
return ItemInteractionResult.CONSUME;
}
MoveResult opponentMove = session.playOpponentTurn();
if (!opponentMove.valid()) {
player.displayClientMessage(Component.literal(opponentMove.errorMessage()).withStyle(ChatFormatting.RED), false);
clearAndRefund(level, pos, player, true);
return ItemInteractionResult.CONSUME;
}
placeBoardCard(table, opponentMove, DuelTableBlockEntity.OWNER_SECOND);
applyCapturedOwnership(table, opponentMove, DuelTableBlockEntity.OWNER_SECOND);
player.displayClientMessage(Component.literal("Training Duelist answers with " + opponentMove.playedCardName() + "."), false);
sendBattleLog(player, opponentMove, ChatFormatting.GRAY);
player.displayClientMessage(session.boardSummary(), false);
finishIfComplete(level, pos, player, session);
if (!session.isComplete()) {
player.displayClientMessage(Component.literal("Your turn. Hold one of your remaining duel cards and click an open space.").withStyle(ChatFormatting.YELLOW), false);
player.displayClientMessage(session.handSummary(), false);
}
return ItemInteractionResult.CONSUME;
} catch (Exception exception) {
MineTriad.LOGGER.error("Duel table interaction failed", exception);
player.displayClientMessage(Component.literal("Duel error: " + exception.getClass().getSimpleName() + ": " + exception.getMessage())
.withStyle(ChatFormatting.RED), false);
clearAndRefund(level, pos, player, true);
return ItemInteractionResult.CONSUME;
}
}
@Override
protected InteractionResult useWithoutItem(BlockState state, Level level, BlockPos pos, Player player, BlockHitResult hitResult) {
return useItemOn(ItemStack.EMPTY, state, level, pos, player, InteractionHand.MAIN_HAND, hitResult).result();
}
@Override
public BlockState playerWillDestroy(Level level, BlockPos pos, BlockState state, Player player) {
return super.playerWillDestroy(level, pos, state, player);
}
@Override
protected float getDestroyProgress(BlockState state, Player player, net.minecraft.world.level.BlockGetter level, BlockPos pos) {
if (!player.getAbilities().instabuild && DuelSessionManager.hasActiveAt(pos)) {
return 0.0F;
}
return super.getDestroyProgress(state, player, level, pos);
}
@Override
protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
if (state.getBlock() != newState.getBlock()) {
for (var cardId : DuelSessionManager.endAndCollectRemainingAt(pos)) {
Block.popResource(level, pos, CardItem.createCardStack(cardId, TriadItems.TRIAD_CARD.get()));
}
DuelTableBlockEntity table = getTableEntity(level, pos);
if (table != null) {
table.dropBoardCards(level, pos);
}
}
super.onRemove(state, level, pos, newState, isMoving);
}
@Override
public BlockEntity newBlockEntity(BlockPos pos, BlockState state) {
return new DuelTableBlockEntity(pos, state);
}
@Override
protected RenderShape getRenderShape(BlockState state) {
return RenderShape.MODEL;
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
builder.add(FACING);
}
@Override
public BlockState getStateForPlacement(BlockPlaceContext context) {
return defaultBlockState().setValue(FACING, context.getHorizontalDirection().getOpposite());
}
private static boolean placeBoardCard(DuelTableBlockEntity table, MoveResult moveResult, int owner) {
if (moveResult.playedCardId() == null || moveResult.playedCell() == null) {
return false;
}
return table.setCard(moveResult.playedCell().index(), CardItem.createCardStack(moveResult.playedCardId(), TriadItems.TRIAD_CARD.get()), owner);
}
private static void applyCapturedOwnership(DuelTableBlockEntity table, MoveResult moveResult, int owner) {
for (var cell : moveResult.capturedCells()) {
table.setOwner(cell.index(), owner);
}
}
private static void sendBattleLog(Player player, MoveResult moveResult, ChatFormatting color) {
for (String line : moveResult.battleLog()) {
player.displayClientMessage(Component.literal(line).withStyle(color), false);
}
}
private static DuelTableBlockEntity getTableEntity(Level level, BlockPos pos) {
BlockEntity blockEntity = level.getBlockEntity(pos);
return blockEntity instanceof DuelTableBlockEntity duelTableBlockEntity ? duelTableBlockEntity : null;
}
private static void finishIfComplete(Level level, BlockPos pos, Player player, DuelSession session) {
if (!session.isComplete()) {
return;
}
session.enterOverview();
player.displayClientMessage(session.resultSummary().copy().withStyle(ChatFormatting.AQUA), false);
player.displayClientMessage(session.overviewMessage().copy().withStyle(ChatFormatting.YELLOW), false);
}
private static void clearAndRefund(Level level, BlockPos pos, Player player, boolean refundFullHand) {
DuelTableBlockEntity table = getTableEntity(level, pos);
if (table != null) {
table.clearBoard();
}
DuelSessionManager.end(player, refundFullHand);
}
private static void completeOverview(Level level, BlockPos pos, Player player, DuelSession session) {
DuelTableBlockEntity table = getTableEntity(level, pos);
if (table != null) {
table.clearBoard();
}
DuelSessionManager.end(player, true);
player.displayClientMessage(Component.literal("Duel finished. All played cards have been returned.").withStyle(ChatFormatting.GREEN), false);
}
}

View File

@@ -0,0 +1,8 @@
{
"variants": {
"facing=north": { "model": "minetriad:block/duel_table", "y": 180 },
"facing=south": { "model": "minetriad:block/duel_table" },
"facing=west": { "model": "minetriad:block/duel_table", "y": 90 },
"facing=east": { "model": "minetriad:block/duel_table", "y": 270 }
}
}

View File

@@ -0,0 +1,8 @@
{
"itemGroup.minetriad.cards": "Mine Triad Cards",
"itemGroup.minetriad.gameplay": "Mine Triad Gameplay",
"block.minetriad.duel_table": "Duel Table",
"item.minetriad.triad_card": "Triad Card",
"item.minetriad.deck_box": "Deck Box",
"item.minetriad.card_binder": "Card Binder"
}

View File

@@ -0,0 +1,8 @@
{
"parent": "minecraft:block/cube_bottom_top",
"textures": {
"bottom": "minetriad:block/duel_table_bottom",
"top": "minetriad:block/duel_table_top",
"side": "minetriad:block/duel_table_side"
}
}

View File

@@ -0,0 +1,6 @@
{
"parent": "minecraft:item/generated",
"textures": {
"layer0": "minetriad:item/card_binder"
}
}

View File

@@ -0,0 +1,6 @@
{
"parent": "minecraft:item/generated",
"textures": {
"layer0": "minetriad:item/deck_box"
}
}

View File

@@ -0,0 +1,3 @@
{
"parent": "minetriad:block/duel_table"
}

View File

@@ -0,0 +1,6 @@
{
"parent": "minecraft:item/generated",
"textures": {
"layer0": "minetriad:item/triad_card"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 176 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 149 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 412 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 173 B

View File

@@ -0,0 +1,6 @@
{
"replace": false,
"values": [
"minetriad:duel_table"
]
}

View File

@@ -0,0 +1,6 @@
{
"replace": false,
"values": [
"minetriad:duel_table"
]
}

View File

@@ -0,0 +1,19 @@
{
"type": "minecraft:block",
"pools": [
{
"rolls": 1,
"entries": [
{
"type": "minecraft:item",
"name": "minetriad:duel_table"
}
],
"conditions": [
{
"condition": "minecraft:survives_explosion"
}
]
}
]
}

View File

@@ -0,0 +1,95 @@
# This is an example neoforge.mods.toml file. It contains the data relating to the loading mods.
# There are several mandatory fields (#mandatory), and many more that are optional (#optional).
# The overall format is standard TOML format, v0.5.0.
# Note that there are a couple of TOML lists in this file.
# Find more information on toml format here: https://github.com/toml-lang/toml
# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
modLoader="javafml" #mandatory
# A version range to match for said mod loader - for regular FML @Mod it will be the FML version. This is currently 2.
loaderVersion="${loader_version_range}" #mandatory
# The license for you mod. This is mandatory metadata and allows for easier comprehension of your redistributive properties.
# Review your options at https://choosealicense.com/. All rights reserved is the default copyright stance, and is thus the default here.
license="${mod_license}"
# A URL to refer people to when problems occur with this mod
#issueTrackerURL="https://change.me.to.your.issue.tracker.example.invalid/" #optional
# A list of mods - how many allowed here is determined by the individual mod loader
[[mods]] #mandatory
# The modid of the mod
modId="${mod_id}" #mandatory
# The version number of the mod
version="${mod_version}" #mandatory
# A display name for the mod
displayName="${mod_name}" #mandatory
# A URL to query for updates for this mod. See the JSON update specification https://docs.neoforged.net/docs/misc/updatechecker/
#updateJSONURL="https://change.me.example.invalid/updates.json" #optional
# A URL for the "homepage" for this mod, displayed in the mod UI
#displayURL="https://change.me.to.your.mods.homepage.example.invalid/" #optional
# A file name (in the root of the mod JAR) containing a logo for display
#logoFile="examplemod.png" #optional
# A text field displayed in the mod UI
#credits="" #optional
# The authors of the mod, displayed in the mod UI (optional)
authors="trunksbomb"
# The description text for the mod (multi line!) (#mandatory)
description='''
Collect Minecraft-themed cards, build five-card decks, and play Triple Triad in-game.
'''
# The [[mixins]] block allows you to declare your mixin config to FML so that it gets loaded.
#[[mixins]]
#config="${mod_id}.mixins.json"
# The [[accessTransformers]] block allows you to declare where your AT file is.
# If this block is omitted, a fallback attempt will be made to load an AT from META-INF/accesstransformer.cfg
#[[accessTransformers]]
#file="META-INF/accesstransformer.cfg"
# The coremods config file path is not configurable and is always loaded from META-INF/coremods.json
# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional.
[[dependencies.${mod_id}]] #optional
# the modid of the dependency
modId="neoforge" #mandatory
# The type of the dependency. Can be one of "required", "optional", "incompatible" or "discouraged" (case insensitive).
# 'required' requires the mod to exist, 'optional' does not
# 'incompatible' will prevent the game from loading when the mod exists, and 'discouraged' will show a warning
type="required" #mandatory
# Optional field describing why the dependency is required or why it is incompatible
# reason="..."
# The version range of the dependency
versionRange="[${neo_version},)" #mandatory
# An ordering relationship for the dependency.
# BEFORE - This mod is loaded BEFORE the dependency
# AFTER - This mod is loaded AFTER the dependency
ordering="NONE"
# Side this dependency is applied on - BOTH, CLIENT, or SERVER
side="BOTH"
# Here's another dependency
[[dependencies.${mod_id}]]
modId="minecraft"
type="required"
# This version range declares a minimum of the current minecraft version up to but not including the next major version
versionRange="${minecraft_version_range}"
ordering="NONE"
side="BOTH"
# Features are specific properties of the game environment, that you may want to declare you require. This example declares
# that your mod requires GL version 3.2 or higher. Other features will be added. They are side aware so declaring this won't
# stop your mod loading on the server for example.
#[features.${mod_id}]
#openGLVersion="[3.2,)"