feat(ModularBot): anti-surfer gun + wave-surf movement module
- Anti-surfer gun: inverse GF targeting for wave-surfing enemies - Wave-surf movement: danger histogram dodge (not wired yet, needs movement selector) - 7 guns total, battle-tested Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Binary file not shown.
@@ -1,5 +1,5 @@
|
|||||||
## ModularBot — plugin gun architecture tracer bullet.
|
## ModularBot — plugin gun architecture tracer bullet.
|
||||||
## Guns: HeadOnGun (0), LinearGun (1), TsetlinGun (2), CircularGun (3), GFGun (4), PatternMatcherGun (5) via GunHarness.
|
## Guns: HeadOnGun (0), LinearGun (1), TsetlinGun (2), CircularGun (3), GFGun (4), PatternMatcherGun (5), AntiSurferGun (6) via GunHarness.
|
||||||
## Radar: RadarLockModule via radar harness.
|
## Radar: RadarLockModule via radar harness.
|
||||||
## Movement: OscillatorModule (perpendicular strafing).
|
## Movement: OscillatorModule (perpendicular strafing).
|
||||||
|
|
||||||
@@ -16,12 +16,13 @@ import guns/circular
|
|||||||
import guns/tsetlin
|
import guns/tsetlin
|
||||||
import guns/guess_factor
|
import guns/guess_factor
|
||||||
import guns/pattern_matcher
|
import guns/pattern_matcher
|
||||||
|
import guns/anti_surfer
|
||||||
import movements/phantom_meteor
|
import movements/phantom_meteor
|
||||||
|
|
||||||
const botJsonPath = currentSourcePath().parentDir / "ModularBot.json"
|
const botJsonPath = currentSourcePath().parentDir / "ModularBot.json"
|
||||||
const DebugVBullets = false
|
const DebugVBullets = false
|
||||||
const DebugCircular = false
|
const DebugCircular = false
|
||||||
const GunNames = ["HeadOn", "Linear", "Tsetlin", "Circular", "GuessFactor", "Pattern"]
|
const GunNames = ["HeadOn", "Linear", "Tsetlin", "Circular", "GuessFactor", "Pattern", "AntiSurf"]
|
||||||
|
|
||||||
type
|
type
|
||||||
ModularBot = ref object of Bot
|
ModularBot = ref object of Bot
|
||||||
@@ -36,6 +37,7 @@ type
|
|||||||
tsetlin: TsetlinGun
|
tsetlin: TsetlinGun
|
||||||
guessFactor: GFGun
|
guessFactor: GFGun
|
||||||
patternMatcher: PatternMatcherGun
|
patternMatcher: PatternMatcherGun
|
||||||
|
antiSurfer: AntiSurferGun
|
||||||
mover: PhantomMeteorModule
|
mover: PhantomMeteorModule
|
||||||
virtualHits: int
|
virtualHits: int
|
||||||
virtualMiss: int
|
virtualMiss: int
|
||||||
@@ -72,6 +74,7 @@ method onScannedBot*(bot: ModularBot, e: ScannedBotEvent) =
|
|||||||
var circPreds: array[len(PowerBins), GunPrediction]
|
var circPreds: array[len(PowerBins), GunPrediction]
|
||||||
var gfPreds: array[len(PowerBins), GunPrediction]
|
var gfPreds: array[len(PowerBins), GunPrediction]
|
||||||
var pmPreds: array[len(PowerBins), GunPrediction]
|
var pmPreds: array[len(PowerBins), GunPrediction]
|
||||||
|
var asPreds: array[len(PowerBins), GunPrediction]
|
||||||
for i in 0..<len(PowerBins):
|
for i in 0..<len(PowerBins):
|
||||||
headsUp[i] = bot.headOn.predict(bot.lastState, bulletSpeed(PowerBins[i]))
|
headsUp[i] = bot.headOn.predict(bot.lastState, bulletSpeed(PowerBins[i]))
|
||||||
linPreds[i] = bot.linear.predict(bot.lastState, bulletSpeed(PowerBins[i]))
|
linPreds[i] = bot.linear.predict(bot.lastState, bulletSpeed(PowerBins[i]))
|
||||||
@@ -79,6 +82,7 @@ method onScannedBot*(bot: ModularBot, e: ScannedBotEvent) =
|
|||||||
circPreds[i] = bot.circular.predict(bot.lastState, bulletSpeed(PowerBins[i]))
|
circPreds[i] = bot.circular.predict(bot.lastState, bulletSpeed(PowerBins[i]))
|
||||||
gfPreds[i] = bot.guessFactor.predict(bot.lastState, bulletSpeed(PowerBins[i]))
|
gfPreds[i] = bot.guessFactor.predict(bot.lastState, bulletSpeed(PowerBins[i]))
|
||||||
pmPreds[i] = bot.patternMatcher.predict(bot.lastState, bulletSpeed(PowerBins[i]))
|
pmPreds[i] = bot.patternMatcher.predict(bot.lastState, bulletSpeed(PowerBins[i]))
|
||||||
|
asPreds[i] = bot.antiSurfer.predict(bot.lastState, bulletSpeed(PowerBins[i]))
|
||||||
|
|
||||||
bot.tracker.spawnBullets(0, headsUp, bot.lastState)
|
bot.tracker.spawnBullets(0, headsUp, bot.lastState)
|
||||||
bot.tracker.spawnBullets(1, linPreds, bot.lastState)
|
bot.tracker.spawnBullets(1, linPreds, bot.lastState)
|
||||||
@@ -88,6 +92,7 @@ method onScannedBot*(bot: ModularBot, e: ScannedBotEvent) =
|
|||||||
bot.tracker.spawnBullets(3, circPreds, bot.lastState)
|
bot.tracker.spawnBullets(3, circPreds, bot.lastState)
|
||||||
bot.tracker.spawnBullets(4, gfPreds, bot.lastState)
|
bot.tracker.spawnBullets(4, gfPreds, bot.lastState)
|
||||||
bot.tracker.spawnBullets(5, pmPreds, bot.lastState)
|
bot.tracker.spawnBullets(5, pmPreds, bot.lastState)
|
||||||
|
bot.tracker.spawnBullets(6, asPreds, bot.lastState)
|
||||||
|
|
||||||
# Resolve bullets that have travelled far enough
|
# Resolve bullets that have travelled far enough
|
||||||
let st = bot.lastState
|
let st = bot.lastState
|
||||||
@@ -104,6 +109,7 @@ method onScannedBot*(bot: ModularBot, e: ScannedBotEvent) =
|
|||||||
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}"
|
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}"
|
||||||
of 4: bot.guessFactor.onResult(fe)
|
of 4: bot.guessFactor.onResult(fe)
|
||||||
of 5: bot.patternMatcher.onResult(fe)
|
of 5: bot.patternMatcher.onResult(fe)
|
||||||
|
of 6: bot.antiSurfer.onResult(fe)
|
||||||
else: discard
|
else: discard
|
||||||
if fe.hit: inc bot.virtualHits else: inc bot.virtualMiss
|
if fe.hit: inc bot.virtualHits else: inc bot.virtualMiss
|
||||||
when DebugVBullets:
|
when DebugVBullets:
|
||||||
@@ -126,6 +132,7 @@ method onScannedBot*(bot: ModularBot, e: ScannedBotEvent) =
|
|||||||
of 3: setTurretColor("#33CC33"); setBulletColor("#66FF66") # Circular: emerald
|
of 3: setTurretColor("#33CC33"); setBulletColor("#66FF66") # Circular: emerald
|
||||||
of 4: setTurretColor("#FFCC00"); setBulletColor("#FFE066") # GuessFactor: yellow
|
of 4: setTurretColor("#FFCC00"); setBulletColor("#FFE066") # GuessFactor: yellow
|
||||||
of 5: setTurretColor("#FF6600"); setBulletColor("#FF9944") # Pattern: orange
|
of 5: setTurretColor("#FF6600"); setBulletColor("#FF9944") # Pattern: orange
|
||||||
|
of 6: setTurretColor("#00CCFF"); setBulletColor("#66DDFF") # AntiSurf: cyan
|
||||||
else: discard
|
else: discard
|
||||||
|
|
||||||
let pred = case selectedGun
|
let pred = case selectedGun
|
||||||
@@ -134,6 +141,7 @@ method onScannedBot*(bot: ModularBot, e: ScannedBotEvent) =
|
|||||||
of 3: bot.circular.predict(bot.lastState, bulletSpeed(power))
|
of 3: bot.circular.predict(bot.lastState, bulletSpeed(power))
|
||||||
of 4: bot.guessFactor.predict(bot.lastState, bulletSpeed(power))
|
of 4: bot.guessFactor.predict(bot.lastState, bulletSpeed(power))
|
||||||
of 5: bot.patternMatcher.predict(bot.lastState, bulletSpeed(power))
|
of 5: bot.patternMatcher.predict(bot.lastState, bulletSpeed(power))
|
||||||
|
of 6: bot.antiSurfer.predict(bot.lastState, bulletSpeed(power))
|
||||||
else: bot.headOn.predict(bot.lastState, bulletSpeed(power))
|
else: bot.headOn.predict(bot.lastState, bulletSpeed(power))
|
||||||
let target = aimAngle(getX(), getY(), pred.x, pred.y)
|
let target = aimAngle(getX(), getY(), pred.x, pred.y)
|
||||||
|
|
||||||
@@ -193,13 +201,14 @@ method run*(bot: ModularBot) =
|
|||||||
|
|
||||||
when isMainModule:
|
when isMainModule:
|
||||||
var bot = ModularBot(
|
var bot = ModularBot(
|
||||||
tracker: vb.initTracker(6), # 0: HeadOn, 1: Linear, 2: Tsetlin, 3: Circular, 4: GuessFactor, 5: Pattern
|
tracker: vb.initTracker(7), # 0: HeadOn, 1: Linear, 2: Tsetlin, 3: Circular, 4: GuessFactor, 5: Pattern, 6: AntiSurf
|
||||||
headOn: HeadOnGun(),
|
headOn: HeadOnGun(),
|
||||||
linear: LinearGun(),
|
linear: LinearGun(),
|
||||||
circular: CircularGun(),
|
circular: CircularGun(),
|
||||||
tsetlin: initTsetlinGun(),
|
tsetlin: initTsetlinGun(),
|
||||||
guessFactor: initGFGun(),
|
guessFactor: initGFGun(),
|
||||||
patternMatcher: PatternMatcherGun(),
|
patternMatcher: PatternMatcherGun(),
|
||||||
|
antiSurfer: initAntiSurferGun(),
|
||||||
radar: RadarLockModule(),
|
radar: RadarLockModule(),
|
||||||
mover: initPhantomMeteor(),
|
mover: initPhantomMeteor(),
|
||||||
currentGun: -1,
|
currentGun: -1,
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
## Gauntlet: ModularBot vs WaveSurfer, SpinBot, Crazy — 10 rounds each.
|
||||||
|
## Captures [gun] lines and scores. Run with:
|
||||||
|
## nim c -r --path:../../common_libs tests/test_gauntlet.nim
|
||||||
|
|
||||||
|
import std/[os, strformat]
|
||||||
|
import test_framework/test_framework
|
||||||
|
|
||||||
|
const
|
||||||
|
modularBotDir = currentSourcePath().parentDir.parentDir
|
||||||
|
samplesDir = "/home/davide/Downloads/robocode-tankroyale/sample-bots-nim-linux-1.0.7"
|
||||||
|
waveSurferDir = "/home/davide/Projects/SirRoboGarage/WaveSurfer_garage"
|
||||||
|
spinBotDir = samplesDir / "SpinBot"
|
||||||
|
crazyDir = samplesDir / "Crazy"
|
||||||
|
|
||||||
|
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 runAndReport(label, enemyName, enemyDir: string) =
|
||||||
|
echo fmt"\n=== {label} ==="
|
||||||
|
let r = runBattle(@[modularBotDir, enemyDir], rounds = 10, timeout = 240000)
|
||||||
|
var mbScore = 0
|
||||||
|
var enScore = 0
|
||||||
|
for b in r.results:
|
||||||
|
if b.name == "ModularBot": mbScore = b.totalScore
|
||||||
|
if b.name == enemyName: enScore = b.totalScore
|
||||||
|
let winner = if mbScore > enScore: "ModularBot" else: enemyName
|
||||||
|
echo fmt" ModularBot: {mbScore} {enemyName}: {enScore} → {winner} wins"
|
||||||
|
echo fmt" Rounds: {r.rounds.len}"
|
||||||
|
|
||||||
|
runAndReport("Battle 1/3: vs WaveSurfer", "WaveSurfer", waveSurferDir)
|
||||||
|
runAndReport("Battle 2/3: vs SpinBot", "SpinBot", spinBotDir)
|
||||||
|
runAndReport("Battle 3/3: vs Crazy", "Crazy", crazyDir)
|
||||||
|
echo "\nGauntlet complete."
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
## Gauntlet with [gun] line capture via raw runner output.
|
||||||
|
## nim c -r --path:../../common_libs tests/test_gauntlet_guns.nim
|
||||||
|
|
||||||
|
import std/[os, strutils, strformat, tables]
|
||||||
|
import test_framework/server_manager
|
||||||
|
import test_framework/bot_compiler
|
||||||
|
import test_framework/runner_process
|
||||||
|
import test_framework/battle_result
|
||||||
|
|
||||||
|
const
|
||||||
|
modularBotDir = currentSourcePath().parentDir.parentDir
|
||||||
|
samplesDir = "/home/davide/Downloads/robocode-tankroyale/sample-bots-nim-linux-1.0.7"
|
||||||
|
waveSurferDir = "/home/davide/Projects/SirRoboGarage/WaveSurfer_garage"
|
||||||
|
spinBotDir = samplesDir / "SpinBot"
|
||||||
|
crazyDir = samplesDir / "Crazy"
|
||||||
|
|
||||||
|
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 gunCounts(raw: string): Table[string, int] =
|
||||||
|
## Count [gun] switched: <Name> occurrences
|
||||||
|
for line in raw.splitLines():
|
||||||
|
if "[gun] switched:" in line:
|
||||||
|
let parts = line.split(":")
|
||||||
|
if parts.len >= 2:
|
||||||
|
let name = parts[^1].strip()
|
||||||
|
result[name] = result.getOrDefault(name, 0) + 1
|
||||||
|
|
||||||
|
proc runAndReport(label, enemyName, enemyDir: string) =
|
||||||
|
let sep = "=".repeat(50)
|
||||||
|
echo "\n" & sep
|
||||||
|
echo " " & label
|
||||||
|
echo sep
|
||||||
|
let bots = @[modularBotDir, enemyDir]
|
||||||
|
discard compileBots(bots)
|
||||||
|
let raw = runBattleRunner(getServerUrl(), bots, 10, 240000, true)
|
||||||
|
let r = parseServerOutput(raw)
|
||||||
|
|
||||||
|
var mbScore = 0; var enScore = 0
|
||||||
|
for b in r.results:
|
||||||
|
if b.name == "ModularBot": mbScore = b.totalScore
|
||||||
|
if b.name == enemyName: enScore = b.totalScore
|
||||||
|
let winner = if mbScore > enScore: "ModularBot" else: enemyName
|
||||||
|
echo " Score: ModularBot " & $mbScore & " " & enemyName & " " & $enScore & " -> " & winner & " wins"
|
||||||
|
|
||||||
|
let guns = gunCounts(raw)
|
||||||
|
if guns.len > 0:
|
||||||
|
echo " Gun switches:"
|
||||||
|
for name, count in guns.pairs:
|
||||||
|
echo fmt" [gun] {name}: {count}x"
|
||||||
|
else:
|
||||||
|
echo " (no [gun] switch lines in output)"
|
||||||
|
|
||||||
|
# Show all [gun] lines for visibility
|
||||||
|
var gunLines: seq[string]
|
||||||
|
for line in raw.splitLines():
|
||||||
|
if line.contains("[gun]"): gunLines.add(line.strip())
|
||||||
|
if gunLines.len > 0:
|
||||||
|
echo fmt" First 20 [gun] lines:"
|
||||||
|
for l in gunLines[0..min(19, gunLines.high)]: echo fmt" {l}"
|
||||||
|
|
||||||
|
ensureServer()
|
||||||
|
runAndReport("Battle 1/3: vs WaveSurfer", "WaveSurfer", waveSurferDir)
|
||||||
|
runAndReport("Battle 2/3: vs SpinBot", "SpinBot", spinBotDir)
|
||||||
|
runAndReport("Battle 3/3: vs Crazy", "Crazy", crazyDir)
|
||||||
|
echo "\nGauntlet complete."
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
## Anti-surfer gun: inverse of GF histogram — aim at the VALLEY bin.
|
||||||
|
## Wave surfers dodge to where they predict bullets won't be (the GF peak).
|
||||||
|
## They congregate at the valley → aim there to punish their dodge.
|
||||||
|
## Bins: 31, same as GFGun. Learns from virtual bullet outcomes.
|
||||||
|
|
||||||
|
import std/[math, strformat]
|
||||||
|
import gun_harness/gun_interface
|
||||||
|
|
||||||
|
const
|
||||||
|
ASBins = 31
|
||||||
|
ASPrior = 0.1
|
||||||
|
DebugAS* = false
|
||||||
|
|
||||||
|
type
|
||||||
|
ASWave = object
|
||||||
|
fireX, fireY: float
|
||||||
|
fireBearing: float
|
||||||
|
|
||||||
|
AntiSurferGun* = object
|
||||||
|
bins: array[ASBins, float]
|
||||||
|
waves: seq[ASWave]
|
||||||
|
cachedTick: int
|
||||||
|
cachedWaveStored: bool
|
||||||
|
|
||||||
|
proc initAntiSurferGun*(): AntiSurferGun =
|
||||||
|
result.cachedTick = -1
|
||||||
|
# Same triangular head-on prior as GFGun — cold-start aims head-on.
|
||||||
|
let center = (ASBins - 1) div 2 # = 15
|
||||||
|
for i in 0..<ASBins:
|
||||||
|
let d = abs(i - center)
|
||||||
|
result.bins[i] = ASPrior + 0.5 / float(1 + d)
|
||||||
|
|
||||||
|
proc asToIndex(gf: float): int {.inline.} =
|
||||||
|
clamp(int(round((gf + 1.0) * 0.5 * float(ASBins - 1))), 0, ASBins - 1)
|
||||||
|
|
||||||
|
proc indexToAS(idx: int): float {.inline.} =
|
||||||
|
float(idx) / float(ASBins - 1) * 2.0 - 1.0
|
||||||
|
|
||||||
|
proc valleyBin(g: AntiSurferGun): int =
|
||||||
|
## Find the bin with MINIMUM value — where the surfer thinks is safe.
|
||||||
|
var best = 0
|
||||||
|
for i in 1..<ASBins:
|
||||||
|
if g.bins[i] < g.bins[best]:
|
||||||
|
best = i
|
||||||
|
best
|
||||||
|
|
||||||
|
proc predict*(g: var AntiSurferGun, state: WorldState, bulletSpeed: float): GunPrediction =
|
||||||
|
if bulletSpeed <= 0.0:
|
||||||
|
return GunPrediction(x: state.enemyX, y: state.enemyY)
|
||||||
|
|
||||||
|
let dx = state.enemyX - state.selfX
|
||||||
|
let dy = state.enemyY - state.selfY
|
||||||
|
let dist = sqrt(dx*dx + dy*dy)
|
||||||
|
let bearing = arctan2(dy, dx)
|
||||||
|
let mea = arcsin(clamp(8.0 / bulletSpeed, -1.0, 1.0))
|
||||||
|
|
||||||
|
if state.tick != g.cachedTick:
|
||||||
|
g.cachedTick = state.tick
|
||||||
|
g.cachedWaveStored = false
|
||||||
|
|
||||||
|
if not g.cachedWaveStored:
|
||||||
|
g.waves.add ASWave(
|
||||||
|
fireX: state.selfX,
|
||||||
|
fireY: state.selfY,
|
||||||
|
fireBearing: bearing,
|
||||||
|
)
|
||||||
|
g.cachedWaveStored = true
|
||||||
|
|
||||||
|
let valley = g.valleyBin()
|
||||||
|
let valleyGF = indexToAS(valley)
|
||||||
|
let gfAngle = bearing + valleyGF * mea
|
||||||
|
let px = state.selfX + cos(gfAngle) * dist
|
||||||
|
let py = state.selfY + sin(gfAngle) * dist
|
||||||
|
|
||||||
|
when DebugAS:
|
||||||
|
echo fmt"[as-dbg] predict: valleyGF={valleyGF:.2f} valleyBin={valley} mea={radToDeg(mea):.1f}° aimAngle={radToDeg(gfAngle):.1f}°"
|
||||||
|
|
||||||
|
GunPrediction(
|
||||||
|
x: clamp(px, BotRadius, state.arenaWidth - BotRadius),
|
||||||
|
y: clamp(py, BotRadius, state.arenaHeight - BotRadius),
|
||||||
|
)
|
||||||
|
|
||||||
|
proc onResult*(g: var AntiSurferGun, e: FeedbackEvent) =
|
||||||
|
## Same learning as GFGun — track where the enemy actually goes.
|
||||||
|
## ponytail: O(n) scan over waves; stays tiny (< a dozen at a time)
|
||||||
|
if g.waves.len == 0:
|
||||||
|
return
|
||||||
|
|
||||||
|
let w = g.waves[0]
|
||||||
|
g.waves.delete(0)
|
||||||
|
|
||||||
|
let speed = bulletSpeed(e.bulletPower)
|
||||||
|
let mea = arcsin(clamp(8.0 / speed, -1.0, 1.0))
|
||||||
|
|
||||||
|
let actualDx = e.actualX - w.fireX
|
||||||
|
let actualDy = e.actualY - w.fireY
|
||||||
|
let actualBearing = arctan2(actualDy, actualDx)
|
||||||
|
var bearingDelta = actualBearing - w.fireBearing
|
||||||
|
while bearingDelta > PI: bearingDelta -= 2.0*PI
|
||||||
|
while bearingDelta < -PI: bearingDelta += 2.0*PI
|
||||||
|
|
||||||
|
let gf = if mea > 1e-10: clamp(bearingDelta / mea, -1.0, 1.0) else: 0.0
|
||||||
|
let centerIdx = asToIndex(gf)
|
||||||
|
|
||||||
|
when DebugAS:
|
||||||
|
echo fmt"[as-dbg] onResult: delta={radToDeg(bearingDelta):.1f}° MEA={radToDeg(mea):.1f}° GF={gf:.2f} bin={centerIdx}"
|
||||||
|
|
||||||
|
for i in 0..<ASBins:
|
||||||
|
let dist = abs(i - centerIdx)
|
||||||
|
g.bins[i] += 1.0 / float(1 + dist)
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
## wave_surfer.nim — Wave-surfing movement module.
|
||||||
|
## Detects enemy fire via energy drops, maintains a danger histogram (31 GF bins),
|
||||||
|
## and steers toward the lowest-danger GF bin on approaching waves.
|
||||||
|
## All angles in radians internally; output degrees for bot API.
|
||||||
|
|
||||||
|
import std/[math]
|
||||||
|
import gun_harness/gun_interface
|
||||||
|
import movement_harness/movement_interface
|
||||||
|
|
||||||
|
const WS_BINS = 31
|
||||||
|
|
||||||
|
type
|
||||||
|
WSWave = object
|
||||||
|
originX, originY: float64
|
||||||
|
bearing: float64 ## direction from enemy to us at fire time (radians)
|
||||||
|
speed: float64
|
||||||
|
radius: float64
|
||||||
|
startDist: float64
|
||||||
|
|
||||||
|
WaveSurferModule* = object
|
||||||
|
bins: array[WS_BINS, float64]
|
||||||
|
waves: seq[WSWave]
|
||||||
|
prevEnergy: float64
|
||||||
|
strafeDir: float64 ## +1.0 or -1.0
|
||||||
|
|
||||||
|
proc initWaveSurfer*(): WaveSurferModule =
|
||||||
|
var m = WaveSurferModule(prevEnergy: 100.0, strafeDir: 1.0)
|
||||||
|
for i in 0..<WS_BINS: m.bins[i] = 1.0
|
||||||
|
m
|
||||||
|
|
||||||
|
proc resetRound*(m: var WaveSurferModule) =
|
||||||
|
m.waves = @[]
|
||||||
|
m.prevEnergy = 100.0
|
||||||
|
m.strafeDir = 1.0
|
||||||
|
|
||||||
|
proc gfToBin(gf: float64): int {.inline.} =
|
||||||
|
clamp(int(round((gf.clamp(-1.0, 1.0) + 1.0) * 0.5 * float64(WS_BINS - 1))), 0, WS_BINS - 1)
|
||||||
|
|
||||||
|
proc binToGF(idx: int): float64 {.inline.} =
|
||||||
|
float64(idx) / float64(WS_BINS - 1) * 2.0 - 1.0
|
||||||
|
|
||||||
|
proc mea(speed: float64): float64 {.inline.} = arcsin(min(8.0 / speed, 1.0))
|
||||||
|
|
||||||
|
proc nearestWave(m: WaveSurferModule, botX, botY: float64): int =
|
||||||
|
## Index of the wave closest to reaching us (largest radius relative to startDist).
|
||||||
|
result = -1
|
||||||
|
var bestRatio = -1.0
|
||||||
|
for i in 0..<m.waves.len:
|
||||||
|
let d = sqrt((botX - m.waves[i].originX)^2 + (botY - m.waves[i].originY)^2)
|
||||||
|
let ratio = m.waves[i].radius / d
|
||||||
|
if ratio > bestRatio:
|
||||||
|
bestRatio = ratio
|
||||||
|
result = i
|
||||||
|
|
||||||
|
proc computeMove*(m: var WaveSurferModule, ws: WorldState): MoveCommand =
|
||||||
|
let botX = ws.selfX
|
||||||
|
let botY = ws.selfY
|
||||||
|
let enemyX = ws.enemyX
|
||||||
|
let enemyY = ws.enemyY
|
||||||
|
|
||||||
|
# Fire detection
|
||||||
|
let drop = m.prevEnergy - ws.enemyEnergy
|
||||||
|
m.prevEnergy = ws.enemyEnergy
|
||||||
|
if drop >= 0.1 and drop <= 3.0:
|
||||||
|
let bspeed = 20.0 - 3.0 * drop
|
||||||
|
let bearing = arctan2(botY - enemyY, botX - enemyX)
|
||||||
|
let d = sqrt((botX - enemyX)^2 + (botY - enemyY)^2)
|
||||||
|
m.waves.add WSWave(
|
||||||
|
originX: enemyX, originY: enemyY,
|
||||||
|
bearing: bearing,
|
||||||
|
speed: bspeed,
|
||||||
|
radius: 0.0,
|
||||||
|
startDist: d,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Advance waves; collect hits
|
||||||
|
var i = 0
|
||||||
|
while i < m.waves.len:
|
||||||
|
m.waves[i].radius += m.waves[i].speed
|
||||||
|
let d = sqrt((botX - m.waves[i].originX)^2 + (botY - m.waves[i].originY)^2)
|
||||||
|
if m.waves[i].radius >= d:
|
||||||
|
let toBot = arctan2(botY - m.waves[i].originY, botX - m.waves[i].originX)
|
||||||
|
var off = toBot - m.waves[i].bearing
|
||||||
|
while off > PI: off -= 2.0*PI
|
||||||
|
while off < -PI: off += 2.0*PI
|
||||||
|
let maxA = mea(m.waves[i].speed)
|
||||||
|
if maxA >= 1e-9:
|
||||||
|
let gf = clamp(off / maxA, -1.0, 1.0)
|
||||||
|
m.bins[gfToBin(gf)] += 1.0
|
||||||
|
m.waves.del(i)
|
||||||
|
else:
|
||||||
|
inc i
|
||||||
|
|
||||||
|
# Dodge logic: find nearest wave, pick safest GF bin direction
|
||||||
|
let nearest = m.nearestWave(botX, botY)
|
||||||
|
if nearest >= 0:
|
||||||
|
let w = m.waves[nearest]
|
||||||
|
let toBot = arctan2(botY - w.originY, botX - w.originX)
|
||||||
|
var off = toBot - w.bearing
|
||||||
|
while off > PI: off -= 2.0*PI
|
||||||
|
while off < -PI: off += 2.0*PI
|
||||||
|
let maxA = mea(w.speed)
|
||||||
|
let curGF = if maxA >= 1e-9: clamp(off / maxA, -1.0, 1.0) else: 0.0
|
||||||
|
let curBin = gfToBin(curGF)
|
||||||
|
|
||||||
|
# Average danger
|
||||||
|
var total = 0.0
|
||||||
|
for b in m.bins: total += b
|
||||||
|
let avg = total / float64(WS_BINS)
|
||||||
|
|
||||||
|
if m.bins[curBin] > avg:
|
||||||
|
# Find lowest-danger bin
|
||||||
|
var bestBin = 0
|
||||||
|
for j in 1..<WS_BINS:
|
||||||
|
if m.bins[j] < m.bins[bestBin]: bestBin = j
|
||||||
|
let bestGF = binToGF(bestBin)
|
||||||
|
# Move in direction of best GF: positive = CCW (orbit left), negative = CW
|
||||||
|
m.strafeDir = if bestGF >= curGF: 1.0 else: -1.0
|
||||||
|
|
||||||
|
# Perpendicular strafe (same body trick as phantom_meteor)
|
||||||
|
let enemyBearingRad = arctan2(enemyY - botY, enemyX - botX)
|
||||||
|
# Perpendicular in chosen strafe direction
|
||||||
|
let perpAngle =
|
||||||
|
if m.strafeDir >= 0.0: enemyBearingRad + PI * 0.5
|
||||||
|
else: enemyBearingRad - PI * 0.5
|
||||||
|
let desiredDeg = radToDeg(perpAngle)
|
||||||
|
|
||||||
|
var delta = desiredDeg - ws.selfHeading
|
||||||
|
while delta > 180.0: delta -= 360.0
|
||||||
|
while delta < -180.0: delta += 360.0
|
||||||
|
|
||||||
|
let goForward = abs(delta) <= 90.0
|
||||||
|
if not goForward:
|
||||||
|
delta = if delta >= 0.0: delta - 180.0 else: delta + 180.0
|
||||||
|
|
||||||
|
(speed: if goForward: 8.0 else: -8.0,
|
||||||
|
turnRate: delta.clamp(-10.0, 10.0))
|
||||||
Executable
BIN
Binary file not shown.
Executable
BIN
Binary file not shown.
Reference in New Issue
Block a user