29. Space Invaders Part 3: Scenes, Score and Polish
Chapter 28 made Invaders playable: the ship and the aliens shoot, the shields erode pixel by pixel, things explode, and the game ends.
But it's still a test bench: it starts straight in the arena, the side panels show developer numbers, a cleared formation simply resets in place, and "game over" is a line of text.
This chapter turns it into a finished arcade game.
We add a title screen, score, high score, lives and a HUD, a pause menu and a game-over screen, waves that get harder, the bonus saucer and an extra ship.
Then comes the part that makes a game feel good rather than merely work: screen shake, flashes, and a CRT finish drawn by a shader.
Almost everything here is game code on top of chapter 26's toolkit.
The one new rendering technique is the CRT pass, which draws the PixelCanvas texture through our own fragment shader instead of copying it, so it's a short return to chapter 17's post-processing.
The design question that runs through the whole chapter is simpler and more important: which data dies with a scene, and which data outlives it?
29.1 What we're building
The finished game, right after the saucer was shot for 300 points:
The clip starts on the title, fades into wave 1, shoots through the formation, loses a ship (red flash and shake) and shoots the saucer for 100 points:
The controls:
- Title: Space or Enter starts a game, Esc quits
- Play: ← → or A D move, Space, ↑ or W fire, P or Esc pause
- Pause menu: ↑ ↓ or W S select, Space or Enter confirm, P or Esc resume
- Any time: C toggles the CRT finish, Tab shows the developer line
- Developer keys: I switches the formation renderer, B shows the collision boxes, = and − change the march rate, N skips to the next wave
Starting from chapter 28, the changes are all inside games/invaders/:
src/layout.hh(new): the screen layout from chapter 27–28'sgame.hh, plus the saucer's lanesrc/game.hh:WaveSettings,Run, the biggerGame, and four scene classes:TitleScene,PlayScene,PauseScene,GameOverScenesrc/game.cc(new):waveSettingsanddrawTinyTextsrc/backdrop.hh,src/backdrop.cc(new): the stars, the ground and the side panels, shared by the title and the play scenesrc/title_scene.cc(new): the title screensrc/play_scene.cc: phases, scoring, the saucer, popups, shake and flashes, the HUDsrc/menus.cc(new): the pause and game-over overlayssrc/effects.hh,src/effects.cc:ShakeandScreenFlashnext to chapter 28's particlessrc/crt.hh,src/crt.cc,shaders/crt.frag(new): the CRT finishsrc/main.cc: loads thepixel5font, the CRT filter and the backdrop, starts on the title, handles C and TabREADME.md: the full controls, the points and the files
formation* and shields* don't change.
The executable gets five more source files:
# Invaders(第27〜29章):エンジンだけを使う一つの実行ファイル。プロジェクトのルートから ./build/games/invaders/invaders
# Invaders (chapters 27-29): one executable that only uses the engine. Run ./build/games/invaders/invaders from the
# project root
add_executable(invaders
src/main.cc
src/game.cc
src/title_scene.cc
src/play_scene.cc
src/menus.cc
src/backdrop.cc
src/formation.cc
src/formation_renderer.cc
src/shields.cc
src/effects.cc
src/crt.cc)
target_include_directories(invaders PRIVATE src)
target_link_libraries(invaders PRIVATE engine)
enable_warnings(invaders)
set_working_directory(invaders)
You don't have to re-run CMake by hand: CMake has read this file since chapter 27, so the next build notices that it changed and re-runs CMake by itself (section 27.2).
As in every game chapter, nothing outside games/invaders/ changes: no engine edits, no shared assets.
29.2 Scene reloading and data that persists
In chapter 28, PlayScene owned everything: the formation, the shields, the bullets, and also lives, kills and a waves counter.
That was fine, because the only way to leave the scene was "play again", which replaced it with a fresh one, and a fresh game should start with three lives.
This chapter adds waves, and I want a cleared wave to work the same way: replace the play scene with a brand-new one for the next wave.
That's what "level reload" means here, and it's the easiest way to make sure nothing from the old wave leaks into the new one: no half-eaten shields, no bullet still in flight, no saucer, no stale timer.
The constructor builds a wave, the destructor throws it away, and no "reset everything" function has to remember every member.
But now some data must survive the replace.
If the score lived in PlayScene, clearing wave 1 would reset it to 0.
So the data is split by how long it must live:
- The whole program (
mainandGame): the window, input, loop, batch, fonts, sprites, the backdrop's stars, the CRT filter, the gameplayRng, the developer toggles, and the high score. - One game (
Game::run): score, lives, the wave number and whether the extra ship was given. The title resets it. - One wave (
PlayScene): everything on the playfield.
Here are the two structs:
// 一回の遊び(タイトルで作り直す)。波が変わっても場面をまたいで残る / one game (reset on the title). Survives the
// scene reload between waves
struct Run {
int score = 0;
int lives = kStartLives;
int wave = 1;
bool extraLife = false;
};
// ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference
struct Game {
Window &window;
Input &input;
GameLoop &loop;
SpriteBatch &batch;
FormationRenderer &formationRenderer;
const Font &ui; // mono16:画面の解像度の文字 / text at screen resolution
const Font &tiny; // pixel5:キャンバスの中のHUD(3 × 5、大文字と数字) / the canvas HUD (3 × 5, capitals
// and digits)
const SpriteSheet &sprites; // games/invaders/assets/sprites.atlas
const Image &shieldArt; // 防壁の絵(CPU側、削る元) / the shield art (CPU side, what gets eroded)
const Backdrop &backdrop; // 星と脇の板 / the stars and the side panels
Camera2D world; // 320 × 180のキャンバス / the 320 × 180 canvas
Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI
Viewport uiViewport;
Rng rng{27};
Run run{};
int hiScore = 0; // この起動の間だけ覚える(電源を入れたゲーム機と同じく0から) / remembered while the
// program runs (starts at 0, like an arcade machine just switched on)
bool instanced = true; // 隊列をインスタンシングで(I) / draw the formation instanced (I)
bool showBoxes = false; // 当たり判定の箱(B) / collision boxes (B)
bool crt = true; // ブラウン管風の仕上げ(C) / the CRT-style finish (C)
bool devInfo = false; // 開発用の数字(Tab) / developer numbers (Tab)
// 開発用の数字(Tabで画面の下に) / developer numbers (shown at the bottom with Tab)
int formationDrawCalls = 0, formationBytes = 0, shieldBytes = 0;
};
Game is chapter 26's "context struct" idea: main creates exactly one, every scene's constructor takes it by reference.
Because the scenes only hold a reference, a scene can be destroyed and recreated as often as we like; Game doesn't notice.
A few of the choices deserve a sentence each:
hiScorestarts at 0 and is kept only while the program runs, like an arcade cabinet that was just switched on. Saving it to a file is challenge 1.rnglives inGame, not in the scene. If each wave made its ownRng{27}, every wave would replay the same sequence of alien shots. With one generator for the whole program, wave 2 continues the sequence, so it plays differently from wave 1, and the whole run is still exactly repeatable from the start (which the screenshots rely on).- The backdrop has its own seed (
Rng sky(1978)in its constructor) and is created once inmain, so the stars stay where they are across every scene change. Run run{};with braces. Without an initializer,Game game{.window = window, …}inmainmakes GCC (-Wextra) and Clang (-Wmissing-field-initializers) warn "missing initializer for memberGame::run": a designated initializer list that skips a member without its own default initializer triggers it.run{}gives it one, so the member can be left out silently.
The rule I follow: put data in the shortest-lived owner that's still long enough.
Then a scene change cleans up by itself, and only the few things that really carry over are visible in one place.
29.3 The scene flow
Here are all the scenes and how they hand over to each other:
Every arrow between scenes is one of chapter 26's SceneManager requests: replace swaps the top scene, push puts an overlay on top, pop removes it, replaceAll empties the stack and starts over.
All of them are queued and applied after the update, and with a Transition they wait for the fade-out, so no scene is ever destroyed inside its own update.
main starts the stack with the title:
SceneManager scenes;
scenes.push(std::make_unique<TitleScene>(game));
and the title is where a game begins:
void TitleScene::update(float dt) {
time += dt;
ufoPrevX = ufoX;
ufoX += 30.0f * dt;
if (ufoX > kArenaRight + 40.0f) ufoX = ufoPrevX = kArenaLeft - 60.0f; // 戦場の外で一周 / loops outside the arena
if (g.input.pressed(GLFW_KEY_ESCAPE)) {
scenes().pop(); // 空になる → 終了 / empty → quit
return;
}
if (g.input.actionPressed("confirm")) {
g.run = Run{}; // 新しい遊び:点数0、残機3、第1波 / a new game: score 0, 3 lives, wave 1
// 円盤を止めておく(第26章の課題5の直し方。drawAlphaもフェードアウト中はalpha = 1で描く)
// hold the saucer still (the fix of ch26 challenge 5; drawAlpha also draws alpha = 1 during the fade-out)
ufoPrevX = ufoX;
scenes().replace(std::make_unique<PlayScene>(g), {.duration = 0.8f});
}
}
g.run = Run{} is the whole "new game" logic: score 0, three lives, wave 1, no extra ship yet.
The PlayScene is constructed right here, inside the title's update, but it only goes on the stack after the 0.4 s fade-out.
That's fine, because the constructor reads g.run.wave, which was just reset.
ufoPrevX = ufoX is the fix from chapter 26's challenge 5.
Nobody is updated during the 0.4 s fade-out, but drawing goes on, and interpolating between the saucer's previous and current position with an alpha that changes every frame would make the frozen saucer shuffle back and forth.
The engine already prevents that: during a fade-out SceneManager::drawAlpha hands every scene alpha = 1 (chapter 26).
With the previous position set to the current one, the title holds still by itself as well, so it doesn't depend on that detail of the manager.
Phases inside the play scene
Inside one wave, the play scene goes through phases.
Chapter 28 had two flags for this, shipDying and gameOver; with Ready and Cleared added, flags would multiply into combinations that make no sense ("dying and cleared and over?").
An enum says that exactly one phase is active:
enum class Phase { Ready, Playing, ShipDown, Cleared, Over };
with the time spent in it:
Game &g;
WaveSettings settings;
Phase phase = Phase::Ready;
float phaseTime = 0.0f;
bool leaving = false; // 次の波を頼んだ / the next wave was requested
setPhase changes the phase and restarts the clock, so every timed phase is just "if phaseTime is past my duration".
Why phases inside one scene and not more scenes?
Ready, Playing, ShipDown and Cleared all show the same playfield, which must keep its state across them: the ship explosion happens in the formation, the "WAVE 1 CLEAR" banner shows over the emptied arena.
Separate scenes would have to share the playfield between them, but owning a playfield is exactly what a scene is for.
Pause and game over are different: they cover the playfield and stop it, which is what an overlay is for.
PlayScene::update first handles the keys and the "dressing" that always moves (particles, impact flares, popups, shake, flashes, and the alien explosions outside Playing, where formation.update already advances them), and then switches on the phase:
switch (phase) {
case Phase::Ready:
// 「WAVE n」を見せる間は何も動かない / nothing moves while "WAVE n" is shown
if (phaseTime >= kReadyTime) setPhase(Phase::Playing);
return;
case Phase::Cleared:
// 全滅:少し待ってから、波の番号を上げて場面ごと作り直す(フェード付き)。隊列・防壁・弾は新品になり、
// 点数と残機はGame::runにあるので残る
// Wiped out: after a moment, raise the wave number and rebuild the whole scene (with a fade). Formation,
// shields and bullets start fresh; score and lives live in Game::run, so they stay
updateShot(dt);
if (phaseTime >= kClearedTime && !leaving) {
leaving = true;
++g.run.wave;
scenes().replace(std::make_unique<PlayScene>(g), {.duration = 1.0f});
}
return;
case Phase::ShipDown:
// 自機の爆発中:隊列も宇宙人の弾も止まる(元のゲームと同じ)。終わったら真ん中に戻るか、ゲームオーバー
// While the ship explodes the formation and the alien fire stop (as in the original). Afterwards the ship comes
// back in the middle, or the game is over
shipBoom.update(dt);
updateShot(dt);
if (phaseTime >= kShipBoomTime) {
if (g.run.lives > 0) {
playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f);
setPhase(Phase::Playing);
} else {
setPhase(Phase::Over);
bool newHigh = g.run.score > g.hiScore;
if (newHigh) g.hiScore = g.run.score;
printf("game over: score %d (wave %d)%s\n", g.run.score, g.run.wave, newHigh ? ", new high score" : "");
scenes().push(std::make_unique<GameOverScene>(g, newHigh));
}
}
return;
case Phase::Over:
return;
case Phase::Playing:
break;
}
Every phase except Playing returns early, so the rest of update (moving the ship, the march, the saucer, the shots) is chapter 28's battle, now running only in Playing.
- Ready (
kReadyTime= 1.6 s): "WAVE n / GET READY" blinks and nothing moves. The player gets a moment to see the new formation. - ShipDown (1.4 s, chapter 28's ship explosion): the march and the alien fire stop, but
updateShotstill runs, so the ship's last bullet can still hit something and score. - Over: the game-over overlay is on top. The play scene isn't updated any more, but it stays on the stack and is drawn below the overlay: the frozen arena is the background of the game-over screen.
Game over is also where the high score is updated, once, with the final score; the HUD shows max(hiScore, score) while you play, so it already looks like a high score is being set.
Here is the whole flow in one take: the title (HI-SCORE 00000), wave 1, the N key clears it, "WAVE 1 CLEAR", the fade, wave 2, the pause menu, three ship deaths, GAME OVER with NEW HIGH SCORE!, and back on the title the high score shows 00010:
29.4 The wave reload
The Cleared case above is the level reload.
When the last alien's explosion has finished (formation.cleared()), the scene flashes white, stops the saucer and the alien bullets, and switches to Cleared.
After 1.5 s of "WAVE n CLEAR" it raises the wave number in Game::run and asks the manager to replace it with a new PlayScene, with a 1.0 s fade: 0.5 s to black, the switch, 0.5 s back.
The leaving flag matters.
Cleared keeps running after the request, because the request doesn't take effect immediately: SceneManager::update starts the fade-out after this update, and during the fade-out nobody is updated.
So in practice the second request would never be made, but only because of how the manager happens to schedule things.
Without the flag, a transition with duration = 0 (or any change in the manager) would let the condition phaseTime >= kClearedTime stay true for several updates, queue several new scenes, and raise the wave number several times.
Request a scene change once, and make the "once" explicit.
The other half of the reload is the constructor, which builds the wave from nothing but Game:
PlayScene::PlayScene(Game &game) : g(game), settings(waveSettings(game.run.wave)) {
const char *names[3][2] = {{"jelly_0", "jelly_1"}, {"beetle_0", "beetle_1"}, {"blob_0", "blob_1"}};
for (int k = 0; k < 3; ++k)
for (int p = 0; p < 2; ++p) frames[k][p] = g.sprites.find(names[k][p]);
shipFrame = g.sprites.find("ship");
shotFrame = g.sprites.find("shot");
splatFrame = g.sprites.find("splat");
ufoFrame = g.sprites.find("ufo");
boomFrames[0] = g.sprites.find("alien_boom_0");
boomFrames[1] = g.sprites.find("alien_boom_1");
zigClip = g.sprites.clip("zig");
boltClip = g.sprites.clip("bolt");
shipBoomClip = g.sprites.clip("ship_boom");
// 隊列:波が進むほど低い所から、速く / the formation: lower and faster as the waves go on
formation.minX = kArenaLeft + 2.0f;
formation.maxX = kArenaRight - 2.0f;
formation.reset(formationStartX(), settings.top);
formation.rate = settings.marchRate;
// 防壁4つを戦場に等間隔で(中心 76, 132, 188, 244)。波ごとに新品 / four shields evenly across the arena (centers
// 76, 132, 188, 244). New ones every wave
Vec2 shieldPos[kShieldCount];
for (int i = 0; i < kShieldCount; ++i)
shieldPos[i] = {kArenaLeft + (kArenaRight - kArenaLeft) * (static_cast<float>(i) + 0.5f) / kShieldCount - kShieldW / 2,
kShieldY};
shields = Shields::create(g.shieldArt, shieldPos);
if (!shields) { // 防壁が無いと遊べない(理由はcreateが書いた) / no game without shields (create logged why)
fprintf(stderr, "防壁を作れないので終了 / cannot create the shields: quitting\n");
g.window.close(); // 防壁を使う関数は何もしない / the functions that use the shields do nothing
}
playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f);
ufoTimer = g.rng.range(8.0f, 14.0f); // 最初の円盤は早めに / the first saucer comes early
}
Everything the wave needs is derived from g.run.wave and the shared assets.
New shields mean a new 88 × 16 texture from chapter 28's Shields::create, and the old one is freed by the old scene's destructor: RAII does the cleanup of GPU objects for free.
If create fails, the scene logs it and closes the window, as in chapter 28 (update and draw begin with if (!shields) return;).
Creating one small texture once per wave costs nothing; if a level had to load megabytes, I'd keep the loaded data in Game and only rebuild the per-wave state, which is the same split again.
Reloading is not the only way.
Chapter 28 did it in place: formation.reset(…) and fireTimer = 1.0f.
That's less code at first, but every new member (the saucer, the popups, the shake, the flash, the phase) would need a line in the reset, and the bug is always the line someone forgot: a saucer that's still crossing the screen when wave 2 starts, or a flash that carries over.
With a fresh scene, forgetting is impossible.
The price is that the scene can't keep anything by accident, so whatever should carry over has to be moved out deliberately, which is the point of section 29.2.
29.5 Waves that speed up
Chapter 27's march already speeds up by itself: the formation moves rate aliens per second, one at a time, so with fewer aliens each one's turn comes around sooner.
At wave 1's 60 aliens per second, a full formation of 55 takes 55 / 60 ≈ 0.92 s for one pass; the last alien moves 60 times per second.
That's the speed-up inside a wave.
On top of it, every wave starts harder:
// 波ごとの難しさ(第29章):先へ進むほど低い所から始まり、速く行進し、よく撃つ
// Difficulty per wave (chapter 29): later waves start lower, march faster and shoot more
struct WaveSettings {
float top; // 隊列の一番上の行 / the formation's top row
float marchRate; // 1秒に動く宇宙人の数 / aliens moved per second
float fireMin, fireMax; // 宇宙人が撃つ間隔(秒) / seconds between alien shots
float shotSpeed; // 宇宙人の弾の速さ / alien bullet speed
int maxShots; // 画面に出せる宇宙人の弾 / alien bullets on screen at once
};
WaveSettings waveSettings(int wave);
// 波wの難しさ。8波目からは同じ / the difficulty of wave w; constant from wave 8
WaveSettings waveSettings(int wave) {
int w = std::clamp(wave, 1, 8) - 1;
float faster = 1.0f + 0.15f * static_cast<float>(w);
return {.top = kFormationTop + 6.0f * static_cast<float>(std::min(w, 4)), // 最大4段(24ピクセル)低く / up to 4
// steps (24 px) lower
.marchRate = 60.0f * faster,
.fireMin = 0.5f / faster,
.fireMax = 1.1f / faster,
.shotSpeed = 75.0f + 7.5f * static_cast<float>(w),
.maxShots = 3 + (w >= 2) + (w >= 5)};
}
With = wave − 1 (clamped to 0…7), the factor is ; the march rate is multiplied by it, the fire interval divided by it:
| wave | top row y | march (aliens/s) | alien fire interval (s) | alien bullet (px/s) | max alien bullets |
|---|---|---|---|---|---|
| 1 | 28 | 60 | 0.50–1.10 | 75 | 3 |
| 2 | 34 | 69 | 0.43–0.96 | 82.5 | 3 |
| 3 | 40 | 78 | 0.38–0.85 | 90 | 4 |
| 4 | 46 | 87 | 0.34–0.76 | 97.5 | 4 |
| 5 | 52 | 96 | 0.31–0.69 | 105 | 4 |
| 6 | 52 | 105 | 0.29–0.63 | 112.5 | 5 |
| 7 | 52 | 114 | 0.26–0.58 | 120 | 5 |
| 8 and later | 52 | 123 | 0.24–0.54 | 127.5 | 5 |
Some reasoning behind the numbers:
- The start height goes down by one march step (6 px) per wave, at most 4 steps. Every 6 px is one drop the formation doesn't have to make before it reaches the shields, so it's a real difficulty step; the arcade did the same. Starting even lower than 52 would put the bottom row (52 + 4 × 14 + 10 = 118) too close to the shields at 136.
- A cap at wave 8. Without it the game would become impossible instead of hard; with it, a good player can go on and the score keeps meaning something.
settingsreplaces chapter 28's constantskAlienShotSpeedandkMaxAlienShots. The battle code readssettings.shotSpeed,settings.maxShotsand the fire interval fromsettingsand is otherwise unchanged.maxShotsuses the fact thatboolconverts to 0 or 1:3 + (w >= 2) + (w >= 5)is 3, 4 from wave 3, 5 from wave 6.
In later waves the formation's bottom row reaches the "WAVE n" banner at y 104 (it starts touching it in wave 3, and in wave 5 above it's well behind it), so the Ready phase draws a dark translucent band behind the text.
The developer key N kills every alien without points, which sends you to Cleared and then the next wave; that's how the wave 5 picture was made without playing four waves.
29.6 Score, the saucer and the extra ship
Points are per alien kind, as in the arcade:
| target | points |
|---|---|
| jelly (top row) | 30 |
| beetle (rows 2–3) | 20 |
| blob (rows 4–5) | 10 |
| saucer | 50, 100, 150 or 300 |
A full wave is 11 × 30 + 22 × 20 + 22 × 10 = 330 + 440 + 220 = 990 points.
Every score change goes through one function:
void PlayScene::addScore(int points) {
g.run.score += points;
scoreFlash = 0.15f;
// 1500点で一度だけ1機増える / one extra ship at 1500 points, once
if (!g.run.extraLife && g.run.score >= kExtraLifeScore) {
g.run.extraLife = true;
++g.run.lives;
popup({shipBox().centre().x, kPlayerY - 8.0f}, "1UP", hexColor(0x9adc48ff));
printf("extra life at %d\n", g.run.score);
}
}
One function means one place for the side effects: the HUD digits flash for 0.15 s, and the extra ship is checked.
The extra ship comes once, at 1500 points (kExtraLifeScore), which is about a wave and a half; a green "1UP" floats up above the ship.
extraLife lives in Run, not in the scene, for the same reason as the score: if it were a scene member, every new wave would forget that the bonus was already given, and the player would get another ship at the first kill of wave 3.
The saucer
The saucer (the "mystery ship") crosses the top of the arena now and then:
void PlayScene::updateUfo(float dt) {
if (!ufo.active) {
// 時々、宇宙人が8匹以上いる間だけ / now and then, only while 8 or more aliens are left
ufoTimer -= dt;
if (ufoTimer <= 0.0f && formation.alive() >= 8) {
ufo.active = true;
ufo.direction = g.rng.chance(0.5f) ? 1.0f : -1.0f;
ufo.x = ufo.prevX = ufo.direction > 0.0f ? kArenaLeft - 18.0f : kArenaRight;
printf("saucer from the %s\n", ufo.direction > 0.0f ? "left" : "right");
}
return;
}
ufo.x += ufo.direction * 40.0f * dt;
if (ufo.x > kArenaRight + 1.0f || ufo.x < kArenaLeft - 19.0f) {
ufo.active = false;
ufoTimer = g.rng.range(18.0f, 28.0f);
}
}
- The first one comes 8–14 s into the wave (from the constructor), later ones 18–28 s after the previous one left or was shot.
- Only while at least 8 aliens are alive. With fewer, the timer keeps running below zero, and the saucer waits until the next wave, which keeps the end of a wave about the formation.
- It starts just outside the arena (x = 30 from the left, 272 from the right), in the lane at y 14 (
kUfoYinlayout.hh), and moves 40 px/s, about 6 s for the crossing. Starting outside the arena is safe because the side panels are drawn over the arena afterwards and hide it (section 29.9). - Its collision box is 16 × 6, the 18 × 8 sprite without its outline, like the ship's box in chapter 28.
updateUfo doesn't save the previous position itself.
That happens at the top of PlayScene::update, in every phase, next to the ship's:
// 補間用の前の位置は、どのフェーズでも毎回ここで。ShipDownではupdateUfoが呼ばれないので円盤もここ(止まった円盤が
// 古いprevXとxの間で震えない様に、第26章)
// Previous positions for the interpolation, refreshed here in every phase. ShipDown does not call updateUfo, so
// the saucer's is refreshed here too (or the frozen saucer wobbles between a stale prevX and x, chapter 26)
playerPrevX = playerX;
ufo.prevX = ufo.x;
While the ship explodes (ShipDown), the march and the saucer stop, and updateUfo isn't called.
If updateUfo refreshed prevX, a saucer caught mid-crossing would keep the prevX of its last move, 2/3 px behind x, for the whole 1.4 s, and be drawn between the two with a changing alpha.
That's chapter 26's wobble again, this time in an object that is frozen without being paused.
The ship's bullet tests the saucer after the aliens and before the shields:
if (ufo.active && overlaps(box, ufo.box())) {
// 円盤:50〜300点(乱数)、点数が浮かび、揺れて白く光る / the saucer: 50-300 points (random), the points float
// up, a shake and a white flash
int points = kUfoPoints[g.rng.range(0, 3)];
addScore(points);
printf("saucer hit: %d points\n", points);
char text[12];
snprintf(text, sizeof text, "%d", points);
popup(ufo.box().centre(), text, hexColor(0xffec96ff));
particles.burst(ufo.box().centre(), 20, hexColor(0xd9474bff), 20.0f, 60.0f, g.rng);
shake.add(0.5f); // 0.408未満では1ピクセルも動かない / below 0.408 it would not move a single pixel
flash.start({1.0f, 1.0f, 1.0f, 0.35f});
ufo.active = false;
ufoTimer = g.rng.range(18.0f, 28.0f);
shot.reset();
return;
}
g.rng.range(0, 3) is chapter 26's unbiased integer range, inclusive at both ends, so each of the four values {50, 100, 150, 300} has a chance of 1/4 and a saucer is worth 150 on average.
The arcade did it differently: the value came from a fixed table indexed by the number of shots you had fired, so experienced players counted their shots and timed the saucer for 300.
PlayScene already counts shotsFired; challenge 4 builds the table.
The points float up as a popup: a short string in pixel5, moving 8 px/s up for 1 s and fading in its last third (alpha = min(1, 3 × life)).
"1UP" uses the same struct.
29.7 The HUD in the side panels
Chapter 27 split the 320 × 180 canvas into a 224 px arena and two 48 px side panels.
Chapter 28 filled them with developer numbers; now they hold the HUD: SCORE, HI-SCORE and WAVE on the left, LIVES with the reserve ships, ALIENS and the key hints on the right.
The HUD is drawn inside the canvas, in the 3 × 5 pixel5 font, not at screen resolution with mono16.
There are three reasons:
- It's part of the pixel art: the same pixel grid, the same ×4 scaling, and the CRT finish scanlines it like everything else.
- It's drawn with the steady camera after the shaken arena, so the panels cover whatever the shake pushes out of the arena (section 29.9).
- An arcade HUD is big blocky digits.
pixel5at ×2 gives 6 × 10 px digits with an 8 px advance; five digits are 40 px of advance and fit the 48 px panel with a few pixels to spare.
All HUD text goes through one helper:
void drawTinyText(Game &g, const char *text, Vec2 position, Vec4 color, float scale, TextAlign align) {
// pixel5は3 × 5の1ビットの文字。整数倍なら崩れない。影 = 輪郭の色で1ピクセル右下(shadowOffsetは
// scale倍されるので1/scale)
// pixel5 is a 1-bit 3 × 5 font; whole-number scales keep it crisp. Shadow = the outline color, 1 px down right
// (shadowOffset is multiplied by scale, hence 1/scale)
g.tiny.draw(g.batch, text, position,
{.color = color, .scale = scale, .align = align, .shadow = hexColor(0x1b1726ff),
.shadowOffset = {1.0f / scale, 1.0f / scale}});
}
Font::draw draws the shadow at position + shadowOffset × scale, which is right for antialiased UI text (a bigger text gets a bigger shadow), but for pixel art I want a 1 px shadow at every scale.
With the default offset (1, 1), "GAME OVER" at ×3 got a 3 px dark ghost under every letter; passing 1 / scale cancels the multiplication.
The shadow color is the sprites' shared outline color (27, 23, 38), so the text sits on the panels like the sprites do.
pixel5 is loaded with TextureFilter::Nearest in main and only drawn at whole-number scales and whole-pixel positions, the pixel-art rules of chapter 25.
The HUD itself:
void PlayScene::drawHud() {
char line[32];
Vec4 digits = scoreFlash > 0.0f ? hexColor(0xffec96ff) : hexColor(0xf4f1e8ff);
drawTinyText(g, "SCORE", {6.0f, 10.0f}, kHudLabel);
snprintf(line, sizeof line, "%05d", g.run.score);
drawTinyText(g, line, {5.0f, 18.0f}, digits, 2.0f);
drawTinyText(g, "HI-SCORE", {6.0f, 40.0f}, kHudLabel);
snprintf(line, sizeof line, "%05d", std::max(g.hiScore, g.run.score));
drawTinyText(g, line, {5.0f, 48.0f}, hexColor(0xf2c14eff), 2.0f);
drawTinyText(g, "WAVE", {6.0f, 70.0f}, kHudLabel);
snprintf(line, sizeof line, "%d", g.run.wave);
drawTinyText(g, line, {5.0f, 78.0f}, hexColor(0xf4f1e8ff), 2.0f);
const float rx = kArenaRight + 6.0f;
drawTinyText(g, "LIVES", {rx, 10.0f}, kHudLabel);
snprintf(line, sizeof line, "%d", g.run.lives);
drawTinyText(g, line, {rx - 1.0f, 18.0f}, hexColor(0xf4f1e8ff), 2.0f);
// 控えの自機(今の1機を除く) / the ships in reserve (not counting the one in play)
for (int i = 0; i < std::min(g.run.lives - 1, 4); ++i)
g.batch.draw(g.sprites.sprite(shipFrame, {rx + static_cast<float>(i % 2) * 18.0f, 32.0f + static_cast<float>(i / 2) * 11.0f}));
drawTinyText(g, "ALIENS", {rx, 70.0f}, kHudLabel);
snprintf(line, sizeof line, "%d", formation.alive());
drawTinyText(g, line, {rx - 1.0f, 78.0f}, hexColor(0xf4f1e8ff), 2.0f);
drawTinyText(g, "P PAUSE", {rx, 150.0f}, kHudLabel);
drawTinyText(g, "C CRT", {rx, 158.0f}, kHudLabel);
drawTinyText(g, "TAB INFO", {rx, 166.0f}, kHudLabel);
}
- Labels at ×1 in a muted blue, numbers at ×2. The score is always five digits (
%05d), arcade style, so the number doesn't jump around as it grows. - The digits flash yellow for 0.15 s whenever
addScoreruns. It's a tiny thing, but your eye goes to the score at the moment it changes, and that's what tells you a hit counted. - The HI-SCORE line shows the larger of the stored high score and the current score, so it climbs with you once you pass it.
- The reserve ships are the ships not in play:
lives − 1, at most four icons in two columns. - The HUD is drawn every frame from
Game::runand the formation. It has no state of its own, so there's nothing to keep in sync.
The text at screen resolution (mono16, drawn in drawUi) is used only for the bilingual lines: the title's prompt "スペースキーで開始 / PRESS SPACE", the pause menu, "ゲームオーバー 新記録!" and "スペースキーでタイトルへ".
That's chapter 26's rule: short UI strings in both languages, HUD numbers and labels in English.
mono16 only has the 252 UI kanji of chapter 26's subset, so I checked every string against mono16.fnt before writing it: 移動 (move), 波 (wave) and the arrows ← → are not in the atlas.
That's why the title's help line says "A D 左右・Space 撃つ・P 一時停止・Esc 終了" (左右 = left/right) and the wave banner is English only.
The engine's "character not in the font" warning is the safety net, but it's better not to need it; no run of the finished game prints one.
29.8 Title, pause and game over
The title
The title draws the same backdrop as the play scene, the logo (64 × 11 in the atlas) at ×2, a saucer that crosses at 30 px/s and wraps outside the arena, and the score table, whose aliens switch poses every 0.5 s (static_cast<int>(time * 2.0f) % 2), as if they were marching on the spot.
The prompt pulses with , between 0.1 and 1.0 alpha.
It's all chapter 26 material (sprites, Font::draw, interpolation of the saucer), so I won't go through the code; it's title_scene.cc.
Backdrop is new only as a file: chapter 28's PlayScene::drawBackground moved into a class that both scenes use, and it's split into drawSky (stars and ground, inside the arena) and drawPanels (the side panels and their borders).
The split is what lets the play scene draw the panels after the arena; section 29.9 needs that.
The pause menu
PauseScene is an overlay (isOverlay() returns true), so the play scene below is still drawn but no longer updated:
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 (in.pressed(GLFW_KEY_UP) || in.pressed(GLFW_KEY_W) || in.pressed(GLFW_KEY_DOWN) || in.pressed(GLFW_KEY_S))
selected = 1 - selected;
if (in.actionPressed("confirm")) {
if (selected == 0) scenes().pop();
else scenes().replaceAll(std::make_unique<TitleScene>(g), {.duration = 0.8f});
}
}
With two items, "up" and "down" both just flip the selection.
Resume is a pop: the play scene gets resume() and continues exactly where it stopped, because nothing touched it.
Back to title is a replaceAll: both the pause scene and the play scene are destroyed, with their wave, and the title starts fresh.
Quitting this way abandons the run: the high score is only updated at game over, so a score you walk away from doesn't count (the arcade had no quit button either).
PlayScene::pause() sets every "previous" position to the current one, as chapter 26 explained, so the frozen arena doesn't wobble with the interpolation alpha.
The pause scene's draw dims the arena inside the canvas (fading in over 0.25 s), and its drawUi draws a 600 × 210 panel at screen resolution with "一時停止 / PAUSED" and the two items.
The panel is there because the menu text over a live formation was unreadable; the first version was also narrower than "> タイトルへ / Back to title <" at ×2.
Game over
void GameOverScene::update(float dt) {
time += dt;
// 1.5秒は待つ(撃っていたスペースで飛ばさないように) / wait 1.5 s (so a Space meant as a shot does not skip it)
if (time > 1.5f && g.input.actionPressed("confirm"))
scenes().replaceAll(std::make_unique<TitleScene>(g), {.duration = 1.0f});
}
void GameOverScene::draw(float /*alpha*/) {
float in = std::min(1.0f, time * 2.0f);
dimArena(g, in * 0.55f);
g.batch.begin(g.world.matrix());
g.batch.drawRect({kArenaLeft, 40.0f, kArenaRight - kArenaLeft, 84.0f}, {0.05f, 0.04f, 0.1f, 0.85f * in});
// 「GAME OVER」を一文字ずつ打つ / type "GAME OVER" one letter at a time
const char *title = "GAME OVER";
char shown[16] = {};
size_t n = std::min(std::strlen(title), static_cast<size_t>(time / 0.09f));
std::memcpy(shown, title, n);
// 位置は全部の文字の幅で決める(打っている途中で動かない) / position from the full width (does not move while
// typing)
float x = std::round(160.0f - 0.5f * g.tiny.measure(title, 3.0f).x);
drawTinyText(g, shown, {x, 48.0f}, hexColor(0xd9474bff), 3.0f);
char line[32];
snprintf(line, sizeof line, "SCORE %05d WAVE %d", g.run.score, g.run.wave);
drawTinyText(g, line, {160.0f, 72.0f}, hexColor(0xf4f1e8ff), 1.0f, TextAlign::Centre);
if (newHigh && std::fmod(time, 0.5f) < 0.35f)
drawTinyText(g, "NEW HIGH SCORE!", {160.0f, 82.0f}, hexColor(0xffec96ff), 1.0f, TextAlign::Centre);
g.batch.end();
}
- The 1.5 s guard. Space is both "fire" and "confirm". A player who is hammering Space when the last ship dies would skip the game-over screen without ever seeing it (chapter 28 had exactly that problem). The prompt only appears once the guard is over, so the screen tells you when it listens.
- Typed text: one more letter every 0.09 s, all 9 characters of "GAME OVER" after 0.81 s. The string is cut with
memcpyinto a zero-filled buffer. - Position from the full text. With
TextAlign::Centreon the partial string, the text would slide left with every new letter. Instead the x position is computed from the whole string, 9 × 4 × 3 = 108 px wide, so it starts at 160 − 54 = 106 and the letters appear in place. - NEW HIGH SCORE! blinks (0.35 s on, 0.15 s off) only when
PlayScenereported a new record; the overlay doesn't compare scores itself, it just shows what it was given in its constructor.
After the guard, Space goes to the title with replaceAll and a 1.0 s fade, and the title shows the new high score.
29.9 Screen shake
Game feel ("juice") is the set of small effects that make an action feel like it has weight.
The classic one is screen shake, and the version I use is the one from Squirrel Eiserloh's GDC talk "Juicing Your Cameras With Math": trauma.
// 画面の揺れ(第29章):「トラウマ」(0〜1)を足し、時間とともに減らす。ずれ = 最大3ピクセル × トラウマ²、
// 整数のピクセル(ピクセルアートの格子からはみ出さない)。乱数は自分の種:揺れがゲームの乱数の並びを変えない
// Screen shake (chapter 29): add "trauma" (0..1), which decays over time. Offset = up to 3 px × trauma², in whole
// pixels (stays on the pixel-art grid). Its own random seed: shaking does not change the game's random sequence
class Shake {
public:
void add(float amount);
void update(float dt); // 固定ステップで / in the fixed step
Vec2 offset() const { return current; }
float trauma() const { return amount; }
private:
float amount = 0.0f;
Vec2 current = {0.0f, 0.0f};
Rng rng{29};
};
void Shake::add(float a) { amount = std::min(1.0f, amount + a); }
void Shake::update(float dt) {
amount = std::max(0.0f, amount - 1.6f * dt);
float k = 3.0f * amount * amount;
current = {std::round(k * rng.range(-1.0f, 1.0f)), std::round(k * rng.range(-1.0f, 1.0f))};
}
Events add trauma (capped at 1), and trauma decays linearly by 1.6 per second.
The offset isn't proportional to trauma but to its square:
separately for x and y, with a new random every update.
Squaring makes big events much bigger than small ones (trauma 1 shakes 4 times as far as trauma 0.5) and makes the end of a shake fade out softly instead of stopping abruptly.
The events:
- The ship is hit: +0.75, together with a red flash.
- An invasion: +1.0 on top of the hit's 0.75, so it's capped at 1.0: the biggest shake in the game.
- The saucer is shot: +0.5, together with a white flash.
Whole pixels. The offset is rounded, so the arena moves on the canvas's pixel grid; a 0.3 px offset of a pixel-art scene would either do nothing or (with linear filtering) blur it.
Rounding also sets a threshold, and the plot shows it.
A whole pixel needs , that is trauma .
The ship hit (0.75) is above that for (0.75 − 0.408) / 1.6 ≈ 0.21 s, with 2 px possible only in the first 0.03 s; the invasion (1.0) for (1 − 0.408) / 1.6 ≈ 0.37 s, with 3 px at the start.
Why 0.5 and not 0.4. The saucer should get a light tap, much less than a ship hit, and 0.4 looks about right on a scale from 0 to 1.
But 0.4 is just below the threshold: its largest offset is 3 × 0.4² = 0.48 px, which always rounds to 0.
On its own it would never move the screen; it could only add to a shake that's already running.
0.5 is just above it: 3 × 0.5² = 0.75 px at the hit, and above 0.5 px for about (0.5 − 0.408) / 1.6 ≈ 0.06 s.
In the game that's the first three updates after the hit, and an axis jumps by 1 px only when its random is large enough (above 0.5 / 0.67 ≈ 0.74 in the first update).
So it's a one-pixel tick, and about one saucer hit in three shows no movement at all; the white flash and the popup carry the moment anyway.
The lesson holds for anything whose output ends up quantized (whole pixels, whole steps, 8-bit colors): tune the strength against the threshold, not against the smooth curve, because below the threshold the effect isn't small, it's absent.
Its own Rng. The shake draws two random numbers every update, whether it's shaking or not.
If it used Game::rng, turning the shake off (or changing how often it's updated) would change every later alien shot and saucer value; a cosmetic change would change the game.
With Rng rng{29} inside Shake, the gameplay sequence is the same with or without shake.
The shake is also updated in the fixed step, not per frame, so it's as deterministic as the rest: the screenshots and clips can be reproduced exactly.
Shake is a member of PlayScene, so a shake dies with its wave: the new wave never starts in the middle of the old wave's shake.
Shaking only the arena
Here is the first part of PlayScene::draw:
// 揺れ:戦場の中身だけをカメラごとずらす(整数のピクセル)。脇の板とHUDは揺らさずに上から描くので、
// はみ出した分は隠れる
// Shake: only the arena's contents move, by moving the camera (whole pixels). The side panels and HUD are drawn on
// top without the shake, so whatever is pushed out is hidden
Camera2D steady = g.world;
g.world.centre = steady.centre - shake.offset();
SpriteBatch &b = g.batch;
b.begin(g.world.matrix());
g.backdrop.drawSky(b, time);
shields->draw(b);
b.end();
drawFormation();
The shake moves the camera, not the objects.
Moving the camera's centre by −offset moves everything drawn with it by +offset, so the sky, the shields, the formation (the instanced renderer reads the same g.world.matrix()), the ship, the bullets, the particles and the popups all shift together, and no game object ever has a "drawn here but really there" position.
Collisions are unaffected, since they never look at the camera.
Then the steady part:
// 揺れない物:閃光(戦場だけ)、波の見出し、脇の板とHUD / things that do not shake: the flash (arena only), the
// wave banner, the side panels and the HUD
g.world = steady;
b.begin(g.world.matrix());
if (flash.color.w > 0.0f) b.drawRect({kArenaLeft, 0.0f, kArenaRight - kArenaLeft, kView.y}, flash.color);
char line[32];
if (phase == Phase::Ready) {
// 後の波は隊列が低いので、見出しの後ろに暗い帯 / later waves start lower, so a dark band behind the banner
b.drawRect({kArenaLeft, 99.0f, kArenaRight - kArenaLeft, 28.0f}, {0.05f, 0.04f, 0.1f, 0.75f});
}
if (phase == Phase::Ready && std::fmod(phaseTime, 0.4f) < 0.28f) {
snprintf(line, sizeof line, "WAVE %d", g.run.wave);
drawTinyText(g, line, {160.0f, 104.0f}, hexColor(0xf2c14eff), 2.0f, TextAlign::Centre);
drawTinyText(g, "GET READY", {160.0f, 120.0f}, hexColor(0xd8dcefff), 1.0f, TextAlign::Centre);
}
if (phase == Phase::Cleared) {
snprintf(line, sizeof line, "WAVE %d CLEAR", g.run.wave);
drawTinyText(g, line, {160.0f, 104.0f}, hexColor(0x9adc48ff), 2.0f, TextAlign::Centre);
}
g.backdrop.drawPanels(b);
drawHud();
b.end();
}
Restore the camera first.
g.world is shared: the pause and game-over overlays draw with it after this function returns, and so does the next frame.
Taking a copy (steady), changing the shared camera, and putting the copy back is the simplest way to "borrow" it.
Then the order does the clipping.
A 3 px shake pushes up to 3 px of the arena over the panel on one side and uncovers a strip on the other.
drawPanels paints the two 48 px panels and their 1 px borders after the shaken arena, opaque, so the overflow disappears under them.
The uncovered strip shows the canvas clear color (0x0c0a1a), which is the arena's background anyway (the sky is only stars on that color), so only the ground line gives it away: it ends a few pixels short of the border, as in the invasion picture below.
At the top and bottom the arena reaches the canvas edges, so whatever moves out there is simply off the canvas.
No scissor test, no stencil: the painter's algorithm, with the panels as the frame of a window.
The HUD is then drawn on the steady panels, so the numbers never shake, which matters: the score is what you read in the moment of a hit.
29.10 Flashes
The second effect is a flash, a translucent rectangle over the arena that fades fast:
// 閃光:色の四角を一瞬かぶせ、すぐに消す / a flash: a colored rectangle over the arena for a moment, fading fast
struct ScreenFlash {
Vec4 color = {1.0f, 1.0f, 1.0f, 0.0f};
void start(Vec4 c) { color = c; }
void update(float dt) { color.w = std::max(0.0f, color.w - 3.0f * dt); } // 約0.2秒で消える / gone in ~0.2 s
};
The alpha drops by 3 per second, so a flash lasts its starting alpha divided by 3:
| event | color (RGBA) | duration |
|---|---|---|
| ship hit | (1, 0.25, 0.2, 0.45) red | 0.15 s |
| saucer hit | (1, 1, 1, 0.35) white | 0.12 s |
| wave cleared | (1, 1, 1, 0.5) white | 0.17 s |
A new flash replaces the old one instead of adding to it; flashes are too short to overlap in a way that matters.
The flash is drawn with the steady camera over the arena only (x 48 to 272), before the panels, so the HUD never flashes and stays readable.
The ship hit combines everything:
void PlayScene::killShip() {
--g.run.lives;
setPhase(Phase::ShipDown);
shipBoom.play(shipBoomClip, true);
Vec2 c = shipBox().centre();
particles.burst(c, 24, hexColor(0x4fc0a5ff), 20.0f, 70.0f, g.rng);
particles.burst(c, 12, hexColor(0xffa040ff), 30.0f, 90.0f, g.rng);
alienShots.clear(); // 元のゲームと同じく、飛んでいる弾は消える / bullets in flight vanish, as in the original
// 磨き:大きく揺らし、赤く光らせる / polish: a big shake and a red flash
shake.add(0.75f);
flash.start({1.0f, 0.25f, 0.2f, 0.45f});
printf("ship hit: lives %d\n", g.run.lives);
}
The flash and the shake are the first 0.15–0.2 s, the explosion clip and the particles carry on, and the 1.4 s of ShipDown give you time to understand what happened before the ship comes back.
A word of caution: full-screen flashes can be a problem for players with photosensitivity.
These are short, partial (alpha at most 0.5), confined to the arena and not repeated in quick succession, but a real game should still have an option to turn them off.
29.11 A CRT finish
Arcade Invaders ran on a CRT, and pixel art looks different on one: the pixels have dark gaps between the lines, a faint color structure, and bright things bleed a little.
We can imitate some of that with a shader.
So far PixelCanvas::present copied the canvas into the window with glBlitNamedFramebuffer and GL_NEAREST, an exact ×4 enlargement.
A blit can only scale; to change the pixels on the way, we need to draw the canvas texture with a fragment shader instead, which is exactly what chapter 17's post-processing did with a fullscreen triangle.
CrtFilter
class CrtFilter {
public:
// engine/shaders/post.vert(画面全体の三角形)+ games/invaders/shaders/crt.frag
// engine/shaders/post.vert (the fullscreen triangle) + games/invaders/shaders/crt.frag
static std::optional<CrtFilter> create();
// PixelCanvas::presentと同じ場所(整数倍のレターボックス)に描き、その場所を返す。帯は黒
// Draws to the same place as PixelCanvas::present (the integer-scaled letterbox) and returns it. Black bars
Viewport present(const PixelCanvas &canvas, int windowWidth, int windowHeight) const;
private:
CrtFilter() = default;
std::optional<Shader> shader;
FullscreenTriangle triangle;
};
It reuses two engine pieces: chapter 17's FullscreenTriangle (one triangle, no vertex buffer) and its vertex shader engine/shaders/post.vert, which makes vUv run from 0 to 1 across the viewport.
Only the fragment shader is the game's own.
The factory follows the engine's pattern (no exceptions, std::optional):
std::optional<CrtFilter> CrtFilter::create() {
CrtFilter crt;
crt.shader = Shader::load("engine/shaders/post.vert", "games/invaders/shaders/crt.frag");
if (!crt.shader) return std::nullopt;
return crt;
}
and present takes the place of PixelCanvas::present:
Viewport CrtFilter::present(const PixelCanvas &canvas, int windowWidth, int windowHeight) const {
Viewport v = letterbox(windowWidth, windowHeight, canvas.size(), true);
Framebuffer::bindDefault(windowWidth, windowHeight);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
v.apply();
// 不透明な一枚の絵:ブレンドは要らない(SpriteBatch::beginがまた有効にする) / one opaque picture: no blending
// (SpriteBatch::begin turns it back on)
glDisable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
shader->set("uCanvasSize", canvas.size());
shader->set("uScale", v.scale);
shader->set("uOrigin", Vec2{static_cast<float>(v.x), static_cast<float>(v.y)});
// FBOの色テクスチャは下の行がv = 0。post.vertのvUvも下が0なので、そのまま貼れば上下は正しい
// An FBO color texture has its bottom row at v = 0. post.vert's vUv is 0 at the bottom too, so it maps the right
// way up as it is
canvas.framebuffer().color().bind(0);
shader->use();
triangle.draw();
return v;
}
Step by step:
- The same letterbox as
PixelCanvas::present:letterbox(…, true)picks the largest whole-number scale (4 at 1280 × 720) and centers the 1280 × 720 picture. Toggling the CRT with C must not move anything, so both paths use the same function. - Bind the default framebuffer, clear it to black (the bars), and set
glViewportto the letterbox withv.apply(). The fullscreen triangle now covers exactly the canvas's place, andvUvis 0…1 over it. - No blending, no depth test. The picture is opaque and replaces what's there;
SpriteBatch::endleaves blending on (chapter 25), and with alpha 1 the premultiplied blend would give the same result, but turning it off says what we mean and skips the read of the destination. The nextSpriteBatch::begin, in the UI pass, turns it back on. - Three uniforms with the geometry: the canvas size (320, 180), the scale (4), and the viewport's bottom-left corner in window pixels.
Shader::setusesglProgramUniform*, so it works beforeuse(). - The canvas's color texture on unit 0 (it was created with
GL_NEARESTbyPixelCanvas), then one triangle.
No flip. In chapter 25, drawing a framebuffer texture as a sprite needed flipY, because sprites have v = 0 at the top of the image while a framebuffer's row 0 is the bottom of what was rendered.
post.vert's vUv is 0 at the bottom of the viewport, like gl_FragCoord, so it matches the texture the right way up as it is.
In main the world pass picks one of the two:
canvas.begin(hexColor(0x0c0a1aff));
scenes.draw(alpha);
if (game.crt) crt->present(canvas, window.width(), window.height());
else canvas.present(window.width(), window.height());
The UI pass (drawUi, then the fade) comes after it, at screen resolution, so the bilingual mono16 text stays crisp; only the pixel-art canvas gets the CRT look.
The shader
Here is crt.frag in full:
#version 460 core
// ブラウン管風(第29章):320 × 180のキャンバスを整数倍で画面に。色はsRGBの値のまま計算する(2Dの約束)
// CRT style (chapter 29): the 320 × 180 canvas at a whole-number scale. Colors stay sRGB-encoded values (the 2D rule)
in vec2 vUv; // engine/shaders/post.vert:ビューポートの中で0〜1、下が0 / 0..1 across the viewport, 0 at the bottom
layout(binding = 0) uniform sampler2D uCanvas; // GL_NEARESTのキャンバス / the GL_NEAREST canvas
uniform vec2 uCanvasSize; // (320, 180)
uniform float uScale; // 画面のピクセル / キャンバスのピクセル(4) / screen pixels per canvas pixel (4)
uniform vec2 uOrigin; // ビューポートの左下(ウィンドウのピクセル) / the viewport's bottom left (window pixels)
layout(location = 0) out vec4 out_color;
void main() {
vec2 texel = 1.0 / uCanvasSize;
vec3 color = texture(uCanvas, vUv).rgb;
// にじみ:上下左右のキャンバスのピクセルを少し足す(明るい物の周りがぼんやり光る)
// Glow: add a little of the canvas pixels around (bright things get a soft halo)
vec3 around = texture(uCanvas, vUv + vec2(texel.x, 0.0)).rgb + texture(uCanvas, vUv - vec2(texel.x, 0.0)).rgb +
texture(uCanvas, vUv + vec2(0.0, texel.y)).rgb + texture(uCanvas, vUv - vec2(0.0, texel.y)).rgb;
color += 0.06 * around;
// 画面のピクセルが、キャンバスのピクセルの中のどこか(0〜uScale-1)。gl_FragCoordはピクセルの中心(+0.5)
// Where this screen pixel lies inside its canvas pixel (0..uScale-1). gl_FragCoord is a pixel center (+0.5)
vec2 inside = mod(floor(gl_FragCoord.xy - uOrigin), uScale);
// 走査線:キャンバスの各行の一番下の画面の行を暗く / scanlines: the lowest screen row of every canvas row is darker
float scan = inside.y < 0.5 ? 0.62 : 1.06;
// 蛍光体の縞:画面の列ごとに赤・緑・青を少しだけ強める / phosphor mask: every screen column leans a little towards
// red, green or blue in turn
int column = int(mod(floor(gl_FragCoord.x), 3.0));
vec3 mask = column == 0 ? vec3(1.06, 0.97, 0.97) : column == 1 ? vec3(0.97, 1.06, 0.97) : vec3(0.97, 0.97, 1.06);
// 周辺減光:四隅が少し暗い / vignette: the corners are a little darker
vec2 d = vUv - 0.5;
float vignette = 1.0 - 0.35 * dot(d, d);
out_color = vec4(clamp(color * scan * mask * vignette, 0.0, 1.0), 1.0);
}
The shader runs once per screen pixel, 1280 × 720 of them, but the texture only has 320 × 180 texels.
With GL_NEAREST and a whole-number scale, every canvas pixel covers exactly a 4 × 4 block of screen pixels, all 16 of which read the same texel.
The effects come from knowing where inside that block the current screen pixel is:
Glow. Four more texture calls, one canvas texel to the right, left, up and down (texel = 1 / 320 and 1 / 180 in UV units), and 6 % of each is added.
A bright sprite next to the dark sky lends a little of its color to the neighboring pixels, a soft halo like a CRT's beam spreading.
On a flat area every neighbor equals the center, so it becomes 1.24 times brighter before the clamp; the background is dark enough that this doesn't matter, and the scanlines take some of it back.
Where inside the block. gl_FragCoord.xy is the window position of the pixel's center, x.5 (see GLSL chapter 2).
Subtracting the viewport's corner uOrigin and taking floor gives whole screen pixels counted from the canvas's bottom-left corner; mod by the scale (the floor/mod pattern of GLSL chapter 7) gives 0, 1, 2 or 3: the position inside the 4 × 4 block.
uOrigin matters as soon as the canvas isn't at the window's corner: in a 1280 × 730 window the letterbox starts at y = 5, and without the subtraction the dark line would land on the top row of every canvas row instead of the lowest one.
Scanlines. gl_FragCoord counts from the bottom, so inside.y == 0 is the lowest of the four screen rows of every canvas row.
That row is multiplied by 0.62, the other three by 1.06.
The average over the four rows is (0.62 + 3 × 1.06) / 4 = 3.8 / 4 = 0.95, so the picture keeps 95 % of its brightness while getting a visible line structure; a plain 0.62 on one row and 1.0 on the others would lose 9.5 %.
The comparison < 0.5 instead of == 0.0 is the usual floating-point caution.
Phosphor mask. A color CRT's screen is made of red, green and blue phosphors.
The mask imitates that by screen column, repeating every three columns: one channel × 1.06, the other two × 0.97.
Over three columns each channel averages (1.06 + 0.97 + 0.97) / 3 = 1.0, so the color doesn't shift; only a fine stripe appears when you look closely.
The period (3) doesn't match the scale (4) on purpose: a real tube's mask has nothing to do with the signal's pixels.
Here gl_FragCoord.x isn't relative to uOrigin, because the stripes belong to the "glass", not to the picture.
Vignette. With the factor is : 1 in the middle, 1 − 0.35 × 0.25 ≈ 0.91 at the middle of the left and right edges, 1 − 0.35 × 0.5 ≈ 0.83 in the corners.
vUv isn't corrected for the 16 : 9 aspect, so the darkening follows the frame's shape, an ellipse.
Everything is multiplied together, clamped and written with alpha 1.
sRGB values. The canvas holds sRGB-encoded colors and GL_FRAMEBUFFER_SRGB is off (the 2D color rule of chapter 25), so the shader multiplies encoded values.
Physically, light should be mixed in linear space (chapter 21), and a factor of 0.62 on an encoded value darkens more than 0.62 in light.
For a look that's tuned by eye anyway, that doesn't matter: the numbers were chosen while looking at the result, in the same space the art was painted in.
The cost is five texture reads and a few multiplications for 921 600 pixels, which is nothing on any GPU; even the software rasterizer of the test harness doesn't notice it next to the sprites.
One caution for screenshots and videos: scanlines are a pattern at the full window resolution.
Downscaling 1280 → 960 with nearest-neighbor sampling keeps three of every four screen rows, unevenly, and the scanlines turn into an irregular moiré.
That's why the screenshots in this chapter are resized with a filter that averages (LANCZOS), the clips with an area filter, and the comparison above is a ×2 crop.
29.12 Developer keys
Two keys work in every scene, so they're handled in main before the scenes update:
[&](float dt) {
// どの場面でも効くキー / keys that work in every scene
if (input.pressed(GLFW_KEY_C)) game.crt = !game.crt;
if (input.pressed(GLFW_KEY_TAB)) game.devInfo = !game.devInfo;
scenes.update(dt);
if (scenes.empty()) window.close();
},
The flags live in Game, so the CRT stays off on the title if you switched it off during play.
Tab shows one line at the bottom of the play scene's UI pass: FPS, the formation renderer with its draw calls and bytes per frame (chapter 27), the march rate, the last shield upload in bytes (chapter 28) and the particle count.
The side panels used to show these numbers; they now belong to the player, and the numbers are one key away.
N sends you to the next wave:
if (in.pressed(GLFW_KEY_N) && phase == Phase::Playing) {
// 開発用:全員を倒して次の波へ(点は入らない) / developer key: destroy everyone and go to the next wave (no points)
for (Alien &a : formation.aliens)
if (a.alive) formation.kill(a);
}
It kills every alien through the normal kill (so they explode) without calling addScore, and the regular Cleared logic does the rest.
A developer key that goes through the same path as the game is worth more than one that jumps to the end state, because it tests the real path every time you use it.
I, B and = / − are still there from chapters 27 and 28.
29.13 Running it
From the project root:
cmake --build build -j8
./build/games/invaders/invaders
In Visual Studio, choose invaders as the startup project (build\games\invaders\Debug\invaders.exe); its working directory is already the project root.
After the line with the OpenGL version, the program prints its progress on stdout, which is handy to check the flow (here the start of a run that shoots the saucer for 300):
title: high score 0
wave 1: score 0, lives 3
ship hit: lives 2
saucer from the left
saucer hit: 300 points
29.14 Platform notes
- Windows (Visual Studio): the Japanese UI strings need the
/utf-8compile option, as chapter 26 explained; without it MSVC reads the sources in the system code page and the bilingual lines show?. The project's CMake already passes it to MSVC, so there's nothing to do. - All: the CRT pattern is locked to the window's pixels. With display scaling (125 % or 150 % on Windows, fractional scaling on some Linux desktops), the compositor may resample the window, and the scanlines can turn soft or uneven; at 100 % (or with integer scaling) they're exact.
- All:
CandTabare GLFW key codes, named by their position on a US keyboard, like W A S D in chapter 26.
29.15 How real games do it
- Scenes and levels: Unity loads a scene file per level (
SceneManager.LoadScene) and keeps cross-level data in objects markedDontDestroyOnLoador in a separate persistent scene; Godot replaces the current scene (change_scene_to_file) and keeps such data in autoload singletons. Both are this chapter's split: scene-owned objects die with the scene, a small persistent object carries the run. - High scores and saves: saved to the user's data folder (
%APPDATA%on Windows,$XDG_DATA_HOMEor~/.local/shareon Linux and FreeBSD), written to a temporary file first and renamed, so a crash can't leave a half-written save. - Game feel: trauma-based shake, hit stop (freezing the game for a few frames on a hit, challenge 5), flashes, particles and popups are standard; engines and asset stores ship camera-shake components, often with Perlin noise instead of white noise for a smoother motion.
- CRT shaders: emulators such as RetroArch offer whole families of CRT shaders (with curvature, beam shapes, bloom and masks modeled on real tubes), usually as multi-pass chains; ours is the one-pass minimum of the same idea.
29.16 Space Invaders in review, and what comes next
Three chapters built one complete game on the engine of Part 5:
- Chapter 27: the game's own folder and executable, pixel-art sprites from a generator script, the ship, and a formation of 55 aliens that marches one alien at a time, drawn with instancing (one draw call, per-instance position and frame) and compared with the
SpriteBatch. - Chapter 28: bullets and AABB collisions without tunneling, alien fire, shields that erode pixel by pixel (a CPU master copy and
glTextureSubImage2Dof the changed rectangle only), explosions, lives and invasion. - This chapter: scenes (title, play, pause and game-over overlays), data that persists vs data that dies with the scene, waves as scene reloads, per-wave difficulty, score, the saucer and the extra ship, an in-canvas HUD, and polish: shake, flashes, flashing digits, typed text and a CRT shader.
The GPU side of the game turned out small: instancing, partial texture uploads and one post-processing shader.
Most of the work, and most of what makes it feel like a game, was CPU-side structure: a fixed step, scenes, ownership and timing.
That's typical for 2D games, and it's also why a good engine API pays off: the game never touched OpenGL state except in its two renderers.
Next is the second game of Part 6, a 2D fighting game.
Chapter 30 starts with characters made of many animation frames and a state machine for each fighter (idle, walk, jump, crouch…), 2D physics with gravity and the ground, and two players reading input from the same keyboard.
The scene stack, fades, Font and the fixed step all come along unchanged, and so does this chapter's question about ownership: which data belongs to one round, and which to the whole match.
29.17 Summary
- Ownership by lifetime: data lives in the shortest-lived owner that's still long enough.
Game(whole program: high score, gameplayRng, assets, toggles),Game::run(one game: score, lives, wave, extra ship; reset withRun{}on the title),PlayScene(one wave: everything on the playfield). - Scene reloading: a cleared wave raises
run.waveand replaces the play scene with a new one (1.0 s fade). The constructor builds the wave fromGame, the destructor frees it (RAII); nothing can leak from one wave into the next. Request the change once (leaving). - Scene flow: Title → (replace) Play → push Pause (pop to resume, replaceAll to the title) or push GameOver (replaceAll to the title after 1.5 s). Inside the play scene an
enum class Phase(Ready 1.6 s, Playing, ShipDown 1.4 s, Cleared 1.5 s, Over) replaces boolean flags. - Difficulty:
waveSettingswith up to wave 8: march × f, fire interval / f, start up to 24 px lower, faster and more alien bullets; on top of the march's own speed-up as aliens die. - Score: 30 / 20 / 10 per alien (990 per wave), the saucer 50–300 (random, 150 on average), one extra ship at 1500; all through
addScore, which flashes the digits for 0.15 s. - HUD: inside the canvas in
pixel5(×1 labels, ×2 numbers, 1 px shadow withshadowOffset = 1 / scale), drawn on top of the arena with the steady camera;mono16only for the bilingual lines, every string checked against the atlas. - Shake: trauma (capped at 1, −1.6 per second), offset round(3 · trauma² · r) in whole pixels, its own
Rng{29}, updated in the fixed step; applied by moving the camera for the arena only and hidden at the edges by drawing the panels afterwards. Below trauma 0.408 it rounds to nothing. - Flashes: a translucent rectangle over the arena, alpha −3 per second (0.12–0.17 s).
- CRT: the canvas texture drawn with
post.vertandcrt.fraginto the same integer letterbox instead of a blit: glow (+6 % of 4 neighbors), scanlines (the lowest of 4 screen rows × 0.62, the others × 1.06, average 0.95) fromgl_FragCoordrelative to the viewport, a 3-column RGB mask (average 1.0) and a vignette; no flip needed, blending off; the UI is drawn after it at full resolution.
29.18 Challenges
- ★ Save the high score: on game over, write
hiScoretogames/invaders/highscore.txt, and read it inmainwith the engine'sreadTextFilebefore the title starts. After a restart the title should show the best score instead of 00000; with no file (or a broken one) it should start at 0 as before. Then think about where such a file really belongs (%APPDATA%,$XDG_DATA_HOME) and why a game shouldn't write into its own install folder. - ★ Shake the HUD too: in
PlayScene::draw, moveg.world = steady;from the start of the steady part (the last pass) to the very end of the function, so the panels and the HUD are drawn with the shaken camera (and the camera is still restored for the next frame). When the ship is hit, the side panels and their digits should now jitter along with the arena, and for a moment a 1–2 px strip of the darker canvas clear color should show at the edge of the canvas that a panel moved away from. That's why the code draws the panels with the steady camera, on top. - ★ Make the extra ship repeat every 1500 points: replace
bool extraLifewithint nextExtraLife = kExtraLifeScoreinRunand raise it by 1500 each time a ship is given. "1UP" should appear at 1500, 3000, 4500 and so on; why must the field stay inRunand not move intoPlayScene? - ★★ The arcade's saucer table: replace the random choice with a 15-entry table indexed by
shotsFired % 15, with 300 at index 8 and a mix of 50, 100 and 150 elsewhere. Hitting the saucer with the 23rd shot (and the 38th, 53rd…) should always give 300, which you can check by printingshotsFirednext to "saucer hit".shotsFiredis aPlayScenemember, so it starts at 0 every wave; decide whether it belongs inRuninstead, and see how the answer changes which shots score 300 in wave 2. - ★★ Hit stop: when an alien dies, freeze the playfield for 3 updates (0.05 s) by counting down a
hitStopmember at the top ofPlayScene::updateand returning early while it's above 0 (but keep the pause key working). Kills should feel heavier; because the march timer pauses too, a wave should take slightly longer overall (55 kills × 0.05 s ≈ 2.75 s more). - ★★ Curve the tube: at the start of
crt.frag'smain, distort the coordinate withvec2 uv = vUv + (vUv - 0.5) * dot(vUv - 0.5, vUv - 0.5) * 0.1;, sample withuvinstead ofvUv, and write black whereuvis outside 0…1. The picture should bulge like a curved screen, with black corners; look closely at the edges and you'll see that nearest sampling now gives slightly uneven pixel widths there: chapter 25's integer-scale rule broken on purpose. - ★★★ Two players taking turns: give
GametwoRuns and acurrentindex, and on every lost ship switch players with a "PLAYER 2" banner. Each player must find their own half-eaten formation and their own shields again, so the play scene can no longer just be rebuilt from the wave number: save the formation (positions, alive flags, march state) and the shields' CPU pixels into the player'sRunbefore the replace, and restore them in the constructor. Scene reloading now has to restore state, not just reset it; when it works, each player should resume exactly where they left off.
ファイル: a/games/invaders/CMakeLists.txt | b/games/invaders/CMakeLists.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -3,11 +3,16 @@ | |||
| 3 | # project root | 3 | # project root |
| 4 | add_executable(invaders | 4 | add_executable(invaders |
| 5 | src/main.cc | 5 | src/main.cc |
| 6 | src/game.cc | ||
| 7 | src/title_scene.cc | ||
| 6 | src/play_scene.cc | 8 | src/play_scene.cc |
| 9 | src/menus.cc | ||
| 10 | src/backdrop.cc | ||
| 7 | src/formation.cc | 11 | src/formation.cc |
| 8 | src/formation_renderer.cc | 12 | src/formation_renderer.cc |
| 9 | src/shields.cc | 13 | src/shields.cc |
| 10 | src/effects.cc) | 14 | src/effects.cc |
| 15 | src/crt.cc) | ||
| 11 | target_include_directories(invaders PRIVATE src) | 16 | target_include_directories(invaders PRIVATE src) |
| 12 | target_link_libraries(invaders PRIVATE engine) | 17 | target_link_libraries(invaders PRIVATE engine) |
| 13 | enable_warnings(invaders) | 18 | enable_warnings(invaders) |
ファイル: a/games/invaders/README.md | b/games/invaders/README.md
| 前 | 新 | ||
|---|---|---|---|
| @@ -12,20 +12,31 @@ is already the project root)。 | |||
| 12 | ## 操作 / Controls | 12 | ## 操作 / Controls |
| 13 | | キー / Key | | | 13 | | キー / Key | | |
| 14 | |---|---| | 14 | |---|---| |
| 15 | | Space / Enter | タイトル:開始 / title: start | | ||
| 15 | | ← → / A D | 移動 / move | | 16 | | ← → / A D | 移動 / move | |
| 16 | | Space / ↑ / W | 撃つ / fire | | 17 | | Space / ↑ / W | 撃つ / fire | |
| 17 | | I | 隊列の描き方:インスタンシング ⇔ SpriteBatch / formation: instancing ⇔ SpriteBatch | | 18 | | P / Esc | 一時停止(↑ ↓ で選んで Space / Enter) / pause (↑ ↓ to choose, Space / Enter) | |
| 18 | | B | 当たり判定の箱 / collision boxes | | 19 | | Esc | タイトルで:終了 / on the title: quit | |
| 19 | | = / - | 行進を速く・遅く / march faster / slower | | 20 | | C | ブラウン管風の仕上げ オン・オフ / CRT finish on / off | |
| 20 | | Space / Enter | ゲームオーバーの後:もう一度 / after game over: play again | | 21 | | Tab | 開発用の数字 / developer numbers | |
| 21 | | Esc | 終了 / quit | | 22 | | I | 隊列の描き方:インスタンシング ⇔ SpriteBatch(開発用) / formation: instancing ⇔ SpriteBatch (developer) | |
| 23 | | B | 当たり判定の箱(開発用) / collision boxes (developer) | | ||
| 24 | | = / - | 行進を速く・遅く(開発用) / march faster / slower (developer) | | ||
| 25 | | N | 次の波へ(開発用、点は入らない) / next wave (developer, no points) | | ||
| 26 | |||
| 27 | 点数 / points: クラゲ / jelly 30, 甲虫 / beetle 20, 丸い奴 / blob 10, 円盤 / saucer 50-300。1500点で1機増える / an extra | ||
| 28 | ship at 1500 points。 | ||
| 22 | 29 | ||
| 23 | ## ファイル / Files | 30 | ## ファイル / Files |
| 24 | * `src/main.cc` ウィンドウ、読み込み、行動、ゲームループ / window, loading, actions, game loop | 31 | * `src/main.cc` ウィンドウ、読み込み、行動、ゲームループ、ブラウン管風の仕上げ / window, loading, actions, game loop, CRT |
| 25 | * `src/game.hh` 共有データ・画面の寸法・シーン / shared data, layout, scenes | 32 | * `src/game.hh/.cc` 共有データ(`Game`、`Run`)、波の難しさ、シーンの宣言 / shared data, wave difficulty, scenes |
| 26 | * `src/play_scene.cc` 遊ぶ場面 / the play scene | 33 | * `src/layout.hh` 画面の寸法 / the layout |
| 34 | * `src/title_scene.cc`, `src/play_scene.cc`, `src/menus.cc` タイトル・遊ぶ場面・一時停止とゲームオーバー / title, play, | ||
| 35 | pause and game over | ||
| 36 | * `src/backdrop.hh/.cc` 星と脇の板 / stars and side panels | ||
| 27 | * `src/formation.hh/.cc` 隊列と行進(GLなし) / the formation and its march (no GL) | 37 | * `src/formation.hh/.cc` 隊列と行進(GLなし) / the formation and its march (no GL) |
| 28 | * `src/formation_renderer.hh/.cc`, `shaders/formation.vert` インスタンシングで隊列を描く / instanced formation drawing | 38 | * `src/formation_renderer.hh/.cc`, `shaders/formation.vert` インスタンシングで隊列を描く / instanced formation drawing |
| 29 | * `src/shields.hh/.cc` 削れる防壁(CPUのピクセル+glTextureSubImage2D) / eroding shields (CPU pixels + glTextureSubImage2D) | 39 | * `src/shields.hh/.cc` 削れる防壁(CPUのピクセル+glTextureSubImage2D) / eroding shields (CPU pixels + glTextureSubImage2D) |
| 30 | * `src/effects.hh/.cc` 破片と着弾 / debris particles and impact flares | 40 | * `src/effects.hh/.cc` 破片、着弾、画面の揺れ、閃光 / debris, impacts, screen shake, flashes |
| 41 | * `src/crt.hh/.cc`, `shaders/crt.frag` ブラウン管風の仕上げ / the CRT finish | ||
| 31 | * `assets/` 絵(作者の自作スクリプトで生成。スクリプトはダウンロードに含まれない) / art (generated by the author's own script, not part of the download) | 42 | * `assets/` 絵(作者の自作スクリプトで生成。スクリプトはダウンロードに含まれない) / art (generated by the author's own script, not part of the download) |
ファイル: /dev/null | b/games/invaders/shaders/crt.frag
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,37 @@ | |||
| 1 | #version 460 core | ||
| 2 | // ブラウン管風(第29章):320 × 180のキャンバスを整数倍で画面に。色はsRGBの値のまま計算する(2Dの約束) | ||
| 3 | // CRT style (chapter 29): the 320 × 180 canvas at a whole-number scale. Colors stay sRGB-encoded values (the 2D rule) | ||
| 4 | in vec2 vUv; // engine/shaders/post.vert:ビューポートの中で0〜1、下が0 / 0..1 across the viewport, 0 at the bottom | ||
| 5 | |||
| 6 | layout(binding = 0) uniform sampler2D uCanvas; // GL_NEARESTのキャンバス / the GL_NEAREST canvas | ||
| 7 | |||
| 8 | uniform vec2 uCanvasSize; // (320, 180) | ||
| 9 | uniform float uScale; // 画面のピクセル / キャンバスのピクセル(4) / screen pixels per canvas pixel (4) | ||
| 10 | uniform vec2 uOrigin; // ビューポートの左下(ウィンドウのピクセル) / the viewport's bottom left (window pixels) | ||
| 11 | |||
| 12 | layout(location = 0) out vec4 out_color; | ||
| 13 | |||
| 14 | void main() { | ||
| 15 | vec2 texel = 1.0 / uCanvasSize; | ||
| 16 | vec3 color = texture(uCanvas, vUv).rgb; | ||
| 17 | // にじみ:上下左右のキャンバスのピクセルを少し足す(明るい物の周りがぼんやり光る) | ||
| 18 | // Glow: add a little of the canvas pixels around (bright things get a soft halo) | ||
| 19 | vec3 around = texture(uCanvas, vUv + vec2(texel.x, 0.0)).rgb + texture(uCanvas, vUv - vec2(texel.x, 0.0)).rgb + | ||
| 20 | texture(uCanvas, vUv + vec2(0.0, texel.y)).rgb + texture(uCanvas, vUv - vec2(0.0, texel.y)).rgb; | ||
| 21 | color += 0.06 * around; | ||
| 22 | |||
| 23 | // 画面のピクセルが、キャンバスのピクセルの中のどこか(0〜uScale-1)。gl_FragCoordはピクセルの中心(+0.5) | ||
| 24 | // Where this screen pixel lies inside its canvas pixel (0..uScale-1). gl_FragCoord is a pixel center (+0.5) | ||
| 25 | vec2 inside = mod(floor(gl_FragCoord.xy - uOrigin), uScale); | ||
| 26 | // 走査線:キャンバスの各行の一番下の画面の行を暗く / scanlines: the lowest screen row of every canvas row is darker | ||
| 27 | float scan = inside.y < 0.5 ? 0.62 : 1.06; | ||
| 28 | // 蛍光体の縞:画面の列ごとに赤・緑・青を少しだけ強める / phosphor mask: every screen column leans a little towards | ||
| 29 | // red, green or blue in turn | ||
| 30 | int column = int(mod(floor(gl_FragCoord.x), 3.0)); | ||
| 31 | vec3 mask = column == 0 ? vec3(1.06, 0.97, 0.97) : column == 1 ? vec3(0.97, 1.06, 0.97) : vec3(0.97, 0.97, 1.06); | ||
| 32 | // 周辺減光:四隅が少し暗い / vignette: the corners are a little darker | ||
| 33 | vec2 d = vUv - 0.5; | ||
| 34 | float vignette = 1.0 - 0.35 * dot(d, d); | ||
| 35 | |||
| 36 | out_color = vec4(clamp(color * scan * mask * vignette, 0.0, 1.0), 1.0); | ||
| 37 | } | ||
ファイル: /dev/null | b/games/invaders/src/backdrop.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,27 @@ | |||
| 1 | #include "backdrop.hh" | ||
| 2 | |||
| 3 | #include "engine/rng.hh" | ||
| 4 | |||
| 5 | #include <cmath> | ||
| 6 | |||
| 7 | Backdrop::Backdrop() { | ||
| 8 | Rng sky(1978); | ||
| 9 | for (int i = 0; i < 40; ++i) | ||
| 10 | stars.push_back({{std::round(sky.range(kArenaLeft + 2.0f, kArenaRight - 2.0f)), std::round(sky.range(4.0f, 150.0f))}, | ||
| 11 | sky.unit()}); | ||
| 12 | } | ||
| 13 | |||
| 14 | void Backdrop::drawSky(SpriteBatch &b, float time) const { | ||
| 15 | for (const Star &s : stars) { | ||
| 16 | float t = 0.5f + 0.5f * std::sin(2.0f * time + 6.283f * s.phase); | ||
| 17 | b.drawRect({s.position.x, s.position.y, 1.0f, 1.0f}, {0.62f, 0.64f, 0.8f, 0.25f + 0.5f * t}); | ||
| 18 | } | ||
| 19 | b.drawRect({kArenaLeft, kGroundY, kArenaRight - kArenaLeft, 1.0f}, hexColor(0x68c454ff)); | ||
| 20 | } | ||
| 21 | |||
| 22 | void Backdrop::drawPanels(SpriteBatch &b) const { | ||
| 23 | b.drawRect({0.0f, 0.0f, kArenaLeft, kView.y}, hexColor(0x16132aff)); | ||
| 24 | b.drawRect({kArenaRight, 0.0f, kView.x - kArenaRight, kView.y}, hexColor(0x16132aff)); | ||
| 25 | b.drawRect({kArenaLeft - 1.0f, 0.0f, 1.0f, kView.y}, hexColor(0x3a3460ff)); | ||
| 26 | b.drawRect({kArenaRight, 0.0f, 1.0f, kView.y}, hexColor(0x3a3460ff)); | ||
| 27 | } | ||
ファイル: /dev/null | b/games/invaders/src/backdrop.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,25 @@ | |||
| 1 | // 背景(第29章でタイトルと遊ぶ場面の共通に):瞬く星、地面、脇の板 | ||
| 2 | // The backdrop (shared by the title and the play scene from chapter 29): twinkling stars, the ground, the side panels | ||
| 3 | #pragma once | ||
| 4 | |||
| 5 | #include "layout.hh" | ||
| 6 | |||
| 7 | #include "engine/sprite_batch.hh" | ||
| 8 | |||
| 9 | #include <vector> | ||
| 10 | |||
| 11 | class Backdrop { | ||
| 12 | public: | ||
| 13 | Backdrop(); // 星は自分の種で作る:何度場面を作り直しても同じ空 / stars use their own seed: the same sky every time | ||
| 14 | void drawSky(SpriteBatch &batch, float time) const; // 星と地面(戦場の中) / stars and ground (inside the arena) | ||
| 15 | // 脇の板と枠。戦場の物(揺れではみ出した分も)の上に描いて隠す / the side panels and borders, drawn over the | ||
| 16 | // arena's contents so they hide whatever a shake pushes out | ||
| 17 | void drawPanels(SpriteBatch &batch) const; | ||
| 18 | |||
| 19 | private: | ||
| 20 | struct Star { | ||
| 21 | Vec2 position; | ||
| 22 | float phase; | ||
| 23 | }; | ||
| 24 | std::vector<Star> stars; | ||
| 25 | }; | ||
ファイル: /dev/null | b/games/invaders/src/crt.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,30 @@ | |||
| 1 | #include "crt.hh" | ||
| 2 | |||
| 3 | std::optional<CrtFilter> CrtFilter::create() { | ||
| 4 | CrtFilter crt; | ||
| 5 | crt.shader = Shader::load("engine/shaders/post.vert", "games/invaders/shaders/crt.frag"); | ||
| 6 | if (!crt.shader) return std::nullopt; | ||
| 7 | return crt; | ||
| 8 | } | ||
| 9 | |||
| 10 | Viewport CrtFilter::present(const PixelCanvas &canvas, int windowWidth, int windowHeight) const { | ||
| 11 | Viewport v = letterbox(windowWidth, windowHeight, canvas.size(), true); | ||
| 12 | Framebuffer::bindDefault(windowWidth, windowHeight); | ||
| 13 | glClearColor(0.0f, 0.0f, 0.0f, 1.0f); | ||
| 14 | glClear(GL_COLOR_BUFFER_BIT); | ||
| 15 | v.apply(); | ||
| 16 | // 不透明な一枚の絵:ブレンドは要らない(SpriteBatch::beginがまた有効にする) / one opaque picture: no blending | ||
| 17 | // (SpriteBatch::begin turns it back on) | ||
| 18 | glDisable(GL_BLEND); | ||
| 19 | glDisable(GL_DEPTH_TEST); | ||
| 20 | shader->set("uCanvasSize", canvas.size()); | ||
| 21 | shader->set("uScale", v.scale); | ||
| 22 | shader->set("uOrigin", Vec2{static_cast<float>(v.x), static_cast<float>(v.y)}); | ||
| 23 | // FBOの色テクスチャは下の行がv = 0。post.vertのvUvも下が0なので、そのまま貼れば上下は正しい | ||
| 24 | // An FBO color texture has its bottom row at v = 0. post.vert's vUv is 0 at the bottom too, so it maps the right | ||
| 25 | // way up as it is | ||
| 26 | canvas.framebuffer().color().bind(0); | ||
| 27 | shader->use(); | ||
| 28 | triangle.draw(); | ||
| 29 | return v; | ||
| 30 | } | ||
ファイル: /dev/null | b/games/invaders/src/crt.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,26 @@ | |||
| 1 | // ブラウン管風の仕上げ(第29章):PixelCanvasのテクスチャを、ただ拡大コピー(present)する代わりに | ||
| 2 | // シェーダーで画面に描く。走査線、蛍光体の縞、にじみ、周辺減光 | ||
| 3 | // A CRT-style finish (chapter 29): instead of the plain scaled copy (present), the PixelCanvas texture is drawn to the | ||
| 4 | // screen through a shader: scanlines, a phosphor mask, a little glow, a vignette | ||
| 5 | #pragma once | ||
| 6 | |||
| 7 | #include "engine/framebuffer.hh" | ||
| 8 | #include "engine/pixel_canvas.hh" | ||
| 9 | #include "engine/shader.hh" | ||
| 10 | |||
| 11 | #include <optional> | ||
| 12 | |||
| 13 | class CrtFilter { | ||
| 14 | public: | ||
| 15 | // engine/shaders/post.vert(画面全体の三角形)+ games/invaders/shaders/crt.frag | ||
| 16 | // engine/shaders/post.vert (the fullscreen triangle) + games/invaders/shaders/crt.frag | ||
| 17 | static std::optional<CrtFilter> create(); | ||
| 18 | // PixelCanvas::presentと同じ場所(整数倍のレターボックス)に描き、その場所を返す。帯は黒 | ||
| 19 | // Draws to the same place as PixelCanvas::present (the integer-scaled letterbox) and returns it. Black bars | ||
| 20 | Viewport present(const PixelCanvas &canvas, int windowWidth, int windowHeight) const; | ||
| 21 | |||
| 22 | private: | ||
| 23 | CrtFilter() = default; | ||
| 24 | std::optional<Shader> shader; | ||
| 25 | FullscreenTriangle triangle; | ||
| 26 | }; | ||
ファイル: a/games/invaders/src/effects.cc | b/games/invaders/src/effects.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -27,3 +27,11 @@ void Particles::draw(SpriteBatch &batch, float layer) const { | |||
| 27 | batch.drawRect({std::round(p.position.x), std::round(p.position.y), 1.0f, 1.0f}, c, layer); | 27 | batch.drawRect({std::round(p.position.x), std::round(p.position.y), 1.0f, 1.0f}, c, layer); |
| 28 | } | 28 | } |
| 29 | } | 29 | } |
| 30 | |||
| 31 | void Shake::add(float a) { amount = std::min(1.0f, amount + a); } | ||
| 32 | |||
| 33 | void Shake::update(float dt) { | ||
| 34 | amount = std::max(0.0f, amount - 1.6f * dt); | ||
| 35 | float k = 3.0f * amount * amount; | ||
| 36 | current = {std::round(k * rng.range(-1.0f, 1.0f)), std::round(k * rng.range(-1.0f, 1.0f))}; | ||
| 37 | } | ||
ファイル: a/games/invaders/src/effects.hh | b/games/invaders/src/effects.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,10 +1,13 @@ | |||
| 1 | // 爆発の飾り(第28章):飛び散るピクセル(パーティクル)と、短く見せるスプライト(着弾など) | 1 | // 爆発の飾り(第28章):飛び散るピクセル(パーティクル)と、短く見せるスプライト(着弾など)。 |
| 2 | // Explosion dressing (chapter 28): flying pixels (particles) and sprites shown for a moment (impacts and such) | 2 | // 第29章:画面の揺れと閃光 |
| 3 | // Explosion dressing (chapter 28): flying pixels (particles) and sprites shown for a moment (impacts and such). | ||
| 4 | // Chapter 29: screen shake and flashes | ||
| 3 | #pragma once | 5 | #pragma once |
| 4 | 6 | ||
| 5 | #include "engine/rng.hh" | 7 | #include "engine/rng.hh" |
| 6 | #include "engine/sprite_batch.hh" | 8 | #include "engine/sprite_batch.hh" |
| 7 | 9 | ||
| 10 | #include <algorithm> | ||
| 8 | #include <vector> | 11 | #include <vector> |
| 9 | 12 | ||
| 10 | // 1ピクセルの破片。固定ステップで動き、だんだん消える / one-pixel debris: moves in the fixed step and fades out | 13 | // 1ピクセルの破片。固定ステップで動き、だんだん消える / one-pixel debris: moves in the fixed step and fades out |
| @@ -34,3 +37,27 @@ struct Flare { | |||
| 34 | float life; // 残り秒 / seconds left | 37 | float life; // 残り秒 / seconds left |
| 35 | Vec4 color; | 38 | Vec4 color; |
| 36 | }; | 39 | }; |
| 40 | |||
| 41 | // 画面の揺れ(第29章):「トラウマ」(0〜1)を足し、時間とともに減らす。ずれ = 最大3ピクセル × トラウマ²、 | ||
| 42 | // 整数のピクセル(ピクセルアートの格子からはみ出さない)。乱数は自分の種:揺れがゲームの乱数の並びを変えない | ||
| 43 | // Screen shake (chapter 29): add "trauma" (0..1), which decays over time. Offset = up to 3 px × trauma², in whole | ||
| 44 | // pixels (stays on the pixel-art grid). Its own random seed: shaking does not change the game's random sequence | ||
| 45 | class Shake { | ||
| 46 | public: | ||
| 47 | void add(float amount); | ||
| 48 | void update(float dt); // 固定ステップで / in the fixed step | ||
| 49 | Vec2 offset() const { return current; } | ||
| 50 | float trauma() const { return amount; } | ||
| 51 | |||
| 52 | private: | ||
| 53 | float amount = 0.0f; | ||
| 54 | Vec2 current = {0.0f, 0.0f}; | ||
| 55 | Rng rng{29}; | ||
| 56 | }; | ||
| 57 | |||
| 58 | // 閃光:色の四角を一瞬かぶせ、すぐに消す / a flash: a colored rectangle over the arena for a moment, fading fast | ||
| 59 | struct ScreenFlash { | ||
| 60 | Vec4 color = {1.0f, 1.0f, 1.0f, 0.0f}; | ||
| 61 | void start(Vec4 c) { color = c; } | ||
| 62 | void update(float dt) { color.w = std::max(0.0f, color.w - 3.0f * dt); } // 約0.2秒で消える / gone in ~0.2 s | ||
| 63 | }; | ||
ファイル: /dev/null | b/games/invaders/src/game.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,27 @@ | |||
| 1 | // 場面をまたいで使う小さな道具 / small helpers shared by the scenes | ||
| 2 | #include "game.hh" | ||
| 3 | |||
| 4 | #include <algorithm> | ||
| 5 | |||
| 6 | // 波wの難しさ。8波目からは同じ / the difficulty of wave w; constant from wave 8 | ||
| 7 | WaveSettings waveSettings(int wave) { | ||
| 8 | int w = std::clamp(wave, 1, 8) - 1; | ||
| 9 | float faster = 1.0f + 0.15f * static_cast<float>(w); | ||
| 10 | return {.top = kFormationTop + 6.0f * static_cast<float>(std::min(w, 4)), // 最大4段(24ピクセル)低く / up to 4 | ||
| 11 | // steps (24 px) lower | ||
| 12 | .marchRate = 60.0f * faster, | ||
| 13 | .fireMin = 0.5f / faster, | ||
| 14 | .fireMax = 1.1f / faster, | ||
| 15 | .shotSpeed = 75.0f + 7.5f * static_cast<float>(w), | ||
| 16 | .maxShots = 3 + (w >= 2) + (w >= 5)}; | ||
| 17 | } | ||
| 18 | |||
| 19 | void drawTinyText(Game &g, const char *text, Vec2 position, Vec4 color, float scale, TextAlign align) { | ||
| 20 | // pixel5は3 × 5の1ビットの文字。整数倍なら崩れない。影 = 輪郭の色で1ピクセル右下(shadowOffsetは | ||
| 21 | // scale倍されるので1/scale) | ||
| 22 | // pixel5 is a 1-bit 3 × 5 font; whole-number scales keep it crisp. Shadow = the outline color, 1 px down right | ||
| 23 | // (shadowOffset is multiplied by scale, hence 1/scale) | ||
| 24 | g.tiny.draw(g.batch, text, position, | ||
| 25 | {.color = color, .scale = scale, .align = align, .shadow = hexColor(0x1b1726ff), | ||
| 26 | .shadowOffset = {1.0f / scale, 1.0f / scale}}); | ||
| 27 | } | ||
ファイル: a/games/invaders/src/game.hh | b/games/invaders/src/game.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -2,9 +2,11 @@ | |||
| 2 | // Invaders: the data every scene shares, the screen layout, the scenes | 2 | // Invaders: the data every scene shares, the screen layout, the scenes |
| 3 | #pragma once | 3 | #pragma once |
| 4 | 4 | ||
| 5 | #include "backdrop.hh" | ||
| 5 | #include "effects.hh" | 6 | #include "effects.hh" |
| 6 | #include "formation.hh" | 7 | #include "formation.hh" |
| 7 | #include "formation_renderer.hh" | 8 | #include "formation_renderer.hh" |
| 9 | #include "layout.hh" | ||
| 8 | #include "shields.hh" | 10 | #include "shields.hh" |
| 9 | 11 | ||
| 10 | #include "engine/animation.hh" | 12 | #include "engine/animation.hh" |
| @@ -20,20 +22,31 @@ | |||
| 20 | #include <optional> | 22 | #include <optional> |
| 21 | #include <vector> | 23 | #include <vector> |
| 22 | 24 | ||
| 23 | // 仮想解像度320 × 180(ウィンドウ1280 × 720で4倍)。真ん中の224ピクセル幅が戦場、左右48ピクセルは脇の板 | 25 | // 速さと決まり(画面の寸法はlayout.hh) / speeds and rules (the layout is in layout.hh) |
| 24 | // Virtual resolution 320 × 180 (× 4 in the 1280 × 720 window). The middle 224 pixels are the arena, 48 pixels on | ||
| 25 | // each side are side panels | ||
| 26 | constexpr Vec2 kView = {320.0f, 180.0f}; | ||
| 27 | constexpr float kArenaLeft = 48.0f, kArenaRight = 272.0f; | ||
| 28 | constexpr float kFormationTop = 28.0f; // 最初の隊列の一番上 / the first formation's top row | ||
| 29 | constexpr float kShieldY = 136.0f; // 防壁の上端 / the shields' top | ||
| 30 | constexpr float kPlayerY = 158.0f; // 自機の上端 / the ship's top | ||
| 31 | constexpr float kGroundY = 170.0f; // 地面の線 / the ground line | ||
| 32 | constexpr float kPlayerSpeed = 60.0f; // ピクセル毎秒(1ステップ1ピクセル) / pixels per second (1 px per step) | 26 | constexpr float kPlayerSpeed = 60.0f; // ピクセル毎秒(1ステップ1ピクセル) / pixels per second (1 px per step) |
| 33 | constexpr float kShotSpeed = 240.0f; // 自機の弾:1ステップ4ピクセル / the ship's bullet: 4 px per step | 27 | constexpr float kShotSpeed = 240.0f; // 自機の弾:1ステップ4ピクセル / the ship's bullet: 4 px per step |
| 34 | constexpr float kAlienShotSpeed = 75.0f; // 宇宙人の弾 / alien bullets | ||
| 35 | constexpr int kMaxAlienShots = 3; | ||
| 36 | constexpr int kStartLives = 3; | 28 | constexpr int kStartLives = 3; |
| 29 | constexpr int kExtraLifeScore = 1500; // 一度だけ1機増える / one extra ship, once | ||
| 30 | |||
| 31 | // 波ごとの難しさ(第29章):先へ進むほど低い所から始まり、速く行進し、よく撃つ | ||
| 32 | // Difficulty per wave (chapter 29): later waves start lower, march faster and shoot more | ||
| 33 | struct WaveSettings { | ||
| 34 | float top; // 隊列の一番上の行 / the formation's top row | ||
| 35 | float marchRate; // 1秒に動く宇宙人の数 / aliens moved per second | ||
| 36 | float fireMin, fireMax; // 宇宙人が撃つ間隔(秒) / seconds between alien shots | ||
| 37 | float shotSpeed; // 宇宙人の弾の速さ / alien bullet speed | ||
| 38 | int maxShots; // 画面に出せる宇宙人の弾 / alien bullets on screen at once | ||
| 39 | }; | ||
| 40 | WaveSettings waveSettings(int wave); | ||
| 41 | |||
| 42 | // 一回の遊び(タイトルで作り直す)。波が変わっても場面をまたいで残る / one game (reset on the title). Survives the | ||
| 43 | // scene reload between waves | ||
| 44 | struct Run { | ||
| 45 | int score = 0; | ||
| 46 | int lives = kStartLives; | ||
| 47 | int wave = 1; | ||
| 48 | bool extraLife = false; | ||
| 49 | }; | ||
| 37 | 50 | ||
| 38 | // ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference | 51 | // ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference |
| 39 | struct Game { | 52 | struct Game { |
| @@ -43,50 +56,98 @@ struct Game { | |||
| 43 | SpriteBatch &batch; | 56 | SpriteBatch &batch; |
| 44 | FormationRenderer &formationRenderer; | 57 | FormationRenderer &formationRenderer; |
| 45 | const Font &ui; // mono16:画面の解像度の文字 / text at screen resolution | 58 | const Font &ui; // mono16:画面の解像度の文字 / text at screen resolution |
| 59 | const Font &tiny; // pixel5:キャンバスの中のHUD(3 × 5、大文字と数字) / the canvas HUD (3 × 5, capitals | ||
| 60 | // and digits) | ||
| 46 | const SpriteSheet &sprites; // games/invaders/assets/sprites.atlas | 61 | const SpriteSheet &sprites; // games/invaders/assets/sprites.atlas |
| 47 | const Image &shieldArt; // 防壁の絵(CPU側、削る元) / the shield art (CPU side, what gets eroded) | 62 | const Image &shieldArt; // 防壁の絵(CPU側、削る元) / the shield art (CPU side, what gets eroded) |
| 63 | const Backdrop &backdrop; // 星と脇の板 / the stars and the side panels | ||
| 48 | Camera2D world; // 320 × 180のキャンバス / the 320 × 180 canvas | 64 | Camera2D world; // 320 × 180のキャンバス / the 320 × 180 canvas |
| 49 | Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI | 65 | Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI |
| 50 | Viewport uiViewport; | 66 | Viewport uiViewport; |
| 51 | Rng rng{27}; | 67 | Rng rng{27}; |
| 68 | Run run{}; | ||
| 69 | int hiScore = 0; // この起動の間だけ覚える(電源を入れたゲーム機と同じく0から) / remembered while the | ||
| 70 | // program runs (starts at 0, like an arcade machine just switched on) | ||
| 52 | bool instanced = true; // 隊列をインスタンシングで(I) / draw the formation instanced (I) | 71 | bool instanced = true; // 隊列をインスタンシングで(I) / draw the formation instanced (I) |
| 53 | bool showBoxes = false; // 当たり判定の箱(B) / collision boxes (B) | 72 | bool showBoxes = false; // 当たり判定の箱(B) / collision boxes (B) |
| 73 | bool crt = true; // ブラウン管風の仕上げ(C) / the CRT-style finish (C) | ||
| 74 | bool devInfo = false; // 開発用の数字(Tab) / developer numbers (Tab) | ||
| 75 | // 開発用の数字(Tabで画面の下に) / developer numbers (shown at the bottom with Tab) | ||
| 76 | int formationDrawCalls = 0, formationBytes = 0, shieldBytes = 0; | ||
| 54 | }; | 77 | }; |
| 55 | 78 | ||
| 56 | // 遊ぶ場面:自機、行進する隊列、弾、防壁、爆発 / the play scene: the ship, the marching formation, bullets, | 79 | // スコアの5桁表示とHUDの文字(pixel5、キャンバスの中) / the 5-digit score and HUD text (pixel5, inside the canvas) |
| 57 | // shields, explosions | 80 | void drawTinyText(Game &g, const char *text, Vec2 position, Vec4 color, float scale = 1.0f, |
| 81 | TextAlign align = TextAlign::Left); | ||
| 82 | |||
| 83 | // タイトル:ロゴ、点数表、最高得点。スペースで始める / the title: logo, score table, high score. Space starts | ||
| 84 | class TitleScene : public Scene { | ||
| 85 | public: | ||
| 86 | explicit TitleScene(Game &game) : g(game) {} | ||
| 87 | void enter() override; | ||
| 88 | void update(float dt) override; | ||
| 89 | void draw(float alpha) override; | ||
| 90 | void drawUi(float alpha) override; | ||
| 91 | |||
| 92 | private: | ||
| 93 | Game &g; | ||
| 94 | float time = 0.0f; | ||
| 95 | float ufoX = 180.0f, ufoPrevX = 180.0f; | ||
| 96 | }; | ||
| 97 | |||
| 98 | // 遊ぶ場面:一つの波。全滅させたら、波の番号を上げて自分を新しい場面と入れ替える(場面の読み直し) | ||
| 99 | // The play scene: one wave. When the wave is wiped out it raises the wave number and replaces itself with a fresh | ||
| 100 | // scene (scene reloading) | ||
| 58 | class PlayScene : public Scene { | 101 | class PlayScene : public Scene { |
| 59 | public: | 102 | public: |
| 60 | explicit PlayScene(Game &game); | 103 | explicit PlayScene(Game &game); |
| 104 | void enter() override; | ||
| 61 | void pause() override; | 105 | void pause() override; |
| 62 | void update(float dt) override; | 106 | void update(float dt) override; |
| 63 | void draw(float alpha) override; | 107 | void draw(float alpha) override; |
| 64 | void drawUi(float alpha) override; | 108 | void drawUi(float alpha) override; |
| 65 | 109 | ||
| 66 | private: | 110 | private: |
| 67 | struct Star { | 111 | enum class Phase { Ready, Playing, ShipDown, Cleared, Over }; |
| 68 | Vec2 position; | ||
| 69 | float phase; | ||
| 70 | }; | ||
| 71 | // 弾:当たり判定の箱と、補間用の前のステップのy / a bullet: its collision box and last step's y (interpolation) | 112 | // 弾:当たり判定の箱と、補間用の前のステップのy / a bullet: its collision box and last step's y (interpolation) |
| 72 | struct Bullet { | 113 | struct Bullet { |
| 73 | Rect box; | 114 | Rect box; |
| 74 | float prevY; | 115 | float prevY; |
| 75 | Animator anim; // 宇宙人の弾は4コマのクリップ / alien bullets play a 4-frame clip | 116 | Animator anim; // 宇宙人の弾は4コマのクリップ / alien bullets play a 4-frame clip |
| 76 | }; | 117 | }; |
| 118 | struct Ufo { | ||
| 119 | bool active = false; | ||
| 120 | float x = 0.0f, prevX = 0.0f, direction = 1.0f; | ||
| 121 | Rect box() const { return {x + 1.0f, kUfoY + 1.0f, 16.0f, 6.0f}; } | ||
| 122 | }; | ||
| 123 | // 点数が浮かぶ(円盤、1UP) / floating score text (the saucer, 1UP) | ||
| 124 | struct Popup { | ||
| 125 | Vec2 position; | ||
| 126 | float life; | ||
| 127 | char text[12]; | ||
| 128 | Vec4 color; | ||
| 129 | }; | ||
| 130 | void setPhase(Phase p); | ||
| 77 | int alienFrame(const Alien &a) const; | 131 | int alienFrame(const Alien &a) const; |
| 78 | Rect shipBox() const; | 132 | Rect shipBox() const; |
| 79 | void fire(); | 133 | void fire(); |
| 80 | void alienFire(float dt); | 134 | void alienFire(float dt); |
| 81 | void updateShot(float dt); | 135 | void updateShot(float dt); |
| 82 | void updateAlienShots(float dt); | 136 | void updateAlienShots(float dt); |
| 137 | void updateUfo(float dt); | ||
| 83 | void killShip(); | 138 | void killShip(); |
| 139 | void addScore(int points); | ||
| 140 | void popup(Vec2 position, const char *text, Vec4 color); | ||
| 84 | void flare(Vec2 centre, Vec4 color, float life = 0.12f); | 141 | void flare(Vec2 centre, Vec4 color, float life = 0.12f); |
| 85 | void drawBackground(); | ||
| 86 | void drawFormation(); | 142 | void drawFormation(); |
| 87 | void drawBoxes(); | 143 | void drawBoxes(); |
| 144 | void drawHud(); | ||
| 88 | 145 | ||
| 89 | Game &g; | 146 | Game &g; |
| 147 | WaveSettings settings; | ||
| 148 | Phase phase = Phase::Ready; | ||
| 149 | float phaseTime = 0.0f; | ||
| 150 | bool leaving = false; // 次の波を頼んだ / the next wave was requested | ||
| 90 | Formation formation; | 151 | Formation formation; |
| 91 | std::optional<Shields> shields; | 152 | std::optional<Shields> shields; |
| 92 | float playerX = 0.0f, playerPrevX = 0.0f; // 自機の左端(補間用に前のステップも) / the ship's left edge (+ the | 153 | float playerX = 0.0f, playerPrevX = 0.0f; // 自機の左端(補間用に前のステップも) / the ship's left edge (+ the |
| @@ -95,17 +156,49 @@ private: | |||
| 95 | // (as in the original) | 156 | // (as in the original) |
| 96 | std::vector<Bullet> alienShots; | 157 | std::vector<Bullet> alienShots; |
| 97 | float fireTimer = 1.0f; // 宇宙人が次に撃つまで / until the aliens fire next | 158 | float fireTimer = 1.0f; // 宇宙人が次に撃つまで / until the aliens fire next |
| 98 | float shipDying = 0.0f; // 自機の爆発の残り時間(> 0 の間は隊列も止まる) / ship explosion time | 159 | Ufo ufo; |
| 99 | // left (the march stops meanwhile) | 160 | float ufoTimer = 0.0f; |
| 100 | Animator shipBoom; | 161 | Animator shipBoom; |
| 101 | Particles particles; | 162 | Particles particles; |
| 102 | std::vector<Flare> flares; | 163 | std::vector<Flare> flares; |
| 103 | std::vector<Star> stars; | 164 | std::vector<Popup> popups; |
| 165 | Shake shake; // 画面の揺れ(戦場だけ) / screen shake (the arena only) | ||
| 166 | ScreenFlash flash; // 戦場が一瞬光る / the arena lights up for a moment | ||
| 167 | float scoreFlash = 0.0f; // 点が入ったときHUDの数字が光る / the HUD digits flash on points | ||
| 104 | float time = 0.0f; | 168 | float time = 0.0f; |
| 105 | int frames[3][2] = {}; // 種類 × 足踏み → シートのコマ / kind × pose → sheet frame | 169 | int frames[3][2] = {}; // 種類 × 足踏み → シートのコマ / kind × pose → sheet frame |
| 106 | int shipFrame = 0, shotFrame = 0, splatFrame = 0, boomFrames[2] = {}; | 170 | int shipFrame = 0, shotFrame = 0, splatFrame = 0, ufoFrame = 0, boomFrames[2] = {}; |
| 107 | const AnimationClip *zigClip = nullptr, *boltClip = nullptr, *shipBoomClip = nullptr; | 171 | const AnimationClip *zigClip = nullptr, *boltClip = nullptr, *shipBoomClip = nullptr; |
| 108 | int formationDrawCalls = 0, formationBytes = 0, shieldBytes = 0; | 172 | int shotsFired = 0; |
| 109 | int lives = kStartLives, kills = 0, shotsFired = 0, waves = 1; | 173 | }; |
| 110 | bool gameOver = false; | 174 | |
| 175 | // 一時停止(上に重ねるシーン):再開かタイトルへ / pause (an overlay): resume or back to the title | ||
| 176 | class PauseScene : public Scene { | ||
| 177 | public: | ||
| 178 | explicit PauseScene(Game &game) : g(game) {} | ||
| 179 | bool isOverlay() const override { return true; } | ||
| 180 | void update(float dt) override; | ||
| 181 | void draw(float alpha) override; | ||
| 182 | void drawUi(float alpha) override; | ||
| 183 | |||
| 184 | private: | ||
| 185 | Game &g; | ||
| 186 | float time = 0.0f; | ||
| 187 | int selected = 0; | ||
| 188 | }; | ||
| 189 | |||
| 190 | // ゲームオーバー(上に重ねるシーン):止まった戦場の上に結果を出し、スペースでタイトルへ | ||
| 191 | // Game over (an overlay): shows the result over the frozen arena; Space goes back to the title | ||
| 192 | class GameOverScene : public Scene { | ||
| 193 | public: | ||
| 194 | GameOverScene(Game &game, bool newHighScore) : g(game), newHigh(newHighScore) {} | ||
| 195 | bool isOverlay() const override { return true; } | ||
| 196 | void update(float dt) override; | ||
| 197 | void draw(float alpha) override; | ||
| 198 | void drawUi(float alpha) override; | ||
| 199 | |||
| 200 | private: | ||
| 201 | Game &g; | ||
| 202 | bool newHigh; | ||
| 203 | float time = 0.0f; | ||
| 111 | }; | 204 | }; |
ファイル: /dev/null | b/games/invaders/src/layout.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,15 @@ | |||
| 1 | // Invaders:画面の寸法(キャンバスのピクセル) / Invaders: the screen layout (canvas pixels) | ||
| 2 | #pragma once | ||
| 3 | |||
| 4 | #include "engine/mathx.hh" | ||
| 5 | |||
| 6 | // 仮想解像度320 × 180(ウィンドウ1280 × 720で4倍)。真ん中の224ピクセル幅が戦場、左右48ピクセルは脇の板 | ||
| 7 | // Virtual resolution 320 × 180 (× 4 in the 1280 × 720 window). The middle 224 pixels are the arena, 48 pixels on | ||
| 8 | // each side are side panels | ||
| 9 | constexpr Vec2 kView = {320.0f, 180.0f}; | ||
| 10 | constexpr float kArenaLeft = 48.0f, kArenaRight = 272.0f; | ||
| 11 | constexpr float kFormationTop = 28.0f; // 第1波の隊列の一番上 / the first wave's top row | ||
| 12 | constexpr float kUfoY = 14.0f; // 円盤の通り道 / the saucer's lane | ||
| 13 | constexpr float kShieldY = 136.0f; // 防壁の上端 / the shields' top | ||
| 14 | constexpr float kPlayerY = 158.0f; // 自機の上端 / the ship's top | ||
| 15 | constexpr float kGroundY = 170.0f; // 地面の線 / the ground line | ||
ファイル: a/games/invaders/src/main.cc | b/games/invaders/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,13 +1,16 @@ | |||
| 1 | // Invaders 第2部(第28章):弾、AABBの当たり判定、宇宙人の弾、削れる防壁、爆発 | 1 | // Invaders 第3部(第29章):点数・残機・HUD、タイトルとゲームオーバーの場面、波ごとの場面の読み直し、速くなる波、 |
| 2 | // Invaders part 2 (chapter 28): bullets, AABB collisions, alien bullets, shields that erode, explosions | 2 | // 磨き(画面の揺れ、閃光、ブラウン管風の仕上げ) |
| 3 | // Invaders part 3 (chapter 29): score, lives and the HUD, title and game-over scenes, reloading the scene for every | ||
| 4 | // wave, waves that speed up, polish (screen shake, flashes, a CRT-style finish) | ||
| 3 | // | 5 | // |
| 4 | // 操作 / Controls: | 6 | // 操作 / Controls: |
| 5 | // ← → / A D 移動 / move | 7 | // タイトル / title Space・Enter 開始 / start Esc 終了 / quit |
| 6 | // Space / ↑ 撃つ / fire | 8 | // 遊ぶ / play ← → / A D 移動 / move Space / ↑ / W 撃つ / fire P / Esc 一時停止 / pause |
| 7 | // I 隊列の描き方:インスタンシング ⇔ SpriteBatch / formation: instancing ⇔ SpriteBatch | 9 | // 一時停止 / pause ↑ ↓ 選ぶ / select Space・Enter 決定 / confirm P / Esc 再開 / resume |
| 8 | // B 当たり判定の箱 / collision boxes | 10 | // いつでも / any time C ブラウン管風 / CRT Tab 開発用の数字 / developer numbers |
| 9 | // = / - 行進を速く・遅く / march faster / slower | 11 | // 開発用 / developer I 隊列の描き方 / formation drawing B 当たり判定の箱 / collision boxes |
| 10 | // Esc 終了 / quit | 12 | // = / - 行進の速さ / march speed N 次の波 / next wave |
| 13 | #include "crt.hh" | ||
| 11 | #include "game.hh" | 14 | #include "game.hh" |
| 12 | 15 | ||
| 13 | #include "engine/pixel_canvas.hh" | 16 | #include "engine/pixel_canvas.hh" |
| @@ -22,13 +25,17 @@ int main() { | |||
| 22 | 25 | ||
| 23 | std::optional<SpriteBatch> batch = SpriteBatch::create(); | 26 | std::optional<SpriteBatch> batch = SpriteBatch::create(); |
| 24 | std::optional<Font> ui = Font::load("assets/fonts/mono16.fnt"); | 27 | std::optional<Font> ui = Font::load("assets/fonts/mono16.fnt"); |
| 28 | // キャンバスの中のHUD:3 × 5の1ビットの文字(GL_NEAREST) / the canvas HUD: the 1-bit 3 × 5 font (GL_NEAREST) | ||
| 29 | std::optional<Font> tiny = Font::load("assets/fonts/pixel5.fnt", TextureFilter::Nearest); | ||
| 25 | std::optional<SpriteSheet> sprites = SpriteSheet::loadAtlas("games/invaders/assets/sprites.atlas"); | 30 | std::optional<SpriteSheet> sprites = SpriteSheet::loadAtlas("games/invaders/assets/sprites.atlas"); |
| 26 | if (!batch || !ui || !sprites) return 1; | 31 | if (!batch || !ui || !tiny || !sprites) return 1; |
| 27 | std::optional<FormationRenderer> formationRenderer = FormationRenderer::create(*sprites); | 32 | std::optional<FormationRenderer> formationRenderer = FormationRenderer::create(*sprites); |
| 28 | // 防壁の絵はCPUにも要る(削るため):同じPNGをもう一度デコードして切り出す / the shield art is needed on the CPU | 33 | // 防壁の絵はCPUにも要る(削るため):同じPNGをもう一度デコードして切り出す / the shield art is needed on the CPU |
| 29 | // too (to erode it): decode the same PNG again and cut it out | 34 | // too (to erode it): decode the same PNG again and cut it out |
| 30 | std::optional<Image> shieldArt = loadSpriteImage("games/invaders/assets/sprites.png", *sprites, "shield"); | 35 | std::optional<Image> shieldArt = loadSpriteImage("games/invaders/assets/sprites.png", *sprites, "shield"); |
| 31 | if (!formationRenderer || !shieldArt) return 1; | 36 | std::optional<CrtFilter> crt = CrtFilter::create(); |
| 37 | if (!formationRenderer || !shieldArt || !crt) return 1; | ||
| 38 | Backdrop backdrop; | ||
| 32 | 39 | ||
| 33 | // 行動に名前を付ける(キーを変えるならここだけ) / name the actions (to change keys, edit only this) | 40 | // 行動に名前を付ける(キーを変えるならここだけ) / name the actions (to change keys, edit only this) |
| 34 | Input input; | 41 | Input input; |
| @@ -42,23 +49,28 @@ int main() { | |||
| 42 | GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); | 49 | GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); |
| 43 | PixelCanvas canvas(static_cast<int>(kView.x), static_cast<int>(kView.y)); | 50 | PixelCanvas canvas(static_cast<int>(kView.x), static_cast<int>(kView.y)); |
| 44 | Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .formationRenderer = *formationRenderer, | 51 | Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .formationRenderer = *formationRenderer, |
| 45 | .ui = *ui, .sprites = *sprites, .shieldArt = *shieldArt, .world = Camera2D::screen(kView), | 52 | .ui = *ui, .tiny = *tiny, .sprites = *sprites, .shieldArt = *shieldArt, .backdrop = backdrop, |
| 46 | .screen = Camera2D::screen({1280.0f, 720.0f}), .uiViewport = {}}; | 53 | .world = Camera2D::screen(kView), .screen = Camera2D::screen({1280.0f, 720.0f}), .uiViewport = {}}; |
| 47 | 54 | ||
| 48 | SceneManager scenes; | 55 | SceneManager scenes; |
| 49 | scenes.push(std::make_unique<PlayScene>(game)); | 56 | scenes.push(std::make_unique<TitleScene>(game)); |
| 50 | 57 | ||
| 51 | loop.run( | 58 | loop.run( |
| 52 | window, input, | 59 | window, input, |
| 53 | [&](float dt) { | 60 | [&](float dt) { |
| 61 | // どの場面でも効くキー / keys that work in every scene | ||
| 62 | if (input.pressed(GLFW_KEY_C)) game.crt = !game.crt; | ||
| 63 | if (input.pressed(GLFW_KEY_TAB)) game.devInfo = !game.devInfo; | ||
| 54 | scenes.update(dt); | 64 | scenes.update(dt); |
| 55 | if (scenes.empty()) window.close(); | 65 | if (scenes.empty()) window.close(); |
| 56 | }, | 66 | }, |
| 57 | [&](float alpha) { | 67 | [&](float alpha) { |
| 58 | // 1. 世界:320 × 180のキャンバスに描いて4倍で画面へ / 1. the world: into the 320 × 180 canvas, shown × 4 | 68 | // 1. 世界:320 × 180のキャンバスに描き、4倍で画面へ(そのままコピーか、ブラウン管風のシェーダーで) |
| 69 | // 1. the world: into the 320 × 180 canvas, then × 4 onto the screen (a plain copy, or through the CRT shader) | ||
| 59 | canvas.begin(hexColor(0x0c0a1aff)); | 70 | canvas.begin(hexColor(0x0c0a1aff)); |
| 60 | scenes.draw(alpha); | 71 | scenes.draw(alpha); |
| 61 | canvas.present(window.width(), window.height()); | 72 | if (game.crt) crt->present(canvas, window.width(), window.height()); |
| 73 | else canvas.present(window.width(), window.height()); | ||
| 62 | // 2. UI:1280 × 720の文字 / 2. the UI: text at 1280 × 720 | 74 | // 2. UI:1280 × 720の文字 / 2. the UI: text at 1280 × 720 |
| 63 | game.uiViewport = letterbox(window.width(), window.height(), game.screen.viewSize, false); | 75 | game.uiViewport = letterbox(window.width(), window.height(), game.screen.viewSize, false); |
| 64 | game.uiViewport.apply(); | 76 | game.uiViewport.apply(); |
ファイル: /dev/null | b/games/invaders/src/menus.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,93 @@ | |||
| 1 | // 上に重ねるシーン(第29章):一時停止とゲームオーバー。下の遊ぶ場面は描かれるが更新されない(止まった戦場) | ||
| 2 | // Overlay scenes (chapter 29): pause and game over. The play scene below is drawn but not updated (a frozen arena) | ||
| 3 | #include "game.hh" | ||
| 4 | |||
| 5 | #include <algorithm> | ||
| 6 | #include <cmath> | ||
| 7 | #include <cstdio> | ||
| 8 | #include <cstring> | ||
| 9 | #include <memory> | ||
| 10 | #include <string> | ||
| 11 | |||
| 12 | // 戦場を暗くする(キャンバスの中、脇の板は残す) / darken the arena (inside the canvas; the side panels stay) | ||
| 13 | static void dimArena(Game &g, float amount) { | ||
| 14 | g.batch.begin(g.world.matrix()); | ||
| 15 | g.batch.drawRect({kArenaLeft, 0.0f, kArenaRight - kArenaLeft, kView.y}, {0.03f, 0.02f, 0.08f, amount}); | ||
| 16 | g.batch.end(); | ||
| 17 | } | ||
| 18 | |||
| 19 | void PauseScene::update(float dt) { | ||
| 20 | time += dt; | ||
| 21 | Input &in = g.input; | ||
| 22 | if (in.pressed(GLFW_KEY_ESCAPE) || in.pressed(GLFW_KEY_P)) { | ||
| 23 | scenes().pop(); | ||
| 24 | return; | ||
| 25 | } | ||
| 26 | if (in.pressed(GLFW_KEY_UP) || in.pressed(GLFW_KEY_W) || in.pressed(GLFW_KEY_DOWN) || in.pressed(GLFW_KEY_S)) | ||
| 27 | selected = 1 - selected; | ||
| 28 | if (in.actionPressed("confirm")) { | ||
| 29 | if (selected == 0) scenes().pop(); | ||
| 30 | else scenes().replaceAll(std::make_unique<TitleScene>(g), {.duration = 0.8f}); | ||
| 31 | } | ||
| 32 | } | ||
| 33 | |||
| 34 | void PauseScene::draw(float /*alpha*/) { dimArena(g, std::min(1.0f, time * 4.0f) * 0.6f); } | ||
| 35 | |||
| 36 | void PauseScene::drawUi(float /*alpha*/) { | ||
| 37 | SpriteBatch &b = g.batch; | ||
| 38 | b.begin(g.screen.matrix()); | ||
| 39 | // 枠:文字が下の宇宙人と混ざらないように / a panel, so the text does not mix with the aliens below | ||
| 40 | Rect panel = {340.0f, 220.0f, 600.0f, 210.0f}; | ||
| 41 | b.drawRect(panel, hexColor(0x16132af0)); | ||
| 42 | b.drawRectOutline(panel, hexColor(0x3a3460ff), 4.0f); | ||
| 43 | g.ui.draw(b, "一時停止 / PAUSED", {640.0f, 244.0f}, | ||
| 44 | {.color = hexColor(0xf2c14eff), .scale = 2.0f, .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); | ||
| 45 | const char *items[2] = {"再開 / Resume", "タイトルへ / Back to title"}; | ||
| 46 | for (int i = 0; i < 2; ++i) { | ||
| 47 | bool on = i == selected; | ||
| 48 | g.ui.draw(b, on ? (std::string("> ") + items[i] + " <").c_str() : items[i], {640.0f, 316.0f + 44.0f * static_cast<float>(i)}, | ||
| 49 | {.color = on ? hexColor(0xfff4d6ff) : hexColor(0x8c91b4ff), .scale = 2.0f, .align = TextAlign::Centre, | ||
| 50 | .shadow = hexColor(0x000000ff)}); | ||
| 51 | } | ||
| 52 | b.end(); | ||
| 53 | } | ||
| 54 | |||
| 55 | void GameOverScene::update(float dt) { | ||
| 56 | time += dt; | ||
| 57 | // 1.5秒は待つ(撃っていたスペースで飛ばさないように) / wait 1.5 s (so a Space meant as a shot does not skip it) | ||
| 58 | if (time > 1.5f && g.input.actionPressed("confirm")) | ||
| 59 | scenes().replaceAll(std::make_unique<TitleScene>(g), {.duration = 1.0f}); | ||
| 60 | } | ||
| 61 | |||
| 62 | void GameOverScene::draw(float /*alpha*/) { | ||
| 63 | float in = std::min(1.0f, time * 2.0f); | ||
| 64 | dimArena(g, in * 0.55f); | ||
| 65 | g.batch.begin(g.world.matrix()); | ||
| 66 | g.batch.drawRect({kArenaLeft, 40.0f, kArenaRight - kArenaLeft, 84.0f}, {0.05f, 0.04f, 0.1f, 0.85f * in}); | ||
| 67 | // 「GAME OVER」を一文字ずつ打つ / type "GAME OVER" one letter at a time | ||
| 68 | const char *title = "GAME OVER"; | ||
| 69 | char shown[16] = {}; | ||
| 70 | size_t n = std::min(std::strlen(title), static_cast<size_t>(time / 0.09f)); | ||
| 71 | std::memcpy(shown, title, n); | ||
| 72 | // 位置は全部の文字の幅で決める(打っている途中で動かない) / position from the full width (does not move while | ||
| 73 | // typing) | ||
| 74 | float x = std::round(160.0f - 0.5f * g.tiny.measure(title, 3.0f).x); | ||
| 75 | drawTinyText(g, shown, {x, 48.0f}, hexColor(0xd9474bff), 3.0f); | ||
| 76 | char line[32]; | ||
| 77 | snprintf(line, sizeof line, "SCORE %05d WAVE %d", g.run.score, g.run.wave); | ||
| 78 | drawTinyText(g, line, {160.0f, 72.0f}, hexColor(0xf4f1e8ff), 1.0f, TextAlign::Centre); | ||
| 79 | if (newHigh && std::fmod(time, 0.5f) < 0.35f) | ||
| 80 | drawTinyText(g, "NEW HIGH SCORE!", {160.0f, 82.0f}, hexColor(0xffec96ff), 1.0f, TextAlign::Centre); | ||
| 81 | g.batch.end(); | ||
| 82 | } | ||
| 83 | |||
| 84 | void GameOverScene::drawUi(float /*alpha*/) { | ||
| 85 | SpriteBatch &b = g.batch; | ||
| 86 | b.begin(g.screen.matrix()); | ||
| 87 | g.ui.draw(b, newHigh ? "ゲームオーバー 新記録!" : "ゲームオーバー", {640.0f, 372.0f}, | ||
| 88 | {.color = hexColor(0xd8dcefff), .scale = 2.0f, .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); | ||
| 89 | if (time > 1.5f) | ||
| 90 | g.ui.draw(b, "スペースキーでタイトルへ / Space: back to title", {640.0f, 438.0f}, | ||
| 91 | {.color = hexColor(0xb8bccaff), .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); | ||
| 92 | b.end(); | ||
| 93 | } | ||
ファイル: a/games/invaders/src/play_scene.cc | b/games/invaders/src/play_scene.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,5 +1,7 @@ | |||
| 1 | // 遊ぶ場面(第28章):自機の弾と宇宙人の弾、AABBの当たり判定、削れる防壁、爆発 | 1 | // 遊ぶ場面(第29章):点数・残機・HUD、波の流れ(準備 → 戦い → 全滅 → 次の波 = 場面の読み直し)、速くなる波、 |
| 2 | // The play scene (chapter 28): the ship's and the aliens' bullets, AABB collisions, eroding shields, explosions | 2 | // 円盤、画面の揺れと閃光 |
| 3 | // The play scene (chapter 29): score, lives and the HUD, the wave flow (ready → fight → cleared → next wave = a scene | ||
| 4 | // reload), waves that speed up, the saucer, screen shake and flashes | ||
| 3 | #include "game.hh" | 5 | #include "game.hh" |
| 4 | 6 | ||
| 5 | #include "engine/collision.hh" | 7 | #include "engine/collision.hh" |
| @@ -9,32 +11,39 @@ | |||
| 9 | #include <cstdio> | 11 | #include <cstdio> |
| 10 | #include <memory> | 12 | #include <memory> |
| 11 | 13 | ||
| 12 | // 宇宙人の色(破片の色) / alien colors (for the debris) | 14 | // 宇宙人の色(破片の色)と点数 / alien colors (for the debris) and points |
| 13 | static const Vec4 kAlienColors[3] = {hexColor(0xf06292ff), hexColor(0x5dbce6ff), hexColor(0x9adc48ff)}; | 15 | static const Vec4 kAlienColors[3] = {hexColor(0xf06292ff), hexColor(0x5dbce6ff), hexColor(0x9adc48ff)}; |
| 16 | static const int kAlienPoints[3] = {30, 20, 10}; | ||
| 17 | static const int kUfoPoints[4] = {50, 100, 150, 300}; | ||
| 14 | constexpr float kFormationWidth = (kColumns - 1) * kColumnSpacing + kAlienSize.x; // 174 | 18 | constexpr float kFormationWidth = (kColumns - 1) * kColumnSpacing + kAlienSize.x; // 174 |
| 15 | constexpr float kShipBoomTime = 1.4f; | 19 | constexpr float kShipBoomTime = 1.4f; |
| 20 | constexpr float kReadyTime = 1.6f, kClearedTime = 1.5f; | ||
| 21 | constexpr Vec4 kHudLabel = {0.55f, 0.57f, 0.75f, 1.0f}; | ||
| 16 | 22 | ||
| 17 | static float formationStartX() { return std::round(0.5f * (kArenaLeft + kArenaRight - kFormationWidth)); } | 23 | static float formationStartX() { return std::round(0.5f * (kArenaLeft + kArenaRight - kFormationWidth)); } |
| 18 | 24 | ||
| 19 | PlayScene::PlayScene(Game &game) : g(game) { | 25 | PlayScene::PlayScene(Game &game) : g(game), settings(waveSettings(game.run.wave)) { |
| 20 | const char *names[3][2] = {{"jelly_0", "jelly_1"}, {"beetle_0", "beetle_1"}, {"blob_0", "blob_1"}}; | 26 | const char *names[3][2] = {{"jelly_0", "jelly_1"}, {"beetle_0", "beetle_1"}, {"blob_0", "blob_1"}}; |
| 21 | for (int k = 0; k < 3; ++k) | 27 | for (int k = 0; k < 3; ++k) |
| 22 | for (int p = 0; p < 2; ++p) frames[k][p] = g.sprites.find(names[k][p]); | 28 | for (int p = 0; p < 2; ++p) frames[k][p] = g.sprites.find(names[k][p]); |
| 23 | shipFrame = g.sprites.find("ship"); | 29 | shipFrame = g.sprites.find("ship"); |
| 24 | shotFrame = g.sprites.find("shot"); | 30 | shotFrame = g.sprites.find("shot"); |
| 25 | splatFrame = g.sprites.find("splat"); | 31 | splatFrame = g.sprites.find("splat"); |
| 32 | ufoFrame = g.sprites.find("ufo"); | ||
| 26 | boomFrames[0] = g.sprites.find("alien_boom_0"); | 33 | boomFrames[0] = g.sprites.find("alien_boom_0"); |
| 27 | boomFrames[1] = g.sprites.find("alien_boom_1"); | 34 | boomFrames[1] = g.sprites.find("alien_boom_1"); |
| 28 | zigClip = g.sprites.clip("zig"); | 35 | zigClip = g.sprites.clip("zig"); |
| 29 | boltClip = g.sprites.clip("bolt"); | 36 | boltClip = g.sprites.clip("bolt"); |
| 30 | shipBoomClip = g.sprites.clip("ship_boom"); | 37 | shipBoomClip = g.sprites.clip("ship_boom"); |
| 31 | 38 | ||
| 32 | // 隊列:幅174ピクセル、戦場の真ん中 / the formation: 174 px wide, centered in the arena | 39 | // 隊列:波が進むほど低い所から、速く / the formation: lower and faster as the waves go on |
| 33 | formation.minX = kArenaLeft + 2.0f; | 40 | formation.minX = kArenaLeft + 2.0f; |
| 34 | formation.maxX = kArenaRight - 2.0f; | 41 | formation.maxX = kArenaRight - 2.0f; |
| 35 | formation.reset(formationStartX(), kFormationTop); | 42 | formation.reset(formationStartX(), settings.top); |
| 43 | formation.rate = settings.marchRate; | ||
| 36 | 44 | ||
| 37 | // 防壁4つを戦場に等間隔で(中心 76, 132, 188, 244) / four shields evenly across the arena (centers 76, 132, 188, 244) | 45 | // 防壁4つを戦場に等間隔で(中心 76, 132, 188, 244)。波ごとに新品 / four shields evenly across the arena (centers |
| 46 | // 76, 132, 188, 244). New ones every wave | ||
| 38 | Vec2 shieldPos[kShieldCount]; | 47 | Vec2 shieldPos[kShieldCount]; |
| 39 | for (int i = 0; i < kShieldCount; ++i) | 48 | for (int i = 0; i < kShieldCount; ++i) |
| 40 | shieldPos[i] = {kArenaLeft + (kArenaRight - kArenaLeft) * (static_cast<float>(i) + 0.5f) / kShieldCount - kShieldW / 2, | 49 | shieldPos[i] = {kArenaLeft + (kArenaRight - kArenaLeft) * (static_cast<float>(i) + 0.5f) / kShieldCount - kShieldW / 2, |
| @@ -46,19 +55,22 @@ PlayScene::PlayScene(Game &game) : g(game) { | |||
| 46 | } | 55 | } |
| 47 | 56 | ||
| 48 | playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f); | 57 | playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f); |
| 49 | // 星:自分の種で作るので、場面を作り直しても同じ空 / stars: made with their own seed, so the sky stays the same when | 58 | ufoTimer = g.rng.range(8.0f, 14.0f); // 最初の円盤は早めに / the first saucer comes early |
| 50 | // the scene is created again | ||
| 51 | Rng sky(1978); | ||
| 52 | for (int i = 0; i < 40; ++i) | ||
| 53 | stars.push_back({{std::round(sky.range(kArenaLeft + 2.0f, kArenaRight - 2.0f)), std::round(sky.range(4.0f, 150.0f))}, | ||
| 54 | sky.unit()}); | ||
| 55 | } | 59 | } |
| 56 | 60 | ||
| 61 | void PlayScene::enter() { printf("wave %d: score %d, lives %d\n", g.run.wave, g.run.score, g.run.lives); } | ||
| 62 | |||
| 57 | // 一時停止の間は補間しない(第26章) / no interpolation while paused (chapter 26) | 63 | // 一時停止の間は補間しない(第26章) / no interpolation while paused (chapter 26) |
| 58 | void PlayScene::pause() { | 64 | void PlayScene::pause() { |
| 59 | playerPrevX = playerX; | 65 | playerPrevX = playerX; |
| 60 | if (shot) shot->prevY = shot->box.y; | 66 | if (shot) shot->prevY = shot->box.y; |
| 61 | for (Bullet &b : alienShots) b.prevY = b.box.y; | 67 | for (Bullet &b : alienShots) b.prevY = b.box.y; |
| 68 | ufo.prevX = ufo.x; | ||
| 69 | } | ||
| 70 | |||
| 71 | void PlayScene::setPhase(Phase p) { | ||
| 72 | phase = p; | ||
| 73 | phaseTime = 0.0f; | ||
| 62 | } | 74 | } |
| 63 | 75 | ||
| 64 | int PlayScene::alienFrame(const Alien &a) const { | 76 | int PlayScene::alienFrame(const Alien &a) const { |
| @@ -71,34 +83,53 @@ Rect PlayScene::shipBox() const { return {playerX + 1.0f, kPlayerY + 1.0f, 13.0f | |||
| 71 | 83 | ||
| 72 | void PlayScene::flare(Vec2 centre, Vec4 color, float life) { flares.push_back({splatFrame, centre, life, color}); } | 84 | void PlayScene::flare(Vec2 centre, Vec4 color, float life) { flares.push_back({splatFrame, centre, life, color}); } |
| 73 | 85 | ||
| 86 | void PlayScene::popup(Vec2 position, const char *text, Vec4 color) { | ||
| 87 | Popup p{position, 1.0f, {}, color}; | ||
| 88 | snprintf(p.text, sizeof p.text, "%s", text); | ||
| 89 | popups.push_back(p); | ||
| 90 | } | ||
| 91 | |||
| 92 | void PlayScene::addScore(int points) { | ||
| 93 | g.run.score += points; | ||
| 94 | scoreFlash = 0.15f; | ||
| 95 | // 1500点で一度だけ1機増える / one extra ship at 1500 points, once | ||
| 96 | if (!g.run.extraLife && g.run.score >= kExtraLifeScore) { | ||
| 97 | g.run.extraLife = true; | ||
| 98 | ++g.run.lives; | ||
| 99 | popup({shipBox().centre().x, kPlayerY - 8.0f}, "1UP", hexColor(0x9adc48ff)); | ||
| 100 | printf("extra life at %d\n", g.run.score); | ||
| 101 | } | ||
| 102 | } | ||
| 103 | |||
| 74 | void PlayScene::fire() { | 104 | void PlayScene::fire() { |
| 75 | // 画面に自機の弾がない時だけ撃てる:連打より狙いが大事(元のゲームの決まり) | 105 | // 画面に自機の弾がない時だけ撃てる:連打より狙いが大事(元のゲームの決まり) |
| 76 | // Only when no ship bullet is on screen: aiming beats mashing (the original's rule) | 106 | // Only when no ship bullet is on screen: aiming beats mashing (the original's rule) |
| 77 | if (shot || shipDying > 0.0f || gameOver || !g.input.actionPressed("fire")) return; | 107 | if (shot || !g.input.actionPressed("fire")) return; |
| 78 | float y = kPlayerY - 4.0f; | 108 | float y = kPlayerY - 4.0f; |
| 79 | shot = Bullet{.box = {playerX + 7.0f, y, 1.0f, 5.0f}, .prevY = y, .anim = {}}; | 109 | shot = Bullet{.box = {playerX + 7.0f, y, 1.0f, 5.0f}, .prevY = y, .anim = {}}; |
| 80 | ++shotsFired; | 110 | ++shotsFired; |
| 81 | } | 111 | } |
| 82 | 112 | ||
| 83 | void PlayScene::killShip() { | 113 | void PlayScene::killShip() { |
| 84 | --lives; | 114 | --g.run.lives; |
| 85 | shipDying = kShipBoomTime; | 115 | setPhase(Phase::ShipDown); |
| 86 | shipBoom.play(shipBoomClip, true); | 116 | shipBoom.play(shipBoomClip, true); |
| 87 | Vec2 c = shipBox().centre(); | 117 | Vec2 c = shipBox().centre(); |
| 88 | particles.burst(c, 24, hexColor(0x4fc0a5ff), 20.0f, 70.0f, g.rng); | 118 | particles.burst(c, 24, hexColor(0x4fc0a5ff), 20.0f, 70.0f, g.rng); |
| 89 | particles.burst(c, 12, hexColor(0xffa040ff), 30.0f, 90.0f, g.rng); | 119 | particles.burst(c, 12, hexColor(0xffa040ff), 30.0f, 90.0f, g.rng); |
| 90 | alienShots.clear(); // 元のゲームと同じく、飛んでいる弾は消える / bullets in flight vanish, as in the original | 120 | alienShots.clear(); // 元のゲームと同じく、飛んでいる弾は消える / bullets in flight vanish, as in the original |
| 91 | printf("ship hit: lives %d\n", lives); | 121 | // 磨き:大きく揺らし、赤く光らせる / polish: a big shake and a red flash |
| 122 | shake.add(0.75f); | ||
| 123 | flash.start({1.0f, 0.25f, 0.2f, 0.45f}); | ||
| 124 | printf("ship hit: lives %d\n", g.run.lives); | ||
| 92 | } | 125 | } |
| 93 | 126 | ||
| 94 | void PlayScene::updateShot(float dt) { | 127 | void PlayScene::updateShot(float dt) { |
| 95 | if (!shot) return; | 128 | if (!shot) return; |
| 96 | shot->prevY = shot->box.y; | 129 | shot->prevY = shot->box.y; |
| 97 | shot->box.y -= kShotSpeed * dt; | 130 | shot->box.y -= kShotSpeed * dt; |
| 98 | // 1ステップ4ピクセル、弾の長さ5ピクセル:続けて見れば隙間がないので、すり抜けない(第26章のトンネリング)。 | 131 | // 1ステップ4ピクセル、弾の長さ5ピクセル:続けて見れば隙間がないので、すり抜けない(第26章のトンネリング) |
| 99 | // 宇宙人の弾とも:近づく速さは1ステップ5.25ピクセル < 5 + 7 | 132 | // 4 px per step with a 5 px bullet: consecutive boxes leave no gap, so nothing is skipped (ch26's tunneling) |
| 100 | // 4 px per step with a 5 px bullet: consecutive boxes leave no gap, so nothing is skipped (ch26's tunneling). | ||
| 101 | // Against alien bullets too: they close in at 5.25 px per step < 5 + 7 | ||
| 102 | const Rect &box = shot->box; | 133 | const Rect &box = shot->box; |
| 103 | for (size_t i = 0; i < alienShots.size(); ++i) | 134 | for (size_t i = 0; i < alienShots.size(); ++i) |
| 104 | if (overlaps(box, alienShots[i].box)) { | 135 | if (overlaps(box, alienShots[i].box)) { |
| @@ -111,10 +142,27 @@ void PlayScene::updateShot(float dt) { | |||
| 111 | if (a.alive && overlaps(box, a.box())) { | 142 | if (a.alive && overlaps(box, a.box())) { |
| 112 | formation.kill(a); | 143 | formation.kill(a); |
| 113 | particles.burst(a.box().centre(), 10, kAlienColors[static_cast<int>(a.kind)], 15.0f, 50.0f, g.rng); | 144 | particles.burst(a.box().centre(), 10, kAlienColors[static_cast<int>(a.kind)], 15.0f, 50.0f, g.rng); |
| 114 | ++kills; | 145 | addScore(kAlienPoints[static_cast<int>(a.kind)]); |
| 115 | shot.reset(); | 146 | shot.reset(); |
| 116 | return; | 147 | return; |
| 117 | } | 148 | } |
| 149 | if (ufo.active && overlaps(box, ufo.box())) { | ||
| 150 | // 円盤:50〜300点(乱数)、点数が浮かび、揺れて白く光る / the saucer: 50-300 points (random), the points float | ||
| 151 | // up, a shake and a white flash | ||
| 152 | int points = kUfoPoints[g.rng.range(0, 3)]; | ||
| 153 | addScore(points); | ||
| 154 | printf("saucer hit: %d points\n", points); | ||
| 155 | char text[12]; | ||
| 156 | snprintf(text, sizeof text, "%d", points); | ||
| 157 | popup(ufo.box().centre(), text, hexColor(0xffec96ff)); | ||
| 158 | particles.burst(ufo.box().centre(), 20, hexColor(0xd9474bff), 20.0f, 60.0f, g.rng); | ||
| 159 | shake.add(0.5f); // 0.408未満では1ピクセルも動かない / below 0.408 it would not move a single pixel | ||
| 160 | flash.start({1.0f, 1.0f, 1.0f, 0.35f}); | ||
| 161 | ufo.active = false; | ||
| 162 | ufoTimer = g.rng.range(18.0f, 28.0f); | ||
| 163 | shot.reset(); | ||
| 164 | return; | ||
| 165 | } | ||
| 118 | if (std::optional<Vec2> p = shields->hit(box, true)) { | 166 | if (std::optional<Vec2> p = shields->hit(box, true)) { |
| 119 | shields->erode(*p, g.rng); | 167 | shields->erode(*p, g.rng); |
| 120 | flare(*p, hexColor(0x68c454ff)); | 168 | flare(*p, hexColor(0x68c454ff)); |
| @@ -130,8 +178,8 @@ void PlayScene::updateShot(float dt) { | |||
| 130 | void PlayScene::alienFire(float dt) { | 178 | void PlayScene::alienFire(float dt) { |
| 131 | fireTimer -= dt; | 179 | fireTimer -= dt; |
| 132 | if (fireTimer > 0.0f) return; | 180 | if (fireTimer > 0.0f) return; |
| 133 | fireTimer = g.rng.range(0.5f, 1.1f); | 181 | fireTimer = g.rng.range(settings.fireMin, settings.fireMax); |
| 134 | if (static_cast<int>(alienShots.size()) >= kMaxAlienShots) return; | 182 | if (static_cast<int>(alienShots.size()) >= settings.maxShots) return; |
| 135 | // 撃つ列:3回に1回は自機の真上の列、それ以外は生きている宇宙人をランダムに選んでその列。撃つのはその列の一番下 | 183 | // 撃つ列:3回に1回は自機の真上の列、それ以外は生きている宇宙人をランダムに選んでその列。撃つのはその列の一番下 |
| 136 | // The firing column: one time in three the column above the ship, otherwise the column of a random living alien. | 184 | // The firing column: one time in three the column above the ship, otherwise the column of a random living alien. |
| 137 | // The lowest alien of that column shoots | 185 | // The lowest alien of that column shoots |
| @@ -157,9 +205,9 @@ void PlayScene::updateAlienShots(float dt) { | |||
| 157 | for (size_t i = 0; i < alienShots.size();) { | 205 | for (size_t i = 0; i < alienShots.size();) { |
| 158 | Bullet &b = alienShots[i]; | 206 | Bullet &b = alienShots[i]; |
| 159 | b.prevY = b.box.y; | 207 | b.prevY = b.box.y; |
| 160 | b.box.y += kAlienShotSpeed * dt; | 208 | b.box.y += settings.shotSpeed * dt; |
| 161 | b.anim.update(dt); | 209 | b.anim.update(dt); |
| 162 | if (shipDying <= 0.0f && overlaps(b.box, shipBox())) { | 210 | if (overlaps(b.box, shipBox())) { |
| 163 | killShip(); // 全部の弾を消す / clears every bullet | 211 | killShip(); // 全部の弾を消す / clears every bullet |
| 164 | return; | 212 | return; |
| 165 | } | 213 | } |
| @@ -177,12 +225,32 @@ void PlayScene::updateAlienShots(float dt) { | |||
| 177 | } | 225 | } |
| 178 | } | 226 | } |
| 179 | 227 | ||
| 228 | void PlayScene::updateUfo(float dt) { | ||
| 229 | if (!ufo.active) { | ||
| 230 | // 時々、宇宙人が8匹以上いる間だけ / now and then, only while 8 or more aliens are left | ||
| 231 | ufoTimer -= dt; | ||
| 232 | if (ufoTimer <= 0.0f && formation.alive() >= 8) { | ||
| 233 | ufo.active = true; | ||
| 234 | ufo.direction = g.rng.chance(0.5f) ? 1.0f : -1.0f; | ||
| 235 | ufo.x = ufo.prevX = ufo.direction > 0.0f ? kArenaLeft - 18.0f : kArenaRight; | ||
| 236 | printf("saucer from the %s\n", ufo.direction > 0.0f ? "left" : "right"); | ||
| 237 | } | ||
| 238 | return; | ||
| 239 | } | ||
| 240 | ufo.x += ufo.direction * 40.0f * dt; | ||
| 241 | if (ufo.x > kArenaRight + 1.0f || ufo.x < kArenaLeft - 19.0f) { | ||
| 242 | ufo.active = false; | ||
| 243 | ufoTimer = g.rng.range(18.0f, 28.0f); | ||
| 244 | } | ||
| 245 | } | ||
| 246 | |||
| 180 | void PlayScene::update(float dt) { | 247 | void PlayScene::update(float dt) { |
| 181 | if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor) | 248 | if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor) |
| 182 | time += dt; | 249 | time += dt; |
| 250 | phaseTime += dt; | ||
| 183 | Input &in = g.input; | 251 | Input &in = g.input; |
| 184 | if (in.pressed(GLFW_KEY_ESCAPE)) { | 252 | if (in.pressed(GLFW_KEY_ESCAPE) || in.pressed(GLFW_KEY_P)) { |
| 185 | scenes().pop(); // スタックが空になる → main が終わらせる / the stack becomes empty → main quits | 253 | scenes().push(std::make_unique<PauseScene>(g)); |
| 186 | return; | 254 | return; |
| 187 | } | 255 | } |
| 188 | if (in.pressed(GLFW_KEY_I)) { | 256 | if (in.pressed(GLFW_KEY_I)) { |
| @@ -192,39 +260,74 @@ void PlayScene::update(float dt) { | |||
| 192 | if (in.pressed(GLFW_KEY_B)) g.showBoxes = !g.showBoxes; | 260 | if (in.pressed(GLFW_KEY_B)) g.showBoxes = !g.showBoxes; |
| 193 | if (in.pressed(GLFW_KEY_EQUAL)) formation.rate = std::min(formation.rate * 2.0f, 960.0f); | 261 | if (in.pressed(GLFW_KEY_EQUAL)) formation.rate = std::min(formation.rate * 2.0f, 960.0f); |
| 194 | if (in.pressed(GLFW_KEY_MINUS)) formation.rate = std::max(formation.rate * 0.5f, 15.0f); | 262 | if (in.pressed(GLFW_KEY_MINUS)) formation.rate = std::max(formation.rate * 0.5f, 15.0f); |
| 263 | if (in.pressed(GLFW_KEY_N) && phase == Phase::Playing) { | ||
| 264 | // 開発用:全員を倒して次の波へ(点は入らない) / developer key: destroy everyone and go to the next wave (no points) | ||
| 265 | for (Alien &a : formation.aliens) | ||
| 266 | if (a.alive) formation.kill(a); | ||
| 267 | } | ||
| 195 | 268 | ||
| 196 | // 飾りはいつでも動く / the dressing always moves | 269 | // 飾りはいつでも動く / the dressing always moves |
| 197 | particles.update(dt); | 270 | particles.update(dt); |
| 198 | for (Flare &f : flares) f.life -= dt; | 271 | for (Flare &f : flares) f.life -= dt; |
| 199 | std::erase_if(flares, [](const Flare &f) { return f.life <= 0.0f; }); | 272 | std::erase_if(flares, [](const Flare &f) { return f.life <= 0.0f; }); |
| 200 | 273 | for (Popup &p : popups) { | |
| 201 | if (gameOver) { | 274 | p.position.y -= 8.0f * dt; |
| 202 | formation.updateExplosions(dt); | 275 | p.life -= dt; |
| 203 | // やり直し:この場面を新しい場面と入れ替える(全部が最初の状態に戻る) / play again: replace this scene with a | ||
| 204 | // new one (everything starts from scratch) | ||
| 205 | if (in.actionPressed("confirm")) scenes().replace(std::make_unique<PlayScene>(g)); | ||
| 206 | return; | ||
| 207 | } | 276 | } |
| 208 | 277 | std::erase_if(popups, [](const Popup &p) { return p.life <= 0.0f; }); | |
| 278 | shake.update(dt); | ||
| 279 | flash.update(dt); | ||
| 280 | scoreFlash = std::max(0.0f, scoreFlash - dt); | ||
| 281 | // Playingではformation.updateが爆発も進めるので、此処は其れ以外のフェーズだけ | ||
| 282 | // in Playing, formation.update advances the explosions itself, so only the other phases do it here | ||
| 283 | if (phase != Phase::Playing) formation.updateExplosions(dt); | ||
| 284 | // 補間用の前の位置は、どのフェーズでも毎回ここで。ShipDownではupdateUfoが呼ばれないので円盤もここ(止まった円盤が | ||
| 285 | // 古いprevXとxの間で震えない様に、第26章) | ||
| 286 | // Previous positions for the interpolation, refreshed here in every phase. ShipDown does not call updateUfo, so | ||
| 287 | // the saucer's is refreshed here too (or the frozen saucer wobbles between a stale prevX and x, chapter 26) | ||
| 209 | playerPrevX = playerX; | 288 | playerPrevX = playerX; |
| 210 | if (shipDying > 0.0f) { | 289 | ufo.prevX = ufo.x; |
| 290 | |||
| 291 | switch (phase) { | ||
| 292 | case Phase::Ready: | ||
| 293 | // 「WAVE n」を見せる間は何も動かない / nothing moves while "WAVE n" is shown | ||
| 294 | if (phaseTime >= kReadyTime) setPhase(Phase::Playing); | ||
| 295 | return; | ||
| 296 | case Phase::Cleared: | ||
| 297 | // 全滅:少し待ってから、波の番号を上げて場面ごと作り直す(フェード付き)。隊列・防壁・弾は新品になり、 | ||
| 298 | // 点数と残機はGame::runにあるので残る | ||
| 299 | // Wiped out: after a moment, raise the wave number and rebuild the whole scene (with a fade). Formation, | ||
| 300 | // shields and bullets start fresh; score and lives live in Game::run, so they stay | ||
| 301 | updateShot(dt); | ||
| 302 | if (phaseTime >= kClearedTime && !leaving) { | ||
| 303 | leaving = true; | ||
| 304 | ++g.run.wave; | ||
| 305 | scenes().replace(std::make_unique<PlayScene>(g), {.duration = 1.0f}); | ||
| 306 | } | ||
| 307 | return; | ||
| 308 | case Phase::ShipDown: | ||
| 211 | // 自機の爆発中:隊列も宇宙人の弾も止まる(元のゲームと同じ)。終わったら真ん中に戻るか、ゲームオーバー | 309 | // 自機の爆発中:隊列も宇宙人の弾も止まる(元のゲームと同じ)。終わったら真ん中に戻るか、ゲームオーバー |
| 212 | // While the ship explodes the formation and the alien fire stop (as in the original). Afterwards the ship comes | 310 | // While the ship explodes the formation and the alien fire stop (as in the original). Afterwards the ship comes |
| 213 | // back in the middle, or the game is over | 311 | // back in the middle, or the game is over |
| 214 | shipBoom.update(dt); | 312 | shipBoom.update(dt); |
| 215 | formation.updateExplosions(dt); | ||
| 216 | updateShot(dt); | 313 | updateShot(dt); |
| 217 | shipDying -= dt; | 314 | if (phaseTime >= kShipBoomTime) { |
| 218 | if (shipDying <= 0.0f) { | 315 | if (g.run.lives > 0) { |
| 219 | shipDying = 0.0f; | ||
| 220 | if (lives > 0) { | ||
| 221 | playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f); | 316 | playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f); |
| 317 | setPhase(Phase::Playing); | ||
| 222 | } else { | 318 | } else { |
| 223 | gameOver = true; | 319 | setPhase(Phase::Over); |
| 224 | printf("game over: %d kills\n", kills); | 320 | bool newHigh = g.run.score > g.hiScore; |
| 321 | if (newHigh) g.hiScore = g.run.score; | ||
| 322 | printf("game over: score %d (wave %d)%s\n", g.run.score, g.run.wave, newHigh ? ", new high score" : ""); | ||
| 323 | scenes().push(std::make_unique<GameOverScene>(g, newHigh)); | ||
| 225 | } | 324 | } |
| 226 | } | 325 | } |
| 227 | return; | 326 | return; |
| 327 | case Phase::Over: | ||
| 328 | return; | ||
| 329 | case Phase::Playing: | ||
| 330 | break; | ||
| 228 | } | 331 | } |
| 229 | 332 | ||
| 230 | // 自機 / the ship | 333 | // 自機 / the ship |
| @@ -233,10 +336,11 @@ void PlayScene::update(float dt) { | |||
| 233 | fire(); | 336 | fire(); |
| 234 | 337 | ||
| 235 | formation.update(dt); | 338 | formation.update(dt); |
| 339 | updateUfo(dt); | ||
| 236 | updateShot(dt); | 340 | updateShot(dt); |
| 237 | alienFire(dt); | 341 | alienFire(dt); |
| 238 | updateAlienShots(dt); | 342 | updateAlienShots(dt); |
| 239 | if (shipDying > 0.0f) return; | 343 | if (phase != Phase::Playing) return; // 撃たれた / the ship was hit |
| 240 | 344 | ||
| 241 | // 防壁まで下りてきた宇宙人は防壁を食べる / aliens that reach the shields eat them | 345 | // 防壁まで下りてきた宇宙人は防壁を食べる / aliens that reach the shields eat them |
| 242 | for (const Alien &a : formation.aliens) | 346 | for (const Alien &a : formation.aliens) |
| @@ -245,88 +349,110 @@ void PlayScene::update(float dt) { | |||
| 245 | // game over whatever lives are left | 349 | // game over whatever lives are left |
| 246 | if (formation.alive() > 0 && formation.bounds().bottom() > kPlayerY) { | 350 | if (formation.alive() > 0 && formation.bounds().bottom() > kPlayerY) { |
| 247 | printf("invaded\n"); | 351 | printf("invaded\n"); |
| 248 | lives = 1; | 352 | g.run.lives = 1; |
| 249 | killShip(); | 353 | killShip(); |
| 354 | shake.add(1.0f); | ||
| 250 | return; | 355 | return; |
| 251 | } | 356 | } |
| 252 | // 全滅させたら次の隊列(第29章で場面ごと読み直す) / when the formation is wiped out, a new one comes (chapter 29 | ||
| 253 | // reloads the whole scene) | ||
| 254 | if (formation.cleared()) { | 357 | if (formation.cleared()) { |
| 255 | ++waves; | 358 | printf("wave %d cleared: score %d\n", g.run.wave, g.run.score); |
| 256 | printf("wave cleared: %d kills\n", kills); | 359 | flash.start({1.0f, 1.0f, 1.0f, 0.5f}); |
| 257 | formation.reset(formationStartX(), kFormationTop); | 360 | ufo.active = false; |
| 258 | fireTimer = 1.0f; | 361 | alienShots.clear(); |
| 259 | } | 362 | setPhase(Phase::Cleared); |
| 260 | } | ||
| 261 | |||
| 262 | void PlayScene::drawBackground() { | ||
| 263 | SpriteBatch &b = g.batch; | ||
| 264 | // 脇の板と枠 / the side panels and their borders | ||
| 265 | b.drawRect({0.0f, 0.0f, kArenaLeft, kView.y}, hexColor(0x16132aff)); | ||
| 266 | b.drawRect({kArenaRight, 0.0f, kView.x - kArenaRight, kView.y}, hexColor(0x16132aff)); | ||
| 267 | b.drawRect({kArenaLeft - 1.0f, 0.0f, 1.0f, kView.y}, hexColor(0x3a3460ff)); | ||
| 268 | b.drawRect({kArenaRight, 0.0f, 1.0f, kView.y}, hexColor(0x3a3460ff)); | ||
| 269 | // 瞬く星 / twinkling stars | ||
| 270 | for (const Star &s : stars) { | ||
| 271 | float t = 0.5f + 0.5f * std::sin(2.0f * time + 6.283f * s.phase); | ||
| 272 | b.drawRect({s.position.x, s.position.y, 1.0f, 1.0f}, {0.62f, 0.64f, 0.8f, 0.25f + 0.5f * t}); | ||
| 273 | } | 363 | } |
| 274 | // 地面 / the ground | ||
| 275 | b.drawRect({kArenaLeft, kGroundY, kArenaRight - kArenaLeft, 1.0f}, hexColor(0x68c454ff)); | ||
| 276 | } | 364 | } |
| 277 | 365 | ||
| 278 | void PlayScene::drawFormation() { | 366 | void PlayScene::drawFormation() { |
| 279 | // 生きている宇宙人と、爆発中の宇宙人(爆発のコマ) / living aliens and exploding ones (explosion frames) | 367 | // 生きている宇宙人と、爆発中の宇宙人(爆発のコマ) / living aliens and exploding ones (explosion frames) |
| 368 | Mat4 camera = g.world.matrix(); | ||
| 280 | if (g.instanced) { | 369 | if (g.instanced) { |
| 281 | std::vector<AlienInstance> list; | 370 | std::vector<AlienInstance> list; |
| 282 | for (const Alien &a : formation.aliens) | 371 | for (const Alien &a : formation.aliens) |
| 283 | if (a.alive || a.dying > 0.0f) | 372 | if (a.alive || a.dying > 0.0f) |
| 284 | list.push_back({a.position, static_cast<std::uint32_t>(alienFrame(a)), packRgba8(kWhite)}); | 373 | list.push_back({a.position, static_cast<std::uint32_t>(alienFrame(a)), packRgba8(kWhite)}); |
| 285 | g.formationRenderer.draw(g.world.matrix(), list); | 374 | g.formationRenderer.draw(camera, list); |
| 286 | formationDrawCalls = g.formationRenderer.lastDrawCalls(); | 375 | g.formationDrawCalls = g.formationRenderer.lastDrawCalls(); |
| 287 | formationBytes = g.formationRenderer.lastBytes(); | 376 | g.formationBytes = g.formationRenderer.lastBytes(); |
| 288 | } else { | 377 | } else { |
| 289 | g.batch.begin(g.world.matrix()); | 378 | g.batch.begin(camera); |
| 290 | for (const Alien &a : formation.aliens) | 379 | for (const Alien &a : formation.aliens) |
| 291 | if (a.alive || a.dying > 0.0f) g.batch.draw(g.sprites.sprite(alienFrame(a), a.position)); | 380 | if (a.alive || a.dying > 0.0f) g.batch.draw(g.sprites.sprite(alienFrame(a), a.position)); |
| 292 | g.batch.end(); | 381 | g.batch.end(); |
| 293 | formationDrawCalls = g.batch.stats().drawCalls; | 382 | g.formationDrawCalls = g.batch.stats().drawCalls; |
| 294 | formationBytes = g.batch.stats().sprites * 4 * static_cast<int>(sizeof(SpriteVertex)); | 383 | g.formationBytes = g.batch.stats().sprites * 4 * static_cast<int>(sizeof(SpriteVertex)); |
| 295 | } | 384 | } |
| 296 | } | 385 | } |
| 297 | 386 | ||
| 298 | void PlayScene::drawBoxes() { | 387 | void PlayScene::drawBoxes() { |
| 299 | // 当たり判定の箱(B):宇宙人 = 赤、自機 = 緑、弾 = 黄、防壁 = 青(防壁はさらにピクセル単位で調べる) | 388 | // 当たり判定の箱(B):宇宙人 = 赤、自機 = 緑、弾 = 黄、防壁と円盤 = 青(防壁はさらにピクセル単位で調べる) |
| 300 | // The collision boxes (B): aliens red, ship green, bullets yellow, shields blue (shields are then tested per pixel) | 389 | // The collision boxes (B): aliens red, ship green, bullets yellow, shields and saucer blue (shields are then tested |
| 390 | // per pixel) | ||
| 301 | SpriteBatch &b = g.batch; | 391 | SpriteBatch &b = g.batch; |
| 302 | for (const Alien &a : formation.aliens) | 392 | for (const Alien &a : formation.aliens) |
| 303 | if (a.alive) b.drawRectOutline(a.box(), hexColor(0xff4040c0)); | 393 | if (a.alive) b.drawRectOutline(a.box(), hexColor(0xff4040c0)); |
| 304 | for (int i = 0; i < kShieldCount; ++i) b.drawRectOutline(shields->bounds(i), hexColor(0x40a0ffc0)); | 394 | for (int i = 0; i < kShieldCount; ++i) b.drawRectOutline(shields->bounds(i), hexColor(0x40a0ffc0)); |
| 305 | if (shipDying <= 0.0f && !gameOver) b.drawRectOutline(shipBox(), hexColor(0x40ff60ff)); | 395 | if (ufo.active) b.drawRectOutline(ufo.box(), hexColor(0x40a0ffff)); |
| 396 | if (phase == Phase::Playing) b.drawRectOutline(shipBox(), hexColor(0x40ff60ff)); | ||
| 306 | if (shot) b.drawRectOutline(shot->box, hexColor(0xffe040ff)); | 397 | if (shot) b.drawRectOutline(shot->box, hexColor(0xffe040ff)); |
| 307 | for (const Bullet &s : alienShots) b.drawRectOutline(s.box, hexColor(0xffe040ff)); | 398 | for (const Bullet &s : alienShots) b.drawRectOutline(s.box, hexColor(0xffe040ff)); |
| 308 | } | 399 | } |
| 309 | 400 | ||
| 401 | // 脇の板のHUD(キャンバスの中、pixel5):左 = 点数・最高点・波、右 = 残機・宇宙人の数・操作 | ||
| 402 | // The side-panel HUD (inside the canvas, pixel5): left = score, high score, wave; right = lives, aliens left, controls | ||
| 403 | void PlayScene::drawHud() { | ||
| 404 | char line[32]; | ||
| 405 | Vec4 digits = scoreFlash > 0.0f ? hexColor(0xffec96ff) : hexColor(0xf4f1e8ff); | ||
| 406 | drawTinyText(g, "SCORE", {6.0f, 10.0f}, kHudLabel); | ||
| 407 | snprintf(line, sizeof line, "%05d", g.run.score); | ||
| 408 | drawTinyText(g, line, {5.0f, 18.0f}, digits, 2.0f); | ||
| 409 | drawTinyText(g, "HI-SCORE", {6.0f, 40.0f}, kHudLabel); | ||
| 410 | snprintf(line, sizeof line, "%05d", std::max(g.hiScore, g.run.score)); | ||
| 411 | drawTinyText(g, line, {5.0f, 48.0f}, hexColor(0xf2c14eff), 2.0f); | ||
| 412 | drawTinyText(g, "WAVE", {6.0f, 70.0f}, kHudLabel); | ||
| 413 | snprintf(line, sizeof line, "%d", g.run.wave); | ||
| 414 | drawTinyText(g, line, {5.0f, 78.0f}, hexColor(0xf4f1e8ff), 2.0f); | ||
| 415 | |||
| 416 | const float rx = kArenaRight + 6.0f; | ||
| 417 | drawTinyText(g, "LIVES", {rx, 10.0f}, kHudLabel); | ||
| 418 | snprintf(line, sizeof line, "%d", g.run.lives); | ||
| 419 | drawTinyText(g, line, {rx - 1.0f, 18.0f}, hexColor(0xf4f1e8ff), 2.0f); | ||
| 420 | // 控えの自機(今の1機を除く) / the ships in reserve (not counting the one in play) | ||
| 421 | for (int i = 0; i < std::min(g.run.lives - 1, 4); ++i) | ||
| 422 | g.batch.draw(g.sprites.sprite(shipFrame, {rx + static_cast<float>(i % 2) * 18.0f, 32.0f + static_cast<float>(i / 2) * 11.0f})); | ||
| 423 | drawTinyText(g, "ALIENS", {rx, 70.0f}, kHudLabel); | ||
| 424 | snprintf(line, sizeof line, "%d", formation.alive()); | ||
| 425 | drawTinyText(g, line, {rx - 1.0f, 78.0f}, hexColor(0xf4f1e8ff), 2.0f); | ||
| 426 | drawTinyText(g, "P PAUSE", {rx, 150.0f}, kHudLabel); | ||
| 427 | drawTinyText(g, "C CRT", {rx, 158.0f}, kHudLabel); | ||
| 428 | drawTinyText(g, "TAB INFO", {rx, 166.0f}, kHudLabel); | ||
| 429 | } | ||
| 430 | |||
| 310 | void PlayScene::draw(float alpha) { | 431 | void PlayScene::draw(float alpha) { |
| 311 | if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor) | 432 | if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor) |
| 312 | // 防壁:変わった所だけGPUへ(描く前に) / shields: send only the changed part to the GPU (before drawing) | 433 | // 防壁:変わった所だけGPUへ(描く前に) / shields: send only the changed part to the GPU (before drawing) |
| 313 | shields->upload(); | 434 | shields->upload(); |
| 314 | if (shields->lastUploadBytes() > 0) shieldBytes = shields->lastUploadBytes(); | 435 | if (shields->lastUploadBytes() > 0) g.shieldBytes = shields->lastUploadBytes(); |
| 315 | 436 | ||
| 316 | // 奥から:背景と防壁(バッチ)→ 隊列(インスタンシングかバッチ)→ 自機・弾・爆発(バッチ) | 437 | // 揺れ:戦場の中身だけをカメラごとずらす(整数のピクセル)。脇の板とHUDは揺らさずに上から描くので、 |
| 317 | // Back to front: background and shields (batch) → formation (instanced or batch) → ship, bullets, explosions (batch) | 438 | // はみ出した分は隠れる |
| 318 | g.batch.begin(g.world.matrix()); | 439 | // Shake: only the arena's contents move, by moving the camera (whole pixels). The side panels and HUD are drawn on |
| 319 | drawBackground(); | 440 | // top without the shake, so whatever is pushed out is hidden |
| 320 | shields->draw(g.batch); | 441 | Camera2D steady = g.world; |
| 321 | g.batch.end(); | 442 | g.world.centre = steady.centre - shake.offset(); |
| 443 | SpriteBatch &b = g.batch; | ||
| 444 | b.begin(g.world.matrix()); | ||
| 445 | g.backdrop.drawSky(b, time); | ||
| 446 | shields->draw(b); | ||
| 447 | b.end(); | ||
| 322 | 448 | ||
| 323 | drawFormation(); | 449 | drawFormation(); |
| 324 | 450 | ||
| 325 | SpriteBatch &b = g.batch; | ||
| 326 | b.begin(g.world.matrix()); | 451 | b.begin(g.world.matrix()); |
| 327 | float x = std::round(playerPrevX + (playerX - playerPrevX) * alpha); | 452 | float x = std::round(playerPrevX + (playerX - playerPrevX) * alpha); |
| 328 | if (shipDying > 0.0f) b.draw(g.sprites.sprite(shipBoom.frame(), {x, kPlayerY})); | 453 | if (phase == Phase::ShipDown) b.draw(g.sprites.sprite(shipBoom.frame(), {x, kPlayerY})); |
| 329 | else if (!gameOver) b.draw(g.sprites.sprite(shipFrame, {x, kPlayerY})); | 454 | else if (phase != Phase::Over) b.draw(g.sprites.sprite(shipFrame, {x, kPlayerY})); |
| 455 | if (ufo.active) b.draw(g.sprites.sprite(ufoFrame, {std::round(ufo.prevX + (ufo.x - ufo.prevX) * alpha), kUfoY})); | ||
| 330 | // 弾は滑らかに動くので補間する / bullets move smoothly, so they are interpolated | 456 | // 弾は滑らかに動くので補間する / bullets move smoothly, so they are interpolated |
| 331 | if (shot) b.draw(g.sprites.sprite(shotFrame, {shot->box.x, std::round(shot->prevY + (shot->box.y - shot->prevY) * alpha)})); | 457 | if (shot) b.draw(g.sprites.sprite(shotFrame, {shot->box.x, std::round(shot->prevY + (shot->box.y - shot->prevY) * alpha)})); |
| 332 | for (const Bullet &s : alienShots) | 458 | for (const Bullet &s : alienShots) |
| @@ -337,69 +463,51 @@ void PlayScene::draw(float alpha) { | |||
| 337 | b.draw(s); | 463 | b.draw(s); |
| 338 | } | 464 | } |
| 339 | particles.draw(b); | 465 | particles.draw(b); |
| 466 | for (const Popup &p : popups) { | ||
| 467 | Vec4 c = p.color; | ||
| 468 | c.w = std::min(1.0f, 3.0f * p.life); | ||
| 469 | drawTinyText(g, p.text, {std::round(p.position.x), std::round(p.position.y)}, c, 1.0f, TextAlign::Centre); | ||
| 470 | } | ||
| 340 | if (g.showBoxes) drawBoxes(); | 471 | if (g.showBoxes) drawBoxes(); |
| 341 | b.end(); | 472 | b.end(); |
| 473 | |||
| 474 | // 揺れない物:閃光(戦場だけ)、波の見出し、脇の板とHUD / things that do not shake: the flash (arena only), the | ||
| 475 | // wave banner, the side panels and the HUD | ||
| 476 | g.world = steady; | ||
| 477 | b.begin(g.world.matrix()); | ||
| 478 | if (flash.color.w > 0.0f) b.drawRect({kArenaLeft, 0.0f, kArenaRight - kArenaLeft, kView.y}, flash.color); | ||
| 479 | char line[32]; | ||
| 480 | if (phase == Phase::Ready) { | ||
| 481 | // 後の波は隊列が低いので、見出しの後ろに暗い帯 / later waves start lower, so a dark band behind the banner | ||
| 482 | b.drawRect({kArenaLeft, 99.0f, kArenaRight - kArenaLeft, 28.0f}, {0.05f, 0.04f, 0.1f, 0.75f}); | ||
| 483 | } | ||
| 484 | if (phase == Phase::Ready && std::fmod(phaseTime, 0.4f) < 0.28f) { | ||
| 485 | snprintf(line, sizeof line, "WAVE %d", g.run.wave); | ||
| 486 | drawTinyText(g, line, {160.0f, 104.0f}, hexColor(0xf2c14eff), 2.0f, TextAlign::Centre); | ||
| 487 | drawTinyText(g, "GET READY", {160.0f, 120.0f}, hexColor(0xd8dcefff), 1.0f, TextAlign::Centre); | ||
| 488 | } | ||
| 489 | if (phase == Phase::Cleared) { | ||
| 490 | snprintf(line, sizeof line, "WAVE %d CLEAR", g.run.wave); | ||
| 491 | drawTinyText(g, line, {160.0f, 104.0f}, hexColor(0x9adc48ff), 2.0f, TextAlign::Centre); | ||
| 492 | } | ||
| 493 | g.backdrop.drawPanels(b); | ||
| 494 | drawHud(); | ||
| 495 | b.end(); | ||
| 342 | } | 496 | } |
| 343 | 497 | ||
| 344 | void PlayScene::drawUi(float /*alpha*/) { | 498 | void PlayScene::drawUi(float /*alpha*/) { |
| 345 | if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor) | 499 | if (!g.devInfo) return; |
| 500 | // 開発用の数字(Tab):画面の下に一行 / developer numbers (Tab): one line at the bottom | ||
| 501 | char line[192]; | ||
| 502 | snprintf(line, sizeof line, | ||
| 503 | "FPS %.0f formation %s (I): %d draw call(s), %d B/frame march %.0f aliens/s shield upload %d B " | ||
| 504 | "particles %zu", | ||
| 505 | static_cast<double>(g.loop.stats().fps), g.instanced ? "instanced" : "SpriteBatch", g.formationDrawCalls, | ||
| 506 | g.formationBytes, static_cast<double>(formation.rate), g.shieldBytes, particles.size()); | ||
| 346 | SpriteBatch &b = g.batch; | 507 | SpriteBatch &b = g.batch; |
| 347 | b.begin(g.screen.matrix()); | 508 | b.begin(g.screen.matrix()); |
| 348 | TextStyle head = {.color = hexColor(0xf2c14eff), .shadow = hexColor(0x000000ff)}; | 509 | b.drawRect({0.0f, 692.0f, 1280.0f, 28.0f}, hexColor(0x0c0a1ae0)); |
| 349 | TextStyle body = {.color = hexColor(0xd8dcefff), .shadow = hexColor(0x000000ff)}; | 510 | g.ui.draw(b, line, {640.0f, 697.0f}, |
| 350 | char line[64]; | 511 | {.color = hexColor(0xd8dcefff), .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); |
| 351 | // 左の板:隊列の描き方と、戦いの数字 / the left panel: how the formation is drawn, and the battle numbers | ||
| 352 | float y = 24.0f; | ||
| 353 | auto text = [&](const char *s, const TextStyle &st) { | ||
| 354 | g.ui.draw(b, s, {14.0f, y}, st); | ||
| 355 | y += 22.0f; | ||
| 356 | }; | ||
| 357 | text("FORMATION (I)", head); | ||
| 358 | text(g.instanced ? "instanced" : "SpriteBatch", body); | ||
| 359 | snprintf(line, sizeof line, "%d B/frame", formationBytes); | ||
| 360 | text(line, body); | ||
| 361 | snprintf(line, sizeof line, "%.0f aliens/s", static_cast<double>(formation.rate)); | ||
| 362 | text(line, body); | ||
| 363 | snprintf(line, sizeof line, "alive %d", formation.alive()); | ||
| 364 | text(line, body); | ||
| 365 | y += 16.0f; | ||
| 366 | text("BATTLE", head); | ||
| 367 | snprintf(line, sizeof line, "lives %d", lives); | ||
| 368 | text(line, body); | ||
| 369 | snprintf(line, sizeof line, "kills %d", kills); | ||
| 370 | text(line, body); | ||
| 371 | snprintf(line, sizeof line, "shots %d", shotsFired); | ||
| 372 | text(line, body); | ||
| 373 | snprintf(line, sizeof line, "wave %d", waves); | ||
| 374 | text(line, body); | ||
| 375 | y += 16.0f; | ||
| 376 | text("SHIELDS", head); | ||
| 377 | snprintf(line, sizeof line, "%d px left", shields->pixelsLeft()); | ||
| 378 | text(line, body); | ||
| 379 | snprintf(line, sizeof line, "upload %d B", shieldBytes); | ||
| 380 | text(line, body); | ||
| 381 | |||
| 382 | // 右の板:操作 / the right panel: controls | ||
| 383 | y = 24.0f; | ||
| 384 | auto right = [&](const char *s, const TextStyle &st) { | ||
| 385 | g.ui.draw(b, s, {1102.0f, y}, st); | ||
| 386 | y += 22.0f; | ||
| 387 | }; | ||
| 388 | right("CONTROLS", head); | ||
| 389 | right("A D / arrows", body); | ||
| 390 | right(" move", body); | ||
| 391 | right("Space fire", body); | ||
| 392 | right("I formation", body); | ||
| 393 | right("B boxes", body); | ||
| 394 | right("= - march", body); | ||
| 395 | right("Esc quit", body); | ||
| 396 | |||
| 397 | if (gameOver) { | ||
| 398 | b.drawRect({192.0f, 300.0f, 896.0f, 110.0f}, hexColor(0x0c0a1ad0)); | ||
| 399 | g.ui.draw(b, "GAME OVER", {640.0f, 316.0f}, | ||
| 400 | {.color = hexColor(0xd9474bff), .scale = 3.0f, .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); | ||
| 401 | g.ui.draw(b, "Space / Enter: play again", {640.0f, 378.0f}, | ||
| 402 | {.color = hexColor(0xd8dcefff), .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); | ||
| 403 | } | ||
| 404 | b.end(); | 512 | b.end(); |
| 405 | } | 513 | } |
ファイル: /dev/null | b/games/invaders/src/title_scene.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,79 @@ | |||
| 1 | // タイトル(第29章):ロゴ、点数表(宇宙人が足踏み)、最高得点、横切る円盤。スペースで新しい遊びを始める | ||
| 2 | // The title (chapter 29): logo, score table (the aliens walk on the spot), high score, a passing saucer. Space starts a | ||
| 3 | // new game | ||
| 4 | #include "game.hh" | ||
| 5 | |||
| 6 | #include <cmath> | ||
| 7 | #include <cstdio> | ||
| 8 | #include <memory> | ||
| 9 | |||
| 10 | void TitleScene::enter() { printf("title: high score %d\n", g.hiScore); } | ||
| 11 | |||
| 12 | void TitleScene::update(float dt) { | ||
| 13 | time += dt; | ||
| 14 | ufoPrevX = ufoX; | ||
| 15 | ufoX += 30.0f * dt; | ||
| 16 | if (ufoX > kArenaRight + 40.0f) ufoX = ufoPrevX = kArenaLeft - 60.0f; // 戦場の外で一周 / loops outside the arena | ||
| 17 | if (g.input.pressed(GLFW_KEY_ESCAPE)) { | ||
| 18 | scenes().pop(); // 空になる → 終了 / empty → quit | ||
| 19 | return; | ||
| 20 | } | ||
| 21 | if (g.input.actionPressed("confirm")) { | ||
| 22 | g.run = Run{}; // 新しい遊び:点数0、残機3、第1波 / a new game: score 0, 3 lives, wave 1 | ||
| 23 | // 円盤を止めておく(第26章の課題5の直し方。drawAlphaもフェードアウト中はalpha = 1で描く) | ||
| 24 | // hold the saucer still (the fix of ch26 challenge 5; drawAlpha also draws alpha = 1 during the fade-out) | ||
| 25 | ufoPrevX = ufoX; | ||
| 26 | scenes().replace(std::make_unique<PlayScene>(g), {.duration = 0.8f}); | ||
| 27 | } | ||
| 28 | } | ||
| 29 | |||
| 30 | void TitleScene::draw(float alpha) { | ||
| 31 | SpriteBatch &b = g.batch; | ||
| 32 | b.begin(g.world.matrix()); | ||
| 33 | g.backdrop.drawSky(b, time); | ||
| 34 | // ロゴ(64 × 11)を2倍で / the logo (64 × 11) at × 2 | ||
| 35 | Sprite logo = g.sprites.sprite(g.sprites.find("logo"), {160.0f, 20.0f}, {0.5f, 0.0f}, 2.0f); | ||
| 36 | b.draw(logo); | ||
| 37 | // 円盤(横切る) / the saucer (passing by) | ||
| 38 | float ux = std::round(ufoPrevX + (ufoX - ufoPrevX) * alpha); | ||
| 39 | b.draw(g.sprites.sprite(g.sprites.find("ufo"), {ux, 52.0f})); | ||
| 40 | |||
| 41 | // 点数表:宇宙人は0.5秒ごとに足踏み / the score table: the aliens change pose every 0.5 s | ||
| 42 | int pose = static_cast<int>(time * 2.0f) % 2; | ||
| 43 | const char *names[3][2] = {{"jelly_0", "jelly_1"}, {"beetle_0", "beetle_1"}, {"blob_0", "blob_1"}}; | ||
| 44 | const char *points[3] = {"= 30 POINTS", "= 20 POINTS", "= 10 POINTS"}; | ||
| 45 | const Vec4 label = hexColor(0xd8dcefff); | ||
| 46 | b.draw(g.sprites.sprite(g.sprites.find("ufo"), {116.0f, 70.0f})); | ||
| 47 | drawTinyText(g, "= ? MYSTERY", {140.0f, 71.0f}, hexColor(0xd9474bff)); | ||
| 48 | for (int k = 0; k < 3; ++k) { | ||
| 49 | float y = 84.0f + 14.0f * static_cast<float>(k); | ||
| 50 | b.draw(g.sprites.sprite(g.sprites.find(names[k][pose]), {118.0f, y - 2.0f})); | ||
| 51 | drawTinyText(g, points[k], {140.0f, y}, label); | ||
| 52 | } | ||
| 53 | b.end(); | ||
| 54 | |||
| 55 | b.begin(g.world.matrix()); | ||
| 56 | g.backdrop.drawPanels(b); | ||
| 57 | char line[16]; | ||
| 58 | drawTinyText(g, "HI-SCORE", {6.0f, 40.0f}, {0.55f, 0.57f, 0.75f, 1.0f}); | ||
| 59 | snprintf(line, sizeof line, "%05d", g.hiScore); | ||
| 60 | drawTinyText(g, line, {5.0f, 48.0f}, hexColor(0xf2c14eff), 2.0f); | ||
| 61 | drawTinyText(g, "C CRT", {kArenaRight + 6.0f, 158.0f}, {0.55f, 0.57f, 0.75f, 1.0f}); | ||
| 62 | drawTinyText(g, "ESC QUIT", {kArenaRight + 6.0f, 166.0f}, {0.55f, 0.57f, 0.75f, 1.0f}); | ||
| 63 | b.end(); | ||
| 64 | } | ||
| 65 | |||
| 66 | void TitleScene::drawUi(float /*alpha*/) { | ||
| 67 | // 画面の解像度の文字(mono16):日本語は短い所だけ / text at screen resolution (mono16): Japanese only where short | ||
| 68 | SpriteBatch &b = g.batch; | ||
| 69 | b.begin(g.screen.matrix()); | ||
| 70 | float blink = 0.55f + 0.45f * std::cos(4.0f * time); | ||
| 71 | g.ui.draw(b, "スペースキーで開始 / PRESS SPACE", {640.0f, 556.0f}, | ||
| 72 | {.color = {1.0f, 0.93f, 0.6f, blink}, .scale = 2.0f, .align = TextAlign::Centre, | ||
| 73 | .shadow = {0.0f, 0.0f, 0.0f, blink}}); | ||
| 74 | g.ui.draw(b, "A D 左右・Space 撃つ・P 一時停止・Esc 終了", {640.0f, 620.0f}, | ||
| 75 | {.color = hexColor(0xb8bccaff), .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); | ||
| 76 | g.ui.draw(b, "A D move / Space fire / P pause / Esc quit", {640.0f, 642.0f}, | ||
| 77 | {.color = hexColor(0xb8bccaff), .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); | ||
| 78 | b.end(); | ||
| 79 | } | ||
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。