feat(ModularBot): pluggable bot with 4 guns, phantom meteor movement, radar harness

- Gun harness: virtual bullet tracker, rolling fitness, auto-selector
- Guns: head-on, linear (extrapolation), circular (integrated formula), tsetlin machine (learning)
- Movement: phantom meteor gravity engine (danger histograms, phantom bullets, fire detection)
- Radar: harness + radar_lock adapter
- Color-coded modules: turret/bullet color per gun, body per movement, scan per radar
- Beats Target, SpinBot, Crazy, TrackFire in 10-round battles
This commit is contained in:
2026-09-20 00:37:10 +02:00
parent c9191b7afb
commit 254c7dc997
39 changed files with 2630 additions and 30 deletions
+11
View File
@@ -0,0 +1,11 @@
{
"name": "ModularBot",
"version": "0.1.0",
"authors": ["Davide Cappellini"],
"description": "Plugin gun architecture — head-on gun via virtual bullet harness",
"homepage": "",
"countryCodes": ["IT"],
"gameTypes": ["classic", "1v1"],
"platform": "Nim",
"programmingLang": "Nim"
}
+12
View File
@@ -0,0 +1,12 @@
# Package
version = "0.1.0"
author = "Davide Cappellini"
description = "Modular gun harness bot — plugin architecture tracer bullet"
license = "MIT"
srcDir = "src"
bin = @["ModularBot"]
# Dependencies
requires "nim >= 2.0.0"
requires "robocode_tankroyale_botapi >= 1.0.7"
# gun_harness and radar_lock are in common_libs, wired via config.nims --path
+7
View File
@@ -0,0 +1,7 @@
--path:"../common_libs"
switch("outdir", "out")
switch("path", thisDir() & "/src")
# begin Nimble config (version 2)
when withDir(thisDir(), system.fileExists("nimble.paths")):
include "nimble.paths"
# end Nimble config
+11
View File
@@ -0,0 +1,11 @@
{
"name": "ModularBot",
"version": "0.1.0",
"authors": ["Davide Cappellini"],
"description": "Plugin gun architecture — head-on gun via virtual bullet harness",
"homepage": "",
"countryCodes": ["IT"],
"gameTypes": ["classic", "1v1"],
"platform": "Nim",
"programmingLang": "Nim"
}
+187
View File
@@ -0,0 +1,187 @@
## ModularBot — plugin gun architecture tracer bullet.
## Guns: HeadOnGun (0), LinearGun (1), TsetlinGun (2), CircularGun (3) via GunHarness.
## Radar: RadarLockModule via radar harness.
## Movement: OscillatorModule (perpendicular strafing).
import std/[math, os, strformat]
import robocode_tankroyale_botapi
import radar_harness/radar_interface
import radars/radar_lock_module
import gun_harness/gun_interface
import gun_harness/virtual_bullets as vb
import gun_harness/selector
import guns/head_on
import guns/linear
import guns/circular
import guns/tsetlin
import movements/phantom_meteor
const botJsonPath = currentSourcePath().parentDir / "ModularBot.json"
const DebugVBullets = false
const DebugCircular = false
const GunNames = ["HeadOn", "Linear", "Tsetlin", "Circular"]
type
ModularBot = ref object of Bot
hasContact: bool
enemyBearing: float
lastState: WorldState
radar: RadarLockModule
tracker: VirtualTracker
headOn: HeadOnGun
linear: LinearGun
circular: CircularGun
tsetlin: TsetlinGun
mover: PhantomMeteorModule
virtualHits: int
virtualMiss: int
tick: int
currentGun: int
proc buildState(bot: ModularBot, ex, ey, espeed, eheading, eenergy: float): WorldState =
WorldState(
enemyX: ex,
enemyY: ey,
enemySpeed: espeed,
enemyHeading: eheading,
enemyEnergy: eenergy,
selfX: getX(),
selfY: getY(),
selfSpeed: getSpeed(),
selfHeading: getDirection(),
selfRadarHeading: getRadarDirection(),
selfEnergy: getEnergy(),
arenaWidth: getArenaWidth().float,
arenaHeight: getArenaHeight().float,
tick: bot.tick,
)
method onScannedBot*(bot: ModularBot, e: ScannedBotEvent) =
bot.enemyBearing = directionTo(getX(), getY(), e.x, e.y)
bot.hasContact = true
bot.lastState = bot.buildState(e.x, e.y, e.speed, e.direction, e.energy)
# Collect predictions for all power bins from all guns
var headsUp: array[len(PowerBins), GunPrediction]
var linPreds: array[len(PowerBins), GunPrediction]
var tmPreds: array[len(PowerBins), GunPrediction]
var circPreds: array[len(PowerBins), GunPrediction]
for i in 0..<len(PowerBins):
headsUp[i] = bot.headOn.predict(bot.lastState, bulletSpeed(PowerBins[i]))
linPreds[i] = bot.linear.predict(bot.lastState, bulletSpeed(PowerBins[i]))
tmPreds[i] = bot.tsetlin.predict(bot.lastState, bulletSpeed(PowerBins[i]))
circPreds[i] = bot.circular.predict(bot.lastState, bulletSpeed(PowerBins[i]))
bot.tracker.spawnBullets(0, headsUp, bot.lastState)
bot.tracker.spawnBullets(1, linPreds, bot.lastState)
bot.tracker.spawnBullets(2, tmPreds, bot.lastState)
bot.tracker.spawnBullets(3, circPreds, bot.lastState)
# Resolve bullets that have travelled far enough
let st = bot.lastState
bot.tracker.tickBullets(st, proc(gunId: GunId, binIdx: int, fe: FeedbackEvent) =
case gunId
of 0: bot.headOn.onResult(fe)
of 1: bot.linear.onResult(fe)
of 2: bot.tsetlin.onResult(fe)
of 3:
bot.circular.onResult(fe)
when DebugCircular:
let ax = st.enemyX
let ay = st.enemyY
echo fmt"[circ-vb] predicted=({fe.prediction.x:.0f},{fe.prediction.y:.0f}) actual=({ax:.0f},{ay:.0f}) miss={fe.missDistance:.1f}px hit={fe.hit}"
else: discard
if fe.hit: inc bot.virtualHits else: inc bot.virtualMiss
when DebugVBullets:
let total = bot.virtualHits + bot.virtualMiss
let pct = if total > 0: bot.virtualHits.float / total.float * 100.0 else: 0.0
echo fmt"[vbullet] gun={gunId} bin={binIdx} miss={fe.missDistance:.1f}px hit={fe.hit} | total hits={bot.virtualHits}/{total} ({pct:.1f}%)"
)
# Gun selection + fire
let (selectedGun, _, power) = selectShot(bot.tracker)
# Log gun switch + update turret/bullet colors
if selectedGun != bot.currentGun:
echo fmt"[gun] switched: {GunNames[selectedGun]}"
bot.currentGun = selectedGun
case selectedGun
of 0: setTurretColor("#FF3333"); setBulletColor("#FF6666") # HeadOn: warm red
of 1: setTurretColor("#3366FF"); setBulletColor("#6699FF") # Linear: electric blue
of 2: setTurretColor("#9933FF"); setBulletColor("#CC66FF") # Tsetlin: violet
of 3: setTurretColor("#33CC33"); setBulletColor("#66FF66") # Circular: emerald
else: discard
let pred = case selectedGun
of 1: bot.linear.predict(bot.lastState, bulletSpeed(power))
of 2: bot.tsetlin.predict(bot.lastState, bulletSpeed(power))
of 3: bot.circular.predict(bot.lastState, bulletSpeed(power))
else: bot.headOn.predict(bot.lastState, bulletSpeed(power))
let target = aimAngle(getX(), getY(), pred.x, pred.y)
let gunDir = getGunDirection()
let gunHeat = getGunHeat()
let gunDelta = (target - gunDir) mod 360.0
var normDelta = gunDelta
if normDelta > 180.0: normDelta -= 360.0
elif normDelta < -180.0: normDelta += 360.0
if shouldFire(gunDir, target, gunHeat):
discard setFire(power)
# Turn gun toward predicted point every scan
setGunTurnRate(normDelta)
method onRoundEnded*(bot: ModularBot, e: RoundEndedEventForBot) =
discard # Skip detailed logging for now
method onRoundStarted*(bot: ModularBot, e: RoundStartedEvent) =
setAdjustGunForBodyTurn(true)
setAdjustRadarForBodyTurn(true)
setAdjustRadarForGunTurn(true)
setBodyColor("#FF9900") # PhantomMeteor: deep orange/gold
setRadarColor("#00CCCC") # RadarLock: cyan/teal
setScanColor("#33FFFF") # RadarLock scan arc: bright teal
bot.radar.init()
bot.hasContact = false
bot.tick = 0
bot.currentGun = -1 # Reset to trigger initial log on first selectShot
bot.mover.resetRound()
echo fmt"[gun] starting: {GunNames[0]}"
# tracker fitness persists across rounds (rolling window carries over)
method onGameStarted*(bot: ModularBot, e: GameStartedEventForBot) =
discard
method run*(bot: ModularBot) =
while isRunning():
inc bot.tick
if not bot.hasContact:
setTargetSpeed(0.0)
setTurnRate(0.0)
setRadarTurnRate(45.0)
go()
continue
# Movement harness: oscillate perpendicular to enemy
let (spd, tr) = bot.mover.computeMove(bot.lastState)
setTargetSpeed(spd)
setTurnRate(tr)
setRadarTurnRate(bot.radar.computeScan(bot.lastState))
go()
when isMainModule:
var bot = ModularBot(
tracker: vb.initTracker(4), # 0: HeadOn, 1: Linear, 2: Tsetlin, 3: Circular
headOn: HeadOnGun(),
linear: LinearGun(),
circular: CircularGun(),
tsetlin: initTsetlinGun(),
radar: RadarLockModule(),
mover: initPhantomMeteor(),
currentGun: -1,
)
start(bot, botJsonPath)
@@ -0,0 +1,17 @@
## Minimal ModularBot for testing.
import std/os
import robocode_tankroyale_botapi
const botJsonPath = currentSourcePath().parentDir / "ModularBot.json"
type ModularBot = ref object of Bot
method run*(bot: ModularBot) =
while isRunning():
setTargetSpeed(0.0)
setRadarTurnRate(45.0)
go()
when isMainModule:
var bot = ModularBot()
start(bot, botJsonPath)
+1
View File
@@ -0,0 +1 @@
--path:"../../common_libs"
+32
View File
@@ -0,0 +1,32 @@
import std/[os, strutils]
import test_framework/test_framework
import test_framework/battle_result
import test_framework/server_manager
import test_framework/bot_compiler
import test_framework/runner_process
const
modularBotDir = currentSourcePath().parentDir.parentDir
tfAdversaries = currentSourcePath().parentDir.parentDir.parentDir /
"common_libs" / "test_framework" / "adversaries"
sittingDuck = tfAdversaries / "SittingDuck"
# Skip if JARs are missing
if not fileExists("/home/davide/Projects/tank-royale/server/build/libs/robocode-tankroyale-server-0.35.5-all.jar") or
not fileExists("/home/davide/Projects/tank-royale/runner/examples/lib/robocode-tankroyale-runner.jar"):
echo "Skipping: Tank Royale JARs not found"
quit(0)
# Compile bots
let compiledBots = compileBots(@[modularBotDir, sittingDuck])
echo "Compiled bots: ", compiledBots
# Run battle
ensureServer()
let stdout = runBattleRunner(getServerUrl(), @[modularBotDir, sittingDuck], 3, 300000, true)
echo ""
echo "Raw battle runner output (last 50 lines):"
let lines = stdout.split('\n')
let start = max(0, lines.len - 50)
for i in start..<lines.len:
echo lines[i]
@@ -0,0 +1,58 @@
import std/[os, unittest, strformat]
import test_framework/test_framework
const
modularBotDir = currentSourcePath().parentDir.parentDir
samplesDir = "/home/davide/Downloads/robocode-tankroyale/sample-bots-nim-linux-1.0.7"
target = samplesDir / "Target"
spinBot = samplesDir / "SpinBot"
crazy = samplesDir / "Crazy"
trackFire = samplesDir / "TrackFire"
# Skip if JARs are missing
if not fileExists("/home/davide/Projects/tank-royale/server/build/libs/robocode-tankroyale-server-0.35.5-all.jar") or
not fileExists("/home/davide/Projects/tank-royale/runner/examples/lib/robocode-tankroyale-runner.jar"):
echo "Skipping: Tank Royale JARs not found"
quit(0)
proc extractFinalScores(r: BattleResult, enemyName: string): tuple[modularScore, enemyScore: int] =
var modularScore = 0
var enemyScore = 0
for b in r.results:
if b.name == "ModularBot": modularScore = b.totalScore
if b.name == enemyName: enemyScore = b.totalScore
(modularScore, enemyScore)
suite "ModularBot battle suite":
test "vs Target (stationary)":
echo "\n[1/4] ModularBot vs Target"
let r = runBattle(@[modularBotDir, target], rounds = 10, timeout = 180000)
let (mb, en) = extractFinalScores(r, "Target")
let winner = if mb > en: "ModularBot" else: "Target"
echo fmt" ModularBot: {mb}, Target: {en} → {winner} wins"
check mb > 0 or en > 0 # At least one score recorded
test "vs SpinBot (circular)":
echo "\n[2/4] ModularBot vs SpinBot"
let r = runBattle(@[modularBotDir, spinBot], rounds = 10, timeout = 180000)
let (mb, en) = extractFinalScores(r, "SpinBot")
let winner = if mb > en: "ModularBot" else: "SpinBot"
echo fmt" ModularBot: {mb}, SpinBot: {en} → {winner} wins"
check mb > 0 or en > 0
test "vs Crazy (unpredictable)":
echo "\n[3/4] ModularBot vs Crazy"
let r = runBattle(@[modularBotDir, crazy], rounds = 10, timeout = 180000)
let (mb, en) = extractFinalScores(r, "Crazy")
let winner = if mb > en: "ModularBot" else: "Crazy"
echo fmt" ModularBot: {mb}, Crazy: {en} → {winner} wins"
check mb > 0 or en > 0
test "vs TrackFire (fires back)":
echo "\n[4/4] ModularBot vs TrackFire"
let r = runBattle(@[modularBotDir, trackFire], rounds = 10, timeout = 180000)
let (mb, en) = extractFinalScores(r, "TrackFire")
let winner = if mb > en: "ModularBot" else: "TrackFire"
echo fmt" ModularBot: {mb}, TrackFire: {en} → {winner} wins"
check mb > 0 or en > 0
@@ -0,0 +1,24 @@
import std/os
import std/strutils
import test_framework/test_framework
if not existsEnv("TR_SERVER_JAR") or not existsEnv("TR_BATTLE_RUNNER"):
echo "Skipping: TR_SERVER_JAR / TR_BATTLE_RUNNER not set"
quit(0)
let modularBotDir = "/home/davide/Projects/SirRoboGarage/ModularBot_garage"
let sampleBotsDir = "/home/davide/Downloads/robocode-tankroyale/sample-bots-nim-linux-1.0.7"
echo "\n=== BATTLE 1: ModularBot vs SpinBot (Circular Movement) ==="
let r1 = runBattle(@[modularBotDir, sampleBotsDir / "SpinBot"], rounds = 10)
echo "\nBattle 1 Results:"
for bot in r1.results:
echo " " & bot.name & ": score=" & $bot.totalScore & " rank=" & $bot.rank
echo "Winners: " & r1.winners.join(", ")
echo "\n=== BATTLE 2: ModularBot vs Crazy (Unpredictable Movement) ==="
let r2 = runBattle(@[modularBotDir, sampleBotsDir / "Crazy"], rounds = 10)
echo "\nBattle 2 Results:"
for bot in r2.results:
echo " " & bot.name & ": score=" & $bot.totalScore & " rank=" & $bot.rank
echo "Winners: " & r2.winners.join(", ")
@@ -0,0 +1,36 @@
import std/os
import std/strutils
import test_framework/test_framework
if not existsEnv("TR_SERVER_JAR") or not existsEnv("TR_BATTLE_RUNNER"):
echo "Skipping: TR_SERVER_JAR / TR_BATTLE_RUNNER not set"
quit(0)
let modularBotDir = "/home/davide/Projects/SirRoboGarage/ModularBot_garage"
let sampleBotsDir = "/home/davide/Downloads/robocode-tankroyale/sample-bots-nim-linux-1.0.7"
echo "\n" & "=".repeat(60)
echo "BATTLE 1: ModularBot vs SpinBot (Circular Movement)"
echo "=".repeat(60)
let r1 = runBattle(@[modularBotDir, sampleBotsDir / "SpinBot"], rounds = 10)
echo "\nRound Details:"
for i, round in r1.rounds:
echo " Round " & $i & ":"
for bot in round.results:
echo " " & bot.name & ": score=" & $bot.score & " rank=" & $bot.rank & " survived=" & $bot.survived
echo "\nFinal Scores:"
for bot in r1.results:
echo " " & bot.name & ": score=" & $bot.totalScore & " rank=" & $bot.rank & " firstPlaces=" & $bot.firstPlaces & " survived=" & $bot.survivalCount
echo "\n" & "=".repeat(60)
echo "BATTLE 2: ModularBot vs Crazy (Unpredictable Movement)"
echo "=".repeat(60)
let r2 = runBattle(@[modularBotDir, sampleBotsDir / "Crazy"], rounds = 10)
echo "\nRound Details:"
for i, round in r2.rounds:
echo " Round " & $i & ":"
for bot in round.results:
echo " " & bot.name & ": score=" & $bot.score & " rank=" & $bot.rank & " survived=" & $bot.survived
echo "\nFinal Scores:"
for bot in r2.results:
echo " " & bot.name & ": score=" & $bot.totalScore & " rank=" & $bot.rank & " firstPlaces=" & $bot.firstPlaces & " survived=" & $bot.survivalCount
@@ -0,0 +1,34 @@
import std/os
import std/strutils
import test_framework/test_framework
if not existsEnv("TR_SERVER_JAR") or not existsEnv("TR_BATTLE_RUNNER"):
echo "Skipping: TR_SERVER_JAR / TR_BATTLE_RUNNER not set"
quit(0)
let modularBotDir = "/home/davide/Projects/SirRoboGarage/ModularBot_garage"
let sampleBotsDir = "/home/davide/Downloads/robocode-tankroyale/sample-bots-nim-linux-1.0.7"
echo "\n" & "=".repeat(60)
echo "BATTLE 1: ModularBot vs SpinBot (Circular Movement)"
echo "=".repeat(60)
let r1 = runBattle(@[modularBotDir, sampleBotsDir / "SpinBot"], rounds = 10)
echo "\nFinal Scores:"
for bot in r1.results:
echo " " & bot.name & ": score=" & $bot.totalScore & " rank=" & $bot.rank & " firstPlaces=" & $bot.firstPlaces & " survived=" & $bot.survivalCount
echo "Winner: " & r1.winners[0]
echo "\n" & "=".repeat(60)
echo "BATTLE 2: ModularBot vs Crazy (Unpredictable Movement)"
echo "=".repeat(60)
let r2 = runBattle(@[modularBotDir, sampleBotsDir / "Crazy"], rounds = 10)
echo "\nFinal Scores:"
for bot in r2.results:
echo " " & bot.name & ": score=" & $bot.totalScore & " rank=" & $bot.rank & " firstPlaces=" & $bot.firstPlaces & " survived=" & $bot.survivalCount
echo "Winner: " & r2.winners[0]
echo "\n" & "=".repeat(60)
echo "SUMMARY"
echo "=".repeat(60)
echo "Battle 1 (vs SpinBot): " & (if "ModularBot" in r1.winners: "WON" else: "LOST")
echo "Battle 2 (vs Crazy): " & (if "ModularBot" in r2.winners: "WON" else: "LOST")
@@ -0,0 +1,39 @@
## Unit test for ModularBot gun selection
import unittest
import gun_harness/virtual_bullets as vb
import gun_harness/selector
import gun_harness/gun_interface
suite "Gun Selection":
test "selector picks best gun and power":
# Create a simple tracker with mock vbullets
var t = initTracker(4)
# Spawn some bullets on gun 1 (linear) to simulate tracking history
let state = WorldState(
enemyX: 100, enemyY: 100, enemySpeed: 5.0, enemyHeading: 0.0,
selfX: 50, selfY: 50, selfSpeed: 0.0, selfHeading: 0.0,
selfRadarHeading: 0.0, selfEnergy: 100.0,
arenaWidth: 800, arenaHeight: 600, tick: 1
)
# Gun 1 (linear) predictions
var linPreds: array[len(PowerBins), GunPrediction]
for i in 0..<len(PowerBins):
linPreds[i] = GunPrediction(x: 105.0 + i.float, y: 105.0 + i.float)
t.spawnBullets(1, linPreds, state)
# Simulate a hit on one of the linear gun bullets
t.tickBullets(state, proc(gunId: GunId, binIdx: int, fe: FeedbackEvent) =
if gunId == 1 and binIdx == 0:
check fe.hit == false # Just verify callback works
)
# Select best shot
let (gunId, binIdx, power) = selectShot(t)
echo "[test] Selected gun=" & $gunId & " binIdx=" & $binIdx & " power=" & $power
check gunId >= 0 and gunId < 4 # Should be one of 4 guns
check binIdx >= 0 and binIdx < len(PowerBins) # Valid power bin
@@ -0,0 +1,20 @@
import std/os
import std/strutils
import test_framework/test_framework
if not existsEnv("TR_SERVER_JAR") or not existsEnv("TR_BATTLE_RUNNER"):
echo "Skipping: TR_SERVER_JAR / TR_BATTLE_RUNNER not set"
quit(0)
let modularBotDir = "/home/davide/Projects/SirRoboGarage/ModularBot_garage"
let sampleBotsDir = "/home/davide/Downloads/robocode-tankroyale/sample-bots-nim-linux-1.0.7"
echo "\nSingle round: ModularBot vs SpinBot"
let r = runBattle(@[modularBotDir, sampleBotsDir / "SpinBot"], rounds = 1)
for i, round in r.rounds:
echo "\nRound " & $i & " details:"
for bot in round.results:
echo " " & bot.name & ": score=" & $bot.score & " survived=" & $bot.survived
echo "\nFinal: " & r.results[0].name & " " & $r.results[0].totalScore & " vs " & r.results[1].name & " " & $r.results[1].totalScore
@@ -0,0 +1,70 @@
import std/[os, unittest]
import test_framework/test_framework
import test_framework/battle_result
import test_framework/server_manager
import test_framework/bot_compiler
import test_framework/runner_process
const
modularBotDir = currentSourcePath().parentDir.parentDir
tfAdversaries = currentSourcePath().parentDir.parentDir.parentDir /
"common_libs" / "test_framework" / "adversaries"
sittingDuck = tfAdversaries / "SittingDuck"
# Skip if JARs are missing
if not fileExists("/home/davide/Projects/tank-royale/server/build/libs/robocode-tankroyale-server-0.35.5-all.jar") or
not fileExists("/home/davide/Projects/tank-royale/runner/examples/lib/robocode-tankroyale-runner.jar"):
echo "Skipping: Tank Royale JARs not found"
quit(0)
suite "ModularBot basic battle":
test "beats SittingDuck in 1 round":
# Debug: manually compile and check
try:
let compiledBots = compileBots(@[modularBotDir, sittingDuck])
echo "Compiled bots: ", compiledBots
for bot in compiledBots:
if fileExists(bot):
echo " ✓ ", bot
else:
echo " ✗ MISSING: ", bot
except CatchableError as e:
echo "Compilation error: ", e.msg
raise
# Now run battle with longer timeout for ModularBot boot
ensureServer()
let stdout = runBattleRunner(getServerUrl(), @[modularBotDir, sittingDuck], 1, 180000, true)
echo ""
echo "Raw battle runner output:"
echo stdout
echo ""
let r = parseServerOutput(stdout)
echo ""
echo "=== Battle Result ==="
echo "Rounds: ", r.rounds.len
echo "Bots: ", r.bots
echo ""
echo "Final standings:"
for result in r.results:
echo " ", result.name, ": rank=", result.rank, " score=", result.totalScore,
" survived=", result.survivalCount, " first=", result.firstPlaces
echo ""
echo "Winners: ", r.winners
echo ""
# Basic checks
check r.rounds.len == 1
check r.results.len == 2
check "ModularBot" in r.bots
check "SittingDuck" in r.bots
# ModularBot should win
var modularResult: BotResult
for b in r.results:
if b.name == "ModularBot": modularResult = b
check modularResult.name == "ModularBot"
check modularResult.rank == 1
check "ModularBot" in r.winners