////// One line of an overlay: what it says, how big, and in what colour.///pubtypealiasCaption = {text = String, size = Float32, colour = Color}////// Drawing the cabinet, as opposed to drawing the game.////// `View.render` knows how to draw one game and nothing else. This module decides *which*/// game is on screen and what to overlay on it -- the title, the invitation to press a key,/// the score table. It uses only the `Canvas` effect, so a test can record a whole title/// screen as data without a window.///mod Screens {////// How dark the panel behind overlay text is.////// Light enough that the game keeps playing visibly through it. The point of an attract/// screen is the game; the text only has to stay readable where it crosses a sprite.///defpanelAlpha(): Int32 = 130defpadding(): Float32 = 12.0f32defleading(): Float32 = 12.0f32/// The width of the widest caption.defblockWidth(captions: List[Caption]): Float32 =List.foldLeft( (widest, c) -> Float32.max(widest, View.textWidth(c#text, c#size)),0.0f32,captions )/// The height the captions occupy once stacked.defblockHeight(captions: List[Caption]): Float32 = {letaddCaptionHeight = (total, c) -> total+c#size +leading();lettotalHeight = List.foldLeft(addCaptionHeight, 0.0f32, captions);totalHeight-leading() }/// Draws a stack of centred captions, starting with the first baseline a line down.defstack(captions: List[Caption], top: Float32): Unit \ Canvas = {defdraw(rest, y) = matchrest {case Nil => ()casec :: more =>letx = View.centredX(c#text, c#size);letnextY = y+c#size;Canvas.fill(c#colour);Canvas.textSize(c#size);Canvas.text(c#text, x, nextY);draw(more, nextY+leading()) };draw(captions, top) }////// Draws captions on a translucent panel sized to fit them.////// Sized to the text rather than spanning the screen: a full-width band hid whichever/// invaders happened to be behind it, and dimming the whole field made the demo murky.///defblock(captions: List[Caption], top: Float32): Unit \ Canvas = {letwidth = blockWidth(captions);letheight = blockHeight(captions);Canvas.fillAlpha(Palette.background(), panelAlpha());Canvas.rect( (Rules.fieldWidth() -width) /2.0f32-padding(),top-padding(),width+2.0f32*padding(),height+2.0f32*padding() );stack(captions, top) }defcaption(text: String, size: Float32, colour: Color): Caption = {text = text, size = size, colour = colour}/// Where a block of `captions` starts if it is to sit centred in the field.defcentredTop(captions: List[Caption]): Float32 = (Rules.fieldHeight() -blockHeight(captions)) /2.0f32////// The attract screen: the demo playing at full brightness, with the title over it.///defattract(s: Session): Unit \ Canvas = {View.render(Session.onScreen(s));block(attractCaptions(), centredTop(attractCaptions())) }defattractCaptions(): List[Caption] =caption("FLIX INVADERS", View.bannerSize(), Palette.invaderGreen()) :: caption(Meta.label(), View.hudSize(), Palette.invaderGreen()) :: caption("PRESS 1 OR 2 FOR PLAYERS TO PLAY", View.hudSize(), Palette.ink()) :: Nil////// The top edge of the attract screen's panel.////// Public because `View` has to stay clear of it. The demo plays *behind* this panel, so/// anything the game itself draws at the middle of the field -- the level banner between/// waves, most of all -- lands inside it and neither is readable.///pubdefattractPanelTop(): Float32 = centredTop(attractCaptions()) -padding()////// Asking for the initials that go beside a qualifying score.////// The caret is a literal underscore rather than a drawn rectangle, so it lines up with/// the monospaced font for free.///defentering(s: Session): Unit \ Canvas = {// Told who else is playing, like the playing screen: a two-player game must still show// both scores while the second player is typing.View.renderWith(Session.onScreen(s), Session.cabinet(s));letasking = List.head(s#pending);letscore = asking |> Option.map(claim -> claim#entry#score) |> Option.getWithDefault(0);letcaret = if (String.length(s#typing) <Scores.nameLength()) "_"else"";// Whose initials these are, but only when there is more than one candidate. In a// one-player game naming the player is noise; in a two-player game the prompts arrive// back to back and are otherwise indistinguishable -- the first version of this screen// asked twice without ever saying who it was asking.letwhose =if (s#players <2) Nilelseasking |> Option.map(claim ->caption("PLAYER ${claim#player +1}",View.hudSize(),Palette.invaderGreen() ) :: Nil ) |> Option.getWithDefault(Nil);letcaptions =List.append(whose,caption("NEW HIGH SCORE ${score}", View.hudSize(), Palette.sun()) :: caption(s#typing +caret, View.bannerSize(), Palette.ink()) :: caption("TYPE 3, THEN ENTER", View.hudSize(), Palette.invaderCyan()) :: Nil );block(captions, centredTop(captions)) }////// The high-score table, on its own rather than over the game.///deftable(s: Session): Unit \ Canvas = {lettitleSize = View.bannerSize();lettitleX = View.centredX("HIGH SCORES", titleSize);Canvas.clear(Palette.background());Canvas.fill(Palette.invaderGreen());Canvas.textSize(titleSize);Canvas.text("HIGH SCORES", titleX, 64.0f32);letrows =if (List.isEmpty(s#scores))caption("NOBODY YET", View.hudSize(), Palette.dim()) :: NilelseList.mapWithIndex( (i, e) ->letcol = if (i==0) Palette.sun() elsePalette.ink();letnameStr = Scores.padded(e#name);letscoreStr = View.scoreText(e#score);letrowText = "${nameStr} ${scoreStr} L${e#level}";caption(rowText, View.hudSize(), col),s#scores );// No panel here: there is no game behind this screen to see through to.stack(rows, 110.0f32);letpromptX = View.centredX("PRESS ENTER", View.hudSize());Canvas.fill(Palette.invaderCyan());Canvas.textSize(View.hudSize());Canvas.text("PRESS ENTER", promptX, Rules.fieldHeight() -40.0f32) }// -- stats for nerds ------------------------------------------------------------------defnerdSize(): Float32 = 10.0f32defnerdLeft(): Float32 = 12.0f32defnerdTop(): Float32 = 64.0f32defnerdLine(): Float32 = 13.0f32defnerdWidth(): Float32 = 214.0f32////// The telemetry overlay, in the corner, on F3.////// Left-aligned and monospaced-by-accident -- the arcade font is fixed width -- so the/// numbers sit in columns and a changing digit is easy to catch out of the corner of an/// eye. Deliberately in the top left, clear of the score row above it, the formation, and/// the attract panel across the middle.////// What it shows is chosen to answer the questions this project actually asks: is the/// frame budget being met, is the simulation keeping up, and is the world where you think/// it is. `DIGEST` is the same fingerprint the replay tests compare, so two runs that/// should be identical can be checked against each other by eye.///defnerds(s: Session, telemetry: Stats): Unit \ Canvas = {letw = Session.onScreen(s);letlines = nerdLines(s, w, telemetry);letlen = Int32.toFloat32(List.length(lines));letheight = len*nerdLine() +padding();letboxX = nerdLeft() -padding() /2.0f32;letboxY = nerdTop() -nerdLine();Canvas.fillAlpha(Palette.background(), 190);Canvas.rect(boxX, boxY, nerdWidth(), height);Canvas.textSize(nerdSize());List.forEachWithIndex( (i, line) -> {let (label, value) = line;letlineY = nerdTop() +Int32.toFloat32(i) *nerdLine();Canvas.fill(Palette.dim());Canvas.text(label, nerdLeft(), lineY);Canvas.fill(Palette.invaderCyan());Canvas.text(value, nerdLeft() +84.0f32, lineY) },lines ) }////// What the overlay says, as label and value pairs.////// Split out from the drawing so a test can read it. Everything here is a pure function of/// the session and the figures the runtime handed over.///pubdefnerdLines(s: Session, w: World, telemetry: Stats): List[(String, String)] = {letalive = Vector.count(inv -> inv#alive, w#invaders);letcountBlocks = (total, b) -> total+Bunkers.remaining(b);letblocks = Vector.foldLeft(countBlocks, 0, w#bunkers);letfpsStr = Stats.oneDecimal(telemetry#fps);letsimStr = "${Stats.twoDecimals(telemetry#simMs)} MS";letdrawStr = "${Stats.twoDecimals(telemetry#drawMs)} MS";lettargetMs = 1000.0f32/Int32.toFloat32(Rules.ticksPerSecond());lettotalTime = telemetry#simMs +telemetry#drawMs;letbMsg = "${Stats.twoDecimals(totalTime)} / "+"${Stats.twoDecimals(targetMs)} MS"; ("FPS", fpsStr) :: ("SIM", simStr) :: ("DRAW", drawStr) :: ("BUDGET", bMsg) :: ("STEPS", "${telemetry#steps} CATCHUP ${telemetry#catchUps}") :: ("FRAMES", "${telemetry#frames}") :: ("SCREEN", "${s#screen}") :: ("TICK", "${w#tick} LEVEL ${w#level}") :: ("INVADERS", "${alive} / ${Rules.totalInvaders()}") :: ("SHOTS", "${List.length(w#bullets)} UP ${List.length(w#bombs)} DOWN") :: ("BUNKERS", "${blocks}") :: ("SHIELD", "${w#shield}") :: ("SEED", "${w#seed}") :: ("DIGEST", digestOf(w)) :: Nil }/// The replay fingerprint, shortened to something a person can compare at a glance.defdigestOf(w: World): String = {letfull = Game.digest(w);if (String.length(full) <=22) fullelseString.takeLeft(22, full) +".." }////// The beat between one player's game ending and the next player's starting.////// Their own fresh field is already behind it, so what they are about to play is visible/// while they get a hand back on the controls. On the same dimmed panel the title uses,/// for the same reason: the field behind stays legible, and a plain overlay of text on a/// formation is hard to read at a glance.////// Same position and same count as the pause between waves -- it is the same idea, and/// two different countdowns would be two things to learn.///defhandover(s: Session): Unit \ Canvas = {View.renderWith(Session.active(s), Session.cabinet(s));letcount = View.countdown(s#handover);letdigits =if (count<=0) Nilelsecaption("${count}", View.countdownSize(), Palette.sun()) :: Nil;letcaptions =caption("PLAYER ${s#current +1}", View.bannerSize(), Palette.ink()) :: caption("GET READY", View.hudSize(), Palette.invaderCyan()) :: digits;// Positioned so the first line lands on the same baseline as every other banner.block(captions, View.bannerY() -View.bannerSize()) }////// The beat after a game ends, before anything replaces it.////// On the same dimmed panel as the title and the hand-over. It names the player in a/// two-player game for the same reason the initials prompt does: two people finish one/// after the other, and an unlabelled GAME OVER between them says nothing about whose.///defgameOver(s: Session): Unit \ Canvas = {letactiveWorld = Session.active(s);letcab = Session.cabinet(s);View.renderWith(activeWorld, cab);letpName = "PLAYER ${s#current +1}";letwhose =if (s#players <2) Nilelsecaption(pName, View.hudSize(), Palette.invaderGreen()) :: Nil;letcaptions =List.append(whose, caption("GAME OVER", View.bannerSize(), Palette.ink()) :: Nil);lettopY = View.bannerY() -View.bannerSize();block(captions, topY) }////// One frame of whatever the cabinet is showing.///pubdefrender(s: Session, telemetry: Stats): Unit \ Canvas = {matchs#screen {case Screen.Attract => attract(s)case Screen.Playing =>if (s#over >0)gameOver(s)elseif (s#handover >0)handover(s)elseView.renderWith(Session.active(s), Session.cabinet(s))case Screen.Entering => entering(s)case Screen.Table => table(s) };if (s#nerds) nerds(s, telemetry) else() }}