diff --git a/games/invaders/CMakeLists.txt b/games/invaders/CMakeLists.txt index d5d31d3..37ebba6 100644 --- a/games/invaders/CMakeLists.txt +++ b/games/invaders/CMakeLists.txt @@ -3,11 +3,16 @@ # 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/effects.cc + src/crt.cc) target_include_directories(invaders PRIVATE src) target_link_libraries(invaders PRIVATE engine) enable_warnings(invaders) diff --git a/games/invaders/README.md b/games/invaders/README.md index db437a3..650d713 100644 --- a/games/invaders/README.md +++ b/games/invaders/README.md @@ -12,20 +12,31 @@ is already the project root)。 ## 操作 / Controls | キー / Key | | |---|---| +| Space / Enter | タイトル:開始 / title: start | | ← → / A D | 移動 / move | | Space / ↑ / W | 撃つ / fire | -| I | 隊列の描き方:インスタンシング ⇔ SpriteBatch / formation: instancing ⇔ SpriteBatch | -| B | 当たり判定の箱 / collision boxes | -| = / - | 行進を速く・遅く / march faster / slower | -| Space / Enter | ゲームオーバーの後:もう一度 / after game over: play again | -| Esc | 終了 / quit | +| P / Esc | 一時停止(↑ ↓ で選んで Space / Enter) / pause (↑ ↓ to choose, Space / Enter) | +| Esc | タイトルで:終了 / on the title: quit | +| C | ブラウン管風の仕上げ オン・オフ / CRT finish on / off | +| Tab | 開発用の数字 / developer numbers | +| I | 隊列の描き方:インスタンシング ⇔ SpriteBatch(開発用) / formation: instancing ⇔ SpriteBatch (developer) | +| B | 当たり判定の箱(開発用) / collision boxes (developer) | +| = / - | 行進を速く・遅く(開発用) / march faster / slower (developer) | +| N | 次の波へ(開発用、点は入らない) / next wave (developer, no points) | + +点数 / points: クラゲ / jelly 30, 甲虫 / beetle 20, 丸い奴 / blob 10, 円盤 / saucer 50-300。1500点で1機増える / an extra +ship at 1500 points。 ## ファイル / Files -* `src/main.cc` ウィンドウ、読み込み、行動、ゲームループ / window, loading, actions, game loop -* `src/game.hh` 共有データ・画面の寸法・シーン / shared data, layout, scenes -* `src/play_scene.cc` 遊ぶ場面 / the play scene +* `src/main.cc` ウィンドウ、読み込み、行動、ゲームループ、ブラウン管風の仕上げ / window, loading, actions, game loop, CRT +* `src/game.hh/.cc` 共有データ(`Game`、`Run`)、波の難しさ、シーンの宣言 / shared data, wave difficulty, scenes +* `src/layout.hh` 画面の寸法 / the layout +* `src/title_scene.cc`, `src/play_scene.cc`, `src/menus.cc` タイトル・遊ぶ場面・一時停止とゲームオーバー / title, play, + pause and game over +* `src/backdrop.hh/.cc` 星と脇の板 / stars and side panels * `src/formation.hh/.cc` 隊列と行進(GLなし) / the formation and its march (no GL) * `src/formation_renderer.hh/.cc`, `shaders/formation.vert` インスタンシングで隊列を描く / instanced formation drawing * `src/shields.hh/.cc` 削れる防壁(CPUのピクセル+glTextureSubImage2D) / eroding shields (CPU pixels + glTextureSubImage2D) -* `src/effects.hh/.cc` 破片と着弾 / debris particles and impact flares +* `src/effects.hh/.cc` 破片、着弾、画面の揺れ、閃光 / debris, impacts, screen shake, flashes +* `src/crt.hh/.cc`, `shaders/crt.frag` ブラウン管風の仕上げ / the CRT finish * `assets/` 絵(作者の自作スクリプトで生成。スクリプトはダウンロードに含まれない) / art (generated by the author's own script, not part of the download) diff --git a/games/invaders/shaders/crt.frag b/games/invaders/shaders/crt.frag new file mode 100644 index 0000000..e164ffa --- /dev/null +++ b/games/invaders/shaders/crt.frag @@ -0,0 +1,37 @@ +#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); +} diff --git a/games/invaders/src/backdrop.cc b/games/invaders/src/backdrop.cc new file mode 100644 index 0000000..948e8bc --- /dev/null +++ b/games/invaders/src/backdrop.cc @@ -0,0 +1,27 @@ +#include "backdrop.hh" + +#include "engine/rng.hh" + +#include + +Backdrop::Backdrop() { + Rng sky(1978); + for (int i = 0; i < 40; ++i) + stars.push_back({{std::round(sky.range(kArenaLeft + 2.0f, kArenaRight - 2.0f)), std::round(sky.range(4.0f, 150.0f))}, + sky.unit()}); +} + +void Backdrop::drawSky(SpriteBatch &b, float time) const { + for (const Star &s : stars) { + float t = 0.5f + 0.5f * std::sin(2.0f * time + 6.283f * s.phase); + b.drawRect({s.position.x, s.position.y, 1.0f, 1.0f}, {0.62f, 0.64f, 0.8f, 0.25f + 0.5f * t}); + } + b.drawRect({kArenaLeft, kGroundY, kArenaRight - kArenaLeft, 1.0f}, hexColor(0x68c454ff)); +} + +void Backdrop::drawPanels(SpriteBatch &b) const { + b.drawRect({0.0f, 0.0f, kArenaLeft, kView.y}, hexColor(0x16132aff)); + b.drawRect({kArenaRight, 0.0f, kView.x - kArenaRight, kView.y}, hexColor(0x16132aff)); + b.drawRect({kArenaLeft - 1.0f, 0.0f, 1.0f, kView.y}, hexColor(0x3a3460ff)); + b.drawRect({kArenaRight, 0.0f, 1.0f, kView.y}, hexColor(0x3a3460ff)); +} diff --git a/games/invaders/src/backdrop.hh b/games/invaders/src/backdrop.hh new file mode 100644 index 0000000..80b5265 --- /dev/null +++ b/games/invaders/src/backdrop.hh @@ -0,0 +1,25 @@ +// 背景(第29章でタイトルと遊ぶ場面の共通に):瞬く星、地面、脇の板 +// The backdrop (shared by the title and the play scene from chapter 29): twinkling stars, the ground, the side panels +#pragma once + +#include "layout.hh" + +#include "engine/sprite_batch.hh" + +#include + +class Backdrop { +public: + Backdrop(); // 星は自分の種で作る:何度場面を作り直しても同じ空 / stars use their own seed: the same sky every time + void drawSky(SpriteBatch &batch, float time) const; // 星と地面(戦場の中) / stars and ground (inside the arena) + // 脇の板と枠。戦場の物(揺れではみ出した分も)の上に描いて隠す / the side panels and borders, drawn over the + // arena's contents so they hide whatever a shake pushes out + void drawPanels(SpriteBatch &batch) const; + +private: + struct Star { + Vec2 position; + float phase; + }; + std::vector stars; +}; diff --git a/games/invaders/src/crt.cc b/games/invaders/src/crt.cc new file mode 100644 index 0000000..719d5c7 --- /dev/null +++ b/games/invaders/src/crt.cc @@ -0,0 +1,30 @@ +#include "crt.hh" + +std::optional 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; +} + +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(v.x), static_cast(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; +} diff --git a/games/invaders/src/crt.hh b/games/invaders/src/crt.hh new file mode 100644 index 0000000..3a0499c --- /dev/null +++ b/games/invaders/src/crt.hh @@ -0,0 +1,26 @@ +// ブラウン管風の仕上げ(第29章):PixelCanvasのテクスチャを、ただ拡大コピー(present)する代わりに +// シェーダーで画面に描く。走査線、蛍光体の縞、にじみ、周辺減光 +// A CRT-style finish (chapter 29): instead of the plain scaled copy (present), the PixelCanvas texture is drawn to the +// screen through a shader: scanlines, a phosphor mask, a little glow, a vignette +#pragma once + +#include "engine/framebuffer.hh" +#include "engine/pixel_canvas.hh" +#include "engine/shader.hh" + +#include + +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 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; + FullscreenTriangle triangle; +}; diff --git a/games/invaders/src/effects.cc b/games/invaders/src/effects.cc index 8da169d..58972ee 100644 --- a/games/invaders/src/effects.cc +++ b/games/invaders/src/effects.cc @@ -27,3 +27,11 @@ void Particles::draw(SpriteBatch &batch, float layer) const { batch.drawRect({std::round(p.position.x), std::round(p.position.y), 1.0f, 1.0f}, c, layer); } } + +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))}; +} diff --git a/games/invaders/src/effects.hh b/games/invaders/src/effects.hh index 3565366..50d48bd 100644 --- a/games/invaders/src/effects.hh +++ b/games/invaders/src/effects.hh @@ -1,10 +1,13 @@ -// 爆発の飾り(第28章):飛び散るピクセル(パーティクル)と、短く見せるスプライト(着弾など) -// Explosion dressing (chapter 28): flying pixels (particles) and sprites shown for a moment (impacts and such) +// 爆発の飾り(第28章):飛び散るピクセル(パーティクル)と、短く見せるスプライト(着弾など)。 +// 第29章:画面の揺れと閃光 +// Explosion dressing (chapter 28): flying pixels (particles) and sprites shown for a moment (impacts and such). +// Chapter 29: screen shake and flashes #pragma once #include "engine/rng.hh" #include "engine/sprite_batch.hh" +#include #include // 1ピクセルの破片。固定ステップで動き、だんだん消える / one-pixel debris: moves in the fixed step and fades out @@ -34,3 +37,27 @@ struct Flare { float life; // 残り秒 / seconds left Vec4 color; }; + +// 画面の揺れ(第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}; +}; + +// 閃光:色の四角を一瞬かぶせ、すぐに消す / 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 +}; diff --git a/games/invaders/src/game.cc b/games/invaders/src/game.cc new file mode 100644 index 0000000..71d3410 --- /dev/null +++ b/games/invaders/src/game.cc @@ -0,0 +1,27 @@ +// 場面をまたいで使う小さな道具 / small helpers shared by the scenes +#include "game.hh" + +#include + +// 波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(w); + return {.top = kFormationTop + 6.0f * static_cast(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(w), + .maxShots = 3 + (w >= 2) + (w >= 5)}; +} + +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}}); +} diff --git a/games/invaders/src/game.hh b/games/invaders/src/game.hh index 9f1652f..ed75f69 100644 --- a/games/invaders/src/game.hh +++ b/games/invaders/src/game.hh @@ -2,9 +2,11 @@ // Invaders: the data every scene shares, the screen layout, the scenes #pragma once +#include "backdrop.hh" #include "effects.hh" #include "formation.hh" #include "formation_renderer.hh" +#include "layout.hh" #include "shields.hh" #include "engine/animation.hh" @@ -20,20 +22,31 @@ #include #include -// 仮想解像度320 × 180(ウィンドウ1280 × 720で4倍)。真ん中の224ピクセル幅が戦場、左右48ピクセルは脇の板 -// Virtual resolution 320 × 180 (× 4 in the 1280 × 720 window). The middle 224 pixels are the arena, 48 pixels on -// each side are side panels -constexpr Vec2 kView = {320.0f, 180.0f}; -constexpr float kArenaLeft = 48.0f, kArenaRight = 272.0f; -constexpr float kFormationTop = 28.0f; // 最初の隊列の一番上 / the first formation's top row -constexpr float kShieldY = 136.0f; // 防壁の上端 / the shields' top -constexpr float kPlayerY = 158.0f; // 自機の上端 / the ship's top -constexpr float kGroundY = 170.0f; // 地面の線 / the ground line +// 速さと決まり(画面の寸法はlayout.hh) / speeds and rules (the layout is in layout.hh) constexpr float kPlayerSpeed = 60.0f; // ピクセル毎秒(1ステップ1ピクセル) / pixels per second (1 px per step) constexpr float kShotSpeed = 240.0f; // 自機の弾:1ステップ4ピクセル / the ship's bullet: 4 px per step -constexpr float kAlienShotSpeed = 75.0f; // 宇宙人の弾 / alien bullets -constexpr int kMaxAlienShots = 3; constexpr int kStartLives = 3; +constexpr int kExtraLifeScore = 1500; // 一度だけ1機増える / one extra ship, once + +// 波ごとの難しさ(第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); + +// 一回の遊び(タイトルで作り直す)。波が変わっても場面をまたいで残る / 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 { @@ -43,50 +56,98 @@ struct Game { 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; }; -// 遊ぶ場面:自機、行進する隊列、弾、防壁、爆発 / the play scene: the ship, the marching formation, bullets, -// shields, explosions +// スコアの5桁表示とHUDの文字(pixel5、キャンバスの中) / the 5-digit score and HUD text (pixel5, inside the canvas) +void drawTinyText(Game &g, const char *text, Vec2 position, Vec4 color, float scale = 1.0f, + TextAlign align = TextAlign::Left); + +// タイトル:ロゴ、点数表、最高得点。スペースで始める / the title: logo, score table, high score. Space starts +class TitleScene : public Scene { +public: + explicit TitleScene(Game &game) : g(game) {} + void enter() override; + void update(float dt) override; + void draw(float alpha) override; + void drawUi(float alpha) override; + +private: + Game &g; + float time = 0.0f; + float ufoX = 180.0f, ufoPrevX = 180.0f; +}; + +// 遊ぶ場面:一つの波。全滅させたら、波の番号を上げて自分を新しい場面と入れ替える(場面の読み直し) +// The play scene: one wave. When the wave is wiped out it raises the wave number and replaces itself with a fresh +// scene (scene reloading) class PlayScene : public Scene { public: explicit PlayScene(Game &game); + void enter() override; void pause() override; void update(float dt) override; void draw(float alpha) override; void drawUi(float alpha) override; private: - struct Star { - Vec2 position; - float phase; - }; + enum class Phase { Ready, Playing, ShipDown, Cleared, Over }; // 弾:当たり判定の箱と、補間用の前のステップのy / a bullet: its collision box and last step's y (interpolation) struct Bullet { Rect box; float prevY; Animator anim; // 宇宙人の弾は4コマのクリップ / alien bullets play a 4-frame clip }; + struct Ufo { + bool active = false; + float x = 0.0f, prevX = 0.0f, direction = 1.0f; + Rect box() const { return {x + 1.0f, kUfoY + 1.0f, 16.0f, 6.0f}; } + }; + // 点数が浮かぶ(円盤、1UP) / floating score text (the saucer, 1UP) + struct Popup { + Vec2 position; + float life; + char text[12]; + Vec4 color; + }; + void setPhase(Phase p); int alienFrame(const Alien &a) const; Rect shipBox() const; void fire(); void alienFire(float dt); void updateShot(float dt); void updateAlienShots(float dt); + void updateUfo(float dt); void killShip(); + void addScore(int points); + void popup(Vec2 position, const char *text, Vec4 color); void flare(Vec2 centre, Vec4 color, float life = 0.12f); - void drawBackground(); void drawFormation(); void drawBoxes(); + void drawHud(); Game &g; + WaveSettings settings; + Phase phase = Phase::Ready; + float phaseTime = 0.0f; + bool leaving = false; // 次の波を頼んだ / the next wave was requested Formation formation; std::optional shields; float playerX = 0.0f, playerPrevX = 0.0f; // 自機の左端(補間用に前のステップも) / the ship's left edge (+ the @@ -95,17 +156,49 @@ private: // (as in the original) std::vector alienShots; float fireTimer = 1.0f; // 宇宙人が次に撃つまで / until the aliens fire next - float shipDying = 0.0f; // 自機の爆発の残り時間(> 0 の間は隊列も止まる) / ship explosion time - // left (the march stops meanwhile) + Ufo ufo; + float ufoTimer = 0.0f; Animator shipBoom; Particles particles; std::vector flares; - std::vector stars; + std::vector popups; + Shake shake; // 画面の揺れ(戦場だけ) / screen shake (the arena only) + ScreenFlash flash; // 戦場が一瞬光る / the arena lights up for a moment + float scoreFlash = 0.0f; // 点が入ったときHUDの数字が光る / the HUD digits flash on points float time = 0.0f; int frames[3][2] = {}; // 種類 × 足踏み → シートのコマ / kind × pose → sheet frame - int shipFrame = 0, shotFrame = 0, splatFrame = 0, boomFrames[2] = {}; + int shipFrame = 0, shotFrame = 0, splatFrame = 0, ufoFrame = 0, boomFrames[2] = {}; const AnimationClip *zigClip = nullptr, *boltClip = nullptr, *shipBoomClip = nullptr; - int formationDrawCalls = 0, formationBytes = 0, shieldBytes = 0; - int lives = kStartLives, kills = 0, shotsFired = 0, waves = 1; - bool gameOver = false; + int shotsFired = 0; +}; + +// 一時停止(上に重ねるシーン):再開かタイトルへ / pause (an overlay): resume or back to the title +class PauseScene : public Scene { +public: + explicit PauseScene(Game &game) : g(game) {} + bool isOverlay() const override { return true; } + void update(float dt) override; + void draw(float alpha) override; + void drawUi(float alpha) override; + +private: + Game &g; + float time = 0.0f; + int selected = 0; +}; + +// ゲームオーバー(上に重ねるシーン):止まった戦場の上に結果を出し、スペースでタイトルへ +// Game over (an overlay): shows the result over the frozen arena; Space goes back to the title +class GameOverScene : public Scene { +public: + GameOverScene(Game &game, bool newHighScore) : g(game), newHigh(newHighScore) {} + bool isOverlay() const override { return true; } + void update(float dt) override; + void draw(float alpha) override; + void drawUi(float alpha) override; + +private: + Game &g; + bool newHigh; + float time = 0.0f; }; diff --git a/games/invaders/src/layout.hh b/games/invaders/src/layout.hh new file mode 100644 index 0000000..8cee035 --- /dev/null +++ b/games/invaders/src/layout.hh @@ -0,0 +1,15 @@ +// Invaders:画面の寸法(キャンバスのピクセル) / Invaders: the screen layout (canvas pixels) +#pragma once + +#include "engine/mathx.hh" + +// 仮想解像度320 × 180(ウィンドウ1280 × 720で4倍)。真ん中の224ピクセル幅が戦場、左右48ピクセルは脇の板 +// Virtual resolution 320 × 180 (× 4 in the 1280 × 720 window). The middle 224 pixels are the arena, 48 pixels on +// each side are side panels +constexpr Vec2 kView = {320.0f, 180.0f}; +constexpr float kArenaLeft = 48.0f, kArenaRight = 272.0f; +constexpr float kFormationTop = 28.0f; // 第1波の隊列の一番上 / the first wave's top row +constexpr float kUfoY = 14.0f; // 円盤の通り道 / the saucer's lane +constexpr float kShieldY = 136.0f; // 防壁の上端 / the shields' top +constexpr float kPlayerY = 158.0f; // 自機の上端 / the ship's top +constexpr float kGroundY = 170.0f; // 地面の線 / the ground line diff --git a/games/invaders/src/main.cc b/games/invaders/src/main.cc index 263386e..c0bbd53 100644 --- a/games/invaders/src/main.cc +++ b/games/invaders/src/main.cc @@ -1,13 +1,16 @@ -// Invaders 第2部(第28章):弾、AABBの当たり判定、宇宙人の弾、削れる防壁、爆発 -// Invaders part 2 (chapter 28): bullets, AABB collisions, alien bullets, shields that erode, explosions +// Invaders 第3部(第29章):点数・残機・HUD、タイトルとゲームオーバーの場面、波ごとの場面の読み直し、速くなる波、 +// 磨き(画面の揺れ、閃光、ブラウン管風の仕上げ) +// Invaders part 3 (chapter 29): score, lives and the HUD, title and game-over scenes, reloading the scene for every +// wave, waves that speed up, polish (screen shake, flashes, a CRT-style finish) // // 操作 / Controls: -// ← → / A D 移動 / move -// Space / ↑ 撃つ / fire -// I 隊列の描き方:インスタンシング ⇔ SpriteBatch / formation: instancing ⇔ SpriteBatch -// B 当たり判定の箱 / collision boxes -// = / - 行進を速く・遅く / march faster / slower -// Esc 終了 / quit +// タイトル / title Space・Enter 開始 / start Esc 終了 / quit +// 遊ぶ / play ← → / A D 移動 / move Space / ↑ / W 撃つ / fire P / Esc 一時停止 / pause +// 一時停止 / pause ↑ ↓ 選ぶ / select Space・Enter 決定 / confirm P / Esc 再開 / resume +// いつでも / any time C ブラウン管風 / CRT Tab 開発用の数字 / developer numbers +// 開発用 / developer I 隊列の描き方 / formation drawing B 当たり判定の箱 / collision boxes +// = / - 行進の速さ / march speed N 次の波 / next wave +#include "crt.hh" #include "game.hh" #include "engine/pixel_canvas.hh" @@ -22,13 +25,17 @@ int main() { std::optional batch = SpriteBatch::create(); std::optional ui = Font::load("assets/fonts/mono16.fnt"); + // キャンバスの中のHUD:3 × 5の1ビットの文字(GL_NEAREST) / the canvas HUD: the 1-bit 3 × 5 font (GL_NEAREST) + std::optional tiny = Font::load("assets/fonts/pixel5.fnt", TextureFilter::Nearest); std::optional sprites = SpriteSheet::loadAtlas("games/invaders/assets/sprites.atlas"); - if (!batch || !ui || !sprites) return 1; + if (!batch || !ui || !tiny || !sprites) return 1; std::optional formationRenderer = FormationRenderer::create(*sprites); // 防壁の絵はCPUにも要る(削るため):同じPNGをもう一度デコードして切り出す / the shield art is needed on the CPU // too (to erode it): decode the same PNG again and cut it out std::optional shieldArt = loadSpriteImage("games/invaders/assets/sprites.png", *sprites, "shield"); - if (!formationRenderer || !shieldArt) return 1; + std::optional crt = CrtFilter::create(); + if (!formationRenderer || !shieldArt || !crt) return 1; + Backdrop backdrop; // 行動に名前を付ける(キーを変えるならここだけ) / name the actions (to change keys, edit only this) Input input; @@ -42,23 +49,28 @@ int main() { GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); PixelCanvas canvas(static_cast(kView.x), static_cast(kView.y)); Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .formationRenderer = *formationRenderer, - .ui = *ui, .sprites = *sprites, .shieldArt = *shieldArt, .world = Camera2D::screen(kView), - .screen = Camera2D::screen({1280.0f, 720.0f}), .uiViewport = {}}; + .ui = *ui, .tiny = *tiny, .sprites = *sprites, .shieldArt = *shieldArt, .backdrop = backdrop, + .world = Camera2D::screen(kView), .screen = Camera2D::screen({1280.0f, 720.0f}), .uiViewport = {}}; SceneManager scenes; - scenes.push(std::make_unique(game)); + scenes.push(std::make_unique(game)); loop.run( window, input, [&](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(); }, [&](float alpha) { - // 1. 世界:320 × 180のキャンバスに描いて4倍で画面へ / 1. the world: into the 320 × 180 canvas, shown × 4 + // 1. 世界:320 × 180のキャンバスに描き、4倍で画面へ(そのままコピーか、ブラウン管風のシェーダーで) + // 1. the world: into the 320 × 180 canvas, then × 4 onto the screen (a plain copy, or through the CRT shader) canvas.begin(hexColor(0x0c0a1aff)); scenes.draw(alpha); - canvas.present(window.width(), window.height()); + if (game.crt) crt->present(canvas, window.width(), window.height()); + else canvas.present(window.width(), window.height()); // 2. UI:1280 × 720の文字 / 2. the UI: text at 1280 × 720 game.uiViewport = letterbox(window.width(), window.height(), game.screen.viewSize, false); game.uiViewport.apply(); diff --git a/games/invaders/src/menus.cc b/games/invaders/src/menus.cc new file mode 100644 index 0000000..82ed9f6 --- /dev/null +++ b/games/invaders/src/menus.cc @@ -0,0 +1,93 @@ +// 上に重ねるシーン(第29章):一時停止とゲームオーバー。下の遊ぶ場面は描かれるが更新されない(止まった戦場) +// Overlay scenes (chapter 29): pause and game over. The play scene below is drawn but not updated (a frozen arena) +#include "game.hh" + +#include +#include +#include +#include +#include +#include + +// 戦場を暗くする(キャンバスの中、脇の板は残す) / darken the arena (inside the canvas; the side panels stay) +static void dimArena(Game &g, float amount) { + g.batch.begin(g.world.matrix()); + g.batch.drawRect({kArenaLeft, 0.0f, kArenaRight - kArenaLeft, kView.y}, {0.03f, 0.02f, 0.08f, amount}); + g.batch.end(); +} + +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(g), {.duration = 0.8f}); + } +} + +void PauseScene::draw(float /*alpha*/) { dimArena(g, std::min(1.0f, time * 4.0f) * 0.6f); } + +void PauseScene::drawUi(float /*alpha*/) { + SpriteBatch &b = g.batch; + b.begin(g.screen.matrix()); + // 枠:文字が下の宇宙人と混ざらないように / a panel, so the text does not mix with the aliens below + Rect panel = {340.0f, 220.0f, 600.0f, 210.0f}; + b.drawRect(panel, hexColor(0x16132af0)); + b.drawRectOutline(panel, hexColor(0x3a3460ff), 4.0f); + g.ui.draw(b, "一時停止 / PAUSED", {640.0f, 244.0f}, + {.color = hexColor(0xf2c14eff), .scale = 2.0f, .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); + const char *items[2] = {"再開 / Resume", "タイトルへ / Back to title"}; + for (int i = 0; i < 2; ++i) { + bool on = i == selected; + g.ui.draw(b, on ? (std::string("> ") + items[i] + " <").c_str() : items[i], {640.0f, 316.0f + 44.0f * static_cast(i)}, + {.color = on ? hexColor(0xfff4d6ff) : hexColor(0x8c91b4ff), .scale = 2.0f, .align = TextAlign::Centre, + .shadow = hexColor(0x000000ff)}); + } + b.end(); +} + +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(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(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(); +} + +void GameOverScene::drawUi(float /*alpha*/) { + SpriteBatch &b = g.batch; + b.begin(g.screen.matrix()); + g.ui.draw(b, newHigh ? "ゲームオーバー 新記録!" : "ゲームオーバー", {640.0f, 372.0f}, + {.color = hexColor(0xd8dcefff), .scale = 2.0f, .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); + if (time > 1.5f) + g.ui.draw(b, "スペースキーでタイトルへ / Space: back to title", {640.0f, 438.0f}, + {.color = hexColor(0xb8bccaff), .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); + b.end(); +} diff --git a/games/invaders/src/play_scene.cc b/games/invaders/src/play_scene.cc index 2496b19..7a8dc3c 100644 --- a/games/invaders/src/play_scene.cc +++ b/games/invaders/src/play_scene.cc @@ -1,5 +1,7 @@ -// 遊ぶ場面(第28章):自機の弾と宇宙人の弾、AABBの当たり判定、削れる防壁、爆発 -// The play scene (chapter 28): the ship's and the aliens' bullets, AABB collisions, eroding shields, explosions +// 遊ぶ場面(第29章):点数・残機・HUD、波の流れ(準備 → 戦い → 全滅 → 次の波 = 場面の読み直し)、速くなる波、 +// 円盤、画面の揺れと閃光 +// The play scene (chapter 29): score, lives and the HUD, the wave flow (ready → fight → cleared → next wave = a scene +// reload), waves that speed up, the saucer, screen shake and flashes #include "game.hh" #include "engine/collision.hh" @@ -9,32 +11,39 @@ #include #include -// 宇宙人の色(破片の色) / alien colors (for the debris) +// 宇宙人の色(破片の色)と点数 / alien colors (for the debris) and points static const Vec4 kAlienColors[3] = {hexColor(0xf06292ff), hexColor(0x5dbce6ff), hexColor(0x9adc48ff)}; +static const int kAlienPoints[3] = {30, 20, 10}; +static const int kUfoPoints[4] = {50, 100, 150, 300}; constexpr float kFormationWidth = (kColumns - 1) * kColumnSpacing + kAlienSize.x; // 174 constexpr float kShipBoomTime = 1.4f; +constexpr float kReadyTime = 1.6f, kClearedTime = 1.5f; +constexpr Vec4 kHudLabel = {0.55f, 0.57f, 0.75f, 1.0f}; static float formationStartX() { return std::round(0.5f * (kArenaLeft + kArenaRight - kFormationWidth)); } -PlayScene::PlayScene(Game &game) : g(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"); - // 隊列:幅174ピクセル、戦場の真ん中 / the formation: 174 px wide, centered in the arena + // 隊列:波が進むほど低い所から、速く / the formation: lower and faster as the waves go on formation.minX = kArenaLeft + 2.0f; formation.maxX = kArenaRight - 2.0f; - formation.reset(formationStartX(), kFormationTop); + 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) + // 防壁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(i) + 0.5f) / kShieldCount - kShieldW / 2, @@ -46,19 +55,22 @@ PlayScene::PlayScene(Game &game) : g(game) { } playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f); - // 星:自分の種で作るので、場面を作り直しても同じ空 / stars: made with their own seed, so the sky stays the same when - // the scene is created again - Rng sky(1978); - for (int i = 0; i < 40; ++i) - stars.push_back({{std::round(sky.range(kArenaLeft + 2.0f, kArenaRight - 2.0f)), std::round(sky.range(4.0f, 150.0f))}, - sky.unit()}); + ufoTimer = g.rng.range(8.0f, 14.0f); // 最初の円盤は早めに / the first saucer comes early } +void PlayScene::enter() { printf("wave %d: score %d, lives %d\n", g.run.wave, g.run.score, g.run.lives); } + // 一時停止の間は補間しない(第26章) / no interpolation while paused (chapter 26) void PlayScene::pause() { playerPrevX = playerX; if (shot) shot->prevY = shot->box.y; for (Bullet &b : alienShots) b.prevY = b.box.y; + ufo.prevX = ufo.x; +} + +void PlayScene::setPhase(Phase p) { + phase = p; + phaseTime = 0.0f; } int PlayScene::alienFrame(const Alien &a) const { @@ -71,34 +83,53 @@ Rect PlayScene::shipBox() const { return {playerX + 1.0f, kPlayerY + 1.0f, 13.0f void PlayScene::flare(Vec2 centre, Vec4 color, float life) { flares.push_back({splatFrame, centre, life, color}); } +void PlayScene::popup(Vec2 position, const char *text, Vec4 color) { + Popup p{position, 1.0f, {}, color}; + snprintf(p.text, sizeof p.text, "%s", text); + popups.push_back(p); +} + +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); + } +} + void PlayScene::fire() { // 画面に自機の弾がない時だけ撃てる:連打より狙いが大事(元のゲームの決まり) // Only when no ship bullet is on screen: aiming beats mashing (the original's rule) - if (shot || shipDying > 0.0f || gameOver || !g.input.actionPressed("fire")) return; + if (shot || !g.input.actionPressed("fire")) return; float y = kPlayerY - 4.0f; shot = Bullet{.box = {playerX + 7.0f, y, 1.0f, 5.0f}, .prevY = y, .anim = {}}; ++shotsFired; } void PlayScene::killShip() { - --lives; - shipDying = kShipBoomTime; + --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 - printf("ship hit: lives %d\n", lives); + // 磨き:大きく揺らし、赤く光らせる / 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); } void PlayScene::updateShot(float dt) { if (!shot) return; shot->prevY = shot->box.y; shot->box.y -= kShotSpeed * dt; - // 1ステップ4ピクセル、弾の長さ5ピクセル:続けて見れば隙間がないので、すり抜けない(第26章のトンネリング)。 - // 宇宙人の弾とも:近づく速さは1ステップ5.25ピクセル < 5 + 7 - // 4 px per step with a 5 px bullet: consecutive boxes leave no gap, so nothing is skipped (ch26's tunneling). - // Against alien bullets too: they close in at 5.25 px per step < 5 + 7 + // 1ステップ4ピクセル、弾の長さ5ピクセル:続けて見れば隙間がないので、すり抜けない(第26章のトンネリング) + // 4 px per step with a 5 px bullet: consecutive boxes leave no gap, so nothing is skipped (ch26's tunneling) const Rect &box = shot->box; for (size_t i = 0; i < alienShots.size(); ++i) if (overlaps(box, alienShots[i].box)) { @@ -111,10 +142,27 @@ void PlayScene::updateShot(float dt) { if (a.alive && overlaps(box, a.box())) { formation.kill(a); particles.burst(a.box().centre(), 10, kAlienColors[static_cast(a.kind)], 15.0f, 50.0f, g.rng); - ++kills; + addScore(kAlienPoints[static_cast(a.kind)]); shot.reset(); return; } + 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; + } if (std::optional p = shields->hit(box, true)) { shields->erode(*p, g.rng); flare(*p, hexColor(0x68c454ff)); @@ -130,8 +178,8 @@ void PlayScene::updateShot(float dt) { void PlayScene::alienFire(float dt) { fireTimer -= dt; if (fireTimer > 0.0f) return; - fireTimer = g.rng.range(0.5f, 1.1f); - if (static_cast(alienShots.size()) >= kMaxAlienShots) return; + fireTimer = g.rng.range(settings.fireMin, settings.fireMax); + if (static_cast(alienShots.size()) >= settings.maxShots) return; // 撃つ列:3回に1回は自機の真上の列、それ以外は生きている宇宙人をランダムに選んでその列。撃つのはその列の一番下 // The firing column: one time in three the column above the ship, otherwise the column of a random living alien. // The lowest alien of that column shoots @@ -157,9 +205,9 @@ void PlayScene::updateAlienShots(float dt) { for (size_t i = 0; i < alienShots.size();) { Bullet &b = alienShots[i]; b.prevY = b.box.y; - b.box.y += kAlienShotSpeed * dt; + b.box.y += settings.shotSpeed * dt; b.anim.update(dt); - if (shipDying <= 0.0f && overlaps(b.box, shipBox())) { + if (overlaps(b.box, shipBox())) { killShip(); // 全部の弾を消す / clears every bullet return; } @@ -177,12 +225,32 @@ void PlayScene::updateAlienShots(float dt) { } } +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); + } +} + void PlayScene::update(float dt) { if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor) time += dt; + phaseTime += dt; Input &in = g.input; - if (in.pressed(GLFW_KEY_ESCAPE)) { - scenes().pop(); // スタックが空になる → main が終わらせる / the stack becomes empty → main quits + if (in.pressed(GLFW_KEY_ESCAPE) || in.pressed(GLFW_KEY_P)) { + scenes().push(std::make_unique(g)); return; } if (in.pressed(GLFW_KEY_I)) { @@ -192,39 +260,74 @@ void PlayScene::update(float dt) { if (in.pressed(GLFW_KEY_B)) g.showBoxes = !g.showBoxes; if (in.pressed(GLFW_KEY_EQUAL)) formation.rate = std::min(formation.rate * 2.0f, 960.0f); if (in.pressed(GLFW_KEY_MINUS)) formation.rate = std::max(formation.rate * 0.5f, 15.0f); + 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); + } // 飾りはいつでも動く / the dressing always moves particles.update(dt); for (Flare &f : flares) f.life -= dt; std::erase_if(flares, [](const Flare &f) { return f.life <= 0.0f; }); - - if (gameOver) { - formation.updateExplosions(dt); - // やり直し:この場面を新しい場面と入れ替える(全部が最初の状態に戻る) / play again: replace this scene with a - // new one (everything starts from scratch) - if (in.actionPressed("confirm")) scenes().replace(std::make_unique(g)); - return; + for (Popup &p : popups) { + p.position.y -= 8.0f * dt; + p.life -= dt; } - + std::erase_if(popups, [](const Popup &p) { return p.life <= 0.0f; }); + shake.update(dt); + flash.update(dt); + scoreFlash = std::max(0.0f, scoreFlash - dt); + // Playingではformation.updateが爆発も進めるので、此処は其れ以外のフェーズだけ + // in Playing, formation.update advances the explosions itself, so only the other phases do it here + if (phase != Phase::Playing) formation.updateExplosions(dt); + // 補間用の前の位置は、どのフェーズでも毎回ここで。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; - if (shipDying > 0.0f) { + ufo.prevX = ufo.x; + + 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(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); - formation.updateExplosions(dt); updateShot(dt); - shipDying -= dt; - if (shipDying <= 0.0f) { - shipDying = 0.0f; - if (lives > 0) { + if (phaseTime >= kShipBoomTime) { + if (g.run.lives > 0) { playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f); + setPhase(Phase::Playing); } else { - gameOver = true; - printf("game over: %d kills\n", kills); + 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(g, newHigh)); } } return; + case Phase::Over: + return; + case Phase::Playing: + break; } // 自機 / the ship @@ -233,10 +336,11 @@ void PlayScene::update(float dt) { fire(); formation.update(dt); + updateUfo(dt); updateShot(dt); alienFire(dt); updateAlienShots(dt); - if (shipDying > 0.0f) return; + if (phase != Phase::Playing) return; // 撃たれた / the ship was hit // 防壁まで下りてきた宇宙人は防壁を食べる / aliens that reach the shields eat them for (const Alien &a : formation.aliens) @@ -245,88 +349,110 @@ void PlayScene::update(float dt) { // game over whatever lives are left if (formation.alive() > 0 && formation.bounds().bottom() > kPlayerY) { printf("invaded\n"); - lives = 1; + g.run.lives = 1; killShip(); + shake.add(1.0f); return; } - // 全滅させたら次の隊列(第29章で場面ごと読み直す) / when the formation is wiped out, a new one comes (chapter 29 - // reloads the whole scene) if (formation.cleared()) { - ++waves; - printf("wave cleared: %d kills\n", kills); - formation.reset(formationStartX(), kFormationTop); - fireTimer = 1.0f; - } -} - -void PlayScene::drawBackground() { - SpriteBatch &b = g.batch; - // 脇の板と枠 / the side panels and their borders - b.drawRect({0.0f, 0.0f, kArenaLeft, kView.y}, hexColor(0x16132aff)); - b.drawRect({kArenaRight, 0.0f, kView.x - kArenaRight, kView.y}, hexColor(0x16132aff)); - b.drawRect({kArenaLeft - 1.0f, 0.0f, 1.0f, kView.y}, hexColor(0x3a3460ff)); - b.drawRect({kArenaRight, 0.0f, 1.0f, kView.y}, hexColor(0x3a3460ff)); - // 瞬く星 / twinkling stars - for (const Star &s : stars) { - float t = 0.5f + 0.5f * std::sin(2.0f * time + 6.283f * s.phase); - b.drawRect({s.position.x, s.position.y, 1.0f, 1.0f}, {0.62f, 0.64f, 0.8f, 0.25f + 0.5f * t}); + printf("wave %d cleared: score %d\n", g.run.wave, g.run.score); + flash.start({1.0f, 1.0f, 1.0f, 0.5f}); + ufo.active = false; + alienShots.clear(); + setPhase(Phase::Cleared); } - // 地面 / the ground - b.drawRect({kArenaLeft, kGroundY, kArenaRight - kArenaLeft, 1.0f}, hexColor(0x68c454ff)); } void PlayScene::drawFormation() { // 生きている宇宙人と、爆発中の宇宙人(爆発のコマ) / living aliens and exploding ones (explosion frames) + Mat4 camera = g.world.matrix(); if (g.instanced) { std::vector list; for (const Alien &a : formation.aliens) if (a.alive || a.dying > 0.0f) list.push_back({a.position, static_cast(alienFrame(a)), packRgba8(kWhite)}); - g.formationRenderer.draw(g.world.matrix(), list); - formationDrawCalls = g.formationRenderer.lastDrawCalls(); - formationBytes = g.formationRenderer.lastBytes(); + g.formationRenderer.draw(camera, list); + g.formationDrawCalls = g.formationRenderer.lastDrawCalls(); + g.formationBytes = g.formationRenderer.lastBytes(); } else { - g.batch.begin(g.world.matrix()); + g.batch.begin(camera); for (const Alien &a : formation.aliens) if (a.alive || a.dying > 0.0f) g.batch.draw(g.sprites.sprite(alienFrame(a), a.position)); g.batch.end(); - formationDrawCalls = g.batch.stats().drawCalls; - formationBytes = g.batch.stats().sprites * 4 * static_cast(sizeof(SpriteVertex)); + g.formationDrawCalls = g.batch.stats().drawCalls; + g.formationBytes = g.batch.stats().sprites * 4 * static_cast(sizeof(SpriteVertex)); } } void PlayScene::drawBoxes() { - // 当たり判定の箱(B):宇宙人 = 赤、自機 = 緑、弾 = 黄、防壁 = 青(防壁はさらにピクセル単位で調べる) - // The collision boxes (B): aliens red, ship green, bullets yellow, shields blue (shields are then tested per pixel) + // 当たり判定の箱(B):宇宙人 = 赤、自機 = 緑、弾 = 黄、防壁と円盤 = 青(防壁はさらにピクセル単位で調べる) + // The collision boxes (B): aliens red, ship green, bullets yellow, shields and saucer blue (shields are then tested + // per pixel) SpriteBatch &b = g.batch; for (const Alien &a : formation.aliens) if (a.alive) b.drawRectOutline(a.box(), hexColor(0xff4040c0)); for (int i = 0; i < kShieldCount; ++i) b.drawRectOutline(shields->bounds(i), hexColor(0x40a0ffc0)); - if (shipDying <= 0.0f && !gameOver) b.drawRectOutline(shipBox(), hexColor(0x40ff60ff)); + if (ufo.active) b.drawRectOutline(ufo.box(), hexColor(0x40a0ffff)); + if (phase == Phase::Playing) b.drawRectOutline(shipBox(), hexColor(0x40ff60ff)); if (shot) b.drawRectOutline(shot->box, hexColor(0xffe040ff)); for (const Bullet &s : alienShots) b.drawRectOutline(s.box, hexColor(0xffe040ff)); } +// 脇の板のHUD(キャンバスの中、pixel5):左 = 点数・最高点・波、右 = 残機・宇宙人の数・操作 +// The side-panel HUD (inside the canvas, pixel5): left = score, high score, wave; right = lives, aliens left, controls +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(i % 2) * 18.0f, 32.0f + static_cast(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); +} + void PlayScene::draw(float alpha) { if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor) // 防壁:変わった所だけGPUへ(描く前に) / shields: send only the changed part to the GPU (before drawing) shields->upload(); - if (shields->lastUploadBytes() > 0) shieldBytes = shields->lastUploadBytes(); - - // 奥から:背景と防壁(バッチ)→ 隊列(インスタンシングかバッチ)→ 自機・弾・爆発(バッチ) - // Back to front: background and shields (batch) → formation (instanced or batch) → ship, bullets, explosions (batch) - g.batch.begin(g.world.matrix()); - drawBackground(); - shields->draw(g.batch); - g.batch.end(); + if (shields->lastUploadBytes() > 0) g.shieldBytes = shields->lastUploadBytes(); + + // 揺れ:戦場の中身だけをカメラごとずらす(整数のピクセル)。脇の板と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(); - SpriteBatch &b = g.batch; b.begin(g.world.matrix()); float x = std::round(playerPrevX + (playerX - playerPrevX) * alpha); - if (shipDying > 0.0f) b.draw(g.sprites.sprite(shipBoom.frame(), {x, kPlayerY})); - else if (!gameOver) b.draw(g.sprites.sprite(shipFrame, {x, kPlayerY})); + if (phase == Phase::ShipDown) b.draw(g.sprites.sprite(shipBoom.frame(), {x, kPlayerY})); + else if (phase != Phase::Over) b.draw(g.sprites.sprite(shipFrame, {x, kPlayerY})); + if (ufo.active) b.draw(g.sprites.sprite(ufoFrame, {std::round(ufo.prevX + (ufo.x - ufo.prevX) * alpha), kUfoY})); // 弾は滑らかに動くので補間する / bullets move smoothly, so they are interpolated if (shot) b.draw(g.sprites.sprite(shotFrame, {shot->box.x, std::round(shot->prevY + (shot->box.y - shot->prevY) * alpha)})); for (const Bullet &s : alienShots) @@ -337,69 +463,51 @@ void PlayScene::draw(float alpha) { b.draw(s); } particles.draw(b); + for (const Popup &p : popups) { + Vec4 c = p.color; + c.w = std::min(1.0f, 3.0f * p.life); + drawTinyText(g, p.text, {std::round(p.position.x), std::round(p.position.y)}, c, 1.0f, TextAlign::Centre); + } if (g.showBoxes) drawBoxes(); b.end(); + + // 揺れない物:閃光(戦場だけ)、波の見出し、脇の板と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(); } void PlayScene::drawUi(float /*alpha*/) { - if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor) + if (!g.devInfo) return; + // 開発用の数字(Tab):画面の下に一行 / developer numbers (Tab): one line at the bottom + char line[192]; + snprintf(line, sizeof line, + "FPS %.0f formation %s (I): %d draw call(s), %d B/frame march %.0f aliens/s shield upload %d B " + "particles %zu", + static_cast(g.loop.stats().fps), g.instanced ? "instanced" : "SpriteBatch", g.formationDrawCalls, + g.formationBytes, static_cast(formation.rate), g.shieldBytes, particles.size()); SpriteBatch &b = g.batch; b.begin(g.screen.matrix()); - TextStyle head = {.color = hexColor(0xf2c14eff), .shadow = hexColor(0x000000ff)}; - TextStyle body = {.color = hexColor(0xd8dcefff), .shadow = hexColor(0x000000ff)}; - char line[64]; - // 左の板:隊列の描き方と、戦いの数字 / the left panel: how the formation is drawn, and the battle numbers - float y = 24.0f; - auto text = [&](const char *s, const TextStyle &st) { - g.ui.draw(b, s, {14.0f, y}, st); - y += 22.0f; - }; - text("FORMATION (I)", head); - text(g.instanced ? "instanced" : "SpriteBatch", body); - snprintf(line, sizeof line, "%d B/frame", formationBytes); - text(line, body); - snprintf(line, sizeof line, "%.0f aliens/s", static_cast(formation.rate)); - text(line, body); - snprintf(line, sizeof line, "alive %d", formation.alive()); - text(line, body); - y += 16.0f; - text("BATTLE", head); - snprintf(line, sizeof line, "lives %d", lives); - text(line, body); - snprintf(line, sizeof line, "kills %d", kills); - text(line, body); - snprintf(line, sizeof line, "shots %d", shotsFired); - text(line, body); - snprintf(line, sizeof line, "wave %d", waves); - text(line, body); - y += 16.0f; - text("SHIELDS", head); - snprintf(line, sizeof line, "%d px left", shields->pixelsLeft()); - text(line, body); - snprintf(line, sizeof line, "upload %d B", shieldBytes); - text(line, body); - - // 右の板:操作 / the right panel: controls - y = 24.0f; - auto right = [&](const char *s, const TextStyle &st) { - g.ui.draw(b, s, {1102.0f, y}, st); - y += 22.0f; - }; - right("CONTROLS", head); - right("A D / arrows", body); - right(" move", body); - right("Space fire", body); - right("I formation", body); - right("B boxes", body); - right("= - march", body); - right("Esc quit", body); - - if (gameOver) { - b.drawRect({192.0f, 300.0f, 896.0f, 110.0f}, hexColor(0x0c0a1ad0)); - g.ui.draw(b, "GAME OVER", {640.0f, 316.0f}, - {.color = hexColor(0xd9474bff), .scale = 3.0f, .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); - g.ui.draw(b, "Space / Enter: play again", {640.0f, 378.0f}, - {.color = hexColor(0xd8dcefff), .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); - } + b.drawRect({0.0f, 692.0f, 1280.0f, 28.0f}, hexColor(0x0c0a1ae0)); + g.ui.draw(b, line, {640.0f, 697.0f}, + {.color = hexColor(0xd8dcefff), .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); b.end(); } diff --git a/games/invaders/src/title_scene.cc b/games/invaders/src/title_scene.cc new file mode 100644 index 0000000..08576ea --- /dev/null +++ b/games/invaders/src/title_scene.cc @@ -0,0 +1,79 @@ +// タイトル(第29章):ロゴ、点数表(宇宙人が足踏み)、最高得点、横切る円盤。スペースで新しい遊びを始める +// The title (chapter 29): logo, score table (the aliens walk on the spot), high score, a passing saucer. Space starts a +// new game +#include "game.hh" + +#include +#include +#include + +void TitleScene::enter() { printf("title: high score %d\n", g.hiScore); } + +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(g), {.duration = 0.8f}); + } +} + +void TitleScene::draw(float alpha) { + SpriteBatch &b = g.batch; + b.begin(g.world.matrix()); + g.backdrop.drawSky(b, time); + // ロゴ(64 × 11)を2倍で / the logo (64 × 11) at × 2 + Sprite logo = g.sprites.sprite(g.sprites.find("logo"), {160.0f, 20.0f}, {0.5f, 0.0f}, 2.0f); + b.draw(logo); + // 円盤(横切る) / the saucer (passing by) + float ux = std::round(ufoPrevX + (ufoX - ufoPrevX) * alpha); + b.draw(g.sprites.sprite(g.sprites.find("ufo"), {ux, 52.0f})); + + // 点数表:宇宙人は0.5秒ごとに足踏み / the score table: the aliens change pose every 0.5 s + int pose = static_cast(time * 2.0f) % 2; + const char *names[3][2] = {{"jelly_0", "jelly_1"}, {"beetle_0", "beetle_1"}, {"blob_0", "blob_1"}}; + const char *points[3] = {"= 30 POINTS", "= 20 POINTS", "= 10 POINTS"}; + const Vec4 label = hexColor(0xd8dcefff); + b.draw(g.sprites.sprite(g.sprites.find("ufo"), {116.0f, 70.0f})); + drawTinyText(g, "= ? MYSTERY", {140.0f, 71.0f}, hexColor(0xd9474bff)); + for (int k = 0; k < 3; ++k) { + float y = 84.0f + 14.0f * static_cast(k); + b.draw(g.sprites.sprite(g.sprites.find(names[k][pose]), {118.0f, y - 2.0f})); + drawTinyText(g, points[k], {140.0f, y}, label); + } + b.end(); + + b.begin(g.world.matrix()); + g.backdrop.drawPanels(b); + char line[16]; + drawTinyText(g, "HI-SCORE", {6.0f, 40.0f}, {0.55f, 0.57f, 0.75f, 1.0f}); + snprintf(line, sizeof line, "%05d", g.hiScore); + drawTinyText(g, line, {5.0f, 48.0f}, hexColor(0xf2c14eff), 2.0f); + drawTinyText(g, "C CRT", {kArenaRight + 6.0f, 158.0f}, {0.55f, 0.57f, 0.75f, 1.0f}); + drawTinyText(g, "ESC QUIT", {kArenaRight + 6.0f, 166.0f}, {0.55f, 0.57f, 0.75f, 1.0f}); + b.end(); +} + +void TitleScene::drawUi(float /*alpha*/) { + // 画面の解像度の文字(mono16):日本語は短い所だけ / text at screen resolution (mono16): Japanese only where short + SpriteBatch &b = g.batch; + b.begin(g.screen.matrix()); + float blink = 0.55f + 0.45f * std::cos(4.0f * time); + g.ui.draw(b, "スペースキーで開始 / PRESS SPACE", {640.0f, 556.0f}, + {.color = {1.0f, 0.93f, 0.6f, blink}, .scale = 2.0f, .align = TextAlign::Centre, + .shadow = {0.0f, 0.0f, 0.0f, blink}}); + g.ui.draw(b, "A D 左右・Space 撃つ・P 一時停止・Esc 終了", {640.0f, 620.0f}, + {.color = hexColor(0xb8bccaff), .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); + g.ui.draw(b, "A D move / Space fire / P pause / Esc quit", {640.0f, 642.0f}, + {.color = hexColor(0xb8bccaff), .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); + b.end(); +}