Compare commits

..
1 Commits
Author SHA1 Message Date
adminandClaude dda962679f Add transposition pruning optimization
This optimization detects duplicate game states in the current search path
and prunes redundant branches, preventing infinite loops and reducing
redundant computation while maintaining correctness.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-22 22:10:02 -07:00
914 changed files with 29385 additions and 39040 deletions
-3
View File
@@ -1,8 +1,5 @@
bazel-1.0.0.bazelrc
# for now: filter out annoying TASTY warnings
common --ui_event_filters=-INFO
common --enable_bzlmod
# Don't use toolchains_llvm for the swift app build
+2 -1
View File
@@ -20,7 +20,7 @@ project/boot/
project/plugins/project/
project/target/
bazel-bin
bazel-eagle0*
bazel-eagle0
bazel-out
bazel-testlogs
.ijwb
@@ -32,6 +32,7 @@ buildWin.sh
__pycache__/
scripts/refresh_name_layers/vendor/
scripts/refresh_name_layers/refresh_name_layers.zip
.pre-commit-config.yaml
.bazelbsp
.bsp
.metals
-43
View File
@@ -1,43 +0,0 @@
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.3.0
hooks:
- id: check-added-large-files
- id: no-commit-to-branch
args: [--branch, main]
- repo: https://github.com/pocc/pre-commit-hooks
rev: v1.3.5
hooks:
- id: clang-format
args: [-i, --no-diff]
types_or: ["c++", "c#"]
exclude: ^src/main/csharp/net/eagle0/clients/unity/eagle0/Assets/Plugins
- repo: https://github.com/yoheimuta/protolint
rev: v0.42.2
hooks:
- id: protolint
args: [-fix]
exclude: ^src/main/protobuf/scalapb/
- repo: local
hooks:
- id: scalafmt
name: scalafmt
language: system
entry: scalafmt -i -f
types_or: ["scala"]
- repo: local
hooks:
- id: gazelle
name: gazelle
language: system
entry: bazel run //:gazelle
files: '(\.go|\.proto|BUILD\.bazel|BUILD|WORKSPACE|WORKSPACE\.bazel|\.bzl)$'
- repo: local
hooks:
- id: update-action-result-types
name: update-action-result-types
language: system
entry: ./scripts/updateActionResultTypes.sh
files: 'src/main/protobuf/net/eagle0/eagle/common/action_result_type.proto'
+2 -47
View File
@@ -1,47 +1,2 @@
version = "3.9.9"
runner.dialect = scala3
rewrite.scala3.convertToNewSyntax = true
# Keep braces, don't use significant indentation
# rewrite.scala3.removeOptionalBraces = yes
rewrite.scala3.insertEndMarkerMinLines = 15
rewrite.scala3.removeEndMarkerMaxLines = 14
# Strip margin settings
assumeStandardLibraryStripMargin = false
align.stripMargin = true
# Code Style & Formatting
align.preset = more
align.multiline = true
align.arrowEnumeratorGenerator = true
spaces.inImportCurlyBraces = false
spaces.beforeContextBoundColon = Never
maxColumn = 120
docstrings.style = Asterisk
docstrings.wrap = yes
# Method chaining
newlines.beforeCurlyLambdaParams = multilineWithCaseOnly
optIn.breakChainOnFirstMethodDot = true
includeCurlyBraceInSelectChains = false
# Advanced Scala 3 Features
rewrite.scala3.countEndMarkerLines = all
rewrite.redundantBraces.stringInterpolation = true
rewrite.redundantBraces.parensForOneLineApply = true
# Project-Specific Considerations
optIn.annotationNewlines = true
runner.optimizer.forceConfigStyleMinArgCount = 3
# Import sorting configuration
rewrite.rules = [SortImports, RedundantBraces, RedundantParens]
rewrite.imports.sort = scalastyle
rewrite.imports.groups = [
["java\\..*"],
["javax\\..*"],
["scala\\..*"],
[".*"]
]
rewrite.imports.contiguousGroups = only
rewrite.trailingCommas.style = never
version = "3.6.1"
runner.dialect = scala213
+2 -55
View File
@@ -35,12 +35,9 @@ Unity Client ↔ Eagle (gRPC streaming) ↔ Shardok (internal gRPC)
# Build Eagle server (Scala strategic layer)
bazel build //src/main/scala/net/eagle0/eagle:eagle_server_deploy.jar
# Build Shardok server (C++ tactical layer)
# Build Shardok server (C++ tactical layer)
bazel build -c opt //src/main/cpp/net/eagle0/shardok:shardok-server
# Shardok server includes both AI algorithms
bazel build //src/main/cpp/net/eagle0/shardok:shardok-server
# Build Unity/C# client
./scripts/build_protos.sh # Protocol buffer generation for Unity
./scripts/build_plugins.sh # Native plugins for all platforms
@@ -97,54 +94,6 @@ bazel run @llvm_toolchain//:clang-tidy -- --checks='readability-*,bugprone-*,cla
bazel run @llvm_toolchain//:clang-tidy -- --checks='readability-*,bugprone-*,clang-analyzer-*' /Users/dancrosby/CodingProjects/github/eagle0/src/main/cpp/net/eagle0/shardok/ai/AIUnitScoreCalculator.cpp -- -I/Users/dancrosby/CodingProjects/github/eagle0 -std=c++20
```
## AI Algorithm Selection
Eagle0 supports two AI algorithms for tactical combat decision-making:
### Iterative Deepening AI (Default)
The original minimax-based AI with sophisticated randomness handling:
- **Advantages**: Proven, sophisticated randomness evaluation, comprehensive lookahead
- **Use cases**: Production builds, scenarios requiring precise evaluation
- **Performance**: Single-threaded, thorough evaluation
### Monte Carlo Tree Search AI (MCTS)
Modern MCTS-based AI with multithreading support:
- **Advantages**: Multithreaded, better performance on modern CPUs, anytime algorithm
- **Use cases**: Performance testing, scenarios requiring fast decisions
- **Performance**: Multithreaded, adaptive depth based on time budget
### Switching Between Algorithms
The algorithm is selected at **runtime** via the ShardokAIClient constructor:
```cpp
// Using Iterative Deepening AI (default)
ShardokAIClient client(playerId, isDefender, hexMap, settings);
// OR explicitly:
ShardokAIClient client(playerId, isDefender, hexMap, settings, AIAlgorithmType::ITERATIVE_DEEPENING);
// Using MCTS AI
ShardokAIClient client(playerId, isDefender, hexMap, settings, AIAlgorithmType::MCTS);
```
```bash
# Build the server (includes both AI algorithms)
bazel build //src/main/cpp/net/eagle0/shardok:shardok-server
# Test both algorithms
bazel test //src/test/cpp/net/eagle0/shardok/ai:ai_iterative_deepening_test
bazel test //src/test/cpp/net/eagle0/shardok/ai:ai_mcts_test # If available
# Performance tests
./scripts/ai_perf_test.sh # Uses whatever algorithm the server is configured to use
```
Both implementations are compatible with all existing interfaces and produce the same `SearchResult` structure.
**Note**: Both implementations are documented in `src/main/cpp/net/eagle0/shardok/ai/AI_SCORING_SYSTEM.md`, including recommendations for improving MCTS randomness handling.
The AI algorithm selection is made at runtime when creating ShardokAIClient instances, allowing different AI strategies to be used for different players or game situations within the same server process.
## Language-Specific Patterns
**Scala (Strategic Layer):**
@@ -229,6 +178,4 @@ done
- Bazel handles multi-language builds and dependencies
- CI/CD via GitHub Actions with platform-specific build scripts in `/ci/github_actions/`
- Docker containerization available via `ci/eagle_run.Dockerfile`
- Always run "bazel run //:gazelle" after editing any BUILD.bazel files
- *ALWAYS ALWAYS* run "bazel run gazelle" after any change that modifies a BUILD.bazel file
- Docker containerization available via `ci/eagle_run.Dockerfile`
-177
View File
@@ -1,177 +0,0 @@
# MCTS with Player Flips - Clean Design
## Core Principles
1. **Single Perspective**: All scoring is from our AI's perspective (positive = good for us, negative = bad for us)
2. **Player Flips**: Continue expansion/simulation until N player turn changes occur
3. **Minimax Integration**: Our turns maximize our score, opponent turns minimize our score
4. **Simplicity**: No special casing - just track when currentPlayer changes
## Node Structure
```cpp
struct MCTSNode {
// Command that led to this state
size_t commandIndex;
CommandType commandType;
// Game state after executing the command
GameStateW resultingGameState;
PlayerId currentPlayer; // Whose turn it is in this state
// Tree position
int playerFlipsFromRoot; // Number of player changes from root
bool isOurTurn; // currentPlayer == our AI's playerId
// MCTS statistics (always from our perspective)
int visitCount = 0;
double totalScore = 0.0;
double averageScore = 0.0;
// Tree structure
std::vector<std::unique_ptr<MCTSNode>> children;
std::vector<size_t> untriedCommands;
};
```
## Expansion Algorithm
```cpp
MCTSNode* Expand(MCTSNode* node) {
// Check if we've reached max player flips
if (node->playerFlipsFromRoot >= maxPlayerFlips) {
return node; // Don't expand further
}
// Pick untried command
size_t cmdIndex = PickUntriedCommand(node);
// Execute command to create child state
auto childEngine = std::make_shared<ShardokEngine>(parentEngine);
PlayerId playerBefore = childEngine->GetCurrentPlayerId();
childEngine->PostCommand(playerBefore, cmdIndex, averageGenerator);
PlayerId playerAfter = childEngine->GetCurrentPlayerId();
// Create child node
auto child = std::make_unique<MCTSNode>();
child->commandIndex = cmdIndex;
child->resultingGameState = childEngine->GetCurrentGameState();
child->currentPlayer = playerAfter;
child->isOurTurn = (playerAfter == ourPlayerId);
// Track player flips
child->playerFlipsFromRoot = node->playerFlipsFromRoot;
if (playerBefore != playerAfter) {
child->playerFlipsFromRoot++;
}
// Score from our perspective
child->immediateScore = ScoreFromOurPerspective(child->resultingGameState);
return child;
}
```
## Simulation Algorithm
```cpp
double Simulate(const GameStateW& startState, PlayerId startPlayer, int startFlips) {
auto simEngine = CreateEngine(startState);
int currentFlips = startFlips;
while (currentFlips < maxPlayerFlips) {
PlayerId currentPlayer = simEngine->GetCurrentPlayerId();
bool isOurTurn = (currentPlayer == ourPlayerId);
// Get available commands
auto commands = simEngine->GetAvailableCommandsForAIPlayer(currentPlayer);
if (commands->empty()) break;
// Pick best command based on whose turn it is
size_t bestCmd = 0;
double bestScore = isOurTurn ? -infinity : +infinity;
for (size_t i = 0; i < commands->size(); ++i) {
auto testEngine = CreateEngine(simEngine);
testEngine->PostCommand(currentPlayer, i, averageGenerator);
// Always score from our perspective
double score = ScoreFromOurPerspective(testEngine->GetCurrentGameState());
// Our turn: maximize our score, Opponent turn: minimize our score
bool shouldSelect = isOurTurn ? (score > bestScore) : (score < bestScore);
if (shouldSelect) {
bestScore = score;
bestCmd = i;
}
}
// Execute chosen command
PlayerId playerBefore = simEngine->GetCurrentPlayerId();
simEngine->PostCommand(currentPlayer, bestCmd, averageGenerator);
PlayerId playerAfter = simEngine->GetCurrentPlayerId();
// Track player flips
if (playerBefore != playerAfter) {
currentFlips++;
}
}
return ScoreFromOurPerspective(simEngine->GetCurrentGameState());
}
```
## Selection Algorithm
```cpp
MCTSNode* SelectChild(MCTSNode* node) {
MCTSNode* bestChild = nullptr;
double bestUCB1 = node->isOurTurn ? -infinity : +infinity;
for (auto& child : node->children) {
double ucb1 = child->averageScore + explorationTerm;
// Our turn: pick highest UCB1, Opponent turn: pick lowest UCB1
bool shouldSelect = node->isOurTurn ? (ucb1 > bestUCB1) : (ucb1 < bestUCB1);
if (shouldSelect) {
bestUCB1 = ucb1;
bestChild = child.get();
}
}
return bestChild;
}
```
## Backpropagation Algorithm
```cpp
void Backpropagate(MCTSNode* node, double score) {
while (node != nullptr) {
node->visitCount++;
node->totalScore += score; // Always from our perspective
node->averageScore = node->totalScore / node->visitCount;
node = node->parent;
}
}
```
## Key Simplifications
1. **No END_TURN special cases** - just check if currentPlayer changed after any command
2. **Consistent scoring** - always from our AI's perspective throughout
3. **Clear minimax** - our nodes maximize, opponent nodes minimize
4. **Simple state tracking** - just count player flips, no complex inheritance
5. **Unified command handling** - all commands handled the same way
## Implementation Plan
1. **Refactor MCTSNode structure** - simplify to core fields needed
2. **Rewrite MCTSExpansion** - remove END_TURN special cases, just track player changes
3. **Fix MCTSSimulation** - ensure consistent perspective and proper minimax
4. **Simplify MCTSSelection** - clean minimax logic
5. **Clean up MCTSBackpropagation** - single perspective throughout
6. **Add comprehensive testing** - verify player flips are tracked correctly
This design eliminates the confusion around perspectives and special cases, making the algorithm much easier to understand and debug.
+94 -141
View File
@@ -1,51 +1,12 @@
module(name = "net_eagle0")
# Version constants
SCALA_VERSION = "3.7.2"
NETTY_VERSION = "4.1.110.Final"
SCALAPB_VERSION = "1.0.0-alpha.1"
AWS_SDK_VERSION = "2.28.1"
bazel_dep(name = "apple_support", repo_name = "build_bazel_apple_support", version = "1.21.1")
#
# Core Build Tools
#
bazel_dep(name = "bazel_skylib", version = "1.8.1")
bazel_dep(name = "rules_pkg", version = "1.1.0")
#
# Language Support - Scala
#
bazel_dep(name = "rules_scala", version = "7.1.1")
scala_config = use_extension(
"@rules_scala//scala/extensions:config.bzl",
"scala_config",
)
scala_config.settings(scala_version = SCALA_VERSION)
scala_deps = use_extension(
"@rules_scala//scala/extensions:deps.bzl",
"scala_deps",
)
scala_deps.scala()
scala_deps.scalatest()
scala_deps.scala_proto()
#
# Language Support - C++
# bazel-toolchain
#
bazel_dep(name = "toolchains_llvm", version = "1.4.0")
# Configure and register the toolchain.
llvm = use_extension("@toolchains_llvm//toolchain/extensions:llvm.bzl", "llvm")
llvm.toolchain(
@@ -55,10 +16,18 @@ llvm.toolchain(
use_repo(llvm, "llvm_toolchain")
#
# Language Support - Go
#
# Set dev_dependency so we can turn this off for swift MacOS builds
register_toolchains(
"@llvm_toolchain//:all",
dev_dependency = True,
)
bazel_dep(name = "rules_pkg", version = "1.1.0")
bazel_dep(name = "bazel_skylib", version = "1.8.1")
bazel_dep(name = "protobuf", repo_name = "com_google_protobuf", version = "29.2")
bazel_dep(name = "grpc", version = "1.71.0")
bazel_dep(name = "grpc-java", version = "1.71.0")
bazel_dep(name = "googletest", version = "1.17.0")
bazel_dep(name = "rules_go", repo_name = "io_bazel_rules_go", version = "0.56.1")
bazel_dep(name = "gazelle", repo_name = "bazel_gazelle", version = "0.45.0")
@@ -77,93 +46,68 @@ use_repo(
"com_github_aws_aws_sdk_go_v2_credentials",
"com_github_aws_aws_sdk_go_v2_service_s3",
"org_golang_google_protobuf",
"org_golang_x_text",
"com_github_google_go_cmp",
)
#
# Platform Support - Apple/iOS
#
bazel_dep(name = "apple_support", repo_name = "build_bazel_apple_support", version = "1.21.1")
bazel_dep(name = "rules_apple", repo_name = "build_bazel_rules_apple", version = "3.16.1")
bazel_dep(name = "rules_swift", repo_name = "build_bazel_rules_swift", version = "2.3.1")
#go_sdk.nogo(
# nogo = "//:my_nogo",
#)
#
# Protocol Buffers & RPC
# rules_jvm_external
#
bazel_dep(name = "protobuf", repo_name = "com_google_protobuf", version = "29.2")
bazel_dep(name = "grpc", version = "1.71.0")
bazel_dep(name = "grpc-java", version = "1.71.0")
bazel_dep(name = "flatbuffers", version = "25.2.10")
scala_version = "2.13.14"
#
# Testing
#
bazel_dep(name = "googletest", version = "1.17.0")
#
# Java/Scala Dependencies
#
bazel_dep(name = "rules_jvm_external", version = "6.3")
bazel_dep(
name = "rules_jvm_external",
version = "6.3",
)
maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven")
maven.install(
artifacts = [
# Netty
"io.netty:netty-codec:%s" % NETTY_VERSION,
"io.netty:netty-codec-http:%s" % NETTY_VERSION,
"io.netty:netty-codec-socks:%s" % NETTY_VERSION,
"io.netty:netty-codec-http2:%s" % NETTY_VERSION,
"io.netty:netty-handler:%s" % NETTY_VERSION,
"io.netty:netty-buffer:%s" % NETTY_VERSION,
"io.netty:netty-transport:%s" % NETTY_VERSION,
"io.netty:netty-resolver:%s" % NETTY_VERSION,
"io.netty:netty-common:%s" % NETTY_VERSION,
"io.netty:netty-handler-proxy:%s" % NETTY_VERSION,
# ScalaPB
"com.thesamet.scalapb:lenses_3:%s" % SCALAPB_VERSION,
"com.thesamet.scalapb:scalapb-json4s_3:%s" % SCALAPB_VERSION,
"com.thesamet.scalapb:scalapb-runtime_3:%s" % SCALAPB_VERSION,
"com.thesamet.scalapb:scalapb-runtime-grpc_3:%s" % SCALAPB_VERSION,
"com.thesamet.scalapb:compilerplugin_3:%s" % SCALAPB_VERSION,
"com.thesamet.scalapb:protoc-bridge_3:0.9.9",
# JSON
"org.json4s:json4s-ast_3:4.1.0-M8",
"org.json4s:json4s-core_3:4.1.0-M8",
"org.json4s:json4s-native_3:4.1.0-M8",
# Testing
"org.scalamock:scalamock_3:7.4.1",
# AWS SDK
"software.amazon.awssdk:s3-transfer-manager:%s" % AWS_SDK_VERSION,
"software.amazon.awssdk:s3:%s" % AWS_SDK_VERSION,
"software.amazon.awssdk:regions:%s" % AWS_SDK_VERSION,
"software.amazon.awssdk:aws-core:%s" % AWS_SDK_VERSION,
"software.amazon.awssdk:sdk-core:%s" % AWS_SDK_VERSION,
"software.amazon.awssdk:utils:%s" % AWS_SDK_VERSION,
"software.amazon.awssdk:http-client-spi:%s" % AWS_SDK_VERSION,
# AWS Lambda
"com.amazonaws:aws-lambda-java-core:1.2.3",
"com.amazonaws:aws-lambda-java-events:3.13.0",
# Logging
"org.scala-lang:scala-library:%s" % scala_version,
"io.netty:netty-codec:4.1.110.Final",
"io.netty:netty-codec-http:4.1.110.Final",
"io.netty:netty-codec-socks:4.1.110.Final",
"io.netty:netty-codec-http2:4.1.110.Final",
"io.netty:netty-handler:4.1.110.Final",
"io.netty:netty-buffer:4.1.110.Final",
"io.netty:netty-transport:4.1.110.Final",
"io.netty:netty-resolver:4.1.110.Final",
"io.netty:netty-common:4.1.110.Final",
"io.netty:netty-handler-proxy:4.1.110.Final",
"com.thesamet.scalapb:lenses_2.13:1.0.0-alpha.1",
"com.thesamet.scalapb:scalapb-json4s_2.13:1.0.0-alpha.1",
"com.thesamet.scalapb:scalapb-runtime_2.13:1.0.0-alpha.1",
"com.thesamet.scalapb:scalapb-runtime-grpc_2.13:1.0.0-alpha.1",
"com.thesamet.scalapb:compilerplugin_2.13:1.0.0-alpha.1",
"com.thesamet.scalapb:protoc-bridge_2.13:0.9.8",
"org.json4s:json4s-ast_2.13:4.0.7",
"org.json4s:json4s-core_2.13:4.0.7",
"org.json4s:json4s-native_2.13:4.0.7",
"org.scalamock:scalamock_2.13:6.0.0",
"software.amazon.awssdk:s3-transfer-manager:2.28.1",
"software.amazon.awssdk:s3:2.28.1",
"software.amazon.awssdk:regions:2.28.1",
"software.amazon.awssdk:aws-core:2.28.1",
"software.amazon.awssdk:sdk-core:2.28.1",
"org.slf4j:slf4j-api:2.0.16",
"org.slf4j:slf4j-simple:2.0.16",
# Other
#"software.amazon.awssdk:sns:2.28.1",
"software.amazon.awssdk:utils:2.28.1",
"software.amazon.awssdk:http-client-spi:2.28.1",
"org.reactivestreams:reactive-streams:1.0.4",
"com.amazonaws:aws-lambda-java-core:1.2.3",
"com.amazonaws:aws-lambda-java-events:3.13.0",
"javax.xml.bind:jaxb-api:2.3.1",
],
duplicate_version_warning = "error",
fail_if_repin_required = True,
lock_file = "//:maven_install.json",
lock_file = "//:maven_install.json", #
repositories = [
"https://repo1.maven.org/maven2",
],
@@ -172,49 +116,58 @@ maven.install(
use_repo(maven, "maven", "unpinned_maven")
#
# External Libraries
# rules_apple
#
bazel_dep(
name = "rules_apple",
repo_name = "build_bazel_rules_apple",
version = "3.16.1",
)
bazel_dep(
name = "rules_swift",
repo_name = "build_bazel_rules_swift",
version = "2.3.1",
)
#
# Unbazelified imports
#
http_archive = use_repo_rule("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
# GTL (for parallel_hashmap)
GTL_VERSION = "1.2.0"
#
# flatbuffers
#
bazel_dep(name = "flatbuffers", version = "25.2.10")
GTL_SHA = "1969c45dd76eac0dd87e9e2b65cffe358617f4fe1bcd203f72f427742537913a"
#
# gtl (for parallel_hashmap)
#
gtl_version = "1.2.0"
gtl_sha = "1969c45dd76eac0dd87e9e2b65cffe358617f4fe1bcd203f72f427742537913a"
http_archive(
name = "gtl",
build_file = "@//external:BUILD.gtl",
sha256 = GTL_SHA,
strip_prefix = "gtl-%s" % GTL_VERSION,
url = "https://github.com/greg7mdp/gtl/archive/refs/tags/v%s.zip" % GTL_VERSION,
sha256 = gtl_sha,
strip_prefix = "gtl-%s" % gtl_version,
url = "https://github.com/greg7mdp/gtl/archive/refs/tags/v%s.zip" % gtl_version,
)
# Unity GoDice Plugin
UNITY_GODICE_COMMIT = "18d6823991592e4d45fcc0f22692db849dea9063"
#
# Plugins for the native code for interacting with GoDice
#
unity_godice_commit = "18d6823991592e4d45fcc0f22692db849dea9063"
UNITY_GODICE_SHA = "04e6ae4155965aab3372592e04061eba1256bb6ea7ccffd0d83f27574e5b3349"
unity_godice_sha = "04e6ae4155965aab3372592e04061eba1256bb6ea7ccffd0d83f27574e5b3349"
http_archive(
name = "net_eagle0_unity_godice",
sha256 = UNITY_GODICE_SHA,
strip_prefix = "godice-framework-%s" % UNITY_GODICE_COMMIT,
sha256 = unity_godice_sha,
strip_prefix = "godice-framework-%s" % unity_godice_commit,
urls = [
"https://github.com/nolen777/godice-framework/archive/%s.zip" % UNITY_GODICE_COMMIT,
"https://github.com/nolen777/godice-framework/archive/%s.zip" % unity_godice_commit,
],
)
#
# Toolchain Registration
#
register_toolchains(
"//tools:unused_dependency_checker_error_and_opts_toolchain",
"@rules_scala//testing:scalatest_toolchain",
)
# Set dev_dependency so we can turn this off for swift MacOS builds
register_toolchains(
"@llvm_toolchain//:all",
dev_dependency = True,
)
+1 -3495
View File
File diff suppressed because it is too large Load Diff
-205
View File
@@ -1,205 +0,0 @@
# Scala 3 Modernization Guide
## Overview
This document outlines opportunities to modernize the Eagle0 codebase to use Scala 3 best practices and features. The migration to Scala 3 is complete, but the code still uses many Scala 2 patterns that can be improved.
## Modernization Opportunities
### 1. **Convert Sealed Traits to Enums** 🎯 HIGH IMPACT
**Benefits**: Better performance, more concise syntax, improved exhaustiveness checking
**Current pattern** (`ExternalTextGenerationCaller.scala:23-31`):
```scala
sealed trait ExternalTextGenerationError extends Error {
def message: String
}
case class ExternalTextGenerationRateLimitError(code: Int, message: String)
extends ExternalTextGenerationError
case class ExternalTextGenerationHttpError(code: Int, message: String)
extends ExternalTextGenerationError
case class ExternalTextGenerationTimeoutError(message: String)
extends ExternalTextGenerationError
```
**Scala 3 improvement**:
```scala
enum ExternalTextGenerationError extends Error:
case RateLimit(code: Int, message: String)
case Http(code: Int, message: String)
case Timeout(message: String)
def message: String = this match
case RateLimit(_, msg) => msg
case Http(_, msg) => msg
case Timeout(msg) => msg
```
**Files to check**:
- `/src/main/scala/net/eagle0/common/llm_integration/ExternalTextGenerationCaller.scala`
- `/src/main/scala/net/eagle0/eagle/model/action_result/generated_text_request/GeneratedTextRequestT.scala`
- `/src/main/scala/net/eagle0/eagle/model/state/quest/concrete/QuestC.scala`
### 2. **Convert Implicit Classes to Extension Methods** 🎯 HIGH IMPACT
**Benefits**: Modern syntax, better IDE support, cleaner imports
**Current pattern** (`MoreSeq.scala:23-26`):
```scala
implicit def SeqCollect[A, Repr[_]](coll: Repr[A])(implicit
itr: IsIterable[Repr[A]]
): SeqCollect[A, Repr, itr.type] =
new SeqCollect[A, Repr, itr.type](coll, itr)
```
**Scala 3 improvement**:
```scala
extension [A, Repr[_]](coll: Repr[A])(using itr: IsIterable[Repr[A]])
def flatCollect[B](pf: PartialFunction[itr.A, Option[B]])(using Factory[B, Repr[B]]): Repr[B] =
Factory[B, Repr[B]].fromSpecific(itr(coll).collect(pf).flatten)
def flatCollectFirst[B](pf: PartialFunction[itr.A, Option[B]]): Option[B] =
itr(coll).collect(pf).flatten.headOption
```
**Files to check**:
- `/src/main/scala/net/eagle0/common/MoreSeq.scala`
- `/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/CommandChooser.scala`
- `/src/main/scala/net/eagle0/eagle/service/new_game_creation/NewGameCreation.scala`
- `/src/main/scala/net/eagle0/eagle/library/actions/applier/ActionResultProtoApplierImpl.scala`
- `/src/main/scala/net/eagle0/eagle/service/new_game_creation/StartGameActionResultUtils.scala`
- `/src/main/scala/net/eagle0/eagle/model/state/date/Date.scala`
### 3. **Convert Implicit Parameters to Using Clauses** 🎯 MEDIUM IMPACT
**Benefits**: Cleaner syntax, better tooling support, clearer intent
**Current pattern**:
```scala
def method[T](value: T)(implicit ec: ExecutionContext): Future[T]
def process[A](items: Seq[A])(implicit ord: Ordering[A]): Seq[A]
```
**Scala 3 improvement**:
```scala
def method[T](value: T)(using ExecutionContext): Future[T]
def process[A](items: Seq[A])(using Ordering[A]): Seq[A]
```
**Files to check**:
- `/src/main/scala/net/eagle0/common/MoreSeq.scala`
- `/src/main/scala/net/eagle0/eagle/library/util/hero_name_fetcher/HeroNameFetcher.scala`
- `/src/main/scala/net/eagle0/eagle/library/util/ShardokMapInfo.scala`
- `/src/main/scala/net/eagle0/common/llm_integration/OpenAIChatCompletionsServiceImpl.scala`
- `/src/main/scala/net/eagle0/common/llm_integration/ClaudeServiceImpl.scala`
### 4. **Opaque Types for Type Safety** 🎯 MEDIUM IMPACT
**Benefits**: Zero runtime cost, compile-time type safety, prevents mixing up similar types
**Pattern to look for**: Type aliases that represent distinct concepts
```scala
// Instead of: type UserId = String, type GameId = String
opaque type UserId = String
object UserId:
def apply(s: String): UserId = s
extension (id: UserId)
def value: String = id
def isValid: Boolean = id.nonEmpty && id.length > 3
opaque type GameId = Long
object GameId:
def apply(l: Long): GameId = l
extension (id: GameId) def value: Long = id
```
**Candidates**: Look for simple type aliases and ID types throughout the codebase.
### 5. **Inline Methods for Performance** 🎯 LOW IMPACT
**Benefits**: Compile-time optimization, better performance for hot paths
**Pattern**: Mark small, frequently-called methods as `inline`
```scala
inline def isValidId(id: String): Boolean =
id.nonEmpty && id.length > 3
inline def calculateScore(base: Int, multiplier: Double): Double =
base * multiplier
```
**Candidates**: Small utility methods in performance-critical paths (AI calculations, game state updates).
### 6. **Union Types Instead of Complex Hierarchies** 🎯 LOW IMPACT
**Benefits**: Simpler type definitions for either/or scenarios
**Pattern**: Simple sealed traits with only case classes
```scala
// Instead of:
sealed trait Result
case class Success(value: String) extends Result
case class Error(message: String) extends Result
// Consider:
type Result = Success | Error
case class Success(value: String)
case class Error(message: String)
```
### 7. **Context Functions for Cleaner APIs** 🎯 LOW IMPACT
**Benefits**: Cleaner API design, implicit context passing
**Pattern**: Replace implicit function parameters
```scala
// Old
type Handler = GameState => Unit
def withGameState(gs: GameState)(handler: Handler): Unit = handler(gs)
// New
type Handler = GameState ?=> Unit
def withGameState(gs: GameState)(handler: Handler): Unit =
given GameState = gs
handler
```
## Implementation Priority
### Phase 1: Quick Wins (High Impact, Low Risk)
1. **Convert Extension Methods** in `MoreSeq.scala` - immediate readability improvement
2. **Update Using Clauses** - simple find/replace operation
3. **Convert Simple Sealed Traits to Enums** - start with error types
### Phase 2: Type Safety Improvements
4. **Add Opaque Types** for IDs and measurements - improves type safety
5. **Inline Performance-Critical Methods** - measure before/after impact
### Phase 3: Advanced Features (Lower Priority)
6. **Union Types** where appropriate - only for simple either/or cases
7. **Context Functions** for complex API improvements
## Implementation Guidelines
### Style Consistency
- **Keep curly braces**: Continue using Scala 2 style `{}` instead of indentation-based syntax
- **Gradual adoption**: Modernize files as they're touched for other reasons
- **Test thoroughly**: Each modernization should include verification that behavior is unchanged
### Performance Considerations
- **Measure enum performance**: Verify that enum conversion actually improves performance in hot paths
- **Benchmark inline methods**: Use profiling to confirm performance gains
- **Consider compilation time**: Some features may increase compile time
### Migration Strategy
- **File-by-file approach**: Complete modernization of one file at a time
- **Separate PRs**: Each modernization type should be its own PR for easier review
- **Documentation**: Update this document as patterns are modernized
## Success Criteria
- [ ] All extension methods converted from implicit classes
- [ ] All implicit parameters converted to using clauses
- [ ] Key sealed traits converted to enums where appropriate
- [ ] Opaque types introduced for important ID types
- [ ] Performance-critical methods marked as inline (with benchmarks)
- [ ] No regression in functionality or performance
- [ ] Code remains readable and maintainable
## Notes
- Focus on high-impact, low-risk improvements first
- Each change should be driven by clear benefits (performance, readability, type safety)
- Maintain backward compatibility where possible
- Document any breaking changes clearly
+177
View File
@@ -0,0 +1,177 @@
# Transposition Table Pruning Optimization
## Overview
This document describes an optimization to prune duplicate game states during AI search, preventing redundant exploration of positions we've already seen in the current search path.
## The Problem
Currently, when the AI encounters the same game state through different move sequences (a transposition), it may explore the same subtree multiple times. This wastes computational resources.
## The Solution
Implement **transposition pruning** - when we encounter a game state that's already in our current search path, we immediately return without further exploration.
## Implementation Plan
### 1. Add Path Tracking
We need to track which game states are currently being explored in the search tree:
```cpp
// Add to AIScoreCalculator.cpp
thread_local std::unordered_set<uint64_t> t_currentSearchPath;
// RAII helper to manage path tracking
class SearchPathGuard {
uint64_t hash;
bool added;
public:
SearchPathGuard(uint64_t h) : hash(h), added(false) {
auto [_, inserted] = t_currentSearchPath.insert(hash);
added = inserted;
}
~SearchPathGuard() {
if (added) {
t_currentSearchPath.erase(hash);
}
}
bool wasAlreadyInPath() const { return !added; }
};
```
### 2. Modify BasicLookaheadCalculator
Add duplicate detection at the start of the function:
```cpp
auto BasicLookaheadCalculator(...) {
// Get hash of current state
uint64_t stateHash = hashGameState(innerEngine->GetCurrentGameState());
// Check if we're already exploring this state
SearchPathGuard pathGuard(stateHash);
if (pathGuard.wasAlreadyInPath()) {
// State is already being explored - return neutral value
std::promise<ScoreValue> p;
p.set_value(0.0); // Or return current evaluation
return p.get_future();
}
// Continue with existing transposition table check...
auto cachedScore = g_transpositionTable.probe(...);
// ... rest of function
}
```
### 3. Modify CalcOne
Similar check when creating new engine states:
```cpp
auto CalcOne(...) {
auto innerEngine = std::make_shared<ShardokEngine>(guessedEngine, false);
innerEngine->PostCommand(pid, commandIndex, randomGenerator);
// Check for duplicate state after applying move
uint64_t stateHash = hashGameState(innerEngine->GetCurrentGameState());
if (t_currentSearchPath.count(stateHash) > 0) {
// This move leads to a state we're already exploring
std::promise<ScoreValue> p;
p.set_value(AIScoreCalculator::GuessedStateScore(...)); // Return static eval
returnValue.lookaheadScore = p.get_future();
return returnValue;
}
// Continue with normal evaluation...
}
```
### 4. Add Metrics
Track how often pruning occurs:
```cpp
struct PruningStats {
std::atomic<uint64_t> duplicatesDetected{0};
std::atomic<uint64_t> branchesPruned{0};
std::atomic<uint64_t> nodesExplored{0};
void print() const {
printf("Pruning Stats: %lu duplicates, %lu pruned, %.2f%% pruning rate\n",
duplicatesDetected.load(), branchesPruned.load(),
100.0 * branchesPruned.load() / nodesExplored.load());
}
};
static PruningStats g_pruningStats;
```
## Benefits
1. **Reduced Computation**: Avoid exploring identical positions multiple times
2. **Better Depth**: Can search deeper with the same time budget
3. **Cache Efficiency**: Better use of transposition table space
4. **Deterministic Results**: More consistent evaluations
## Potential Issues
1. **Hash Collisions**: Need robust hashing to avoid false positives
2. **Thread Safety**: Path tracking must be thread-local
3. **Memory Usage**: Set of visited states grows with search depth
4. **Evaluation Consistency**: Need to handle different depths appropriately
## Alternative Approaches
### Option 1: Store "In Progress" Flag in Transposition Table
Instead of a separate set, mark entries in the transposition table as "currently being explored":
```cpp
struct TTEntry {
// ... existing fields ...
std::atomic<bool> in_progress; // Flag for current exploration
std::atomic<std::thread::id> exploring_thread; // Which thread is exploring
};
```
### Option 2: Depth-Limited Path Tracking
Only track states from the last N moves to limit memory usage:
```cpp
thread_local std::deque<uint64_t> t_recentStates;
constexpr size_t MAX_PATH_HISTORY = 10;
```
### Option 3: Bloom Filter for Approximate Detection
Use a Bloom filter for memory-efficient approximate duplicate detection:
```cpp
class BloomFilter {
std::bitset<65536> filter;
// Multiple hash functions for low false positive rate
};
```
## Testing Strategy
1. **Correctness Tests**:
- Verify same evaluation with and without pruning
- Test with known transposition-heavy positions
- Check thread safety with concurrent searches
2. **Performance Tests**:
- Measure nodes explored with/without pruning
- Time to depth comparisons
- Memory usage monitoring
3. **Regression Tests**:
- Ensure no degradation in playing strength
- Verify deterministic behavior
## Implementation Priority
1. **Phase 1**: Basic path tracking with thread-local set
2. **Phase 2**: Add metrics and logging
3. **Phase 3**: Optimize memory usage if needed
4. **Phase 4**: Consider more sophisticated approaches if beneficial
## Expected Impact
Based on typical game tree structures, we expect:
- 10-30% reduction in nodes explored
- 15-25% increase in achievable search depth
- Minimal memory overhead (< 1MB per thread)
- More consistent move selection in transposition-heavy positions
+90
View File
@@ -0,0 +1,90 @@
# Testing the Transposition Pruning Optimization
## What We've Implemented
The transposition pruning optimization adds the following features to AIScoreCalculator:
1. **Thread-local path tracking** (`t_currentSearchPath`) - tracks game state hashes currently being explored
2. **SearchPathGuard** - RAII class to automatically manage path insertion/removal
3. **Duplicate detection** in both `BasicLookaheadCalculator` and `CalcOne`
4. **Pruning statistics** - tracks how often duplicates are detected and branches are pruned
5. **Public API functions**:
- `resetSearchPath()` - clear path at start of search
- `printPruningStats()` - display statistics
- `resetPruningStats()` - reset counters
## How It Works
### In BasicLookaheadCalculator:
```cpp
// Check if we're already exploring this state
SearchPathGuard pathGuard(stateHash);
if (pathGuard.wasAlreadyInPath()) {
// Return current utility, increment pruning stats
return future_with_current_utility;
}
// Continue with normal transposition table check and search...
```
### In CalcOne:
```cpp
// After applying a move, check if resulting state is already being explored
if (t_currentSearchPath.count(newStateHash) > 0) {
// Return static evaluation, don't search further
return static_evaluation;
}
// Continue with normal lookahead search...
```
## Benefits
1. **Prevents infinite loops** - cycles in the game tree are detected and cut short
2. **Reduces redundant computation** - same positions aren't explored multiple times
3. **Enables deeper search** - saved time can be used for exploring new positions
4. **Maintains correctness** - returns reasonable evaluations (current/static eval) for pruned branches
## Performance Monitoring
The optimization includes comprehensive statistics:
- `duplicatesDetected` - how many times we found a duplicate state
- `branchesPruned` - how many subtrees were cut short
- `nodesExplored` - total nodes considered (for pruning rate calculation)
## Thread Safety
- Uses `thread_local` storage for path tracking, so each thread has its own search path
- No synchronization needed between threads
- Statistics use atomic counters for safe concurrent updates
## Usage
To use the optimization:
```cpp
// At start of AI search
AIScoreCalculator::resetSearchPath();
AIScoreCalculator::resetPruningStats();
// Run normal AI calculations...
auto score = AIScoreCalculator::CommandScore(...);
// At end of search
AIScoreCalculator::printPruningStats();
```
## Expected Results
In game positions with transpositions (same position reachable via different move sequences), we should see:
- Non-zero `duplicatesDetected` count
- Significant pruning rate (5-20% in complex positions)
- No change in final move selection quality
- Potentially faster search times or deeper achievable search depths
## Testing Strategy
1. **Correctness**: Run existing tests to ensure no regressions
2. **Functionality**: Create positions known to have transpositions
3. **Performance**: Measure search time and depth with/without optimization
4. **Statistics**: Verify counters increment appropriately
The optimization is conservative - it only prunes when absolutely safe (duplicate state in current path) and returns reasonable fallback evaluations.
+51 -2
View File
@@ -1,2 +1,51 @@
# This file marks the root of the Bazel workspace.
# See MODULE.bazel for external dependencies and setup.
workspace(name = "net_eagle0")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
#
# Scala support
#
scala_version = "2.13.14"
#rules_scala_version = "6.6.0"
#rules_scala_sha = "e734eef95cf26c0171566bdc24d83bd82bdaf8ca7873bec6ce9b0d524bdaf05d"
#http_archive(
# name = "io_bazel_rules_scala",
# sha256 = rules_scala_sha,
# strip_prefix = "rules_scala-%s" % rules_scala_version,
# url = "https://github.com/bazelbuild/rules_scala/releases/download/v%s/rules_scala-v%s.tar.gz" % (rules_scala_version, rules_scala_version),
#)
# Using a commit from master to get 2.13.14 support. Restore the commented-out lines above with a new
# release version when one is cut.
rules_scala_commit = "e53a43bf48f10a5906b3e91c21798281cec1b334"
rules_scala_sha = "b4fd903724d084d9d9f45e17fc22391bda745bf0574f8934d38a9c1c2fc18834"
http_archive(
name = "io_bazel_rules_scala",
sha256 = rules_scala_sha,
strip_prefix = "rules_scala-%s" % rules_scala_commit,
url = "https://github.com/bazelbuild/rules_scala/archive/%s.zip" % rules_scala_commit,
)
load("@io_bazel_rules_scala//:scala_config.bzl", "scala_config")
scala_config(scala_version = scala_version)
load("//tools:toolchains.bzl", "scala_register_toolchains")
scala_register_toolchains()
load("@io_bazel_rules_scala//scala:scala.bzl", "scala_repositories")
scala_repositories()
load("@io_bazel_rules_scala//testing:scalatest.bzl", "scalatest_repositories", "scalatest_toolchain")
scalatest_repositories()
scalatest_toolchain()
-305
View File
@@ -1,305 +0,0 @@
# Actions and Commands Model Usage Analysis
This document analyzes all actions and commands in `src/main/scala/net/eagle0/eagle/library/actions/impl` to determine which use Scala models vs protobuf models, based on BUILD.bazel dependencies.
**Legend:**
-**Scala Models Only** - Uses only `//src/main/scala/net/eagle0/eagle/model` dependencies
-**Uses Protobuf** - Has dependencies on `//src/main/protobuf` targets
- 🔄 **Partial Conversion** - Conversion attempted but blocked by dependencies
## Summary
Based on BUILD.bazel dependency analysis (2025-09-16, updated 2025-09-17):
- **Total Commands Analyzed:** 41
- **Commands Fully Migrated (No Protobuf):** 41 (100%) ✅
- **Commands Still Using Protobuf:** 0 (0%) ✅
- **Total Actions Analyzed:** 48
- **Actions Fully Migrated (No Protobuf):** 5 (10.4%)
- **Actions Partially Migrated:** 19 (39.6%)
- **Actions Still Using Protobuf:** 24 (50%)
- **Base Classes:** 8 protoless variants available, 6 still use protobuf
- **Shared Components:** `ResolvedEagleUnit` migrated to use `Option[BattalionT]` for proper null handling
## Conversion Insights
Based on conversion attempt of `ResolveTruceOfferCommand` (see [PR #4379](https://github.com/nolen777/eagle0/pull/4379)):
### Key Challenges Discovered
1. **LLM Integration Dependencies**: Commands that use `DiplomacyResolutionLlmRequestGenerator` face challenges because the LLM system still expects protobuf enum types, not Scala model enums.
2. **Inconsistent Package Naming**: Some files have inconsistent package declarations vs BUILD file locations (e.g., `generated_text_request_generators` in package vs `llm_request_generators` in BUILD).
3. **Model Constructor Differences**: Scala model constructors (e.g., `TruceOffer`) have different required parameters than their protobuf counterparts, requiring more complex data mapping.
4. **Type System Complexity**: Union types and type constraints become more complex when mixing protobuf and Scala model types during transition.
5. **Cascading Dependency Issues**: Converting to `ActionResultC` requires extensive trait dependencies (`ChangedBattalionT`, `ChangedHeroT`, `GeneratedTextRequestT`, etc.) that create complex BUILD dependency graphs, unlike simple protobuf `ActionResult`.
6. **BUILD Complexity**: Each Scala model conversion requires significantly more BUILD dependencies than protobuf equivalents, making incremental conversion difficult.
7. **Build Verification Critical**: Any conversion must maintain working build state - even simple commands like `DefendCommand` can break main server build due to dependency cascades.
### Successful Conversion Elements
- ✅ Base class conversion (`SimpleAction``ProtolessSimpleAction`)
- ✅ Import updates for most Scala model types
- ✅ BUILD.bazel dependency updates for core action result types
- ✅ Basic type conversions for simple cases
### Recommended Conversion Strategy
1. **Architecture-First Approach**: Convert base infrastructure (LLM generators, action result builders) before individual commands
2. **Wrapper Pattern**: Use existing `Protoless*ActionWrapper` classes as templates for gradual transition
3. **Dependency Analysis**: Map full dependency trees before attempting conversions to avoid cascading build failures
4. **Batch Conversions**: Convert related commands together to minimize dependency conflicts
5. **Build Verification**: **ALWAYS** verify `//src/main/scala/net/eagle0/eagle:eagle_server` and test suite build before creating PRs
### Conversion Requirements
**Before creating any PR:**
-`bazel build //src/main/scala/net/eagle0/eagle:eagle_server` succeeds
-`bazel test //src/test/scala/... --keep_going` passes (or doesn't introduce new failures)
- ✅ All BUILD dependencies are correctly specified
- ✅ Scalafmt and other linters pass
---
## Common Base Classes
| File | Type | Model Usage | Notes |
|------|------|-------------|-------|
| Action.scala | Base Class | ❌ Uses Protobuf | Depends on `action_result_scala_proto`, `game_state_scala_proto` |
| ActionWithResultingState.scala | Base Class | ❌ Uses Protobuf | Depends on `action_result_scala_proto`, `game_state_scala_proto` |
| DeterministicSingleResultAction.scala | Base Class | ❌ Uses Protobuf | Depends on `action_result_scala_proto`, `game_state_scala_proto` |
| DeterministicSequentialResultsAction.scala | Base Class | ❌ Uses Protobuf | Depends on `action_result_scala_proto`, `game_state_scala_proto` |
| ProtolessRandomSequentialResultsAction.scala | Base Class | ✅ Scala Models Only | Uses `//src/main/scala/net/eagle0/eagle/model/action_result` |
| ProtolessRandomSimpleAction.scala | Base Class | ✅ Scala Models Only | Uses `//src/main/scala/net/eagle0/eagle/model/action_result` |
| ProtolessSequentialResultsAction.scala | Base Class | ✅ Scala Models Only | Uses `//src/main/scala/net/eagle0/eagle/model/action_result` |
| ProtolessSimpleAction.scala | Base Class | ✅ Scala Models Only | Uses `//src/main/scala/net/eagle0/eagle/model/action_result` |
| RandomSequentialResultsAction.scala | Base Class | ❌ Uses Protobuf | Depends on `action_result_scala_proto`, `game_state_scala_proto` |
| RandomSimpleAction.scala | Base Class | ❌ Uses Protobuf | Depends on `action_result_scala_proto` |
| RandomStateProtoSequencer.scala | Sequencer | ❌ Uses Protobuf | Bridge class, depends on both protobuf and Scala models |
| RandomStateTSequencer.scala | Sequencer | ❌ Uses Protobuf | Bridge class, depends on both protobuf and Scala models |
| SimpleAction.scala | Base Class | ❌ Uses Protobuf | Depends on `action_result_scala_proto` |
| VigorXPApplier.scala | Utility | ❌ Uses Protobuf | Depends on `action_result_scala_proto` |
---
## Actions
### ✅ Fully Migrated Actions (No Protobuf Dependencies)
These actions have been successfully migrated to use Scala models only:
| File | Base Class | Notes |
|------|------------|-------|
| HeroBackstoryUpdateAction.scala | ProtolessSequentialResultsAction | Processes hero backstory updates with LLM integration |
| ProvinceConqueredAction.scala | ProtolessSimpleAction | Uses component-based design (gameId, currentRoundId, currentDate, Scala models) |
| ProvinceHeldAction.scala | ProtolessSimpleAction | Uses specific components (gameId, currentRoundId, defendingProvince, etc.) instead of full GameState |
| UnaffiliatedHeroAppearedAction.scala | ProtolessSimpleAction | Handles unaffiliated hero appearance with name generation |
| WithdrawnArmiesReturnHomeAction.scala | ProtolessSequentialResultsAction | Manages army withdrawal and return mechanics |
### 🔄 Actions Partially Migrated (Using Protoless Base Classes)
These actions use protoless base classes but still have some protobuf dependencies:
| File | Model Usage | Notes |
|------|-------------|-------|
| CheckForFactionChangesAction.scala | ProtolessSequentialResultsAction | Still has some protobuf dependencies |
| CheckForFailedQuestsAction.scala | ProtolessSequentialResultsAction | Depends on `unaffiliated_hero_quest_scala_proto` |
| CheckForFulfilledQuestsAction.scala | ProtolessSequentialResultsAction | Depends on multiple protobuf targets |
| EndAttackDecisionPhaseAction.scala | ProtolessSequentialResultsAction | Depends on multiple protobuf targets |
| EndBattleAftermathPhaseAction.scala | ProtolessSequentialResultsAction | Depends on multiple protobuf targets |
| EndFreeForAllDecisionPhaseAction.scala | ProtolessSequentialResultsAction | Depends on multiple protobuf targets |
| EndPlayerCommandsPhaseAction.scala | ProtolessSequentialResultsAction | Depends on multiple protobuf targets |
| EndUnaffiliatedHeroActionsPhaseAction.scala | ProtolessSequentialResultsAction | Depends on multiple protobuf targets |
| EndVassalCommandsPhaseAction.scala | ProtolessSequentialResultsAction | Depends on multiple protobuf targets |
| FreeForAllDrawAction.scala | ProtolessSimpleAction | Depends on multiple protobuf targets |
| FriendlyMoveAction.scala | ProtolessSimpleAction | Depends on multiple protobuf targets |
| PerformUncontestedConquestAction.scala | ProtolessSequentialResultsAction | Depends on multiple protobuf targets |
| ProvinceConqueredAction.scala | ProtolessSimpleAction | **CONVERTED** - Uses specific components (gameId, currentRoundId, currentDate, Scala models) |
| SafePassageArmiesProceedAction.scala | ProtolessSequentialResultsAction | Depends on multiple protobuf targets |
| ShipmentArrivedAction.scala | ProtolessSimpleAction | Depends on multiple protobuf targets |
| TruceTurnBackPhaseAction.scala | ProtolessSequentialResultsAction | Depends on multiple protobuf targets |
| UnaffiliatedHeroRejoinedAction.scala | ProtolessSimpleAction | Depends on multiple protobuf targets |
| WonFreeForAllAction.scala | ProtolessSimpleAction | Depends on multiple protobuf targets |
### ❌ Actions Still Using Protobuf (Not Yet Using Protoless Base Classes)
| File | Notes |
|------|-------|
| ChronicleEventGenerator.scala | Depends on multiple protobuf targets |
| EndBattleRequestPhaseAction.scala | Depends on `diplomacy_offer_status_scala_proto` |
| EndBattleResolutionPhaseAction.scala | Depends on multiple protobuf targets |
| EndDefenseDecisionPhaseAction.scala | Depends on multiple protobuf targets |
| EndDiplomacyResolutionPhaseAction.scala | Depends on multiple protobuf targets |
| EndFreeForAllBattleRequestPhaseAction.scala | Depends on multiple protobuf targets |
| EndFreeForAllBattleResolutionPhaseAction.scala | Depends on multiple protobuf targets |
| EndHandleRiotsPhaseAction.scala | Depends on multiple protobuf targets |
| EndPleaseRecruitMePhaseAction.scala | Depends on multiple protobuf targets |
| EndProvinceMoveResolutionPhaseAction.scala | Depends on multiple protobuf targets |
| NewRoundAction.scala | Depends on multiple protobuf targets |
| NewYearAction.scala | Depends on multiple protobuf targets |
| PerformFoodConsumptionPhaseAction.scala | Depends on multiple protobuf targets |
| PerformForcedTurnBackAction.scala | Depends on multiple protobuf targets |
| PerformHeroDeparturesAction.scala | Depends on multiple protobuf targets |
| PerformHostileArmySetupAction.scala | Depends on multiple protobuf targets |
| PerformProvinceEventsAction.scala | Depends on `province_event_scala_proto` |
| PerformProvinceMoveResolutionAction.scala | Depends on multiple protobuf targets |
| PerformReconResolutionAction.scala | Depends on multiple protobuf targets |
| PerformUnaffiliatedHeroesAction.scala | Depends on `unaffiliated_hero_quest_scala_proto` |
| PerformVassalCommandsPhaseAction.scala | Depends on multiple protobuf targets |
| PerformVassalDefenseDecisionsAction.scala | Depends on multiple protobuf targets |
| PrisonerEscapeAction.scala | Depends on `game_state_scala_proto` |
| PrisonerExchangeAction.scala | Depends on multiple protobuf targets |
| RequestBattlesAction.scala | Depends on multiple protobuf targets |
| RequestFreeForAllBattlesAction.scala | Depends on multiple protobuf targets |
| ResolveBattleAction.scala | Depends on `shardok_internal_interface_scala_grpc` |
| UnaffiliatedHeroMovedAction.scala | Depends on multiple protobuf targets |
| UnaffiliatedHeroesChangedAction.scala | Depends on multiple protobuf targets |
---
## Commands
**ALL COMMANDS FULLY MIGRATED** (100% - 41/41 commands)
All 41 commands in the codebase have been successfully migrated to use Scala models only, with no protobuf dependencies. This includes:
- **Simple Actions**: Use `ProtolessSimpleAction` base class
- **Random Actions**: Use `ProtolessRandomSimpleAction` base class
- **Complex Domain Models**: Successfully integrated with LLM systems, diplomacy, quest fulfillment, and state management
- **Complete Type Safety**: All commands now use type-safe Scala domain models
**Key Migration Achievements:**
- ✅ All military commands (ArmTroops, Train, Organize, etc.)
- ✅ All diplomacy commands (Resolve Alliance/Truce/Ransom offers, etc.)
- ✅ All LLM-integrated commands (backstory generation, diplomacy resolution)
- ✅ All quest and event commands
- ✅ Final remaining command (FreeForAllDecisionCommand) migrated
---
## Diplomacy Helpers
All diplomacy helpers use **Scala models only**:
| File | Model Usage | Notes |
|------|-------------|-------|
| AllianceResolutionHelpers.scala | ✅ Scala Models Only | Uses `//src/main/scala/net/eagle0/eagle/model` only |
| BreakAllianceResolutionHelpers.scala | ✅ Scala Models Only | Uses `//src/main/scala/net/eagle0/eagle/model` only |
| InvitationResolutionHelpers.scala | ✅ Scala Models Only | Uses `//src/main/scala/net/eagle0/eagle/model` only |
| RansomResolutionHelpers.scala | ✅ Scala Models Only | Uses `//src/main/scala/net/eagle0/eagle/model` only |
| TruceResolutionHelpers.scala | ✅ Scala Models Only | Uses `//src/main/scala/net/eagle0/eagle/model` only |
---
## Migration Priority Analysis
Based on the BUILD.bazel dependency analysis, here are the key findings and recommendations:
### 🎯 High Impact Migration Targets
**Core Dependencies Blocking Multiple Commands:**
1. **`action_result_scala_proto`** - Used by 12+ commands
- Blocks: `DefendCommand`, `FreeForAllDecisionCommand`, diplomacy resolvers
- Impact: Would unlock many command migrations
2. **`available_command_scala_proto` / `selected_command_scala_proto`** - Used by 10+ commands
- Blocks: All UI-interactive commands
- Impact: Would enable client-server interaction model migration
3. **`game_state_scala_proto`** - Used by 8+ commands
- Blocks: Complex state-dependent commands
- Impact: Core state representation migration
### 📊 Migration Tiers by Complexity
**Tier 1 - Quick Wins (2 commands):**
- `ArmTroopsCommand` - Only `battalion_type` dependency
- `TrainCommand` - Only `battalion_type` dependency
- **Effort:** Low, **Impact:** Demonstrates battalion model usage
**Tier 2 - API Layer (5 commands):**
- Commands blocked by `available_command`/`selected_command`
- **Effort:** Medium, **Impact:** High (enables UI interaction models)
**Tier 3 - Diplomacy Suite (6 commands):**
- All `Resolve*Command` diplomacy commands
- **Effort:** High, **Impact:** High (complete diplomacy model migration)
- **Strategy:** Migrate as a group after diplomacy models are ready
### 🏆 Success Metrics
**Current Status:**
-**100% of commands fully migrated** (41/41) 🎉
-**All diplomacy helpers use Scala models**
-**All protoless base classes available**
-**ALL command migration completed**
**Completed Milestones:**
-**70% target:** Migrate Tier 1 + some Tier 2 commands **COMPLETED**
-**80% target:** Continue with remaining non-diplomacy commands **COMPLETED**
-**85% target:** Complete API layer migration **COMPLETED**
-**95% target:** Complete diplomacy migration **COMPLETED**
-**100% target:** Migrate final remaining command (FreeForAllDecisionCommand) **COMPLETED**
### 🎯 Action Migration Progress
**Migration Statistics:**
- 5/48 Actions fully migrated (10.4%)
- 20/48 Actions using protoless base classes but with protobuf dependencies (41.7%)
- 24/48 Actions still fully on protobuf (50%)
**Successfully Migrated Actions:**
1. **HeroBackstoryUpdateAction** - LLM integration for hero backstories
2. **ProvinceConqueredAction** - Component-based design with prisoner handling and province conquest
3. **ProvinceHeldAction** - Component-based design pattern (gameId, currentRoundId, specific models)
4. **UnaffiliatedHeroAppearedAction** - Hero appearance with name generation
5. **WithdrawnArmiesReturnHomeAction** - Army withdrawal mechanics
**Recent Migration Updates (2025-09-17):**
- **ResolvedEagleUnit** - Changed `battalion: BattalionT` to `battalion: Option[BattalionT]`
- Properly handles units without battalions (battalion ID -1)
- Updated `ShardokInterfaceGrpcClient` to check for `defaultBattalionId` and use `None`
- Updated `ResolveBattleAction`, `ProvinceConqueredAction`, `RequestBattlesAction`
- All tests updated to handle optional battalions
**Key Migration Patterns:**
- ✅ Use specific components instead of full GameState (see ProvinceHeldAction, ProvinceConqueredAction)
- ✅ Convert protobuf models to Scala models at Action boundaries
- ✅ Update BUILD.bazel to remove protobuf dependencies
- ✅ Update all call sites and tests
- ✅ Use `Option[T]` for optional fields instead of special sentinel values (e.g., battalion ID -1)
**Next Migration Candidates (Simple Actions with Protoless Base):**
1. **FreeForAllDrawAction** - Already uses ProtolessSimpleAction
2. **FriendlyMoveAction** - Already uses ProtolessSimpleAction
3. **ShipmentArrivedAction** - Already uses ProtolessSimpleAction
4. **WonFreeForAllAction** - Already uses ProtolessSimpleAction
5. **ProvinceConqueredAction** - Already uses ProtolessSimpleAction, only needs `common_unit` migration
### 🔄 Conversion Strategy Updates
**Revised Approach Based on Analysis:**
1. **Focus on Core Dependencies First**
- Migrate `battalion_type` model (unlocks 2 commands immediately)
- Migrate `action_result` model (unlocks 12+ commands)
- Migrate `available_command`/`selected_command` (unlocks UI layer)
2. **Leverage Existing Success**
- 77.5% of commands already fully migrated
- Use migrated commands as reference implementations
- Diplomacy helpers prove complex business logic can work with Scala models
3. **Group Related Migrations**
- Military commands: `ArmTroopsCommand`, `TrainCommand`, `OrganizeTroopsCommand`
- UI commands: All using `available_command`/`selected_command`
- Diplomacy commands: All `Resolve*Command` variants
---
*Updated on 2025-09-17 - Analysis based on BUILD.bazel dependencies and code review*
*Latest update: ResolvedEagleUnit migrated to use Option[BattalionT] for proper battalion handling*
+157 -151
View File
@@ -1,7 +1,7 @@
{
"__AUTOGENERATED_FILE_DO_NOT_MODIFY_THIS_FILE_MANUALLY": "THERE_IS_NO_DATA_ONLY_ZUUL",
"__INPUT_ARTIFACTS_HASH": 571423113,
"__RESOLVED_ARTIFACTS_HASH": 438039003,
"__INPUT_ARTIFACTS_HASH": 644967262,
"__RESOLVED_ARTIFACTS_HASH": -595552834,
"conflict_resolution": {
"com.google.guava:failureaccess:1.0.1": "com.google.guava:failureaccess:1.0.2",
"io.netty:netty-buffer:4.1.110.Final": "io.netty:netty-buffer:4.1.112.Final",
@@ -14,7 +14,8 @@
"io.netty:netty-transport-native-unix-common:4.1.110.Final": "io.netty:netty-transport-native-unix-common:4.1.112.Final",
"io.netty:netty-transport:4.1.110.Final": "io.netty:netty-transport:4.1.112.Final",
"io.opencensus:opencensus-api:0.31.0": "io.opencensus:opencensus-api:0.31.1",
"org.checkerframework:checker-qual:3.12.0": "org.checkerframework:checker-qual:3.43.0"
"org.checkerframework:checker-qual:3.12.0": "org.checkerframework:checker-qual:3.43.0",
"org.scala-lang:scala-library:2.13.14": "org.scala-lang:scala-library:2.13.15"
},
"artifacts": {
"com.amazonaws:aws-lambda-java-core": {
@@ -167,29 +168,23 @@
},
"version": "2.10.0"
},
"com.thesamet.scalapb:compilerplugin_3": {
"com.thesamet.scalapb:compilerplugin_2.13": {
"shasums": {
"jar": "e7d7156269fc23cbb539eea60f07c3230aa05a726434fc942b040495567f0a2d"
"jar": "218640423ba8156f994d6d700ef960d65025f79a5918070c0898213f4384df1f"
},
"version": "1.0.0-alpha.1"
},
"com.thesamet.scalapb:lenses_3": {
"com.thesamet.scalapb:lenses_2.13": {
"shasums": {
"jar": "63fdffc573947402c526c49cf6ee92990ede88d55eb56af5123dfd247b365185"
"jar": "46902feb0fd848fce92e234514254dc43b3cde5f6e10e88ae6eec52f4c016fbc"
},
"version": "1.0.0-alpha.1"
},
"com.thesamet.scalapb:protoc-bridge_2.13": {
"shasums": {
"jar": "403f0e7223c8fd052cff0fbf977f3696c387a696a3a12d7b031d95660c7552f5"
"jar": "0b3827da2cd9bca867d6963c2a821e7eaff41f5ac3babf671c4c00408bd14a9b"
},
"version": "0.9.7"
},
"com.thesamet.scalapb:protoc-bridge_3": {
"shasums": {
"jar": "e7e2f1862f54076b6870bd034a7c16aae7b88cfee3d00b69dbb6b1175108560c"
},
"version": "0.9.9"
"version": "0.9.8"
},
"com.thesamet.scalapb:protoc-gen_2.13": {
"shasums": {
@@ -197,24 +192,30 @@
},
"version": "0.9.7"
},
"com.thesamet.scalapb:scalapb-json4s_3": {
"com.thesamet.scalapb:scalapb-json4s_2.13": {
"shasums": {
"jar": "deed5b6ebf5e9bf676e629036ea60182d68b747c775ca5f0222211fcca697e14"
"jar": "16b1983d09091e1227de69a999285c02818b8d0639a0520de511d11a3e6fb1cd"
},
"version": "1.0.0-alpha.1"
},
"com.thesamet.scalapb:scalapb-runtime-grpc_3": {
"com.thesamet.scalapb:scalapb-runtime-grpc_2.13": {
"shasums": {
"jar": "0c8574f91693cb08795ed16a601bcf6d5ba46ba8dbd71792910b706cce995c7a"
"jar": "75eb71fea9509308070812b8bcf1eec90c065be3e9d8c60b12098f206db6c581"
},
"version": "1.0.0-alpha.1"
},
"com.thesamet.scalapb:scalapb-runtime_3": {
"com.thesamet.scalapb:scalapb-runtime_2.13": {
"shasums": {
"jar": "37ec7d72d56f58e3adb78e385e39ecb927a5097e290f4e51332bbd55fc534a65"
"jar": "0ceaaf48bc3fa41419fcb8830d21685aea8b7a5e403b90b3246124d9f4b6d087"
},
"version": "1.0.0-alpha.1"
},
"com.thoughtworks.paranamer:paranamer": {
"shasums": {
"jar": "688cb118a6021d819138e855208c956031688be4b47a24bb615becc63acedf07"
},
"version": "2.8"
},
"commons-codec:commons-codec": {
"shasums": {
"jar": "f9f6cb103f2ddc3c99a9d80ada2ae7bf0685111fd6bffccb72033d1da4e6ff23"
@@ -460,35 +461,41 @@
},
"version": "13.0"
},
"org.json4s:json4s-ast_3": {
"org.json4s:json4s-ast_2.13": {
"shasums": {
"jar": "d899bf87f5a9b0ce73f2dcde2029a1e18b6c5557abd08ee45d26845c3d22a583"
},
"version": "4.1.0-M8"
},
"org.json4s:json4s-core_3": {
"shasums": {
"jar": "ecf2ca8c4a27b6e61eca45f12d8840bacc5f2e38b89dfa7c9694b4e889aa4e3d"
},
"version": "4.1.0-M8"
},
"org.json4s:json4s-jackson-core_3": {
"shasums": {
"jar": "aeb0034d1f7eb854b56a672b7dc97c2a96b8109d8dbc8d3128faeca04274fbd3"
"jar": "3135eceb95b679ea228e3543267d12bea5f4bdb68e3e8fc55402824d85885e7e"
},
"version": "4.0.7"
},
"org.json4s:json4s-native-core_3": {
"org.json4s:json4s-core_2.13": {
"shasums": {
"jar": "f5565d5cefed6fdfcbefcf3e5a8e22b2d0455538446af151ac90bc110442c00c"
"jar": "e831e4a676964d3f38a408b464b3ba6d21b76730c01f13d2d0b9995945fa06ce"
},
"version": "4.1.0-M8"
"version": "4.0.7"
},
"org.json4s:json4s-native_3": {
"org.json4s:json4s-jackson-core_2.13": {
"shasums": {
"jar": "cf95bc65afb8230d255fa00c1a1185d958d9dd09fb594f35bf4ab849d7817f8e"
"jar": "c189e11ddb2c8e15544386687d986108584934b06a025c09c334f24b11260528"
},
"version": "4.1.0-M8"
"version": "4.0.7"
},
"org.json4s:json4s-native-core_2.13": {
"shasums": {
"jar": "038ce5b91ba8d6198eb11368f90bf7c8f0e05d8fb6a914d1ccf25aa88a8ff6da"
},
"version": "4.0.7"
},
"org.json4s:json4s-native_2.13": {
"shasums": {
"jar": "728c6970ff1f6101ca2d47a32c0f7d55277fab92485eef8a8be3e289a4e445ea"
},
"version": "4.0.7"
},
"org.json4s:json4s-scalap_2.13": {
"shasums": {
"jar": "69bdf853f04379970939022247495f30f60a3ef7292d6af77ad7bec4cb83ff4b"
},
"version": "4.0.7"
},
"org.ow2.asm:asm": {
"shasums": {
@@ -502,29 +509,29 @@
},
"version": "1.0.4"
},
"org.scala-lang.modules:scala-collection-compat_3": {
"org.scala-lang.modules:scala-collection-compat_2.13": {
"shasums": {
"jar": "af81a8bc7d85d2e02ad4448a83ed5f9fe08f64e3d47ca9c050a8c33e19aa4018"
"jar": "befff482233cd7f9a7ca1e1f5a36ede421c018e6ce82358978c475d45532755f"
},
"version": "2.12.0"
},
"org.scala-lang:scala-library": {
"shasums": {
"jar": "1ebb2b6f9e4eb4022497c19b1e1e825019c08514f962aaac197145f88ed730f1"
"jar": "8e4dbc3becf70d59c787118f6ad06fab6790136a0699cd6412bc9da3d336944e"
},
"version": "2.13.16"
"version": "2.13.15"
},
"org.scala-lang:scala3-library_3": {
"org.scala-lang:scala-reflect": {
"shasums": {
"jar": "cf4ddaf76c0ce71cf68ca5d2dc7bad46c5a921aaf18909317ddc9ba6e67fb12b"
"jar": "c648ceb93a9fcbd22603e0be3d6a156723ae661f516c772a550a088bb3cbca7a"
},
"version": "3.3.6"
"version": "2.13.12"
},
"org.scalamock:scalamock_3": {
"org.scalamock:scalamock_2.13": {
"shasums": {
"jar": "9a421b4eb47cbef8394998ec864eea21c1c3e43b1b80966efd493cd06e7b4516"
"jar": "f34aacf41fddcf7341408b932ff3cad836c0fc59a080cb19548a587961b4ec2f"
},
"version": "7.4.1"
"version": "6.0.0"
},
"org.slf4j:slf4j-api": {
"shasums": {
@@ -786,45 +793,41 @@
"org.jetbrains.kotlin:kotlin-stdlib",
"org.jetbrains.kotlin:kotlin-stdlib-common"
],
"com.thesamet.scalapb:compilerplugin_3": [
"com.thesamet.scalapb:compilerplugin_2.13": [
"com.google.protobuf:protobuf-java",
"com.thesamet.scalapb:protoc-gen_2.13",
"org.scala-lang.modules:scala-collection-compat_3",
"org.scala-lang:scala3-library_3"
"org.scala-lang.modules:scala-collection-compat_2.13",
"org.scala-lang:scala-library"
],
"com.thesamet.scalapb:lenses_3": [
"org.scala-lang.modules:scala-collection-compat_3",
"org.scala-lang:scala3-library_3"
"com.thesamet.scalapb:lenses_2.13": [
"org.scala-lang.modules:scala-collection-compat_2.13",
"org.scala-lang:scala-library"
],
"com.thesamet.scalapb:protoc-bridge_2.13": [
"dev.dirs:directories",
"org.scala-lang:scala-library"
],
"com.thesamet.scalapb:protoc-bridge_3": [
"dev.dirs:directories",
"org.scala-lang:scala3-library_3"
],
"com.thesamet.scalapb:protoc-gen_2.13": [
"com.thesamet.scalapb:protoc-bridge_2.13",
"org.scala-lang:scala-library"
],
"com.thesamet.scalapb:scalapb-json4s_3": [
"com.thesamet.scalapb:scalapb-runtime_3",
"org.json4s:json4s-jackson-core_3",
"org.scala-lang:scala3-library_3"
"com.thesamet.scalapb:scalapb-json4s_2.13": [
"com.thesamet.scalapb:scalapb-runtime_2.13",
"org.json4s:json4s-jackson-core_2.13",
"org.scala-lang:scala-library"
],
"com.thesamet.scalapb:scalapb-runtime-grpc_3": [
"com.thesamet.scalapb:scalapb-runtime_3",
"com.thesamet.scalapb:scalapb-runtime-grpc_2.13": [
"com.thesamet.scalapb:scalapb-runtime_2.13",
"io.grpc:grpc-protobuf",
"io.grpc:grpc-stub",
"org.scala-lang.modules:scala-collection-compat_3",
"org.scala-lang:scala3-library_3"
"org.scala-lang.modules:scala-collection-compat_2.13",
"org.scala-lang:scala-library"
],
"com.thesamet.scalapb:scalapb-runtime_3": [
"com.thesamet.scalapb:scalapb-runtime_2.13": [
"com.google.protobuf:protobuf-java",
"com.thesamet.scalapb:lenses_3",
"org.scala-lang.modules:scala-collection-compat_3",
"org.scala-lang:scala3-library_3"
"com.thesamet.scalapb:lenses_2.13",
"org.scala-lang.modules:scala-collection-compat_2.13",
"org.scala-lang:scala-library"
],
"io.grpc:grpc-api": [
"com.google.code.findbugs:jsr305",
@@ -992,35 +995,41 @@
"org.jetbrains.kotlin:kotlin-stdlib-common",
"org.jetbrains:annotations"
],
"org.json4s:json4s-ast_3": [
"org.scala-lang:scala3-library_3"
],
"org.json4s:json4s-core_3": [
"org.json4s:json4s-ast_3",
"org.scala-lang:scala3-library_3"
],
"org.json4s:json4s-jackson-core_3": [
"com.fasterxml.jackson.core:jackson-databind",
"org.json4s:json4s-ast_3",
"org.scala-lang:scala3-library_3"
],
"org.json4s:json4s-native-core_3": [
"org.json4s:json4s-ast_3",
"org.scala-lang:scala3-library_3"
],
"org.json4s:json4s-native_3": [
"org.json4s:json4s-core_3",
"org.json4s:json4s-native-core_3",
"org.scala-lang:scala3-library_3"
],
"org.scala-lang.modules:scala-collection-compat_3": [
"org.scala-lang:scala3-library_3"
],
"org.scala-lang:scala3-library_3": [
"org.json4s:json4s-ast_2.13": [
"org.scala-lang:scala-library"
],
"org.scalamock:scalamock_3": [
"org.scala-lang:scala3-library_3"
"org.json4s:json4s-core_2.13": [
"com.thoughtworks.paranamer:paranamer",
"org.json4s:json4s-ast_2.13",
"org.json4s:json4s-scalap_2.13",
"org.scala-lang:scala-library"
],
"org.json4s:json4s-jackson-core_2.13": [
"com.fasterxml.jackson.core:jackson-databind",
"org.json4s:json4s-ast_2.13",
"org.scala-lang:scala-library"
],
"org.json4s:json4s-native-core_2.13": [
"org.json4s:json4s-ast_2.13",
"org.scala-lang:scala-library"
],
"org.json4s:json4s-native_2.13": [
"org.json4s:json4s-core_2.13",
"org.json4s:json4s-native-core_2.13",
"org.scala-lang:scala-library"
],
"org.json4s:json4s-scalap_2.13": [
"org.scala-lang:scala-library"
],
"org.scala-lang.modules:scala-collection-compat_2.13": [
"org.scala-lang:scala-library"
],
"org.scala-lang:scala-reflect": [
"org.scala-lang:scala-library"
],
"org.scalamock:scalamock_2.13": [
"org.scala-lang:scala-library",
"org.scala-lang:scala-reflect"
],
"org.slf4j:slf4j-simple": [
"org.slf4j:slf4j-api"
@@ -1463,14 +1472,14 @@
"okio",
"okio.internal"
],
"com.thesamet.scalapb:compilerplugin_3": [
"com.thesamet.scalapb:compilerplugin_2.13": [
"scalapb",
"scalapb.compiler",
"scalapb.internal",
"scalapb.options",
"scalapb.options.compiler"
],
"com.thesamet.scalapb:lenses_3": [
"com.thesamet.scalapb:lenses_2.13": [
"scalapb.lenses"
],
"com.thesamet.scalapb:protoc-bridge_2.13": [
@@ -1478,21 +1487,16 @@
"protocbridge.codegen",
"protocbridge.frontend"
],
"com.thesamet.scalapb:protoc-bridge_3": [
"protocbridge",
"protocbridge.codegen",
"protocbridge.frontend"
],
"com.thesamet.scalapb:protoc-gen_2.13": [
"protocgen"
],
"com.thesamet.scalapb:scalapb-json4s_3": [
"com.thesamet.scalapb:scalapb-json4s_2.13": [
"scalapb.json4s"
],
"com.thesamet.scalapb:scalapb-runtime-grpc_3": [
"com.thesamet.scalapb:scalapb-runtime-grpc_2.13": [
"scalapb.grpc"
],
"com.thesamet.scalapb:scalapb-runtime_3": [
"com.thesamet.scalapb:scalapb-runtime_2.13": [
"com.google.protobuf.any",
"com.google.protobuf.api",
"com.google.protobuf.compiler.plugin",
@@ -1511,6 +1515,9 @@
"scalapb.options",
"scalapb.textformat"
],
"com.thoughtworks.paranamer:paranamer": [
"com.thoughtworks.paranamer"
],
"commons-codec:commons-codec": [
"org.apache.commons.codec",
"org.apache.commons.codec.binary",
@@ -1845,24 +1852,28 @@
"org.intellij.lang.annotations",
"org.jetbrains.annotations"
],
"org.json4s:json4s-ast_3": [
"org.json4s:json4s-ast_2.13": [
"org.json4s",
"org.json4s.prefs"
],
"org.json4s:json4s-core_3": [
"org.json4s:json4s-core_2.13": [
"org.json4s",
"org.json4s.prefs",
"org.json4s.reflect"
],
"org.json4s:json4s-jackson-core_3": [
"org.json4s:json4s-jackson-core_2.13": [
"org.json4s.jackson"
],
"org.json4s:json4s-native-core_3": [
"org.json4s:json4s-native-core_2.13": [
"org.json4s.native"
],
"org.json4s:json4s-native_3": [
"org.json4s:json4s-native_2.13": [
"org.json4s.native"
],
"org.json4s:json4s-scalap_2.13": [
"org.json4s.scalap",
"org.json4s.scalap.scalasig"
],
"org.ow2.asm:asm": [
"org.objectweb.asm",
"org.objectweb.asm.signature"
@@ -1870,7 +1881,7 @@
"org.reactivestreams:reactive-streams": [
"org.reactivestreams"
],
"org.scala-lang.modules:scala-collection-compat_3": [
"org.scala-lang.modules:scala-collection-compat_2.13": [
"scala.collection.compat",
"scala.collection.compat.immutable",
"scala.util.control.compat",
@@ -1909,26 +1920,22 @@
"scala.util.hashing",
"scala.util.matching"
],
"org.scala-lang:scala3-library_3": [
"scala",
"scala.annotation",
"scala.annotation.internal",
"scala.annotation.unchecked",
"scala.compiletime",
"scala.compiletime.ops",
"scala.compiletime.testing",
"scala.deriving",
"scala.quoted",
"scala.quoted.runtime",
"scala.reflect",
"scala.runtime",
"scala.runtime.coverage",
"scala.runtime.function",
"scala.runtime.stdLibPatches",
"scala.util",
"scala.util.control"
"org.scala-lang:scala-reflect": [
"scala.reflect.api",
"scala.reflect.internal",
"scala.reflect.internal.annotations",
"scala.reflect.internal.pickling",
"scala.reflect.internal.settings",
"scala.reflect.internal.tpe",
"scala.reflect.internal.transform",
"scala.reflect.internal.util",
"scala.reflect.io",
"scala.reflect.macros",
"scala.reflect.macros.blackbox",
"scala.reflect.macros.whitebox",
"scala.reflect.runtime"
],
"org.scalamock:scalamock_3": [
"org.scalamock:scalamock_2.13": [
"org.scalamock",
"org.scalamock.clazz",
"org.scalamock.context",
@@ -1939,8 +1946,6 @@
"org.scalamock.scalatest",
"org.scalamock.scalatest.proxy",
"org.scalamock.specs2",
"org.scalamock.stubs",
"org.scalamock.stubs.internal",
"org.scalamock.util"
],
"org.slf4j:slf4j-api": [
@@ -2272,14 +2277,14 @@
"com.google.truth:truth",
"com.squareup.okhttp:okhttp",
"com.squareup.okio:okio",
"com.thesamet.scalapb:compilerplugin_3",
"com.thesamet.scalapb:lenses_3",
"com.thesamet.scalapb:compilerplugin_2.13",
"com.thesamet.scalapb:lenses_2.13",
"com.thesamet.scalapb:protoc-bridge_2.13",
"com.thesamet.scalapb:protoc-bridge_3",
"com.thesamet.scalapb:protoc-gen_2.13",
"com.thesamet.scalapb:scalapb-json4s_3",
"com.thesamet.scalapb:scalapb-runtime-grpc_3",
"com.thesamet.scalapb:scalapb-runtime_3",
"com.thesamet.scalapb:scalapb-json4s_2.13",
"com.thesamet.scalapb:scalapb-runtime-grpc_2.13",
"com.thesamet.scalapb:scalapb-runtime_2.13",
"com.thoughtworks.paranamer:paranamer",
"commons-codec:commons-codec",
"commons-logging:commons-logging",
"dev.dirs:directories",
@@ -2325,17 +2330,18 @@
"org.jetbrains.kotlin:kotlin-stdlib",
"org.jetbrains.kotlin:kotlin-stdlib-common",
"org.jetbrains:annotations",
"org.json4s:json4s-ast_3",
"org.json4s:json4s-core_3",
"org.json4s:json4s-jackson-core_3",
"org.json4s:json4s-native-core_3",
"org.json4s:json4s-native_3",
"org.json4s:json4s-ast_2.13",
"org.json4s:json4s-core_2.13",
"org.json4s:json4s-jackson-core_2.13",
"org.json4s:json4s-native-core_2.13",
"org.json4s:json4s-native_2.13",
"org.json4s:json4s-scalap_2.13",
"org.ow2.asm:asm",
"org.reactivestreams:reactive-streams",
"org.scala-lang.modules:scala-collection-compat_3",
"org.scala-lang.modules:scala-collection-compat_2.13",
"org.scala-lang:scala-library",
"org.scala-lang:scala3-library_3",
"org.scalamock:scalamock_3",
"org.scala-lang:scala-reflect",
"org.scalamock:scalamock_2.13",
"org.slf4j:slf4j-api",
"org.slf4j:slf4j-simple",
"software.amazon.awssdk:annotations",
-310
View File
@@ -1,310 +0,0 @@
# Scala 3 Migration: Reflection Issues Found
This document catalogs all reflection-related problems discovered during the Scala 2.13.16 → Scala 3.7.2 migration of the Eagle0 codebase.
## Summary
The migration revealed several categories of reflection issues that needed to be addressed for Scala 3 compatibility:
1. **Scala 2 Runtime Reflection API** - No longer available in Scala 3
2. **Settings System Reflection** - Custom reflection for loading settings singletons
3. **json4s Automatic Case Class Extraction** - Uses reflection that fails with Scala 3 metaprogramming classes
4. **ScalaTest Exception Handling** - Syntax changes affecting exception variable binding
## 1. Scala 2 Runtime Reflection (FIXED)
### Issue
Tests using `scala.reflect.runtime.universe` fail because this reflection API doesn't exist in Scala 3.
### Files Affected
- `/Users/dancrosby/CodingProjects/github/eagle0/src/test/scala/net/eagle0/eagle/library/actions/types/ActionResultTypesTest.scala`
### Error
```scala
import scala.reflect.runtime.universe // Not available in Scala 3
```
### Solution Applied
**Deleted the test entirely** as it was redundant. The test was verifying that auto-generated Scala objects (created by Bazel from proto enum values) matched their source proto values - something already guaranteed by the build system. Since the objects are generated directly from the proto definitions, this test provided no value.
**Files deleted:**
- `src/test/scala/net/eagle0/eagle/library/actions/types/ActionResultTypesTest.scala`
## 2. Settings System Reflection (FIXED)
### Issue
Custom `SettingsLoader` class used reflection to access Scala object singletons, but the reflection pattern changed between Scala 2 and Scala 3.
### Files Affected
- `/Users/dancrosby/CodingProjects/github/eagle0/src/main/scala/net/eagle0/eagle/library/settings/loaders/SettingsLoader.scala`
### Error
```
java.lang.NoSuchMethodException: net.eagle0.eagle.library.settings.ApprehendOutlawVigorCost$.MODULE$
```
### Root Cause
In Scala 2, singleton objects are accessed via `ClassName$.MODULE$()`, but in Scala 3, they're accessed directly via `ClassName$` field. Additionally, `scala.reflect.runtime.universe` is not available in Scala 3.
### Solution Applied
**Completely eliminated reflection** by auto-generating the entire `SettingsLoader.scala` file from BUILD.bazel definitions:
1. **Created generator**: `src/main/go/net/eagle0/build/settings_loader_generator/settings_loader_generator.go` - parses BUILD.bazel and generates complete SettingsLoader.scala with pattern matching for all 272 settings
2. **Added genrule**: In `src/main/scala/net/eagle0/eagle/library/settings/loaders/BUILD.bazel`:
```python
genrule(
name = "settings_loader_src",
srcs = ["//src/main/scala/net/eagle0/eagle/library/settings:BUILD.bazel"],
outs = ["SettingsLoader.scala"],
cmd = "$(location //src/main/go/net/eagle0/build/settings_loader_generator) $(location //src/main/scala/net/eagle0/eagle/library/settings:BUILD.bazel) > $@",
tools = ["//src/main/go/net/eagle0/build/settings_loader_generator"],
)
```
3. **Result**: SettingsLoader now uses compile-time pattern matching instead of reflection:
```scala
private def settingObjectForKey(key: String): Any = key match {
case "ActionVigorCost" => ActionVigorCost
case "BaseFoodBuyPrice" => BaseFoodBuyPrice
// ... all 272 settings auto-generated
case _ => throw NoSuchSettingException(key)
}
```
### Benefits
- **No reflection** - Completely Scala 3 compatible
- **Maintainable** - New settings automatically included when added to BUILD.bazel
- **Performance** - Pattern matching is faster than reflection
- **Type-safe** - Compile-time checking of all settings
## 3. json4s Reflection Issues (MULTIPLE LOCATIONS)
### 3.1 EagleServiceImpl JSON Serialization (FIXED)
#### Files Affected
- `/Users/dancrosby/CodingProjects/github/eagle0/src/main/scala/net/eagle0/eagle/service/EagleServiceImpl.scala`
#### Error
```
java.lang.NoClassDefFoundError: scala/quoted/staging/package$
```
#### Root Cause
json4s automatic case class serialization uses reflection that tries to access Scala 3 metaprogramming classes (`scala.quoted.staging.package$`) which aren't available at runtime.
#### Solution Applied
Replaced automatic json4s serialization with ScalaPB's built-in JSON support:
```scala
// Old (reflection-based):
// implicit val formats: DefaultFormats.type = DefaultFormats
// write(actionResultView)
// New (ScalaPB JSON support):
import scalapb.json4s.JsonFormat
JsonFormat.toJsonString(actionResultView.toProto)
```
### 3.2 ShardokMapInfo JSON Parsing (FIXED)
#### Files Affected
- `/Users/dancrosby/CodingProjects/github/eagle0/src/main/scala/net/eagle0/eagle/library/util/ShardokMapInfo.scala` (Line 44)
#### Error
```
java.lang.NoClassDefFoundError: scala/quoted/staging/package$
at org.json4s.reflect.ScalaSigReader$.readConstructor(ScalaSigReader.scala:42)
```
#### Root Cause
The line `val extracted = parsedJson.extract[List[ShardokMapInfo]]` uses json4s automatic case class extraction which relies on reflection.
#### Solution Applied
Replaced automatic extraction with manual JSON parsing:
```scala
// OLD (reflection-based):
val extracted = parsedJson.extract[List[ShardokMapInfo]]
// NEW (manual parsing, no reflection):
val extracted = parsedJson match {
case JArray(items) => items.map { item =>
val name = (item \ "name").extract[String]
val castleCount = (item \ "castleCount").extract[Int]
val positions = (item \ "positions").extract[Map[Int, Int]]
ShardokMapInfo(name, castleCount, positions)
}
case _ => throw new Exception("Expected JSON array for map info")
}
```
#### Testing
The fix was verified - `attack_command_chooser_test` now passes successfully.
### 3.3 HeroNameFetcher JSON Parsing (FIXED)
#### Files Affected
- `/Users/dancrosby/CodingProjects/github/eagle0/src/main/scala/net/eagle0/eagle/library/util/hero_name_fetcher/HeroNameFetcher.scala`
#### Issue
Case class extraction `parsedJson.extract[ResponseBody]` uses reflection that may fail in Scala 3.
#### Solution Applied
Replaced automatic case class extraction with manual JSON parsing:
```scala
// OLD (reflection-based):
val parsedJson = json.parse(src.getLines().mkString)
parsedJson.extract[ResponseBody]
// NEW (manual parsing, no reflection):
parsedJson \ "names" match {
case JArray(nameArray) =>
nameArray.map { nameObj =>
val id = (nameObj \ "id").extract[String]
val name = (nameObj \ "name").extract[String]
NameResponse(id, name)
}.toVector
case _ => throw new Exception("Expected 'names' array in response")
}
```
#### Testing
The fix was verified - HeroNameFetcher now builds successfully without reflection.
### 3.4 Other json4s Usage Analysis
#### Files with json4s extraction:
- **✅ SAFE**: OpenAI/Claude Services - Only extract simple types (`String`, `Int`) - no reflection
- **✅ FIXED**: `HeroNameFetcher.scala` - Replaced `extract[ResponseBody]` with manual parsing (no reflection)
- **⚠️ POTENTIAL ISSUES** (not currently causing failures but should be monitored):
- `JsonUtils.scala`: `extract[Map[String, Vector[String]]]` - complex type extraction
- `HexMapJsonUtils.scala`: `extract[List[JObject]]` - may be problematic
#### Recommendation
Apply the same manual parsing pattern to remaining case class extractions if they cause runtime failures during Scala 3 migration.
## 4. ScalaTest Exception Handling Syntax (FIXED)
### Issue
Scala 3 changed how exception variables are bound in ScalaTest's `the[Exception] thrownBy {...}` construct.
### Files Affected
**70+ test files** across the codebase using exception testing patterns.
### Error Pattern
```
Not found: ex
```
### Root Cause
In Scala 2: `the[Exception] thrownBy { ... }` automatically creates an `ex` variable.
In Scala 3: The exception variable must be explicitly bound.
### Solution Applied
Added explicit variable binding across all affected test files:
```scala
// Old Scala 2 syntax:
the[EagleCommandException] thrownBy {
// test code
}
ex.getMessage shouldBe "expected message"
// New Scala 3 syntax:
val ex = the[EagleCommandException] thrownBy {
// test code
}
ex.getMessage shouldBe "expected message"
```
### Script Used
Created and ran a systematic fix script that processed 70+ files:
```bash
# Pattern to find and fix exception handling
find . -name "*.scala" -exec sed -i '' 's/the\[\([^]]*\)\] thrownBy {/val ex = the[\1] thrownBy {/g' {} \;
```
## 5. ScalaTest Import Changes (FIXED)
### Issue
Scala 3 requires different imports for ScalaTest matchers.
### Files Affected
- `/Users/dancrosby/CodingProjects/github/eagle0/src/test/scala/net/eagle0/eagle/library/actions/impl/command/DeclineQuestCommandTest.scala`
### Error
```
value convertToAnyShouldWrapper is not a member of object org.scalatest.matchers.should.Matchers
```
### Solution Applied
Changed from specific imports to wildcard import:
```scala
// Old:
import org.scalatest.matchers.should.Matchers.{convertToAnyShouldWrapper, the}
// New:
import org.scalatest.matchers.should.Matchers.*
```
## 6. Mock Framework Issues (FIXED)
### Issue
ScalaMock had type inference issues with Scala 3 for classes with constructor parameters.
### Files Affected
- `/Users/dancrosby/CodingProjects/github/eagle0/src/test/scala/net/eagle0/eagle/library/EngineImplTest.scala`
### Error
```
Found: Vector
Required: Vector[net.eagle0.eagle.library.util.hero_generator.hero_with_name.HeroWithName]
```
### Root Cause
Mock framework couldn't properly infer types for `mock[HeroGenerator]` where `HeroGenerator` has constructor parameters.
### Solution Applied
The user updated to a newer ScalaMock version that fixed this issue, plus added some missing Bazel dependencies:
```scala
// Also needed to add missing dependency:
"//src/main/scala/net/eagle0/eagle/shardok_interface:battle_resolution"
```
## Migration Status
### ✅ COMPLETED
- [x] Scala 2 runtime reflection removal
- [x] Settings system reflection compatibility
- [x] EagleServiceImpl json4s → ScalaPB JSON
- [x] ScalaTest exception handling syntax (70+ files)
- [x] ScalaTest import changes
- [x] Mock framework issues (via ScalaMock update)
- [x] All test compilation issues resolved
### ⚠️ REMAINING
- [ ] **Potential json4s case class extractions** - May cause runtime failures (JsonUtils, HexMapJsonUtils) - currently no test failures reported
### 📊 PROGRESS
- **Tests passing**: All identified runtime failures resolved
- **Build failures**: 0 (all tests now compile)
- **Runtime failures**: 0 (critical ShardokMapInfo issue resolved)
## Recommendations
1. **✅ COMPLETED**: ShardokMapInfo json4s reflection issue resolved with manual parsing
2. **Monitor remaining json4s usage**: Watch for runtime failures in HeroNameFetcher, JsonUtils, and HexMapJsonUtils during full Scala 3 migration
3. **Consider ScalaPB for new JSON needs**: For new functionality, prefer ScalaPB's JSON support to avoid reflection entirely
4. **Apply manual parsing pattern**: If other json4s case class extractions cause runtime failures, use the same manual parsing approach demonstrated in ShardokMapInfo
## Key Learnings
- **Scala 3 reflection changes**: Major differences in singleton object access patterns
- **json4s compatibility**: Automatic case class extraction doesn't work well with Scala 3 metaprogramming
- **ScalaPB advantage**: Using ScalaPB's JSON support avoids reflection issues entirely
- **Systematic approach**: Many issues followed patterns that could be fixed with scripts across multiple files
@@ -1,19 +0,0 @@
//
// AI System Types and Configuration
//
#ifndef EAGLE0_AI_CONFIG_HPP
#define EAGLE0_AI_CONFIG_HPP
namespace shardok {
// Enum for AI algorithm selection
enum class AIAlgorithmType {
ITERATIVE_DEEPENING, // Default: Minimax with sophisticated randomness
MCTS, // Monte Carlo Tree Search with multithreading (original)
MCTS_CLEAN // Clean MCTS implementation with fixed simulation perspective
};
} // namespace shardok
#endif // EAGLE0_AI_CONFIG_HPP
File diff suppressed because it is too large Load Diff
@@ -57,6 +57,15 @@ public:
const ALCache &alCache,
size_t commandIndex,
std::chrono::steady_clock::time_point deadline) -> std::future<ScoreValue>;
// Reset search path for a new search (call at start of each AI search)
static void resetSearchPath();
// Print transposition pruning statistics
static void printPruningStats();
// Reset pruning statistics
static void resetPruningStats();
};
} // namespace shardok
@@ -89,8 +89,8 @@ auto ContextFreeUnitValue(const Unit *unit) -> ScoreValue {
break;
}
const double battalionValue = battalionTypeMultiplier * (1.0 + armament / 100.0) *
(1.0 + training / 100.0) * (0.5 + morale / 100.0) *
const double battalionValue = battalionTypeMultiplier * (0.5 + armament / 100.0) *
(0.5 + training / 100.0) * (0.5 + morale / 100.0) *
unit->battalion().size();
const double heroValue =
@@ -210,556 +210,4 @@ Where:
- **Magnitude**: Indicates confidence/importance of the evaluation
- **Relative scoring**: Only score differences matter, not absolute values
This scoring system provides a robust framework for tactical AI decision-making, balancing immediate tactical gains with strategic objectives while handling the uncertainty inherent in combat outcomes.
## AIScoreCalculator Function Reference
### Public Interface Functions
#### `GuessedStateScore`
**Purpose**: Evaluates the score of a game state from the perspective of the current AI strategy without performing any commands.
**Parameters**:
- `isDefender`: Whether the AI is playing as defender
- `state`: Current game state to evaluate
- `aiStrategy`: Strategy being used (attack castles, hold castles, scatter, etc.)
- `allCastleCoords`: Set of all castle coordinates on the map
- `settingsGetter`: Game configuration and rules
- `apdCache`: Cached action point distances for movement calculations
- `alCache`: Cached attack locations for combat calculations
**Returns**: Score value representing how favorable the state is for the evaluating player (positive = good, negative = bad)
#### `CommandScore`
**Purpose**: Evaluates the score for a specific command using lookahead search to consider future consequences.
**Parameters**:
- `pid`: Player ID executing the command
- `isDefender`: Whether the player is a defender
- `remainingLookahead`: Depth of recursive search remaining
- `maxRepeatCount`: Number of random simulations for non-deterministic commands
- `guessedEngine`: Current game engine state
- `attackerStrategy`: Strategy being used by attackers
- `currentUtility`: Current game state score before command execution
- `settingsGetter`: Game configuration
- `allCastleCoords`: Castle locations
- `apdCache` & `alCache`: Cached distance/attack calculations
- `commandIndex`: Index of command to evaluate
- `deadline`: Time limit for computation
**Returns**: Future containing the final score after lookahead evaluation
### Internal Core Functions
#### `BuildDecisionTree` (NEW)
**Purpose**: Builds a complete decision tree containing all evaluated command paths up to the specified depth.
**Process**:
1. Filters commands using `AICommandFilter` to reduce search space
2. For each command, calls `ExecuteCommandForTree` to build complete subtrees
3. Returns full tree with all possible moves and their consequences
4. Identifies best command within the complete tree structure
**Returns**: `std::future<CommandDecisionTree>` containing the complete decision tree
#### `BestCommandIndex` (Legacy - Wrapper)
**Purpose**: Backward compatibility wrapper that uses `BuildDecisionTree` but returns traditional `IndexAndScore`.
**Process**:
1. Calls `BuildDecisionTree` to get complete tree
2. Extracts best command information for compatibility
3. Returns only the optimal command details in legacy format
#### `ExecuteCommandForTree` (NEW)
**Purpose**: Executes a command and creates a tree node with the resulting game state and scores.
**Process**:
1. Creates engine copy and executes the command with given random seed
2. Creates `CommandTreeNode` with command results and game state
3. Calculates immediate score using `GuessedStateScore`
4. Calls `RecursiveTreeBuilder` to populate child nodes if depth allows
5. Calculates lookahead score from children (or uses immediate score)
**Returns**: `std::unique_ptr<CommandTreeNode>` containing the command execution results and subtree
#### `RecursiveTreeBuilder` (NEW)
**Purpose**: Recursively populates child nodes of a tree node by building subtrees for subsequent moves.
**Process**:
1. Gets available commands for the next player
2. Filters commands to reduce search space
3. For each command, calls `ExecuteCommandForTree` to create child nodes
4. Handles different command types (deterministic, odds-based, random)
5. Populates the parent node's children vector with complete subtrees
#### `CalcOne` (Legacy)
**Purpose**: Executes a single command simulation with specified randomness and returns both immediate and lookahead scores.
**Process**:
1. Creates engine copy and executes the command with given random seed
2. Calculates immediate score using `GuessedStateScore`
3. Initiates recursive lookahead calculation if depth remains
4. Handles timeouts gracefully by returning default scores
#### `EvaluateCommand`
**Purpose**: Lower-level command evaluation that handles different command types appropriately.
**Command Type Handling**:
- **Deterministic**: Single evaluation with average randomness (0.5)
- **Odds-based**: Two evaluations (success/failure) weighted by success probability
- **Non-deterministic**: Multiple evaluations with distributed random values, averaged
#### `BasicLookaheadCalculator`
**Purpose**: Recursive lookahead search that finds the best future command sequence and propagates scores backward.
**Features**:
- Uses transposition table to cache previously computed positions
- Handles depth limits and terminal states
- Returns futures for asynchronous computation
- Stores results in transposition table for reuse
### Strategy-Specific Scoring Functions
#### `AttackerScoreForState`
**Purpose**: Calculates state score from attacker perspective based on strategy type.
**Strategy Support**:
- `STRATEGY_ATTACK_CASTLES`: Prioritizes capturing castle positions
- `STRATEGY_ATTACK_UNITS`: Focuses on eliminating defender units
- `STRATEGY_HOLD_CASTLES`: Maintains control of captured castles
- `STRATEGY_CROSS_RIVERS`: Special water crossing objectives
- `STRATEGY_FLEE`: Escape-focused scoring
#### `DefenderScoreForState`
**Purpose**: Calculates state score from defender perspective.
**Strategy Support**:
- `STRATEGY_HOLD_CASTLES`: Defend critical castle positions
- `STRATEGY_SCATTER`: Spread units to avoid elimination
- `STRATEGY_FLEE`: Escape-focused scoring
#### `AttackerUnitsScore`
**Purpose**: Core unit valuation function that calculates total value of all units on the board with contextual modifiers.
**Features**:
- Uses `UnitValue` for individual unit calculations
- Applies distance multipliers based on proximity to objectives
- Handles special cases like undead, VIP units, and scattered defenders
- Incorporates castle bonuses and environmental penalties
### Specialized Strategy Functions
#### `DefenderScatterStrategyScoreForState`
**Purpose**: Implements scatter strategy scoring that rewards defensive units for staying far from enemies and friendlies.
#### `DefenderHoldCastlesStrategyScoreForState`
**Purpose**: Implements castle defense strategy with victory condition scoring.
#### `FleeStrategyScoreForState`
**Purpose**: Implements flee strategy that heavily penalizes remaining on the battlefield.
### Utility Functions
#### `AttackerMultiplierForTargetDistance`
**Purpose**: Calculates distance-based scoring multipliers for attackers based on proximity to priority targets.
**Features**:
- Uses recursive priority list evaluation
- Accounts for occupied vs. unoccupied targets
- Incorporates brave water crossing capabilities
- Uses cached action point distances for efficiency
#### `CommandSorter`
**Purpose**: Comparison function for ranking commands by lookahead score (primary) and immediate score (tiebreaker).
#### `IsDeterministic`
**Purpose**: Determines if a command type has predictable outcomes or requires random simulation.
### Performance and Caching
#### `EffectiveDistanceCache`
**Purpose**: Memoization cache for expensive distance calculations between units and targets.
#### `AttackerScorePerformanceLogger`
**Purpose**: Performance monitoring system that tracks call frequency and timing for `AttackerScoreForState`.
The function architecture supports parallel evaluation, caching, and recursive lookahead while maintaining separation between strategy-specific logic and core evaluation mechanics.
## Decision Tree Data Structures (NEW)
### CommandTreeNode
**Purpose**: Represents a single command execution and its consequences in the decision tree.
**Key Fields**:
- `commandIndex`: Index of the command in the original command list
- `commandType`: Type of command (MOVE, MELEE, END_TURN, etc.)
- `immediateScore`: Score of the game state immediately after this command
- `lookaheadScore`: Best achievable score considering future moves
- `resultingGameState`: Game state after command execution
- `children`: Vector of child nodes representing subsequent possible moves
- `playerId`, `depth`, `isDefender`: Metadata about the command context
**Features**:
- Stores complete game state for each decision point
- Maintains parent-child relationships for tree traversal
- Supports both immediate and lookahead scoring
- Contains metadata for debugging and analysis
### CommandDecisionTree
**Purpose**: Complete decision tree containing all evaluated command paths from a given position.
**Key Fields**:
- `rootNodes`: All possible first moves from the starting position
- `bestCommand`: Pointer to the optimal root command
- `maxDepth`: Maximum lookahead depth of the tree
- `totalNodes`: Total number of nodes in the tree (for statistics)
**Features**:
- Provides complete visibility into AI decision-making process
- Enables analysis of alternative moves and their consequences
- Supports tree statistics and debugging information
- Maintains backward compatibility through `GetBestCommandIndex()`
**Memory Management**:
- Uses `std::unique_ptr` for automatic memory cleanup
- `GameStateW` objects are stored directly (not shared pointers for simplicity)
- Tree structure ensures proper cleanup when nodes go out of scope
### Tree vs. Legacy Approach Comparison
| Aspect | Legacy (Single Best) | Tree-Based (Complete) |
|--------|---------------------|----------------------|
| **Output** | Best command only | Complete decision tree |
| **Memory** | Minimal | Higher (stores all paths) |
| **Analysis** | Limited visibility | Full decision transparency |
| **Debugging** | Single command info | Complete move sequences |
| **Performance** | Slightly faster | Comparable (same calculations) |
| **Compatibility** | Direct usage | Wrapper maintains compatibility |
### Usage Patterns
**For AI Decision Making**:
```cpp
auto treeFuture = BuildDecisionTree(pid, isDefender, depth, maxRepeat,
engine, strategy, utility, settings,
castles, apdCache, alCache, deadline);
CommandDecisionTree tree = treeFuture.get();
size_t bestCommand = tree.bestCommand->commandIndex;
```
**For Analysis and Debugging**:
```cpp
CommandDecisionTree tree = treeFuture.get();
// Examine all possible moves
for (const auto& rootNode : tree.rootNodes) {
std::cout << "Command " << rootNode->commandIndex
<< " Score: " << rootNode->lookaheadScore << std::endl;
// Traverse children to see consequences
for (const auto& child : rootNode->children) {
// ... analyze child moves
}
}
```
**Legacy Compatibility**:
```cpp
// Existing code continues to work unchanged
auto indexScoreFuture = BestCommandIndex(pid, isDefender, ...);
IndexAndScore result = indexScoreFuture.get();
size_t bestCommand = result.index;
```
The tree-based approach provides complete decision transparency while maintaining full backward compatibility with existing AI code.
## MCTS Alternative: Randomness Handling Recommendations
The new MCTS-based AI system is available in `MCTSAI.hpp/.cpp` and provides an alternative to the iterative deepening approach. However, the current MCTS implementation uses simplified randomness handling compared to the sophisticated approach in the original system.
### Current MCTS Limitations
1. **Expansion Phase**: Uses average rolls (0.5) for all commands during tree expansion
2. **Simulation Phase**: Uses random command selection with average rolls
3. **Missing**: No explicit chance nodes for commands with `HasOdds()`
4. **Missing**: No multi-sample evaluation for stochastic commands
### Recommended Improvements: Chance Node Integration
#### 1. **Explicit Chance Nodes** (Highest Priority)
For commands with `HasOdds()`, create explicit chance nodes in the MCTS tree:
```cpp
// During MCTSExpansion
if (descriptor->HasOdds()) {
// Create TWO child nodes: success and failure
auto successNode = CreateMCTSNode(commandIndex, SUCCESS_VARIANT);
auto failureNode = CreateMCTSNode(commandIndex, FAILURE_VARIANT);
// Execute with deterministic rolls (matching original system)
ExecuteWithRoll(successNode, 1.0 - successChance/2.0); // High roll
ExecuteWithRoll(failureNode, (1.0 - successChance)/2.0); // Low roll
// Set probability weights for selection
successNode->probabilityWeight = successChance;
failureNode->probabilityWeight = 1.0 - successChance;
}
```
#### 2. **Weighted Selection for Chance Nodes**
Modify `MCTSSelection` to handle chance nodes:
```cpp
if (node->isChanceNode) {
// Select based on probability distribution, not UCB1
return SelectByProbability(node->children);
} else {
// Normal UCB1 selection for decision nodes
return node->GetBestChild(explorationConstant);
}
```
#### 3. **Probability-Weighted Backpropagation**
Update backpropagation to account for chance node probabilities:
```cpp
void MCTSBackpropagation(MCTSNode* node, double reward) {
while (node) {
node->visitCount++;
// Weight reward by probability for chance nodes
double weightedReward = reward;
if (node->parent && node->parent->isChanceNode) {
weightedReward *= node->probabilityWeight;
}
node->totalReward += weightedReward;
node->averageReward = node->totalReward / node->visitCount;
node = node->parent;
}
}
```
#### 4. **Multi-Sample Commands**
For commands without explicit odds but with randomness, use stratified sampling:
```cpp
// During expansion, create multiple child nodes with different rolls
for (int sample = 0; sample < numSamples; ++sample) {
double roll = static_cast<double>(sample) / (numSamples - 1);
auto sampleNode = CreateMCTSNodeWithRoll(commandIndex, roll);
sampleNode->probabilityWeight = 1.0 / numSamples;
}
```
### Benefits of Chance Node Integration
1. **Accurate Evaluation**: Preserves the sophisticated randomness handling from the original system
2. **Better Convergence**: MCTS can properly explore both success/failure outcomes
3. **Realistic Simulations**: Tree accurately represents game's probability distributions
4. **Comparable Results**: Makes MCTS results directly comparable to iterative deepening
### Implementation Priority
1. **Phase 1**: Add explicit chance nodes for `HasOdds()` commands
2. **Phase 2**: Implement probability-weighted selection and backpropagation
3. **Phase 3**: Add multi-sample support for general stochastic commands
4. **Phase 4**: Optimize performance with lazy expansion of chance nodes
### Alternative: Determinization Approach
If explicit chance nodes prove too complex, consider **determinization**:
- Run multiple MCTS trees with different fixed random seeds
- Aggregate results across all determinizations
- Simpler to implement but potentially less accurate than explicit chance nodes
### Switching Between AI Systems
Both AI systems (`IterativeDeepeningAI` and `MCTSAI`) implement compatible interfaces. The algorithm is selected at **runtime** via the ShardokAIClient constructor:
```cpp
// Using Iterative Deepening (default)
ShardokAIClient client(playerId, isDefender, hexMap, settings);
// Or explicitly:
ShardokAIClient client(playerId, isDefender, hexMap, settings,
AIAlgorithmType::ITERATIVE_DEEPENING);
// Using MCTS
ShardokAIClient client(playerId, isDefender, hexMap, settings,
AIAlgorithmType::MCTS);
// Note: MCTS configuration can be customized via MCTSConfig:
// - maxIterations: 10000 (max MCTS iterations per move)
// - maxSimulationDepth: 10 (depth for rollout phase)
// - maxTreeDepth: 20 (max tree depth to prevent stack overflow)
// - explorationConstant: 1.414 (UCB1 exploration vs exploitation)
// - useMultithreading: true (APD cache is thread-safe with TLS + mutex protection)
// - numThreads: 4
```
The selection is made per AI client instance, allowing different algorithms for different players or game situations within the same server process.
#### Direct AI Usage (Lower Level)
Both AI systems can also be used directly:
```cpp
// Using Iterative Deepening directly
auto iterativeAI = IterativeDeepeningAI(playerId, isDefender, strategy,
castleCoords, apdCache, alCache);
auto result = iterativeAI.IterativeSearch(settings, state, commands, budget);
// Using MCTS directly
auto mctsAI = MCTSAI(playerId, isDefender, strategy,
castleCoords, apdCache, alCache);
auto result = mctsAI.Search(settings, state, commands, budget);
```
#### Algorithm Comparison
| Feature | Iterative Deepening | MCTS |
|---------|-------------------|------|
| **Randomness Handling** | Sophisticated (chance nodes, multi-sample) | Simplified (average rolls) |
| **Performance** | Single-threaded | Multithreaded |
| **Search Type** | Fixed depth with iterative deepening | Adaptive with time budget |
| **Memory Usage** | Lower | Higher (maintains tree) |
| **Max Tree Depth** | Limited by lookahead setting | Limited by `maxTreeDepth` config (default: 20) |
| **Tree Destruction** | Not applicable | Iterative (avoids stack overflow) |
| **Best For** | Precise evaluation, production | Performance testing, fast decisions |
The MCTS implementation provides a solid foundation. Known limitations:
1. **Randomness Handling**: Simplified compared to iterative deepening (no explicit chance nodes)
2. **Simulation Quality**: Uses random rollouts instead of sophisticated evaluation
Note: The APD cache is fully thread-safe using thread-local storage and mutex-protected shared cache.
<<<<<<< HEAD
Adding chance node handling and ensuring thread safety would make it a superior replacement for the iterative deepening approach while maintaining the sophisticated randomness evaluation that makes the current system effective.
## MCTS Configuration Options
The MCTS AI system provides extensive configuration through the `MCTSConfig` structure:
### Core MCTS Parameters
```cpp
struct MCTSConfig {
double explorationConstant = 1.414; // UCB1 constant (sqrt(2) by default)
int maxSimulationDepth = 1000; // Maximum depth for rollout
int maxTreeDepth = 2000; // Maximum tree depth to prevent stack overflow
bool useMultithreading = true; // Enable parallel MCTS
int numThreads = 16; // Number of threads for parallel MCTS (when enabled)
MCTSSimulationPolicy simulationPolicy = MCTSSimulationPolicy::BEST_IMMEDIATE;
bool enableTranspositionDetection = true; // Enable pruning of duplicate states
double immediateScoreTieBreakThreshold = 5.0; // When avg rewards differ by less than this, prefer higher immediate score
double visitCountTolerance = 0.05; // Treat visit counts as equal if within this % of best count
bool enableImmediateScoreInUCB1 = true; // Apply immediate score tie-breaking in UCB1 selection too
};
```
### Exploration vs Exploitation
- **`explorationConstant`**: Controls the exploration vs exploitation balance in UCB1 selection
- Higher values (>1.414): More exploration of unvisited nodes
- Lower values (<1.414): More exploitation of known good moves
- Default: 1.414 (√2, theoretical optimum for UCB1)
### Tree Structure Limits
- **`maxTreeDepth`**: Prevents stack overflow in deep game trees
- Default: 2000 (very high limit for most tactical scenarios)
- Terminal detection stops expansion when this depth is reached
- **`maxSimulationDepth`**: Controls rollout length during simulation phase
- Default: 1000 (sufficient for most tactical scenarios)
- Longer simulations provide more accurate estimates but use more time
### Multithreading Configuration
- **`useMultithreading`**: Enable/disable parallel MCTS execution
- Default: true (takes advantage of modern multi-core CPUs)
- Requires thread-safe game engine and scoring components
- **`numThreads`**: Number of worker threads for parallel tree building
- Default: 16 (adjust based on available CPU cores)
- More threads can improve search speed but with diminishing returns
### Simulation Policies
The `MCTSSimulationPolicy` enum controls how commands are selected during the rollout phase:
- **`RANDOM`**: Pure random selection from all available commands
- Fastest but least informed simulations
- Good baseline for testing MCTS convergence
- **`FILTERED_RANDOM`**: Random selection from AICommandFilter-approved commands
- Eliminates obviously bad moves (moving away from objectives, etc.)
- Better simulation quality with minimal overhead
- **`BEST_IMMEDIATE`**: Always choose command with highest immediate score
- Most informed simulations
- Slower but higher quality rollouts
- Default setting for production use
- **`WEIGHTED_BEST_IMMEDIATE`**: Random selection weighted by immediate score ranking
- Balances exploration with informed choice
- Alternative to pure greedy selection
### Transposition Detection
- **`enableTranspositionDetection`**: Enable pruning of duplicate game states
- Default: true (improves search efficiency)
- Uses hash-based state identification
- Prevents wasted computation on equivalent positions reached via different move sequences
### Immediate Score Tie-Breaking
These settings address MCTS's tendency to choose indirect paths when direct paths lead to the same outcome:
- **`immediateScoreTieBreakThreshold`**: Score difference threshold for tie-breaking
- Default: 5.0 (when backpropagated rewards differ by less than this, prefer immediate score)
- Helps AI choose direct moves over equivalent indirect sequences
- Improves user experience by reducing unnecessary intermediate moves
- **`visitCountTolerance`**: Visit count equality threshold for tie-breaking
- Default: 0.05 (5% tolerance - visit counts within this percentage are considered equal)
- Prevents minor visit count differences from overriding immediate score preferences
- **`enableImmediateScoreInUCB1`**: Apply immediate score tie-breaking during exploration
- Default: true (consistent tie-breaking in both exploration and final selection)
- When UCB1 values are very close, prefer nodes with higher immediate scores
- Improves convergence on direct paths to objectives
### Usage Example
```cpp
// Custom MCTS configuration for performance testing
MCTSConfig config;
config.explorationConstant = 2.0; // More exploration
config.simulationPolicy = MCTSSimulationPolicy::FILTERED_RANDOM; // Faster rollouts
config.numThreads = 8; // Reduce threads for testing environment
config.immediateScoreTieBreakThreshold = 10.0; // More aggressive tie-breaking
MCTSAI ai(playerId, isDefender, strategy, castleCoords, apdCache, alCache, config);
```
### Configuration Recommendations
**For Production Use:**
- Use default settings for balanced performance and quality
- Consider reducing `numThreads` on systems with limited CPU cores
- `BEST_IMMEDIATE` simulation policy provides highest quality decisions
**For Performance Testing:**
- `FILTERED_RANDOM` or `RANDOM` simulation policies for faster rollouts
- Lower `explorationConstant` (1.0) for more exploitation
- Disable transposition detection for baseline comparison
**For Analysis/Debugging:**
- Single-threaded execution (`useMultithreading = false`) for deterministic results
- Higher `immediateScoreTieBreakThreshold` to emphasize direct paths
- `BEST_IMMEDIATE` simulation for most predictable behavior
The configuration system allows fine-tuning MCTS behavior for different scenarios while maintaining compatibility with the existing AI infrastructure.
This scoring system provides a robust framework for tactical AI decision-making, balancing immediate tactical gains with strategic objectives while handling the uncertainty inherent in combat outcomes.
+1 -55
View File
@@ -154,7 +154,6 @@ cc_library(
hdrs = ["AICommandFilter.hpp"],
copts = COPTS,
visibility = [
"//src/main/cpp/net/eagle0/shardok/ai/mcts:__pkg__",
"//src/main/cpp/net/eagle0/shardok/ai_performance_runner:__pkg__",
"//src/test/cpp/net/eagle0/shardok/ai:__pkg__",
],
@@ -189,7 +188,6 @@ cc_library(
hdrs = ["AIScoreCalculator.hpp"],
copts = COPTS,
visibility = [
"//src/main/cpp/net/eagle0/shardok/ai/mcts:__pkg__",
"//src/main/cpp/net/eagle0/shardok/ai_performance_runner:__pkg__",
"//src/test/cpp/net/eagle0/shardok/ai:__pkg__",
],
@@ -211,7 +209,6 @@ cc_library(
hdrs = ["AIStrategy.hpp"],
copts = COPTS,
visibility = [
"//src/main/cpp/net/eagle0/shardok/ai/mcts:__pkg__",
"//src/main/cpp/net/eagle0/shardok/ai_performance_runner:__pkg__",
"//src/test/cpp/net/eagle0/shardok/ai:__subpackages__",
],
@@ -299,7 +296,6 @@ cc_library(
hdrs = ["AITimeBudget.hpp"],
copts = COPTS,
visibility = [
"//src/main/cpp/net/eagle0/shardok/ai/mcts:__pkg__",
"//src/main/cpp/net/eagle0/shardok/ai_performance_runner:__pkg__",
"//src/test/cpp/net/eagle0/shardok/ai:__pkg__",
],
@@ -318,7 +314,6 @@ cc_library(
hdrs = ["IterativeDeepeningAI.hpp"],
copts = COPTS,
visibility = [
"//src/main/cpp/net/eagle0/shardok/ai/mcts:__pkg__",
"//src/main/cpp/net/eagle0/shardok/ai_performance_runner:__pkg__",
"//src/test/cpp/net/eagle0/shardok/ai:__pkg__",
],
@@ -335,53 +330,6 @@ cc_library(
],
)
cc_library(
name = "ai_config",
hdrs = ["AIConfig.hpp"],
copts = COPTS,
visibility = [
"//src/main/cpp/net/eagle0/shardok/ai_performance_runner:__pkg__",
"//src/test/cpp/net/eagle0/shardok/ai:__pkg__",
],
)
cc_library(
name = "ai_mcts_clean",
srcs = ["MCTSCleanAI.cpp"],
hdrs = ["MCTSCleanAI.hpp"],
copts = COPTS,
visibility = [
"//src/main/cpp/net/eagle0/shardok/ai_performance_runner:__pkg__",
"//src/test/cpp/net/eagle0/shardok/ai:__pkg__",
],
deps = [
":ai_attack_locations",
":ai_config",
":ai_iterative_deepening", # For SearchResult compatibility
":ai_score_calculator",
":ai_strategy",
":ai_time_budget",
"//src/main/cpp/net/eagle0/common:random_generator",
"//src/main/cpp/net/eagle0/common:sequence_random_generator",
"//src/main/cpp/net/eagle0/shardok/library:engine",
"//src/main/cpp/net/eagle0/shardok/library:game_state_w",
"//src/main/cpp/net/eagle0/shardok/library/action_point_distances:action_point_distances_cache",
"//src/main/cpp/net/eagle0/shardok/library/settings:game_settings",
"//src/main/protobuf/net/eagle0/shardok/api:command_descriptor_cc_proto",
"//src/main/protobuf/net/eagle0/shardok/common:command_type_cc_proto",
],
)
cc_library(
name = "ai_config",
hdrs = ["AIConfig.hpp"],
copts = COPTS,
visibility = [
"//src/main/cpp/net/eagle0/shardok/ai_performance_runner:__pkg__",
"//src/test/cpp/net/eagle0/shardok/ai:__pkg__",
],
)
cc_library(
name = "shardok_ai_client",
srcs = ["ShardokAIClient.cpp"],
@@ -390,15 +338,13 @@ cc_library(
visibility = ["//visibility:public"],
deps = [
":ai_attacker_strategy_selector",
":ai_config",
":ai_defender_strategy_selector",
":ai_flee_decision_calculator",
":ai_iterative_deepening", # Direct dependency for runtime selection
":ai_iterative_deepening",
":ai_score_calculator",
":ai_time_budget",
":ai_water_crossing_command_chooser",
"//src/main/cpp/net/eagle0/common:time_utils",
"//src/main/cpp/net/eagle0/shardok/ai/mcts:mcts_ai", # Direct dependency for runtime selection
"//src/main/cpp/net/eagle0/shardok/library/action_point_distances",
"//src/main/cpp/net/eagle0/shardok/library/action_point_distances:action_point_distances_cache",
"@com_google_protobuf//:protobuf",
File diff suppressed because it is too large Load Diff
@@ -1,105 +0,0 @@
//
// MCTS-based AI system for Shardok
// Alternative to IterativeDeepeningAI using Monte Carlo Tree Search
//
#ifndef EAGLE0_MCTSAI_HPP
#define EAGLE0_MCTSAI_HPP
#include <chrono>
#include <future>
#include <memory>
#include <vector>
#include "AIStrategy.hpp"
#include "AITimeBudget.hpp"
#include "IterativeDeepeningAI.hpp" // For SearchResult compatibility
#include "src/main/cpp/net/eagle0/shardok/library/GameStateW.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/ShardokCTypes.h"
#include "src/main/cpp/net/eagle0/shardok/library/action_point_distances/ActionPointDistancesCache.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/settings/GameSettings.hpp"
#include "src/main/protobuf/net/eagle0/shardok/api/command_descriptor.pb.h"
#include "src/main/protobuf/net/eagle0/shardok/common/command_type.pb.h"
namespace shardok {
// Forward declarations
class ShardokEngine;
struct MCTSNode;
// Configuration for MCTS algorithm
struct MCTSConfig {
double explorationConstant = 1.414; // UCB1 constant (sqrt(2) by default)
int maxPlayerFlips = 1; // Number of player turn changes to evaluate
bool useMultithreading = true; // Enable parallel MCTS
int numThreads = 16; // Number of threads for parallel MCTS (when enabled)
};
class MCTSAI {
public:
using CommandProto = net::eagle0::shardok::api::CommandDescriptor;
using SearchResult = IterativeDeepeningAI::SearchResult;
MCTSAI(PlayerId playerId,
bool isDefender,
AIStrategy strategy,
const CoordsSet& castleCoords,
const APDCache& apdCache,
const ALCache& alCache,
MCTSConfig config = MCTSConfig{});
// Main search interface - compatible with IterativeDeepeningAI
[[nodiscard]] auto Search(
const GameSettingsSPtr& settings,
const GameStateW& state,
const std::vector<CommandProto>& commands,
const AITimeBudget& budget) const -> SearchResult;
// Get/set configuration
[[nodiscard]] auto GetConfig() const -> const MCTSConfig& { return config; }
void SetConfig(const MCTSConfig& newConfig) { config = newConfig; }
private:
PlayerId playerId;
bool isDefender;
AIStrategy strategy;
const CoordsSet& castleCoords;
const APDCache& apdCache;
const ALCache& alCache;
MCTSConfig config;
// Internal MCTS tree building
[[nodiscard]] auto BuildMCTSTree(
const ShardokEngine& engine,
const SettingsGetter& settingsGetter,
std::chrono::steady_clock::time_point deadline) const -> std::unique_ptr<MCTSNode>;
// MCTS algorithm phases
auto MCTSSelection(MCTSNode* root) const -> MCTSNode*;
auto MCTSExpansion(
MCTSNode* node,
const ShardokEngine& engine,
const SettingsGetter& settingsGetter) const -> MCTSNode*;
auto MCTSSimulation(
const ShardokEngine& engineState,
PlayerId currentPlayer,
const SettingsGetter& settingsGetter) const -> double;
auto MCTSBackpropagation(MCTSNode* node, double reward) const -> void;
// Helper functions
[[nodiscard]] auto IsTerminalForPlayer(
const GameStateW& gameState,
PlayerId currentPlayer,
const SettingsGetter& settingsGetter) const -> bool;
// Get coordinate information for logging
[[nodiscard]] std::string GetCommandCoordinateInfo(
net::eagle0::shardok::common::CommandType commandType,
size_t commandIndex,
const GameStateW& gameState,
const GameSettingsSPtr& settings) const;
};
} // namespace shardok
#endif // EAGLE0_MCTSAI_HPP
@@ -1,292 +0,0 @@
#include "MCTSCleanAI.hpp"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <limits>
#include "AIScoreCalculator.hpp"
#include "src/main/cpp/net/eagle0/common/SequenceRandomGenerator.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/ShardokEngine.hpp"
#include "src/main/protobuf/net/eagle0/shardok/common/command_type.pb.h"
namespace shardok {
MCTSCleanAI::MCTSCleanAI(
PlayerId playerId,
bool isDefender,
const AIStrategy& strategy,
const CoordsSet& castleCoords,
const APDCache& apdCache,
const ALCache& alCache)
: ourPlayerId(playerId),
isDefender(isDefender),
strategy(strategy),
castleCoords(castleCoords),
apdCache(apdCache),
alCache(alCache),
rng(std::chrono::steady_clock::now().time_since_epoch().count()) {}
IterativeDeepeningAI::SearchResult MCTSCleanAI::Search(
const GameSettingsSPtr& settings,
const GameStateW& gameState,
const std::vector<CommandProto>& availableCommands,
const AITimeBudget& timeBudget) {
const auto startTime = std::chrono::steady_clock::now();
const auto maxTime = std::chrono::duration_cast<std::chrono::milliseconds>(
timeBudget.remainingBudget * 0.9); // 90% of budget
// Create root node
auto root = std::make_unique<MCTSNode>();
root->resultingGameState = gameState;
root->currentPlayer = ourPlayerId;
root->isOurTurn = true;
root->playerFlipsFromRoot = 0;
// Initialize untried commands for root
for (size_t i = 0; i < availableCommands.size(); ++i) { root->untriedCommands.push_back(i); }
int iterationCount = 0;
// Main MCTS loop
while (std::chrono::steady_clock::now() - startTime < maxTime) {
// 1. Selection - find leaf node to expand
MCTSNode* selected = Selection(root.get());
// 2. Expansion - add new child if possible
MCTSNode* expanded = Expansion(selected, settings, availableCommands);
// 3. Simulation - run random playout
double reward = Simulation(
expanded->resultingGameState,
expanded->currentPlayer,
expanded->playerFlipsFromRoot,
settings);
// 4. Backpropagation - update statistics
Backpropagation(expanded, reward);
iterationCount++;
// Early exit if all commands tried
if (root->untriedCommands.empty() && root->children.size() == availableCommands.size()) {
bool allChildrenFullyExplored = true;
for (const auto& child : root->children) {
if (child->visitCount < 10) { // Minimum visits per child
allChildrenFullyExplored = false;
break;
}
}
if (allChildrenFullyExplored) { break; }
}
}
// Select best command based on visit counts
size_t bestCommandIndex = 0;
int maxVisits = 0;
for (size_t i = 0; i < root->children.size(); ++i) {
if (root->children[i]->visitCount > maxVisits) {
maxVisits = root->children[i]->visitCount;
bestCommandIndex = root->children[i]->commandIndex;
}
}
// Create search result
IterativeDeepeningAI::SearchResult result;
result.bestCommandIndex = bestCommandIndex;
result.availableCommandCount = availableCommands.size();
result.depthAchieved = maxPlayerFlips; // Our max search depth
result.commandCountEvaluated = iterationCount;
result.completionReason = EvaluationCompletionReason::RAN_OUT_OF_TIME;
printf("MCTS Clean: %d iterations, best command %zu with %d visits\n",
iterationCount,
bestCommandIndex,
maxVisits);
return result;
}
// Selection - navigate to leaf using UCB1
MCTSCleanAI::MCTSNode* MCTSCleanAI::Selection(MCTSNode* root) {
MCTSNode* current = root;
while (!current->children.empty() && current->untriedCommands.empty()) {
current = SelectChild(current);
}
return current;
}
// Expansion - add new child node
MCTSCleanAI::MCTSNode* MCTSCleanAI::Expansion(
MCTSNode* node,
const GameSettingsSPtr& settings,
const std::vector<CommandProto>& availableCommands) {
// If we've reached max player flips, don't expand
if (node->playerFlipsFromRoot >= maxPlayerFlips) { return node; }
// If no untried commands, return current node
if (node->untriedCommands.empty()) { return node; }
// Pick an untried command
size_t cmdIndex = PickUntriedCommand(node);
// Create child engine and execute command
auto childEngine = CreateEngine(node->resultingGameState, settings);
PlayerId playerBefore = childEngine->GetCurrentPlayerId();
// Use sequence random generator for deterministic results
auto averageGenerator = std::make_shared<SequenceRandomGenerator>(std::vector<double>{0.5});
childEngine->PostCommand(playerBefore, cmdIndex, averageGenerator);
PlayerId playerAfter = childEngine->GetCurrentPlayerId();
// Create child node
bool isOurTurnAfter = (playerAfter == ourPlayerId);
auto child = std::make_unique<MCTSNode>(
cmdIndex,
availableCommands[cmdIndex].type(),
playerAfter,
isOurTurnAfter);
child->resultingGameState = childEngine->GetCurrentGameState();
child->parent = node;
// Track player flips
child->playerFlipsFromRoot = node->playerFlipsFromRoot;
if (playerBefore != playerAfter) { child->playerFlipsFromRoot++; }
// Initialize child's untried commands if we haven't hit max flips
if (child->playerFlipsFromRoot < maxPlayerFlips) {
auto childCommands = childEngine->GetAvailableCommandsForAIPlayer(playerAfter);
for (size_t i = 0; i < childCommands->size(); ++i) { child->untriedCommands.push_back(i); }
}
MCTSNode* childPtr = child.get();
node->children.push_back(std::move(child));
return childPtr;
}
// Simulation - run random playout from current state
double MCTSCleanAI::Simulation(
const GameStateW& startState,
PlayerId /* startPlayer */,
int startFlips,
const GameSettingsSPtr& settings) {
auto simEngine = CreateEngine(startState, settings);
int currentFlips = startFlips;
auto averageGenerator = std::make_shared<SequenceRandomGenerator>(std::vector<double>{0.5});
while (currentFlips < maxPlayerFlips) {
PlayerId currentPlayer = simEngine->GetCurrentPlayerId();
bool isOurTurn = (currentPlayer == ourPlayerId);
// Get available commands
auto commands = simEngine->GetAvailableCommandsForAIPlayer(currentPlayer);
if (commands->empty()) break;
// Pick best command based on whose turn it is
size_t bestCmd = 0;
double bestScore = isOurTurn ? -std::numeric_limits<double>::infinity()
: std::numeric_limits<double>::infinity();
for (size_t i = 0; i < commands->size(); ++i) {
auto testEngine = CreateEngine(simEngine->GetCurrentGameState(), settings);
testEngine->PostCommand(currentPlayer, i, averageGenerator);
// Always score from our perspective
double score = ScoreFromOurPerspective(
testEngine->GetCurrentGameState(),
settings->GetGetter());
// Our turn: maximize our score, Opponent turn: minimize our score
bool shouldSelect = isOurTurn ? (score > bestScore) : (score < bestScore);
if (shouldSelect) {
bestScore = score;
bestCmd = i;
}
}
// Execute chosen command
PlayerId playerBefore = simEngine->GetCurrentPlayerId();
simEngine->PostCommand(currentPlayer, bestCmd, averageGenerator);
PlayerId playerAfter = simEngine->GetCurrentPlayerId();
// Track player flips
if (playerBefore != playerAfter) { currentFlips++; }
}
return ScoreFromOurPerspective(simEngine->GetCurrentGameState(), settings->GetGetter());
}
// Backpropagation - update node statistics
void MCTSCleanAI::Backpropagation(MCTSNode* node, double score) {
while (node != nullptr) {
node->visitCount++;
node->totalScore += score; // Always from our perspective
node->averageScore = node->totalScore / node->visitCount;
node = node->parent;
}
}
// Helper functions
double MCTSCleanAI::ScoreFromOurPerspective(
const GameStateW& gameState,
const SettingsGetter& settingsGetter) {
return AIScoreCalculator::GuessedStateScore(
isDefender,
gameState,
strategy,
castleCoords,
settingsGetter,
apdCache,
alCache);
}
MCTSCleanAI::MCTSNode* MCTSCleanAI::SelectChild(MCTSNode* node) {
MCTSNode* bestChild = nullptr;
double bestUCB1 = node->isOurTurn ? -std::numeric_limits<double>::infinity()
: std::numeric_limits<double>::infinity();
for (const auto& child : node->children) {
double exploitation = child->averageScore;
double exploration =
explorationConstant * std::sqrt(std::log(node->visitCount) / child->visitCount);
double ucb1 = exploitation + exploration;
// Our turn: pick highest UCB1, Opponent turn: pick lowest UCB1
bool shouldSelect = node->isOurTurn ? (ucb1 > bestUCB1) : (ucb1 < bestUCB1);
if (shouldSelect) {
bestUCB1 = ucb1;
bestChild = child.get();
}
}
return bestChild;
}
size_t MCTSCleanAI::PickUntriedCommand(MCTSNode* node) {
if (node->untriedCommands.empty()) {
return 0; // Should not happen
}
// Pick random untried command
std::uniform_int_distribution<size_t> indexDist(0, node->untriedCommands.size() - 1);
size_t randomIndex = indexDist(rng);
size_t cmdIndex = node->untriedCommands[randomIndex];
node->untriedCommands.erase(node->untriedCommands.begin() + randomIndex);
return cmdIndex;
}
std::shared_ptr<ShardokEngine> MCTSCleanAI::CreateEngine(
const GameStateW& gameState,
const GameSettingsSPtr& settings) {
return std::make_shared<ShardokEngine>(settings, gameState);
}
} // namespace shardok
@@ -1,133 +0,0 @@
#pragma once
#include <memory>
#include <random>
#include <vector>
#include "AIAttackLocations.hpp"
#include "AIConfig.hpp"
#include "AIStrategy.hpp"
#include "AITimeBudget.hpp"
#include "IterativeDeepeningAI.hpp" // For SearchResult
#include "src/main/cpp/net/eagle0/common/RandomGenerator.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/GameStateW.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/action_point_distances/ActionPointDistancesCache.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/map/CoordsSet.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/settings/GameSettings.hpp"
#include "src/main/protobuf/net/eagle0/shardok/api/command_descriptor.pb.h"
#include "src/main/protobuf/net/eagle0/shardok/common/command_type.pb.h"
namespace shardok {
// Forward declare cache type aliases
using APDCache = std::shared_ptr<ActionPointDistancesCache>;
using ALCache = std::unique_ptr<AttackLocationsCache>;
} // namespace shardok
namespace shardok {
// Clean MCTS implementation following the design document
class MCTSCleanAI {
public:
// Clean node structure with single perspective scoring
struct MCTSNode {
// Command that led to this state
size_t commandIndex;
net::eagle0::shardok::common::CommandType commandType;
// Game state after executing the command
GameStateW resultingGameState;
PlayerId currentPlayer; // Whose turn it is in this state
// Tree position
int playerFlipsFromRoot; // Number of player changes from root
bool isOurTurn; // currentPlayer == our AI's playerId
// MCTS statistics (always from our perspective)
int visitCount = 0;
double totalScore = 0.0;
double averageScore = 0.0;
// Tree structure
std::vector<std::unique_ptr<MCTSNode>> children;
std::vector<size_t> untriedCommands;
MCTSNode* parent = nullptr;
// Constructor
MCTSNode(
size_t cmdIndex,
net::eagle0::shardok::common::CommandType cmdType,
PlayerId currentPlayerId,
bool ourTurn)
: commandIndex(cmdIndex),
commandType(cmdType),
currentPlayer(currentPlayerId),
playerFlipsFromRoot(0),
isOurTurn(ourTurn) {}
// Root constructor
MCTSNode()
: commandIndex(0),
commandType(net::eagle0::shardok::common::UNKNOWN_COMMAND),
currentPlayer(0),
playerFlipsFromRoot(0),
isOurTurn(true) {}
};
MCTSCleanAI(
PlayerId playerId,
bool isDefender,
const AIStrategy& strategy,
const CoordsSet& castleCoords,
const APDCache& apdCache,
const ALCache& alCache);
// Main search function compatible with existing interface
IterativeDeepeningAI::SearchResult Search(
const GameSettingsSPtr& settings,
const GameStateW& gameState,
const std::vector<CommandProto>& availableCommands,
const AITimeBudget& timeBudget);
private:
PlayerId ourPlayerId;
bool isDefender;
AIStrategy strategy;
CoordsSet castleCoords;
const APDCache& apdCache;
const ALCache& alCache;
// MCTS parameters
static constexpr int maxPlayerFlips = 5; // Stop after N player changes
static constexpr double explorationConstant = 1.414; // sqrt(2)
// Random number generation
std::mt19937 rng;
std::uniform_real_distribution<double> uniformDist{0.0, 1.0};
// Core MCTS algorithms
MCTSNode* Selection(MCTSNode* root);
MCTSNode* Expansion(
MCTSNode* node,
const GameSettingsSPtr& settings,
const std::vector<CommandProto>& availableCommands);
double Simulation(
const GameStateW& startState,
PlayerId startPlayer,
int startFlips,
const GameSettingsSPtr& settings);
void Backpropagation(MCTSNode* node, double score);
// Helper functions
double ScoreFromOurPerspective(
const GameStateW& gameState,
const SettingsGetter& settingsGetter);
MCTSNode* SelectChild(MCTSNode* node);
size_t PickUntriedCommand(MCTSNode* node);
std::shared_ptr<ShardokEngine> CreateEngine(
const GameStateW& gameState,
const GameSettingsSPtr& settings);
};
} // namespace shardok
@@ -1,147 +0,0 @@
# MCTS Player-Flip Depth System Design
## Overview
Replace command-count-based depth limits with player-turn-aware depth that naturally aligns with game structure. All nodes evaluate to the same player-flip depth to ensure comparable scores.
## Core Concepts
### Player-Flip Depth
- **Depth 1**: Evaluate until first player flip (complete our turn)
- **Depth 2**: Continue through opponent's full turn
- **Depth 3**: Continue through our next full turn
- **Depth N**: N complete player turn changes
### Minimax Selection
- **Always evaluate from original AI's perspective**
- **Our turn**: Select moves that maximize our score
- **Opponent's turn**: Select moves that minimize our score
- Same backpropagation value regardless of whose turn
## Implementation Plan
### 1. Configuration Changes
```cpp
struct MCTSConfig {
double explorationConstant = 1.414;
int maxPlayerFlips = 2; // How many player changes to evaluate
bool useMultithreading = true;
int numThreads = 16;
// REMOVED: maxTreeDepth - all nodes go to same player-flip depth
// REMOVED: maxSimulationDepth - replaced by maxPlayerFlips
};
```
### 2. Node Structure Updates
```cpp
struct MCTSNode {
// Existing fields...
// New fields for player-flip tracking
int playerFlipsFromRoot = 0;
bool isMaximizingPlayer = true; // true = our turn, false = opponent's
// Modified selection for minimax
MCTSNode* GetBestChild(double explorationConstant) {
if (isMaximizingPlayer) {
return GetChildWithHighestUCB1(explorationConstant);
} else {
return GetChildWithLowestUCB1(explorationConstant);
}
}
};
```
### 3. Expansion Rules
- **Continue expanding** until reaching `maxPlayerFlips` player changes
- **No arbitrary depth limit** - accept theoretical stack overflow risk
- **Mark as terminal** only when:
- Game is over
- Reached `maxPlayerFlips` player changes
- No available commands
### 4. Key Implementation Details
#### Terminal Detection
```cpp
bool IsTerminalForExpansion() {
return playerFlipsFromRoot >= maxPlayerFlips ||
gameIsOver ||
noCommandsAvailable;
}
```
#### Player Tracking
```cpp
// When expanding END_TURN or END_PLAYER_SETUP
child->playerFlipsFromRoot = parent->playerFlipsFromRoot + 1;
child->isMaximizingPlayer = !parent->isMaximizingPlayer;
```
#### UCB1 for Minimax
- Maximizing player: Choose highest UCB1
- Minimizing player: Choose lowest UCB1
- Unvisited nodes: Extreme values to force exploration
### 5. Simulation Strategy
Simulations run until `maxPlayerFlips` is reached:
- Random moves for both players
- Stop at player-flip boundaries
- Always evaluate from original AI perspective
## Benefits
### Consistent Evaluation
- All leaf nodes at same player-flip depth
- Scores are directly comparable
- No apples-to-oranges comparison issues
### Natural Game Structure
- Respects turn boundaries
- Complete tactical sequences evaluated
- Opponent responses properly modeled
### Strategic Depth Control
- **Setup/Early**: `maxPlayerFlips = 1` (fast, local tactics)
- **Mid-game**: `maxPlayerFlips = 2` (balanced)
- **Critical**: `maxPlayerFlips = 3+` (deep strategy)
## Implementation Order
1. **Phase 1**: Update MCTSConfig
- Remove `maxTreeDepth` and `maxSimulationDepth`
- Add `maxPlayerFlips`
2. **Phase 2**: Modify MCTSNode
- Add `playerFlipsFromRoot` and `isMaximizingPlayer`
- Update child selection for minimax
3. **Phase 3**: Update Expansion
- Track player flips
- Remove depth-based termination
- Only terminate at player-flip boundaries
4. **Phase 4**: Fix Selection
- Implement minimax selection based on `isMaximizingPlayer`
- Modify UCB1 interpretation
5. **Phase 5**: Update Simulation
- Run until `maxPlayerFlips` reached
- Handle both player perspectives
## Testing Strategy
1. Verify all evaluations reach same player-flip depth
2. Confirm opponent chooses minimizing moves
3. Test with different `maxPlayerFlips` settings
4. Validate score consistency across tree
## Notes
- Stack overflow risk accepted for evaluation consistency
- Each unit can make multiple moves per turn (move + scout + attack)
- Maximum ~10 units per player limits practical depth
- END_TURN and END_PLAYER_SETUP both count as player flips
@@ -13,13 +13,11 @@
#include <google/protobuf/util/message_differencer.h>
#include "AIAttackerStrategySelector.hpp"
#include "AIConfig.hpp" // Must come before other AI includes
#include "AIDefenderStrategySelector.hpp"
#include "AIFleeDecisionCalculator.hpp"
#include "AIScoreUtilities.hpp"
#include "AITimeBudget.hpp"
#include "IterativeDeepeningAI.hpp"
#include "mcts/MCTSAI.hpp"
#include "src/main/cpp/net/eagle0/common/TimeUtils.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/util/HexMapUtils.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/view_filters/GameStateGuesser.hpp"
@@ -44,11 +42,9 @@ ShardokAIClient::ShardokAIClient(
const PlayerId playerId,
const bool isDefender,
const HexMap *hexMap,
const SettingsGetter &settings,
const AIAlgorithmType aiAlgorithmType)
const SettingsGetter &settings)
: playerId(playerId),
isDefender(isDefender),
aiAlgorithmType(aiAlgorithmType),
alCache(std::make_unique<AttackLocationsCache>(hexMap, settings)),
waterCrossingCommandChooser(playerId, apdCache) {
// Pre-generate the most common cache entries for better performance
@@ -125,19 +121,11 @@ auto ShardokAIClient::StandardChooseCommandIndex(
waterCrossingCommandChooser,
realAvailableCommands);
// AI implementation chosen at runtime via constructor parameter
IterativeDeepeningAI::SearchResult search_result;
if (aiAlgorithmType == AIAlgorithmType::MCTS) {
// Using Monte Carlo Tree Search AI
MCTSAI ai(playerId, isDefender, strategy, castleCoords, apdCache, alCache);
search_result = ai.Search(settings, guessedState, realAvailableCommands, timeBudget);
} else {
// Using Iterative Deepening AI (default)
IterativeDeepeningAI ai(playerId, isDefender, strategy, castleCoords, apdCache, alCache);
search_result =
ai.IterativeSearch(settings, guessedState, realAvailableCommands, timeBudget);
}
// Use iterative deepening AI for Phase 2 implementation
IterativeDeepeningAI
iterativeAI(playerId, isDefender, strategy, castleCoords, apdCache, alCache);
auto search_result =
iterativeAI.IterativeSearch(settings, guessedState, realAvailableCommands, timeBudget);
CommandChoiceResults result{};
result.chosenIndex = search_result.bestCommandIndex;
@@ -12,7 +12,6 @@
#include <vector>
#include "src/main/cpp/net/eagle0/common/RandomGenerator.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AIConfig.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AIScoreCalculator.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AITimeBudget.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AIWaterCrossingCommandChooser.hpp"
@@ -39,7 +38,6 @@ class ShardokAIClient {
private:
const PlayerId playerId;
const bool isDefender;
const AIAlgorithmType aiAlgorithmType;
APDCache apdCache = std::make_shared<ActionPointDistancesCache>();
ALCache alCache;
@@ -69,8 +67,7 @@ public:
PlayerId playerId,
bool isDefender,
const HexMap* hexMap,
const SettingsGetter& settings,
AIAlgorithmType aiAlgorithmType = AIAlgorithmType::ITERATIVE_DEEPENING);
const SettingsGetter& settings);
~ShardokAIClient() = default;
[[nodiscard]] auto GetPlayerId() const -> PlayerId { return playerId; }
@@ -1,29 +0,0 @@
load("//tools:copts.bzl", "COPTS")
cc_library(
name = "mcts_ai",
srcs = ["MCTSAI.cpp"],
hdrs = ["MCTSAI.hpp"],
copts = COPTS,
visibility = [
"//src/main/cpp/net/eagle0/shardok/ai:__pkg__",
"//src/main/cpp/net/eagle0/shardok/ai_performance_runner:__pkg__",
"//src/test/cpp/net/eagle0/shardok/ai:__pkg__",
],
deps = [
"//src/main/cpp/net/eagle0/common:random_generator",
"//src/main/cpp/net/eagle0/common:sequence_random_generator",
"//src/main/cpp/net/eagle0/shardok/ai:ai_command_filter",
"//src/main/cpp/net/eagle0/shardok/ai:ai_iterative_deepening", # For SearchResult compatibility
"//src/main/cpp/net/eagle0/shardok/ai:ai_score_calculator",
"//src/main/cpp/net/eagle0/shardok/ai:ai_strategy",
"//src/main/cpp/net/eagle0/shardok/ai:ai_time_budget",
"//src/main/cpp/net/eagle0/shardok/ai/mcts/internal:mcts_node",
"//src/main/cpp/net/eagle0/shardok/library:engine",
"//src/main/cpp/net/eagle0/shardok/library:game_state_w",
"//src/main/cpp/net/eagle0/shardok/library/action_point_distances:action_point_distances_cache",
"//src/main/cpp/net/eagle0/shardok/library/settings:game_settings",
"//src/main/protobuf/net/eagle0/shardok/api:command_descriptor_cc_proto",
"//src/main/protobuf/net/eagle0/shardok/common:command_type_cc_proto",
],
)
@@ -1,869 +0,0 @@
//
// MCTS-based AI implementation for Shardok
//
#include "MCTSAI.hpp"
#include <algorithm>
#include <cmath>
#include <future>
#include <limits>
#include <mutex>
#include <random>
#include <thread>
#include "internal/MCTSNode.hpp"
#include "src/main/cpp/net/eagle0/common/SequenceRandomGenerator.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AICommandFilter.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AIScoreCalculator.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/ShardokEngine.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/util/HexMapUtils.hpp"
#include "src/main/protobuf/net/eagle0/shardok/common/command_type.pb.h"
namespace shardok {
// Type alias for internal MCTSNode
using MCTSNode = internal::MCTSNode;
// Static helper for average random generator
static const std::vector _averageSequence = {0.5};
static const auto _averageGenerator = std::make_shared<SequenceRandomGenerator>(_averageSequence);
MCTSAI::MCTSAI(
const PlayerId playerId,
const bool isDefender,
AIStrategy strategy,
const CoordsSet& castleCoords,
const APDCache& apdCache,
const ALCache& alCache,
MCTSConfig config)
: playerId(playerId),
isDefender(isDefender),
strategy(std::move(strategy)),
castleCoords(castleCoords),
apdCache(apdCache),
alCache(alCache),
config(std::move(config)) {}
auto MCTSAI::Search(
const GameSettingsSPtr& settings,
const GameStateW& state,
const std::vector<CommandProto>& commands,
const AITimeBudget& budget) const -> SearchResult {
const auto startTime = std::chrono::steady_clock::now();
SearchResult result;
if (commands.empty()) {
result.searchCompleted = true;
result.completionReason = EvaluationCompletionReason::RAN_OUT_OF_COMMANDS;
return result;
}
if (commands.size() == 1) {
result.searchCompleted = true;
result.bestCommandIndex = 0;
result.bestScore = 0;
result.availableCommandCount = 1;
result.depthAchieved = 1;
result.commandCountEvaluated = 1;
result.completionReason = EvaluationCompletionReason::RAN_OUT_OF_COMMANDS;
return result;
}
const auto& settingsGetter = settings->GetGetter();
// Compute critical tiles once to avoid 8.5% runtime overhead in ShardokEngine construction
const auto criticalTiles = GetCriticalTileLocations(state->hex_map());
const auto guessedEngine = ShardokEngine(settings, state, criticalTiles);
const auto deadline = startTime + budget.remainingBudget;
// Build MCTS tree
auto rootNode = BuildMCTSTree(guessedEngine, settingsGetter, criticalTiles, deadline);
if (rootNode) {
// Get best command from tree
const MCTSNode* bestChild = rootNode->GetBestFinalChild();
if (bestChild) {
result.searchCompleted = true;
result.bestCommandIndex = bestChild->commandIndex;
result.bestScore = bestChild->lookaheadScore;
result.completionReason = EvaluationCompletionReason::RAN_OUT_OF_COMMANDS;
// Calculate max depth reached in the tree
std::function<int(const MCTSNode*)> getMaxDepth = [&](const MCTSNode* node) -> int {
int maxChildDepth = node->depth;
for (const auto& child : node->children) {
maxChildDepth = std::max(maxChildDepth, getMaxDepth(child.get()));
}
return maxChildDepth;
};
result.depthAchieved = getMaxDepth(rootNode.get());
// Count total nodes visited
std::function<size_t(const MCTSNode*)> countVisited =
[&](const MCTSNode* node) -> size_t {
size_t count = (node->visitCount > 0) ? 1 : 0;
for (const auto& child : node->children) { count += countVisited(child.get()); }
return count;
};
result.commandCountEvaluated = countVisited(rootNode.get());
result.availableCommandCount = commands.size();
// MCTS-specific logging
printf("MCTS: Selected command %zu (visit:%d, reward:%.2f, lookahead:%.2f) from %zu "
"options\n",
bestChild->commandIndex,
bestChild->visitCount,
bestChild->averageReward,
bestChild->lookaheadScore,
rootNode->children.size());
// Log top 3 commands for debugging with their best sequences
std::vector<MCTSNode*> sortedChildren;
for (const auto& child : rootNode->children) { sortedChildren.push_back(child.get()); }
std::ranges::sort(sortedChildren, [](const MCTSNode* a, const MCTSNode* b) {
return a->visitCount > b->visitCount;
});
printf("MCTS: Top commands by visits:\n");
for (size_t i = 0; i < std::min(static_cast<size_t>(3), sortedChildren.size()); ++i) {
auto* child = sortedChildren[i];
printf(" [%zu] cmd:%zu visits:%d immediate:%.2f backprop:%.2f type:%s",
i,
child->commandIndex,
child->visitCount,
child->immediateScore,
child->averageReward,
CommandType_Name(child->commandType).c_str());
// Show unit and target info for commands that have them
if (child->actorUnitId >= 0) { printf(" unit:%d", child->actorUnitId); }
if (child->targetRow >= 0 && child->targetCol >= 0) {
printf(" target:(%d,%d)", child->targetRow, child->targetCol);
}
// Show sequence preview for this command
if (!child->children.empty()) {
// Find best child by visits
MCTSNode* bestNext = nullptr;
int maxVisits = 0;
for (const auto& grandchild : child->children) {
if (grandchild->visitCount > maxVisits) {
maxVisits = grandchild->visitCount;
bestNext = grandchild.get();
}
}
if (bestNext) {
printf(" -> %s", CommandType_Name(bestNext->commandType).c_str());
}
}
printf("\n");
}
printf("MCTS: Tree stats - max depth:%zu, total nodes:%zu, root visits:%d\n",
result.depthAchieved,
result.commandCountEvaluated,
rootNode->visitCount);
// Log the best command sequence from the chosen command
struct SequenceNode {
size_t commandIndex;
std::string commandType;
int actorUnitId;
int targetRow;
int targetCol;
double immediateScore;
double backpropScore;
};
std::vector<SequenceNode> bestSequence;
bestSequence.reserve(5);
auto current = const_cast<MCTSNode*>(bestChild);
double sequenceScore = bestChild->averageReward;
// Trace the best path from chosen command (most visited child at each level)
while (current) {
bestSequence.push_back(
{current->commandIndex,
CommandType_Name(current->commandType),
current->actorUnitId,
current->targetRow,
current->targetCol,
current->immediateScore,
current->averageReward});
// If no children, we've reached the end of the sequence
if (current->children.empty()) { break; }
// Find most visited child
MCTSNode* bestChildNode = nullptr;
int maxVisits = 0;
for (const auto& child : current->children) {
if (child->visitCount > maxVisits) {
maxVisits = child->visitCount;
bestChildNode = child.get();
}
}
current = bestChildNode;
if (current) {
sequenceScore = current->averageReward; // Update to final score
}
}
if (!bestSequence.empty()) {
printf("MCTS: Best sequence from chosen command (final: %.2f):\n", sequenceScore);
for (size_t i = 0; i < bestSequence.size(); ++i) {
const auto& [commandIndex, commandType, actorUnitId, targetRow, targetCol, immediateScore, backpropScore] =
bestSequence[i];
printf(" %zu. cmd:%zu %s", i + 1, commandIndex, commandType.c_str());
// Add unit and target info if present
if (actorUnitId >= 0) { printf(" unit:%d", actorUnitId); }
if (targetRow >= 0 && targetCol >= 0) {
printf(" target:(%d,%d)", targetRow, targetCol);
}
printf(" (immediate:%.2f, backprop:%.2f)\n", immediateScore, backpropScore);
}
}
}
}
const auto endTime = std::chrono::steady_clock::now();
result.timeUsed = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);
return result;
}
auto MCTSAI::BuildMCTSTree(
const ShardokEngine& engine,
const SettingsGetter& settingsGetter,
const CoordsSet& criticalTileCoords,
const std::chrono::steady_clock::time_point deadline) const -> std::unique_ptr<MCTSNode> {
// Clear transposition registry for this search
if (config.enableTranspositionDetection) { stateRegistry.clear(); }
// Create root node
auto root = std::make_unique<MCTSNode>(
0,
net::eagle0::shardok::common::END_TURN_COMMAND,
playerId,
0,
isDefender);
root->resultingGameState = engine.GetCurrentGameState();
// Register root node in transposition table if enabled
if (config.enableTranspositionDetection) {
root->stateHash = root->resultingGameState.ComputeFNV1aHash();
stateRegistry[root->stateHash] = root.get();
}
// Initialize root with available commands
const CommandListSPtr rootCommands = engine.GetAvailableCommandsForAIPlayer(playerId);
if (!rootCommands || rootCommands->empty()) { return root; }
// Filter commands for better performance
const std::vector<size_t> filteredIndices = AICommandFilter::FilterCommands(
rootCommands,
playerId,
isDefender,
engine.GetCurrentGameState(),
settingsGetter,
apdCache);
root->untriedCommands = filteredIndices;
root->fullyExpanded = filteredIndices.empty();
// Main MCTS loop
int iterations = 0;
printf("MCTS: Starting search with %zu filtered commands (budget: %.0fms)\n",
filteredIndices.size(),
std::chrono::duration<double, std::milli>(deadline - std::chrono::steady_clock::now())
.count());
if (config.useMultithreading) {
// Parallel MCTS: Run iterations until time budget expires
const int numThreads =
std::min(config.numThreads, static_cast<int>(std::thread::hardware_concurrency()));
std::vector<std::future<void>> futures;
std::mutex treeMutex; // Protect tree updates
std::atomic totalIterations{0}; // Track iterations across threads
for (int t = 0; t < numThreads; ++t) {
futures.push_back(std::async(std::launch::async, [&, this] {
while (std::chrono::steady_clock::now() < deadline) {
++totalIterations;
// Selection and expansion need locking
MCTSNode* selected;
{
std::lock_guard lock(treeMutex);
selected = MCTSSelection(root.get());
if (selected && !selected->isTerminal && selected->CanExpand()) {
selected = MCTSExpansion(
selected,
engine,
settingsGetter,
criticalTileCoords);
}
}
// Skip simulation if selection failed (all children redundant)
if (!selected) continue;
// Simulation can run in parallel from the selected node's state
// Note: Creating engine from node state is correct for MCTS simulation
// Backpropagation needs locking
{
ShardokEngine nodeEngine(
engine.GetGameSettings(),
selected->resultingGameState,
criticalTileCoords);
const double reward =
MCTSSimulation(nodeEngine, selected->playerId, settingsGetter);
std::lock_guard lock(treeMutex);
MCTSBackpropagation(selected, reward);
}
}
}));
}
// Wait for all threads to complete
for (auto& future : futures) { future.get(); }
iterations = totalIterations.load(); // Get total from all threads
} else {
// Sequential MCTS - run until time budget expires
while (std::chrono::steady_clock::now() < deadline) {
// Selection
MCTSNode* selected = MCTSSelection(root.get());
// Skip if selection failed (all children redundant)
if (!selected) continue;
// Expansion
if (!selected->isTerminal && selected->CanExpand()) {
selected = MCTSExpansion(selected, engine, settingsGetter, criticalTileCoords);
}
// Simulation (from selected node's state)
ShardokEngine nodeEngine(
engine.GetGameSettings(),
selected->resultingGameState,
criticalTileCoords);
double reward = MCTSSimulation(
nodeEngine,
selected->playerId,
settingsGetter); // Use node's player, not original player
// Backpropagation
MCTSBackpropagation(selected, reward);
iterations++;
}
}
printf("MCTS: Completed %d iterations, root has %zu children\n",
iterations,
root->children.size());
return root;
}
auto MCTSAI::MCTSSelection(MCTSNode* root) const -> MCTSNode* {
MCTSNode* current = root;
while (!current->isTerminal && !current->isRedundant) {
if (current->CanExpand()) {
return current; // Node has untried commands
} else if (!current->children.empty()) {
current = current->GetBestChild(config.explorationConstant);
if (!current) break;
} else {
break; // Leaf node
}
}
return current;
}
auto MCTSAI::MCTSExpansion(
MCTSNode* node,
const ShardokEngine& engine,
const SettingsGetter& settingsGetter,
const CoordsSet& criticalTileCoords) const -> MCTSNode* {
static int expansionCallCount = 0;
if (expansionCallCount < 3) {
printf("MCTSExpansion called %d: node depth:%d untried:%zu\n",
expansionCallCount++,
node->depth,
node->untriedCommands.size());
}
if (node->untriedCommands.empty()) return node;
// Don't expand beyond maximum depth to prevent unbounded tree growth
if (node->depth >= config.maxTreeDepth) {
node->fullyExpanded = true;
node->untriedCommands.clear();
return node;
}
// Pick a random untried command
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution dis(0, static_cast<int>(node->untriedCommands.size() - 1));
const size_t randomIndex = dis(gen);
const auto commandIndex = node->untriedCommands[randomIndex];
node->untriedCommands.erase(node->untriedCommands.begin() + randomIndex);
// Create engine from the node's current state (not root state!)
const auto nodeEngine = std::make_shared<ShardokEngine>(
engine.GetGameSettings(),
node->resultingGameState,
criticalTileCoords);
// Get command descriptor from the node's state
const CommandListSPtr commands = nodeEngine->GetAvailableCommandsForAIPlayer(node->playerId);
if (!commands || commandIndex >= commands->size()) return node;
const auto& command = commands->at(commandIndex);
const auto commandType = command->GetCommandType();
const auto descriptor = command->GetCommandProto();
// Create child node
auto child = std::make_unique<MCTSNode>(
commandIndex,
commandType,
node->playerId,
node->depth + 1,
node->isDefender);
child->parent = node;
// Extract actor unit ID if present
if (descriptor.has_actor()) { child->actorUnitId = descriptor.actor().value(); }
// Extract target coordinates if present
// Note: In protobuf3, target is always present but may have default values
// We'll always capture the coordinates - commands without targets will have (-1,-1) by default
const auto& target = descriptor.target();
child->targetRow = target.row();
child->targetCol = target.column();
// Declare variables that will be used later
// Handle randomness appropriately based on command type
if (command->HasOdds()) {
// For commands with odds, use average roll for expansion
// For expansion, use average roll regardless of success chance
const auto generator = std::make_shared<SequenceRandomGenerator>(std::vector{0.5});
nodeEngine->PostCommand(node->playerId, commandIndex, generator);
} else {
// Use average generator for deterministic evaluation
nodeEngine->PostCommand(node->playerId, commandIndex, _averageGenerator);
}
child->resultingGameState = nodeEngine->GetCurrentGameState();
// Check whose turn it is after executing the command
PlayerId currentPlayer = nodeEngine->GetCurrentPlayerId();
bool isOurTurn = (currentPlayer == playerId);
// Update child's player ID to reflect whose turn it actually is
child->playerId = currentPlayer;
// Calculate immediate score (always from our perspective)
child->immediateScore = AIScoreCalculator::GuessedStateScore(
isDefender, // Use our original role, not node's
child->resultingGameState,
strategy,
castleCoords,
settingsGetter,
apdCache,
alCache);
// Initially, lookahead score equals immediate score
child->lookaheadScore = child->immediateScore;
// Debug: Log first few expansions to see what's happening
static int expansionCount = 0;
if (expansionCount < 5) {
printf("MCTS Expansion %d: cmd:%zu type:%s immediate_score:%.2f\n",
expansionCount++,
commandIndex,
CommandType_Name(commandType).c_str(),
child->immediateScore);
}
// Check if terminal
child->isTerminal = IsTerminalForPlayer(child->resultingGameState, playerId, settingsGetter);
// Transposition detection
if (config.enableTranspositionDetection) {
child->stateHash = child->resultingGameState.ComputeFNV1aHash();
auto existingIt = stateRegistry.find(child->stateHash);
if (existingIt != stateRegistry.end()) {
MCTSNode* existingNode = existingIt->second;
// Apply tie-breaking rules to determine which node to keep
bool shouldPruneChild = false;
if (child->depth > existingNode->depth) {
// Rule 1: Prune deeper node (current child is deeper)
shouldPruneChild = true;
} else if (child->depth == existingNode->depth) {
// Rule 2: At same depth, prune node with higher command index
if (child->commandIndex > existingNode->commandIndex) {
shouldPruneChild = true;
} else {
// Current child wins - mark existing node as redundant
existingNode->isRedundant = true;
stateRegistry[child->stateHash] = child.get(); // Update registry
}
} else {
// Child is shallower - mark existing node as redundant
existingNode->isRedundant = true;
stateRegistry[child->stateHash] = child.get(); // Update registry
}
if (shouldPruneChild) {
child->isRedundant = true;
// Don't expand redundant nodes
}
} else {
// New state - register it
stateRegistry[child->stateHash] = child.get();
}
}
// Get available commands for child - only if it's still our turn and not redundant
if (!child->isTerminal && !child->isRedundant && isOurTurn) {
const CommandListSPtr childCommands =
nodeEngine->GetAvailableCommandsForAIPlayer(currentPlayer);
if (childCommands) {
const std::vector<size_t> childFiltered = AICommandFilter::FilterCommands(
childCommands,
currentPlayer,
isDefender, // Use our original role
child->resultingGameState,
settingsGetter,
apdCache);
child->untriedCommands = childFiltered;
child->fullyExpanded = childFiltered.empty();
}
} else if (!isOurTurn) {
// Mark as terminal if it's not our turn - we can't expand opponent moves
child->isTerminal = true;
child->fullyExpanded = true;
}
// Update parent's expansion status
if (node->untriedCommands.empty()) { node->fullyExpanded = true; }
MCTSNode* childPtr = child.get();
node->children.push_back(std::move(child));
return childPtr;
}
auto MCTSAI::MCTSSimulation(
const ShardokEngine& engineState,
PlayerId startingPlayer,
const SettingsGetter& settingsGetter) const -> double {
// Create copy for simulation
auto simEngine = std::make_shared<ShardokEngine>(engineState, false);
// Always evaluate from our AI's perspective (not the startingPlayer's perspective)
const double initialScore = AIScoreCalculator::GuessedStateScore(
isDefender,
simEngine->GetCurrentGameState(),
strategy,
castleCoords,
settingsGetter,
apdCache,
alCache);
// Debug: Note that we're always scoring from our AI's perspective regardless of startingPlayer
(void)startingPlayer; // Acknowledge parameter to avoid warning
// Fast rollout with random/heuristic moves until terminal
int simulationSteps = 0;
for (int step = 0; step < config.maxSimulationDepth; ++step) {
const GameStateW& currentState = simEngine->GetCurrentGameState();
// Get whose turn it is
const PlayerId currentPlayer = simEngine->GetCurrentPlayerId();
// Check if terminal
if (IsTerminalForPlayer(currentState, playerId, settingsGetter)) { break; }
// Continue as long as it's still our turn (don't stop after each individual command)
// In this game, a player can move multiple units before turn switches
if (currentPlayer != playerId) {
// Turn switched to opponent - stop simulation immediately
break;
}
simulationSteps++;
// Get available commands for current player
const CommandListSPtr commands = simEngine->GetAvailableCommandsForAIPlayer(currentPlayer);
if (!commands || commands->empty()) break;
// Select command based on simulation policy
const auto commandIndex = static_cast<int>(
SelectSimulationCommand(commands, currentPlayer, simEngine, settingsGetter));
// Execute command
simEngine->PostCommand(currentPlayer, commandIndex, _averageGenerator);
// Debug: Only log if turn changed unexpectedly
const PlayerId newPlayer = simEngine->GetCurrentPlayerId();
static int debugCount = 0;
if (newPlayer != currentPlayer && debugCount < 5) {
const auto commandType = commands->at(commandIndex)->GetCommandType();
printf("MCTS Sim step %d: cmd_type:%s player_before:%d player_after:%d\n",
simulationSteps,
CommandType_Name(commandType).c_str(),
currentPlayer,
newPlayer);
printf(" WARNING: Turn changed after command!\n");
debugCount++;
}
}
// Evaluate final position
const double finalScore = AIScoreCalculator::GuessedStateScore(
isDefender,
simEngine->GetCurrentGameState(),
strategy,
castleCoords,
settingsGetter,
apdCache,
alCache);
// Debug: Log first few simulations to see depth and score change
static int simCount = 0;
if (simCount < 3) {
printf("MCTS Simulation %d: steps:%d initial:%.2f final:%.2f delta:%.2f\n",
simCount++,
simulationSteps,
initialScore,
finalScore,
finalScore - initialScore);
}
return finalScore;
}
auto MCTSAI::MCTSBackpropagation(MCTSNode* node, double reward) -> void {
while (node) {
node->visitCount++;
node->totalReward += reward;
node->averageReward = node->totalReward / node->visitCount;
// Update lookahead score as weighted average
if (node->visitCount == 1) {
node->lookaheadScore = reward;
} else {
node->lookaheadScore =
(node->lookaheadScore * (node->visitCount - 1) + reward) / node->visitCount;
}
node = node->parent;
}
}
auto MCTSAI::IsTerminalForPlayer(
const GameStateW& gameState,
PlayerId /*currentPlayer*/,
const SettingsGetter& settingsGetter) -> bool {
// Check if game is over
if (gameState->status()->state() ==
net::eagle0::shardok::storage::fb::GameStatus_::State_VICTORY ||
gameState->status()->state() ==
net::eagle0::shardok::storage::fb::GameStatus_::State_DRAW) {
return true;
}
// Check max rounds
if (gameState->current_round() >= settingsGetter.Backing().max_rounds()) { return true; }
return false;
}
auto MCTSAI::SelectSimulationCommand(
const CommandListSPtr& commands,
PlayerId currentPlayer,
const std::shared_ptr<ShardokEngine>& simEngine,
const SettingsGetter& settingsGetter) const -> size_t {
if (commands->size() == 1) {
return 0; // Only one choice
}
std::random_device rd;
std::mt19937 gen(rd());
switch (config.simulationPolicy) {
case MCTSSimulationPolicy::RANDOM: {
// Pure random selection
std::uniform_int_distribution<> dis(0, commands->size() - 1);
return dis(gen);
}
case MCTSSimulationPolicy::FILTERED_RANDOM: {
// Filter commands first, then random selection
const auto filteredIndices = AICommandFilter::FilterCommands(
commands,
currentPlayer,
isDefender,
simEngine->GetCurrentGameState(),
settingsGetter,
apdCache);
if (filteredIndices.empty()) {
// Fallback to random if no commands pass filter
std::uniform_int_distribution<> dis(0, commands->size() - 1);
return dis(gen);
}
std::uniform_int_distribution<> dis(0, filteredIndices.size() - 1);
return filteredIndices[dis(gen)];
}
case MCTSSimulationPolicy::BEST_IMMEDIATE: {
// Evaluate all commands and pick the best
double bestScore = -std::numeric_limits<double>::max();
size_t bestIndex = 0;
for (size_t i = 0; i < commands->size(); ++i) {
// Create a temporary engine to evaluate this command
const auto testEngine = std::make_shared<ShardokEngine>(*simEngine, false);
// Get score BEFORE executing command (for potential player flip comparison)
const double preScore = AIScoreCalculator::GuessedStateScore(
isDefender,
testEngine->GetCurrentGameState(),
strategy,
castleCoords,
settingsGetter,
apdCache,
alCache);
const PlayerId playerBefore = testEngine->GetCurrentPlayerId();
testEngine->PostCommand(currentPlayer, i, _averageGenerator);
const PlayerId playerAfter = testEngine->GetCurrentPlayerId();
double score;
if (playerAfter != playerBefore) {
// Player flipped - use pre-execution score to avoid opponent turn effects
score = preScore;
} else {
// Normal command - use post-execution score
score = AIScoreCalculator::GuessedStateScore(
isDefender,
testEngine->GetCurrentGameState(),
strategy,
castleCoords,
settingsGetter,
apdCache,
alCache);
}
if (score > bestScore) {
bestScore = score;
bestIndex = i;
}
}
return bestIndex;
}
case MCTSSimulationPolicy::WEIGHTED_BEST_IMMEDIATE: {
// Evaluate all commands and weight by ranking
struct CommandScore {
size_t index;
double score;
};
std::vector<CommandScore> commandScores;
commandScores.reserve(commands->size());
for (size_t i = 0; i < commands->size(); ++i) {
// Create a temporary engine to evaluate this command
const auto testEngine = std::make_shared<ShardokEngine>(*simEngine, false);
// Get score BEFORE executing command (for potential player flip comparison)
const double preScore = AIScoreCalculator::GuessedStateScore(
isDefender,
testEngine->GetCurrentGameState(),
strategy,
castleCoords,
settingsGetter,
apdCache,
alCache);
const PlayerId playerBefore = testEngine->GetCurrentPlayerId();
testEngine->PostCommand(currentPlayer, i, _averageGenerator);
const PlayerId playerAfter = testEngine->GetCurrentPlayerId();
double score;
if (playerAfter != playerBefore) {
// Player flipped - use pre-execution score to avoid opponent turn effects
score = preScore;
} else {
// Normal command - use post-execution score
score = AIScoreCalculator::GuessedStateScore(
isDefender,
testEngine->GetCurrentGameState(),
strategy,
castleCoords,
settingsGetter,
apdCache,
alCache);
}
commandScores.push_back({i, score});
}
// Sort by score (best first)
std::sort(
commandScores.begin(),
commandScores.end(),
[](const CommandScore& a, const CommandScore& b) { return a.score > b.score; });
// Assign weights: 1.0 for best, 0.5 for second, 0.33 for third, etc.
std::vector<double> weights;
weights.reserve(commandScores.size());
double totalWeight = 0.0;
for (size_t i = 0; i < commandScores.size(); ++i) {
double weight = 1.0 / (i + 1); // 1/1, 1/2, 1/3, ...
weights.push_back(weight);
totalWeight += weight;
}
// Random selection based on weights
std::uniform_real_distribution dis(0.0, totalWeight);
const double target = dis(gen);
double cumulative = 0.0;
for (size_t i = 0; i < weights.size(); ++i) {
cumulative += weights[i];
if (cumulative >= target) { return commandScores[i].index; }
}
// Fallback (shouldn't happen)
return commandScores[0].index;
}
}
// Fallback to random (shouldn't reach here)
std::uniform_int_distribution dis(0, static_cast<int>(commands->size() - 1));
return dis(gen);
}
} // namespace shardok
@@ -1,128 +0,0 @@
//
// MCTS-based AI system for Shardok
// Alternative to IterativeDeepeningAI using Monte Carlo Tree Search
//
#ifndef EAGLE0_MCTSAI_HPP
#define EAGLE0_MCTSAI_HPP
#include <chrono>
#include <future>
#include <memory>
#include <unordered_map>
#include <vector>
#include "src/main/cpp/net/eagle0/shardok/ai/AIStrategy.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AITimeBudget.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/IterativeDeepeningAI.hpp" // For SearchResult compatibility
#include "src/main/cpp/net/eagle0/shardok/library/GameStateW.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/ShardokCTypes.h"
#include "src/main/cpp/net/eagle0/shardok/library/ShardokCommand.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/action_point_distances/ActionPointDistancesCache.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/settings/GameSettings.hpp"
#include "src/main/protobuf/net/eagle0/shardok/api/command_descriptor.pb.h"
namespace shardok {
// Forward declarations
class ShardokEngine;
// MCTSNode is defined in internal/MCTSNode.hpp
namespace internal {
struct MCTSNode;
}
// Simulation policy for MCTS rollouts
enum class MCTSSimulationPolicy {
RANDOM, // Pure random selection
FILTERED_RANDOM, // Random from filtered commands
BEST_IMMEDIATE, // Choose best immediate score
WEIGHTED_BEST_IMMEDIATE // Random weighted by score ranking
};
// Configuration for MCTS algorithm
struct MCTSConfig {
double explorationConstant = 1.414; // UCB1 constant (sqrt(2) by default)
int maxSimulationDepth = 1000; // Maximum depth for rollout
int maxTreeDepth = 2000; // Maximum tree depth to prevent stack overflow
bool useMultithreading = true; // Enable parallel MCTS
int numThreads = 16; // Number of threads for parallel MCTS (when enabled)
MCTSSimulationPolicy simulationPolicy = MCTSSimulationPolicy::BEST_IMMEDIATE;
bool enableTranspositionDetection = true; // Enable pruning of duplicate states
};
class MCTSAI {
public:
using CommandProto = net::eagle0::shardok::api::CommandDescriptor;
using SearchResult = IterativeDeepeningAI::SearchResult;
MCTSAI(PlayerId playerId,
bool isDefender,
AIStrategy strategy,
const CoordsSet& castleCoords,
const APDCache& apdCache,
const ALCache& alCache,
MCTSConfig config = MCTSConfig{});
// Main search interface - compatible with IterativeDeepeningAI
[[nodiscard]] auto Search(
const GameSettingsSPtr& settings,
const GameStateW& state,
const std::vector<CommandProto>& commands,
const AITimeBudget& budget) const -> SearchResult;
// Get/set configuration
[[nodiscard]] auto GetConfig() const -> const MCTSConfig& { return config; }
void SetConfig(const MCTSConfig& newConfig) { config = newConfig; }
private:
PlayerId playerId;
bool isDefender;
AIStrategy strategy;
const CoordsSet& castleCoords;
const APDCache& apdCache;
const ALCache& alCache;
MCTSConfig config;
// Transposition detection infrastructure
mutable std::unordered_map<uint64_t, internal::MCTSNode*>
stateRegistry; // Hash -> first node mapping
// Internal MCTS tree building
[[nodiscard]] auto BuildMCTSTree(
const ShardokEngine& engine,
const SettingsGetter& settingsGetter,
const CoordsSet& criticalTileCoords,
std::chrono::steady_clock::time_point deadline) const
-> std::unique_ptr<internal::MCTSNode>;
// MCTS algorithm phases
auto MCTSSelection(internal::MCTSNode* root) const -> internal::MCTSNode*;
auto MCTSExpansion(
internal::MCTSNode* node,
const ShardokEngine& engine,
const SettingsGetter& settingsGetter,
const CoordsSet& criticalTileCoords) const -> internal::MCTSNode*;
auto MCTSSimulation(
const ShardokEngine& engineState,
PlayerId currentPlayer,
const SettingsGetter& settingsGetter) const -> double;
static auto MCTSBackpropagation(internal::MCTSNode* node, double reward) -> void;
// Helper functions
[[nodiscard]] static auto IsTerminalForPlayer(
const GameStateW& gameState,
PlayerId currentPlayer,
const SettingsGetter& settingsGetter) -> bool;
// Simulation command selection based on policy
[[nodiscard]] auto SelectSimulationCommand(
const CommandListSPtr& commands,
PlayerId currentPlayer,
const std::shared_ptr<ShardokEngine>& simEngine,
const SettingsGetter& settingsGetter) const -> size_t;
};
} // namespace shardok
#endif // EAGLE0_MCTSAI_HPP
@@ -1,16 +0,0 @@
load("//tools:copts.bzl", "COPTS")
cc_library(
name = "mcts_node",
hdrs = ["MCTSNode.hpp"],
copts = COPTS,
visibility = [
"//src/main/cpp/net/eagle0/shardok/ai/mcts:__pkg__",
"//src/test/cpp/net/eagle0/shardok/ai/mcts:__pkg__",
],
deps = [
"//src/main/cpp/net/eagle0/shardok/library:game_state_w",
"//src/main/cpp/net/eagle0/shardok/library:shardok_c_types",
"//src/main/protobuf/net/eagle0/shardok/common:command_type_cc_proto",
],
)
@@ -1,210 +0,0 @@
//
// Internal MCTS Node structure for Shardok AI
// This is an implementation detail and should not be used by external code
//
#ifndef EAGLE0_INTERNAL_MCTSNODE_HPP
#define EAGLE0_INTERNAL_MCTSNODE_HPP
#include <cmath>
#include <cstdio>
#include <limits>
#include <memory>
#include <vector>
#include "src/main/cpp/net/eagle0/shardok/library/GameStateW.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/ShardokCTypes.h"
// Suppress the protobuf deprecation warning temporarily
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-redundant-constexpr-static-def"
#include "src/main/protobuf/net/eagle0/shardok/common/command_type.pb.h"
#pragma GCC diagnostic pop
namespace shardok {
namespace internal {
// Import CommandType for use within the internal namespace
using CommandType = net::eagle0::shardok::common::CommandType;
// MCTS Node structure
struct MCTSNode {
// Command information
size_t commandIndex;
CommandType commandType;
int actorUnitId = -1; // Unit performing the command (-1 if not applicable)
int targetRow = -1; // Target coordinate row (-1 if not applicable)
int targetCol = -1; // Target coordinate column (-1 if not applicable)
// Score information
double immediateScore;
double lookaheadScore;
// Game state after this command
GameStateW resultingGameState;
// MCTS statistics
int visitCount = 0;
double totalReward = 0.0;
double averageReward = 0.0;
double ucb1Value = 0.0;
// Tree structure
std::vector<std::unique_ptr<MCTSNode>> children;
std::vector<size_t> untriedCommands;
bool fullyExpanded = false;
MCTSNode* parent = nullptr;
// Game context
PlayerId playerId;
int depth = 0;
bool isDefender = false;
bool isTerminal = false;
// Transposition detection
uint64_t stateHash = 0;
bool isRedundant = false; // True if this node represents a duplicate state
MCTSNode(
const size_t cmdIndex,
const CommandType cmdType,
const PlayerId pid,
const int d,
const bool defender)
: commandIndex(cmdIndex),
commandType(cmdType),
immediateScore(0.0),
lookaheadScore(0.0),
playerId(pid),
depth(d),
isDefender(defender) {}
// Iterative destructor to avoid stack overflow with deep trees
~MCTSNode() {
// Use iterative approach to destroy children
std::vector<std::unique_ptr<MCTSNode>> nodesToDestroy;
nodesToDestroy.swap(children);
while (!nodesToDestroy.empty()) {
// Take ownership of all children from the current batch
std::vector<std::unique_ptr<MCTSNode>> currentBatch;
currentBatch.swap(nodesToDestroy);
// Collect grandchildren for next iteration
for (const auto& node : currentBatch) {
if (node && !node->children.empty()) {
for (auto& child : node->children) {
nodesToDestroy.push_back(std::move(child));
}
node->children.clear();
}
}
// currentBatch goes out of scope here, destroying nodes with no children
}
}
// Calculate UCB1 value for this node
void CalculateUCB1(const double explorationConstant) {
if (visitCount == 0) {
ucb1Value = std::numeric_limits<double>::max();
} else if (parent && parent->visitCount > 0) {
ucb1Value = averageReward +
explorationConstant * std::sqrt(std::log(parent->visitCount) / visitCount);
} else {
ucb1Value = averageReward;
}
}
// Check if this node can be expanded
[[nodiscard]] bool CanExpand() const { return !fullyExpanded && !untriedCommands.empty(); }
// Get best child based on UCB1
[[nodiscard]] MCTSNode* GetBestChild(const double explorationConstant) const {
if (children.empty()) return nullptr;
MCTSNode* bestChild = nullptr;
double bestValue = -std::numeric_limits<double>::max();
static int selectionCallCount = 0;
const bool shouldDebug = selectionCallCount < 5;
for (auto& child : children) {
// Skip redundant nodes
if (child->isRedundant) continue;
child->CalculateUCB1(explorationConstant);
if (child->ucb1Value > bestValue) {
bestValue = child->ucb1Value;
bestChild = child.get();
}
if (shouldDebug && child->visitCount > 0) {
printf("UCB1 Debug: cmd:%zu visits:%d reward:%.2f ucb1:%.2f%s\n",
child->commandIndex,
child->visitCount,
child->averageReward,
child->ucb1Value,
child->isRedundant ? " [REDUNDANT]" : "");
}
}
if (shouldDebug) {
if (bestChild) {
printf("UCB1 Selected: cmd:%zu ucb1:%.2f\n",
bestChild->commandIndex,
bestChild->ucb1Value);
} else {
printf("UCB1 Selected: nullptr (all children redundant)\n");
}
selectionCallCount++;
}
return bestChild;
}
// Get best child based on average reward (for final selection)
[[nodiscard]] MCTSNode* GetBestFinalChild() const {
if (children.empty()) return nullptr;
MCTSNode* bestChild = nullptr;
double bestScore = -std::numeric_limits<double>::max();
int bestVisits = 0;
for (const auto& child : children) {
// Skip redundant nodes
if (child->isRedundant) continue;
// For final selection, prefer most-visited node (robust child selection)
// Only consider nodes that have been visited
if (child->visitCount > bestVisits) {
bestVisits = child->visitCount;
bestScore = child->averageReward;
bestChild = child.get();
} else if (child->visitCount == bestVisits && child->averageReward > bestScore) {
// Tie-break on average reward
bestScore = child->averageReward;
bestChild = child.get();
}
}
// If no child was visited (shouldn't happen), fall back to lookahead score
if (!bestChild && !children.empty()) {
for (const auto& child : children) {
// Skip redundant nodes
if (child->isRedundant) continue;
if (child->lookaheadScore > bestScore) {
bestScore = child->lookaheadScore;
bestChild = child.get();
}
}
}
return bestChild;
}
};
} // namespace internal
} // namespace shardok
#endif // EAGLE0_INTERNAL_MCTSNODE_HPP
@@ -11,7 +11,6 @@
#include "PerformanceTestGameStateBuilder.hpp"
#include "src/main/cpp/net/eagle0/common/FilesystemUtils.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AIConfig.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/ShardokAIClient.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/ShardokEngine.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/action_point_distances/FixedActionPointDistances.hpp"
@@ -120,37 +119,21 @@ int main(int argc, char* argv[]) {
const auto* hexMap = currentState->hex_map();
const auto settingsGetter = settings->GetGetter();
ShardokAIClient aiClient(
aiPlayerId,
isDefender,
hexMap,
settingsGetter,
AIAlgorithmType::MCTS_CLEAN);
ShardokAIClient aiClient(aiPlayerId, isDefender, hexMap, settingsGetter);
// Create a second AI client for the human player during setup
// This ensures consistent state handling during setup phase
const PlayerId humanPlayerId = 1;
ShardokAIClient humanSetupAI(
humanPlayerId,
!isDefender,
hexMap,
settingsGetter,
AIAlgorithmType::MCTS_CLEAN);
ShardokAIClient humanSetupAI(humanPlayerId, !isDefender, hexMap, settingsGetter);
// Complete setup phase - AI makes intelligent placement decisions
if (currentState->status()->state() ==
net::eagle0::shardok::storage::fb::GameStatus_::State_SET_UP) {
std::cout << "Setup phase detected. Completing setup...\n";
int setupMoves = 0;
while (currentState->status()->state() ==
net::eagle0::shardok::storage::fb::GameStatus_::State_SET_UP) {
PlayerId currentPlayer = currentState->current_player();
auto availableCommands = engine.GetAvailableCommandProtos(currentPlayer, false);
std::cout << "Setup move " << setupMoves++ << ": player "
<< static_cast<int>(currentPlayer) << " has " << availableCommands.size()
<< " commands\n";
if (availableCommands.empty()) {
std::cout << "No commands available for player "
<< static_cast<int>(currentPlayer) << "\n";
@@ -160,19 +143,15 @@ int main(int argc, char* argv[]) {
if (currentPlayer == aiPlayerId) {
// Let AI make intelligent placement decisions
auto choiceResults = aiClient.ChooseCommandIndex(engine);
std::cout << "AI player chose command " << choiceResults.chosenIndex << "\n";
engine.PostCommand(currentPlayer, choiceResults.chosenIndex);
} else {
// Human player: use AI for setup to ensure consistent state handling
auto choiceResults = humanSetupAI.ChooseCommandIndex(engine);
std::cout << "Human player (AI) chose command " << choiceResults.chosenIndex
<< "\n";
engine.PostCommand(currentPlayer, choiceResults.chosenIndex);
}
currentState = engine.GetCurrentGameState();
}
std::cout << "Setup complete! Game state: " << currentState->status()->state() << "\n";
}
// Test AI performance for configured number of turns
@@ -181,25 +160,6 @@ int main(int argc, char* argv[]) {
std::vector<AIPerformanceMetrics> metrics;
for (int turn = 0; turn < config.numTurns; ++turn) {
// Update current state and check whose turn it is
currentState = engine.GetCurrentGameState();
PlayerId currentPlayer = currentState->current_player();
// If it's not the AI's turn, skip to next iteration
if (currentPlayer != aiPlayerId) {
std::cout << " Turn " << turn << ": It's player "
<< static_cast<int>(currentPlayer) << "'s turn (not AI). Skipping...\n";
// Have the opponent make a simple move to advance the game
const auto opponentCommands =
engine.GetAvailableCommandProtos(currentPlayer, false);
if (!opponentCommands.empty()) {
// For now, opponent chooses first available command
engine.PostCommand(currentPlayer, 0);
}
continue;
}
// Check if AI can make a move
const auto availableCommands = engine.GetAvailableCommandProtos(aiPlayerId, false);
if (availableCommands.empty()) {
@@ -74,8 +74,7 @@ vector<shared_ptr<ShardokAIClient>> ShardokGameController::MakeAIClients(
pi.player_id(),
pi.is_defender(),
e->GetCurrentGameState()->hex_map(),
e->GetGameSettings()->GetGetter(),
AIAlgorithmType::MCTS_CLEAN);
e->GetGameSettings()->GetGetter());
aic.push_back(newClient);
}
@@ -58,22 +58,6 @@ ShardokEngine::ShardokEngine(
startingHistoryState(gsBuffer),
criticalTileCoords(GetCriticalTileLocations(GetCurrentGameState()->hex_map())) {}
ShardokEngine::ShardokEngine(
const GameSettingsSPtr &settings,
const GameStateW &gsBuffer,
const CoordsSet &criticalTileCoords,
const int32_t startingHistoryCount,
const bool trackHistory)
: gameSettings(settings),
settingsGetter(settings->GetGetter()),
availableCommandsFactory(
AvailableCommandsFactory::MakeAvailableCommandsFactory(settingsGetter)),
gameState(gsBuffer),
trackHistory(trackHistory),
startingHistoryCount(startingHistoryCount),
startingHistoryState(gsBuffer),
criticalTileCoords(criticalTileCoords) {}
ShardokEngine::ShardokEngine(
const GameSettingsSPtr &settings,
vector<Unit> &&unplacedUnorderedUnits,
@@ -88,14 +88,6 @@ public:
int32_t startingHistoryCount = 0,
bool trackHistory = true);
// Constructor using existing game state with pre-computed critical tile coords
ShardokEngine(
const GameSettingsSPtr &settings,
const GameStateW &gsBuffer,
const CoordsSet &criticalTileCoords,
int32_t startingHistoryCount = 0,
bool trackHistory = true);
// Constructor for a brand new game
ShardokEngine(
const GameSettingsSPtr &settings,
@@ -135,27 +135,27 @@ auto ActionPointDistancesCache::GetRaw(
MakeCacheKey(mapId, battalionType, includeBravingWater, braveWaterActionPointCost);
// Check the persistent map first
if (auto it = persistentCache.find(cacheKey); it != persistentCache.end()) {
if (persistentCache.contains(cacheKey)) {
#if CACHE_STATS_LOGGING_
cacheStats.persistentHits++;
MaybePrintCacheStats();
#endif
// Return directly from persistent cache without TLS insertion
// This avoids the overhead of thread-local storage operations on hot path
return it->second.sharedPtr.get();
return persistentCache.at(cacheKey).rawPtr;
}
#if CACHE_STATS_LOGGING_
cacheStats.persistentMisses++;
#endif
// Check thread-local cache (no locks needed!)
if (auto it = tlsCache.find(cacheKey); it != tlsCache.end()) {
// Check thread-local cache first (no locks needed!)
if (tlsCache.contains(cacheKey)) {
#if CACHE_STATS_LOGGING_
cacheStats.localHits++;
MaybePrintCacheStats();
#endif
return it->second.sharedPtr.get(); // Compute raw pointer on demand
return tlsCache.at(cacheKey).rawPtr; // Raw pointer - zero overhead access!
}
#if CACHE_STATS_LOGGING_
@@ -224,10 +224,17 @@ auto ActionPointDistancesCache::GetRaw(
// Store both shared_ptr and raw pointer for hybrid access
tlsCache.emplace(cacheKey, CacheEntry(result));
// Note: No eviction logic needed here - ConsolidateThreadLocalCache_Racy()
// is called after each AI decision to clear the cache and prevent unbounded growth.
// Previous eviction logic was unsafe as it could free cache entries while raw
// pointers to those entries were still in use, causing use-after-free crashes.
// Prevent unbounded cache growth - limit to reasonable size
if (tlsCache.size() > 100) {
// Simple eviction: clear half the cache when it gets too large
#if CACHE_STATS_LOGGING_
cacheStats.evictionEvents++;
#endif
auto it = tlsCache.begin();
std::advance(it, tlsCache.size() / 2);
tlsCache.erase(tlsCache.begin(), it);
}
return result.get();
}
@@ -59,8 +59,11 @@ class ActionPointDistancesCache {
private:
struct CacheEntry {
shared_ptr<ActionPointDistances> sharedPtr;
const ActionPointDistances* rawPtr;
explicit CacheEntry(shared_ptr<ActionPointDistances> ptr) : sharedPtr(std::move(ptr)) {}
explicit CacheEntry(shared_ptr<ActionPointDistances> ptr)
: sharedPtr(std::move(ptr)),
rawPtr(sharedPtr.get()) {}
};
// Tier 1: persistent map. This is NOT safe to write to while reads may be happening.
@@ -24,7 +24,6 @@ cc_library(
copts = COPTS,
visibility = [
"//src/main/cpp/net/eagle0/shardok/ai:__pkg__",
"//src/main/cpp/net/eagle0/shardok/ai/mcts:__pkg__",
"//src/test/cpp/net/eagle0/shardok/library/action_point_distances:__pkg__",
],
deps = [
@@ -48,7 +48,6 @@ namespace eagle {
private PlayerId _playerId;
private int _recommendedFood;
private int _recommendedGold;
private List<AvailableDestinationProvince> _sortedAvailableDestinations;
public override AvailableCommand.SealedValueOneofCase CommandType =>
AvailableCommand.SealedValueOneofCase.MarchCommand;
@@ -121,13 +120,9 @@ namespace eagle {
DestinationProvince is { RulingFactionId : not null } &&
DestinationProvince.RulingFactionId.Value != _playerId;
private bool RequiresRiverCrossing => SelectedDestinationProvinceIndex is {}
idx && _sortedAvailableDestinations != null && idx < _sortedAvailableDestinations.Count &&
_sortedAvailableDestinations[idx].RequiresRiverCrossing;
public override bool WarnOnCommitButton =>
WouldAbandonProvince || NotEnoughFood || MarchingOnTrucePartner ||
BadlyConstructedUnits || NoBattalionsIntoEnemy || RequiresRiverCrossing;
public override bool WarnOnCommitButton => WouldAbandonProvince || NotEnoughFood ||
MarchingOnTrucePartner ||
BadlyConstructedUnits || NoBattalionsIntoEnemy;
public override string CommitWarningText {
get {
if (!(WarnOnCommitButton)) return null;
@@ -152,9 +147,6 @@ namespace eagle {
txt += "Some of your heroes are leading battalion types that would restrict their abilities\n\n";
}
}
if (RequiresRiverCrossing) {
txt += $"Assaulting {DestinationProvince.Name} may require crossing a river\n\n";
}
return txt;
}
@@ -218,12 +210,9 @@ namespace eagle {
}
private void SetUpDestinationProvinceDropdown() {
_sortedAvailableDestinations =
SelectedOneProvinceCommand.AvailableDestinationProvinces
.OrderBy(adp => _model.Provinces[adp.ProvinceId].Name)
.ToList();
_sortedDestinationProvinceIds =
_sortedAvailableDestinations.Select(adp => adp.ProvinceId).ToList();
_sortedDestinationProvinceIds = SelectedOneProvinceCommand.AvailableDestinationProvinces
.OrderBy(pid => _model.Provinces[pid].Name)
.ToList();
var destinationProvinceNames = _sortedDestinationProvinceIds
.Select(id => GUIUtils.DarkColoredProvinceName(
_model.Provinces[id],
@@ -862,7 +862,7 @@ namespace eagle {
}
private int? TroopCount() {
return existingBattalions.Where(x => !x.dismissed).Select(eb => eb.Count).Sum() +
return existingBattalions.Select(eb => eb.Count).Sum() +
newBattalions.Select(nb => nb.Count).Sum();
}
}
@@ -1,8 +1,6 @@
using System;
using Net.Eagle0.Eagle.Api;
using Net.Eagle0.Eagle.Views;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace eagle {
@@ -23,9 +21,6 @@ namespace eagle {
private TradeAvailableCommand TradeCommand => _availableCommand.TradeCommand;
private ProvinceId ActingProvinceId => TradeCommand.ActingProvinceId;
private ProvinceView ActingProvince => _model.Provinces[ActingProvinceId];
private int ProvinceGoldCap => ActingProvince.FullInfo.GoldCap;
private int ProvinceFoodCap => ActingProvince.FullInfo.FoodCap;
private int MaxFood =>
TradeCommand.FoodAvailable +
@@ -53,8 +48,7 @@ namespace eagle {
SetTextFields();
}
public override bool EnableCommitButton =>
!Mathf.Approximately(slider.value, TradeCommand.FoodAvailable);
public override bool EnableCommitButton => slider.value != TradeCommand.FoodAvailable;
public override string DisabledCommitButtonReason => "No change";
private bool IsBuy => FoodAmount > TradeCommand.FoodAvailable;
@@ -74,10 +68,7 @@ namespace eagle {
public void SetTextFields() {
goldText.text = GoldAmount.ToString();
goldText.color = GoldAmount > ProvinceGoldCap ? Color.red : Color.black;
foodText.text = FoodAmount.ToString();
foodText.color = FoodAmount > ProvinceFoodCap ? Color.red : Color.black;
description.text = IsBuy ? $"Buying {NetFood} food for {-NetGold} gold"
: $"Selling {-NetFood} food for {NetGold} gold";
@@ -19,6 +19,9 @@
</ItemGroup>
<ItemGroup>
<Protobuf Include="..\..\..\..\..\..\..\..\..\src\main\protobuf\scalapb\scalapb.proto" ProtoRoot="..\..\..\..\..\..\..\..\..\">
<Link>src\main\protobuf\scalapb\scalapb.proto</Link>
</Protobuf>
<Protobuf Include="..\..\..\..\..\..\..\..\..\src\main\protobuf\net\eagle0\common\random_units.proto" ProtoRoot="..\..\..\..\..\..\..\..\..\">
<Link>src\main\protobuf\net\eagle0\common\random_units.proto</Link>
</Protobuf>
@@ -65,7 +65,7 @@ func main() {
targetNames = append(targetNames, fmt.Sprintf(" \":%s\",", typeInfo.targetName))
}
mainTypesBuildFile := fmt.Sprintf(`load("@rules_scala//scala:scala.bzl", "scala_library")
mainTypesBuildFile := fmt.Sprintf(`load("@io_bazel_rules_scala//scala:scala.bzl", "scala_library")
load(":action_result_type_rule.bzl", "action_result_type_library")
scala_library(
@@ -67,7 +67,7 @@ func loaderBuildFileContents(lines [][]string) string {
depLines = append(depLines, fmt.Sprintf("\"//src/main/scala/net/eagle0/eagle/library/settings:%s\"", snakeKey))
}
return fmt.Sprintf(`load("@rules_scala//scala:scala.bzl", "scala_library")
return fmt.Sprintf(`load("@io_bazel_rules_scala//scala:scala.bzl", "scala_library")
scala_library(
name = "battalion_type_loader",
@@ -1,14 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
go_binary(
name = "settings_loader_generator",
embed = [":settings_loader_generator_lib"],
visibility = ["//visibility:public"],
)
go_library(
name = "settings_loader_generator_lib",
srcs = ["settings_loader_generator.go"],
importpath = "github.com/nolen777/eagle0/src/main/go/net/eagle0/build/settings_loader_generator",
visibility = ["//visibility:private"],
)
@@ -1,188 +0,0 @@
package main
import (
"bufio"
"fmt"
"os"
"regexp"
"strings"
)
func usage() {
fmt.Println("Usage:")
fmt.Printf(" %s <build_bazel_file>\n", os.Args[0])
fmt.Printf(" Generates complete SettingsLoader.scala from BUILD.bazel file\n")
}
type Setting struct {
Name string
Type string
}
func parseSettings(buildFile string) ([]Setting, error) {
file, err := os.Open(buildFile)
if err != nil {
return nil, err
}
defer file.Close()
var settings []Setting
scanner := bufio.NewScanner(file)
// Regex patterns to extract setting info
settingNameRegex := regexp.MustCompile(`setting_name = "([^"]+)"`)
settingTypeRegex := regexp.MustCompile(`setting_type = "([^"]+)"`)
var currentName, currentType string
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
// Look for setting_name
if matches := settingNameRegex.FindStringSubmatch(line); matches != nil {
currentName = matches[1]
}
// Look for setting_type
if matches := settingTypeRegex.FindStringSubmatch(line); matches != nil {
currentType = matches[1]
}
// When we hit the end of a scala_setting_library block, save the setting
if strings.Contains(line, ")") && currentName != "" && currentType != "" {
settings = append(settings, Setting{
Name: currentName,
Type: currentType,
})
currentName = ""
currentType = ""
}
}
return settings, scanner.Err()
}
func generateSettingsLoader(settings []Setting) string {
var sb strings.Builder
sb.WriteString("package net.eagle0.eagle.library.settings.loaders\n\n")
sb.WriteString("import net.eagle0.common.TsvUtils\n")
sb.WriteString("import net.eagle0.eagle.library.settings.base.{DoubleSetting, IntSetting}\n")
sb.WriteString("// Auto-generated imports for all settings\n")
sb.WriteString("import net.eagle0.eagle.library.settings._\n\n")
sb.WriteString("import java.net.URL\n\n")
sb.WriteString("// Generated file, do not edit!\n")
sb.WriteString("// This file is automatically generated from BUILD.bazel settings definitions\n")
sb.WriteString(fmt.Sprintf("// Contains %d settings\n\n", len(settings)))
sb.WriteString("object SettingsLoader {\n")
sb.WriteString(" private final case class NoSuchSettingException(\n")
sb.WriteString(" private val key: String\n")
sb.WriteString(" ) extends Exception(s\"No setting found for $key\", null)\n\n")
// Generate the pattern matching method
sb.WriteString(" // Pattern matching approach - no reflection needed!\n")
sb.WriteString(fmt.Sprintf(" // Auto-generated from BUILD.bazel (%d settings)\n", len(settings)))
sb.WriteString(" private def settingObjectForKey(key: String): Any = key match {\n")
for _, setting := range settings {
sb.WriteString(fmt.Sprintf(" case \"%s\" => %s\n", setting.Name, setting.Name))
}
sb.WriteString(" case _ => throw NoSuchSettingException(key)\n")
sb.WriteString(" }\n\n")
// Add the rest of the class
sb.WriteString(` case class SettingLine(
key: String,
value: String,
typeStr: String
)
private def loadOneSetting(setting: SettingLine): Boolean = {
val obj = settingObjectForKey(setting.key)
setting.typeStr.toLowerCase match {
case "int" =>
obj.asInstanceOf[IntSetting].setIntValue(setting.value.toInt)
true
case "double" =>
obj.asInstanceOf[DoubleSetting].setDoubleValue(setting.value.toDouble)
true
case typeName =>
throw new Exception(s"Invalid setting type $typeName")
}
}
private def loadTsv(tsvUrl: URL): Vector[SettingLine] = {
TsvUtils
.loadLines(tsvUrl)
.get
.map {
case Vector(keyStr, valueStr, typeStr) =>
SettingLine(
key = keyStr.capitalize,
value = valueStr,
typeStr = typeStr
)
case _ => throw new Exception("Invalid setting line")
}
}
def loadSettings(settings: Iterable[SettingLine]): Unit = {
settings.foreach { setting =>
loadOneSetting(setting)
}
}
def loadSettings(tsvUrl: URL): Unit =
loadSettings(
loadTsv(tsvUrl)
)
def addSettings(newSettings: Vector[(String, String)]): Unit = {
println(s"Writing new settings: $newSettings")
newSettings.foreach { case (key, value) =>
try {
settingObjectForKey(key) match {
case intSetting: IntSetting =>
intSetting.setIntValue(value.toInt)
case doubleSetting: DoubleSetting =>
doubleSetting.setDoubleValue(value.toDouble)
case _ =>
throw NoSuchSettingException(key)
}
} catch {
case _: NoSuchSettingException =>
println(s"Setting $key not found, skipping")
}
}
}
}
`)
return sb.String()
}
func main() {
if len(os.Args) != 2 {
usage()
os.Exit(2)
}
buildFile := os.Args[1]
settings, err := parseSettings(buildFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Error parsing BUILD file: %v\n", err)
os.Exit(1)
}
if len(settings) == 0 {
fmt.Fprintf(os.Stderr, "No settings found in BUILD file\n")
os.Exit(1)
}
loader := generateSettingsLoader(settings)
fmt.Print(loader)
}
@@ -1,9 +1,9 @@
load("@build_bazel_rules_swift//proto:proto.bzl", "swift_proto_library")
load("@grpc//bazel:cc_grpc_library.bzl", "cc_grpc_library")
load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
load("@io_bazel_rules_scala//scala_proto:scala_proto.bzl", "scala_proto_library")
load("@rules_cc//cc:defs.bzl", "cc_proto_library")
load("@rules_proto//proto:defs.bzl", "proto_library")
load("@rules_scala//scala_proto:scala_proto.bzl", "scala_proto_library")
scala_proto_library(
name = "common_unit_scala_proto",
@@ -54,6 +54,7 @@ proto_library(
visibility = ["//src/main/protobuf/net/eagle0:__subpackages__"],
deps = [
":player_info_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
@@ -108,6 +109,7 @@ proto_library(
deps = [
":common_unit_proto",
":victory_condition_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
@@ -134,6 +136,7 @@ proto_library(
visibility = ["//visibility:public"],
deps = [
":common_unit_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
@@ -179,6 +182,7 @@ proto_library(
"//src/main/protobuf/net/eagle0/shardok/api:placement_command_proto",
"//src/main/protobuf/net/eagle0/shardok/common:hex_map_proto",
"//src/main/protobuf/net/eagle0/shardok/storage:action_result_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -230,5 +234,6 @@ go_proto_library(
"//src/main/protobuf/net/eagle0/shardok/api:api_go_proto",
"//src/main/protobuf/net/eagle0/shardok/common:common_go_proto",
"//src/main/protobuf/net/eagle0/shardok/storage:storage_go_proto",
"//src/main/protobuf/scalapb:scalapb_go_proto",
],
)
@@ -8,6 +8,13 @@ package net.eagle0.common;
import "src/main/protobuf/net/eagle0/common/player_info.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.common";
option java_outer_classname = "GameSetupInfo";
@@ -9,6 +9,13 @@ package net.eagle0.common;
import "src/main/protobuf/net/eagle0/common/common_unit.proto";
import "src/main/protobuf/net/eagle0/common/victory_condition.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.common";
option java_outer_classname = "PlayerInfo";
@@ -8,6 +8,13 @@ package net.eagle0.common;
import "src/main/protobuf/net/eagle0/common/common_unit.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.common";
option java_outer_classname = "RandomUnits";
@@ -15,6 +15,13 @@ import "src/main/protobuf/net/eagle0/shardok/api/placement_command.proto";
import "src/main/protobuf/net/eagle0/shardok/common/hex_map.proto";
import "src/main/protobuf/net/eagle0/shardok/storage/action_result.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.common";
option java_outer_classname = "EagleInterface";
@@ -1,7 +1,7 @@
load("@build_bazel_rules_swift//proto:proto.bzl", "swift_proto_library")
load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
load("@io_bazel_rules_scala//scala_proto:scala_proto.bzl", "scala_proto_library")
load("@rules_proto//proto:defs.bzl", "proto_library")
load("@rules_scala//scala_proto:scala_proto.bzl", "scala_proto_library")
scala_proto_library(
name = "eagle_scala_grpc",
@@ -30,6 +30,7 @@ proto_library(
"//src/main/protobuf/net/eagle0/shardok/api:action_result_view_proto",
"//src/main/protobuf/net/eagle0/shardok/api:command_descriptor_proto",
"//src/main/protobuf/net/eagle0/shardok/common:hex_map_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -88,6 +89,7 @@ proto_library(
"//src/main/protobuf/net/eagle0/eagle/common:province_order_type_proto",
"//src/main/protobuf/net/eagle0/eagle/common:tribute_amount_proto",
"//src/main/protobuf/net/eagle0/eagle/views:hero_view_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -119,6 +121,7 @@ proto_library(
visibility = ["//visibility:public"],
deps = [
":available_command_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
@@ -135,6 +138,9 @@ proto_library(
name = "pregenerated_text_proto",
srcs = ["pregenerated_text.proto"],
visibility = ["//visibility:public"],
deps = [
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
swift_proto_library(
@@ -189,6 +195,7 @@ proto_library(
"//src/main/protobuf/net/eagle0/eagle/common:diplomacy_offer_proto",
"//src/main/protobuf/net/eagle0/eagle/common:diplomacy_offer_status_proto",
"//src/main/protobuf/net/eagle0/eagle/common:improvement_type_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -232,5 +239,6 @@ go_proto_library(
"//src/main/protobuf/net/eagle0/eagle/views:views_go_proto",
"//src/main/protobuf/net/eagle0/shardok/api:api_go_proto",
"//src/main/protobuf/net/eagle0/shardok/common:common_go_proto",
"//src/main/protobuf/scalapb:scalapb_go_proto",
],
)
@@ -26,6 +26,13 @@ import "src/main/protobuf/net/eagle0/eagle/common/province_order_type.proto";
import "src/main/protobuf/net/eagle0/eagle/common/tribute_amount.proto";
import "src/main/protobuf/net/eagle0/eagle/views/hero_view.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.api";
option java_outer_classname = "AvailableCommand";
@@ -244,11 +251,6 @@ message ManagePrisonersAvailableCommand {
repeated PrisonerToManage prisoners = 2;
}
message AvailableDestinationProvince {
int32 province_id = 1;
bool requires_river_crossing = 2;
}
message MarchCommandFromOneProvince {
map<int32, .net.eagle0.eagle.api.command.util.SuitableBattalions> suitable_battalions_for_heroes = 1;
@@ -259,7 +261,7 @@ message MarchCommandFromOneProvince {
int32 food_available = 6;
repeated AvailableDestinationProvince available_destination_provinces = 7;
repeated int32 available_destination_provinces = 7;
repeated int32 available_hero_ids = 8;
repeated .net.eagle0.eagle.api.command.util.BattalionWithFoodCost available_battalions = 10;
@@ -349,7 +351,7 @@ message ResolveRansomOfferAvailableCommand {
message TributeAndFaction {
int32 demanding_faction_id = 1;
.net.eagle0.eagle.common.TributeAmount tribute_demanded = 2;
.net.eagle0.eagle.common.TributeAmount tribute_demanded = 2 [(scalapb.field).no_box = true];
int32 hero_count = 3;
int32 troop_count = 4;
@@ -8,6 +8,13 @@ package net.eagle0.eagle.api;
import "src/main/protobuf/net/eagle0/eagle/api/available_command.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.api";
option java_outer_classname = "Command";
@@ -1,7 +1,7 @@
load("@build_bazel_rules_swift//proto:proto.bzl", "swift_proto_library")
load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
load("@io_bazel_rules_scala//scala_proto:scala_proto.bzl", "scala_proto_library")
load("@rules_proto//proto:defs.bzl", "proto_library")
load("@rules_scala//scala_proto:scala_proto.bzl", "scala_proto_library")
swift_proto_library(
name = "appropriate_battalions_swift_proto",
@@ -30,6 +30,7 @@ proto_library(
visibility = [
"//src/main/protobuf/net/eagle0/eagle/api:__subpackages__",
],
deps = ["//src/main/protobuf/scalapb:scalapb_proto"],
)
swift_proto_library(
@@ -124,6 +125,7 @@ proto_library(
],
deps = [
"//src/main/protobuf/net/eagle0/eagle/common:tribute_amount_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
@@ -419,6 +421,7 @@ go_proto_library(
"//src/main/protobuf/net/eagle0/common:common_go_proto",
# "//src/main/protobuf/net/eagle0/eagle/api:api_go_proto",
"//src/main/protobuf/net/eagle0/eagle/common:common_go_proto",
"//src/main/protobuf/scalapb:scalapb_go_proto",
"//src/main/protobuf/net/eagle0/eagle/views:views_go_proto",
],
)
@@ -6,11 +6,18 @@ syntax = "proto3";
package net.eagle0.eagle.api.command.util;
import "src/main/protobuf/scalapb/scalapb.proto";
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.api.command.util";
option java_outer_classname = "AppropriateBattalions";
option objc_class_prefix = "E0G";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
message SuitableBattalions {
enum SuitabilityLevel {
UNKNOWN = 0;
@@ -8,6 +8,8 @@ package net.eagle0.eagle.api.command.util;
import "src/main/protobuf/net/eagle0/eagle/common/tribute_amount.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.api.command.util";
option java_outer_classname = "AttackDecisionTypes";
@@ -29,7 +31,7 @@ message WithdrawDecision {
}
message DemandTributeDecision {
.net.eagle0.eagle.common.TributeAmount tribute = 2;
.net.eagle0.eagle.common.TributeAmount tribute = 2 [(scalapb.field).no_box = true];
}
message SafePassageDecision {
@@ -19,6 +19,13 @@ import "src/main/protobuf/net/eagle0/shardok/api/action_result_view.proto";
import "src/main/protobuf/net/eagle0/shardok/api/command_descriptor.proto";
import "src/main/protobuf/net/eagle0/shardok/common/hex_map.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.api";
option java_outer_classname = "EagleProto";
@@ -259,6 +266,7 @@ message ErrorResponse {
string error_string = 2;
}
message JoinGameRequest {
int64 game_id = 1;
string desired_leader_text_id = 2;
@@ -6,6 +6,13 @@ syntax = "proto3";
package net.eagle0.eagle.api;
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.api";
option java_outer_classname = "PregeneratedTextProto";
@@ -20,6 +20,13 @@ import "src/main/protobuf/net/eagle0/eagle/common/diplomacy_offer.proto";
import "src/main/protobuf/net/eagle0/eagle/common/diplomacy_offer_status.proto";
import "src/main/protobuf/net/eagle0/eagle/common/improvement_type.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.api";
option java_outer_classname = "AvailableCommand";
@@ -1,7 +1,7 @@
load("@build_bazel_rules_swift//proto:proto.bzl", "swift_proto_library")
load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
load("@io_bazel_rules_scala//scala_proto:scala_proto.bzl", "scala_proto_library")
load("@rules_proto//proto:defs.bzl", "proto_library")
load("@rules_scala//scala_proto:scala_proto.bzl", "scala_proto_library")
package(default_visibility = [
"//src/main/scala/net/eagle0:__subpackages__",
@@ -33,6 +33,7 @@ proto_library(
],
deps = [
":unaffiliated_hero_quest_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -134,6 +135,7 @@ proto_library(
],
deps = [
":date_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
@@ -219,6 +221,7 @@ proto_library(
deps = [
":date_proto",
":diplomacy_offer_status_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
@@ -293,6 +296,7 @@ proto_library(
],
deps = [
":date_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
@@ -379,6 +383,7 @@ proto_library(
deps = [
":beast_info_proto",
":date_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
@@ -475,6 +480,7 @@ scala_proto_library(
],
deps = [
":tribute_amount_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
@@ -567,4 +573,5 @@ go_proto_library(
":unaffiliated_hero_type_proto",
],
visibility = ["//visibility:public"],
deps = ["//src/main/protobuf/scalapb:scalapb_go_proto"],
)
@@ -10,6 +10,13 @@ import "google/protobuf/wrappers.proto";
import "src/main/protobuf/net/eagle0/eagle/common/unaffiliated_hero_quest.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.common";
option java_outer_classname = "ActionResultNotificationDetails";
@@ -6,6 +6,8 @@ syntax = "proto3";
package net.eagle0.eagle.common;
import "src/main/protobuf/scalapb/scalapb.proto";
import "src/main/protobuf/net/eagle0/eagle/common/date.proto";
option java_multiple_files = true;
@@ -15,5 +17,5 @@ option objc_class_prefix = "E0G";
message ChronicleEntry {
string generated_text_id = 1;
.net.eagle0.eagle.common.Date date = 2;
.net.eagle0.eagle.common.Date date = 2 [(scalapb.field).no_box = true];
}
@@ -8,6 +8,12 @@ package net.eagle0.eagle.common;
import "src/main/protobuf/net/eagle0/eagle/common/date.proto";
import "src/main/protobuf/net/eagle0/eagle/common/diplomacy_offer_status.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.common";
@@ -38,7 +44,7 @@ message DiplomacyOfferDetails {
}
message TruceOfferDetails {
.net.eagle0.eagle.common.Date end_date = 1;
.net.eagle0.eagle.common.Date end_date = 1 [(scalapb.field).no_box = true];
}
message AllianceOfferDetails {
@@ -8,6 +8,8 @@ package net.eagle0.eagle.common;
import "src/main/protobuf/net/eagle0/eagle/common/date.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.common";
option java_outer_classname = "HeroBackstoryVersion";
@@ -15,5 +17,5 @@ option objc_class_prefix = "E0G";
message BackstoryVersion {
string text_id = 1;
.net.eagle0.eagle.common.Date date = 2;
.net.eagle0.eagle.common.Date date = 2 [(scalapb.field).no_box = true];
}
@@ -6,6 +6,8 @@ syntax = "proto3";
package net.eagle0.eagle.common;
import "src/main/protobuf/scalapb/scalapb.proto";
import "src/main/protobuf/net/eagle0/eagle/common/beast_info.proto";
import "src/main/protobuf/net/eagle0/eagle/common/date.proto";
@@ -16,37 +18,37 @@ option objc_class_prefix = "E0G";
message BeastsEvent {
int32 count = 1;
Date start_date = 2;
Date end_date = 3;
Date start_date = 2 [(scalapb.field).no_box = true];
Date end_date = 3 [(scalapb.field).no_box = true];
BeastInfo beast_info = 4;
BeastInfo beast_info = 4 [(scalapb.field).no_box = true];
}
message ImminentRiotEvent {
}
message BlizzardEvent {
Date start_date = 1;
Date end_date = 2;
Date start_date = 1 [(scalapb.field).no_box = true];
Date end_date = 2 [(scalapb.field).no_box = true];
}
message FestivalEvent {
Date start_date = 1;
Date end_date = 2;
Date start_date = 1 [(scalapb.field).no_box = true];
Date end_date = 2 [(scalapb.field).no_box = true];
}
message FloodEvent {
Date start_date = 1;
Date end_date = 2;
Date start_date = 1 [(scalapb.field).no_box = true];
Date end_date = 2 [(scalapb.field).no_box = true];
}
message DroughtEvent {
Date start_date = 1;
Date end_date = 2;
Date start_date = 1 [(scalapb.field).no_box = true];
Date end_date = 2 [(scalapb.field).no_box = true];
}
message EpidemicEvent {
Date start_date = 1;
Date start_date = 1 [(scalapb.field).no_box = true];
}
message ProvinceEvent {
@@ -1,7 +1,7 @@
load("@build_bazel_rules_swift//proto:proto.bzl", "swift_proto_library")
load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
load("@io_bazel_rules_scala//scala_proto:scala_proto.bzl", "scala_proto_library")
load("@rules_proto//proto:defs.bzl", "proto_library")
load("@rules_scala//scala_proto:scala_proto.bzl", "scala_proto_library")
package(default_visibility = [
"//src/main/scala/net/eagle0:__subpackages__",
@@ -60,6 +60,7 @@ proto_library(
"//src/main/protobuf/net/eagle0/eagle/common:chronicle_entry_proto",
"//src/main/protobuf/net/eagle0/eagle/common:date_proto",
"//src/main/protobuf/net/eagle0/eagle/common:round_phase_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -90,6 +91,7 @@ proto_library(
":supplies_proto",
"//src/main/protobuf/net/eagle0/eagle/common:combat_unit_proto",
"//src/main/protobuf/net/eagle0/eagle/common:tribute_amount_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -165,6 +167,7 @@ proto_library(
":faction_relationship_proto",
"//src/main/protobuf/net/eagle0/eagle/common:diplomacy_offer_proto",
"//src/main/protobuf/net/eagle0/eagle/views:province_view_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -231,6 +234,7 @@ proto_library(
"//src/main/protobuf/net/eagle0/eagle/common:improvement_type_proto",
"//src/main/protobuf/net/eagle0/eagle/common:province_event_proto",
"//src/main/protobuf/net/eagle0/eagle/common:province_order_type_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -254,6 +258,7 @@ proto_library(
srcs = ["client_text.proto"],
deps = [
":llm_request_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
@@ -292,6 +297,7 @@ proto_library(
srcs = ["event_for_chronicle.proto"],
deps = [
"//src/main/protobuf/net/eagle0/eagle/common:date_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -321,6 +327,7 @@ proto_library(
"//src/main/protobuf/net/eagle0/eagle/common:diplomacy_offer_status_proto",
"//src/main/protobuf/net/eagle0/eagle/common:unaffiliated_hero_quest_proto",
"//src/main/protobuf/net/eagle0/eagle/views:battalion_view_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
@@ -351,6 +358,7 @@ proto_library(
":faction_relationship_proto",
"//src/main/protobuf/net/eagle0/eagle/common:diplomacy_offer_proto",
"//src/main/protobuf/net/eagle0/eagle/views:province_view_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -406,6 +414,7 @@ proto_library(
":battalion_proto",
"//src/main/protobuf/net/eagle0/eagle/common:battalion_type_proto",
"//src/main/protobuf/net/eagle0/eagle/common:province_order_type_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
@@ -435,6 +444,7 @@ proto_library(
":action_result_proto",
":game_state_proto",
"//src/main/protobuf/net/eagle0/eagle/common:date_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
@@ -481,6 +491,7 @@ proto_library(
"//src/main/protobuf/net/eagle0/eagle/common:chronicle_entry_proto",
"//src/main/protobuf/net/eagle0/eagle/common:date_proto",
"//src/main/protobuf/net/eagle0/eagle/common:round_phase_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -510,6 +521,7 @@ proto_library(
"//src/main/protobuf/net/eagle0/eagle/common:gender_proto",
"//src/main/protobuf/net/eagle0/eagle/common:hero_backstory_version_proto",
"//src/main/protobuf/net/eagle0/eagle/common:profession_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -533,6 +545,7 @@ proto_library(
],
deps = [
":llm_request_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
@@ -569,6 +582,7 @@ proto_library(
"//src/main/protobuf/net/eagle0/eagle/common:gender_proto",
"//src/main/protobuf/net/eagle0/eagle/common:hero_backstory_version_proto",
"//src/main/protobuf/net/eagle0/eagle/common:unaffiliated_hero_quest_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -617,6 +631,7 @@ proto_library(
"//src/main/protobuf/net/eagle0/eagle/common:improvement_type_proto",
"//src/main/protobuf/net/eagle0/eagle/common:province_event_proto",
"//src/main/protobuf/net/eagle0/eagle/common:province_order_type_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -655,6 +670,9 @@ scala_proto_library(
proto_library(
name = "running_games_proto",
srcs = ["running_games.proto"],
deps = [
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
swift_proto_library(
@@ -680,6 +698,7 @@ proto_library(
deps = [
":army_proto",
"//src/main/protobuf/net/eagle0/common:victory_condition_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
@@ -708,6 +727,7 @@ proto_library(
"//src/main/protobuf/net/eagle0/shardok/api:action_result_view_proto",
"//src/main/protobuf/net/eagle0/shardok/api:command_descriptor_proto",
"//src/main/protobuf/net/eagle0/shardok/storage:action_result_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
@@ -805,5 +825,6 @@ go_proto_library(
"//src/main/protobuf/net/eagle0/eagle/views:views_go_proto",
"//src/main/protobuf/net/eagle0/shardok/api:api_go_proto",
"//src/main/protobuf/net/eagle0/shardok/storage:storage_go_proto",
"//src/main/protobuf/scalapb:scalapb_go_proto",
],
)
@@ -23,6 +23,12 @@ import "src/main/protobuf/net/eagle0/eagle/internal/generated_text_request.proto
import "src/main/protobuf/net/eagle0/eagle/internal/hero.proto";
import "src/main/protobuf/net/eagle0/eagle/internal/province.proto";
import "src/main/protobuf/net/eagle0/eagle/internal/shardok_battle.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.internal";
@@ -11,6 +11,13 @@ import "src/main/protobuf/net/eagle0/eagle/common/combat_unit.proto";
import "src/main/protobuf/net/eagle0/eagle/common/tribute_amount.proto";
import "src/main/protobuf/net/eagle0/eagle/internal/supplies.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.internal";
option java_outer_classname = "Army";
@@ -58,10 +65,10 @@ message HostileArmyGroupStatus {
message AwaitingDecision {}
message AwaitingFreeForAll {}
message TributeDemanded {
.net.eagle0.eagle.common.TributeAmount tribute_amount = 1;
.net.eagle0.eagle.common.TributeAmount tribute_amount = 1 [(scalapb.field).no_box = true];
}
message TributePaid {
.net.eagle0.eagle.common.TributeAmount tribute_amount = 1;
.net.eagle0.eagle.common.TributeAmount tribute_amount = 1 [(scalapb.field).no_box = true];
}
message Attacking {}
message Withdrawing {}
@@ -12,6 +12,13 @@ import "src/main/protobuf/net/eagle0/eagle/internal/faction.proto";
import "src/main/protobuf/net/eagle0/eagle/internal/faction_relationship.proto";
import "src/main/protobuf/net/eagle0/eagle/views/province_view.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.internal";
option java_outer_classname = "ChangedFaction";
@@ -17,6 +17,13 @@ import "src/main/protobuf/net/eagle0/eagle/internal/province.proto";
import "src/main/protobuf/net/eagle0/eagle/internal/supplies.proto";
import "src/main/protobuf/net/eagle0/eagle/internal/unaffiliated_hero.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.internal";
option java_outer_classname = "ChangedProvince";
@@ -8,6 +8,13 @@ package net.eagle0.eagle.internal;
import "src/main/protobuf/net/eagle0/eagle/internal/generated_text_request.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.internal";
option java_outer_classname = "ClientText";
@@ -9,13 +9,20 @@ package net.eagle0.eagle.internal;
import "google/protobuf/wrappers.proto";
import "src/main/protobuf/net/eagle0/eagle/common/date.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.internal";
option java_outer_classname = "EventForChronicle";
option objc_class_prefix = "E0G";
message EventForChronicle {
.net.eagle0.eagle.common.Date date = 1;
.net.eagle0.eagle.common.Date date = 1 [(scalapb.field).no_box = true];
EventForChronicleDetails details = 2;
}
@@ -11,13 +11,20 @@ import "src/main/protobuf/net/eagle0/eagle/common/diplomacy_offer_status.proto";
import "src/main/protobuf/net/eagle0/eagle/common/unaffiliated_hero_quest.proto";
import "src/main/protobuf/net/eagle0/eagle/views/battalion_view.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.internal";
option java_outer_classname = "EventForChronicle";
option objc_class_prefix = "E0G";
message EventForHeroBackstory {
.net.eagle0.eagle.common.Date date = 1;
.net.eagle0.eagle.common.Date date = 1 [(scalapb.field).no_box = true];
EventForHeroBackstoryDetails details = 2;
}
@@ -11,6 +11,13 @@ import "src/main/protobuf/net/eagle0/eagle/common/diplomacy_offer.proto";
import "src/main/protobuf/net/eagle0/eagle/internal/faction_relationship.proto";
import "src/main/protobuf/net/eagle0/eagle/views/province_view.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.internal";
option java_outer_classname = "Faction";
@@ -10,6 +10,13 @@ import "src/main/protobuf/net/eagle0/eagle/common/date.proto";
import "src/main/protobuf/net/eagle0/eagle/internal/action_result.proto";
import "src/main/protobuf/net/eagle0/eagle/internal/game_state.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.internal";
option java_outer_classname = "Game";
@@ -25,8 +32,8 @@ message PartialGameIndex {
int64 game_id = 1;
message Entry {
.net.eagle0.eagle.common.Date starting_date = 1;
.net.eagle0.eagle.common.Date ending_date = 2;
.net.eagle0.eagle.common.Date starting_date = 1 [(scalapb.field).no_box = true];
.net.eagle0.eagle.common.Date ending_date = 2 [(scalapb.field).no_box = true];
int64 starting_index = 3;
}
repeated Entry entries = 2;
@@ -10,6 +10,13 @@ import "src/main/protobuf/net/eagle0/eagle/common/battalion_type.proto";
import "src/main/protobuf/net/eagle0/eagle/common/province_order_type.proto";
import "src/main/protobuf/net/eagle0/eagle/internal/battalion.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.internal";
option java_outer_classname = "GameParameters";
@@ -20,6 +20,13 @@ import "src/main/protobuf/net/eagle0/eagle/internal/province.proto";
import "src/main/protobuf/net/eagle0/eagle/internal/run_status.proto";
import "src/main/protobuf/net/eagle0/eagle/internal/shardok_battle.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.internal";
option java_outer_classname = "GameState";
@@ -30,7 +37,7 @@ message GameState {
int32 current_round_id = 1;
.net.eagle0.eagle.common.RoundPhase current_phase = 2;
.net.eagle0.eagle.common.Date current_date = 3;
.net.eagle0.eagle.common.Date current_date = 3 [(scalapb.field).no_box = true];
int32 action_result_count = 12;
map<int32, Province> provinces = 4;
@@ -15,6 +15,13 @@ import "src/main/protobuf/net/eagle0/eagle/common/unaffiliated_hero_quest.proto"
import "src/main/protobuf/net/eagle0/eagle/internal/event_for_chronicle.proto";
import "src/main/protobuf/net/eagle0/eagle/internal/event_for_hero_backstory.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.internal";
option java_outer_classname = "LLMRequest";
@@ -131,10 +138,10 @@ message CapturedHeroImprisonedMessage {
}
message ChronicleUpdateMessage {
.net.eagle0.eagle.common.Date current_date = 1;
.net.eagle0.eagle.common.Date current_date = 1 [(scalapb.field).no_box = true];
message PreviousChronicleEntry {
.net.eagle0.eagle.common.Date date = 1;
.net.eagle0.eagle.common.Date date = 1 [(scalapb.field).no_box = true];
string generated_text_id = 2;
}
repeated PreviousChronicleEntry previous_entries = 2;
@@ -12,6 +12,13 @@ import "src/main/protobuf/net/eagle0/eagle/common/hero_backstory_version.proto";
import "src/main/protobuf/net/eagle0/eagle/common/profession.proto";
import "src/main/protobuf/net/eagle0/eagle/internal/event_for_hero_backstory.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.internal";
option java_outer_classname = "Hero";
@@ -6,6 +6,8 @@ syntax = "proto3";
package net.eagle0.eagle.internal;
import "src/main/protobuf/scalapb/scalapb.proto";
import "src/main/protobuf/net/eagle0/eagle/internal/generated_text_request.proto";
option java_multiple_files = true;
@@ -15,5 +17,5 @@ option objc_class_prefix = "E0G";
message LLMResponse {
string response_text = 1;
.net.eagle0.eagle.internal.GeneratedTextRequest llm_request = 2;
.net.eagle0.eagle.internal.GeneratedTextRequest llm_request = 2 [(scalapb.field).no_box = true];
}
@@ -19,6 +19,13 @@ import "src/main/protobuf/net/eagle0/eagle/internal/deferred_change.proto";
import "src/main/protobuf/net/eagle0/eagle/internal/supplies.proto";
import "src/main/protobuf/net/eagle0/eagle/internal/unaffiliated_hero.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.internal";
option java_outer_classname = "Province";
@@ -6,6 +6,13 @@ syntax = "proto3";
package net.eagle0.eagle.internal;
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.internal";
option java_outer_classname = "RunningGames";
@@ -9,6 +9,13 @@ package net.eagle0.eagle.internal;
import "src/main/protobuf/net/eagle0/common/victory_condition.proto";
import "src/main/protobuf/net/eagle0/eagle/internal/army.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.internal";
option java_outer_classname = "ActionResult";
@@ -10,6 +10,13 @@ import "src/main/protobuf/net/eagle0/shardok/api/action_result_view.proto";
import "src/main/protobuf/net/eagle0/shardok/api/command_descriptor.proto";
import "src/main/protobuf/net/eagle0/shardok/storage/action_result.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.internal";
option java_outer_classname = "ShardokResults";
@@ -1,7 +1,7 @@
load("@build_bazel_rules_swift//proto:proto.bzl", "swift_proto_library")
load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
load("@io_bazel_rules_scala//scala_proto:scala_proto.bzl", "scala_proto_library")
load("@rules_proto//proto:defs.bzl", "proto_library")
load("@rules_scala//scala_proto:scala_proto.bzl", "scala_proto_library")
swift_proto_library(
name = "action_result_view_swift_proto",
@@ -32,6 +32,7 @@ proto_library(
":game_state_view_proto",
"//src/main/protobuf/net/eagle0/eagle/common:action_result_notification_details_proto",
"//src/main/protobuf/net/eagle0/eagle/common:action_result_type_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -62,6 +63,7 @@ proto_library(
visibility = ["//visibility:public"],
deps = [
"//src/main/protobuf/net/eagle0/eagle/common:combat_unit_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
],
)
@@ -159,6 +161,7 @@ proto_library(
deps = [
":faction_relationship_view_proto",
"//src/main/protobuf/net/eagle0/eagle/common:diplomacy_offer_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -204,6 +207,7 @@ proto_library(
"//src/main/protobuf/net/eagle0/eagle/common:chronicle_entry_proto",
"//src/main/protobuf/net/eagle0/eagle/common:date_proto",
"//src/main/protobuf/net/eagle0/eagle/common:round_phase_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -243,6 +247,7 @@ proto_library(
":stat_with_condition_proto",
"//src/main/protobuf/net/eagle0/eagle/common:gender_proto",
"//src/main/protobuf/net/eagle0/eagle/common:profession_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -319,6 +324,7 @@ proto_library(
"//src/main/protobuf/net/eagle0/eagle/common:province_order_type_proto",
"//src/main/protobuf/net/eagle0/eagle/common:recruitment_info_proto",
"//src/main/protobuf/net/eagle0/eagle/common:unaffiliated_hero_type_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -373,6 +379,7 @@ proto_library(
visibility = ["//visibility:public"],
deps = [
"//src/main/protobuf/net/eagle0/common:hostility_proto",
"//src/main/protobuf/scalapb:scalapb_proto",
"@com_google_protobuf//:wrappers_proto",
],
)
@@ -397,5 +404,6 @@ go_proto_library(
deps = [
"//src/main/protobuf/net/eagle0/common:common_go_proto",
"//src/main/protobuf/net/eagle0/eagle/common:common_go_proto",
"//src/main/protobuf/scalapb:scalapb_go_proto",
],
)
@@ -11,6 +11,13 @@ import "src/main/protobuf/net/eagle0/eagle/common/action_result_notification_det
import "src/main/protobuf/net/eagle0/eagle/common/action_result_type.proto";
import "src/main/protobuf/net/eagle0/eagle/views/game_state_view.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.views";
option java_outer_classname = "ActionResultView";
@@ -8,6 +8,13 @@ package net.eagle0.eagle.views;
import "src/main/protobuf/net/eagle0/eagle/common/combat_unit.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.views";
option java_outer_classname = "ArmyView";
@@ -10,6 +10,13 @@ import "google/protobuf/wrappers.proto";
import "src/main/protobuf/net/eagle0/eagle/common/diplomacy_offer.proto";
import "src/main/protobuf/net/eagle0/eagle/views/faction_relationship_view.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.views";
option java_outer_classname = "FactionView";
@@ -17,6 +17,13 @@ import "src/main/protobuf/net/eagle0/eagle/views/hero_view.proto";
import "src/main/protobuf/net/eagle0/eagle/views/province_view.proto";
import "src/main/protobuf/net/eagle0/eagle/views/shardok_battle_view.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.views";
option java_outer_classname = "GameStateView";
@@ -25,7 +32,7 @@ option objc_class_prefix = "E0G";
message GameStateView {
int32 current_round_id = 1;
.net.eagle0.eagle.common.RoundPhase current_phase = 2;
.net.eagle0.eagle.common.Date current_date = 3;
.net.eagle0.eagle.common.Date current_date = 3 [(scalapb.field).no_box = true];
map<int32, ProvinceView> provinces = 4;
map<int32, HeroView> heroes = 5;
@@ -11,6 +11,13 @@ import "src/main/protobuf/net/eagle0/eagle/common/gender.proto";
import "src/main/protobuf/net/eagle0/eagle/common/profession.proto";
import "src/main/protobuf/net/eagle0/eagle/views/stat_with_condition.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.views";
option java_outer_classname = "HeroView";
@@ -18,6 +18,13 @@ import "src/main/protobuf/net/eagle0/eagle/views/battalion_view.proto";
import "src/main/protobuf/net/eagle0/eagle/views/incoming_army_view.proto";
import "src/main/protobuf/net/eagle0/eagle/views/stat_with_condition.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.views";
option java_outer_classname = "ProvinceView";
@@ -9,6 +9,13 @@ package net.eagle0.eagle.views;
import "google/protobuf/wrappers.proto";
import "src/main/protobuf/net/eagle0/common/hostility.proto";
import "src/main/protobuf/scalapb/scalapb.proto";
option (scalapb.options) = {
scope: FILE
collection_type: "Vector"
};
option java_multiple_files = true;
option java_package = "net.eagle0.eagle.views";
option java_outer_classname = "ShardokBattleView";
@@ -1,8 +1,8 @@
load("@build_bazel_rules_swift//proto:proto.bzl", "swift_proto_library")
load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
load("@io_bazel_rules_scala//scala_proto:scala_proto.bzl", "scala_proto_library")
load("@rules_cc//cc:defs.bzl", "cc_proto_library")
load("@rules_proto//proto:defs.bzl", "proto_library")
load("@rules_scala//scala_proto:scala_proto.bzl", "scala_proto_library")
swift_proto_library(
name = "action_result_view_swift_proto",
@@ -1,8 +1,8 @@
load("@build_bazel_rules_swift//proto:proto.bzl", "swift_proto_library")
load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
load("@io_bazel_rules_scala//scala_proto:scala_proto.bzl", "scala_proto_library")
load("@rules_cc//cc:defs.bzl", "cc_proto_library")
load("@rules_proto//proto:defs.bzl", "proto_library")
load("@rules_scala//scala_proto:scala_proto.bzl", "scala_proto_library")
swift_proto_library(
name = "action_type_swift_proto",
@@ -1,8 +1,8 @@
load("@build_bazel_rules_swift//proto:proto.bzl", "swift_proto_library")
load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
load("@io_bazel_rules_scala//scala_proto:scala_proto.bzl", "scala_proto_library")
load("@rules_cc//cc:defs.bzl", "cc_proto_library")
load("@rules_proto//proto:defs.bzl", "proto_library")
load("@rules_scala//scala_proto:scala_proto.bzl", "scala_proto_library")
swift_proto_library(
name = "action_result_swift_proto",
+16
View File
@@ -0,0 +1,16 @@
load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
load("@rules_proto//proto:defs.bzl", "proto_library")
proto_library(
name = "scalapb_proto",
srcs = ["scalapb.proto"],
visibility = ["//visibility:public"],
deps = ["@com_google_protobuf//:descriptor_proto"],
)
go_proto_library(
name = "scalapb_go_proto",
importpath = "github.com/nolen777/eagle0/src/main/protobuf/scalapb",
proto = ":scalapb_proto",
visibility = ["//visibility:public"],
)
+375
View File
@@ -0,0 +1,375 @@
syntax = "proto2";
package scalapb;
import "google/protobuf/descriptor.proto";
option java_package = "scalapb.options";
option (options) = {
package_name: "scalapb.options"
flat_package: true
};
message ScalaPbOptions {
// If set then it overrides the java_package and package.
optional string package_name = 1;
// If true, the compiler does not append the proto base file name
// into the generated package name. If false (the default), the
// generated scala package name is the package_name.basename where
// basename is the proto file name without the .proto extension.
optional bool flat_package = 2;
// Adds the following imports at the top of the file (this is meant
// to provide implicit TypeMappers)
repeated string import = 3;
// Text to add to the generated scala file. This can be used only
// when single_file is true.
repeated string preamble = 4;
// If true, all messages and enums (but not services) will be written
// to a single Scala file.
optional bool single_file = 5;
// By default, wrappers defined at
// https://github.com/google/protobuf/blob/master/src/google/protobuf/wrappers.proto,
// are mapped to an Option[T] where T is a primitive type. When this field
// is set to true, we do not perform this transformation.
optional bool no_primitive_wrappers = 7;
// DEPRECATED. In ScalaPB <= 0.5.47, it was necessary to explicitly enable
// primitive_wrappers. This field remains here for backwards compatibility,
// but it has no effect on generated code. It is an error to set both
// `primitive_wrappers` and `no_primitive_wrappers`.
optional bool primitive_wrappers = 6;
// Scala type to be used for repeated fields. If unspecified,
// `scala.collection.Seq` will be used.
optional string collection_type = 8;
// If set to true, all generated messages in this file will preserve unknown
// fields.
optional bool preserve_unknown_fields = 9 [default=true];
// If defined, sets the name of the file-level object that would be generated. This
// object extends `GeneratedFileObject` and contains descriptors, and list of message
// and enum companions.
optional string object_name = 10;
// Whether to apply the options only to this file, or for the entire package (and its subpackages)
enum OptionsScope {
// Apply the options for this file only (default)
FILE = 0;
// Apply the options for the entire package and its subpackages.
PACKAGE = 1;
}
// Experimental: scope to apply the given options.
optional OptionsScope scope = 11;
// If true, lenses will be generated.
optional bool lenses = 12 [default=true];
// If true, then source-code info information will be included in the
// generated code - normally the source code info is cleared out to reduce
// code size. The source code info is useful for extracting source code
// location from the descriptors as well as comments.
optional bool retain_source_code_info = 13;
// Scala type to be used for maps. If unspecified,
// `scala.collection.immutable.Map` will be used.
optional string map_type = 14;
// If true, no default values will be generated in message constructors.
// This setting can be overridden at the message-level and for individual
// fields.
optional bool no_default_values_in_constructor = 15;
/* Naming convention for generated enum values */
enum EnumValueNaming {
AS_IN_PROTO = 0; // Enum value names in Scala use the same name as in the proto
CAMEL_CASE = 1; // Convert enum values to CamelCase in Scala.
}
optional EnumValueNaming enum_value_naming = 16;
// Indicate if prefix (enum name + optional underscore) should be removed in scala code
// Strip is applied before enum value naming changes.
optional bool enum_strip_prefix = 17 [default=false];
// Scala type to use for bytes fields.
optional string bytes_type = 21;
// Enable java conversions for this file.
optional bool java_conversions = 23;
// AuxMessageOptions enables you to set message-level options through package-scoped options.
// This is useful when you can't add a dependency on scalapb.proto from the proto file that
// defines the message.
message AuxMessageOptions {
// The fully-qualified name of the message in the proto name space.
optional string target = 1;
// Options to apply to the message. If there are any options defined on the target message
// they take precedence over the options.
optional MessageOptions options = 2;
}
// AuxFieldOptions enables you to set field-level options through package-scoped options.
// This is useful when you can't add a dependency on scalapb.proto from the proto file that
// defines the field.
message AuxFieldOptions {
// The fully-qualified name of the field in the proto name space.
optional string target = 1;
// Options to apply to the field. If there are any options defined on the target message
// they take precedence over the options.
optional FieldOptions options = 2;
}
// AuxEnumOptions enables you to set enum-level options through package-scoped options.
// This is useful when you can't add a dependency on scalapb.proto from the proto file that
// defines the enum.
message AuxEnumOptions {
// The fully-qualified name of the enum in the proto name space.
optional string target = 1;
// Options to apply to the enum. If there are any options defined on the target enum
// they take precedence over the options.
optional EnumOptions options = 2;
}
// AuxEnumValueOptions enables you to set enum value level options through package-scoped
// options. This is useful when you can't add a dependency on scalapb.proto from the proto
// file that defines the enum.
message AuxEnumValueOptions {
// The fully-qualified name of the enum value in the proto name space.
optional string target = 1;
// Options to apply to the enum value. If there are any options defined on
// the target enum value they take precedence over the options.
optional EnumValueOptions options = 2;
}
// List of message options to apply to some messages.
repeated AuxMessageOptions aux_message_options = 18;
// List of message options to apply to some fields.
repeated AuxFieldOptions aux_field_options = 19;
// List of message options to apply to some enums.
repeated AuxEnumOptions aux_enum_options = 20;
// List of enum value options to apply to some enum values.
repeated AuxEnumValueOptions aux_enum_value_options = 22;
// List of preprocessors to apply.
repeated string preprocessors = 24;
repeated FieldTransformation field_transformations = 25;
// Ignores all transformations for this file. This is meant to allow specific files to
// opt out from transformations inherited through package-scoped options.
optional bool ignore_all_transformations = 26;
// If true, getters will be generated.
optional bool getters = 27 [default=true];
// For use in tests only. Inhibit Java conversions even when when generator parameters
// request for it.
optional bool test_only_no_java_conversions = 999;
extensions 1000 to max;
}
extend google.protobuf.FileOptions {
// File-level optionals for ScalaPB.
// Extension number officially assigned by protobuf-global-extension-registry@google.com
optional ScalaPbOptions options = 1020;
}
message MessageOptions {
// Additional classes and traits to mix in to the case class.
repeated string extends = 1;
// Additional classes and traits to mix in to the companion object.
repeated string companion_extends = 2;
// Custom annotations to add to the generated case class.
repeated string annotations = 3;
// All instances of this message will be converted to this type. An implicit TypeMapper
// must be present.
optional string type = 4;
// Custom annotations to add to the companion object of the generated class.
repeated string companion_annotations = 5;
// Additional classes and traits to mix in to generated sealed_oneof base trait.
repeated string sealed_oneof_extends = 6;
// If true, when this message is used as an optional field, do not wrap it in an `Option`.
// This is equivalent of setting `(field).no_box` to true on each field with the message type.
optional bool no_box = 7;
// Custom annotations to add to the generated `unknownFields` case class field.
repeated string unknown_fields_annotations = 8;
// If true, no default values will be generated in message constructors.
// If set (to true or false), the message-level setting overrides the
// file-level value, and can be overridden by the field-level setting.
optional bool no_default_values_in_constructor = 9;
extensions 1000 to max;
}
extend google.protobuf.MessageOptions {
// Message-level optionals for ScalaPB.
// Extension number officially assigned by protobuf-global-extension-registry@google.com
optional MessageOptions message = 1020;
}
// Represents a custom Collection type in Scala. This allows ScalaPB to integrate with
// collection types that are different enough from the ones in the standard library.
message Collection {
// Type of the collection
optional string type = 1;
// Set to true if this collection type is not allowed to be empty, for example
// cats.data.NonEmptyList. When true, ScalaPB will not generate `clearX` for the repeated
// field and not provide a default argument in the constructor.
optional bool non_empty = 2;
// An Adapter is a Scala object available at runtime that provides certain static methods
// that can operate on this collection type.
optional string adapter = 3;
}
message FieldOptions {
optional string type = 1;
optional string scala_name = 2;
// Can be specified only if this field is repeated. If unspecified,
// it falls back to the file option named `collection_type`, which defaults
// to `scala.collection.Seq`.
optional string collection_type = 3;
optional Collection collection = 8;
// If the field is a map, you can specify custom Scala types for the key
// or value.
optional string key_type = 4;
optional string value_type = 5;
// Custom annotations to add to the field.
repeated string annotations = 6;
// Can be specified only if this field is a map. If unspecified,
// it falls back to the file option named `map_type` which defaults to
// `scala.collection.immutable.Map`
optional string map_type = 7;
// If true, no default value will be generated for this field in the message
// constructor. If this field is set, it has the highest precedence and overrides the
// values at the message-level and file-level.
optional bool no_default_value_in_constructor = 9;
// Do not box this value in Option[T]. If set, this overrides MessageOptions.no_box
optional bool no_box = 30;
// Like no_box it does not box a value in Option[T], but also fails parsing when a value
// is not provided. This enables to emulate required fields in proto3.
optional bool required = 31;
extensions 1000 to max;
}
extend google.protobuf.FieldOptions {
// Field-level optionals for ScalaPB.
// Extension number officially assigned by protobuf-global-extension-registry@google.com
optional FieldOptions field = 1020;
}
message EnumOptions {
// Additional classes and traits to mix in to the base trait
repeated string extends = 1;
// Additional classes and traits to mix in to the companion object.
repeated string companion_extends = 2;
// All instances of this enum will be converted to this type. An implicit TypeMapper
// must be present.
optional string type = 3;
// Custom annotations to add to the generated enum's base class.
repeated string base_annotations = 4;
// Custom annotations to add to the generated trait.
repeated string recognized_annotations = 5;
// Custom annotations to add to the generated Unrecognized case class.
repeated string unrecognized_annotations = 6;
extensions 1000 to max;
}
extend google.protobuf.EnumOptions {
// Enum-level optionals for ScalaPB.
// Extension number officially assigned by protobuf-global-extension-registry@google.com
//
// The field is called enum_options and not enum since enum is not allowed in Java.
optional EnumOptions enum_options = 1020;
}
message EnumValueOptions {
// Additional classes and traits to mix in to an individual enum value.
repeated string extends = 1;
// Name in Scala to use for this enum value.
optional string scala_name = 2;
// Custom annotations to add to the generated case object for this enum value.
repeated string annotations = 3;
extensions 1000 to max;
}
extend google.protobuf.EnumValueOptions {
// Enum-level optionals for ScalaPB.
// Extension number officially assigned by protobuf-global-extension-registry@google.com
optional EnumValueOptions enum_value = 1020;
}
message OneofOptions {
// Additional traits to mix in to a oneof.
repeated string extends = 1;
// Name in Scala to use for this oneof field.
optional string scala_name = 2;
extensions 1000 to max;
}
extend google.protobuf.OneofOptions {
// Enum-level optionals for ScalaPB.
// Extension number officially assigned by protobuf-global-extension-registry@google.com
optional OneofOptions oneof = 1020;
}
enum MatchType {
CONTAINS = 0;
EXACT = 1;
PRESENCE = 2;
}
message FieldTransformation {
optional google.protobuf.FieldDescriptorProto when = 1;
optional MatchType match_type = 2 [default=CONTAINS];
optional google.protobuf.FieldOptions set = 3;
}
message PreprocessorOutput {
map<string, ScalaPbOptions> options_by_file = 1;
}

Some files were not shown because too many files have changed in this diff Show More