32. 2D Fighting Game Part 3: Scrolling Stages and AI Opponents

Chapter 31 made Hayate and Jin fight: moves as frame data, hit boxes and hurt boxes, hit stun, knockback, hit stop, an input buffer, health bars and a scene graph for headband tails and sparks.
But they still fight in a box: one dojo exactly as wide as the screen, two humans on one keyboard, and a single endless round in training mode.

This chapter finishes fighter.
The fight moves onto a stage wider than the screen, a temple courtyard at sunset built from five parallax layers, with a camera that follows the fighters and stops at the stage ends.
A CPU opponent joins, written as an invisible player that presses the same buttons a human would.
And the fight becomes a match: best of three rounds with a 60-second timer, a title screen with game modes and difficulty, a pause menu and a win screen with a rematch.

There are no new OpenGL functions in this chapter.
The rendering side is one idea, parallax, and it turns out to be "one camera per layer".
The rest is game structure, and the question that runs through it is a good one to end a game on: what does the CPU need to know, and when is it allowed to know it?

32.1 What we're building

A kick lands on the CPU in the middle of a scrolled stage, with the timer at 55:

The fighting game at 1280 by 720: Hayate in white with a red headband kicks Jin in blue, a big orange spark at the impact. Behind them a red torii, cherry trees, mountains, a setting sun and a pagoda; at the top two health bars, 1P HAYATE and CPU JIN 2P with empty round marks, and the timer 55 in the middle; at the bottom the bilingual control hints

The clip starts on the title, picks 1P vs CPU, shows ROUND 1 and FIGHT!, and then a scripted human trades hits and blocks with the CPU on Normal while the camera scrolls:

The controls:

  • Title: W S or ↑ ↓ select a mode, A D or ← → change the difficulty, Space, Enter, F or K start, Esc quits
  • Fight: as in chapter 31 (1P A D W S with F punch and G kick, 2P the arrow keys with K and L), Esc or P pause, F1 the debug overlay
  • Pause: W S or ↑ ↓ select, Space, Enter, F or K confirm, Esc or P resume
  • Win screen: Space, Enter, F or K rematch (same mode and difficulty), Esc back to the title

The title offers four modes: 1P vs CPU (the CPU plays 2P), 2P vs (two humans, as before), CPU vs CPU (watch two CPUs at the chosen difficulty) and Training (no timer and no rounds, a KO restarts after 3 s, chapter 31's behavior).

Starting from chapter 31, the changes are all inside games/fighter/:

  • src/stage.hh, src/stage.cc (new): the parallax stage, its camera limits and the falling petals
  • src/ai.hh, src/ai.cc (new): Difficulty, the difficulty profiles and AiController
  • src/match.hh (new): Mode, MatchSettings and the match rules
  • src/hud.hh, src/hud.cc (new): the colors and drawBigText, moved out of the fight scene so every scene can use them
  • src/menu_keys.hh (new): menu keys that work with either player's keys
  • src/scenes.hh, src/title_scene.cc, src/pause_scene.cc, src/result_scene.cc (new): the three new scenes
  • src/fight_scene.hh, src/fight_scene.cc: CPU slots, rounds, the timer, the camera, the stage instead of the dojo, the new HUD
  • src/fighter.hh, src/fighter.cc: a Win state for the victory pose
  • src/game.hh, src/main.cc: the stage and the chosen difficulty in Game, and the program now starts on the title
  • assets/stage_*.png (new): the five layers, with their lines in assets/LICENSE.txt (the finished files are in the chapter's ZIP and in ch32/ of the assets ZIP)
  • README.md: modes and rules

The executable gets six more source files:

# 2D格闘ゲーム(第30〜32章):エンジンにリンクする自分の実行ファイル
# The 2D fighting game (chapters 30-32): its own executable linking the engine
add_executable(fighter
  src/main.cc
  src/ai.cc
  src/controls.cc
  src/effects.cc
  src/fighter.cc
  src/fight_scene.cc
  src/frame_data.cc
  src/hud.cc
  src/moves.cc
  src/pause_scene.cc
  src/result_scene.cc
  src/scene_graph.cc
  src/stage.cc
  src/title_scene.cc)
target_include_directories(fighter PRIVATE src)
target_link_libraries(fighter PRIVATE engine)
enable_warnings(fighter)
set_working_directory(fighter)

Re-run CMake after adding the files (Visual Studio does it by itself when CMakeLists.txt changes).
As in every game chapter, nothing outside games/fighter/ changes.

32.2 A stage wider than the screen

The canvas is still 640 × 360 (shown at ×2 in the 1280 × 720 window, chapter 30's choice), but the stage is now 1024 px wide.
It's drawn as five images stacked from back to front:

Layer Factor Width Content Sort layer
stage_sky.png 0.05 659 px sunset gradient, striped sun, clouds 0.0
stage_far.png 0.25 736 px two mountain ranges 0.1
stage_mid.png 0.5 832 px torii, pagoda, cherry trees, temple wall 0.2
stage_ground.png 1.0 1024 px stone paving, the fighters stand at y = 320 0.3
stage_front.png 1.3 1139 px stone lanterns and grass in front of the fighters 12

All five are 360 px high, and all of them come from one generator script of mine, like the fighters' sprites.
It paints with numpy arrays instead of hand-drawn pixel rows: the sky is a vertical gradient between hand-picked sunset colors, broken into bands with a 4 × 4 ordered (Bayer) dither so it stays pixel art without antialiasing; the sun is a disk cut by horizontal stripes; the mountain ridges are sums of three sine waves with random phases, rounded to 2 px steps so their edges look hand-placed; the temple layer draws the torii, the pagoda and the cherry trees from rectangles, polygons and circles; the ground is rows of stone slabs with random lengths and four stone colors, the rows growing from 8 px high at the back to 30 px at the front, a cheap perspective cue.
Everything random comes from numpy.random.RandomState with fixed seeds, so running the script again gives byte-identical PNGs (all five together are only 18 KB).
Each layer's width is computed by the script from the formula we'll derive in a moment, and the script's preview mode draws the article image below: the view at both camera limits, and every layer at half size with the visible window marked at the left limit (cyan) and at the right limit (orange).

Top: the 640 by 360 view at the left camera limit, center x 320, with the torii and a lantern, and at the right limit, center x 704, with the pagoda and the other lantern. Below: the five layers at half size, stage sky 659 px factor 0.05, stage far 736 px factor 0.25, stage mid 832 px factor 0.5, stage ground 1024 px factor 1 and stage front 1139 px factor 1.3, each with a cyan window at its left end and an orange window ending exactly at its right end

Why far things move slower

Look out of a train window: the fence next to the track flies past, the houses behind it slide by, the mountains on the horizon barely move.
That's parallax, and it's what makes a flat 2D background read as deep.

The reason is perspective projection from Linear Algebra chapter 12: a pinhole camera puts a point at depth z on the screen at xs=d⋅x/z, where d is the distance to the image plane.
If the camera slides sideways by t, every point's x relative to the camera changes by t, so its image moves by

Δxs=tdz

Twice as far away, half the motion.
Take the ground at depth z0 as the reference that moves exactly with the camera; then a layer at depth z moves by the fraction

f=z0z

of the camera's motion, and that fraction is the layer's parallax factor.

Top view of a pinhole camera moving sideways by t equals 240, from camera A to camera B. Three depth planes: the ground at z 80 with factor 1, the temple at z 160 with factor 0.5, the mountains at z 320 with factor 0.25. Rays from camera B to points straight ahead of camera A cross B&

Read backwards, the factors in the table say where each layer "is": the temple at f=0.5 behaves as if it stood twice as far away as the ground, the mountains 4 times, the sky 20 times.
The front layer's 1.3 is larger than 1, so it acts as if it were closer than the fighters (z=z0/1.3≈0.77z0) and sweeps past faster than the ground.
None of this is real 3D: each layer is one flat image, and the illusion only works sideways.
That's also why there's no vertical parallax in this game: the camera never moves up or down, so every layer's top edge simply sits at world y = 0.

One camera per layer

In code, the factor becomes a second camera for each layer.
Let L be the view's left edge in stage coordinates (the main camera's center minus 320).
The ground layer is drawn at stage x = 0, so it appears on the screen shifted by −L; a layer with factor f must appear shifted by only −fL, as if its own camera had moved f times as far.
Since the whole batch is drawn with the main camera's matrix, we cancel the main camera and apply the layer's: the layer's left edge goes to world x =L−fL.
Here are the stage's declarations:

// スクロールする舞台:視差の層(遠いほどゆっくり動く)、カメラの範囲、舞い散る花びら
// The scrolling stage: parallax layers (the farther, the slower), the camera's limits, falling petals
#pragma once

#include "engine/camera2d.hh"
#include "engine/rng.hh"
#include "engine/sprite_batch.hh"
#include "engine/texture.hh"

#include <optional>
#include <vector>

constexpr float kStageWidth = 1024.0f; // 舞台の幅(ワールドのピクセル)。見えるのは640 / the stage width (world pixels);
                                       // 640 are visible

// 一枚の層:factor = カメラに対する動きの割合(0 = 動かない空、1 = 地面と同じ、> 1 = 手前)
// One layer: factor = how much of the camera's motion it follows (0 = a still sky, 1 = with the ground, > 1 = in
// front)
struct ParallaxLayer {
  Texture2D texture;
  float factor;
  float layer; // SpriteSort::Layerの順番 / order for SpriteSort::Layer
};

class Stage {
public:
  // games/fighter/assets/stage_*.png を読む / loads games/fighter/assets/stage_*.png
  static std::optional<Stage> load();

  // カメラの中心のxを舞台の中に収める:画面の端が舞台の外を映さない / clamps the camera center's x so the view never
  // shows anything outside the stage
  static float clampCamera(float centreX, float viewWidth);
  // ファイターの後ろの層(空・山・寺・地面)と、前の層(灯籠・花びら)。cameraはワールドのカメラ
  // The layers behind the fighters (sky, mountains, temple, ground) and in front (lanterns, petals). camera is the
  // world camera
  void drawBack(SpriteBatch &batch, const Camera2D &camera) const;
  void drawFront(SpriteBatch &batch, const Camera2D &camera) const;
  void update(float dt); // 花びら / the petals

private:
  struct Petal {
    Vec2 position; // 画面の座標(花びらは手前の層:factor 1.15) / screen-ish coordinates (petals live on a 1.15 layer)
    Vec2 velocity;
    float phase;
  };
  void drawLayer(SpriteBatch &batch, const ParallaxLayer &l, const Camera2D &camera) const;

  std::vector<ParallaxLayer> back, front;
  std::vector<Petal> petals;
  Rng rng{32};
  float time = 0.0f;
};

And the drawing, with the shift rounded to whole pixels:

float Stage::clampCamera(float centreX, float viewWidth) {
  float half = viewWidth * 0.5f;
  return std::clamp(centreX, half, kStageWidth - half);
}

// 視差:その層のカメラはfactor倍だけ動く。画面の左端が舞台のxなら、層は −x·factor だけずらして描く
// Parallax: a layer's camera moves `factor` times as far. If the view's left edge is at stage x, the layer is drawn
// shifted by −x·factor
void Stage::drawLayer(SpriteBatch &batch, const ParallaxLayer &l, const Camera2D &camera) const {
  float left = camera.centre.x - camera.viewSize.x * 0.5f;
  Vec2 size = {static_cast<float>(l.texture.width()), static_cast<float>(l.texture.height())};
  // ワールドの座標で描く:層の左端 = left − left·factor(整数に丸めてピクセルをそろえる)
  // Drawn in world coordinates: the layer's left edge = left − left·factor (rounded to whole pixels)
  float x = left - std::round(left * l.factor);
  // 縦は動かない(カメラの高さは固定):層の上端はワールドのy = 0 / no vertical parallax (the camera height is fixed):
  // a layer's top is at world y = 0
  batch.draw({.texture = &l.texture, .position = {x, 0.0f}, .size = size, .layer = l.layer});
}

clampCamera is the camera's limit, which the next section needs.
drawLayer is the whole parallax technique: one subtraction and one rounding per layer, one sprite per layer.
The rounding matters for pixel art: the main camera's center is already a whole number (we'll see that in a moment), and std::round(left * l.factor) makes each layer's offset whole too, so every layer moves in whole canvas pixels, at its own rate.
The slow layers move one pixel every few camera pixels; that small stepping is what parallax looks like in 16-bit-era games, and no texel is ever sampled between two pixels.
The sort layers (0 to 0.3 behind everything, 12 for the front layer, while the fighters use 2 and 3 and the sparks 6) let SpriteSort::Layer put them in the right order no matter which order we submit them in.

How wide each layer must be

A layer that's too narrow shows its end before the camera reaches the stage's end; a layer that's too wide wastes pixels that are never seen.
The view is 640 px wide and its left edge L goes from 0 (the left limit) to

Lmax=1024−640=384

(the right limit).
At L, the layer's pixel u appears at screen x =u−fL, so the screen shows the layer's pixels u∈[fL,fL+640).
At the left limit that's [0,640); at the right limit it's [384f,384f+640).
The layer must contain both windows, and the smallest image that does ends exactly at the second one:

W(f)=640+f⋅(1024−640)=640+384f

Four bars at 0.6 scale: factor 1.3, 640 plus 499 equals 1139 px; factor 1, 640 plus 384 equals 1024 px; factor 0.5, 640 plus 192 equals 832 px; factor 0.05, 640 plus 19 equals 659 px. On each bar a solid cyan 640 px window at the left end, the view at L equals 0, and a dashed orange 640 px window ending at the right end, the view at L equals 384

Layer f 384f W=640+384f Image Shift at the right limit Visible right edge
sky 0.05 19.2 659.2 659 round(19.2)=19 659 − 19 = 640
far 0.25 96 736 736 96 736 − 96 = 640
mid 0.5 192 832 832 192 832 − 192 = 640
ground 1.0 384 1024 1024 384 1024 − 384 = 640
front 1.3 499.2 1139.2 1139 round(499.2)=499 1139 − 499 = 640

The two fractional widths are where rounding could bite: the generator rounds the width (659.2 → 659, 1139.2 → 1139) and drawLayer rounds the shift the same way (19.2 → 19, 499.2 → 499), so the layer's right edge lands exactly on the view's right edge, 640, with no 1-pixel gap.
For every L in between, the shift is smaller, so the image always covers the view.
The ground is the special case f=1: its width is the stage width, which is why "stage coordinates" and "ground pixels" are the same thing.
The same formula works for the front layer with f>1: it's simply wider than the stage.
And nothing needs to repeat: a tiling background (a horizontally wrapped texture, GL_REPEAT and a UV offset) is the other classic way to do parallax, and it's the right one for a stage with no ends, like a runner; a fighting game's stage has two ends, so exact-width images are simpler and let the art have a left side and a right side.

Loading the layers

Stage::load reads the five PNGs and creates the petals:

std::optional<Stage> Stage::load() {
  struct Spec {
    const char *file;
    float factor, layer;
    bool front;
  };
  // 幅は 640 + factor × (1024 − 640):カメラが端に着いたとき、層もちょうど端 / widths are 640 + factor × (1024 − 640):
  // when the camera reaches an edge, so does every layer (the images have these widths)
  const Spec specs[] = {
    {"stage_sky", 0.05f, 0.0f, false}, {"stage_far", 0.25f, 0.1f, false}, {"stage_mid", 0.5f, 0.2f, false},
    {"stage_ground", 1.0f, 0.3f, false}, {"stage_front", 1.3f, 12.0f, true},
  };
  Stage stage;
  for (const Spec &s : specs) {
    std::optional<Texture2D> t = loadSpriteTexture(std::string("games/fighter/assets/") + s.file + ".png");
    if (!t) return std::nullopt;
    (s.front ? stage.front : stage.back).push_back({std::move(*t), s.factor, s.layer});
  }
  for (int i = 0; i < kPetals; ++i) {
    Petal p{{stage.rng.range(0.0f, 760.0f), stage.rng.range(-40.0f, 300.0f)},
            {stage.rng.range(-28.0f, -12.0f), stage.rng.range(14.0f, 26.0f)}, stage.rng.range(0.0f, 6.28f)};
    stage.petals.push_back(p);
  }
  return stage;
}

The front layer goes into its own list because it's drawn after the fighters.
Its lanterns stand only near the two stage ends, so in the middle of the stage the layer is transparent and costs nothing but a few fragments of blending; at the ends, a lantern passes in front of a fighter pushed into the corner (in the round-win screenshot below, the lantern hides the head of the knocked-out Jin), which is a cheap way to make the stage feel like a place rather than a backdrop.

Petals

The last touch is 28 cherry petals drifting down and to the left, a separate "layer" with factor 1.15, drawn in code instead of from an image:

void Stage::drawBack(SpriteBatch &batch, const Camera2D &camera) const {
  for (const ParallaxLayer &l : back) drawLayer(batch, l, camera);
}

void Stage::drawFront(SpriteBatch &batch, const Camera2D &camera) const {
  float left = camera.centre.x - camera.viewSize.x * 0.5f;
  // 花びら:手前の層(factor 1.15)の上を左下へ。画面の外に出たら上から戻る(760幅で輪になる)
  // Petals: drift down-left on a 1.15 layer, wrapping round a 760-wide band
  for (const Petal &p : petals) {
    float x = std::fmod(p.position.x - left * kPetalFactor, 760.0f);
    if (x < 0.0f) x += 760.0f;
    float sway = 4.0f * std::sin(time * 2.0f + p.phase);
    Vec2 at = {left + std::round(x - 60.0f + sway), std::round(p.position.y)};
    bool flat = std::sin(time * 5.0f + p.phase) > 0.3f; // くるくる回る:2×2と1×2 / tumbling: 2 × 2 or 1 × 2
    batch.drawRect({at.x, at.y, flat ? 2.0f : 1.0f, 2.0f}, hexColor(0xffc8dcff), 11.0f);
  }
  for (const ParallaxLayer &l : front) drawLayer(batch, l, camera);
}

void Stage::update(float dt) {
  time += dt;
  for (Petal &p : petals) {
    p.position += p.velocity * dt;
    if (p.position.y > 370.0f) {
      p.position.y = -10.0f;
      p.position.x = rng.range(0.0f, 760.0f);
    }
  }
}

A petal's x lives in its own scrolling space: p.position.x - left * kPetalFactor is its position on a band that scrolls 1.15 times as fast as the camera, and std::fmod with 760 wraps it, so a petal that leaves on the left comes back on the right.
The band is 760 px wide, the view's 640 plus 60 px on each side (the - 60.0f), so petals enter and leave outside the screen instead of popping up at the edge.
Each petal is a 2 × 2 or 1 × 2 rectangle, switching with a sine to look like it tumbles, and a petal that falls below y = 370 starts again above the top at a new random x from Rng{32}.
The petals only decorate: nothing in the fight reads them, which will matter when we talk about determinism.

32.3 The camera

Following the midpoint

The camera follows the midpoint of the two fighters, clamped so the view never shows anything outside the stage:

cx=clamp(x1+x22,320,1024−320)

So the camera's center stays in [320,704], and at either limit the view's edge is exactly the stage's edge.
For drawing, the fight scene builds the world camera from the interpolated positions (chapter 26's alpha), so scrolling is as smooth as the fighters' motion, and rounds the center to a whole pixel:

// 画面の端も壁:カメラは二人の真ん中を追い、舞台の中に収まる。二人ともその画面の中にいなければならない
// The view edges are walls too: the camera follows the midpoint, clamped to the stage, and both fighters must stay
// inside that view
void FightScene::keepInView() {
  float centre = Stage::clampCamera(0.5f * (fighters[0].position.x + fighters[1].position.x), kViewSize.x);
  float left = centre - kViewSize.x * 0.5f + kViewMargin, right = centre + kViewSize.x * 0.5f - kViewMargin;
  for (Fighter &f : fighters) clampX(f, std::max(left, kStageLeft), std::min(right, kStageRight));
}

Camera2D FightScene::worldCamera(float alpha) const {
  // 描くときは補間した位置の真ん中 / when drawing: the midpoint of the interpolated positions
  float a = lerp(fighters[0].previous, fighters[0].position, alpha).x;
  float b = lerp(fighters[1].previous, fighters[1].position, alpha).x;
  Camera2D c = Camera2D::screen(kViewSize);
  c.centre.x = std::round(Stage::clampCamera(0.5f * (a + b), kViewSize.x));
  c.pixelSnap = true;
  return c;
}

Camera2D::screen(kViewSize) is chapter 25's camera with world = view pixels; changing centre.x scrolls it, and pixelSnap keeps the matrix on whole pixels.
A follow camera often adds smoothing (move a fraction of the way to the target each step), and a fighting game can afford none: both players must always see both fighters, so the camera goes exactly where the midpoint is.

The view's edges are walls

keepInView, above, is the rule that makes a scrolling fighting game work.
Without it, Hayate could walk left while Jin walks right until they are 900 px apart, and the camera at their midpoint would show neither.
So after the fighters are pushed apart, each one is clamped into the camera's view minus an 8 px margin (and into the stage walls, 12 px from each end):

The 1024 px stage with red stage walls at x 12 and 1012. A yellow 640 px view centered on the fighters&

The two fighters can therefore never be farther apart than one screen.
A standing fighter's push box is 38 px wide around the feet, so its feet are at least 8+19=27 px inside each view edge, and two standing fighters are at most

640−2⋅27=586 px

apart.
In play, the walls feel natural: walking backward away from an opponent who stands still moves the view with you at half your speed (the midpoint moves half as far), until the gap reaches 586 px and you stop as if against a wall.
The view edge is a wall in every other sense, too.
Chapter 31 pushed the attacker back when the victim was pinned against the stage end, so a fighter in the corner can't be hit forever; here the wall is whichever is closer, the stage end or the view edge:

    // 壁(舞台の端か画面の端)を背にした相手には、自分が下がる / against an opponent with their back to a wall (the
    // stage end or the view edge) the attacker is pushed back instead
    Rect vb = v.pushbox();
    float wallLeft = std::max(kStageLeft, viewCentre - kViewSize.x * 0.5f + kViewMargin);
    float wallRight = std::min(kStageRight, viewCentre + kViewSize.x * 0.5f - kViewMargin);
    if (vb.left() <= wallLeft + 0.5f || vb.right() >= wallRight - 0.5f) push[i] = m.knockback * 0.7f;

viewCentre is the same clamped midpoint keepInView uses, computed once at the top of resolveHits.
As in chapter 31, the push-back only goes into push[i] here; it is applied after all contacts, so it never cancels a knockback the attacker took in a trade.

Shake at the edges

Chapter 31 shook the camera on heavy hits and hid the edges by drawing the dojo 8 px larger than the screen.
With a scrolling stage there's nothing beyond the stage ends to draw, so a shake at the left limit showed 2 px of the clear color (the builder found it in the KO screenshot).
The fix is to shake horizontally only, and to clamp the shaken center too:

  // 揺れは横だけ、舞台の中で(端で舞台の外が見えないように) / the shake is horizontal only and stays inside the stage
  // (so nothing outside the stage shows at the ends)
  if (shake > 0) view.centre.x = Stage::clampCamera(view.centre.x + (shake % 2 ? 2.0f : -2.0f), kViewSize.x);

At a stage end the shake then only moves inward, which is still visible, because the layers move by different amounts.

32.4 The CPU opponent: an invisible player

The same Controls as a human

There are two ways to write a computer opponent.
One is to let it act on the fighter directly: "if the player is close, call startMove(Kick)".
The other is to let it play the game: every step it produces the same Controls that readControls produces for a human (left, right, up, down held; punch, kick pressed this step), and those go through exactly the same code.
We use the second, and the whole difference is visible in the fight scene's input loop:

  // 入力:人はキーボードとパッド、CPUはAiController。どちらも同じControlsになる / input: humans from the keyboard and
  // pads, the CPU from AiController; both become the same Controls
  Controls controls[2];
  for (int i = 0; i < 2; ++i) {
    Controls human = readControls(in, i, pads[i]);
    controls[i] = ai[i] ? ai[i]->think(fighters[i], fighters[1 - i]) : human;
    if (phase != RoundPhase::Fight) controls[i] = {}; // 始まりと決着の間は動けない / no control before and after
  }
  for (int i = 0; i < 2; ++i) {
    fighters[i].buffer.record(controls[i]);
    fighters[i].savePrevious();
  }

Two paths into the same struct: keyboard or gamepad through readControls for the human slot, and both fighters&

Why this is the better design:

  • The rules can't be broken. The CPU's kick has the same 8-frame startup, the same input buffer window, the same "only when actionable" rule and the same guard conditions as the human's, because it is the same code. An AI that calls startMove directly can attack during its own recovery by accident, and nobody notices until a player complains that the CPU cheats.
  • The fighter doesn't know who plays it. Fighter has no "is CPU" flag. Every feature added to the fighter (a new move, a new state) works for the CPU without touching it, and every bug fixed for humans is fixed for the CPU.
  • Any slot, any mix. ai[i] is an std::optional<AiController> per side, so 1P vs CPU, CPU vs CPU and 2P vs are the same code with different slots set. CPU vs CPU turned out to be the best test tool in the chapter: two CPUs fight thousands of steps without a script, and they found the trade crash that's described in 32.4's last subsection.
  • Inputs can be recorded and replayed. Since everything that drives a fighter is a Controls per step, a match is fully described by the two streams of Controls. That's the basis of replays, and of the rollback netcode modern fighting games use (challenge 7).

The CPU also follows the "phase" rule: during the round's intro and finish everyone's input is emptied, the CPU's included.
The other half of fairness is what the CPU looks at.
think reads only state a human can see on the screen: the positions, the fighters' states, the move phase and, once a move has started, which move it is.
The human's buttons stay private; the one input it reads is whether the opponent holds down, which on the screen shows as a crouch anyway.

Intents and a decision timer

The CPU's brain is a small state machine.
Its states are intents, what it's trying to do right now, and each intent has a timer:

// コンピューターの相手:人と同じControlsを作る「見えないプレイヤー」。状態(意図)と決める間隔(タイマー)で動き、
// 反応の遅れと確率で強さが変わる
// The computer opponent: an invisible player that produces the same Controls a human does. It runs on states
// (intents) and a decision timer; reaction delays and probabilities set the difficulty
#pragma once

#include "controls.hh"
#include "fighter.hh"

#include "engine/rng.hh"

#include <cstdint>

enum class Difficulty { Easy, Normal, Hard };
const char *difficultyName(Difficulty d);

// 強さの数値。時間はフレーム / the difficulty numbers; times in frames
struct AiProfile {
  int thinkFrames;      // 意図を続ける長さの基準(普通 = 20) / the base for how long an intent lasts (Normal = 20)
  int reactionFrames;   // 相手の技を見てから反応するまで(人なら約12〜15) / from seeing a move to reacting (a human
                        // needs about 12-15)
  float blockChance;    // 見えた技をガードする確率 / chance to guard a move it saw
  float antiAirChance;  // 飛び込みを蹴りで落とす確率 / chance to kick a jump-in out of the air
  float punishChance;   // 相手の硬直に反撃する確率 / chance to punish recovery
  float aggression;     // 近づいて攻める割合 / how often it closes in and attacks
  bool combos;          // 突き → 突きをつなぐ / links punch → punch
};
const AiProfile &aiProfile(Difficulty d);

class AiController {
public:
  AiController(Difficulty difficulty, std::uint32_t seed);
  // 1ステップ分の入力を作る(ファイターの公開されている状態だけを見る:ずるはしない)
  // Makes one step of input (looking only at the fighters' public state: no cheating with hidden data)
  Controls think(const Fighter &self, const Fighter &opponent);
  void reset();
  const char *intentName() const;

private:
  enum class Intent { Wait, Approach, Retreat, Attack, JumpIn, Guard, AntiAir };
  void decide(const Fighter &opponent, float distance);
  void setIntent(Intent next, int frames);
  int thinkTime(float lo, float hi);

  const AiProfile &profile;
  Rng rng;
  Intent intent = Intent::Wait;
  int timer = 30;               // 今の意図の残り / frames left for the current intent
  int reaction = -1;            // 反応までの残り(-1 = なし) / frames until the reaction (-1 = none)
  bool guardLow = false;
  bool sawAttack = false;       // 相手の今の技をもう見た / already saw the opponent's current move
  bool punished = false;        // 相手の今の硬直にもう反撃した / already punished the current recovery
  bool pressed = false;         // この意図でボタンをもう押した / already pressed the button for this intent
  MoveId planned = MoveId::Punch;
};

  • Wait: do nothing for a moment (looking at the opponent is a strategy too)
  • Approach: walk forward until in range
  • Retreat: walk backward (which also guards, thanks to chapter 31's proximity guard)
  • Attack: press one planned move once: punch, kick, sweep or crouching punch
  • JumpIn: jump forward and kick while falling, once close enough
  • Guard: hold back (down-back against a low) for as long as the seen move lasts
  • AntiAir: kick a jumping opponent out of the air once within 85 px

When the current intent's timer runs out and the fighter is free to act, decide draws the next intent, with weights that depend on the distance between the fighters' feet:

// 意図の長さ:thinkFramesの lo〜hi 倍からくじで(倍率は普通の20で決めた値。易しいは長く、難しいは短く)
// An intent's duration: a draw from lo to hi times thinkFrames (the factors were tuned on Normal's 20; Easy keeps
// an intent longer, Hard changes its mind sooner)
int AiController::thinkTime(float lo, float hi) {
  float t = static_cast<float>(profile.thinkFrames);
  return rng.range(static_cast<int>(std::lround(lo * t)), static_cast<int>(std::lround(hi * t)));
}

// 意図を選ぶ:距離で重みを変えたくじ引き / picks an intent: a weighted draw that depends on the distance
void AiController::decide(const Fighter &opponent, float distance) {
  float a = profile.aggression;
  float r = rng.unit();
  if (distance > 170.0f) {
    if (r < 0.45f + 0.3f * a) setIntent(Intent::Approach, thinkTime(1.0f, 2.5f));
    else if (r < 0.6f + 0.3f * a) setIntent(Intent::JumpIn, 40);
    else setIntent(Intent::Wait, thinkTime(0.5f, 1.5f));
  } else if (distance > kAttackRange) {
    if (r < 0.35f + 0.3f * a) setIntent(Intent::Approach, thinkTime(0.6f, 1.5f));
    else if (r < 0.5f + 0.3f * a) setIntent(Intent::JumpIn, 40);
    else if (r < 0.8f) setIntent(Intent::Retreat, thinkTime(0.5f, 1.2f));
    else setIntent(Intent::Wait, thinkTime(0.4f, 1.0f));
  } else {
    // 近い:攻めるか、下がるか / close: attack or back off
    if (r < 0.45f + 0.45f * a) {
      float m = rng.unit();
      // 相手がしゃがんでいれば足払いを多めに / sweep more often against a crouching opponent
      bool low = opponent.controls.down || opponent.state == FighterState::Crouch;
      planned = m < (low ? 0.2f : 0.4f) ? MoveId::Punch
                : m < (low ? 0.35f : 0.65f) ? MoveId::Kick
                : m < (low ? 0.8f : 0.85f) ? MoveId::Sweep
                                           : MoveId::CrouchPunch;
      setIntent(Intent::Attack, moveData(planned).total() + thinkTime(0.2f, 0.7f));
    } else if (r < 0.9f) setIntent(Intent::Retreat, thinkTime(0.5f, 1.2f));
    else setIntent(Intent::Wait, thinkTime(0.3f, 0.8f));
  }
}

Three distance bands: far (over 170 px), middle (62 to 170 px) and in range (under 62 px, where punches and kicks reach).
aggression (the a above) moves weight from waiting and retreating to approaching and attacking.
With the three profiles' aggression of 0.35, 0.55 and 0.70, the weights work out as follows (each row adds up to 100 %):

Band Intent Easy Normal Hard
far approach / jump in / wait 55.5 / 15 / 29.5 % 61.5 / 15 / 23.5 % 66 / 15 / 19 %
middle approach / jump in / retreat / wait 45.5 / 15 / 19.5 / 20 % 51.5 / 15 / 13.5 / 20 % 56 / 15 / 9 / 20 %
in range attack / retreat / wait 60.75 / 29.25 / 10 % 69.75 / 20.25 / 10 % 76.5 / 13.5 / 10 %

The jump-in chance is always 15 % because both of its bounds move with aggression by the same amount.
In range, the planned move is a second draw: punch 40 %, kick 25 %, sweep 20 %, crouching punch 15 %, but against a crouching opponent (or one holding down) sweeps rise to 45 %, a low answer to a low stance.
An attack intent lasts the move's total frames plus a short pause (4 to 14 frames on Normal), so the CPU doesn't decide again while its own move is still in recovery.
The timers are random too: thinkTime(lo, hi) draws a duration between lo and hi times the profile's thinkFrames (on Normal, 20 to 50 frames of approaching from far away, 10 to 24 of retreating, and so on), and that randomness is what keeps the CPU from looking like a metronome.
The factors were tuned on Normal, whose thinkFrames is 20; "Difficulty is just numbers" below shows what the other difficulties make of them.

That's "state-driven decisions" in the classic game-AI sense: a handful of states, a timer, and weighted dice.
It sounds primitive next to search trees or learning, but most shipped fighting-game CPUs are exactly this, plus hand-tuning.

Perceive, punish, link, decide

Here's the first half of think, which runs once per step for each CPU:

Controls AiController::think(const Fighter &self, const Fighter &opponent) {
  Controls c;
  float dx = opponent.position.x - self.position.x;
  float distance = std::abs(dx);
  auto hold = [&](bool towards) {
    if ((dx > 0.0f) == towards) c.right = true;
    else c.left = true;
  };

  // 1. 見る(遅れて反応する):相手が技を出し始めたら、反応の時間の後にガードするか決める
  // 1. Perceive (with a delay): when the opponent starts a move, decide after the reaction time whether to guard
  MovePhase op = opponent.phase();
  if (op == MovePhase::Startup && !sawAttack) {
    sawAttack = true;
    reaction = profile.reactionFrames;
  }
  if (op == MovePhase::None) sawAttack = false;
  if (reaction >= 0 && --reaction < 0 && opponent.move) {
    // 飛び込み(空中の技)は対空を狙うこともある / a jump-in may be answered with an anti-air
    bool air = opponent.move->air;
    if (air && distance < 120.0f && rng.chance(profile.antiAirChance)) setIntent(Intent::AntiAir, 20);
    else if (distance < 170.0f && rng.chance(profile.blockChance)) {
      guardLow = opponent.move->height == AttackHeight::Low;
      setIntent(Intent::Guard, opponent.move->startup + opponent.move->active + 6);
    }
  }
  // 2. 反撃:相手が近くで硬直していれば(一度だけ判断) / 2. Punish: the opponent is recovering nearby (decided once)
  if (op != MovePhase::Recovery) punished = false;
  if (op == MovePhase::Recovery && !punished && self.actionable() && distance < kAttackRange + 4.0f) {
    punished = true;
    if (rng.chance(profile.punishChance)) {
      planned = MoveId::Punch;
      setIntent(Intent::Attack, moveData(planned).total() + 4);
    }
  }
  // 3. つなぎ(強いときだけ):自分の突きが当たったら、硬直の終わりにもう一度押す(入力バッファが拾う)
  // 3. Links (hard only): when our punch hit, press again near the end of the recovery (the input buffer catches it)
  if (profile.combos && self.state == FighterState::Attack && self.moveHit && self.moveId == MoveId::Punch &&
      opponent.state == FighterState::Hitstun && self.stateTime == self.move->total() - 3)
    c.punch = true;

  // 4. 決める:意図の時間が切れて、自由に動けるとき / 4. Decide: when the intent's time is up and the fighter is free
  if (--timer <= 0 && self.actionable()) decide(opponent, distance);

1. Perceive, with a delay. When the opponent's move enters its startup, the CPU notes it (sawAttack, so one move is only seen once) and starts a countdown of reactionFrames.
Only when the countdown ends does it decide, with a probability, to guard (blockChance, low or high guard from the move's height) or, against a jump kick within 120 px, to go for an anti-air (antiAirChance).
This delay is the most important number in the whole AI.
Without it, the CPU would know the opponent's move on the very step it starts and block everything it chooses to block: unbeatable, and no fun.
People need about 12 to 15 frames (200 to 250 ms) to react to something they see, and the profiles give the CPU 24, 14 or 8 frames.

It's worth counting exactly what a reaction of R frames can block, because the result is a little surprising.
Take the opponent's kick (startup 8, active 9–12, recovery 13–28), pressed on step 0, its frame 1.
think runs before the fighters update, so the CPU first sees the startup on step 1, counts R steps down, and holds back from step R+1 on; the fighters' update in that step processes the kick's frame R+2.

A frame timeline from 1 to 44. The opponent&

On Hard the guard starts on frame 10, the kick's second active frame; on Normal on frame 16 and on Easy on frame 26, both long after the kick is over.
So the reaction guard can block a move only if its first active frame comes at or after frame R+2, which means a startup of at least R+1 frames, 9 even on Hard.
No ground move in our frame data is that slow (punch 4, crouching punch 4, sweep 7, kick 8).
(This count assumes no hit stop in between. think runs before the hitstop > 0 check in FightScene::update, so the CPU's countdowns keep running while the fighters are frozen: a reaction that starts during a freeze can be mostly used up by the time the fight moves again, which helps the CPU against follow-ups after a hit.)
A kick that's in range from its first active frame is simply too fast to react to, for the CPU on any difficulty and for most humans too.
That's not a flaw; it's how real fighting games work, where "reactable" moves (overheads, slow lunges, jumps) are the exception.
The guard intent still does a lot:

  • Jump kicks stay active until landing, often more than 15 frames, so the CPU can see one coming and block it standing (the CPU vs CPU log shows HAYATE J.KICK -> JIN blocked).
  • The guard lasts the seen move's startup + active + 6 frames (17 steps of holding back for the kick), which covers the next move of a string: the second punch of a punch → punch, or a kick right after a blocked punch.
  • The other blocks in the log happen while the CPU is holding back anyway, in a Retreat or a guard left over from an earlier move: holding back while the opponent attacks nearby is a guard, thanks to chapter 31's proximity guard.

The CPU, like a person, blocks what it expects, and reacts to what's slow.

2. Punish. When the opponent is in recovery within reach and the CPU can act, it punches with punishChance.
punished makes that a single roll per recovery, otherwise it would re-roll every step and punish almost certainly.
A blocked kick is −6 and a blocked sweep −10 (chapter 31's table), and the punch's 4-frame startup fits into both.
3. Links. On Hard, after its punch hit, the CPU presses punch again 3 frames before its recovery ends; chapter 31's input buffer keeps the press and fires the second punch on the first possible frame, and since a punch is +7 on hit, it combos ("2 HITS").
The CPU doesn't need frame-perfect timing code because the buffer is the timing code, for it as for a human.
4. Decide. Only when the intent's timer has run out and the fighter is free (actionable(): idle, walking or crouching).

Executing an intent

The second half turns the intent into buttons:

  // 5. 実行 / 5. Execute
  switch (intent) {
  case Intent::Wait:
    break;
  case Intent::Approach:
    hold(true);
    if (distance < kAttackRange) setIntent(Intent::Wait, 2); // 着いた:すぐ次を決める / arrived: decide again soon
    break;
  case Intent::Retreat:
    hold(false);
    break;
  case Intent::Attack:
    if (!pressed && self.actionable()) {
      pressed = true;
      c.down = planned == MoveId::Sweep || planned == MoveId::CrouchPunch;
      (planned == MoveId::Kick || planned == MoveId::Sweep ? c.kick : c.punch) = true;
    }
    break;
  case Intent::JumpIn:
    if (!pressed && self.actionable()) {
      pressed = true;
      c.up = true;
      hold(true);
    }
    // 落ち始めて近ければ蹴る / kick once falling and close
    if (self.state == FighterState::Air && self.velocity.y > -120.0f && distance < 90.0f) c.kick = true;
    if (self.actionable() && pressed && timer < 30) setIntent(Intent::Wait, 4);
    break;
  case Intent::Guard:
    hold(false);
    c.down = guardLow;
    break;
  case Intent::AntiAir:
    if (!pressed && self.actionable() && distance < 85.0f) {
      pressed = true;
      c.kick = true;
    }
    break;
  }
  return c;
}

hold(true) holds toward the opponent and hold(false) away, worked out from the positions like the human's guard in chapter 31.
pressed makes sure an intent presses its button once: Controls::punch means "pressed this step", so without the flag the CPU would press again on every step of the intent and buffer a second move.
The jump-in is the one intent with a plan: press up and forward once, then kick near the top of the jump or on the way down (velocity.y > -120, with y pointing down) once within 90 px of the opponent.

With F1 the debug overlay now also prints each CPU's current intent under its state:

    // CPUなら今の意図も / for the CPU also its current intent
    if (ai[i] && n > 0 && static_cast<size_t>(n) < sizeof label)
      std::snprintf(label + n, sizeof label - static_cast<size_t>(n), "\nAI %s", ai[i]->intentName());

CPU vs CPU with the F1 overlay: Jin in blue kicks, labeled ATTACK KICK 11 of 28, ACTIVE, AI ANTI-AIR; Hayate in white is in HITSTUN 2 with HP 60 and AI GUARD. Hurt boxes in blue, push boxes in green; the timer shows 51

Hayate's intent says GUARD, yet he's in hit stun: an intent is what the CPU is trying to do, not what its fighter can do, and holding back only blocks while the fighter is free to guard.

Difficulty is just numbers

The three difficulties are not three AIs.
They are three rows of one table:

//                           考える 反応  ガード 対空  反撃  攻め  つなぐ / think react guard anti-air punish aggro combo
constexpr AiProfile kProfiles[] = {
  {34, 24, 0.20f, 0.10f, 0.15f, 0.35f, false}, // Easy
  {20, 14, 0.50f, 0.35f, 0.45f, 0.55f, false}, // Normal
  {10, 8, 0.80f, 0.70f, 0.80f, 0.70f, true},   // Hard
};

Easy Normal Hard
intent durations (thinkFrames) × 1.7 (34) × 1 (20) × 0.5 (10)
reaction 24 frames (400 ms) 14 frames (233 ms) 8 frames (133 ms)
guard a seen move 20 % 50 % 80 %
anti-air a jump kick 10 % 35 % 70 %
punish recovery 15 % 45 % 80 %
aggression 0.35 0.55 0.70
links punch → punch no no yes

The behavior code is identical for all three; making the CPU easier or harder is tuning, not programming, and a designer can do it without reading think.
Normal's 14 frames sit right at human speed; Easy is slower than a person, so it feels beatable, and Hard is faster than a person, which is the usual compromise: a CPU that's both perfect and human-speed is hard to write, so higher difficulties buy strength with superhuman reactions.

thinkFrames sets the tempo.
Every random duration in decide is a range of multiples of it, so Easy holds an intent 1.7 times as long as Normal (approaching from far away for 34 to 85 frames instead of 20 to 50), and Hard changes its mind twice as often (10 to 25).
On Normal the factors give round ranges (20 to 50, 12 to 30, 10 to 24 and so on), the ones the AI was tuned with.
The timers that come from the game rather than from thinking stay fixed: a jump-in lasts 40 frames, a guard the seen move's startup + active + 6, an anti-air 20.

The CPU's difficulty is chosen on the title and kept in Game::difficulty, so it survives going back to the title.

The same match every time

Each AiController has its own Rng, and the fight scene seeds them with constants:

  // CPUの担当:1P対CPUなら2P、CPU対CPUなら両方。種は固定(同じ入力なら同じ試合) / who the computer plays: 2P in
  // 1P vs CPU, both in CPU vs CPU. Fixed seeds (the same input gives the same match)
  if (settings.mode == Mode::VsCpu || settings.mode == Mode::CpuVsCpu) ai[1].emplace(settings.difficulty, 3202u);
  if (settings.mode == Mode::CpuVsCpu) ai[0].emplace(settings.difficulty, 3201u);

Combine that with chapter 26's two promises: the game logic runs in fixed steps of 1/60 s no matter how fast the screen draws, and Rng maps std::mt19937's bits to ranges with its own code, so the same seed gives the same numbers with GCC, Clang and MSVC.
Then the CPU's decisions depend only on the seed and on what happened in the fight, and what happened depends only on the human's inputs.
The same human input gives the same match, step for step, and a rematch from the win screen (a fresh FightScene, fresh AiControllers with the same seeds) replays the CPU's decisions exactly as long as the human repeats theirs.
The scripted clips of this chapter rely on it, and so did debugging: "CPU vs CPU, Normal, crashes at step 1668" is a reproducible bug report.
The petals' Rng{32} lives in the shared Stage and isn't reset, but no game logic reads the petals, so they can drift differently without changing a single hit.
The usual caveat from chapter 26 still applies: bit-identical results across different compilers also need the game state's floating-point math to be computed identically, which is a topic of its own; on one build, it's exact.

Note that the CPU always plays at the same seed, so a human can learn a "pattern" that beats it.
That was literally true of many arcade games, and it's the trade-off of reproducibility; seeding from the clock would fix it for real players at the cost of every property above (challenge 3 asks you to keep both).

What CPU vs CPU found

Chapter 31's notes already mention it: in a trade, both fighters hit each other on the same step.
The first takeHit clears the victim's move, and the victim is also the second attacker, so the second contact read a null pointer.
Two humans almost never trade on the exact same step; two CPUs on Normal did it within a minute.
The fix, already in chapter 31's code, stores what each contact needs before anything is mutated:

  // 技はここで覚える:相打ちだと、一つ目のtakeHitが二人目の技(move)を消してしまう
  // The move is remembered here: in a trade the first takeHit clears the second attacker's move
  struct Contact {
    int attacker;
    const MoveData *move;
    Rect where;
    bool blocked;
  };
  Contact contacts[2];

"Collect, then apply" is chapter 31's rule for simultaneous hits, and here's its second reason: once you start applying, the data you collected must not depend on what you've already changed.

32.5 Rounds and the match

The rules

The match rules are four constants:

// 試合の設定(タイトルで選ぶ) / the match settings (chosen on the title screen)
#pragma once

#include "ai.hh"

enum class Mode {
  VsCpu,      // 1P 対 CPU / 1P vs the computer
  TwoPlayers, // 二人で対戦 / two players
  CpuVsCpu,   // CPU 対 CPU(見るだけ) / computer vs computer (watch)
  Training,   // 練習:時間なし、KOで仕切り直し / training: no timer, a KO restarts
};

struct MatchSettings {
  Mode mode = Mode::VsCpu;
  Difficulty difficulty = Difficulty::Normal;
};

constexpr int kWinsNeeded = 2;      // 3本勝負:先に2本 / best of three: first to two
constexpr int kMaxRounds = 5;       // 引き分けが続いたら5本目で終わり / draws end the match after round 5
constexpr int kRoundSeconds = 60;

Best of three means first to two round wins; a draw gives nobody a round, so the match could go on, and kMaxRounds stops it after the fifth round with whatever the score is.
The timer is counted in update steps, not seconds:

  RoundPhase phase = RoundPhase::Intro;
  int phaseTime = 0;
  int round = 1;
  int wins[2] = {0, 0};
  int timer = kRoundSeconds * 60; // ラウンドの残り(ステップ) / time left in the round (steps)
  int roundWinner = -1;           // -1 = 引き分け / -1 = draw
  bool timeOver = false;
  int koTime = 0;                 // 練習モードのKOからの時間 / training mode: time since a KO
  bool leaving = false;           // 勝利画面への切り替えを頼んだ / the switch to the win screen was requested

kRoundSeconds * 60 = 3600 steps.
Because it's steps, a round lasts exactly 60 seconds of game time on every machine, and it stops during hit stop (the round logic isn't reached while hitstop > 0), as it should: a 40-frame KO freeze shouldn't eat the clock.

The round state machine

A round has three phases, the same enum class Phase pattern as Invaders' play scene in chapter 29:

// ラウンドの流れ(ステップごと)。ヒットストップ中は進まない / the round flow (per step); frozen during hit stop
void FightScene::updateRound() {
  ++phaseTime;
  if (settings.mode == Mode::Training) {
    if (koTime > 0 && ++koTime > 180) startRound(); // 練習:3秒後に仕切り直し / training: restart after 3 s
    return;
  }
  bool ko[2] = {fighters[0].health == 0, fighters[1].health == 0};
  switch (phase) {
  case RoundPhase::Intro:
    if (phaseTime >= kIntroFrames) {
      phase = RoundPhase::Fight;
      phaseTime = 0;
    }
    break;
  case RoundPhase::Fight:
    if (ko[0] || ko[1]) finishRound(ko[0] && ko[1] ? -1 : ko[0] ? 1 : 0, false);
    else if (--timer <= 0) {
      // タイムアップ:体力の多い方の勝ち / time over: the one with more health wins
      int h0 = fighters[0].health, h1 = fighters[1].health;
      finishRound(h0 == h1 ? -1 : h0 > h1 ? 0 : 1, true);
    }
    break;
  case RoundPhase::Finish:
    if (phaseTime == kWinPoseAt && roundWinner >= 0) fighters[roundWinner].win();
    if (leaving) phaseTime = kFinishFrames; // 暗いまま待つ / stay dark while the switch happens
    else if (phaseTime >= kFinishFrames) {
      bool over = wins[0] >= kWinsNeeded || wins[1] >= kWinsNeeded || round >= kMaxRounds;
      if (over) {
        int winner = wins[0] == wins[1] ? -1 : wins[0] > wins[1] ? 0 : 1;
        // 置き換えは予約だけ(このシーンはこのupdateの後で消える) / the replacement is only queued (this scene goes
        // away after this update)
        scenes().replace(std::make_unique<ResultScene>(g, settings, winner, wins), {.duration = 0.6f});
        leaving = true;
      } else {
        ++round;
        startRound();
      }
    }
    break;
  }
}

  • Intro, 100 frames: "ROUND 1" (or "FINAL ROUND") for 60, then "FIGHT!" for 40; nobody can move.
  • Fight: the timer runs. A KO ends the round (both at 0 on the same step, from a trade, is a double KO and a draw). If the timer reaches 0, the fighter with more health wins, equal health is a draw.
  • Finish, 230 frames: "K.O.", "TIME UP" or "DOUBLE K.O." for 70, then the winner's banner. Then either the next round starts or the match is over.

finishRound records the result and logs it:

void FightScene::finishRound(int winner, bool byTime) {
  phase = RoundPhase::Finish;
  phaseTime = 0;
  roundWinner = winner;
  timeOver = byTime;
  if (winner >= 0) ++wins[winner];
  printf("round %d: %s%s (wins %d-%d)\n", round, winner < 0 ? "draw" : fighters[winner].name.c_str(),
         byTime ? " by time" : "", wins[0], wins[1]);
}

At frame 70 of Finish the winner is asked to take the victory pose.
"Asked", because the winner might still be in the air or in the recovery of the final kick; Fighter keeps the request and starts the Win state only once it's on the ground and free:

  // 勝ちポーズは、自由に動ける状態で地上にいるときに / the victory pose starts once free and on the ground
  if (wantsWin && onGround && (actionable() || state == FighterState::Land)) {
    velocity.x = 0.0f;
    setState(FighterState::Win);
    animator.play(winClip, true);
  }

K.O. in red over the stage at the left limit: Hayate&

HAYATE WINS in gold with the Japanese line below it; Hayate in his victory pose with one fist up, Jin lying by the lantern with stars over his head

Two kinds of fade

Between rounds the scene stays the same: startRound resets the fighters, the timer, the effects and the CPUs' intents (but not their Rngs, so round 2 isn't a copy of round 1), and the fight scene draws its own fade, black over the last 30 frames of Finish and back over the first 20 of Intro:

void FightScene::drawUi(float /*alpha*/) {
  SpriteBatch &b = g.batch;
  b.begin(g.screen.matrix());
  // ラウンドの間の暗転(自前のフェード:シーンは変わらない) / the fade between rounds (our own: the scene stays)
  float fade = 0.0f;
  if (phase == RoundPhase::Finish && phaseTime > kFinishFrames - 30)
    fade = static_cast<float>(phaseTime - (kFinishFrames - 30)) / 30.0f;
  if (phase == RoundPhase::Intro && phaseTime < 20) fade = 1.0f - static_cast<float>(phaseTime) / 20.0f;
  if (fade > 0.0f) b.drawRect({0, 0, 1280, 720}, {0.0f, 0.0f, 0.0f, std::clamp(fade, 0.0f, 1.0f)});

At the end of the match it's a real scene change, scenes().replace(ResultScene, 0.6 s), with chapter 26's fade.
Replacing a scene from its own update is the situation chapter 26 queued changes for: the request is only stored, and leaving makes sure the round logic doesn't request it again on the next step and keeps the screen black until the fade takes over.
Chapter 29 used the same flag for its wave reload.

The HUD

The timer sits in a box between the health bars, turning red in the last 10 seconds:

  // 時間(真ん中)。練習は「練習」 / the timer (center); training shows "練習"
  b.drawRect({298, 4, 44, 30}, kOutline, 10.0f);
  TextStyle centre = {.color = kGold, .scale = 2.0f, .align = TextAlign::Centre, .layer = 11.0f};
  if (settings.mode == Mode::Training) {
    centre.scale = 1.0f;
    g.pixel.draw(b, "練習", {320, 12}, centre);
  } else {
    int seconds = (timer + 59) / 60;
    centre.color = seconds <= 10 ? kRed : kGold;
    g.pixel.draw(b, std::to_string(seconds), {320, 6}, centre);
  }

(timer + 59) / 60 rounds up, so the display shows 60 for the first second and 1 for the last one, and reaches 0 exactly when the round ends.
Next to the names, two small squares fill with gold for each round won, and CPU slots get a (CPU) tag.
The round banners use the same outlined drawBigText as chapter 31's K.O., now in hud.cc so the title and the win screen can use it too:

  if (phase == RoundPhase::Intro) {
    bool final = round == kMaxRounds || (wins[0] == kWinsNeeded - 1 && wins[1] == kWinsNeeded - 1);
    if (phaseTime < 60) {
      drawBigText(b, g.pixel, final ? "FINAL ROUND" : "ROUND " + std::to_string(round), {320, 130}, kText, 4.0f);
      g.pixel.draw(b, final ? "最終ラウンド" : "第" + std::to_string(round) + "ラウンド", {320, 162}, sub);
    } else {
      drawBigText(b, g.pixel, "FIGHT!", {320, 130}, kGold, 5.0f);
    }

final is true in the fifth round, or when both have one win, since the next round decides the match either way.

32.6 Title, pause and the win screen

The game now has four scenes.
Their declarations live together in scenes.hh, so the title can create a fight, the fight a result, and the result a title again without include cycles.

The scene flow: TitleScene to FightScene with Space or F, replace 0.8 s; inside FightScene the round phases Intro, 100 frames, Fight with the 60 s timer, KO or time up, Finish, and back to Intro for the next round after 230 frames with a fade of 30 plus 20; FightScene pushes the PauseScene overlay with Esc or P, which pops on Resume or replaceAlls to the title; Finish replaces the scene with ResultScene after 2 wins or round 5, 0.6 s; ResultScene starts a rematch FightScene or replaces itself with the title; Esc on the title pops the last scene and quits

The title

The title screen: FIGHTER in big gold pixel letters, the Japanese subtitle below it, and a menu panel with English and Japanese columns: 1P VS CPU selected, 2P VS, CPU VS CPU, TRAINING and the difficulty NORMAL; the two fighters idle on both sides in front of the stage

The menu is a table of modes plus one difficulty row:

constexpr Item kItems[] = {
  {"1P VS CPU", "1P 対 CPU", Mode::VsCpu},
  {"2P VS", "2人で対戦", Mode::TwoPlayers},
  {"CPU VS CPU", "CPU 対 CPU", Mode::CpuVsCpu},
  {"TRAINING", "練習", Mode::Training},
};
constexpr int kItemCount = 5; // 4つの遊び方 + 難易度 / four modes + the difficulty
const char *const kDifficultyJa[] = {"易しい", "普通", "難しい"};

void TitleScene::update(float dt) {
  time += dt;
  g.stage->update(dt);
  Input &in = g.input;
  if (in.pressed(GLFW_KEY_ESCAPE)) {
    scenes().pop(); // 最後のシーン:終了 / the last scene: quit
    return;
  }
  if (menuUp(in)) selected = (selected + kItemCount - 1) % kItemCount;
  if (menuDown(in)) selected = (selected + 1) % kItemCount;
  int d = static_cast<int>(g.difficulty);
  if (menuLeft(in)) g.difficulty = static_cast<Difficulty>((d + 2) % 3);
  if (menuRight(in)) g.difficulty = static_cast<Difficulty>((d + 1) % 3);
  if (menuConfirm(in) && selected < 4)
    scenes().replace(std::make_unique<FightScene>(g, MatchSettings{kItems[selected].mode, g.difficulty}),
                     {.duration = 0.8f});
}

Behind the menu, the stage drifts by itself, the parallax demo for free: the camera's center swings around the stage middle with a sine, ±150 px, which stays inside the camera limits (512 ± 150 = 362 to 662):

void TitleScene::draw(float /*alpha*/) {
  SpriteBatch &b = g.batch;
  // カメラはゆっくり左右に:視差の層がそれぞれの速さで動く / the camera drifts left and right: each parallax layer
  // moves at its own speed
  Camera2D view = Camera2D::screen(kViewSize);
  view.centre.x = std::round(kStageWidth * 0.5f + 150.0f * std::sin(time * 0.3f));
  b.begin(view.matrix(), SpriteSort::Layer);
  g.stage->drawBack(b, view);

Pause

The pause menu is an overlay scene (chapter 26: isOverlay() keeps the fight drawn below it, and only the top scene updates):

void PauseScene::update(float dt) {
  time += dt;
  Input &in = g.input;
  if (in.pressed(GLFW_KEY_ESCAPE) || in.pressed(GLFW_KEY_P)) {
    scenes().pop();
    return;
  }
  if (menuUp(in) || menuDown(in)) selected = 1 - selected;
  if (menuConfirm(in)) {
    if (selected == 0) scenes().pop();
    else scenes().replaceAll(std::make_unique<TitleScene>(g), {.duration = 0.8f});
  }
}

One detail on the fight's side: when the pause goes on top, the fight copies its current positions into previous, so the frozen picture doesn't interpolate between two different steps forever:

// 一時停止が上に載った:補間で震えないように前の位置 = 今 / the pause went on top: previous = current, so the
// interpolation does not wobble
void FightScene::pause() {
  for (Fighter &f : fighters) f.savePrevious();
}

The pause overlay: the fight darkened behind a framed panel with PAUSED in English and Japanese, Resume highlighted in gold and Back to title; behind it Hayate&

The win screen

ResultScene shows the winner at twice the size in the victory pose, the loser lying further back, and the round score.
Space or F starts a rematch with the same settings; Esc goes back to the title:

void ResultScene::update(float dt) {
  time += dt;
  pose.update(dt);
  g.stage->update(dt);
  Input &in = g.input;
  if (in.pressed(GLFW_KEY_ESCAPE)) scenes().replace(std::make_unique<TitleScene>(g), {.duration = 0.8f});
  else if (menuConfirm(in) && time > 0.5f)
    scenes().replace(std::make_unique<FightScene>(g, settings), {.duration = 0.8f}); // もう一度 / rematch
}

The time > 0.5f guard ignores confirm presses during the first half second, so a punch hammered at the end of the fight doesn't skip the screen.
Drawing the winner at ×2 with SpriteSheet::sprite's scale is fine for pixel art here, because 2 is an integer: every texel becomes a 2 × 2 block of canvas pixels.

The win screen: HAYATE WINS! in gold and the Japanese line, the score 2 - 0 above the names HAYATE and JIN, Hayate at twice the size in his victory pose on the left, Jin lying in the background on the right

The second clip is the end of a CPU vs CPU match: the last exchange, K.O., the victory pose, the fade and the win screen:

main.cc loads the stage once, next to the sprite sheets, and starts on the title instead of the fight:

  std::optional<Stage> stage = Stage::load();
  if (!frameData || !stage) return 1;

  SceneManager scenes;
  scenes.push(std::make_unique<TitleScene>(game));

32.7 Only the glyphs we have

The Japanese strings in this game look a bit unusual if you read Japanese: "パンチ" and "キック" instead of the more natural 突き and 蹴り, "2人で対戦" instead of 二人, "当たり箱" in the help bar for the boxes, and "第Nラウンド" for the round banner.
That's a practical constraint, not a style choice.
The shared fonts from chapter 26 contain ASCII, the kana and 252 kanji picked for typical UI text, and 突 蹴 先 切 闘 二 移 判 aren't among them; Font would draw each missing character as ? and print one warning on stderr.
So the game's strings were written with the characters the atlas has: 第 ラウンド 最終 タイムアップ 勝ち 勝利 引き分け 対戦 練習 難易度 易しい 普通 難しい 一時停止 再開 タイトルへ もう一度 are all in it.
The code comments are another matter, since they never reach the screen, and they use 突き and 蹴り freely.

  const char *help = settings.mode == Mode::TwoPlayers || settings.mode == Mode::Training
                         ? "1P: A D W S + F パンチ・G キック    2P: カーソルキー + K・L    F1 当たり箱    Esc 一時停止 / pause"
                     : settings.mode == Mode::VsCpu
                         ? "1P: A D 前後・W ジャンプ・S しゃがむ・F パンチ・G キック    F1 当たり箱    Esc 一時停止 / pause"
                         : "CPU 対 CPU    F1 当たり箱    Esc 一時停止 / pause";

Rewording works for a handful of menu strings.
It doesn't work for a game with real dialogue, and the RPG in chapter 35 builds its own font atlas: a script scans the dialogue and the strings in the source, and generates a game-local copy of pixel12 with every extra kanji it needs, leaving the shared fonts untouched.

32.8 Running it

From the project root:

cmake --build build -j8
./build/games/fighter/fighter

In Visual Studio, choose fighter as the startup project (build\games\fighter\Debug\fighter.exe); its working directory is already the project root.
The program logs every contact and every round on stdout, which is the quickest way to check a match; the start and the end of a CPU vs CPU match on Normal:

step 145: JIN J.KICK -> HAYATE hit, hp 90, combo 1, hit stop 10
step 253: HAYATE C.PUNCH -> JIN hit, hp 95, combo 1, hit stop 7
step 333: HAYATE C.PUNCH -> JIN blocked, hp 95, combo 0, hit stop 4
...
round 1: HAYATE (wins 1-0)
...
step 3152: HAYATE J.KICK -> JIN blocked, hp 14, combo 0, hit stop 7
step 3180: JIN KICK -> HAYATE blocked, hp 55, combo 0, hit stop 8
step 3208: HAYATE PUNCH -> JIN hit, hp 8, combo 1, hit stop 7
step 3235: HAYATE SWEEP -> JIN KO, hp 0, combo 1, hit stop 40
round 2: HAYATE (wins 2-0)

That whole match has 46 contacts, 10 of them blocked, and it's the same 46 on every run.
Two humans who don't touch the keys get round 1: draw by time after 60 seconds.

32.9 Platform notes

  • Windows (Visual Studio): as in every game chapter, the Japanese strings need /utf-8; without it MSVC reads the sources in the system code page and the menu shows ?. The project's CMake already sets it for MSVC.
  • All: stdout is line-buffered in a terminal but fully buffered when piped into a file or less, so a crashing run may print nothing at all; that's how the trade crash first looked. Debug crashes with a debugger (gdb -batch -ex run -ex bt ./build/games/fighter/fighter on Linux, lldb on FreeBSD, F5 in Visual Studio) rather than by reading the log.
  • All: the menu and fight keys are GLFW key codes named by their position on a US keyboard, as in chapter 26: on AZERTY, "W A S D" are Z Q S D.

32.10 How real games do it

  • Parallax: 2D engines have it built in: Godot's Parallax2D node takes a scroll scale per layer (our factor) and can repeat a layer, and Unity 2D projects usually move each background with a factor of the camera's motion. Many games also add vertical parallax and per-row scrolling ("line scroll"): old hardware changed the scroll register per scanline, so a floor could be drawn in perspective; with shaders, the same effect is a per-row offset in the fragment shader.
  • Fighting-game cameras: besides following the midpoint, many games zoom out when the fighters separate and move up during jumps (challenges 5 and 6). The "screen edge is a wall" rule is nearly universal in 2D fighters.
  • CPU opponents: commercial fighting-game AI is overwhelmingly hand-written state machines with tuned reaction times and probabilities, as here, and many CPUs read the opponent's inputs directly so they can answer on the first frame of a move, which players call "input reading". Some games add learning AIs that imitate a player from recorded matches.
  • Replays and rollback: because a deterministic game is fully described by its inputs, fighting games store replays as input streams, and rollback netcode (GGPO) predicts the remote player's input, simulates ahead, and re-simulates from the last confirmed step when the real input arrives. That needs exactly our properties: fixed steps, seeded randomness, and game state that can be copied and restored cheaply.

32.11 The fighting game in review, and what comes next

Three chapters built a complete 2D fighting game on the engine of Part 5:

  • Chapter 30: the fighters as state machines (idle, walk, jump, crouch), 2D physics with gravity and the ground, large pixel-art sprites at 640 × 360, and two players on one keyboard.
  • Chapter 31: frame data as the authority over animation, hit and hurt boxes generated from the same skeleton as the art, hit stun, block stun, knockback and hit stop, the input buffer, and a 2D scene graph with 2 × 3 affine matrices for body parts and effects.
  • This chapter: a parallax stage (a camera per layer, exact layer widths), a clamped follow camera whose edges are walls, a CPU that plays through the same input path as a human with intents, a decision timer, a reaction delay and difficulty as numbers, deterministic matches, and the round, match and scene flow around it.

On the GPU side, the whole game is sprites in one SpriteBatch, drawn into a PixelCanvas.
Its substance was elsewhere: time measured in frames, data that both the art and the rules come from, and inputs as the only thing that drives the simulation.
That last idea paid off three times in this chapter alone: the CPU is an input device, the clips are scripted inputs, and every match can be replayed.

Next comes the third game of Part 6, a top-down RPG.
Chapter 33 starts with a tilemap: a tileset atlas, a map data format, drawing thousands of tiles with one batch, and moving a character with collision against solid tiles.
Its camera follows the player and stops at the map's edges, which is this chapter's clampCamera again, in two dimensions.

32.12 Summary

  • Parallax: a layer with factor f is drawn at world x =L−round(fL) (L = the view's left edge), so its own camera moves f times as far. f=z0/z for a pinhole camera: 0.05 sky, 0.25 mountains, 0.5 temple, 1 ground, 1.3 foreground; sort layers 0 to 0.3 behind, 12 in front. No vertical parallax (fixed camera height).
  • Layer widths: W=640+f⋅(1024−640)=640+384f (659, 736, 832, 1024, 1139 px), so every layer reaches its own edge exactly when the camera reaches the stage's; generator and code round the same way, no gaps, no repeating. Made by my own script (numpy, Bayer dither, fixed seeds).
  • Petals: 28 rectangles on a 1.15 layer, wrapped on a 760 px band, Rng{32}, visual only.
  • Camera: center = midpoint of the fighters (interpolated when drawing), clamped to [320, 704], rounded to whole pixels. The view minus 8 px is a wall (keepInView), so two standing fighters are at most 586 px apart, and the corner push-back uses the nearer of the stage end and the view edge. Shake: horizontal and clamped.
  • CPU as an invisible player: AiController::think returns a Controls like readControls, through the same input buffer and rules; it reads only visible state.
  • Intents: Wait, Approach, Retreat, Attack, JumpIn, Guard, AntiAir; a new one is drawn when the timer runs out and the fighter is free, weighted by distance (over 170, 62 to 170, under 62 px) and aggression.
  • Reaction: guard or anti-air only reactionFrames after seeing a startup; with think-before-update the guard starts on the move's frame R+2, too late for any ground move in range (all startups are 8 or less), in time for jump kicks and follow-ups. Punish once per recovery; Hard links through the buffer.
  • Difficulty: one table, Easy / Normal / Hard: think 34 / 20 / 10 (every random intent duration is a range of multiples of it), reaction 24 / 14 / 8, guard 0.2 / 0.5 / 0.8, anti-air 0.1 / 0.35 / 0.7, punish 0.15 / 0.45 / 0.8, aggression 0.35 / 0.55 / 0.7, links on Hard.
  • Determinism: fixed seeds 3201 / 3202 + chapter 26's fixed step and portable Rng → the same input gives the same match, and a rematch replays the CPU exactly.
  • Rounds: Intro 100 → Fight (3600-step timer, frozen in hit stop; KO, double KO, time over by health) → Finish 230 (victory pose at 70, own fade) → next round or ResultScene. Best of three, at most five rounds.
  • Scenes: Title (modes, difficulty, drifting stage), Fight, Pause (overlay), Result (rematch or title); declarations in scenes.hh.
  • Font: strings limited to the shared atlas (no 突 蹴 先 切 闘 二 移 判); the RPG makes its own atlas in chapter 35.

32.13 Challenges

  1. ★ Copy stage_mid_1024.png, the same picture drawn 1024 px wide, from extras/ch32-stage-mid-1024/ of the assets ZIP into games/fighter/assets/, and use it instead of stage_mid with factor 1.0 in Stage::load ({"stage_mid_1024", 1.0f, 0.2f, false}). The temple should now slide exactly with the ground, and the whole stage suddenly looks like one flat painting; switch back and watch the depth return. What width would the old 832 px image need to be to stay correct at factor 0.75?
  2. ★ Make rounds 30 s long and the match best of five (kRoundSeconds = 30, kWinsNeeded = 3). Rounds should end by time much more often, the round marks should show three squares per side, and "FINAL ROUND" should appear when both fighters have two wins. Check what kMaxRounds = 5 now means for a match with two draws.
  3. ★ Set Easy's reactionFrames to 0 and play against it. Its guards should start on the kick's frame 2 and its jump-kick blocks become reliable: it blocks almost everything it decides to block, at only 20 %. Then think about how to give real players a different CPU each match (a seed from the clock) without losing reproducible CPU vs CPU runs for testing.
  4. ★★ Let the two CPUs of CPU vs CPU play at different difficulties: give MatchSettings a second Difficulty for 1P's CPU and pass it to ai[0] (hard-code Hard at first; a title option can come later). With Hayate on Hard and Jin on Easy (the seeds stay 3201 and 3202), Hayate should win 2-0, and with the two swapped Jin should win 2-0. Then count the blocks in the log: with Hayate on Hard, the Easy Jin blocks 16 times and Hayate only twice. Explain why the weaker CPU blocks more, using where the CPU's blocks come from in 32.4.
  5. ★★ Let the camera rise when a fighter jumps: center y = min(180, the higher fighter's y + 120), clamped so the ground never leaves the screen, and give the layers vertical factors too. You'll need taller layer images, and the same derivation as 32.2 gives their heights; work them out for a camera that may rise 60 px.
  6. ★★ Add zoom: let Camera2D::zoom grow to 1.25 when the fighters are within 150 px. On a PixelCanvas, a non-integer zoom makes some texels 1 canvas pixel wide and others 2, so the art shimmers while it scrolls; then try rendering the world into a 1280 × 720 canvas instead and compare. Which one would you ship?
  7. ★★★ Record and replay: store both sides' Controls for every step of a match in a std::vector, and add a "Replay" title item that plays the last match by feeding them back instead of reading the keyboard or calling think (with the same seeds). The replay should match the original step for step: compare the stdout logs with diff. Then make it fail on purpose by seeding the CPU from the clock, and explain why rollback netcode needs the same properties.

Download the diff

Download the project (ZIP)

ファイル: a/games/fighter/CMakeLists.txt | b/games/fighter/CMakeLists.txt

前新
@@ -2,13 +2,19 @@
2 # The 2D fighting game (chapters 30-32): its own executable linking the engine 2 # The 2D fighting game (chapters 30-32): its own executable linking the engine
3 add_executable(fighter 3 add_executable(fighter
4 src/main.cc 4 src/main.cc
    5 src/ai.cc
5 src/controls.cc 6 src/controls.cc
6 src/effects.cc 7 src/effects.cc
7 src/fighter.cc 8 src/fighter.cc
8 src/fight_scene.cc 9 src/fight_scene.cc
9 src/frame_data.cc 10 src/frame_data.cc
    11 src/hud.cc
10 src/moves.cc 12 src/moves.cc
11 src/scene_graph.cc) 13 src/pause_scene.cc
    14 src/result_scene.cc
    15 src/scene_graph.cc
    16 src/stage.cc
    17 src/title_scene.cc)
12 target_include_directories(fighter PRIVATE src) 18 target_include_directories(fighter PRIVATE src)
13 target_link_libraries(fighter PRIVATE engine) 19 target_link_libraries(fighter PRIVATE engine)
14 enable_warnings(fighter) 20 enable_warnings(fighter)

ファイル: a/games/fighter/README.md | b/games/fighter/README.md

前新
@@ -7,6 +7,14 @@
7 build\games\fighter\Debug\fighter.exe # Windows (or F5 with the "fighter" target) 7 build\games\fighter\Debug\fighter.exe # Windows (or F5 with the "fighter" target)
8 ``` 8 ```
9   9  
    10 ## 遊び方 / Modes(第32章から / from chapter 32)
    11  
    12 タイトルで選ぶ / chosen on the title screen (W S 選ぶ / select, A D 難易度 / difficulty, Space・Enter・F 決定 / start):
    13 1P 対 CPU / 1P vs CPU, 2人で対戦 / 2P vs, CPU 対 CPU / CPU vs CPU (watch), 練習 / training(時間なし / no timer)。
    14 3本勝負(先に2本)、1ラウンド60秒、時間切れは体力の多い方の勝ち。難易度:EASY / NORMAL / HARD(CPUの反応の速さと確率)。
    15 Best of three (first to two rounds), 60 s per round, time over = more health wins. Difficulty: EASY / NORMAL / HARD
    16 (the CPU's reaction time and probabilities). Esc / P 一時停止 / pause.
    17  
10 ## 操作 / Controls(一台のキーボードを二人で / two players on one keyboard) 18 ## 操作 / Controls(一台のキーボードを二人で / two players on one keyboard)
11   19  
12 | | 1P | 2P | 20 | | 1P | 2P |
@@ -26,5 +34,6 @@ build\games\fighter\Debug\fighter.exe # Windows (or F5 with the "fighter" tar
26 ゲームパッド(GLFW 3.3のゲームパッドAPI):1台目が1P、2台目が2P(十字キーか左スティック、A/X パンチ、B/Y キック)。 34 ゲームパッド(GLFW 3.3のゲームパッドAPI):1台目が1P、2台目が2P(十字キーか左スティック、A/X パンチ、B/Y キック)。
27 Gamepads (GLFW 3.3's gamepad API): the first is 1P, the second 2P (d-pad or left stick, A/X punch, B/Y kick). 35 Gamepads (GLFW 3.3's gamepad API): the first is 1P, the second 2P (d-pad or left stick, A/X punch, B/Y kick).
28   36  
29 F1 判定の箱(食らい = 青、攻撃 = 赤、押し合い = 緑、ソケット = 黄)と状態 / boxes (hurt blue, hit red, push green, 37 F1 判定の箱(食らい = 青、攻撃 = 赤、押し合い = 緑、ソケット = 黄)と状態、CPUの意図 / boxes (hurt blue, hit red,
30 sockets yellow) and states, Esc 終了 / quit. 38 push green, sockets yellow), states and the CPU's intent; Esc 一時停止 / pause (タイトルではEscで終了 / Esc quits on the
    39 title screen).

ファイル: a/games/fighter/assets/LICENSE.txt | b/games/fighter/assets/LICENSE.txt

前新
@@ -9,3 +9,11 @@ fighter.boxes コマごとの食らい判定・攻撃判定・ソケット
9 (made from the skeleton) (chapter 31) 9 (made from the skeleton) (chapter 31)
10 effects.png/.atlas 火花・ガードの火花・砂ぼこり・鉢巻の尾・星・影 / hit and guard sparks, dust, headband tails, stars, 10 effects.png/.atlas 火花・ガードの火花・砂ぼこり・鉢巻の尾・星・影 / hit and guard sparks, dust, headband tails, stars,
11 shadow (chapter 31) 11 shadow (chapter 31)
    12 stage_sky.png 舞台の空(夕焼け、視差0.05) / the stage's sunset sky (parallax 0.05) (chapter 32)
    13 stage_far.png 遠くの山(視差0.25) / distant mountains (parallax 0.25) (chapter 32)
    14 stage_mid.png 鳥居・五重塔・桜・寺の塀(視差0.5) / torii, pagoda, cherry trees, temple wall (parallax 0.5)
    15 (chapter 32)
    16 stage_ground.png 石畳(視差1、ファイターが立つ面) / the stone paving the fighters stand on (parallax 1)
    17 (chapter 32)
    18 stage_front.png 手前の灯籠と草(視差1.3、ファイターより前) / foreground lanterns and grass (parallax 1.3, in front of
    19 the fighters) (chapter 32)

ファイル: /dev/null | b/games/fighter/assets/stage_far.png

新しいファイル:100644 / バイナリファイル

ファイル: /dev/null | b/games/fighter/assets/stage_front.png

新しいファイル:100644 / バイナリファイル

ファイル: /dev/null | b/games/fighter/assets/stage_ground.png

新しいファイル:100644 / バイナリファイル

ファイル: /dev/null | b/games/fighter/assets/stage_mid.png

新しいファイル:100644 / バイナリファイル

ファイル: /dev/null | b/games/fighter/assets/stage_sky.png

新しいファイル:100644 / バイナリファイル

ファイル: /dev/null | b/games/fighter/src/ai.cc

前新
@@ -0,0 +1,179 @@
    1 // コンピューターの相手 / the computer opponent
    2 #include "ai.hh"
    3  
    4 #include <cmath>
    5  
    6 namespace {
    7  
    8 // 考える 反応 ガード 対空 反撃 攻め つなぐ / think react guard anti-air punish aggro combo
    9 constexpr AiProfile kProfiles[] = {
    10 {34, 24, 0.20f, 0.10f, 0.15f, 0.35f, false}, // Easy
    11 {20, 14, 0.50f, 0.35f, 0.45f, 0.55f, false}, // Normal
    12 {10, 8, 0.80f, 0.70f, 0.80f, 0.70f, true}, // Hard
    13 };
    14  
    15 constexpr float kAttackRange = 62.0f; // 突き・蹴りが届く距離(足元の間) / where punches and kicks reach (feet to feet)
    16  
    17 } // namespace
    18  
    19 const char *difficultyName(Difficulty d) {
    20 switch (d) {
    21 case Difficulty::Easy: return "EASY";
    22 case Difficulty::Normal: return "NORMAL";
    23 case Difficulty::Hard: return "HARD";
    24 }
    25 return "?";
    26 }
    27  
    28 const AiProfile &aiProfile(Difficulty d) { return kProfiles[static_cast<int>(d)]; }
    29  
    30 AiController::AiController(Difficulty difficulty, std::uint32_t seed) : profile(aiProfile(difficulty)), rng(seed) {}
    31  
    32 void AiController::reset() {
    33 intent = Intent::Wait;
    34 timer = 30;
    35 reaction = -1;
    36 sawAttack = punished = pressed = false;
    37 }
    38  
    39 const char *AiController::intentName() const {
    40 switch (intent) {
    41 case Intent::Wait: return "WAIT";
    42 case Intent::Approach: return "APPROACH";
    43 case Intent::Retreat: return "RETREAT";
    44 case Intent::Attack: return "ATTACK";
    45 case Intent::JumpIn: return "JUMP-IN";
    46 case Intent::Guard: return "GUARD";
    47 case Intent::AntiAir: return "ANTI-AIR";
    48 }
    49 return "?";
    50 }
    51  
    52 void AiController::setIntent(Intent next, int frames) {
    53 intent = next;
    54 timer = frames;
    55 pressed = false;
    56 }
    57  
    58 // 意図の長さ:thinkFramesの lo〜hi 倍からくじで(倍率は普通の20で決めた値。易しいは長く、難しいは短く)
    59 // An intent's duration: a draw from lo to hi times thinkFrames (the factors were tuned on Normal's 20; Easy keeps
    60 // an intent longer, Hard changes its mind sooner)
    61 int AiController::thinkTime(float lo, float hi) {
    62 float t = static_cast<float>(profile.thinkFrames);
    63 return rng.range(static_cast<int>(std::lround(lo * t)), static_cast<int>(std::lround(hi * t)));
    64 }
    65  
    66 // 意図を選ぶ:距離で重みを変えたくじ引き / picks an intent: a weighted draw that depends on the distance
    67 void AiController::decide(const Fighter &opponent, float distance) {
    68 float a = profile.aggression;
    69 float r = rng.unit();
    70 if (distance > 170.0f) {
    71 if (r < 0.45f + 0.3f * a) setIntent(Intent::Approach, thinkTime(1.0f, 2.5f));
    72 else if (r < 0.6f + 0.3f * a) setIntent(Intent::JumpIn, 40);
    73 else setIntent(Intent::Wait, thinkTime(0.5f, 1.5f));
    74 } else if (distance > kAttackRange) {
    75 if (r < 0.35f + 0.3f * a) setIntent(Intent::Approach, thinkTime(0.6f, 1.5f));
    76 else if (r < 0.5f + 0.3f * a) setIntent(Intent::JumpIn, 40);
    77 else if (r < 0.8f) setIntent(Intent::Retreat, thinkTime(0.5f, 1.2f));
    78 else setIntent(Intent::Wait, thinkTime(0.4f, 1.0f));
    79 } else {
    80 // 近い:攻めるか、下がるか / close: attack or back off
    81 if (r < 0.45f + 0.45f * a) {
    82 float m = rng.unit();
    83 // 相手がしゃがんでいれば足払いを多めに / sweep more often against a crouching opponent
    84 bool low = opponent.controls.down || opponent.state == FighterState::Crouch;
    85 planned = m < (low ? 0.2f : 0.4f) ? MoveId::Punch
    86 : m < (low ? 0.35f : 0.65f) ? MoveId::Kick
    87 : m < (low ? 0.8f : 0.85f) ? MoveId::Sweep
    88 : MoveId::CrouchPunch;
    89 setIntent(Intent::Attack, moveData(planned).total() + thinkTime(0.2f, 0.7f));
    90 } else if (r < 0.9f) setIntent(Intent::Retreat, thinkTime(0.5f, 1.2f));
    91 else setIntent(Intent::Wait, thinkTime(0.3f, 0.8f));
    92 }
    93 }
    94  
    95 Controls AiController::think(const Fighter &self, const Fighter &opponent) {
    96 Controls c;
    97 float dx = opponent.position.x - self.position.x;
    98 float distance = std::abs(dx);
    99 auto hold = [&](bool towards) {
    100 if ((dx > 0.0f) == towards) c.right = true;
    101 else c.left = true;
    102 };
    103  
    104 // 1. 見る(遅れて反応する):相手が技を出し始めたら、反応の時間の後にガードするか決める
    105 // 1. Perceive (with a delay): when the opponent starts a move, decide after the reaction time whether to guard
    106 MovePhase op = opponent.phase();
    107 if (op == MovePhase::Startup && !sawAttack) {
    108 sawAttack = true;
    109 reaction = profile.reactionFrames;
    110 }
    111 if (op == MovePhase::None) sawAttack = false;
    112 if (reaction >= 0 && --reaction < 0 && opponent.move) {
    113 // 飛び込み(空中の技)は対空を狙うこともある / a jump-in may be answered with an anti-air
    114 bool air = opponent.move->air;
    115 if (air && distance < 120.0f && rng.chance(profile.antiAirChance)) setIntent(Intent::AntiAir, 20);
    116 else if (distance < 170.0f && rng.chance(profile.blockChance)) {
    117 guardLow = opponent.move->height == AttackHeight::Low;
    118 setIntent(Intent::Guard, opponent.move->startup + opponent.move->active + 6);
    119 }
    120 }
    121 // 2. 反撃:相手が近くで硬直していれば(一度だけ判断) / 2. Punish: the opponent is recovering nearby (decided once)
    122 if (op != MovePhase::Recovery) punished = false;
    123 if (op == MovePhase::Recovery && !punished && self.actionable() && distance < kAttackRange + 4.0f) {
    124 punished = true;
    125 if (rng.chance(profile.punishChance)) {
    126 planned = MoveId::Punch;
    127 setIntent(Intent::Attack, moveData(planned).total() + 4);
    128 }
    129 }
    130 // 3. つなぎ(強いときだけ):自分の突きが当たったら、硬直の終わりにもう一度押す(入力バッファが拾う)
    131 // 3. Links (hard only): when our punch hit, press again near the end of the recovery (the input buffer catches it)
    132 if (profile.combos && self.state == FighterState::Attack && self.moveHit && self.moveId == MoveId::Punch &&
    133 opponent.state == FighterState::Hitstun && self.stateTime == self.move->total() - 3)
    134 c.punch = true;
    135  
    136 // 4. 決める:意図の時間が切れて、自由に動けるとき / 4. Decide: when the intent's time is up and the fighter is free
    137 if (--timer <= 0 && self.actionable()) decide(opponent, distance);
    138  
    139 // 5. 実行 / 5. Execute
    140 switch (intent) {
    141 case Intent::Wait:
    142 break;
    143 case Intent::Approach:
    144 hold(true);
    145 if (distance < kAttackRange) setIntent(Intent::Wait, 2); // 着いた:すぐ次を決める / arrived: decide again soon
    146 break;
    147 case Intent::Retreat:
    148 hold(false);
    149 break;
    150 case Intent::Attack:
    151 if (!pressed && self.actionable()) {
    152 pressed = true;
    153 c.down = planned == MoveId::Sweep || planned == MoveId::CrouchPunch;
    154 (planned == MoveId::Kick || planned == MoveId::Sweep ? c.kick : c.punch) = true;
    155 }
    156 break;
    157 case Intent::JumpIn:
    158 if (!pressed && self.actionable()) {
    159 pressed = true;
    160 c.up = true;
    161 hold(true);
    162 }
    163 // 落ち始めて近ければ蹴る / kick once falling and close
    164 if (self.state == FighterState::Air && self.velocity.y > -120.0f && distance < 90.0f) c.kick = true;
    165 if (self.actionable() && pressed && timer < 30) setIntent(Intent::Wait, 4);
    166 break;
    167 case Intent::Guard:
    168 hold(false);
    169 c.down = guardLow;
    170 break;
    171 case Intent::AntiAir:
    172 if (!pressed && self.actionable() && distance < 85.0f) {
    173 pressed = true;
    174 c.kick = true;
    175 }
    176 break;
    177 }
    178 return c;
    179 }

ファイル: /dev/null | b/games/fighter/src/ai.hh

前新
@@ -0,0 +1,55 @@
    1 // コンピューターの相手:人と同じControlsを作る「見えないプレイヤー」。状態(意図)と決める間隔(タイマー)で動き、
    2 // 反応の遅れと確率で強さが変わる
    3 // The computer opponent: an invisible player that produces the same Controls a human does. It runs on states
    4 // (intents) and a decision timer; reaction delays and probabilities set the difficulty
    5 #pragma once
    6  
    7 #include "controls.hh"
    8 #include "fighter.hh"
    9  
    10 #include "engine/rng.hh"
    11  
    12 #include <cstdint>
    13  
    14 enum class Difficulty { Easy, Normal, Hard };
    15 const char *difficultyName(Difficulty d);
    16  
    17 // 強さの数値。時間はフレーム / the difficulty numbers; times in frames
    18 struct AiProfile {
    19 int thinkFrames; // 意図を続ける長さの基準(普通 = 20) / the base for how long an intent lasts (Normal = 20)
    20 int reactionFrames; // 相手の技を見てから反応するまで(人なら約12〜15) / from seeing a move to reacting (a human
    21 // needs about 12-15)
    22 float blockChance; // 見えた技をガードする確率 / chance to guard a move it saw
    23 float antiAirChance; // 飛び込みを蹴りで落とす確率 / chance to kick a jump-in out of the air
    24 float punishChance; // 相手の硬直に反撃する確率 / chance to punish recovery
    25 float aggression; // 近づいて攻める割合 / how often it closes in and attacks
    26 bool combos; // 突き → 突きをつなぐ / links punch → punch
    27 };
    28 const AiProfile &aiProfile(Difficulty d);
    29  
    30 class AiController {
    31 public:
    32 AiController(Difficulty difficulty, std::uint32_t seed);
    33 // 1ステップ分の入力を作る(ファイターの公開されている状態だけを見る:ずるはしない)
    34 // Makes one step of input (looking only at the fighters' public state: no cheating with hidden data)
    35 Controls think(const Fighter &self, const Fighter &opponent);
    36 void reset();
    37 const char *intentName() const;
    38  
    39 private:
    40 enum class Intent { Wait, Approach, Retreat, Attack, JumpIn, Guard, AntiAir };
    41 void decide(const Fighter &opponent, float distance);
    42 void setIntent(Intent next, int frames);
    43 int thinkTime(float lo, float hi);
    44  
    45 const AiProfile &profile;
    46 Rng rng;
    47 Intent intent = Intent::Wait;
    48 int timer = 30; // 今の意図の残り / frames left for the current intent
    49 int reaction = -1; // 反応までの残り(-1 = なし) / frames until the reaction (-1 = none)
    50 bool guardLow = false;
    51 bool sawAttack = false; // 相手の今の技をもう見た / already saw the opponent's current move
    52 bool punished = false; // 相手の今の硬直にもう反撃した / already punished the current recovery
    53 bool pressed = false; // この意図でボタンをもう押した / already pressed the button for this intent
    54 MoveId planned = MoveId::Punch;
    55 };

ファイル: a/games/fighter/src/fight_scene.cc | b/games/fighter/src/fight_scene.cc

前新
@@ -1,63 +1,41 @@
1 // 対戦の場面(第31章:技の当たり、ヒットストップ、体力、エフェクト。KOすると練習を仕切り直す) 1 // 対戦の場面(第32章:スクロールする舞台、CPU、ラウンド) / the fight scene (chapter 32: scrolling stage, CPU, rounds)
2 // The fight scene (chapter 31: hits, hit stop, health, effects; a KO restarts the training)    
3 #include "fight_scene.hh" 2 #include "fight_scene.hh"
4   3  
    4 #include "hud.hh"
    5 #include "scenes.hh"
    6  
5 #include "engine/collision.hh" 7 #include "engine/collision.hh"
6   8  
7 #include <algorithm> 9 #include <algorithm>
8 #include <cmath> 10 #include <cmath>
9 #include <cstdio> 11 #include <cstdio>
    12 #include <memory>
10 #include <string> 13 #include <string>
11 #include <string_view>    
12   14  
13 namespace { 15 namespace {
14   16  
15 constexpr float kStageLeft = 16.0f; 17 constexpr float kStageLeft = 12.0f; // 舞台の端の壁 / the walls at the stage ends
16 constexpr float kStageRight = 624.0f; 18 constexpr float kStageRight = kStageWidth - 12.0f;
17 constexpr Vec2 kStart[2] = {{200.0f, kGroundY}, {440.0f, kGroundY}}; 19 constexpr float kViewMargin = 8.0f; // 画面の端からの余白(画面の端も壁) / margin to the view edges
18   20 // (the view edges are walls too)
19 constexpr Vec4 kBeam = hexColor(0x3b2a2eff), kBeamLight = hexColor(0x5a4040ff); 21 constexpr Vec2 kStart[2] = {{kStageWidth * 0.5f - 110.0f, kGroundY}, {kStageWidth * 0.5f + 110.0f, kGroundY}};
20 constexpr Vec4 kPlaster = hexColor(0xdccdaeff), kPlasterShade = hexColor(0xc4b393ff); 22 constexpr int kIntroFrames = 100;
21 constexpr Vec4 kShoji = hexColor(0xf4ecd8ff), kLattice = hexColor(0x8a6a50ff); 23 constexpr int kFinishFrames = 230;
22 constexpr Vec4 kWainscot = hexColor(0x6e4a36ff), kWainscotDark = hexColor(0x553626ff); 24 constexpr int kWinPoseAt = 70;
23 constexpr Vec4 kPlankA = hexColor(0xb07c50ff), kPlankB = hexColor(0xa16f47ff), kPlankLine = hexColor(0x6e4630ff); 25 const char *const kJapaneseNames[2] = {"ハヤテ", "ジン"};
24 constexpr Vec4 kOutline = hexColor(0x1b1726ff);    
25 constexpr Vec4 kText = hexColor(0xfff4d8ff), kGold = hexColor(0xf2c14eff);    
26      
27 void clampToStage(Fighter &f) {    
28 Rect b = f.pushbox();    
29 if (b.left() < kStageLeft) f.position.x += kStageLeft - b.left();    
30 if (b.right() > kStageRight) f.position.x -= b.right() - kStageRight;    
31 }    
32   26  
33 bool atWall(const Fighter &f) { 27 void clampX(Fighter &f, float left, float right) {
34 Rect b = f.pushbox(); 28 Rect b = f.pushbox();
35 return b.left() <= kStageLeft + 0.5f || b.right() >= kStageRight - 0.5f; 29 if (b.left() < left) f.position.x += left - b.left();
    30 if (b.right() > right) f.position.x -= b.right() - right;
36 } 31 }
37   32  
38 // 二つの箱の重なり(火花を出す場所) / the overlap of two boxes (where the spark goes)    
39 Rect intersection(const Rect &a, const Rect &b) { 33 Rect intersection(const Rect &a, const Rect &b) {
40 float l = std::max(a.left(), b.left()), t = std::max(a.top(), b.top()); 34 float l = std::max(a.left(), b.left()), t = std::max(a.top(), b.top());
41 float r = std::min(a.right(), b.right()), bt = std::min(a.bottom(), b.bottom()); 35 float r = std::min(a.right(), b.right()), bt = std::min(a.bottom(), b.bottom());
42 return {l, t, r - l, bt - t}; 36 return {l, t, r - l, bt - t};
43 } 37 }
44   38  
45 // 大きな文字(K.O.など):8方向に輪郭を描いてから本体 / big text (K.O. and so on): an outline in 8 directions, then    
46 // the text itself    
47 void drawBigText(SpriteBatch &b, const Font &font, std::string_view text, Vec2 centre, Vec4 color, float scale) {    
48 Vec2 size = font.measure(text, scale);    
49 Vec2 at = {centre.x, std::round(centre.y - size.y * 0.5f)};    
50 TextStyle s = {.color = kOutline, .scale = scale, .align = TextAlign::Centre, .layer = 11.0f};    
51 for (Vec2 d : {Vec2{-2, -2}, Vec2{0, -2}, Vec2{2, -2}, Vec2{-2, 0}, Vec2{2, 0}, Vec2{-2, 2}, Vec2{0, 2}, Vec2{2, 2},    
52 Vec2{3, 4}, Vec2{0, 4}})    
53 font.draw(b, text, at + d, s);    
54 s.color = color;    
55 s.layer = 11.5f;    
56 font.draw(b, text, at, s);    
57 }    
58      
59 // 体力ゲージ:中央側に寄せて、外側から減る。白い「跡」は少し遅れて追いかける    
60 // A health bar: anchored at the center side, it drains from the outer end. The white "trail" follows a little later    
61 void drawHealthBar(SpriteBatch &b, Rect r, float health, float trail, bool rightSide) { 39 void drawHealthBar(SpriteBatch &b, Rect r, float health, float trail, bool rightSide) {
62 b.drawRect({r.x - 2, r.y - 2, r.w + 4, r.h + 4}, kOutline, 10.0f); 40 b.drawRect({r.x - 2, r.y - 2, r.w + 4, r.h + 4}, kOutline, 10.0f);
63 b.drawRect(r, hexColor(0x4a2434ff), 10.1f); 41 b.drawRect(r, hexColor(0x4a2434ff), 10.1f);
@@ -68,52 +46,73 @@ void drawHealthBar(SpriteBatch &b, Rect r, float health, float trail, bool right
68 b.drawRect(part(trail), hexColor(0xf6f0e8ff), 10.2f); 46 b.drawRect(part(trail), hexColor(0xf6f0e8ff), 10.2f);
69 bool low = health <= kMaxHealth * 0.25f; 47 bool low = health <= kMaxHealth * 0.25f;
70 Rect h = part(health); 48 Rect h = part(health);
71 b.drawRect(h, low ? hexColor(0xe8483cff) : kGold, 10.3f); 49 b.drawRect(h, low ? kRed : kGold, 10.3f);
72 b.drawRect({h.x, h.y, h.w, 2}, low ? hexColor(0xff8a70ff) : hexColor(0xffe48aff), 10.4f); 50 b.drawRect({h.x, h.y, h.w, 2}, low ? hexColor(0xff8a70ff) : hexColor(0xffe48aff), 10.4f);
73 b.drawRect({h.x, h.bottom() - 2, h.w, 2}, low ? hexColor(0xa82a30ff) : hexColor(0xc98a26ff), 10.4f); 51 b.drawRect({h.x, h.bottom() - 2, h.w, 2}, low ? hexColor(0xa82a30ff) : hexColor(0xc98a26ff), 10.4f);
74 } 52 }
75   53  
76 } // namespace 54 } // namespace
77   55  
78 FightScene::FightScene(Game &game) 56 FightScene::FightScene(Game &game, MatchSettings matchSettings)
79 : g(game), camera(Camera2D::screen(kViewSize)), 57 : g(game), settings(matchSettings),
80 fighters{Fighter(*game.fighters[0], *game.effects, *game.frameData, "HAYATE", "tail_hayate", kStart[0], 1.0f), 58 fighters{Fighter(*game.fighters[0], *game.effects, *game.frameData, "HAYATE", "tail_hayate", kStart[0], 1.0f),
81 Fighter(*game.fighters[1], *game.effects, *game.frameData, "JIN", "tail_jin", kStart[1], -1.0f)}, 59 Fighter(*game.fighters[1], *game.effects, *game.frameData, "JIN", "tail_jin", kStart[1], -1.0f)},
82 effects(*game.effects) {} 60 effects(*game.effects) {
    61 // CPUの担当:1P対CPUなら2P、CPU対CPUなら両方。種は固定(同じ入力なら同じ試合) / who the computer plays: 2P in
    62 // 1P vs CPU, both in CPU vs CPU. Fixed seeds (the same input gives the same match)
    63 if (settings.mode == Mode::VsCpu || settings.mode == Mode::CpuVsCpu) ai[1].emplace(settings.difficulty, 3202u);
    64 if (settings.mode == Mode::CpuVsCpu) ai[0].emplace(settings.difficulty, 3201u);
    65 startRound();
    66 }
83   67  
84 void FightScene::resetRound() { 68 void FightScene::startRound() {
85 fighters[0].reset(kStart[0], 1.0f);    
86 fighters[1].reset(kStart[1], -1.0f);    
87 effects.clear();    
88 for (int i = 0; i < 2; ++i) { 69 for (int i = 0; i < 2; ++i) {
    70 fighters[i].reset(kStart[i], i == 0 ? 1.0f : -1.0f);
89 trail[i] = kMaxHealth; 71 trail[i] = kMaxHealth;
90 comboTime[i] = 0; 72 comboTime[i] = 0;
    73 if (ai[i]) ai[i]->reset();
91 } 74 }
    75 effects.clear();
92 hitstop = shake = koTime = 0; 76 hitstop = shake = koTime = 0;
93 victim = -1; 77 victim = -1;
    78 timer = kRoundSeconds * 60;
    79 roundWinner = -1;
    80 timeOver = false;
    81 phase = settings.mode == Mode::Training ? RoundPhase::Fight : RoundPhase::Intro;
    82 phaseTime = 0;
    83 }
    84  
    85 // 一時停止が上に載った:補間で震えないように前の位置 = 今 / the pause went on top: previous = current, so the
    86 // interpolation does not wobble
    87 void FightScene::pause() {
    88 for (Fighter &f : fighters) f.savePrevious();
94 } 89 }
95   90  
96 void FightScene::update(float dt) { 91 void FightScene::update(float dt) {
97 ++steps; 92 ++steps;
98 Input &in = g.input; 93 Input &in = g.input;
99 if (in.pressed(GLFW_KEY_ESCAPE)) { 94 if (in.pressed(GLFW_KEY_ESCAPE) || in.pressed(GLFW_KEY_P)) {
100 scenes().pop(); 95 scenes().push(std::make_unique<PauseScene>(g));
101 return; 96 return;
102 } 97 }
103 if (in.pressed(GLFW_KEY_F1)) g.showBoxes = !g.showBoxes; 98 if (in.pressed(GLFW_KEY_F1)) g.showBoxes = !g.showBoxes;
104   99  
105 Controls controls[2] = {readControls(in, 0, pads[0]), readControls(in, 1, pads[1])}; 100 // 入力:人はキーボードとパッド、CPUはAiController。どちらも同じControlsになる / input: humans from the keyboard and
106 // バッファはヒットストップ中も記録する:止まっている間に押した技が、動き出した瞬間に出る 101 // pads, the CPU from AiController; both become the same Controls
107 // The buffers record during hit stop too: a move pressed while frozen comes out the moment things move again 102 Controls controls[2];
    103 for (int i = 0; i < 2; ++i) {
    104 Controls human = readControls(in, i, pads[i]);
    105 controls[i] = ai[i] ? ai[i]->think(fighters[i], fighters[1 - i]) : human;
    106 if (phase != RoundPhase::Fight) controls[i] = {}; // 始まりと決着の間は動けない / no control before and after
    107 }
108 for (int i = 0; i < 2; ++i) { 108 for (int i = 0; i < 2; ++i) {
109 fighters[i].buffer.record(controls[i]); 109 fighters[i].buffer.record(controls[i]);
110 fighters[i].savePrevious(); // 止まっていても前の位置 = 今(補間で震えない) / even when frozen (no wobble) 110 fighters[i].savePrevious();
111 } 111 }
112 effects.update(dt); 112 effects.update(dt);
    113 g.stage->update(dt);
113 for (int i = 0; i < 2; ++i) comboTime[i] = std::max(0, comboTime[i] - 1); 114 for (int i = 0; i < 2; ++i) comboTime[i] = std::max(0, comboTime[i] - 1);
114 shake = std::max(0, shake - 1); 115 shake = std::max(0, shake - 1);
115 // ヒットストップ:当たった瞬間、数フレーム全部止める(重さが伝わる)。火花のアニメーションだけ進む    
116 // Hit stop: everything freezes for a few frames on contact (it sells the impact). Only the sparks keep animating    
117 if (hitstop > 0) { 116 if (hitstop > 0) {
118 --hitstop; 117 --hitstop;
119 return; 118 return;
@@ -123,30 +122,27 @@ void FightScene::update(float dt) {
123 float startX[2] = {fighters[0].position.x, fighters[1].position.x}; 122 float startX[2] = {fighters[0].position.x, fighters[1].position.x};
124 bool threat[2]; 123 bool threat[2];
125 for (int i = 0; i < 2; ++i) { 124 for (int i = 0; i < 2; ++i) {
126 // 相手が近く(150ピクセル)で技の発生か持続にいる / the opponent is in a move's startup or active frames nearby    
127 const Fighter &o = fighters[1 - i]; 125 const Fighter &o = fighters[1 - i];
128 MovePhase p = o.phase(); 126 MovePhase p = o.phase();
129 threat[i] = (p == MovePhase::Startup || p == MovePhase::Active) && std::abs(o.position.x - startX[i]) < 150.0f; 127 threat[i] = (p == MovePhase::Startup || p == MovePhase::Active) && std::abs(o.position.x - startX[i]) < 150.0f;
130 } 128 }
131 for (int i = 0; i < 2; ++i) fighters[i].update(dt, controls[i], startX[1 - i], threat[i]); 129 for (int i = 0; i < 2; ++i) fighters[i].update(dt, controls[i], startX[1 - i], threat[i]);
132 separate(); 130 separate();
    131 keepInView();
133 resolveHits(); 132 resolveHits();
134 for (Fighter &f : fighters) 133 for (Fighter &f : fighters)
135 if (f.landed) effects.dust(f.position, f.facing); 134 if (f.landed) effects.dust(f.position, f.facing);
136      
137 // 体力の跡:0.5秒待ってから減る / the health trail: waits half a second, then drains    
138 for (int i = 0; i < 2; ++i) { 135 for (int i = 0; i < 2; ++i) {
139 if (trailDelay[i] > 0) --trailDelay[i]; 136 if (trailDelay[i] > 0) --trailDelay[i];
140 else trail[i] = std::max(static_cast<float>(fighters[i].health), trail[i] - 0.6f); 137 else trail[i] = std::max(static_cast<float>(fighters[i].health), trail[i] - 0.6f);
141 } 138 }
142 // 練習:KOから3秒で仕切り直し / training: restart 3 s after a KO 139 updateRound();
143 if (koTime > 0 && ++koTime > 180) resetRound();    
144 } 140 }
145   141  
146 void FightScene::separate() { 142 void FightScene::separate() {
147 Fighter &a = fighters[0], &b = fighters[1]; 143 Fighter &a = fighters[0], &b = fighters[1];
148 clampToStage(a); 144 clampX(a, kStageLeft, kStageRight);
149 clampToStage(b); 145 clampX(b, kStageLeft, kStageRight);
150 Rect ra = a.pushbox(), rb = b.pushbox(); 146 Rect ra = a.pushbox(), rb = b.pushbox();
151 if (!overlaps(ra, rb)) return; 147 if (!overlaps(ra, rb)) return;
152 float overlap = std::min(ra.right(), rb.right()) - std::max(ra.left(), rb.left()); 148 float overlap = std::min(ra.right(), rb.right()) - std::max(ra.left(), rb.left());
@@ -154,17 +150,32 @@ void FightScene::separate() {
154 a.position.x += dir * overlap * 0.5f; 150 a.position.x += dir * overlap * 0.5f;
155 b.position.x -= dir * overlap * 0.5f; 151 b.position.x -= dir * overlap * 0.5f;
156 float ax = a.position.x, bx = b.position.x; 152 float ax = a.position.x, bx = b.position.x;
157 clampToStage(a); 153 clampX(a, kStageLeft, kStageRight);
158 clampToStage(b); 154 clampX(b, kStageLeft, kStageRight);
159 float da = a.position.x - ax, db = b.position.x - bx; 155 float da = a.position.x - ax, db = b.position.x - bx;
160 b.position.x += da; 156 b.position.x += da;
161 a.position.x += db; 157 a.position.x += db;
162 } 158 }
163   159  
164 // 当たり判定:攻撃側の攻撃判定(持続フレーム)と相手の食らい判定が重なったら当たり。 160 // 画面の端も壁:カメラは二人の真ん中を追い、舞台の中に収まる。二人ともその画面の中にいなければならない
165 // 先に二人分を調べてから当てる:同時に当たったら相打ち 161 // The view edges are walls too: the camera follows the midpoint, clamped to the stage, and both fighters must stay
166 // Hit detection: the attacker's hit box (active frames) overlapping one of the opponent's hurt boxes is a hit. 162 // inside that view
167 // Both directions are checked first and applied afterwards: simultaneous hits trade 163 void FightScene::keepInView() {
    164 float centre = Stage::clampCamera(0.5f * (fighters[0].position.x + fighters[1].position.x), kViewSize.x);
    165 float left = centre - kViewSize.x * 0.5f + kViewMargin, right = centre + kViewSize.x * 0.5f - kViewMargin;
    166 for (Fighter &f : fighters) clampX(f, std::max(left, kStageLeft), std::min(right, kStageRight));
    167 }
    168  
    169 Camera2D FightScene::worldCamera(float alpha) const {
    170 // 描くときは補間した位置の真ん中 / when drawing: the midpoint of the interpolated positions
    171 float a = lerp(fighters[0].previous, fighters[0].position, alpha).x;
    172 float b = lerp(fighters[1].previous, fighters[1].position, alpha).x;
    173 Camera2D c = Camera2D::screen(kViewSize);
    174 c.centre.x = std::round(Stage::clampCamera(0.5f * (a + b), kViewSize.x));
    175 c.pixelSnap = true;
    176 return c;
    177 }
    178  
168 void FightScene::resolveHits() { 179 void FightScene::resolveHits() {
169 // 技はここで覚える:相打ちだと、一つ目のtakeHitが二人目の技(move)を消してしまう 180 // 技はここで覚える:相打ちだと、一つ目のtakeHitが二人目の技(move)を消してしまう
170 // The move is remembered here: in a trade the first takeHit clears the second attacker's move 181 // The move is remembered here: in a trade the first takeHit clears the second attacker's move
@@ -186,6 +197,7 @@ void FightScene::resolveHits() {
186 break; 197 break;
187 } 198 }
188 } 199 }
    200 float viewCentre = Stage::clampCamera(0.5f * (fighters[0].position.x + fighters[1].position.x), kViewSize.x);
189 float push[2] = {0.0f, 0.0f}; // 壁際の押し返し(後でまとめて) / corner push-backs (applied at the end) 201 float push[2] = {0.0f, 0.0f}; // 壁際の押し返し(後でまとめて) / corner push-backs (applied at the end)
190 for (int c = 0; c < count; ++c) { 202 for (int c = 0; c < count; ++c) {
191 int i = contacts[c].attacker; 203 int i = contacts[c].attacker;
@@ -194,9 +206,12 @@ void FightScene::resolveHits() {
194 a.confirmHit(); 206 a.confirmHit();
195 bool wasHit = v.state == FighterState::Hitstun; 207 bool wasHit = v.state == FighterState::Hitstun;
196 HitResult r = v.takeHit(m, a.facing, contacts[c].blocked); 208 HitResult r = v.takeHit(m, a.facing, contacts[c].blocked);
197 // 壁際:相手が下がれないので自分が下がる(壁で永久に固めさせない) / at the wall the opponent cannot move back, 209 // 壁(舞台の端か画面の端)を背にした相手には、自分が下がる / against an opponent with their back to a wall (the
198 // so the attacker is pushed back instead (no endless corner pressure) 210 // stage end or the view edge) the attacker is pushed back instead
199 if (atWall(v)) push[i] = m.knockback * 0.7f; 211 Rect vb = v.pushbox();
    212 float wallLeft = std::max(kStageLeft, viewCentre - kViewSize.x * 0.5f + kViewMargin);
    213 float wallRight = std::min(kStageRight, viewCentre + kViewSize.x * 0.5f - kViewMargin);
    214 if (vb.left() <= wallLeft + 0.5f || vb.right() >= wallRight - 0.5f) push[i] = m.knockback * 0.7f;
200 bool blocked = r == HitResult::Blocked; 215 bool blocked = r == HitResult::Blocked;
201 int stop = blocked ? m.hitstop - 3 : m.hitstop; 216 int stop = blocked ? m.hitstop - 3 : m.hitstop;
202 if (r == HitResult::KO) { 217 if (r == HitResult::KO) {
@@ -208,9 +223,7 @@ void FightScene::resolveHits() {
208 top = i; 223 top = i;
209 bool heavy = m.damage >= 10 || r == HitResult::KO; 224 bool heavy = m.damage >= 10 || r == HitResult::KO;
210 if (heavy && !blocked) shake = stop; 225 if (heavy && !blocked) shake = stop;
211 Rect w = contacts[c].where; 226 effects.spark(contacts[c].where.centre(), blocked, heavy);
212 effects.spark(w.centre(), blocked, heavy);    
213 // 記録(台本で動かしたときの確認に) / a log line (to check scripted runs)    
214 static const char *const kResult[] = {"hit", "blocked", "KO"}; 227 static const char *const kResult[] = {"hit", "blocked", "KO"};
215 printf("step %d: %s %s -> %s %s, hp %d, combo %d, hit stop %d\n", steps, a.name.c_str(), m.name, 228 printf("step %d: %s %s -> %s %s, hp %d, combo %d, hit stop %d\n", steps, a.name.c_str(), m.name,
216 v.name.c_str(), kResult[static_cast<int>(r)], v.health, blocked ? 0 : v.combo, stop); 229 v.name.c_str(), kResult[static_cast<int>(r)], v.health, blocked ? 0 : v.combo, stop);
@@ -229,142 +242,194 @@ void FightScene::resolveHits() {
229 if (push[i] > 0.0f) fighters[i].pushBack(push[i]); 242 if (push[i] > 0.0f) fighters[i].pushBack(push[i]);
230 } 243 }
231   244  
232 void FightScene::drawBackground() { 245 void FightScene::finishRound(int winner, bool byTime) {
233 SpriteBatch &b = g.batch; 246 phase = RoundPhase::Finish;
234 // 画面より8ピクセルずつ広く描く:画面が揺れても端に隙間ができない / drawn 8 pixels wider than the view on every side, 247 phaseTime = 0;
235 // so the screen shake never opens a gap at the edges 248 roundWinner = winner;
236 // 梁と漆喰の壁 / beams and the plaster wall 249 timeOver = byTime;
237 b.drawRect({-8, -8, 656, 376}, kPlaster); 250 if (winner >= 0) ++wins[winner];
238 b.drawRect({-8, -8, 656, 42}, kBeam); 251 printf("round %d: %s%s (wins %d-%d)\n", round, winner < 0 ? "draw" : fighters[winner].name.c_str(),
239 b.drawRect({-8, 34, 656, 3}, kBeamLight); 252 byTime ? " by time" : "", wins[0], wins[1]);
240 b.drawRect({-8, 37, 656, 4}, kPlasterShade); 253 }
241 for (float x = 0; x < 640; x += 160) { 254  
242 b.drawRect({x, 37, 12, 200}, kBeam); // 柱 / pillars 255 // ラウンドの流れ(ステップごと)。ヒットストップ中は進まない / the round flow (per step); frozen during hit stop
243 b.drawRect({x + 9, 37, 3, 200}, kBeamLight); 256 void FightScene::updateRound() {
244 } 257 ++phaseTime;
245 // 障子:格子の窓 / shoji: lattice windows 258 if (settings.mode == Mode::Training) {
246 for (float x : {28.0f, 188.0f, 348.0f, 508.0f}) { 259 if (koTime > 0 && ++koTime > 180) startRound(); // 練習:3秒後に仕切り直し / training: restart after 3 s
247 if (x == 188.0f) continue; // 真ん中は掛け軸 / scroll in the middle instead 260 return;
248 Rect w = {x, 62, 104, 120};    
249 b.drawRect(w, kLattice);    
250 b.drawRect({w.x + 3, w.y + 3, w.w - 6, w.h - 6}, kShoji);    
251 for (float lx = w.x + 3 + 24; lx < w.right() - 4; lx += 25) b.drawRect({lx, w.y + 3, 2, w.h - 6}, kLattice);    
252 for (float ly = w.y + 3 + 28; ly < w.bottom() - 4; ly += 29) b.drawRect({w.x + 3, ly, w.w - 6, 2}, kLattice);    
253 } 261 }
254 // 掛け軸「練習」 / a hanging scroll: "practice" 262 bool ko[2] = {fighters[0].health == 0, fighters[1].health == 0};
255 b.drawRect({212, 52, 64, 6}, kBeam); 263 switch (phase) {
256 b.drawRect({218, 58, 52, 132}, hexColor(0xf6f0e0ff)); 264 case RoundPhase::Intro:
257 b.drawRect({218, 58, 52, 4}, hexColor(0x9a4a3aff)); 265 if (phaseTime >= kIntroFrames) {
258 b.drawRect({218, 186, 52, 4}, hexColor(0x9a4a3aff)); 266 phase = RoundPhase::Fight;
259 b.drawRect({212, 190, 64, 6}, kBeam); 267 phaseTime = 0;
260 g.pixel.draw(b, "練", {244, 82}, {.color = kOutline, .scale = 2.0f, .align = TextAlign::Centre}); 268 }
261 g.pixel.draw(b, "習", {244, 122}, {.color = kOutline, .scale = 2.0f, .align = TextAlign::Centre}); 269 break;
262 b.drawRect({236, 166, 16, 8}, hexColor(0xc83c3cff)); // 落款 / the seal 270 case RoundPhase::Fight:
263 // 腰板 / wainscot 271 if (ko[0] || ko[1]) finishRound(ko[0] && ko[1] ? -1 : ko[0] ? 1 : 0, false);
264 b.drawRect({-8, 222, 656, 38}, kWainscot); 272 else if (--timer <= 0) {
265 b.drawRect({-8, 222, 656, 3}, kWainscotDark); 273 // タイムアップ:体力の多い方の勝ち / time over: the one with more health wins
266 for (float x = 0; x < 640; x += 40) b.drawRect({x, 225, 2, 35}, kWainscotDark); 274 int h0 = fighters[0].health, h1 = fighters[1].health;
267 // 床板:奥ほど細い(ゆるい遠近) / floor planks: thinner further back (a gentle perspective) 275 finishRound(h0 == h1 ? -1 : h0 > h1 ? 0 : 1, true);
268 float y = 260.0f; 276 }
269 int row = 0; 277 break;
270 // 最後の段は画面の下より先まで / the last row reaches past the bottom 278 case RoundPhase::Finish:
271 for (float h : {6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 12.0f, 13.0f, 15.0f, 28.0f}) { 279 if (phaseTime == kWinPoseAt && roundWinner >= 0) fighters[roundWinner].win();
272 b.drawRect({-8, y, 656, h}, row % 2 ? kPlankA : kPlankB); 280 if (leaving) phaseTime = kFinishFrames; // 暗いまま待つ / stay dark while the switch happens
273 b.drawRect({-8, y, 656, 1}, kPlankLine); 281 else if (phaseTime >= kFinishFrames) {
274 float offset = static_cast<float>((row * 97) % 120); 282 bool over = wins[0] >= kWinsNeeded || wins[1] >= kWinsNeeded || round >= kMaxRounds;
275 for (float x = offset; x < 640; x += 120) b.drawRect({x, y, 1, h}, kPlankLine); 283 if (over) {
276 y += h; 284 int winner = wins[0] == wins[1] ? -1 : wins[0] > wins[1] ? 0 : 1;
277 ++row; 285 // 置き換えは予約だけ(このシーンはこのupdateの後で消える) / the replacement is only queued (this scene goes
    286 // away after this update)
    287 scenes().replace(std::make_unique<ResultScene>(g, settings, winner, wins), {.duration = 0.6f});
    288 leaving = true;
    289 } else {
    290 ++round;
    291 startRound();
    292 }
    293 }
    294 break;
278 } 295 }
279 } 296 }
280   297  
281 void FightScene::draw(float alpha) { 298 void FightScene::draw(float alpha) {
282 SpriteBatch &b = g.batch; 299 SpriteBatch &b = g.batch;
283 Camera2D view = camera; 300 Camera2D view = worldCamera(alpha);
284 // 画面の揺れ:重い一撃のヒットストップ中、カメラを2ピクセルずつ揺らす / screen shake: during a heavy hit's 301 // 揺れは横だけ、舞台の中で(端で舞台の外が見えないように) / the shake is horizontal only and stays inside the stage
285 // hit stop the camera jumps by 2 pixels 302 // (so nothing outside the stage shows at the ends)
286 if (shake > 0) view.centre += Vec2{shake % 2 ? 2.0f : -2.0f, shake % 4 < 2 ? 1.0f : -1.0f}; 303 if (shake > 0) view.centre.x = Stage::clampCamera(view.centre.x + (shake % 2 ? 2.0f : -2.0f), kViewSize.x);
287 b.begin(view.matrix(), SpriteSort::Layer); 304 b.begin(view.matrix(), SpriteSort::Layer);
288 drawBackground(); 305 g.stage->drawBack(b, view);
289 for (int i = 0; i < 2; ++i) 306 for (int i = 0; i < 2; ++i)
290 fighters[i].draw(b, alpha, i == top ? 3.0f : 2.0f, victim == i && hitstop > 0 ? hitstop : 0); 307 fighters[i].draw(b, alpha, i == top ? 3.0f : 2.0f, victim == i && hitstop > 0 ? hitstop : 0);
291 effects.draw(b); 308 effects.draw(b);
292 if (g.showBoxes) drawDebug(alpha); 309 g.stage->drawFront(b, view);
293 b.end(); 310 b.end();
294 // HUDは揺らさない / the HUD does not shake 311 if (g.showBoxes) {
295 b.begin(camera.matrix(), SpriteSort::Layer); 312 b.begin(view.matrix(), SpriteSort::Layer);
    313 drawDebug();
    314 b.end();
    315 }
    316 b.begin(Camera2D::screen(kViewSize).matrix(), SpriteSort::Layer);
296 drawHud(); 317 drawHud();
297 b.end(); 318 b.end();
298 } 319 }
299   320  
300 void FightScene::drawHud() { 321 void FightScene::drawHud() {
301 SpriteBatch &b = g.batch; 322 SpriteBatch &b = g.batch;
302 drawHealthBar(b, {16, 10, 272, 10}, static_cast<float>(fighters[0].health), trail[0], false); 323 drawHealthBar(b, {16, 10, 260, 10}, static_cast<float>(fighters[0].health), trail[0], false);
303 drawHealthBar(b, {352, 10, 272, 10}, static_cast<float>(fighters[1].health), trail[1], true); 324 drawHealthBar(b, {364, 10, 260, 10}, static_cast<float>(fighters[1].health), trail[1], true);
304 TextStyle name = {.color = kText, .layer = 11.0f, .shadow = kOutline}; 325 TextStyle name = {.color = kText, .layer = 11.0f, .shadow = kOutline};
305 g.pixel.draw(b, "1P " + fighters[0].name, {16, 24}, name); 326 bool cpu[2] = {ai[0].has_value(), ai[1].has_value()};
    327 g.pixel.draw(b, "1P " + fighters[0].name + (cpu[0] ? " (CPU)" : ""), {16, 24}, name);
306 TextStyle right = name; 328 TextStyle right = name;
307 right.align = TextAlign::Right; 329 right.align = TextAlign::Right;
308 g.pixel.draw(b, fighters[1].name + " 2P", {624, 24}, right); 330 g.pixel.draw(b, (cpu[1] ? "(CPU) " : "") + fighters[1].name + " 2P", {624, 24}, right);
309 TextStyle centre = name; 331 // 取ったラウンド:名前の横の印 / rounds won: marks next to the names
310 centre.align = TextAlign::Centre; 332 for (int i = 0; i < 2; ++i)
311 centre.color = kGold; 333 for (int k = 0; k < kWinsNeeded; ++k) {
312 g.pixel.draw(b, "練習", {320, 8}, centre); 334 float x = i == 0 ? 266.0f - 12.0f * static_cast<float>(k) : 366.0f + 12.0f * static_cast<float>(k);
313 // コンボ数(攻撃した側に) / the combo count (on the attacker's side) 335 b.drawRect({x - 1, 25, 10, 10}, kOutline, 10.0f);
    336 b.drawRect({x, 26, 8, 8}, wins[i] > k ? kGold : hexColor(0x4a2434ff), 10.1f);
    337 }
    338 // 時間(真ん中)。練習は「練習」 / the timer (center); training shows "練習"
    339 b.drawRect({298, 4, 44, 30}, kOutline, 10.0f);
    340 TextStyle centre = {.color = kGold, .scale = 2.0f, .align = TextAlign::Centre, .layer = 11.0f};
    341 if (settings.mode == Mode::Training) {
    342 centre.scale = 1.0f;
    343 g.pixel.draw(b, "練習", {320, 12}, centre);
    344 } else {
    345 int seconds = (timer + 59) / 60;
    346 centre.color = seconds <= 10 ? kRed : kGold;
    347 g.pixel.draw(b, std::to_string(seconds), {320, 6}, centre);
    348 }
314 for (int i = 0; i < 2; ++i) { 349 for (int i = 0; i < 2; ++i) {
315 if (comboTime[i] <= 0) continue; 350 if (comboTime[i] <= 0) continue;
316 std::string text = std::to_string(comboHits[i]) + " HITS";    
317 TextStyle s = {.color = hexColor(0xff9a3cff), .scale = 2.0f, .align = i == 0 ? TextAlign::Left : TextAlign::Right, 351 TextStyle s = {.color = hexColor(0xff9a3cff), .scale = 2.0f, .align = i == 0 ? TextAlign::Left : TextAlign::Right,
318 .layer = 11.0f, .shadow = kOutline}; 352 .layer = 11.0f, .shadow = kOutline};
319 g.pixel.draw(b, text, {i == 0 ? 16.0f : 624.0f, 44.0f}, s); 353 g.pixel.draw(b, std::to_string(comboHits[i]) + " HITS", {i == 0 ? 16.0f : 624.0f, 44.0f}, s);
    354 }
    355  
    356 // ラウンドの表示 / the round banners
    357 TextStyle sub = {.color = kText, .scale = 2.0f, .align = TextAlign::Centre, .layer = 11.5f, .shadow = kOutline,
    358 .shadowOffset = {1.0f, 1.0f}};
    359 if (phase == RoundPhase::Intro) {
    360 bool final = round == kMaxRounds || (wins[0] == kWinsNeeded - 1 && wins[1] == kWinsNeeded - 1);
    361 if (phaseTime < 60) {
    362 drawBigText(b, g.pixel, final ? "FINAL ROUND" : "ROUND " + std::to_string(round), {320, 130}, kText, 4.0f);
    363 g.pixel.draw(b, final ? "最終ラウンド" : "第" + std::to_string(round) + "ラウンド", {320, 162}, sub);
    364 } else {
    365 drawBigText(b, g.pixel, "FIGHT!", {320, 130}, kGold, 5.0f);
    366 }
    367 } else if (phase == RoundPhase::Finish) {
    368 if (phaseTime < kWinPoseAt) {
    369 bool doubleKo = roundWinner < 0 && !timeOver;
    370 drawBigText(b, g.pixel, timeOver ? "TIME UP" : doubleKo ? "DOUBLE K.O." : "K.O.", {320, 130}, kRed,
    371 timeOver || doubleKo ? 4.0f : 5.0f);
    372 if (timeOver) g.pixel.draw(b, "タイムアップ", {320, 162}, sub);
    373 } else if (roundWinner >= 0) {
    374 drawBigText(b, g.pixel, fighters[roundWinner].name + " WINS", {320, 130}, kGold, 4.0f);
    375 g.pixel.draw(b, std::string(kJapaneseNames[roundWinner]) + "の勝ち", {320, 162}, sub);
    376 } else {
    377 drawBigText(b, g.pixel, "DRAW", {320, 130}, kText, 4.0f);
    378 g.pixel.draw(b, "引き分け", {320, 162}, sub);
    379 }
    380 } else if (koTime > 0) {
    381 drawBigText(b, g.pixel, "K.O.", {320, 130}, kRed, 5.0f);
320 } 382 }
321 if (koTime > 0) drawBigText(b, g.pixel, "K.O.", {320, 130}, hexColor(0xe8483cff), 5.0f);    
322 } 383 }
323   384  
324 // F1:食らい判定(青)、攻撃判定(赤)、押し合い(緑)、ソケット(黄)、状態と技の段階 385 void FightScene::drawDebug() {
325 // F1: hurt boxes (blue), hit boxes (red), push boxes (green), sockets (yellow), the state and the move's phase    
326 void FightScene::drawDebug(float /*alpha*/) {    
327 // 判定は今のステップの位置で描く(補間しない:当たりを決めたのはこの位置) / boxes at this step's positions (not    
328 // interpolated: these are the positions the hits were decided at)    
329 SpriteBatch &b = g.batch; 386 SpriteBatch &b = g.batch;
330 static const char *const kPhase[] = {"", "STARTUP", "ACTIVE", "RECOVERY"}; 387 static const char *const kPhase[] = {"", "STARTUP", "ACTIVE", "RECOVERY"};
331 for (const Fighter &f : fighters) { 388 for (int i = 0; i < 2; ++i) {
332 for (const Rect &r : f.hurtboxes()) b.drawRectOutline(r, hexColor(0x5aaaffe0), 1.0f, 8.0f); 389 const Fighter &f = fighters[i];
    390 for (const Rect &r : f.hurtboxes()) b.drawRectOutline(r, hexColor(0x5aaaffe0), 1.0f, 20.0f);
333 Rect push = f.pushbox(); 391 Rect push = f.pushbox();
334 b.drawRectOutline(push, hexColor(0x50e070c0), 1.0f, 8.1f); 392 b.drawRectOutline(push, hexColor(0x50e070c0), 1.0f, 20.1f);
335 const FrameBoxes &fb = (*g.frameData)[f.frame]; 393 const FrameBoxes &fb = (*g.frameData)[f.frame];
336 // 攻撃判定:持続フレームの間ずっと。当たった後(もう当たらない)は薄く / the attack box for the whole active    
337 // window; fainter once it has hit (it cannot hit again)    
338 if (f.phase() == MovePhase::Active && fb.hit) 394 if (f.phase() == MovePhase::Active && fb.hit)
339 b.drawRect(toWorld(*fb.hit, f.position, f.facing), f.moveHit ? hexColor(0xff464650) : hexColor(0xff4646a0), 8.2f); 395 b.drawRect(toWorld(*fb.hit, f.position, f.facing), f.moveHit ? hexColor(0xff464650) : hexColor(0xff4646a0), 20.2f);
340 for (Vec2 s : {fb.head, fb.knot, fb.fist, fb.foot}) { 396 for (Vec2 s : {fb.head, fb.knot, fb.fist, fb.foot}) {
341 Rect r = toWorld({s.x, s.y, 0.0f, 0.0f}, f.position, f.facing); 397 Rect r = toWorld({s.x, s.y, 0.0f, 0.0f}, f.position, f.facing);
342 b.drawRect({std::round(r.x) - 1, std::round(r.y) - 1, 2, 2}, hexColor(0xffdc3cff), 8.3f); 398 b.drawRect({std::round(r.x) - 1, std::round(r.y) - 1, 2, 2}, hexColor(0xffdc3cff), 20.3f);
343 } 399 }
344 char label[96]; 400 char label[128];
345 if (f.state == FighterState::Attack) 401 int n = f.state == FighterState::Attack
346 std::snprintf(label, sizeof label, "%s %s %d/%d\n%s", stateName(f.state), f.move->name, f.stateTime, 402 ? std::snprintf(label, sizeof label, "%s %s %d/%d\n%s", stateName(f.state), f.move->name, f.stateTime,
347 f.move->total(), kPhase[static_cast<int>(f.phase())]); 403 f.move->total(), kPhase[static_cast<int>(f.phase())])
348 else std::snprintf(label, sizeof label, "%s %d\nHP %d", stateName(f.state), f.stateTime, f.health); 404 : std::snprintf(label, sizeof label, "%s %d\nHP %d", stateName(f.state), f.stateTime, f.health);
349 // 左の人の札は左へ、右の人の札は右へずらす(近づいても重ならない) / the left fighter's label goes left, the 405 // CPUなら今の意図も / for the CPU also its current intent
350 // right one's right (no overlap at close range) 406 if (ai[i] && n > 0 && static_cast<size_t>(n) < sizeof label)
351 const Fighter &other = &f == &fighters[0] ? fighters[1] : fighters[0]; 407 std::snprintf(label + n, sizeof label - static_cast<size_t>(n), "\nAI %s", ai[i]->intentName());
352 bool leftOne = f.position.x < other.position.x || (f.position.x == other.position.x && &f == &fighters[0]); 408 const Fighter &other = fighters[1 - i];
    409 bool leftOne = f.position.x < other.position.x || (f.position.x == other.position.x && i == 0);
353 Vec2 size = g.tiny.measure(label); 410 Vec2 size = g.tiny.measure(label);
354 float x0 = std::round(leftOne ? f.position.x + 8.0f - size.x : f.position.x - 8.0f); 411 float x0 = std::round(leftOne ? f.position.x + 8.0f - size.x : f.position.x - 8.0f);
355 Vec2 at = {x0, std::round(push.y) - 16.0f}; 412 Vec2 at = {x0, std::round(push.y) - 22.0f};
356 b.drawRect({x0 - 2.0f, at.y - 2.0f, size.x + 3.0f, size.y + 2.0f}, {0.11f, 0.09f, 0.15f, 0.8f}, 8.5f); 413 b.drawRect({x0 - 2.0f, at.y - 2.0f, size.x + 3.0f, size.y + 2.0f}, {0.11f, 0.09f, 0.15f, 0.8f}, 20.5f);
357 g.tiny.draw(b, label, at, {.color = kText, .layer = 9.0f}); 414 g.tiny.draw(b, label, at, {.color = kText, .layer = 21.0f});
358 } 415 }
359 } 416 }
360   417  
361 void FightScene::drawUi(float /*alpha*/) { 418 void FightScene::drawUi(float /*alpha*/) {
362 SpriteBatch &b = g.batch; 419 SpriteBatch &b = g.batch;
363 b.begin(g.screen.matrix()); 420 b.begin(g.screen.matrix());
    421 // ラウンドの間の暗転(自前のフェード:シーンは変わらない) / the fade between rounds (our own: the scene stays)
    422 float fade = 0.0f;
    423 if (phase == RoundPhase::Finish && phaseTime > kFinishFrames - 30)
    424 fade = static_cast<float>(phaseTime - (kFinishFrames - 30)) / 30.0f;
    425 if (phase == RoundPhase::Intro && phaseTime < 20) fade = 1.0f - static_cast<float>(phaseTime) / 20.0f;
    426 if (fade > 0.0f) b.drawRect({0, 0, 1280, 720}, {0.0f, 0.0f, 0.0f, std::clamp(fade, 0.0f, 1.0f)});
364 b.drawRect({0, 688, 1280, 32}, {0.11f, 0.09f, 0.15f, 0.75f}); 427 b.drawRect({0, 688, 1280, 32}, {0.11f, 0.09f, 0.15f, 0.75f});
365 g.ui.draw(b, 428 const char *help = settings.mode == Mode::TwoPlayers || settings.mode == Mode::Training
366 "1P: A D W S + F パンチ・G キック 2P: カーソルキー + K・L 後ろでガード / back = guard " 429 ? "1P: A D W S + F パンチ・G キック 2P: カーソルキー + K・L F1 当たり箱 Esc 一時停止 / pause"
367 "F1 当たり箱 Esc 終了", 430 : settings.mode == Mode::VsCpu
368 {640, 694}, {.color = hexColor(0xe8e0d0ff), .align = TextAlign::Centre}); 431 ? "1P: A D 前後・W ジャンプ・S しゃがむ・F パンチ・G キック F1 当たり箱 Esc 一時停止 / pause"
    432 : "CPU 対 CPU F1 当たり箱 Esc 一時停止 / pause";
    433 g.ui.draw(b, help, {640, 694}, {.color = hexColor(0xe8e0d0ff), .align = TextAlign::Centre});
369 b.end(); 434 b.end();
370 } 435 }

ファイル: a/games/fighter/src/fight_scene.hh | b/games/fighter/src/fight_scene.hh

前新
@@ -1,40 +1,60 @@
1 // 対戦の場面:二人のファイター、押し合い、技の当たり、ヒットストップ、体力ゲージ、エフェクト 1 // 対戦の場面:二人のファイター(人かCPU)、押し合い、技の当たり、ヒットストップ、体力ゲージ、エフェクト、
2 // The fight scene: two fighters, pushing, hits, hit stop, health bars, effects 2 // スクロールする舞台とカメラ、ラウンド(3本勝負、時間、KO・タイムアップ)
    3 // The fight scene: two fighters (human or CPU), pushing, hits, hit stop, health bars, effects, the scrolling stage
    4 // and camera, rounds (best of three, a timer, KO / time over)
3 #pragma once 5 #pragma once
4   6  
    7 #include "ai.hh"
5 #include "effects.hh" 8 #include "effects.hh"
6 #include "fighter.hh" 9 #include "fighter.hh"
7 #include "game.hh" 10 #include "game.hh"
    11 #include "match.hh"
8   12  
9 #include "engine/scene.hh" 13 #include "engine/scene.hh"
10   14  
    15 #include <optional>
    16  
11 class FightScene : public Scene { 17 class FightScene : public Scene {
12 public: 18 public:
13 explicit FightScene(Game &game); 19 FightScene(Game &game, MatchSettings settings);
    20 void pause() override;
14 void update(float dt) override; 21 void update(float dt) override;
15 void draw(float alpha) override; 22 void draw(float alpha) override;
16 void drawUi(float alpha) override; 23 void drawUi(float alpha) override;
17   24  
18 private: 25 private:
    26 // ラウンドの流れ:始まりの表示 → 戦い → 決着の表示 / the round flow: the intro banner → the fight → the result
    27 enum class RoundPhase { Intro, Fight, Finish };
    28  
    29 void startRound();
19 void separate(); 30 void separate();
    31 void keepInView();
20 void resolveHits(); 32 void resolveHits();
21 void resetRound(); 33 void finishRound(int winner, bool timeOver);
22 void drawBackground(); 34 void updateRound();
    35 Camera2D worldCamera(float alpha) const;
23 void drawHud(); 36 void drawHud();
24 void drawDebug(float alpha); 37 void drawDebug();
25   38  
26 Game &g; 39 Game &g;
27 Camera2D camera; 40 MatchSettings settings;
28 Fighter fighters[2]; 41 Fighter fighters[2];
    42 std::optional<AiController> ai[2]; // ある方はCPUが操作する / where set, the computer plays that side
29 Effects effects; 43 Effects effects;
30 GamepadEdges pads[2]; 44 GamepadEdges pads[2];
31 int steps = 0; 45 int steps = 0;
32 int hitstop = 0; // 残りのヒットストップ(二人とも止まる) / hit stop left (both fighters frozen) 46 int hitstop = 0, victim = -1, shake = 0, top = 0;
33 int victim = -1; // ヒットストップ中に震える方 / who shakes during the hit stop 47 float trail[2] = {kMaxHealth, kMaxHealth};
34 int shake = 0; // 画面の揺れ / screen shake    
35 int top = 0; // 手前に描くファイター(最後に攻撃した方) / the fighter drawn in front (the last attacker)    
36 float trail[2] = {kMaxHealth, kMaxHealth}; // 体力ゲージの減っていく白い部分 / the health bar's draining trail    
37 int trailDelay[2] = {0, 0}; 48 int trailDelay[2] = {0, 0};
38 int comboTime[2] = {0, 0}, comboHits[2] = {0, 0}; // 「2 HITS」の表示 / the "2 HITS" display 49 int comboTime[2] = {0, 0}, comboHits[2] = {0, 0};
39 int koTime = 0; // KOからの時間(練習では仕切り直す) / time since a KO (training resets) 50  
    51 RoundPhase phase = RoundPhase::Intro;
    52 int phaseTime = 0;
    53 int round = 1;
    54 int wins[2] = {0, 0};
    55 int timer = kRoundSeconds * 60; // ラウンドの残り(ステップ) / time left in the round (steps)
    56 int roundWinner = -1; // -1 = 引き分け / -1 = draw
    57 bool timeOver = false;
    58 int koTime = 0; // 練習モードのKOからの時間 / training mode: time since a KO
    59 bool leaving = false; // 勝利画面への切り替えを頼んだ / the switch to the win screen was requested
40 }; 60 };

ファイル: a/games/fighter/src/fighter.cc | b/games/fighter/src/fighter.cc

前新
@@ -49,6 +49,7 @@ const char *stateName(FighterState state) {
49 case FighterState::Knockdown: return "KNOCKDOWN"; 49 case FighterState::Knockdown: return "KNOCKDOWN";
50 case FighterState::GetUp: return "GETUP"; 50 case FighterState::GetUp: return "GETUP";
51 case FighterState::KO: return "KO"; 51 case FighterState::KO: return "KO";
    52 case FighterState::Win: return "WIN";
52 } 53 }
53 return "?"; 54 return "?";
54 } 55 }
@@ -57,7 +58,7 @@ Fighter::Fighter(const SpriteSheet &s, const SpriteSheet &effects, const FrameDa
57 const char *tail, Vec2 start, float startFacing) 58 const char *tail, Vec2 start, float startFacing)
58 : name(std::move(fighterName)), position(start), previous(start), facing(startFacing), sheet(s), data(frameData), 59 : name(std::move(fighterName)), position(start), previous(start), facing(startFacing), sheet(s), data(frameData),
59 idleClip(s.clip("idle")), walkClip(s.clip("walk")), walkBackClip(s.clip("walk_back")), 60 idleClip(s.clip("idle")), walkClip(s.clip("walk")), walkBackClip(s.clip("walk_back")),
60 fCrouchIn(findFrame(s, "crouch_in")), fCrouch(findFrame(s, "crouch")), fJumpUp(findFrame(s, "jump_up")), 61 winClip(s.clip("win")), fCrouchIn(findFrame(s, "crouch_in")), fCrouch(findFrame(s, "crouch")), fJumpUp(findFrame(s, "jump_up")),
61 fJumpTuck(findFrame(s, "jump_tuck")), fJumpDown(findFrame(s, "jump_down")), fBlock(findFrame(s, "block")), 62 fJumpTuck(findFrame(s, "jump_tuck")), fJumpDown(findFrame(s, "jump_down")), fBlock(findFrame(s, "block")),
62 fCBlock(findFrame(s, "cblock")), fHit0(findFrame(s, "hit0")), fHit1(findFrame(s, "hit1")), 63 fCBlock(findFrame(s, "cblock")), fHit0(findFrame(s, "hit0")), fHit1(findFrame(s, "hit1")),
63 fCHit(findFrame(s, "chit")), fKo0(findFrame(s, "ko0")), fKo1(findFrame(s, "ko1")) { 64 fCHit(findFrame(s, "chit")), fKo0(findFrame(s, "ko0")), fKo1(findFrame(s, "ko1")) {
@@ -75,6 +76,7 @@ void Fighter::reset(Vec2 start, float startFacing) {
75 health = kMaxHealth; 76 health = kMaxHealth;
76 move = nullptr; 77 move = nullptr;
77 onGround = true; 78 onGround = true;
    79 wantsWin = false;
78 buffer.clear(); 80 buffer.clear();
79 animator.play(idleClip, true); 81 animator.play(idleClip, true);
80 frame = animator.frame(); 82 frame = animator.frame();
@@ -124,6 +126,8 @@ void Fighter::setState(FighterState next) {
124 stateTime = 0; 126 stateTime = 0;
125 } 127 }
126   128  
    129 void Fighter::win() { wantsWin = true; }
    130  
127 bool Fighter::actionable() const { 131 bool Fighter::actionable() const {
128 return state == FighterState::Idle || state == FighterState::Walk || state == FighterState::Crouch; 132 return state == FighterState::Idle || state == FighterState::Walk || state == FighterState::Crouch;
129 } 133 }
@@ -233,8 +237,15 @@ void Fighter::update(float dt, const Controls &c, float opponentX, bool threat)
233 if (stateTime >= kGetUpFrames) setState(FighterState::Idle); 237 if (stateTime >= kGetUpFrames) setState(FighterState::Idle);
234 break; 238 break;
235 case FighterState::KO: 239 case FighterState::KO:
    240 case FighterState::Win:
236 break; 241 break;
237 } 242 }
    243 // 勝ちポーズは、自由に動ける状態で地上にいるときに / the victory pose starts once free and on the ground
    244 if (wantsWin && onGround && (actionable() || state == FighterState::Land)) {
    245 velocity.x = 0.0f;
    246 setState(FighterState::Win);
    247 animator.play(winClip, true);
    248 }
238   249  
239 // 物理:空中は重力、地上は(歩き以外)摩擦で止まる / physics: gravity in the air; on the ground friction stops 250 // 物理:空中は重力、地上は(歩き以外)摩擦で止まる / physics: gravity in the air; on the ground friction stops
240 // everything except walking 251 // everything except walking
@@ -386,6 +397,8 @@ void Fighter::chooseFrame(float dt) {
386 case FighterState::KO: 397 case FighterState::KO:
387 frame = onGround ? fKo1 : fKo0; 398 frame = onGround ? fKo1 : fKo0;
388 return; 399 return;
    400 case FighterState::Win:
    401 break; // animatorの勝ちクリップ / the animator's win clip
389 } 402 }
390 animator.update(dt); 403 animator.update(dt);
391 frame = animator.frame(); 404 frame = animator.frame();

ファイル: a/games/fighter/src/fighter.hh | b/games/fighter/src/fighter.hh

前新
@@ -38,6 +38,7 @@ enum class FighterState {
38 Knockdown, // ダウン:飛ばされて倒れ、起き上がる / knocked down: thrown back, lying, then getting up 38 Knockdown, // ダウン:飛ばされて倒れ、起き上がる / knocked down: thrown back, lying, then getting up
39 GetUp, // 起き上がり(無敵) / getting up (invincible) 39 GetUp, // 起き上がり(無敵) / getting up (invincible)
40 KO, // 体力0:倒れたまま / health 0: stays down 40 KO, // 体力0:倒れたまま / health 0: stays down
    41 Win, // 勝ちポーズ(ラウンドの勝者) / the victory pose (the round's winner)
41 }; 42 };
42 const char *stateName(FighterState state); 43 const char *stateName(FighterState state);
43   44  
@@ -79,6 +80,10 @@ public:
79 // the wall; a faster motion the same way (the knockback just taken in a trade) is kept 80 // the wall; a faster motion the same way (the knockback just taken in a trade) is kept
80 void pushBack(float speed) { velocity.x = -facing * std::max(speed, -facing * velocity.x); } 81 void pushBack(float speed) { velocity.x = -facing * std::max(speed, -facing * velocity.x); }
81 bool actionable() const; 82 bool actionable() const;
    83 bool grounded() const { return onGround; }
    84 // ラウンドに勝った:地上にいれば勝ちポーズ(空中なら着地してから) / won the round: the victory pose once on the
    85 // ground
    86 void win();
82   87  
83 // 体の部品(ノード)をこのステップの値に合わせてから描く / updates the part nodes for this frame, then draws them 88 // 体の部品(ノード)をこのステップの値に合わせてから描く / updates the part nodes for this frame, then draws them
84 void draw(SpriteBatch &batch, float alpha, float layer, int shake); 89 void draw(SpriteBatch &batch, float alpha, float layer, int shake);
@@ -114,11 +119,12 @@ private:
114   119  
115 const SpriteSheet &sheet; 120 const SpriteSheet &sheet;
116 const FrameData &data; 121 const FrameData &data;
117 const AnimationClip *idleClip, *walkClip, *walkBackClip; 122 const AnimationClip *idleClip, *walkClip, *walkBackClip, *winClip;
118 Animator animator; 123 Animator animator;
119 float jumpDirection = 0.0f; 124 float jumpDirection = 0.0f;
120 bool onGround = true; 125 bool onGround = true;
121 bool airMoveUsed = false; 126 bool airMoveUsed = false;
    127 bool wantsWin = false;
122 float time = 0.0f; 128 float time = 0.0f;
123 int fCrouchIn, fCrouch, fJumpUp, fJumpTuck, fJumpDown, fBlock, fCBlock, fHit0, fHit1, fCHit, fKo0, fKo1; 129 int fCrouchIn, fCrouch, fJumpUp, fJumpTuck, fJumpDown, fBlock, fCBlock, fHit0, fHit1, fCHit, fKo0, fKo1;
124   130  

ファイル: a/games/fighter/src/game.hh | b/games/fighter/src/game.hh

前新
@@ -2,7 +2,9 @@
2 // The fighting game's shared data, one per game (main creates it, the scenes keep a reference) 2 // The fighting game's shared data, one per game (main creates it, the scenes keep a reference)
3 #pragma once 3 #pragma once
4   4  
    5 #include "ai.hh"
5 #include "frame_data.hh" 6 #include "frame_data.hh"
    7 #include "stage.hh"
6   8  
7 #include "engine/camera2d.hh" 9 #include "engine/camera2d.hh"
8 #include "engine/font.hh" 10 #include "engine/font.hh"
@@ -26,6 +28,9 @@ struct Game {
26 const SpriteSheet *fighters[2]; // ハヤテ(1P)とジン(2P) / Hayate (1P) and Jin (2P) 28 const SpriteSheet *fighters[2]; // ハヤテ(1P)とジン(2P) / Hayate (1P) and Jin (2P)
27 const SpriteSheet *effects; // 火花・砂ぼこり・鉢巻の尾・星・影 / sparks, dust, headband tails, stars, shadow 29 const SpriteSheet *effects; // 火花・砂ぼこり・鉢巻の尾・星・影 / sparks, dust, headband tails, stars, shadow
28 const FrameData *frameData; // コマごとの判定(二人共通:同じ骨格) / per-frame boxes (shared: same skeleton) 30 const FrameData *frameData; // コマごとの判定(二人共通:同じ骨格) / per-frame boxes (shared: same skeleton)
    31 Stage *stage; // 視差の舞台(タイトルと勝利画面でも使う) / the parallax stage (also behind the
    32 // title and the win screen)
29 Camera2D screen; // 1280×720のUI / the 1280 × 720 UI 33 Camera2D screen; // 1280×720のUI / the 1280 × 720 UI
30 bool showBoxes = false; // F1:判定の箱とデバッグ表示 / F1: boxes and debug labels 34 bool showBoxes = false; // F1:判定の箱とデバッグ表示 / F1: boxes and debug labels
    35 Difficulty difficulty = Difficulty::Normal; // タイトルで選んだ強さ(戻っても覚えている) / chosen on the title (kept)
31 }; 36 };

ファイル: /dev/null | b/games/fighter/src/hud.cc

前新
@@ -0,0 +1,17 @@
    1 // 画面の文字 / on-screen text
    2 #include "hud.hh"
    3  
    4 #include <cmath>
    5  
    6 void drawBigText(SpriteBatch &b, const Font &font, std::string_view text, Vec2 centre, Vec4 color, float scale,
    7 float layer) {
    8 Vec2 size = font.measure(text, scale);
    9 Vec2 at = {centre.x, std::round(centre.y - size.y * 0.5f)};
    10 TextStyle s = {.color = kOutline, .scale = scale, .align = TextAlign::Centre, .layer = layer};
    11 for (Vec2 d : {Vec2{-2, -2}, Vec2{0, -2}, Vec2{2, -2}, Vec2{-2, 0}, Vec2{2, 0}, Vec2{-2, 2}, Vec2{0, 2}, Vec2{2, 2},
    12 Vec2{3, 4}, Vec2{0, 4}})
    13 font.draw(b, text, at + d, s);
    14 s.color = color;
    15 s.layer = layer + 0.5f;
    16 font.draw(b, text, at, s);
    17 }

ファイル: /dev/null | b/games/fighter/src/hud.hh

前新
@@ -0,0 +1,17 @@
    1 // 画面の文字と色(どのシーンでも使う) / on-screen text and colors (used by every scene)
    2 #pragma once
    3  
    4 #include "engine/font.hh"
    5 #include "engine/sprite_batch.hh"
    6  
    7 #include <string_view>
    8  
    9 constexpr Vec4 kOutline = hexColor(0x1b1726ff);
    10 constexpr Vec4 kText = hexColor(0xfff4d8ff);
    11 constexpr Vec4 kGold = hexColor(0xf2c14eff);
    12 constexpr Vec4 kRed = hexColor(0xe8483cff);
    13  
    14 // 大きな文字(K.O.、ROUND 1…):8方向の輪郭と影、それから本体。centreは文字の真ん中
    15 // Big text (K.O., ROUND 1...): an outline in 8 directions plus a drop shadow, then the text. centre is its middle
    16 void drawBigText(SpriteBatch &batch, const Font &font, std::string_view text, Vec2 centre, Vec4 color, float scale,
    17 float layer = 11.0f);

ファイル: a/games/fighter/src/main.cc | b/games/fighter/src/main.cc

前新
@@ -6,6 +6,9 @@
6 // 入力バッファ、体の部品とエフェクトのシーングラフ 6 // 入力バッファ、体の部品とエフェクトのシーングラフ
7 // Chapter 31: moves (frame data), hit / hurt boxes, damage, hit stun, knockback, hit stop, health bars, input 7 // Chapter 31: moves (frame data), hit / hurt boxes, damage, hit stun, knockback, hit stop, health bars, input
8 // buffering, a scene graph for body parts and effects 8 // buffering, a scene graph for body parts and effects
    9 // 第32章:視差のある舞台とカメラ、CPUの相手(状態と決める間隔、難易度)、ラウンド(3本勝負・時間)、勝利画面
    10 // Chapter 32: a parallax stage and camera, the CPU opponent (states, a decision timer, difficulty), rounds (best of
    11 // three, a timer), the win screen
9 // 12 //
10 // 操作(一台のキーボードを二人で) / Controls (two players on one keyboard): 13 // 操作(一台のキーボードを二人で) / Controls (two players on one keyboard):
11 // 1P A D 前後・W ジャンプ・S しゃがみ・F 突き・G 蹴り / A D walk, W jump, S crouch, F punch, G kick 14 // 1P A D 前後・W ジャンプ・S しゃがみ・F 突き・G 蹴り / A D walk, W jump, S crouch, F punch, G kick
@@ -13,9 +16,11 @@
13 // 相手と反対に入れてガード(しゃがみガードは後ろ下) / hold away from the opponent to guard (down-back crouching) 16 // 相手と反対に入れてガード(しゃがみガードは後ろ下) / hold away from the opponent to guard (down-back crouching)
14 // ゲームパッド:1台目 = 1P、2台目 = 2P(十字キーか左スティック、A/X 突き、B/Y 蹴り) / gamepads: 1st = 1P, 17 // ゲームパッド:1台目 = 1P、2台目 = 2P(十字キーか左スティック、A/X 突き、B/Y 蹴り) / gamepads: 1st = 1P,
15 // 2nd = 2P (d-pad or left stick, A/X punch, B/Y kick) 18 // 2nd = 2P (d-pad or left stick, A/X punch, B/Y kick)
16 // F1 判定の箱と状態 / boxes and states Esc 終了 / quit 19 // F1 判定の箱と状態 / boxes and states Esc / P 一時停止 / pause
17 #include "fight_scene.hh" 20 // タイトル:W S 選ぶ、A D 難易度、Space・Enter・F 決定、Esc 終了 / title: W S select, A D difficulty,
    21 // Space / Enter / F start, Esc quit
18 #include "game.hh" 22 #include "game.hh"
    23 #include "scenes.hh"
19   24  
20 #include "engine/pixel_canvas.hh" 25 #include "engine/pixel_canvas.hh"
21 #include "engine/window.hh" 26 #include "engine/window.hh"
@@ -40,7 +45,8 @@ int main() {
40 // 判定のデータは骨格から作ったもの:二人とも同じ(コマの名前と番号も同じ) / the box data comes from the skeleton: 45 // 判定のデータは骨格から作ったもの:二人とも同じ(コマの名前と番号も同じ) / the box data comes from the skeleton:
41 // the same for both (same frame names and indices) 46 // the same for both (same frame names and indices)
42 std::optional<FrameData> frameData = FrameData::load("games/fighter/assets/fighter.boxes", *hayate); 47 std::optional<FrameData> frameData = FrameData::load("games/fighter/assets/fighter.boxes", *hayate);
43 if (!frameData) return 1; 48 std::optional<Stage> stage = Stage::load();
    49 if (!frameData || !stage) return 1;
44   50  
45 Input input; 51 Input input;
46 input.attach(window); 52 input.attach(window);
@@ -49,10 +55,10 @@ int main() {
49 GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); 55 GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5});
50 PixelCanvas canvas(static_cast<int>(kViewSize.x), static_cast<int>(kViewSize.y)); 56 PixelCanvas canvas(static_cast<int>(kViewSize.x), static_cast<int>(kViewSize.y));
51 Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .ui = *ui, .pixel = *pixel, 57 Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .ui = *ui, .pixel = *pixel,
52 .tiny = *tiny, .fighters = {&*hayate, &*jin}, .effects = &*effects, .frameData = &*frameData, .screen = Camera2D::screen({1280.0f, 720.0f})}; 58 .tiny = *tiny, .fighters = {&*hayate, &*jin}, .effects = &*effects, .frameData = &*frameData, .stage = &*stage, .screen = Camera2D::screen({1280.0f, 720.0f})};
53   59  
54 SceneManager scenes; 60 SceneManager scenes;
55 scenes.push(std::make_unique<FightScene>(game)); 61 scenes.push(std::make_unique<TitleScene>(game));
56   62  
57 loop.run( 63 loop.run(
58 window, input, 64 window, input,

ファイル: /dev/null | b/games/fighter/src/match.hh

前新
@@ -0,0 +1,20 @@
    1 // 試合の設定(タイトルで選ぶ) / the match settings (chosen on the title screen)
    2 #pragma once
    3  
    4 #include "ai.hh"
    5  
    6 enum class Mode {
    7 VsCpu, // 1P 対 CPU / 1P vs the computer
    8 TwoPlayers, // 二人で対戦 / two players
    9 CpuVsCpu, // CPU 対 CPU(見るだけ) / computer vs computer (watch)
    10 Training, // 練習:時間なし、KOで仕切り直し / training: no timer, a KO restarts
    11 };
    12  
    13 struct MatchSettings {
    14 Mode mode = Mode::VsCpu;
    15 Difficulty difficulty = Difficulty::Normal;
    16 };
    17  
    18 constexpr int kWinsNeeded = 2; // 3本勝負:先に2本 / best of three: first to two
    19 constexpr int kMaxRounds = 5; // 引き分けが続いたら5本目で終わり / draws end the match after round 5
    20 constexpr int kRoundSeconds = 60;

ファイル: /dev/null | b/games/fighter/src/menu_keys.hh

前新
@@ -0,0 +1,13 @@
    1 // メニューのキー(タイトル・一時停止・勝利画面で共通。1Pと2Pのどちらのキーでも) / menu keys (shared by the title,
    2 // pause and win screens; either player's keys work)
    3 #pragma once
    4  
    5 #include "engine/input.hh"
    6  
    7 inline bool menuUp(const Input &in) { return in.pressed(GLFW_KEY_W) || in.pressed(GLFW_KEY_UP); }
    8 inline bool menuDown(const Input &in) { return in.pressed(GLFW_KEY_S) || in.pressed(GLFW_KEY_DOWN); }
    9 inline bool menuLeft(const Input &in) { return in.pressed(GLFW_KEY_A) || in.pressed(GLFW_KEY_LEFT); }
    10 inline bool menuRight(const Input &in) { return in.pressed(GLFW_KEY_D) || in.pressed(GLFW_KEY_RIGHT); }
    11 inline bool menuConfirm(const Input &in) {
    12 return in.pressed(GLFW_KEY_SPACE) || in.pressed(GLFW_KEY_ENTER) || in.pressed(GLFW_KEY_F) || in.pressed(GLFW_KEY_K);
    13 }

ファイル: /dev/null | b/games/fighter/src/pause_scene.cc

前新
@@ -0,0 +1,37 @@
    1 // 一時停止:対戦の上に重ねる / pause: an overlay on top of the fight
    2 #include "hud.hh"
    3 #include "menu_keys.hh"
    4 #include "scenes.hh"
    5  
    6 #include <algorithm>
    7 #include <memory>
    8  
    9 void PauseScene::update(float dt) {
    10 time += dt;
    11 Input &in = g.input;
    12 if (in.pressed(GLFW_KEY_ESCAPE) || in.pressed(GLFW_KEY_P)) {
    13 scenes().pop();
    14 return;
    15 }
    16 if (menuUp(in) || menuDown(in)) selected = 1 - selected;
    17 if (menuConfirm(in)) {
    18 if (selected == 0) scenes().pop();
    19 else scenes().replaceAll(std::make_unique<TitleScene>(g), {.duration = 0.8f});
    20 }
    21 }
    22  
    23 void PauseScene::drawUi(float /*alpha*/) {
    24 SpriteBatch &b = g.batch;
    25 b.begin(g.screen.matrix());
    26 float dim = std::min(1.0f, time / 0.2f) * 0.55f; // 0.2秒で暗くなる / darkens over 0.2 s
    27 b.drawRect({0, 0, 1280, 720}, {0.05f, 0.04f, 0.08f, dim});
    28 Rect panel = {440, 230, 400, 230};
    29 b.drawRect(panel, {0.11f, 0.09f, 0.15f, 0.92f});
    30 b.drawRectOutline(panel, kGold, 2.0f);
    31 g.ui.draw(b, "一時停止 / PAUSED", {640, 256}, {.color = kText, .scale = 2.0f, .align = TextAlign::Centre});
    32 const char *items[2] = {"再開 / Resume", "タイトルへ / Back to title"};
    33 for (int i = 0; i < 2; ++i)
    34 g.ui.draw(b, items[i], {640, 330.0f + 50.0f * static_cast<float>(i)},
    35 {.color = i == selected ? kGold : kText, .scale = 1.5f, .align = TextAlign::Centre});
    36 b.end();
    37 }

ファイル: /dev/null | b/games/fighter/src/result_scene.cc

前新
@@ -0,0 +1,92 @@
    1 // 勝利画面:勝った方を大きく、取ったラウンドの数、もう一度かタイトルへ / the win screen: the winner large, the rounds
    2 // won, rematch or back to the title
    3 #include "fight_scene.hh"
    4 #include "hud.hh"
    5 #include "menu_keys.hh"
    6 #include "scenes.hh"
    7  
    8 #include <cmath>
    9 #include <memory>
    10 #include <string>
    11  
    12 namespace {
    13  
    14 const char *const kNames[2] = {"HAYATE", "JIN"};
    15 const char *const kJapaneseNames[2] = {"ハヤテ", "ジン"};
    16 constexpr Vec2 kPivot = {0.5f, 116.0f / 120.0f};
    17  
    18 } // namespace
    19  
    20 ResultScene::ResultScene(Game &game, MatchSettings matchSettings, int matchWinner, const int roundWins[2])
    21 : g(game), settings(matchSettings), winner(matchWinner), wins{roundWins[0], roundWins[1]} {
    22 if (winner >= 0) pose.play(g.fighters[winner]->clip("win"));
    23 }
    24  
    25 void ResultScene::update(float dt) {
    26 time += dt;
    27 pose.update(dt);
    28 g.stage->update(dt);
    29 Input &in = g.input;
    30 if (in.pressed(GLFW_KEY_ESCAPE)) scenes().replace(std::make_unique<TitleScene>(g), {.duration = 0.8f});
    31 else if (menuConfirm(in) && time > 0.5f)
    32 scenes().replace(std::make_unique<FightScene>(g, settings), {.duration = 0.8f}); // もう一度 / rematch
    33 }
    34  
    35 void ResultScene::draw(float /*alpha*/) {
    36 SpriteBatch &b = g.batch;
    37 Camera2D view = Camera2D::screen(kViewSize);
    38 view.centre.x = kStageWidth * 0.5f;
    39 b.begin(view.matrix(), SpriteSort::Layer);
    40 g.stage->drawBack(b, view);
    41 float left = view.centre.x - kViewSize.x * 0.5f;
    42 if (winner >= 0) {
    43 // 勝者は2倍の大きさで勝ちポーズ、負けた方は奥で倒れている / the winner at twice the size in the victory pose, the
    44 // loser lying further back
    45 const SpriteSheet &ls = *g.fighters[1 - winner];
    46 Sprite lying = ls.sprite(ls.find("ko1"), {left + 470.0f, kGroundY - 26.0f}, kPivot);
    47 lying.flipX = true;
    48 lying.color = {0.75f, 0.7f, 0.8f, 1.0f};
    49 lying.layer = 1.0f;
    50 b.draw(lying);
    51 const SpriteSheet &ws = *g.fighters[winner];
    52 Sprite s = ws.sprite(pose.frame(), {left + 230.0f, kGroundY + 22.0f}, kPivot, 2.0f);
    53 s.layer = 2.0f;
    54 b.draw(s);
    55 } else {
    56 for (int i = 0; i < 2; ++i) {
    57 const SpriteSheet &sh = *g.fighters[i];
    58 Sprite s = sh.sprite(sh.find("idle0"), {left + (i == 0 ? 220.0f : 420.0f), kGroundY}, kPivot);
    59 s.flipX = i == 1;
    60 s.layer = 2.0f;
    61 b.draw(s);
    62 }
    63 }
    64 g.stage->drawFront(b, view);
    65 b.end();
    66  
    67 b.begin(Camera2D::screen(kViewSize).matrix(), SpriteSort::Layer);
    68 TextStyle sub = {.color = kText, .scale = 2.0f, .align = TextAlign::Centre, .layer = 11.5f, .shadow = kOutline};
    69 if (winner >= 0) {
    70 drawBigText(b, g.pixel, std::string(kNames[winner]) + " WINS!", {430, 70}, kGold, 4.0f);
    71 g.pixel.draw(b, std::string(kJapaneseNames[winner]) + "の勝利", {430, 102}, sub);
    72 } else {
    73 drawBigText(b, g.pixel, "DRAW GAME", {320, 70}, kText, 4.0f);
    74 g.pixel.draw(b, "引き分け", {320, 102}, sub);
    75 }
    76 // 取ったラウンド / the rounds won
    77 std::string score = std::to_string(wins[0]) + " - " + std::to_string(wins[1]);
    78 drawBigText(b, g.pixel, score, {winner >= 0 ? 430.0f : 320.0f, 150}, kText, 3.0f);
    79 g.pixel.draw(b, "HAYATE JIN", {winner >= 0 ? 430.0f : 320.0f, 172},
    80 {.color = kText, .align = TextAlign::Centre, .layer = 11.5f, .shadow = kOutline});
    81 b.end();
    82 }
    83  
    84 void ResultScene::drawUi(float /*alpha*/) {
    85 SpriteBatch &b = g.batch;
    86 b.begin(g.screen.matrix());
    87 b.drawRect({0, 688, 1280, 32}, {0.11f, 0.09f, 0.15f, 0.75f});
    88 float a = 0.55f + 0.45f * std::cos(time * 4.0f);
    89 g.ui.draw(b, "Space / F もう一度 / rematch Esc タイトルへ / title", {640, 694},
    90 {.color = {0.91f, 0.88f, 0.82f, a}, .align = TextAlign::Centre});
    91 b.end();
    92 }

ファイル: /dev/null | b/games/fighter/src/scenes.hh

前新
@@ -0,0 +1,59 @@
    1 // 対戦以外のシーン:タイトル、一時停止、勝利画面 / the scenes besides the fight: title, pause, win screen
    2 #pragma once
    3  
    4 #include "game.hh"
    5 #include "match.hh"
    6  
    7 #include "engine/animation.hh"
    8 #include "engine/scene.hh"
    9  
    10 #include <string>
    11  
    12 // タイトル:遊び方と難易度を選ぶ。後ろで舞台がゆっくり流れる / the title: pick the mode and difficulty; the stage pans
    13 // slowly behind
    14 class TitleScene : public Scene {
    15 public:
    16 explicit TitleScene(Game &game) : g(game) {}
    17 void update(float dt) override;
    18 void draw(float alpha) override;
    19 void drawUi(float alpha) override;
    20  
    21 private:
    22 Game &g;
    23 float time = 0.0f;
    24 int selected = 0;
    25 };
    26  
    27 // 一時停止(上に重ねる) / pause (an overlay)
    28 class PauseScene : public Scene {
    29 public:
    30 explicit PauseScene(Game &game) : g(game) {}
    31 bool isOverlay() const override { return true; }
    32 void update(float dt) override;
    33 void draw(float /*alpha*/) override {}
    34 void drawUi(float alpha) override;
    35  
    36 private:
    37 Game &g;
    38 float time = 0.0f;
    39 int selected = 0;
    40 };
    41  
    42 // 勝利画面:勝った方の勝ちポーズ、取った本数。もう一度・タイトルへ / the win screen: the winner's victory pose and the
    43 // rounds won; rematch or back to the title
    44 class ResultScene : public Scene {
    45 public:
    46 // winner = 0 / 1、-1 = 引き分け / winner = 0 / 1, -1 = a draw game
    47 ResultScene(Game &game, MatchSettings settings, int winner, const int wins[2]);
    48 void update(float dt) override;
    49 void draw(float alpha) override;
    50 void drawUi(float alpha) override;
    51  
    52 private:
    53 Game &g;
    54 MatchSettings settings;
    55 int winner;
    56 int wins[2];
    57 float time = 0.0f;
    58 Animator pose;
    59 };

ファイル: /dev/null | b/games/fighter/src/stage.cc

前新
@@ -0,0 +1,90 @@
    1 // スクロールする舞台 / the scrolling stage
    2 #include "stage.hh"
    3  
    4 #include "engine/sprite_sheet.hh"
    5  
    6 #include <algorithm>
    7 #include <cmath>
    8 #include <string>
    9  
    10 namespace {
    11  
    12 constexpr float kPetalFactor = 1.15f; // 花びらは地面より少し手前 / petals are a little in front of the ground
    13 constexpr int kPetals = 28;
    14  
    15 } // namespace
    16  
    17 std::optional<Stage> Stage::load() {
    18 struct Spec {
    19 const char *file;
    20 float factor, layer;
    21 bool front;
    22 };
    23 // 幅は 640 + factor × (1024 − 640):カメラが端に着いたとき、層もちょうど端 / widths are 640 + factor × (1024 − 640):
    24 // when the camera reaches an edge, so does every layer (the images have these widths)
    25 const Spec specs[] = {
    26 {"stage_sky", 0.05f, 0.0f, false}, {"stage_far", 0.25f, 0.1f, false}, {"stage_mid", 0.5f, 0.2f, false},
    27 {"stage_ground", 1.0f, 0.3f, false}, {"stage_front", 1.3f, 12.0f, true},
    28 };
    29 Stage stage;
    30 for (const Spec &s : specs) {
    31 std::optional<Texture2D> t = loadSpriteTexture(std::string("games/fighter/assets/") + s.file + ".png");
    32 if (!t) return std::nullopt;
    33 (s.front ? stage.front : stage.back).push_back({std::move(*t), s.factor, s.layer});
    34 }
    35 for (int i = 0; i < kPetals; ++i) {
    36 Petal p{{stage.rng.range(0.0f, 760.0f), stage.rng.range(-40.0f, 300.0f)},
    37 {stage.rng.range(-28.0f, -12.0f), stage.rng.range(14.0f, 26.0f)}, stage.rng.range(0.0f, 6.28f)};
    38 stage.petals.push_back(p);
    39 }
    40 return stage;
    41 }
    42  
    43 float Stage::clampCamera(float centreX, float viewWidth) {
    44 float half = viewWidth * 0.5f;
    45 return std::clamp(centreX, half, kStageWidth - half);
    46 }
    47  
    48 // 視差:その層のカメラはfactor倍だけ動く。画面の左端が舞台のxなら、層は −x·factor だけずらして描く
    49 // Parallax: a layer's camera moves `factor` times as far. If the view's left edge is at stage x, the layer is drawn
    50 // shifted by −x·factor
    51 void Stage::drawLayer(SpriteBatch &batch, const ParallaxLayer &l, const Camera2D &camera) const {
    52 float left = camera.centre.x - camera.viewSize.x * 0.5f;
    53 Vec2 size = {static_cast<float>(l.texture.width()), static_cast<float>(l.texture.height())};
    54 // ワールドの座標で描く:層の左端 = left − left·factor(整数に丸めてピクセルをそろえる)
    55 // Drawn in world coordinates: the layer's left edge = left − left·factor (rounded to whole pixels)
    56 float x = left - std::round(left * l.factor);
    57 // 縦は動かない(カメラの高さは固定):層の上端はワールドのy = 0 / no vertical parallax (the camera height is fixed):
    58 // a layer's top is at world y = 0
    59 batch.draw({.texture = &l.texture, .position = {x, 0.0f}, .size = size, .layer = l.layer});
    60 }
    61  
    62 void Stage::drawBack(SpriteBatch &batch, const Camera2D &camera) const {
    63 for (const ParallaxLayer &l : back) drawLayer(batch, l, camera);
    64 }
    65  
    66 void Stage::drawFront(SpriteBatch &batch, const Camera2D &camera) const {
    67 float left = camera.centre.x - camera.viewSize.x * 0.5f;
    68 // 花びら:手前の層(factor 1.15)の上を左下へ。画面の外に出たら上から戻る(760幅で輪になる)
    69 // Petals: drift down-left on a 1.15 layer, wrapping round a 760-wide band
    70 for (const Petal &p : petals) {
    71 float x = std::fmod(p.position.x - left * kPetalFactor, 760.0f);
    72 if (x < 0.0f) x += 760.0f;
    73 float sway = 4.0f * std::sin(time * 2.0f + p.phase);
    74 Vec2 at = {left + std::round(x - 60.0f + sway), std::round(p.position.y)};
    75 bool flat = std::sin(time * 5.0f + p.phase) > 0.3f; // くるくる回る:2×2と1×2 / tumbling: 2 × 2 or 1 × 2
    76 batch.drawRect({at.x, at.y, flat ? 2.0f : 1.0f, 2.0f}, hexColor(0xffc8dcff), 11.0f);
    77 }
    78 for (const ParallaxLayer &l : front) drawLayer(batch, l, camera);
    79 }
    80  
    81 void Stage::update(float dt) {
    82 time += dt;
    83 for (Petal &p : petals) {
    84 p.position += p.velocity * dt;
    85 if (p.position.y > 370.0f) {
    86 p.position.y = -10.0f;
    87 p.position.x = rng.range(0.0f, 760.0f);
    88 }
    89 }
    90 }

ファイル: /dev/null | b/games/fighter/src/stage.hh

前新
@@ -0,0 +1,52 @@
    1 // スクロールする舞台:視差の層(遠いほどゆっくり動く)、カメラの範囲、舞い散る花びら
    2 // The scrolling stage: parallax layers (the farther, the slower), the camera's limits, falling petals
    3 #pragma once
    4  
    5 #include "engine/camera2d.hh"
    6 #include "engine/rng.hh"
    7 #include "engine/sprite_batch.hh"
    8 #include "engine/texture.hh"
    9  
    10 #include <optional>
    11 #include <vector>
    12  
    13 constexpr float kStageWidth = 1024.0f; // 舞台の幅(ワールドのピクセル)。見えるのは640 / the stage width (world pixels);
    14 // 640 are visible
    15  
    16 // 一枚の層:factor = カメラに対する動きの割合(0 = 動かない空、1 = 地面と同じ、> 1 = 手前)
    17 // One layer: factor = how much of the camera's motion it follows (0 = a still sky, 1 = with the ground, > 1 = in
    18 // front)
    19 struct ParallaxLayer {
    20 Texture2D texture;
    21 float factor;
    22 float layer; // SpriteSort::Layerの順番 / order for SpriteSort::Layer
    23 };
    24  
    25 class Stage {
    26 public:
    27 // games/fighter/assets/stage_*.png を読む / loads games/fighter/assets/stage_*.png
    28 static std::optional<Stage> load();
    29  
    30 // カメラの中心のxを舞台の中に収める:画面の端が舞台の外を映さない / clamps the camera center's x so the view never
    31 // shows anything outside the stage
    32 static float clampCamera(float centreX, float viewWidth);
    33 // ファイターの後ろの層(空・山・寺・地面)と、前の層(灯籠・花びら)。cameraはワールドのカメラ
    34 // The layers behind the fighters (sky, mountains, temple, ground) and in front (lanterns, petals). camera is the
    35 // world camera
    36 void drawBack(SpriteBatch &batch, const Camera2D &camera) const;
    37 void drawFront(SpriteBatch &batch, const Camera2D &camera) const;
    38 void update(float dt); // 花びら / the petals
    39  
    40 private:
    41 struct Petal {
    42 Vec2 position; // 画面の座標(花びらは手前の層:factor 1.15) / screen-ish coordinates (petals live on a 1.15 layer)
    43 Vec2 velocity;
    44 float phase;
    45 };
    46 void drawLayer(SpriteBatch &batch, const ParallaxLayer &l, const Camera2D &camera) const;
    47  
    48 std::vector<ParallaxLayer> back, front;
    49 std::vector<Petal> petals;
    50 Rng rng{32};
    51 float time = 0.0f;
    52 };

ファイル: /dev/null | b/games/fighter/src/title_scene.cc

前新
@@ -0,0 +1,105 @@
    1 // タイトル:遊び方と難易度を選ぶ / the title: pick a mode and the difficulty
    2 #include "fight_scene.hh"
    3 #include "hud.hh"
    4 #include "menu_keys.hh"
    5 #include "scenes.hh"
    6  
    7 #include <cmath>
    8 #include <memory>
    9 #include <string>
    10  
    11 namespace {
    12  
    13 struct Item {
    14 const char *english, *japanese;
    15 Mode mode;
    16 };
    17 constexpr Item kItems[] = {
    18 {"1P VS CPU", "1P 対 CPU", Mode::VsCpu},
    19 {"2P VS", "2人で対戦", Mode::TwoPlayers},
    20 {"CPU VS CPU", "CPU 対 CPU", Mode::CpuVsCpu},
    21 {"TRAINING", "練習", Mode::Training},
    22 };
    23 constexpr int kItemCount = 5; // 4つの遊び方 + 難易度 / four modes + the difficulty
    24 const char *const kDifficultyJa[] = {"易しい", "普通", "難しい"};
    25  
    26 // タイトルの後ろの二人(舞台のワールド座標、足元) / the two fighters behind the title (stage world coordinates, feet)
    27 constexpr float kTitleX[2] = {kStageWidth * 0.5f - 210.0f, kStageWidth * 0.5f + 210.0f};
    28  
    29 } // namespace
    30  
    31 void TitleScene::update(float dt) {
    32 time += dt;
    33 g.stage->update(dt);
    34 Input &in = g.input;
    35 if (in.pressed(GLFW_KEY_ESCAPE)) {
    36 scenes().pop(); // 最後のシーン:終了 / the last scene: quit
    37 return;
    38 }
    39 if (menuUp(in)) selected = (selected + kItemCount - 1) % kItemCount;
    40 if (menuDown(in)) selected = (selected + 1) % kItemCount;
    41 int d = static_cast<int>(g.difficulty);
    42 if (menuLeft(in)) g.difficulty = static_cast<Difficulty>((d + 2) % 3);
    43 if (menuRight(in)) g.difficulty = static_cast<Difficulty>((d + 1) % 3);
    44 if (menuConfirm(in) && selected < 4)
    45 scenes().replace(std::make_unique<FightScene>(g, MatchSettings{kItems[selected].mode, g.difficulty}),
    46 {.duration = 0.8f});
    47 }
    48  
    49 void TitleScene::draw(float /*alpha*/) {
    50 SpriteBatch &b = g.batch;
    51 // カメラはゆっくり左右に:視差の層がそれぞれの速さで動く / the camera drifts left and right: each parallax layer
    52 // moves at its own speed
    53 Camera2D view = Camera2D::screen(kViewSize);
    54 view.centre.x = std::round(kStageWidth * 0.5f + 150.0f * std::sin(time * 0.3f));
    55 b.begin(view.matrix(), SpriteSort::Layer);
    56 g.stage->drawBack(b, view);
    57 for (int i = 0; i < 2; ++i) {
    58 const SpriteSheet &sheet = *g.fighters[i];
    59 const AnimationClip *idle = sheet.clip("idle");
    60 int frame = idle->frames[static_cast<size_t>(time * idle->fps + static_cast<float>(i) * 2.0f) % idle->frames.size()];
    61 Sprite s = sheet.sprite(frame, {kTitleX[i], kGroundY}, {0.5f, 116.0f / 120.0f});
    62 s.flipX = i == 1;
    63 s.layer = 2.0f;
    64 b.draw(s);
    65 }
    66 g.stage->drawFront(b, view);
    67 b.end();
    68  
    69 b.begin(Camera2D::screen(kViewSize).matrix(), SpriteSort::Layer);
    70 drawBigText(b, g.pixel, "FIGHTER", {320, 62}, kGold, 6.0f);
    71 g.pixel.draw(b, "2D 対戦アクション", {320, 104},
    72 {.color = kText, .scale = 2.0f, .align = TextAlign::Centre, .layer = 11.0f, .shadow = kOutline});
    73 // メニュー:英語と日本語の二列 / the menu: English and Japanese columns
    74 Rect panel = {176, 150, 288, 116};
    75 b.drawRect(panel, {0.11f, 0.09f, 0.15f, 0.78f}, 10.0f);
    76 b.drawRectOutline(panel, kGold, 1.0f, 10.1f);
    77 for (int i = 0; i < kItemCount; ++i) {
    78 bool on = i == selected;
    79 Vec4 c = on ? kGold : kText;
    80 float y = panel.y + 10.0f + 20.0f * static_cast<float>(i);
    81 std::string en, ja;
    82 if (i < 4) {
    83 en = kItems[i].english;
    84 ja = kItems[i].japanese;
    85 } else {
    86 en = std::string("< ") + difficultyName(g.difficulty) + " >";
    87 ja = std::string("難易度 ") + kDifficultyJa[static_cast<int>(g.difficulty)];
    88 }
    89 if (on) g.pixel.draw(b, ">", {panel.x + 10.0f, y}, {.color = c, .layer = 11.0f});
    90 g.pixel.draw(b, en, {panel.x + 24.0f, y}, {.color = c, .layer = 11.0f});
    91 g.pixel.draw(b, ja, {panel.x + 160.0f, y}, {.color = c, .layer = 11.0f});
    92 }
    93 b.end();
    94 }
    95  
    96 void TitleScene::drawUi(float /*alpha*/) {
    97 SpriteBatch &b = g.batch;
    98 b.begin(g.screen.matrix());
    99 b.drawRect({0, 688, 1280, 32}, {0.11f, 0.09f, 0.15f, 0.75f});
    100 // 点滅する案内 / a blinking prompt
    101 float a = 0.55f + 0.45f * std::cos(time * 4.0f);
    102 g.ui.draw(b, "W S 選ぶ・A D 難易度・Space / F 決定・Esc 終了 select / difficulty / start / quit", {640, 694},
    103 {.color = {0.91f, 0.88f, 0.82f, a}, .align = TextAlign::Centre});
    104 b.end();
    105 }


コメント(0)

まだコメントはありません。