29. スペースインベーダー パート3:シーン・スコア・仕上げ
第28章でInvadersは遊べる様になりました。
自機も宇宙人も撃ち、防壁はピクセル単位で削れ、物は爆発し、ゲームは終わります。
でも、まだ試験台です。
起動するといきなり戦場で、脇の板には開発用の数字が並び、全滅させた隊列は其の場で元に戻るだけで、「ゲームオーバー」は1行の文字です。
此の章で、其れを完成したアーケードゲームにします。
タイトル画面、得点・最高得点・残機とHUD、一時停止メニューとゲームオーバー画面、だんだん難しくなる波、ボーナスの円盤、そして1機増える仕組みを足します。
其の後に、ゲームを「動く」だけでなく「気持ち良い」物にする部分が来ます。
画面の揺れ、閃光、そしてシェーダーで描くブラウン管風の仕上げです。
殆ど全部が、第26章の道具の上に乗るゲームのコードです。
新しい描画の技はブラウン管風のパスだけで、PixelCanvasのテクスチャをコピーする代わりに自分のフラグメントシェーダーで描きます。
従って、第17章のポストプロセスへの短い里帰りです。
章全体を通る設計の問いは、もっと単純で、もっと大事です。
どのデータがシーンと一緒に消え、どのデータがシーンより長く生きるのか?
29.1 此の章で作る物
完成したゲームです。
円盤を撃って300点を取った直後:
動画はタイトルから始まり、フェードで第1波に入り、隊列を撃ち、自機を1機失い(赤い閃光と揺れ)、円盤を撃って100点を取ります:
操作:
- タイトル:SpaceかEnterで開始、Escで終了
- 遊ぶ:← →かA Dで移動、Space、↑かWで撃つ、PかEscで一時停止
- 一時停止メニュー:↑ ↓かW Sで選び、SpaceかEnterで決定、PかEscで再開
- いつでも:Cでブラウン管風の仕上げのオン・オフ、Tabで開発用の行
- 開発用のキー:Iで隊列の描き方を切り替え、Bで当たり判定の箱、=と−で行進の速さ、Nで次の波へ
第28章からの変更は全部games/invaders/の中です:
src/layout.hh(新規):第27〜28章のgame.hhにあった画面の寸法と、円盤の通り道src/game.hh:WaveSettings、Run、大きくなったGame、そして4つのシーンのクラスTitleScene、PlayScene、PauseScene、GameOverScenesrc/game.cc(新規):waveSettingsとdrawTinyTextsrc/backdrop.hh、src/backdrop.cc(新規):星、地面、脇の板。タイトルと遊ぶシーンで共有src/title_scene.cc(新規):タイトル画面src/play_scene.cc:フェーズ、得点、円盤、浮かぶ点数、揺れと閃光、HUDsrc/menus.cc(新規):一時停止とゲームオーバーの重ねるシーンsrc/effects.hh、src/effects.cc:第28章のパーティクルの隣にShakeとScreenFlashsrc/crt.hh、src/crt.cc、shaders/crt.frag(新規):ブラウン管風の仕上げsrc/main.cc:pixel5フォント、CRTフィルター、背景を読み込み、タイトルから始め、CとTabを扱うREADME.md:全ての操作、点数、ファイル
formation*とshields*は変わりません。
実行ファイルのソースは5つ増えます:
# 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)
CMakeを手で実行し直す必要はありません。
CMakeは第27章から此のファイルを読んでいるので、次のビルドが変更に気付き、自分でCMakeを実行し直します(27.2節)。
どのゲームの章とも同じく、games/invaders/の外は何も変わりません。
エンジンの変更も共有のアセットの変更も無しです。
29.2 シーンの読み直しと、残るデータ
第28章ではPlaySceneが全部を持っていました。
隊列、防壁、弾、そしてlives、kills、wavesの数も。
其れで問題はありませんでした。
シーンを抜ける道は「もう一度遊ぶ」だけで、其れは新しいシーンと入れ替える事であり、新しいゲームは残機3で始まる「べき」だからです。
此の章では波を足します。
全滅させた波も同じ様にしたいのです。
次の波の為に、遊ぶシーンを真新しい物と入れ替えます。
此処で言う「レベルの読み直し」とは此の事で、古い波の物が新しい波に漏れない様にする一番簡単な方法です。
食べかけの防壁も、飛んでいる途中の弾も、円盤も、古いタイマーも残りません。
コンストラクタが波を作り、デストラクタが捨てるので、全てのメンバーを覚えておく「全部リセット」関数は要りません。
でも、今度は入れ替えを越えて残るべきデータがあります。
得点がPlaySceneにあったら、第1波を全滅させた途端に0に戻ってしまいます。
其の為、データをどれだけ長く生きる必要があるかで分けます:
- プログラム全体(
mainとGame):ウィンドウ、入力、ループ、バッチ、フォント、スプライト、背景の星、CRTフィルター、ゲームのRng、開発用の切り替え、そして最高得点。 - 一回の遊び(
Game::run):得点、残機、波の番号、1機増えたかどうか。タイトルでリセットされます。 - 一つの波(
PlayScene):戦場の上の全て。
2つの構造体です:
// 一回の遊び(タイトルで作り直す)。波が変わっても場面をまたいで残る / 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は第26章の「共有データの構造体」の考え方です。
mainが丁度1つ作り、各シーンのコンストラクタは其れを参照で受け取ります。
シーンは参照を持つだけなので、何度壊して作り直してもGameは気付きません。
幾つかの選択には一言ずつ説明が要ります:
hiScoreは0から始まり、プログラムが動いている間だけ覚えています。電源を入れたばかりのゲーム機と同じです。ファイルに保存するのは課題1です。rngはシーンではなくGameにあります。 各波が自分のRng{27}を作ったら、全ての波が宇宙人の弾の同じ並びを繰り返します。プログラム全体で1つの乱数なら、第2波は並びの続きを使うので第1波とは違う遊びになり、其れでも遊び全体は最初から完全に再現出来ます(スクリーンショットは其れに頼っています)。- 背景は自分の種を持ち(コンストラクタの中の
Rng sky(1978))、mainで一度だけ作られるので、シーンが何度変わっても星は同じ場所に居ます。 - 波括弧付きの
Run run{};。 初期化子が無いと、mainのGame game{.window = window, …}でGCC(-Wextra)とClang(-Wmissing-field-initializers)が「Game::runの初期化子が無い」と警告します。指示付き初期化子のリストが、自分の既定の初期化子を持たないメンバーを飛ばすと出る警告です。run{}で既定の初期化子を与えれば、黙って省けます。
あたしの決まりはこうです。
データは、十分に長く生きる中で一番短命な持ち主に置く。
そうすれば、シーンの切り替えは自分で後片付けをし、本当に持ち越す少しの物だけが一か所に見えます。
29.3 シーンの流れ
全てのシーンと、其の引き継ぎ方です:
シーンの間の矢印は全部、第26章のSceneManagerへの頼み事です。
replaceは一番上のシーンを入れ替え、pushは上に重ねるシーンを載せ、popは其れを外し、replaceAllはスタックを空にしてやり直します。
どれも予約されて更新の後に適用され、Transition付きならフェードアウトを待つので、シーンが自分のupdateの中で壊される事は決してありません。
mainはタイトルでスタックを始めます:
SceneManager scenes;
scenes.push(std::make_unique<TitleScene>(game));
そして、遊びが始まるのはタイトルです:
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{}が「新しい遊び」の処理の全てです。
得点0、残機3、第1波、まだ1機増えていない。
PlaySceneは此処、タイトルの更新の中で作られますが、スタックに載るのは0.4秒のフェードアウトの後です。
其れで構いません。
コンストラクタが読むのは、たった今リセットしたg.run.waveだからです。
ufoPrevX = ufoXは第26章の課題5の直しです。
0.4秒のフェードアウトの間は誰も更新されませんが、描画は続きます。
毎フレーム変わるアルファで円盤の前の位置と今の位置の間を補間し続けると、止まった円盤が行ったり来たりします。
エンジンは既に其れを防いでいます。
フェードアウトの間、SceneManager::drawAlphaが全てのシーンにalpha = 1を渡すからです(第26章)。
前の位置を今の位置に揃えておけば、タイトル自身もじっとしているので、マネージャーの其の細かい所に頼らずに済みます。
遊ぶシーンの中のフェーズ
一つの波の中で、遊ぶシーンは幾つかのフェーズを通ります。
第28章では其の為にshipDyingとgameOverという2つのフラグがありました。
ReadyとClearedが加わると、フラグは意味の無い組み合わせ(「爆発中で、全滅で、ゲームオーバー?」)に増えていきます。
列挙型なら、動いているフェーズは丁度1つだと言えます:
enum class Phase { Ready, Playing, ShipDown, Cleared, Over };
其のフェーズに居る時間と一緒に:
Game &g;
WaveSettings settings;
Phase phase = Phase::Ready;
float phaseTime = 0.0f;
bool leaving = false; // 次の波を頼んだ / the next wave was requested
setPhaseはフェーズを変えて時計を0に戻すので、時間で終わるフェーズは全部「phaseTimeが自分の長さを過ぎたら」で済みます。
何故シーンを増やさず、一つのシーンの中のフェーズにするのか?
Ready、Playing、ShipDown、Clearedは全部同じ戦場を見せ、戦場は其れらをまたいで状態を保たなければなりません。
自機の爆発は隊列の「中」で起き、「WAVE 1 CLEAR」の見出しは空になった戦場の上に出ます。
別々のシーンにすると戦場をシーンの間で共有しなければなりませんが、戦場を持つ事こそシーンの役目です。
一時停止とゲームオーバーは違います。
戦場を覆って止めるので、其れは重ねるシーンの役目です。
PlayScene::updateはまずキーと、いつでも動く「飾り」(パーティクル、着弾の光、浮かぶ点数、揺れ、閃光、そしてPlaying以外のフェーズでの宇宙人の爆発。Playingではformation.updateが既に進めます)を扱い、其の後でフェーズで分かれます:
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;
}
Playing以外のフェーズは全部早めに戻るので、updateの残り(自機の移動、行進、円盤、弾)は第28章の戦いで、今はPlayingの時だけ動きます。
- Ready(
kReadyTime= 1.6秒):「WAVE n / GET READY」が点滅し、何も動きません。プレイヤーは新しい隊列を見る一瞬を貰えます。 - ShipDown(1.4秒、第28章の自機の爆発):行進と宇宙人の射撃は止まりますが、
updateShotは動き続けるので、自機の最後の弾はまだ何かに当たって点になります。 - Over:ゲームオーバーの重ねるシーンが上にあります。遊ぶシーンはもう更新されませんが、スタックには残り、重ねるシーンの下に描かれます。止まった戦場がゲームオーバー画面の背景です。
最高得点を更新するのもゲームオーバーの時で、最後の得点で一度だけです。
遊んでいる間、HUDはmax(hiScore, score)を見せるので、記録を作っている様子は先に見えています。
流れ全体を一度に見るとこうです。
タイトル(HI-SCORE 00000)、第1波、Nキーで全滅、「WAVE 1 CLEAR」、フェード、第2波、一時停止メニュー、3回の被弾、NEW HIGH SCORE!付きのGAME OVER、そしてタイトルに戻ると最高得点は00010になっています:
29.4 波の読み直し
上のClearedの場合が、レベルの読み直しです。
最後の宇宙人の爆発が終わると(formation.cleared())、シーンは白く光り、円盤と宇宙人の弾を止め、Clearedに移ります。
1.5秒の「WAVE n CLEAR」の後、Game::runの波の番号を上げ、新しいPlaySceneとの入れ替えを1.0秒のフェード付きで頼みます。
0.5秒で暗くなり、切り替わり、0.5秒で戻ります。
leavingのフラグが大事です。
頼んだ後もClearedは動き続けます。
頼み事はすぐには効かないからです。
SceneManager::updateは此の更新の後でフェードアウトを始め、フェードアウトの間は誰も更新されません。
従って実際には2回目の頼み事は起きませんが、其れはマネージャーがたまたま其の順で動くからに過ぎません。
フラグが無いと、duration = 0の切り替え(又はマネージャーの何かの変更)で、条件phaseTime >= kClearedTimeが何回かの更新の間trueのままになり、新しいシーンを幾つも予約し、波の番号を何度も上げてしまいます。
シーンの切り替えは一度だけ頼み、其の「一度だけ」をはっきり書きます。
読み直しのもう半分はコンストラクタで、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
}
波に要る物は全部、g.run.waveと共有のアセットから作られます。
新しい防壁は第28章のShields::createによる新しい88 × 16のテクスチャで、古い物は古いシーンのデストラクタが解放します。
GPUのオブジェクトの後片付けはRAIIがただでやってくれます。
createが失敗した時は、第28章と同じくエラーを書いてウィンドウを閉じます(updateとdrawはif (!shields) return;で始まります)。
小さなテクスチャを波ごとに1枚作る程度は何の負担にもなりません。
もしレベルが何メガバイトも読み込む必要があるなら、読み込んだデータはGameに置き、波ごとの状態だけを作り直します。
又同じ分け方です。
読み直しが唯一の方法ではありません。
第28章は其の場でやっていました。
formation.reset(…)とfireTimer = 1.0fです。
最初はコードが少なくて済みますが、新しいメンバー(円盤、浮かぶ点数、揺れ、閃光、フェーズ)ごとにリセットに1行要り、バグはいつも誰かが忘れた1行です。
第2波が始まってもまだ画面を横切っている円盤や、持ち越された閃光です。
新しいシーンなら、忘れる事自体が出来ません。
其の代わり、シーンはうっかり何かを持ち越す事も出来ないので、持ち越すべき物はわざと外へ出さなければなりません。
其れが29.2節の要点です。
29.5 速くなる波
第27章の行進は、もう自分で速くなります。
隊列は1秒にrate匹を1匹ずつ動かすので、宇宙人が減るほど一匹ずつの順番が早く回ってきます。
第1波の毎秒60匹なら、55匹揃った隊列の一巡は55 / 60 ≈ 0.92秒で、最後の1匹は1秒に60回動きます。
此れが波の中での速さの上がり方です。
其の上に、波ごとに始めから難しくします:
// 波ごとの難しさ(第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)};
}
= 波 − 1(0〜7に制限)とすると、係数はです。
行進の速さに掛け、射撃の間隔を割ります:
| 波 | 一番上の行のy | 行進(匹/秒) | 宇宙人が撃つ間隔(秒) | 宇宙人の弾(px/秒) | 宇宙人の弾の最大数 |
|---|---|---|---|---|---|
| 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以降 | 52 | 123 | 0.24〜0.54 | 127.5 | 5 |
数字の裏の考え:
- 始まる高さは波ごとに行進の1段(6 px)ずつ下がり、最大4段です。6 pxごとに、防壁に届くまでの下降が1回減るので、本当の難しさの一段になります。アーケード版も同じでした。52より低く始めると、一番下の行(52 + 4 × 14 + 10 = 118)が136にある防壁に近過ぎます。
- 第8波で頭打ち。 無いとゲームは難しいのではなく不可能になります。あれば上手なプレイヤーは続けられ、得点に意味が残ります。
settingsが第28章の定数kAlienShotSpeedとkMaxAlienShotsの代わりです。戦いのコードはsettings.shotSpeed、settings.maxShots、射撃の間隔をsettingsから読み、其れ以外は変わりません。maxShotsはboolが0か1になる事を使います。3 + (w >= 2) + (w >= 5)は3、第3波から4、第6波から5です。
後の波では隊列の一番下の行がy 104の「WAVE n」の見出しに届きます(第3波で触れ始め、上の第5波ではしっかり後ろにあります)。
其の為、Readyのフェーズは文字の後ろに暗い半透明の帯を描きます。
開発用のNキーは点を入れずに全ての宇宙人を倒すので、Clearedを経て次の波へ行きます。
上の第5波の絵は、4つの波を遊ばずに此れで作りました。
29.6 得点、円盤、1機増える仕組み
点数はアーケード版と同じく宇宙人の種類ごとです:
| 的 | 点 |
|---|---|
| クラゲ(一番上の行) | 30 |
| 甲虫(2〜3行目) | 20 |
| 丸い奴(4〜5行目) | 10 |
| 円盤 | 50、100、150、又は300 |
一つの波を全部倒すと11 × 30 + 22 × 20 + 22 × 10 = 330 + 440 + 220 = 990点です。
得点の変化は全部1つの関数を通ります:
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);
}
}
関数が1つなら、副作用の場所も1つです。
HUDの数字が0.15秒光り、1機増えるかを調べます。
1機増えるのは一度だけ、1500点(kExtraLifeScore)で、大体1波半です。
緑の「1UP」が自機の上に浮かびます。
extraLifeは得点と同じ理由でシーンではなくRunにあります。
シーンのメンバーだったら、新しい波のたびに「もう貰った」事を忘れ、第3波の最初の1匹でまた1機貰えてしまいます。
円盤
円盤(「ミステリーシップ」)は時々戦場の上を横切ります:
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);
}
}
- 最初の1機は波が始まって8〜14秒で(コンストラクタから)、其の後は前の円盤が去るか撃たれてから18〜28秒で来ます。
- 宇宙人が8匹以上生きている間だけです。其れより少ないとタイマーは0より下へ進み続け、円盤は次の波まで待ちます。波の終わりは隊列との戦いのままです。
- 戦場のすぐ外(左からならx = 30、右からなら272)、y 14の通り道(
layout.hhのkUfoY)から出て、40 px/秒で動き、横切るのに約6秒です。戦場の外から出しても大丈夫なのは、脇の板が後から戦場の上に描かれて隠すからです(29.9節)。 - 当たり判定の箱は16 × 6で、第28章の自機の箱と同じく、18 × 8のスプライトから輪郭を除いた物です。
updateUfoは前の位置を自分では保存しません。
其れはPlayScene::updateの最初で、どのフェーズでも、自機の前の位置と一緒に行います:
// 補間用の前の位置は、どのフェーズでも毎回ここで。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;
自機が爆発している間(ShipDown)、行進も円盤も止まり、updateUfoは呼ばれません。
もしupdateUfoがprevXを更新していたら、横切る途中で止まった円盤は最後に動いた時のprevX(xの2/3 px後ろ)を1.4秒間ずっと持ち続け、変わるアルファで其の2つの間に描かれます。
第26章の震えが、一時停止していないのに止まっている物で又起きるのです。
自機の弾は宇宙人の後、防壁の前に円盤を調べます:
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)は第26章の偏りの無い整数の範囲で両端を含むので、{50, 100, 150, 300}の4つは其々1/4の確率で、円盤は平均150点です。
アーケード版は違いました。
点数は撃った弾の数で引く決まった表から来たので、慣れたプレイヤーは弾を数え、300点になる様に円盤を狙いました。
PlaySceneはもうshotsFiredを数えています。
表を作るのは課題4です。
点数は浮かぶ点数(ポップアップ)として浮かびます。
pixel5の短い文字列で、1秒間8 px/秒で上へ動き、最後の3分の1で消えていきます(alpha = min(1, 3 × life))。
「1UP」も同じ構造体を使います。
29.7 脇の板のHUD
第27章は320 × 180のキャンバスを224 pxの戦場と、両側の48 pxの脇の板に分けました。
第28章は其処を開発用の数字で埋めましたが、今度はHUDが入ります。
左にSCORE、HI-SCORE、WAVE、右に控えの自機付きのLIVES、ALIENS、キーの案内です。
HUDはmono16で画面の解像度に描くのではなく、キャンバスの中に3 × 5のpixel5フォントで描きます。
理由は3つです:
- ピクセルアートの一部だからです。同じピクセルの格子、同じ4倍の拡大で、ブラウン管風の仕上げも他の全てと同じ様に走査線を入れます。
- 揺れる戦場の後に、揺れないカメラで描くので、揺れが戦場から押し出した分を脇の板が覆います(29.9節)。
- アーケードのHUDは大きくてゴツゴツした数字です。
pixel5を2倍にすると6 × 10 pxの数字が8 pxの送りで並び、5桁で送り40 px、48 pxの板に少し余裕を残して収まります。
HUDの文字は全部1つの補助関数を通ります:
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は影をposition + shadowOffset × scaleに描きます。
アンチエイリアスのUIの文字には其れが正しい(大きな文字には大きな影)のですが、ピクセルアートではどの倍率でも1 pxの影が欲しいのです。
既定のずれ(1, 1)のままだと、3倍の「GAME OVER」の各文字の下に3 pxの暗い影が出ました。
1 / scaleを渡すと掛け算が打ち消されます。
影の色はスプライトの共通の輪郭の色(27, 23, 38)なので、文字はスプライトと同じ様に板に馴染みます。
pixel5はmainでTextureFilter::Nearestで読み込み、整数の倍率と整数のピクセル位置でしか描きません。
第25章のピクセルアートの決まりです。
HUD本体:
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);
}
- ラベルは1倍で落ち着いた青、数字は2倍。得点はアーケード風にいつも5桁(
%05d)なので、増えても数字の位置が動きません。 - 数字が光ります。
addScoreが走るたびに0.15秒黄色くなります。小さな事ですが、変わった瞬間に目が得点へ行き、其れが「当たりが数えられた」と教えてくれます。 - HI-SCOREの行は、覚えている最高得点と今の得点の大きい方を見せるので、抜いた後は自分と一緒に上がっていきます。
- 控えの自機は遊んでいない自機で、
lives − 1、最大4つのアイコンを2列で。 - HUDは毎フレーム
Game::runと隊列から描かれます。自分の状態を持たないので、合わせておく物がありません。
画面の解像度の文字(mono16、drawUiで描く)は日英2言語の行だけに使います。
タイトルの「スペースキーで開始 / PRESS SPACE」、一時停止メニュー、「ゲームオーバー 新記録!」、「スペースキーでタイトルへ」です。
第26章の決まりです。
短いUIの文字列は2言語、HUDの数字とラベルは英語。
mono16には第26章の部分集合の252のUIの漢字しか無いので、書く前に全ての文字列をmono16.fntと照らし合わせました。
移動、波、矢印の← →はアトラスに無いのです。
其の為、タイトルの案内は「A D 左右・Space 撃つ・P 一時停止・Esc 終了」で、波の見出しは英語だけです。
エンジンの「フォントに無い文字」の警告は安全網ですが、要らないに越した事はありません。
完成したゲームのどの実行でも、一度も出ません。
29.8 タイトル、一時停止、ゲームオーバー
タイトル
タイトルは遊ぶシーンと同じ背景、2倍のロゴ(アトラスでは64 × 11)、30 px/秒で横切って戦場の外で一周する円盤、そして点数表を描きます。
点数表の宇宙人は0.5秒ごとにポーズを変え(static_cast<int>(time * 2.0f) % 2)、其の場で足踏みしている様に見えます。
案内はで脈打ち、alphaは0.1から1.0の間です。
全部第26章の材料(スプライト、Font::draw、円盤の補間)なので、コードは追いません。
title_scene.ccにあります。
Backdropが新しいのはファイルとしてだけです。
第28章のPlayScene::drawBackgroundが、両方のシーンが使うクラスに移りました。
そしてdrawSky(星と地面、戦場の中)とdrawPanels(脇の板と其の枠)に分かれています。
此の分け方のお陰で、遊ぶシーンは脇の板を戦場の「後で」描けます。
29.9節で其れが要ります。
一時停止メニュー
PauseSceneは重ねるシーン(isOverlay()がtrue)なので、下の遊ぶシーンは描かれますが、もう更新されません:
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});
}
}
項目が2つなので、「上」も「下」も選択を入れ替えるだけです。
再開はpopです。
遊ぶシーンはresume()を受け、止まった所から其のまま続きます。
誰も触っていないからです。
タイトルへはreplaceAllです。
一時停止のシーンも遊ぶシーンも、其の波ごと壊され、タイトルが新しく始まります。
此の抜け方をすると其の遊びは捨てられます。
最高得点はゲームオーバーの時にしか更新されないので、途中でやめた得点は数えられません(アーケード版にも終了ボタンはありませんでした)。
PlayScene::pause()は第26章の説明通り、全ての「前の」位置を今の位置にするので、止まった戦場が補間のalphaで揺れません。
一時停止のシーンのdrawはキャンバスの中で戦場を暗くし(0.25秒かけて)、drawUiは画面の解像度で600 × 210のパネルを描き、「一時停止 / PAUSED」と2つの項目を載せます。
パネルがあるのは、動く隊列の上のメニューの文字が読めなかったからです。
最初の版は、2倍の「> タイトルへ / Back to title <」より狭くもありました。
ゲームオーバー
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();
}
- 1.5秒の待ち。 Spaceは「撃つ」でもあり「決定」でもあります。最後の自機がやられた時にSpaceを連打していたプレイヤーは、ゲームオーバー画面を見ないまま飛ばしてしまいます(第28章には正に其の問題がありました)。案内は待ちが終わってから出るので、画面が「今聞いています」と教えてくれます。
- 打たれる文字:0.09秒ごとに1文字ずつ増え、「GAME OVER」の9文字全部が0.81秒で揃います。文字列は0で埋めたバッファに
memcpyで切り取ります。 - 位置は全部の文字から。 途中の文字列に
TextAlign::Centreを使うと、1文字増えるたびに文字が左へずれます。代わりにx位置を文字列全体の幅9 × 4 × 3 = 108 pxから決めるので、160 − 54 = 106から始まり、文字は其の場所に現れます。 - NEW HIGH SCORE!は、
PlaySceneが新記録と知らせた時だけ点滅します(0.35秒点いて0.15秒消える)。重ねるシーンは自分で得点を比べず、コンストラクタで貰った事を見せるだけです。
待ちの後、SpaceでreplaceAllと1.0秒のフェードでタイトルへ行き、タイトルは新しい最高得点を見せます。
29.9 画面の揺れ
ゲームの手応え(「ジュース」)とは、操作に重さを感じさせる小さな効果の集まりです。
代表は画面の揺れで、あたしが使うのはSquirrel EiserlohのGDCの講演「Juicing Your Cameras With Math」の方法、トラウマです。
// 画面の揺れ(第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))};
}
出来事がトラウマを足し(最大1)、トラウマは1秒に1.6ずつ真っ直ぐ減ります。
ずれはトラウマに比例するのではなく、其の2乗に比例します:
xとyは別々に、更新ごとに新しい乱数で計算します。
2乗にすると大きな出来事は小さな出来事よりずっと大きくなり(トラウマ1はトラウマ0.5の4倍揺れる)、揺れの終わりが急に止まらず柔らかく消えます。
出来事:
- 自機の被弾:+0.75、赤い閃光と一緒に。
- 侵略:被弾の0.75の上に+1.0なので、1.0で頭打ち。ゲームで一番大きな揺れです。
- 円盤を撃った:+0.5、白い閃光と一緒に。
整数のピクセル。 ずれは丸めるので、戦場はキャンバスのピクセルの格子の上で動きます。
ピクセルアートの場面を0.3 pxずらしても、何も起きないか(リニアフィルタなら)ぼやけるだけです。
丸めは境目も作ります。
グラフが其れを見せています。
1ピクセル動くには、つまりトラウマが要ります。
自機の被弾(0.75)は(0.75 − 0.408) / 1.6 ≈ 0.21秒其の上にあり、2 pxになり得るのは最初の0.03秒だけです。
侵略(1.0)は(1 − 0.408) / 1.6 ≈ 0.37秒で、最初は3 pxです。
何故0.4ではなく0.5なのか。 円盤には、自機の被弾よりずっと軽い「コツン」が欲しいです。
0から1の目盛りなら、0.4位が丁度良さそうに見えます。
でも0.4は境目の丁度「下」です。
一番大きいずれは3 × 0.4² = 0.48 pxで、いつも0に丸まります。
単独では画面を全く動かさず、既に揺れている所に足されるだけです。
0.5は境目の丁度「上」です。
当たった時は3 × 0.5² = 0.75 pxで、約(0.5 − 0.408) / 1.6 ≈ 0.06秒の間、0.5 pxより上にあります。
ゲームでは其れは当たった後の最初の3回の更新で、各軸は其の乱数が十分大きい時だけ(最初の更新では0.5 / 0.67 ≈ 0.74より上)1 px跳ねます。
其の為1ピクセルの小さな「コツン」で、円盤に当てても3回に1回位は全く動きません。
其の瞬間は、どちらにしても白い閃光と浮かぶ点数が支えています。
此れは、最後に量子化される物(整数のピクセル、整数のステップ、8ビットの色)全てに通じる教訓です。
強さは滑らかな曲線ではなく、境目に合わせて決めます。
境目の下では、効果は小さいのではなく、無いのです。
自分のRng。 揺れは揺れていてもいなくても、更新ごとに乱数を2つ引きます。
Game::rngを使っていたら、揺れを切る(又は更新の頻度を変える)と、其の後の宇宙人の弾も円盤の点数も全部変わってしまいます。
見た目だけの変更がゲームを変えるのです。
Shakeの中のRng rng{29}なら、揺れがあっても無くてもゲームの乱数の並びは同じです。
揺れはフレームごとではなく固定ステップで更新されるので、他と同じく決定的です。
スクリーンショットも動画も正確に再現出来ます。
ShakeはPlaySceneのメンバーなので、揺れは其の波と一緒に消えます。
新しい波が古い波の揺れの途中から始まる事はありません。
戦場だけを揺らす
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();
揺れが動かすのは物ではなくカメラです。
カメラのcentreを−offset動かすと、其のカメラで描く全てが+offset動きます。
空、防壁、隊列(インスタンシングの描画も同じg.world.matrix()を読みます)、自機、弾、パーティクル、浮かぶ点数が一緒にずれ、どのゲームの物にも「此処に描いたけど本当は彼処」という位置は生まれません。
当たり判定はカメラを見ないので影響を受けません。
そして揺れない部分:
// 揺れない物:閃光(戦場だけ)、波の見出し、脇の板と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();
}
まずカメラを戻します。
g.worldは共有です。
一時停止とゲームオーバーの重ねるシーンも此の関数が戻った後に其れで描き、次のフレームもです。
コピー(steady)を取り、共有のカメラを変え、コピーを戻すのが、カメラを「借りる」一番簡単な方法です。
其の後は描く順番が切り抜きをします。
3 pxの揺れは、戦場を片側で最大3 px脇の板の方へ押し出し、反対側に帯を空けます。
drawPanelsは2枚の48 pxの板と1 pxの枠を、揺れた戦場の「後で」不透明に塗るので、はみ出した分は其の下に消えます。
空いた帯にはキャンバスのクリアの色(0x0c0a1a)が見えますが、其れは元々戦場の背景(空は其の色の上の星だけ)なので、分かるのは地面の線だけです。
下の侵略の絵の様に、地面の線が枠の数ピクセル手前で途切れます。
上と下では戦場がキャンバスの端まであるので、外へ出た分は単にキャンバスの外です。
シザーテストもステンシルも要りません。
画家のアルゴリズムで、脇の板が窓枠の役をします。
其の後で揺れない板の上にHUDを描くので、数字は決して揺れません。
此れは大事です。
当たった瞬間に読むのは得点だからです。
29.10 閃光
2つ目の効果は閃光です。
戦場に半透明の四角をかぶせ、すぐに消します:
// 閃光:色の四角を一瞬かぶせ、すぐに消す / 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
};
alphaは1秒に3ずつ下がるので、閃光の長さは最初のalphaを3で割った物です:
| 出来事 | 色(RGBA) | 長さ |
|---|---|---|
| 自機の被弾 | (1, 0.25, 0.2, 0.45) 赤 | 0.15秒 |
| 円盤に当てた | (1, 1, 1, 0.35) 白 | 0.12秒 |
| 波を全滅 | (1, 1, 1, 0.5) 白 | 0.17秒 |
新しい閃光は古い物に足されず、入れ替わります。
閃光は短いので、重なって困る事はありません。
閃光は揺れないカメラで戦場(xが48から272)の上だけに、脇の板の前に描くので、HUDは決して光らず読めるままです。
自機の被弾は全部を組み合わせます:
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);
}
閃光と揺れが最初の0.15〜0.2秒、爆発のクリップとパーティクルが其の後を続け、ShipDownの1.4秒で、自機が戻る前に何が起きたかを理解する時間が出来ます。
一言注意です。
画面全体の閃光は、光過敏のプレイヤーには問題になる事があります。
此処の閃光は短く、部分的(alphaは最大0.5)で、戦場だけに限られ、立て続けには繰り返しませんが、本物のゲームなら其れでも切る設定を用意すべきです。
29.11 ブラウン管風の仕上げ
アーケードのInvadersはブラウン管で動いていて、ピクセルアートは其の上では違って見えます。
ピクセルの行の間に暗い隙間があり、色にかすかな構造があり、明るい物は少しにじみます。
其の一部をシェーダーで真似出来ます。
此れまでPixelCanvas::presentは、glBlitNamedFramebufferとGL_NEARESTでキャンバスをウィンドウにコピーしていました。
正確な4倍の拡大です。
ブリットは拡大縮小しか出来ません。
途中でピクセルを変えるには、キャンバスのテクスチャをフラグメントシェーダーで「描く」必要があります。
正に第17章のポストプロセスが、画面全体の三角形でやった事です。
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;
};
エンジンの部品を2つ使い回します。
第17章のFullscreenTriangle(三角形1つ、頂点バッファ無し)と、其の頂点シェーダーengine/shaders/post.vertで、此れはvUvをビューポート全体で0から1にします。
ゲーム自身の物はフラグメントシェーダーだけです。
作る関数はエンジンのやり方(例外無し、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;
}
そしてpresentが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;
}
順番に:
PixelCanvas::presentと同じレターボックスです。letterbox(…, true)は一番大きな整数の倍率(1280 × 720なら4)を選び、1280 × 720の絵を真ん中に置きます。CでCRTを切り替えても何も動いてはいけないので、どちらの道も同じ関数を使います。- 既定のフレームバッファをバインドし、黒(帯)でクリアし、
v.apply()でglViewportをレターボックスに合わせます。此れで画面全体の三角形は丁度キャンバスの場所を覆い、vUvは其の上で0〜1になります。 - ブレンド無し、深度テスト無し。 絵は不透明で、其処にある物を置き換えます。
SpriteBatch::endはブレンドを有効のまま残します(第25章)。alphaが1なら乗算済みのブレンドでも同じ結果ですが、切っておけば意図がはっきりし、描き先の読み込みも省けます。UIのパスで次のSpriteBatch::beginが又有効にします。 - 形の情報の3つのユニフォーム:キャンバスの大きさ(320, 180)、倍率(4)、ウィンドウのピクセルでのビューポートの左下。
Shader::setはglProgramUniform*を使うので、use()の前でも効きます。 - キャンバスの色テクスチャをユニット0に(
PixelCanvasがGL_NEARESTで作った物)、そして三角形を1つ。
反転は要りません。 第25章でフレームバッファのテクスチャをスプライトとして描いた時はflipYが要りました。
スプライトは画像の上がv = 0ですが、フレームバッファの0行目は描いた物の「下」だからです。
post.vertのvUvはgl_FragCoordと同じくビューポートの下で0なので、其のままでテクスチャと上下が合います。
mainでは世界のパスが2つの内の1つを選びます:
canvas.begin(hexColor(0x0c0a1aff));
scenes.draw(alpha);
if (game.crt) crt->present(canvas, window.width(), window.height());
else canvas.present(window.width(), window.height());
UIのパス(drawUi、其れからフェード)は其の後で画面の解像度で描くので、日英のmono16の文字はくっきりしたままです。
ブラウン管風になるのはピクセルアートのキャンバスだけです。
シェーダー
crt.fragの全体です:
#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);
}
シェーダーは画面のピクセルごと、1280 × 720回動きますが、テクスチャには320 × 180のテクセルしかありません。
GL_NEARESTと整数の倍率なら、キャンバスの1ピクセルは丁度画面の4 × 4のピクセルの塊を覆い、16個全部が同じテクセルを読みます。
効果は、今の画面のピクセルが「其の塊の中のどこにあるか」を知る事から生まれます:
にじみ。 textureをもう4回、キャンバスの1テクセル右・左・上・下(UVの単位でtexel = 1 / 320と1 / 180)で呼び、其々の6 %を足します。
暗い空の隣の明るいスプライトは、隣のピクセルに自分の色を少し分けます。
ブラウン管のビームが広がる様な、柔らかい光の輪です。
平らな所では隣が全部真ん中と同じなので、clampの前に1.24倍明るくなります。
背景は十分暗いので問題にならず、走査線が其の一部を取り戻します。
塊の中のどこか。 gl_FragCoord.xyはピクセルの中心のウィンドウでの位置で、x.5です(GLSL第2章を見て下さい)。
ビューポートの角uOriginを引いてfloorすると、キャンバスの左下から数えた整数の画面のピクセルになります。
倍率でmodする(GLSL第7章のfloorとmodの形)と0、1、2、3の何れかになり、4 × 4の塊の中の位置が分かります。
キャンバスがウィンドウの角に無くなるとuOriginが効いてきます。
1280 × 730のウィンドウではレターボックスがy = 5から始まり、引き算が無いと、暗い線はキャンバスの各行の一番下ではなく一番上の行に来てしまいます。
走査線。 gl_FragCoordは下から数えるので、inside.y == 0はキャンバスの各行の4つの画面の行の一番下です。
其の行は0.62倍、他の3行は1.06倍です。
4行の平均は(0.62 + 3 × 1.06) / 4 = 3.8 / 4 = 0.95なので、絵は明るさの95 %を保ちながら目に見える線の構造を得ます。
1行を0.62、他を1.0にしただけだと9.5 %暗くなります。
== 0.0ではなく< 0.5で比べるのは、浮動小数点のいつもの用心です。
蛍光体の縞。 カラーのブラウン管の画面は、赤・緑・青の蛍光体で出来ています。
縞は其れを画面の列ごとに、3列ごとに繰り返して真似します。
1つのチャンネルが1.06倍、他の2つが0.97倍です。
3列で見ると各チャンネルの平均は(1.06 + 0.97 + 0.97) / 3 = 1.0なので色はずれず、近くで見ると細い縞が見えるだけです。
周期(3)が倍率(4)と合わないのはわざとです。
本物のブラウン管の縞は、信号のピクセルとは何の関係もありません。
此処でgl_FragCoord.xをuOriginからの相対にしないのは、縞は絵ではなく「ガラス」の物だからです。
周辺減光。 として、係数はです。
真ん中で1、左右の端の真ん中で1 − 0.35 × 0.25 ≈ 0.91、四隅で1 − 0.35 × 0.5 ≈ 0.83です。
vUvは16 : 9の縦横比を直していないので、暗くなり方は画面の形に沿った楕円になります。
全部を掛け合わせ、clampし、alpha 1で書き出します。
sRGBの値。 キャンバスはsRGBで符号化した色を持ち、GL_FRAMEBUFFER_SRGBはオフ(第25章の2Dの色の決まり)なので、シェーダーは符号化された値を掛け算します。
物理的には光は線型の空間で混ぜるべきで(第21章)、符号化された値に0.62を掛けると、光としては0.62より暗くなります。
どの道目で合わせる見た目なので、問題になりません。
数字は結果を見ながら、アートを塗ったのと同じ空間で選んだ物です。
負担は921 600ピクセルにテクスチャの読み込み5回と掛け算が少しで、どのGPUでも何でもありません。
テスト環境のソフトウェアラスタライザでさえ、スプライトの横では気付かない程です。
スクリーンショットと動画には一つ注意があります。
走査線はウィンドウの解像度の模様です。
1280 → 960にニアレストネイバーで縮めると、画面の4行の内3行が不揃いに残り、走査線は不規則なモアレになります。
其の為、此の章のスクリーンショットは平均を取るフィルタ(LANCZOS)で、動画はエリアのフィルタで縮めていて、上の比較は2倍の切り抜きです。
29.12 開発用のキー
2つのキーはどのシーンでも効くので、シーンの更新の前にmainで扱います:
[&](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();
},
フラグはGameにあるので、遊んでいる間にCRTを切ればタイトルでも切れたままです。
Tabは遊ぶシーンのUIのパスの下に1行出します。
FPS、隊列の描き方と其の描画呼び出しの数とフレームごとのバイト数(第27章)、行進の速さ、最後の防壁のアップロードのバイト数(第28章)、パーティクルの数です。
脇の板が見せていた数字で、板はもうプレイヤーの物になり、数字はキー1つ先にあります。
Nは次の波へ送ります:
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);
}
全ての宇宙人を普通のkillで倒し(なので爆発します)、addScoreは呼ばず、残りは普段のClearedの処理がやります。
ゲームと同じ道を通る開発用のキーは、最後の状態に飛ぶキーより価値があります。
使うたびに本物の道を試すからです。
I、B、= / −は第27章と第28章から其のままです。
29.13 動かす
プロジェクトのルートから:
cmake --build build -j8
./build/games/invaders/invaders
Visual Studioではinvadersをスタートアッププロジェクトにします(build\games\invaders\Debug\invaders.exe)。
作業ディレクトリはもうプロジェクトのルートです。
プログラムはOpenGLのバージョンの行の後に進み具合を標準出力に出すので、流れを確かめるのに便利です(此処は円盤を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 プラットフォームごとの注意
- Windows(Visual Studio): 第26章で説明した通り、日本語のUIの文字列には
/utf-8のコンパイルオプションが要ります。無いとMSVCはソースをシステムのコードページで読み、2言語の行は?になります。プロジェクトのCMakeがMSVCに既に渡しているので、何もする必要はありません。 - 全部: CRTの模様はウィンドウのピクセルに固定されています。表示の拡大(Windowsの125 %や150 %、一部のLinuxのデスクトップの小数の拡大)があると、コンポジタがウィンドウを再サンプリングし、走査線がぼやけたり不揃いになったりする事があります。100 %(又は整数の拡大)なら正確です。
- 全部:
CとTabはGLFWのキーコードで、第26章のW A S Dと同じく、米国のキーボードでの位置で名付けられています。
29.15 本物のゲームではどうしているか
- シーンとレベル: Unityはレベルごとにシーンのファイルを読み込み(
SceneManager.LoadScene)、レベルをまたぐデータはDontDestroyOnLoadを付けたオブジェクトか、別の残り続けるシーンに置きます。Godotは今のシーンを入れ替え(change_scene_to_file)、そういうデータはオートロードのシングルトンに置きます。どちらも此の章の分け方です。シーンが持つ物はシーンと一緒に消え、小さな残り続けるオブジェクトが遊びを運びます。 - 最高得点とセーブ: ユーザーのデータのフォルダ(Windowsは
%APPDATA%、LinuxとFreeBSDは$XDG_DATA_HOME又は~/.local/share)に保存し、まず一時ファイルに書いてから名前を変えるので、落ちても書きかけのセーブは残りません。 - 手応え: トラウマ式の揺れ、ヒットストップ(当たった時に数フレームゲームを止める、課題5)、閃光、パーティクル、浮かぶ点数は定番です。エンジンやアセットストアにはカメラの揺れの部品があり、動きを滑らかにする為に白色雑音ではなくパーリンノイズを使う物が多いです。
- CRTのシェーダー: RetroArchの様なエミュレーターには、CRTのシェーダーが一族ごとあり(曲面、ビームの形、ブルーム、本物のブラウン管を真似た縞)、普通は複数パスの連なりです。此の章の物は同じ考えの1パスの最小限です。
29.16 スペースインベーダーの振り返りと、此の先
3つの章で、パート5のエンジンの上に1つの完全なゲームを作りました:
- 第27章:ゲーム自身のフォルダと実行ファイル、生成スクリプトで作るピクセルアートのスプライト、自機、そして一匹ずつ行進する55匹の隊列。インスタンシング(描画呼び出し1回、インスタンスごとの位置とコマ)で描き、
SpriteBatchと比べました。 - 第28章:弾とトンネリングの無いAABBの当たり判定、宇宙人の射撃、ピクセル単位で削れる防壁(CPUの正本と、変わった四角だけの
glTextureSubImage2D)、爆発、残機と侵略。 - 此の章:シーン(タイトル、遊ぶ、一時停止とゲームオーバーの重ねるシーン)、残るデータとシーンと共に消えるデータ、シーンの読み直しとしての波、波ごとの難しさ、得点、円盤と1機増える仕組み、キャンバスの中のHUD、そして仕上げ:揺れ、閃光、光る数字、打たれる文字、CRTのシェーダー。
ゲームのGPU側は小さく済みました。
インスタンシング、テクスチャの部分アップロード、ポストプロセスのシェーダー1つです。
仕事の殆どと、ゲームらしく感じさせる物の殆どは、CPU側の構造でした。
固定ステップ、シーン、持ち主、タイミングです。
2Dのゲームでは其れが普通で、良いエンジンのAPIが報われる理由でもあります。
ゲームが自分でOpenGLの状態に触ったのは、2つの描画の部品の中だけでした。
次はパート6の2つ目のゲーム、2D格闘ゲームです。
第30章は、たくさんのアニメーションのコマで出来たキャラクターと、各キャラクターの状態機械(立ち、歩き、ジャンプ、しゃがみ…)、重力と地面のある2D物理、そして同じキーボードから入力を読む2人のプレイヤーから始めます。
シーンのスタック、フェード、Font、固定ステップは全部其のまま付いて来ますし、此の章の持ち主の問いも付いて来ます。
どのデータが1つのラウンドの物で、どのデータが試合全体の物か、です。
29.17 まとめ
- 寿命で決める持ち主: データは、十分に長く生きる中で一番短命な持ち主に置く。
Game(プログラム全体:最高得点、ゲームのRng、アセット、切り替え)、Game::run(一回の遊び:得点、残機、波、1機増えたか。タイトルでRun{}に戻す)、PlayScene(一つの波:戦場の上の全て)。 - シーンの読み直し: 全滅させた波は
run.waveを上げ、遊ぶシーンを新しい物と入れ替える(1.0秒のフェード)。コンストラクタがGameから波を作り、デストラクタが解放する(RAII)。前の波から次の波へ何も漏れない。切り替えは一度だけ頼む(leaving)。 - シーンの流れ: タイトル →(replace)遊ぶ → 一時停止をpush(popで再開、replaceAllでタイトルへ)又はゲームオーバーをpush(1.5秒後にreplaceAllでタイトルへ)。遊ぶシーンの中では
enum class Phase(Ready 1.6秒、Playing、ShipDown 1.4秒、Cleared 1.5秒、Over)が真偽値のフラグの代わり。 - 難しさ: 第8波までのによる
waveSettings。行進 × f、射撃の間隔 / f、最大24 px低く始まり、宇宙人の弾は速く多く。其の上に、宇宙人が減ると自然に速くなる行進。 - 得点: 宇宙人ごとに30 / 20 / 10(一つの波で990)、円盤は50〜300(乱数、平均150)、1500点で1機増える。全部
addScoreを通り、数字が0.15秒光る。 - HUD: キャンバスの中に
pixel5で(ラベル1倍、数字2倍、shadowOffset = 1 / scaleで1 pxの影)、揺れないカメラで戦場の上に描く。mono16は日英の行だけで、全ての文字列をアトラスと照らし合わせる。 - 揺れ: トラウマ(最大1、1秒に−1.6)、ずれはround(3 · trauma² · r)の整数のピクセル、自分の
Rng{29}、固定ステップで更新。戦場だけのカメラを動かして当て、端は後から描く脇の板で隠す。トラウマ0.408未満では丸めて何も起きない。 - 閃光: 戦場の上の半透明の四角、alphaは1秒に−3(0.12〜0.17秒)。
- CRT: キャンバスのテクスチャをブリットの代わりに
post.vertとcrt.fragで同じ整数のレターボックスに描く。にじみ(4つの隣の+6 %)、ビューポートからの相対のgl_FragCoordによる走査線(4行の一番下 × 0.62、他 × 1.06、平均0.95)、3列のRGBの縞(平均1.0)、周辺減光。反転は要らず、ブレンドはオフ。UIは其の後に元の解像度で描く。
29.18 課題
- ★ 最高得点を保存して下さい。ゲームオーバーで
hiScoreをgames/invaders/highscore.txtに書き、mainでタイトルを始める前にエンジンのreadTextFileで読みます。再起動の後、タイトルは00000ではなく一番良い得点を見せるはずです。ファイルが無い(又は壊れている)なら、前の通り0から始まるはずです。其の後、こういうファイルが本当はどこにあるべきか(%APPDATA%、$XDG_DATA_HOME)、何故ゲームは自分のインストール先のフォルダに書くべきでないかを考えて下さい。 - ★ HUDも揺らして下さい。
PlayScene::drawでg.world = steady;を、揺れない部分(最後のパス)の最初から関数の一番最後へ移します。脇の板とHUDは揺れたカメラで描かれ、カメラは次のフレームの為に元に戻ります。自機が撃たれると、脇の板と其の数字も戦場と一緒に震え、少しの間、板が離れた側のキャンバスの端に、もっと暗いキャンバスのクリアの色が1〜2 pxの帯で見えるはずです。コードが脇の板を揺れないカメラで上から描くのは此の為です。 - ★ 1500点ごとに1機増える様にして下さい。
Runのbool extraLifeをint nextExtraLife = kExtraLifeScoreに替え、1機与えるたびに1500上げます。「1UP」は1500、3000、4500…で出るはずです。何故此のフィールドはRunに残し、PlaySceneに移してはいけないのでしょうか? - ★★ アーケード版の円盤の表:乱数の選択を、
shotsFired % 15で引く15個の表に替えて下さい。添字8に300、他は50、100、150を混ぜます。23発目(そして38発目、53発目…)で円盤に当てるといつも300になるはずで、「saucer hit」の横にshotsFiredを出せば確かめられます。shotsFiredはPlaySceneのメンバーなので波ごとに0から始まります。代わりにRunに置くべきかを決め、其の答えで第2波のどの弾が300になるかが変わる事を見て下さい。 - ★★ ヒットストップ:宇宙人が死んだら、
PlayScene::updateの最初でhitStopのメンバーを数え下ろし、0より大きい間は早めに戻る事で、戦場を更新3回分(0.05秒)止めて下さい(一時停止のキーは効くままに)。倒した手応えが重くなるはずです。行進のタイマーも止まるので、波全体は少し長くかかるはずです(55匹 × 0.05秒 ≈ 2.75秒増える)。 - ★★ 画面を曲げて下さい。
crt.fragのmainの最初でvec2 uv = vUv + (vUv - 0.5) * dot(vUv - 0.5, vUv - 0.5) * 0.1;と座標を歪め、vUvの代わりにuvでサンプリングし、uvが0〜1の外なら黒を書きます。絵は曲面の画面の様に膨らみ、四隅が黒くなるはずです。端をよく見ると、ニアレストのサンプリングで其処のピクセルの幅が少し不揃いになっているのが分かります。第25章の整数倍の決まりを、わざと破った結果です。 - ★★★ 2人交代で遊べる様にして下さい。
Gameに2つのRunとcurrentの添字を持たせ、自機を失うたびに「PLAYER 2」の見出しでプレイヤーを替えます。各プレイヤーは自分の食べかけの隊列と自分の防壁に戻らなければならないので、遊ぶシーンはもう波の番号から作り直すだけでは済みません。入れ替えの前に隊列(位置、生きているか、行進の状態)と防壁のCPUのピクセルをプレイヤーのRunに保存し、コンストラクタで元に戻します。シーンの読み直しが、状態をリセットするだけでなく元に戻す必要が出てきます。上手く行けば、各プレイヤーは丁度やめた所から続けられるはずです。
ファイル: 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)
まだコメントはありません。
ログインするとコメント出来ます。