Files
SirStone b6425ac7f2 tfil: hold the committed dodge while a bullet is within 15 tiles
Proposal #2 (active-dodge commit lock), milder half only: while a tracked
bullet is within LockRadiusTiles (15 x 36px), suppress the tile-crossing
replan so the committed dodge direction survives the crossing.  The 15-tick
dwell and the danger safety valve still apply.

A hard freeze until the bullet passed (no dwell expiry) was measured and
reverted: the bot parked on the committed tile and absorbed the shot
(damage taken/round 26.8 -> 53.9 over 12 opponents x 20 rounds).

Measured on 12 opponents x 40 rounds (RawRecord, verified CONTIGUOUS):
damage taken/round 30.8 -> 25.5, damage dealt/round 73.2 -> 72.1,
rounds won 358/480 -> 360/480.

Raising CommitTicks 15 -> 25 (proposal #3) measured harmful and was reverted.
Proposal #1 (speculative bullet on 'could fire') not implemented: TFIL already
spawns a tracked bullet from the same-tick energy drop, and speculation would
be a ~70% false-positive flood.
2026-10-06 20:14:35 +02:00

805 lines
33 KiB
Nim

## TFIL — "The Floor Is Lava" survival movement, vendored into DevControlBot.
##
## Ported from `common_libs/movements/the_floor_is_lava.nim` (the authoritative
## implementation) with its DEFAULT behaviour, kept byte-for-byte. Self-contained
## on purpose: this bot folder never imports from `common_libs`, so the harness
## types (WorldState / EnemyInfo / MoveCommand) and the enemy-fire detector are
## inlined here rather than imported.
##
## WHAT WAS DROPPED (all of it default-OFF or diagnostic-only in the source, so
## the shipped decision path is unchanged):
## * the whole `TR_TFIL_*` / `TR_FIRE_*` env-port surface (knobs baked in as
## consts below with the source's defaults): TILE_REPLAN, COMMIT_TICKS, NO_REV,
## COMMIT_LOG, COMMIT_ARRIVAL, COMMIT_MARGIN, NOREV_SPEED, TURN_BIAS,
## TURN_REF_DEG, DANGER_THRESHOLD, DIAG, GEO_MODE/GEO_TAU, ARRIVE_TICKS,
## HOLD_WHEN_TRAPPED, HOLD_MAX_TICKS, HEAT_TIME/TAU/POWER_GAIN,
## CORRIDOR_TICKS, CORRIDOR_HEAT, WALL_HOTNESS/RADIANCE, BULLET_CORE/AURA,
## PILLAR_ON, FIRE_DIAG, FIRE_FIX (always on here), FIRE_LAG (always 0 here).
## Consequences, all of them no-ops at the defaults: the time-indexed heat
## model and the damage-proportional magnitude scale are OFF (every heat is
## exactly the flat one), corridors run to the wall, the virtual centre pillar
## is absent (0/0), the pick is a UNIFORM draw (no turn / no-rev / geometry
## tilt), no arrival bound, no bounded hold, no commit diagnostics.
## * debug graphics — restored below, but behind ` ` (off by default,
## since the SVG payload costs time every tick).
## * the pure bookkeeping fields (loss histogram, lastPick*, log-only vars).
##
## ANGLES: 0 deg = east, counter-clockwise positive (Tank Royale standard).
import std/[math, random]
import robocode_tankroyale_botapi
import robocode_tankroyale_botapi/color # graphics comes re-exported by the import above
## ── Debug graphics ──────────────────────────────────────────────────────────
## OFF by default: the drawing is a real per-tick cost (an SVG buffer sent to
## the server) and nothing else needs it. Turn it ON at compile time:
## nim c -d:tfilDebug ...
## or `nimble runBot -d:tfilDebug`. Everything below is inside
## `when defined(tfilDebug)`, so the OFF build contains none of it.
##
## The API has no Graphics object to hand around: the procs are global, the SVG
## buffer is drained and flushed by the API after every tick. `computeMove` runs
## before `go()`, which is exactly where drawing belongs.
# ── Harness types (vendored from gun_harness/movement_interface) ─────────────
type
EnemyInfo* = object
id*: int
x*, y*: float
heading*, speed*, energy*: float
lastSeenTick*: int
WorldState* = object
enemyX*, enemyY*: float
enemySpeed*, enemyHeading*: float
selfX*, selfY*: float
selfSpeed*, selfHeading*: float
selfRadarHeading*: float
selfEnergy*: float
enemyEnergy*: float
arenaWidth*, arenaHeight*: float
tick*: int
enemies*: seq[EnemyInfo]
MoveCommand* = tuple[speed: float, turnRate: float]
## speed: target speed in px/tick (clamped to +-8 by the bot API);
## turnRate: body turn rate in degrees/tick.
# ── Tunables (source defaults, baked in) ────────────────────────────────────
const
GridSize = 36.0
MaxSpeed = 8.0
BulletCoreRadiusMin = 9.0 ## core radius at power 0.1
BulletCoreRadiusMax = 54.0 ## core radius at power 3.0
BulletAuraExtMin = 36.0 ## aura extension at power 3.0 (slow)
BulletAuraExtMax = 54.0 ## aura extension at power 0.1 (fast)
BulletCoreHeat = 10.0 ## lava per bullet-overlapping tile
BulletAuraHeat = 5.0 ## lava for aura ring tiles
EnemyCoreRadius = 18.0 ## half of 36px body
EnemyAuraRadius = 54.0 ## 18 + 36
EnemyCoreHeat = 40.0 ## lava per tile overlapping the enemy body circle
EnemyAuraHeat = 10.0 ## lava per tile in the enemy aura ring
CorridorHeat = 20.0 ## lava per corridor-overlapping tile
WallHotness = 30.0 ## peak wall radiance
WallRadiance = 10.0 ## wall radiance falloff
CommitTicks = 15 ## ticks to commit to a dodge point
MinCommitTicks = 5 ## must commit this long before a danger replan
LockRadiusTiles = 15.0 ## freeze the committed dodge while a tracked
## bullet is this many tiles away or closer
DangerReplanThreshold = 25.0 ## replan on serious threats only (bullet core)
CoolestLevels = 2 ## how many distinct lava values count as "cool"
MaxTrackedBullets = 20 ## hard cap on tracked bullets
PathSampleStep = 18.0 ## ~half a tile
PathDangerThreshold = 10.0 ## max lava on path; above = unsafe
ArriveRadius = 18.0 ## "we are on the committed tile"
HullTicks = 50 ## reachable-hull planning horizon
FireFix = true ## corrected energy-drop detection
proc bulletRadii(power: float): tuple[core, aura: float] =
let t = (power - 0.1) / 2.9
let core = BulletCoreRadiusMin + t * (BulletCoreRadiusMax - BulletCoreRadiusMin)
let auraExt = BulletAuraExtMax - t * (BulletAuraExtMax - BulletAuraExtMin)
(core, core + auraExt)
# ── Enemy-fire detector (vendored from movement_harness/fire_tracker) ────────
#
# One enemy energy reading in, the confirmed fire powers out. Two server facts
# are corrected for: `BULLET_HIT_ENERGY_GAIN_FACTOR = 3` (an ENEMY bullet hitting
# US raises the SHOOTER's energy by 3*power and masks its own shot) and our own
# same-tick damage to the enemy (pushes the delta above the power cap). The
# corrections are staged one scan late because the server emits the hit event on
# turn N but applies the energy change to the reading of turn N+1.
type
FireTracker = object
prevEnergy*: seq[tuple[id: int, energy: float]]
hitBonusPending: float
dealtPending: float
hitBonusIncoming: float
dealtIncoming: float
proc initFireTracker*(): FireTracker =
FireTracker(prevEnergy: @[])
proc reset*(t: var FireTracker) =
t.prevEnergy = @[]
t.hitBonusPending = 0.0
t.dealtPending = 0.0
t.hitBonusIncoming = 0.0
t.dealtIncoming = 0.0
proc prevEnergyGet(t: FireTracker, id: int): float =
for e in t.prevEnergy:
if e.id == id: return e.energy
100.0
proc prevEnergySet(t: var FireTracker, id: int, energy: float) =
for i in 0..<t.prevEnergy.len:
if t.prevEnergy[i].id == id:
t.prevEnergy[i].energy = energy
return
t.prevEnergy.add((id: id, energy: energy))
proc noteEnemyBulletHit*(t: var FireTracker, power: float) {.inline.} =
## `onHitByBullet` -> `e.bullet.power`.
t.hitBonusIncoming += 3.0 * power
proc noteDamageDealt*(t: var FireTracker, damage: float) {.inline.} =
## `onBulletHit` -> `e.damage`.
t.dealtIncoming += damage
proc detect*(t: var FireTracker, id: int, energy: float, lo, hi: float): seq[float] =
let prev = t.prevEnergyGet(id)
let raw = prev - energy
var drop = raw + t.hitBonusPending - t.dealtPending
t.prevEnergySet(id, energy)
if drop > hi:
# Never silently drop a too-large delta: split it into the fewest waves each
# <= 3.0 — some heat beats none.
let n = int(ceil(drop / 3.0))
let p = drop / n.float
result = newSeq[float](n)
for i in 0..<n: result[i] = p
elif drop >= lo and drop <= hi:
result = @[drop]
proc endScan*(t: var FireTracker) =
## Rotate the event corrections one slot: the events noted since the previous
## `endScan` become the corrections applied by the NEXT scan.
t.hitBonusPending = t.hitBonusIncoming
t.dealtPending = t.dealtIncoming
t.hitBonusIncoming = 0.0
t.dealtIncoming = 0.0
# ── The mover ───────────────────────────────────────────────────────────────
type
TrackedBullet = object
x, y: float
velX, velY: float ## speed * cos(heading), speed * sin(heading)
power: float
age: int ## ticks alive; die if > 200
ScoredTile = tuple[col, row: int; pathMaxHeat: float]
CorridorGeom = object
dx, dy: float ## unit heading
px, py: float ## unit perpendicular
tMin: float ## distance to wall
bx, by: float ## bullet origin
TfilModule* = object
cols, rows: int
marginX, marginY: float
arenaWidth, arenaHeight: float
lava: seq[float] ## flat row-major, index = row*cols + col
bullets: seq[TrackedBullet]
fire: FireTracker
commitTarget: tuple[x, y: float] ## world coords of the committed dodge point
commitTicks: int ## ticks remaining on the commitment
commitLava: float ## lava at commit time (spike detection)
blockedTile: tuple[col, row: int; active: bool] ## excluded from the next pick
cachedHull: seq[tuple[x, y: float]]
cachedInsideTiles: seq[tuple[col, row: int]]
callCount: int ## computeMove call count; 0 = never called
lastBotX, lastBotY: float ## position at the last call (gap detection)
lastTileCol, lastTileRow: int ## grid tile at the last call (tile replan)
proc initTFIL*(): TfilModule =
# COLOUR CONVENTION: white = "not programmed yet", black = "programmed and
# running". Survival movement IS programmed, so this init claims the body's
# own colours: body, turret and gun go BLACK (radar claims its own pair in
# radar.nim). Set once here, never per tick.
setBodyColor(BLACK)
setTurretColor(BLACK)
setGunColor(BLACK)
TfilModule(cols: 0, rows: 0, fire: initFireTracker())
proc resetRound*(m: var TfilModule) =
m.bullets = @[]
m.fire.reset()
m.commitTicks = 0
m.cachedHull = @[]
m.cachedInsideTiles = @[]
m.blockedTile = (col: 0, row: 0, active: false)
m.callCount = 0
m.lastBotX = 0.0
m.lastBotY = 0.0
m.lastTileCol = 0
m.lastTileRow = 0
proc removeBulletNear*(m: var TfilModule, x, y: float) =
## Mark the tracked bullet closest to (x,y) within one tile as dead (used when
## OUR bullet destroys one of theirs before we see it).
var bestIdx = -1
var bestD2 = GridSize * GridSize ## tolerance squared
for i, b in m.bullets:
let dx = b.x - x
let dy = b.y - y
let d2 = dx * dx + dy * dy
if d2 < bestD2:
bestD2 = d2
bestIdx = i
if bestIdx >= 0:
m.bullets.del(bestIdx)
proc initGrid(m: var TfilModule, arenaWidth, arenaHeight: float) =
m.cols = int(arenaWidth / GridSize)
m.rows = int(arenaHeight / GridSize)
m.marginX = (arenaWidth - m.cols.float * GridSize) / 2.0
m.marginY = (arenaHeight - m.rows.float * GridSize) / 2.0
m.arenaWidth = arenaWidth
m.arenaHeight = arenaHeight
m.lava = newSeq[float](m.cols * m.rows)
proc lavaAt(m: TfilModule, col, row: int): float {.inline.} =
m.lava[row * m.cols + col]
proc tileAt(m: TfilModule, wx, wy: float): tuple[col, row: int] =
(col: clamp(int((wx - m.marginX) / GridSize), 0, m.cols - 1),
row: clamp(int((wy - m.marginY) / GridSize), 0, m.rows - 1))
proc noteEnemyBulletHit*(m: var TfilModule, power: float) =
## `onHitByBullet` -> the shooter's `3*power` bonus correction.
when FireFix:
m.fire.noteEnemyBulletHit(power)
proc noteDamageDealt*(m: var TfilModule, damage: float) =
## `onBulletHit` -> our same-tick damage to the enemy correction.
when FireFix:
m.fire.noteDamageDealt(damage)
proc spawnTrackedWave(m: var TfilModule, ws: WorldState, ei: EnemyInfo, power: float) =
## One tracked bullet for a confirmed fire of `power`: linear prediction of our
## position at arrival becomes the aim heading.
let speed = 20.0 - 3.0 * power
let dx = ws.selfX - ei.x
let dy = ws.selfY - ei.y
let travelTime = sqrt(dx * dx + dy * dy) / speed
let hRad = ws.selfHeading * PI / 180.0
let predX = ws.selfX + ws.selfSpeed * cos(hRad) * travelTime
let predY = ws.selfY + ws.selfSpeed * sin(hRad) * travelTime
let heading = arctan2(predY - ei.y, predX - ei.x)
if m.bullets.len >= MaxTrackedBullets:
m.bullets.del(0) ## ponytail: drop the oldest; fine for a 20-bullet cap
m.bullets.add TrackedBullet(x: ei.x, y: ei.y,
velX: speed * cos(heading),
velY: speed * sin(heading),
power: power, age: 0)
proc detectFires(m: var TfilModule, ws: WorldState) =
## Check every enemy for an energy drop; spawn a tracked wave per confirmed fire.
for ei in ws.enemies:
for p in m.fire.detect(ei.id, ei.energy, 0.09, 3.01):
m.spawnTrackedWave(ws, ei, p)
m.fire.endScan()
proc bulletLock(m: TfilModule, selfX, selfY: float): bool =
## True while any tracked bullet is within LockRadiusTiles of us: an active
## dodge, during which the committed tile is frozen (proposal #2).
let r2 = (LockRadiusTiles * GridSize) * (LockRadiusTiles * GridSize)
for b in m.bullets:
let dx = selfX - b.x
let dy = selfY - b.y
if dx * dx + dy * dy <= r2: return true
proc advanceBullets(m: var TfilModule, selfX, selfY: float) =
## Advance positions and reap bullets that passed us, left the arena, or are
## too old.
var i = 0
while i < m.bullets.len:
var b = m.bullets[i]
b.x += b.velX
b.y += b.velY
b.age += 1
let dx = selfX - b.x
let dy = selfY - b.y
let passed = b.velX * dx + b.velY * dy < 0.0 ## dot < 0: moving away
let outOfBounds =
b.x < 0.0 or b.x > m.arenaWidth or b.y < 0.0 or b.y > m.arenaHeight
if passed or outOfBounds or b.age > 200:
m.bullets.del(i)
else:
m.bullets[i] = b
inc i
proc corridorGeom(b: TrackedBullet, arenaWidth, arenaHeight: float): CorridorGeom =
## `tMin` is the corridor length: the distance to the wall along the heading.
## Unset (0.0) -> zero-speed bullet, skipped by the caller.
let speed = sqrt(b.velX * b.velX + b.velY * b.velY)
if speed < 0.001: return
let dx = b.velX / speed
let dy = b.velY / speed
var tMin = Inf
if dx > 0.0: tMin = min(tMin, (arenaWidth - b.x) / dx)
elif dx < 0.0: tMin = min(tMin, (0.0 - b.x) / dx)
if dy > 0.0: tMin = min(tMin, (arenaHeight - b.y) / dy)
elif dy < 0.0: tMin = min(tMin, (0.0 - b.y) / dy)
CorridorGeom(dx: dx, dy: dy, px: -dy, py: dx, tMin: tMin, bx: b.x, by: b.y)
proc pointInHull(px, py: float, hull: seq[(float, float)]): bool =
## Crossing-number test against the hull polygon.
var inside = false
var j = hull.high
for i in 0..hull.high:
if ((hull[i][1] > py) != (hull[j][1] > py)) and
(px < (hull[j][0] - hull[i][0]) * (py - hull[i][1]) / (hull[j][1] - hull[i][1]) + hull[i][0]):
inside = not inside
j = i
inside
proc computeReachableHull(x0, y0, heading0, speed0,
arenaW, arenaH: float, ticks: int): seq[(float, float)] =
## Simulate `ticks` ticks at various turn rates / target speeds, then gift-wrap
## the convex hull of the final positions.
const TargetSpeeds = [8.0, 4.0, -4.0, -8.0]
const NumRates = 11
var pts: seq[(float, float)]
pts.add (x0, y0) ## always reachable: stay
for tSpeed in TargetSpeeds:
let mtr = 10.0 - 0.75 * abs(tSpeed) ## max turn rate at the target speed
for ri in 0..<NumRates:
let turnRate = -mtr + (2.0 * mtr / (NumRates - 1).float) * ri.float
var x = x0
var y = y0
var h = heading0
var spd = speed0
for _ in 0..<ticks:
if spd < tSpeed: spd = min(spd + 1.0, tSpeed)
elif spd > tSpeed: spd = max(spd - 1.0, tSpeed)
spd = clamp(spd, -MaxSpeed, MaxSpeed)
let curMtr = 10.0 - 0.75 * abs(spd)
h += clamp(turnRate, -curMtr, curMtr)
let hr = h * PI / 180.0
x = clamp(x + spd * cos(hr), 0.0, arenaW)
y = clamp(y + spd * sin(hr), 0.0, arenaH)
pts.add (x, y)
# Gift-wrap from the leftmost (then lowest) point.
var startIdx = 0
for i in 1..<pts.len:
if pts[i][0] < pts[startIdx][0] or
(pts[i][0] == pts[startIdx][0] and pts[i][1] < pts[startIdx][1]):
startIdx = i
var hull: seq[(float, float)]
var cur = startIdx
while true:
hull.add pts[cur]
var next = 0
for i in 1..<pts.len:
if next == cur:
next = i
continue
let ax = pts[next][0] - pts[cur][0]
let ay = pts[next][1] - pts[cur][1]
let bx = pts[i][0] - pts[cur][0]
let by = pts[i][1] - pts[cur][1]
if ax * by - ay * bx < 0.0: ## i is more counterclockwise
next = i
cur = next
if cur == startIdx: break
hull
proc pathMaxHeat(m: TfilModule, fx, fy, tx, ty: float): float =
## MAX lava on the straight-line segment (fx,fy) -> (tx,ty), sampled every ~half
## a tile. A single hot tile on the path (corridor, bullet core, enemy aura)
## makes the whole path unsafe.
let ddx = tx - fx
let ddy = ty - fy
let lineDist = sqrt(ddx * ddx + ddy * ddy)
if lineDist <= 0.1: return 0.0
let steps = max(1, int(lineDist / PathSampleStep))
var h = 0.0
for si in 0..steps:
let frac = si.float / steps.float
let (sc, sr) = m.tileAt(fx + ddx * frac, fy + ddy * frac)
h = max(h, m.lavaAt(sc, sr))
h
proc paintBulletHeat(m: var TfilModule, b: TrackedBullet) =
## Core circle and aura ring around one tracked bullet.
let (coreR, auraR) = bulletRadii(b.power)
let bx = b.x
let by = b.y
let coreR2 = coreR * coreR
let auraR2 = auraR * auraR
let colMin = max(0, int(floor((bx - auraR - m.marginX) / GridSize)))
let colMax = min(m.cols - 1, int(floor((bx + auraR - m.marginX) / GridSize)))
let rowMin = max(0, int(floor((by - auraR - m.marginY) / GridSize)))
let rowMax = min(m.rows - 1, int(floor((by + auraR - m.marginY) / GridSize)))
for row in rowMin..rowMax:
let y0 = m.marginY + row.float * GridSize
let nearY = clamp(by, y0, y0 + GridSize)
let dy = nearY - by
let dy2 = dy * dy
for col in colMin..colMax:
let x0 = m.marginX + col.float * GridSize
let dx = clamp(bx, x0, x0 + GridSize) - bx
let d2 = dx * dx + dy2
let idx = row * m.cols + col
if d2 <= coreR2: m.lava[idx] += BulletCoreHeat
elif d2 <= auraR2: m.lava[idx] += BulletAuraHeat
proc paintCorridorHeat(m: var TfilModule, b: TrackedBullet) =
## The rotated rectangle from the bullet to the arena wall, auraR wide.
let cg = corridorGeom(b, m.arenaWidth, m.arenaHeight)
if cg.tMin == 0.0: return ## zero-speed bullet
let (_, auraR) = bulletRadii(b.power)
let wx = cg.bx + cg.dx * cg.tMin
let wy = cg.by + cg.dy * cg.tMin
let c0x = cg.bx + cg.px * auraR; let c0y = cg.by + cg.py * auraR
let c1x = cg.bx - cg.px * auraR; let c1y = cg.by - cg.py * auraR
let c2x = wx - cg.px * auraR; let c2y = wy - cg.py * auraR
let c3x = wx + cg.px * auraR; let c3y = wy + cg.py * auraR
let colMin = max(0, int(floor((min(min(c0x, c1x), min(c2x, c3x)) - m.marginX) / GridSize)))
let colMax = min(m.cols - 1, int(floor((max(max(c0x, c1x), max(c2x, c3x)) - m.marginX) / GridSize)))
let rowMin = max(0, int(floor((min(min(c0y, c1y), min(c2y, c3y)) - m.marginY) / GridSize)))
let rowMax = min(m.rows - 1, int(floor((max(max(c0y, c1y), max(c2y, c3y)) - m.marginY) / GridSize)))
for row in rowMin..rowMax:
let cy = m.marginY + (row.float + 0.5) * GridSize
let relY = cy - cg.by
let along0 = relY * cg.dy
let perp0 = relY * cg.py
for col in colMin..colMax:
let cx = m.marginX + (col.float + 0.5) * GridSize
let relX = cx - cg.bx
let along = along0 + relX * cg.dx
let perp = perp0 + relX * cg.px
if along >= 0.0 and along <= cg.tMin and perp >= -auraR and perp <= auraR:
m.lava[row * m.cols + col] += CorridorHeat
proc paintEnemyHeat(m: var TfilModule, ei: EnemyInfo) =
## Enemy core (18px) and aura ring (54px), same pattern as the bullets.
let ex = ei.x
let ey = ei.y
let colMin = max(0, int(floor((ex - EnemyAuraRadius - m.marginX) / GridSize)))
let colMax = min(m.cols - 1, int(floor((ex + EnemyAuraRadius - m.marginX) / GridSize)))
let rowMin = max(0, int(floor((ey - EnemyAuraRadius - m.marginY) / GridSize)))
let rowMax = min(m.rows - 1, int(floor((ey + EnemyAuraRadius - m.marginY) / GridSize)))
let coreR2 = EnemyCoreRadius * EnemyCoreRadius
let auraR2 = EnemyAuraRadius * EnemyAuraRadius
for row in rowMin..rowMax:
let y0 = m.marginY + row.float * GridSize
let dy = clamp(ey, y0, y0 + GridSize) - ey
let dy2 = dy * dy
for col in colMin..colMax:
let x0 = m.marginX + col.float * GridSize
let dx = clamp(ex, x0, x0 + GridSize) - ex
let d2 = dx * dx + dy2
let idx = row * m.cols + col
if d2 <= coreR2: m.lava[idx] += EnemyCoreHeat
elif d2 <= auraR2: m.lava[idx] += EnemyAuraHeat
proc paintWallHeat(m: var TfilModule) =
## Additive wall radiance: hottest along the border, falling off inwards.
for row in 0..<m.rows:
let vert = max(0.0, WallHotness - row.float * WallRadiance) +
max(0.0, WallHotness - (m.rows - 1 - row).float * WallRadiance)
for col in 0..<m.cols:
let heat = vert +
max(0.0, WallHotness - col.float * WallRadiance) +
max(0.0, WallHotness - (m.cols - 1 - col).float * WallRadiance)
m.lava[row * m.cols + col] += heat
proc collectCoolestTiles(m: var TfilModule): seq[tuple[col, row: int]] =
## The tiles inside the reachable hull whose lava is one of the `CoolestLevels`
## coolest DISTINCT values present there.
var distinctVals: seq[float]
for t in m.cachedInsideTiles:
let v = m.lavaAt(t.col, t.row)
var found = false
for dv in distinctVals:
if dv == v:
found = true
break
if not found:
distinctVals.add v
# ascending insertion sort — N is small
for i in 1..<distinctVals.len:
let key = distinctVals[i]
var j = i - 1
while j >= 0 and distinctVals[j] > key:
distinctVals[j + 1] = distinctVals[j]
dec j
distinctVals[j + 1] = key
result = @[]
let numLevels = min(CoolestLevels, distinctVals.len)
for t in m.cachedInsideTiles:
let v = m.lavaAt(t.col, t.row)
for li in 0..<numLevels:
if v == distinctVals[li]:
result.add t
break
when defined(tfilDebug):
proc drawHeatField(m: TfilModule, ws: WorldState) =
## The lava field per tile (colour ramp + value text), the tracked bullets'
## core/aura circles, their danger corridors and the enemies' core/aura.
var maxLava = 0.0
for v in m.lava:
if v > maxLava: maxLava = v
setFont("Arial", 10.0)
for row in 0..<m.rows:
for col in 0..<m.cols:
let val = m.lava[row * m.cols + col]
if val == 0.0: continue
let t = if maxLava > 0.0: val / maxLava else: 0.0
let heatColor = fromRgb(255'u8, uint8(255.0 * (1.0 - t)), 0'u8)
let x0 = m.marginX + col.float * GridSize
let y0 = m.marginY + row.float * GridSize
setStrokeColor(heatColor)
setStrokeWidth(1.0)
drawRectangle(x0, y0, GridSize, GridSize)
setFillColor(heatColor)
drawText($int(val), x0 + 12.0, y0 + 22.0)
# Tracked bullets: red core outline + filled centre, orange aura ring.
for b in m.bullets:
let (coreR, auraR) = bulletRadii(b.power)
setStrokeColor(RED)
setStrokeWidth(1.0)
setFillColor(RED)
drawCircle(b.x, b.y, coreR)
fillCircle(b.x, b.y, 3.0)
setStrokeColor(fromHex("#FF8800"))
drawCircle(b.x, b.y, auraR)
# Danger corridor: the rotated rectangle from each bullet to the arena wall.
setStrokeColor(fromHex("#AAAAAA"))
setStrokeWidth(1.0)
for b in m.bullets:
let (_, auraR) = bulletRadii(b.power)
let cg = corridorGeom(b, m.arenaWidth, m.arenaHeight)
if cg.tMin == 0.0: continue
let wx = cg.bx + cg.dx * cg.tMin
let wy = cg.by + cg.dy * cg.tMin
drawPolygon(@[
(cg.bx + cg.px * auraR, cg.by + cg.py * auraR),
(cg.bx - cg.px * auraR, cg.by - cg.py * auraR),
(wx - cg.px * auraR, wy - cg.py * auraR),
(wx + cg.px * auraR, wy + cg.py * auraR),
])
# Enemies: cyan body core, green aura ring.
setStrokeColor(fromHex("#00FFFF"))
setStrokeWidth(1.5)
for ei in ws.enemies: drawCircle(ei.x, ei.y, EnemyCoreRadius)
setStrokeColor(fromHex("#00CC00"))
setStrokeWidth(1.0)
for ei in ws.enemies: drawCircle(ei.x, ei.y, EnemyAuraRadius)
proc drawDecision(m: TfilModule, ws: WorldState,
scoredTiles, safeTiles: seq[ScoredTile]) =
## What the planner actually did: reachable hull, the tiles whose path is
## blocked, the safe set, the tile it committed to, its own tile, and the
## committed-target line.
if m.cachedHull.len >= 3:
let hullPts = block:
var s: seq[(float, float)]
for p in m.cachedHull: s.add (p.x, p.y)
s
setStrokeColor(fromHex("#336699"))
setStrokeWidth(1.0)
drawPolygon(hullPts)
setStrokeColor(fromHex("#006666"))
setStrokeWidth(1.0)
for t in scoredTiles:
if t.pathMaxHeat <= PathDangerThreshold: continue
if t in safeTiles: continue ## promoted into the safe set: drawn cyan below
drawRectangle(m.marginX + t.col.float * GridSize,
m.marginY + t.row.float * GridSize, GridSize, GridSize)
setStrokeColor(fromHex("#00FFFF"))
setStrokeWidth(2.0)
for t in safeTiles:
drawRectangle(m.marginX + t.col.float * GridSize,
m.marginY + t.row.float * GridSize, GridSize, GridSize)
let (chosenCol, chosenRow) = m.tileAt(m.commitTarget.x, m.commitTarget.y)
setStrokeColor(fromHex("#00FF00"))
setStrokeWidth(2.5)
drawRectangle(m.marginX + chosenCol.float * GridSize,
m.marginY + chosenRow.float * GridSize, GridSize, GridSize)
let (botCol, botRow) = m.tileAt(ws.selfX, ws.selfY)
setStrokeColor(fromHex("#0088FF"))
setStrokeWidth(2.5)
drawRectangle(m.marginX + botCol.float * GridSize,
m.marginY + botRow.float * GridSize, GridSize, GridSize)
setStrokeColor(fromHex("#00FF00"))
setStrokeWidth(1.5)
drawLine(ws.selfX, ws.selfY, m.commitTarget.x, m.commitTarget.y)
proc computeMove*(m: var TfilModule, ws: WorldState): MoveCommand =
if m.cols == 0:
m.initGrid(ws.arenaWidth, ws.arenaHeight)
# Soft reset: a position gap (a rammer moved us across ticks) invalidates the
# commitment, the cached hull and every tracked bullet. 12px is above the 8px
# single-tick maximum, so normal motion never trips it.
let jumpDist = sqrt((ws.selfX - m.lastBotX)^2 + (ws.selfY - m.lastBotY)^2)
let jumped = (m.callCount > 0) and (jumpDist > 12.0)
if jumped:
m.commitTicks = 0
m.cachedHull = @[]
m.cachedInsideTiles = @[]
m.bullets = @[]
m.blockedTile = (col: 0, row: 0, active: false)
# Re-snapshot prevEnergy: energy changes during ramming are not fires.
m.fire.prevEnergy = @[]
for ei in ws.enemies:
m.fire.prevEnergySet(ei.id, ei.energy)
# Per-tick: advance existing bullets, detect new fires
m.advanceBullets(ws.selfX, ws.selfY)
m.detectFires(ws)
# Active-dodge lock: while a tracked bullet is within LockRadiusTiles we stop
# the tile-crossing replan, so the committed dodge direction survives the
# crossing. The 15-tick dwell still expires and the safety valve still fires
# (a hard freeze until the bullet passed measured far worse: the bot parked and
# ate the shot).
let locked = m.bulletLock(ws.selfX, ws.selfY)
# Tile-change replan: crossing a tile boundary cancels the commitment,
# unless we are mid-dodge (locked).
if (not jumped) and (not locked) and (m.callCount > 0) and (m.commitTicks > 0):
let curTileCol = clamp(int((ws.selfX - m.marginX) / GridSize), 0, m.cols - 1)
let curTileRow = clamp(int((ws.selfY - m.marginY) / GridSize), 0, m.rows - 1)
if curTileCol != m.lastTileCol or curTileRow != m.lastTileRow:
m.commitTicks = 0
m.cachedHull = @[]
m.cachedInsideTiles = @[]
# Recompute the lava field from scratch
for i in 0..<m.lava.len: m.lava[i] = 0.0
for b in m.bullets: m.paintBulletHeat(b)
for b in m.bullets: m.paintCorridorHeat(b)
for ei in ws.enemies: m.paintEnemyHeat(ei)
m.paintWallHeat()
when defined(tfilDebug):
drawHeatField(m, ws)
# ── Tile-based dodge system ────────────────────────────────────────────────
# Hull + inside-tiles: recomputed only on a replan tick (commitTicks == 0).
if m.commitTicks == 0:
m.cachedHull = computeReachableHull(ws.selfX, ws.selfY, ws.selfHeading,
ws.selfSpeed, m.arenaWidth,
m.arenaHeight, HullTicks)
m.cachedInsideTiles = @[]
if m.cachedHull.len >= 3:
for row in 0..<m.rows:
let cy = m.marginY + (row.float + 0.5) * GridSize
for col in 0..<m.cols:
let cx = m.marginX + (col.float + 0.5) * GridSize
if pointInHull(cx, cy, m.cachedHull):
m.cachedInsideTiles.add (col: col, row: row)
# Score each cool tile by the MAX lava on the straight-line path from the bot.
var scoredTiles: seq[ScoredTile]
for t in m.collectCoolestTiles():
let tx = m.marginX + (t.col.float + 0.5) * GridSize
let ty = m.marginY + (t.row.float + 0.5) * GridSize
scoredTiles.add (col: t.col, row: t.row,
pathMaxHeat: pathMaxHeat(m, ws.selfX, ws.selfY, tx, ty))
# ascending by path heat — insertion sort, small N
for i in 1..<scoredTiles.len:
let key = scoredTiles[i]
var j = i - 1
while j >= 0 and scoredTiles[j].pathMaxHeat > key.pathMaxHeat:
scoredTiles[j + 1] = scoredTiles[j]
dec j
scoredTiles[j + 1] = key
# Absolute threshold filter: safe = path max lava <= PathDangerThreshold.
# Fallback: if fewer than two tiles survive, promote the least-hot blocked ones.
var safeTiles: seq[ScoredTile]
for t in scoredTiles:
if t.pathMaxHeat <= PathDangerThreshold: safeTiles.add t
if safeTiles.len < 2:
# Promote the least-hot blocked tiles until there are two (scoredTiles is
# sorted ascending, so the first hot ones are the coolest of the hot).
for t in scoredTiles:
if safeTiles.len >= 2: break
if t.pathMaxHeat > PathDangerThreshold: safeTiles.add t
# Commitment logic: a fixed 15-tick dwell, cancellable by our own tile crossing
# (above) or by the committed tile getting genuinely dangerous (the safety
# valve, only after the minimum dwell).
if m.commitTicks > 0:
if CommitTicks - m.commitTicks >= MinCommitTicks:
let (cc, cr) = m.tileAt(m.commitTarget.x, m.commitTarget.y)
if m.lavaAt(cc, cr) > m.commitLava + DangerReplanThreshold:
m.blockedTile = (col: cc, row: cr, active: true)
m.commitTicks = 0
if m.commitTicks > 0:
dec m.commitTicks
if m.commitTicks == 0 and safeTiles.len > 0:
# Never re-pick the tile we just blocked ourselves with; if that empties the
# pool, the block is ignored (being cornered beats being stuck).
var candidates: seq[ScoredTile]
for t in safeTiles:
if m.blockedTile.active and t.col == m.blockedTile.col and t.row == m.blockedTile.row:
continue
candidates.add t
if candidates.len == 0: candidates = safeTiles
## A uniform draw: the randomness in this pick is load-bearing (a
## deterministic argmin measured worse).
let ct = candidates[rand(candidates.high)]
m.commitTarget = (x: m.marginX + (ct.col.float + 0.5) * GridSize,
y: m.marginY + (ct.row.float + 0.5) * GridSize)
m.commitTicks = CommitTicks
m.commitLava = m.lavaAt(ct.col, ct.row)
m.blockedTile.active = false
when defined(tfilDebug):
drawDecision(m, ws, scoredTiles, safeTiles)
# Update the position snapshot and call counter for next gap/tile detection
m.lastBotX = ws.selfX
m.lastBotY = ws.selfY
m.lastTileCol = clamp(int((ws.selfX - m.marginX) / GridSize), 0, m.cols - 1)
m.lastTileRow = clamp(int((ws.selfY - m.marginY) / GridSize), 0, m.rows - 1)
m.callCount += 1
# ── Steering ────────────────────────────────────────────────────────────────
# `speed: 0.0` is how this module says "stop": the already-at-target case below
# returns the same command. The gun is not here — `computeMove` never touches
# fire, so a held tick still fires exactly as every other tick.
let stepDx = m.commitTarget.x - ws.selfX
let stepDy = m.commitTarget.y - ws.selfY
let dist2 = stepDx * stepDx + stepDy * stepDy
if dist2 < ArriveRadius * ArriveRadius:
return (speed: 0.0, turnRate: 0.0)
let targetBearing = arctan2(stepDy, stepDx) * 180.0 / PI
var delta = targetBearing - ws.selfHeading
while delta > 180.0: delta -= 360.0
while delta < -180.0: delta += 360.0
let maxTurnRate = 10.0 - 0.75 * abs(ws.selfSpeed)
if abs(delta) <= 90.0:
result = (speed: MaxSpeed, turnRate: clamp(delta, -maxTurnRate, maxTurnRate))
else:
let flipped = if delta > 0.0: delta - 180.0 else: delta + 180.0
result = (speed: -MaxSpeed, turnRate: clamp(flipped, -maxTurnRate, maxTurnRate))