////// The demo player's hand and attention.////// State, because the things that make play look human are all things that persist. A person/// misjudges a shot and *commits* to the misjudgement for a beat; they do not re-misjudge/// sixty times a second. They keep pushing the stick the way it is already going. They look/// away for a third of a second, not for a single frame.////// The first version of this bot had none of that -- it drew a fresh aim error every tick,/// which around the target swamped the 1.5px movement deadzone and reversed the cannon's/// direction about six times a second. Measured, that was 9-11 reversals per 100 moving/// ticks against 3 for the bot with no error at all: the shake was the jitter, not the game.////// One occupied column of the formation: its lowest invader, and how deep it is.pubtypealiasColumn = {x = Float32, y = Float32, depth = Int32}////// Every number that decides how the demo player behaves.////// A record rather than sixteen `def`s, because they were sixteen `def`s and every one of them/// had to be found, edited and recompiled to try a different value. As data they can be varied/// in a loop, read from a file, and searched -- see `bin/bench --recalc`.////// None of them can be reasoned about in isolation. Widening `dangerWidth` from 30 to 60 cut/// deaths sixfold; a cleverer dodge that predicted where the cannon would be when each bomb/// landed measured worse at every setting. They are tuned by measurement, and the record of/// that is in `docs/ARCHITECTURE.md`.///pubtypealiasTuning = { aimJitter = Int32, judgeFor = Int32, judgeSpread = Int32, lapseOneIn = Int32, lapseFor = Int32, lapseSpread = Int32, startAt = Float32, reverseAt = Float32, dangerWidth = Float32, selfPreservation = Float32, urgency = Float32, shelterRelief = Float32, blockedCost = Float32, calm = Float32, stragglers = Int32, finishFlank = Float32, narrowTo = Float32, narrowing = Float32, fireWindow = Float32, imminence = Float32}/// The imperfect player's state: RNG stream, current error, and timers for movement/lapses.pubtypealiasHand = { rng = Rng, error = Float32, settled = Int32, moving = Int32, lapse = Int32}////// A computer player.////// This is the same code in two jobs. `aim` is the bot the balance test drives to decide/// whether the game is winnable; `imperfect` is that bot with its hands shaking, which is/// what plays behind the title screen. Having one implementation means the demo can never/// drift away from the thing the tests measure.////// Everything here is pure. The imperfection is threaded through an `Rng` the *caller* owns/// -- never the world's own generator -- so watching the demo cannot perturb the determinism/// the replay tests depend on.///mod Demo {////// The tuning the game ships with.////// Every value here was measured, not chosen. See `docs/ARCHITECTURE.md` and `bin/bench`.///pubdefdefaults(): Tuning = { aimJitter = 8, judgeFor = 18, judgeSpread = 19, lapseOneIn = 200, lapseFor = 4, lapseSpread = 9, startAt = 1.5f32, reverseAt = 6.0f32, dangerWidth = 60.0f32, selfPreservation = 6.0f32, urgency = 40.0f32, shelterRelief = 0.25f32, blockedCost = 2.0f32, calm = 0.25f32, stragglers = 1, finishFlank = 1.1f32, narrowTo = 0.30f32, narrowing = 2.0f32, fireWindow = 2.0f32, imminence = 4.0f32 }/// The offsets from its current position that the bot considers standing at.defoptions(): List[Float32] = -96.0f32 :: -64.0f32 :: -36.0f32 :: -16.0f32 :: 0.0f32 :: 16.0f32 :: 36.0f32 :: 64.0f32 :: 96.0f32 :: Nil////// What to shoot at.////// The saucer first when it is on screen -- it is worth up to 300 and a shield, which is/// what a human would go for. Otherwise the lowest living invader: it is the closest, and/// it is the one dropping bombs.///defchooseTarget(t: Tuning, w: World): Option[Vec2] = matchw#mystery {case Some(m) => Some({x = m#x, y = Rules.mysteryY()})case None => bestColumn(t, w) }////// Every occupied column: its lowest invader, and how many are stacked in it.////// A shot rising through a column meets the lowest one in it first, so the lowest is the/// only reachable target there. The depth matters separately, below.///defcolumns(w: World): List[Column] =Vector.foldLeft( (acc, inv) ->if (notinv#alive)accelseMap.insertWith(arriving -> found -> {let (newY, newN) = arriving;let (oldY, oldN) = found; (Float32.max(newY, oldY), newN+oldN) },inv#pos#x, (inv#pos#y, 1),acc ), (Map.empty(): Map[Float32, (Float32, Int32)]),w#invaders ) |> Map.toList |> List.map(match (x, found) -> {let (y, depth) = found; {x = x, y = y, depth = depth} })////// Which column to shoot at.////// Lowest-first, with two exceptions, both of which trade kill rate for a slower descent./// An outer column is worth taking while the formation is still wide, and worth finishing/// once it is nearly empty.////// `Game.liveBounds` measures the formation from its *living* invaders, so the last/// invader in the leftmost or rightmost column is single-handedly holding the block at its/// full width -- and the block's width is what decides how far it marches before it turns/// and drops. Left to itself the bot never takes that shot: the survivor is high up, so it/// scores badly on imminence, and the formation stays 400px wide from eleven columns down/// to six. One shot buys a permanent reduction in the descent rate, which is the best/// value on the board.////// `narrowing` is the same argument applied earlier: the whole outer column, not just its/// last survivor, while the block is still wider than `narrowTo`. Chasing flanks with no/// cutoff is measurably worse -- it costs more kill rate than it buys descent -- so what/// makes this pay is stopping. Below the cutoff the bonus goes away and the bot returns to/// shooting whatever is lowest.///typealiasFlankContext = { left = Float32, right = Float32, spread = Float32, looming = Float32 }defbestColumn(t: Tuning, w: World): Option[Vec2] = {letcandidates = columns(w);letupdateEdges = (acc, c) -> matchacc {case None => Some((c#x, c#x))case Some((left, right)) => Some((Float32.min(left, c#x), Float32.max(right, c#x))) };letedges = List.foldLeft(updateEdges, None, candidates);matchedges {case None => Nonecase Some((left, right)) =>letlooming = pressure(candidates);letspread = (right-left) /fullWidth();letctx = {left = left, right = right, spread = spread, looming = looming};letselectBest = (best, c) -> {letscore = columnWorth(t, c, ctx);matchbest {case None => Some(({x = c#x, y = c#y}, score))case Some((_, top)) =>lethere = {x = c#x, y = c#y};if (score>top) Some((here, score)) elsebest } };List.foldLeft(selectBest, None, candidates) |> Option.map(fst) } }////// How wide the formation is when a level begins.////// Measured between the *centres* of the outer columns, which is what `liveBounds` reports,/// so the two are comparable.///deffullWidth(): Float32 = Int32.toFloat32(Rules.columns() -1) *Rules.columnSpacing()defcolumnWorth(t: Tuning, target: Column, ctx: FlankContext): Float32 = {// Near 0 at the top of the formation, near 1 on the invasion line.letnearness = Float32.max(0.0f32, target#y) /Rules.playerY();letonAFlank = target#x ==ctx#left ortarget#x ==ctx#right;letnearlyDone = target#depth <=t#stragglers;letsteady = composure(t, ctx#looming);letnarrowing = if (ctx#spread >t#narrowTo) t#narrowing *steadyelse0.0f32;letfinishing = if (nearlyDone) t#finishFlank *steadyelse0.0f32;t#imminence *nearness+ (if (onAFlank) narrowing+finishingelse0.0f32) }////// How far down the formation has come: 0 at the top, 1 on the invasion line.///defpressure(candidates: List[Column]): Float32 = {letmaxPos = (low, c) -> Float32.max(low, c#y);letdeepest = List.foldLeft(maxPos, 0.0f32, candidates);Float32.max(0.0f32, deepest) /Rules.invasionLine() }////// How much appetite there is for tidying up the flanks, given how low they have got.////// Finishing an outer column is a long game -- it pays back over the rest of the level --/// and there is no rest of the level once the front row is at the door. Past `t#calm` the/// bonus fades out, so the bot drops the housekeeping and clears the bottom row, which is/// both the thing about to land on it and the thing dropping the bombs.///defcomposure(t: Tuning, looming: Float32): Float32 =if (looming<t#calm)1.0f32elseFloat32.max(0.0f32, (1.0f32-looming) / (1.0f32-t#calm))////// How dangerous it is to stand at `x`.////// Every bomb still above the cannon contributes, weighted by how nearly overhead it is/// and how close it has got. Scoring positions rather than reacting to a single bomb is/// what stops the bot sidestepping out of one bomb's path and into another's -- which is/// how it kept dying with lives to spare.///defdanger(t: Tuning, x: Float32, w: World): Float32 =// A standing bunker overhead stops the bomb before it arrives, which is what bunkers// are for. Shelter is not total -- blocks are being eaten all game, and the bot should// not treat a two-block stub as a roof -- but it is worth most of a dodge.if (Bunkers.blocks(w#bunkers, x))t#shelterRelief *rawDanger(t, x, w)elserawDanger(t, x, w)defrawDanger(t: Tuning, x: Float32, w: World): Float32 =List.foldLeft( (total, b) ->if (b#y >Rules.playerY() orharmless(b, w))totalelse {letacross = Float32.abs(b#x -x);if (across>t#dangerWidth)totalelse {// Near 0 up at the formation, near 1 just above the cannon: a bomb about// to land matters far more than one just dropped.letcloseness = Float32.max(0.0f32, b#y) /Rules.playerY();total+ (1.0f32-across/t#dangerWidth) * (0.3f32+closeness) } },0.0f32,w#bombs )////// Whether the shield will still be up when this bomb arrives.////// Shooting the saucer buys ten seconds of immunity, and dodging through it wastes the/// prize -- that is time the cannon should spend standing under the formation and firing./// Checked bomb by bomb rather than as a blanket "shielded, ignore everything", because/// the shield runs on a clock: one with twenty ticks left does nothing about a bomb that/// takes forty to land, and walking calmly into that would be a strange way to celebrate.///defharmless(bomb: Bomb, w: World): Bool = {// Per kind: a dagger arrives in two thirds the time a wiggler does, so a shield that// covers one may not cover the other.letfall = (Rules.playerY() -bomb#y) /Rules.bombSpeedFor(bomb#kind);fall<Int32.toFloat32(w#shield) }/// `x` clamped to somewhere the cannon can actually stand.defonField(x: Float32): Float32 = {lethalf = Rules.playerSize()#x /2.0f32;letrightEdge = Rules.fieldWidth() -half;if (x<half) halfelseif (x>rightEdge) rightEdgeelsex }////// Whether a shot fired now would hit something.////// Not just the chosen target: a shot that connects with any invader is a shot worth/// taking. Firing only when lined up on the target wasted every tick the cannon spent/// under some *other* column, and the formation landed while it was still being fussy.///defwillConnect(t: Tuning, w: World): Bool = {letliving = Vector.count(inv -> inv#alive, w#invaders);letdrift = w#marchDir *Rules.marchSpeedFor(living, w#level);letwSpan = Rules.invaderSize()#x +Rules.bulletSize()#x;letoverlap = t#fireWindow *wSpan/2.0f32;lethitsInv = inv ->if (notinv#alive)falseelse {letflight = (Rules.playerY() -inv#pos#y) /Rules.bulletSpeed();letprojectedX = inv#pos#x +drift*flight;if (flight<=0.0f32) falseelseFloat32.abs(projectedX-w#playerX) <overlap };Vector.exists(hitsInv, w#invaders) }defworthFiring(t: Tuning, dx: Float32, w: World): Bool =// Never through its own shelter. The rules allow it -- carving a slit is legal, and in// the arcade original it is a tactic -- but a bot doing it by accident is spending// shots to demolish its own cover.if (Bunkers.obstructs(w#bunkers, w#playerX, Rules.bulletSize()#x))false// The saucer crosses above the formation on its own path, so being lined up on it is// its own reason to fire; the formation is judged separately and always.elseif (Option.isEmpty(w#mystery))willConnect(t, w)elseFloat32.abs(dx) <6.0f32orwillConnect(t, w)////// The best place to stand: safe first, in position second.///defbestSpot(t: Tuning, aimX: Float32, w: World): Float32 = {letscoreCandidate = offset -> {letx = onField(w#playerX +offset);letd = danger(t, x, w) *t#selfPreservation;letu = Float32.abs(aimX-x) /t#urgency;letbCost =if (Bunkers.obstructs(w#bunkers, x, Rules.bulletSize()#x))t#blockedCostelse0.0f32; (x, d+u+bCost) };letscored = List.map(scoreCandidate, options());letpickBest = (best, candidate) -> {let (x, score) = candidate;matchbest {case None => Some((x, score))case Some((_, bestScore)) => if (score<bestScore) Some((x, score)) elsebest } };List.foldLeft(pickBest, None, scored) |> Option.map(fst) |> Option.getWithDefault(w#playerX) }////// One tick of play, with `error` added to where the bot thinks the target is.////// The aim leads the target by the bullet's flight time: a bullet takes roughly forty/// ticks to reach the formation, and the invaders move most of their own width in that/// time. Aiming at where a target *is* rather than where it will *be* misses nearly/// every shot.///defintent(t: Tuning, error: Float32, w: World): Option[{goal = Float32, fire = Bool}] = {matchchooseTarget(t, w) {case None => Nonecase Some(p) =>letliving = Vector.count(inv -> inv#alive, w#invaders);letflight = (Rules.playerY() -p#y) /Rules.bulletSpeed();letmSpeed = Rules.marchSpeedFor(living, w#level);letdrift = matchw#mystery {case Some(m) => m#dir *Rules.mysterySpeed()case None => w#marchDir *mSpeed };letdx = (p#x +drift*flight+error) -w#playerX;// A delta from where the cannon stands, not an absolute x: `playTick` walks// `goal` pixels, so dropping this subtraction sends the bot to the far wall.letgoal = bestSpot(t, w#playerX +dx, w) -w#playerX;letfire = worthFiring(t, dx, w); Some({goal = goal, fire = fire}) } }/// The keys for a committed direction and a decision to shoot.defkeysFor(moving: Int32, fire: Bool): Snapshot = {letmove = if (moving<0) Key.Left :: Nil elseif (moving>0) Key.Right :: Nil else Nil;Input.holding(List.append(move, if (fire) Key.Space :: Nil else Nil)) }/// Which way to walk, with no commitment to a previous direction.defwants(t: Tuning, goal: Float32): Int32 =if (goal<-t#startAt) -1elseif (goal>t#startAt) 1else0////// A competent player: perfect aim, and it dodges.////// Used by the balance test, where the point is to measure the *game* rather than the/// player. Its results are an optimistic bound -- a human misses.///pubdefaim(t: Tuning, w: World): Snapshot = matchintent(t, 0.0f32, w) {case None => Input.empty()case Some(i) => keysFor(wants(t, i#goal), i#fire) }/// A hand that has not played yet.pubdeffresh(seed: Int64): Hand = {letrng = Rng.fromSeed(seed); {rng = rng, error = 0.0f32, settled = 0, moving = 0, lapse = 0} }defstartLapse(t: Tuning, hand: Hand, rng: Rng): (Snapshot, Hand) = {let (extra, next) = Rng.nextInt32Below(t#lapseSpread, rng);letlTime = t#lapseFor +extra; (Input.empty(), {rng = next, lapse = lTime, moving = 0 | hand}) }defplayTick(t: Tuning, w: World, hand: Hand, rng: Rng): (Snapshot, Hand) = {let (error, settled, next) = judge(t, hand, rng);matchintent(t, error, w) {case None =>leth = {rng = next, error = error, settled = settled, moving = 0 | hand}; (Input.empty(), h)case Some(i) =>letmoving = commit(t, hand#moving, i#goal);leth = {rng = next, error = error, settled = settled, moving = moving | hand}; (keysFor(moving, i#fire), h) } }////// A fallible player: the same aim, blurred, and occasionally not paying attention.////// Perfect play makes a dull demo -- the formation evaporates in a straight line and/// nothing ever threatens the cannon. A little jitter and the odd idle tick make the/// attract screen look like somebody playing.////// Returns the advanced generator, so the caller keeps the demo's randomness entirely/// separate from the world's.///pubdefimperfect(t: Tuning, w: World, hand: Hand): (Snapshot, Hand) =if (hand#lapse >0) (Input.empty(), {lapse = hand#lapse -1, moving = 0 | hand})else {let (lapsing, afterChance) = Rng.chance(t#lapseOneIn, hand#rng);if (lapsing) startLapse(t, hand, afterChance) elseplayTick(t, w, hand, afterChance) }////// The misjudgement it is working from, re-drawn only when the last one has gone stale.////// Holding it is the whole point. Re-drawing every tick is what made the cannon shake.///defjudge(t: Tuning, hand: Hand, rng: Rng): (Float32, Int32, Rng) =if (hand#settled >0) (hand#error, hand#settled -1, rng)else {let (drawn, afterError) = Rng.nextInt32Below(2*t#aimJitter +1, rng);let (extra, afterHold) = Rng.nextInt32Below(t#judgeSpread, afterError); (Int32.toFloat32(drawn-t#aimJitter), t#judgeFor +extra, afterHold) }////// Which way to push, given which way it is already pushing.////// A hand already moving one way needs a real reason to go the other, so reversing takes a/// wider miss than starting does. The cannon still corrects an overshoot -- it covers 4px/// a tick, so it passes `reverseAt` within two ticks of going too far -- it just no longer/// twitches when it is nearly right.///defcommit(t: Tuning, moving: Int32, goal: Float32): Int32 = {letwanted = wants(t, goal);letreversing = wanted!=0andmoving!=0andwanted!=moving;if (reversingandFloat32.abs(goal) <t#reverseAt) movingelsewanted }}