32. 2D格闘ゲーム パート3:スクロールするステージとAI
第31章で、ハヤテとジンは戦える様になりました。
フレームデータとしての技、攻撃判定と食らい判定、ヒット硬直、ノックバック、ヒットストップ、入力バッファ、体力ゲージ、そして鉢巻の尾や火花の為のシーングラフです。
でも、戦う場所はまだ箱の中です。
画面と丁度同じ幅の道場が一つ、一台のキーボードに人が二人、そして練習モードの終わらない一つのラウンドだけです。
此の章でfighterを完成させます。
戦いは画面より広いステージに移ります。
5枚の視差の層で作った夕暮れの寺の境内で、カメラはファイターを追いかけ、ステージの端で止まります。
CPUの相手も加わります。
人と同じボタンを押す「見えないプレイヤー」として書きます。
そして戦いは試合になります。
60秒の時間制限付きの3本勝負、遊び方と難易度を選ぶタイトル画面、一時停止メニュー、もう一度遊べる勝利画面です。
此の章で新しいOpenGLの関数はありません。
描画の側の考え方は視差だけで、其れは「層ごとにカメラが一つ」という事だと分かります。
残りはゲームの構造で、其の全体を通る問いは、ゲームを締めくくるのに相応しい物です。
CPUは何を知る必要があり、其れを何時知って良いのか?
32.1 此の章で作る物
スクロールしたステージの真ん中で、蹴りがCPUに当たった所です。
時間は55です:
動画はタイトルから始まり、1P 対 CPUを選び、ROUND 1とFIGHT!が出て、台本通りに動く人がNormalのCPUと打ち合い、ガードし合います。
其の間、カメラはスクロールします:
操作:
- タイトル:W Sか↑ ↓で遊び方を選び、A Dか← →で難易度を変え、Space、Enter、F又はKで開始、Escで終了
- 対戦:第31章と同じ(1PはA D W SとFでパンチ・Gでキック、2Pは矢印キーとK・L)、Esc又はPで一時停止、F1でデバッグ表示
- 一時停止:W Sか↑ ↓で選び、Space、Enter、F又はKで決定、Esc又はPで再開
- 勝利画面:Space、Enter、F又はKでもう一度(同じ遊び方と難易度)、Escでタイトルへ
タイトルには遊び方が4つあります。
1P 対 CPU(CPUが2P)、2人で対戦(今迄通り人が二人)、CPU 対 CPU(選んだ難易度のCPU同士の試合を見る)、そして練習(時間もラウンドも無く、KOの3秒後に仕切り直し。第31章の動き)です。
第31章からの変更は全てgames/fighter/の中です:
src/stage.hh、src/stage.cc(新規):視差のステージ、カメラの範囲、舞い散る花びらsrc/ai.hh、src/ai.cc(新規):Difficulty、難易度ごとの数値、AiControllersrc/match.hh(新規):Mode、MatchSettings、試合のルールsrc/hud.hh、src/hud.cc(新規):色とdrawBigText。どのシーンでも使える様に対戦のシーンから移しましたsrc/menu_keys.hh(新規):どちらのプレイヤーのキーでも動くメニューのキーsrc/scenes.hh、src/title_scene.cc、src/pause_scene.cc、src/result_scene.cc(新規):新しい3つのシーンsrc/fight_scene.hh、src/fight_scene.cc:CPUの枠、ラウンド、時間、カメラ、道場の代わりのステージ、新しいHUDsrc/fighter.hh、src/fighter.cc:勝ちポーズの為のWin状態src/game.hh、src/main.cc:Gameにステージと選んだ難易度。プログラムはタイトルから始まりますassets/stage_*.png(新規):5枚の層。assets/LICENSE.txtにも其の行を足しました(完成したファイルは章のZIPとアセットのZIPのch32/に入っています)README.md:遊び方とルール
実行ファイルのソースは6つ増えます:
# 2D格闘ゲーム(第30〜32章):エンジンにリンクする自分の実行ファイル
# The 2D fighting game (chapters 30-32): its own executable linking the engine
add_executable(fighter
src/main.cc
src/ai.cc
src/controls.cc
src/effects.cc
src/fighter.cc
src/fight_scene.cc
src/frame_data.cc
src/hud.cc
src/moves.cc
src/pause_scene.cc
src/result_scene.cc
src/scene_graph.cc
src/stage.cc
src/title_scene.cc)
target_include_directories(fighter PRIVATE src)
target_link_libraries(fighter PRIVATE engine)
enable_warnings(fighter)
set_working_directory(fighter)
ファイルを足したらCMakeをもう一度実行して下さい(Visual StudioはCMakeLists.txtが変わると自分でやります)。
何時ものゲームの章と同じく、games/fighter/の外は何も変わりません。
32.2 画面より広いステージ
キャンバスは今迄通り640 × 360です(1280 × 720のウィンドウに2倍で出す、第30章で決めた事)。
でも、ステージは1024 pxの幅になります。
ステージは奥から手前へ重ねた5枚の画像で描きます:
| 層 | 係数 | 幅 | 中身 | 並べ替えの層 |
|---|---|---|---|---|
stage_sky.png |
0.05 | 659 px | 夕焼けのグラデーション、縞の太陽、雲 | 0.0 |
stage_far.png |
0.25 | 736 px | 2つの山並み | 0.1 |
stage_mid.png |
0.5 | 832 px | 鳥居、五重塔、桜の木、寺の塀 | 0.2 |
stage_ground.png |
1.0 | 1024 px | 石畳。ファイターはy = 320に立つ | 0.3 |
stage_front.png |
1.3 | 1139 px | ファイターより手前の石灯籠と草 | 12 |
5枚とも高さは360 pxで、全部あたしの一つの生成スクリプトから出来ています。
ファイターのスプライトと同じです。
此のスクリプトは手で書いたピクセルの行ではなく、numpyの配列で描きます。
空は手で選んだ夕焼けの色の間の縦のグラデーションで、4 × 4の組織的ディザ(Bayer)で段に分けるので、アンチエイリアス無しのピクセルアートの儘です。
太陽は横縞で欠けた円盤です。
山の稜線はランダムな位相を持つ3つのsin波の和を2 px単位に丸めた物で、手で置いた様な縁になります。
寺の層は鳥居、五重塔、桜の木を長方形、多角形、円で描きます。
地面はランダムな長さと4色の石を並べた石畳の行で、行の高さは奥の8 pxから手前の30 pxまで増えていきます。
安上がりな遠近感の手掛かりです。
乱数は全て固定の種のnumpy.random.RandomStateから来るので、スクリプトをもう一度実行するとバイト単位で同じPNGが出来ます(5枚合わせて18 KBしかありません)。
各層の幅は、すぐ後で導く式でスクリプトが計算します。
スクリプトのプレビューの機能が、下の記事用の画像を描きます。
カメラの両端での画面と、半分の大きさの各層に、左端(シアン)と右端(オレンジ)で見える範囲を付けた物です。
何故遠い物はゆっくり動くのか
電車の窓から外を見て下さい。
線路脇の柵は飛ぶ様に過ぎ、其の後ろの家は滑る様に流れ、地平線の山は殆ど動きません。
此れが視差で、平らな2Dの背景に奥行きを感じさせる物です。
理由は線型代数の第12章の透視投影です。
ピンホールカメラは奥行きの点を画面のに置きます。
は像の面までの距離です。
カメラが横にだけ動くと、カメラから見た全ての点のがだけ変わるので、像は次の分だけ動きます:
2倍遠ければ、動きは半分です。
カメラと丁度同じだけ動く地面の奥行きを基準にすると、奥行きの層はカメラの動きの次の割合だけ動きます:
此の割合が層の視差の係数です。
逆に読むと、表の係数は各層が「何処にあるか」を表しています。
の寺は地面の2倍、山は4倍、空は20倍遠くにあるかの様に振る舞います。
手前の層の1.3は1より大きいので、ファイターより近くにある様に振る舞い()、地面より速く流れます。
どれも本物の3Dではありません。
各層は1枚の平らな画像で、錯覚が働くのは横の動きだけです。
此のゲームに縦の視差が無いのも其の為です。
カメラは上下に動かないので、どの層も上の端はワールドのy = 0にあるだけです。
層ごとにカメラが一つ
コードでは、係数は層ごとの2つ目のカメラになります。
を、ステージの座標での画面の左端(メインカメラの中心から320を引いた物)とします。
地面の層はステージのx = 0に描くので、画面ではだけずれて見えます。
係数の層は、自分のカメラが倍だけ動いたかの様に、だけずれて見えなければなりません。
バッチ全体はメインカメラの行列で描くので、メインカメラの分を打ち消して層のカメラの分を掛けます。
つまり、層の左端はワールドのx に行きます。
ステージの宣言です:
// スクロールする舞台:視差の層(遠いほどゆっくり動く)、カメラの範囲、舞い散る花びら
// The scrolling stage: parallax layers (the farther, the slower), the camera's limits, falling petals
#pragma once
#include "engine/camera2d.hh"
#include "engine/rng.hh"
#include "engine/sprite_batch.hh"
#include "engine/texture.hh"
#include <optional>
#include <vector>
constexpr float kStageWidth = 1024.0f; // 舞台の幅(ワールドのピクセル)。見えるのは640 / the stage width (world pixels);
// 640 are visible
// 一枚の層:factor = カメラに対する動きの割合(0 = 動かない空、1 = 地面と同じ、> 1 = 手前)
// One layer: factor = how much of the camera's motion it follows (0 = a still sky, 1 = with the ground, > 1 = in
// front)
struct ParallaxLayer {
Texture2D texture;
float factor;
float layer; // SpriteSort::Layerの順番 / order for SpriteSort::Layer
};
class Stage {
public:
// games/fighter/assets/stage_*.png を読む / loads games/fighter/assets/stage_*.png
static std::optional<Stage> load();
// カメラの中心のxを舞台の中に収める:画面の端が舞台の外を映さない / clamps the camera center's x so the view never
// shows anything outside the stage
static float clampCamera(float centreX, float viewWidth);
// ファイターの後ろの層(空・山・寺・地面)と、前の層(灯籠・花びら)。cameraはワールドのカメラ
// The layers behind the fighters (sky, mountains, temple, ground) and in front (lanterns, petals). camera is the
// world camera
void drawBack(SpriteBatch &batch, const Camera2D &camera) const;
void drawFront(SpriteBatch &batch, const Camera2D &camera) const;
void update(float dt); // 花びら / the petals
private:
struct Petal {
Vec2 position; // 画面の座標(花びらは手前の層:factor 1.15) / screen-ish coordinates (petals live on a 1.15 layer)
Vec2 velocity;
float phase;
};
void drawLayer(SpriteBatch &batch, const ParallaxLayer &l, const Camera2D &camera) const;
std::vector<ParallaxLayer> back, front;
std::vector<Petal> petals;
Rng rng{32};
float time = 0.0f;
};
描く所では、ずれを整数のピクセルに丸めます:
float Stage::clampCamera(float centreX, float viewWidth) {
float half = viewWidth * 0.5f;
return std::clamp(centreX, half, kStageWidth - half);
}
// 視差:その層のカメラはfactor倍だけ動く。画面の左端が舞台のxなら、層は −x·factor だけずらして描く
// Parallax: a layer's camera moves `factor` times as far. If the view's left edge is at stage x, the layer is drawn
// shifted by −x·factor
void Stage::drawLayer(SpriteBatch &batch, const ParallaxLayer &l, const Camera2D &camera) const {
float left = camera.centre.x - camera.viewSize.x * 0.5f;
Vec2 size = {static_cast<float>(l.texture.width()), static_cast<float>(l.texture.height())};
// ワールドの座標で描く:層の左端 = left − left·factor(整数に丸めてピクセルをそろえる)
// Drawn in world coordinates: the layer's left edge = left − left·factor (rounded to whole pixels)
float x = left - std::round(left * l.factor);
// 縦は動かない(カメラの高さは固定):層の上端はワールドのy = 0 / no vertical parallax (the camera height is fixed):
// a layer's top is at world y = 0
batch.draw({.texture = &l.texture, .position = {x, 0.0f}, .size = size, .layer = l.layer});
}
clampCameraはカメラの範囲で、次の節で使います。
drawLayerが視差の技法の全てです。
層ごとに引き算が一つ、丸めが一つ、スプライトが一つです。
丸めはピクセルアートでは大事です。
メインカメラの中心はもう整数で(すぐ後で見ます)、std::round(left * l.factor)で各層のずれも整数になるので、どの層も自分の速さで、キャンバスの整数ピクセル単位で動きます。
遅い層は、カメラが何ピクセルか動く毎に1ピクセル動きます。
此の小さなカクカクが16ビット時代のゲームの視差の見た目で、テクセルが2つのピクセルの間でサンプリングされる事もありません。
並べ替えの層(全部の後ろに0〜0.3、手前の層に12。ファイターは2と3、火花は6)のお陰で、送る順番に関係無くSpriteSort::Layerが正しい順番に並べます。
各層は何ピクセルの幅が要るか
層が狭過ぎると、カメラがステージの端に着く前に層の端が見えてしまいます。
広過ぎると、決して見えないピクセルが無駄になります。
画面の幅は640 pxで、其の左端は0(左端)から次の値(右端)まで動きます:
の時、層のピクセルは画面のx に見えるので、画面には層のが映ります。
左端では、右端ではです。
層は両方の範囲を含まなければならず、其れを満たす一番小さい画像は丁度2つ目の範囲で終わります:
| 層 | 画像 | 右端でのずれ | 見える右の端 | |||
|---|---|---|---|---|---|---|
| 空 | 0.05 | 19.2 | 659.2 | 659 | 659 − 19 = 640 | |
| 山 | 0.25 | 96 | 736 | 736 | 96 | 736 − 96 = 640 |
| 寺 | 0.5 | 192 | 832 | 832 | 192 | 832 − 192 = 640 |
| 地面 | 1.0 | 384 | 1024 | 1024 | 384 | 1024 − 384 = 640 |
| 手前 | 1.3 | 499.2 | 1139.2 | 1139 | 1139 − 499 = 640 |
丸めが問題になり得るのは、小数の付いた2つの幅です。
生成スクリプトは幅を丸め(659.2 → 659、1139.2 → 1139)、drawLayerはずれを同じ様に丸める(19.2 → 19、499.2 → 499)ので、層の右の端は画面の右の端の640に丁度重なり、1ピクセルの隙間も出来ません。
其の間のでは、ずれはもっと小さいので、画像は何時も画面を覆います。
地面はの特別な場合で、幅はステージの幅です。
「ステージの座標」と「地面のピクセル」が同じ物なのは其の為です。
同じ式はの手前の層にも使えて、単にステージより広くなります。
そして何も繰り返す必要がありません。
繰り返すテクスチャ(GL_REPEATとUVのずらし)も視差の古典的なやり方で、ランゲームの様な端の無いステージには其方が正解です。
格闘ゲームのステージには両端があるので、幅がぴったりの画像の方が簡単で、絵に左側と右側を持たせる事も出来ます。
層を読み込む
Stage::loadは5枚のPNGを読み、花びらを作ります:
std::optional<Stage> Stage::load() {
struct Spec {
const char *file;
float factor, layer;
bool front;
};
// 幅は 640 + factor × (1024 − 640):カメラが端に着いたとき、層もちょうど端 / widths are 640 + factor × (1024 − 640):
// when the camera reaches an edge, so does every layer (the images have these widths)
const Spec specs[] = {
{"stage_sky", 0.05f, 0.0f, false}, {"stage_far", 0.25f, 0.1f, false}, {"stage_mid", 0.5f, 0.2f, false},
{"stage_ground", 1.0f, 0.3f, false}, {"stage_front", 1.3f, 12.0f, true},
};
Stage stage;
for (const Spec &s : specs) {
std::optional<Texture2D> t = loadSpriteTexture(std::string("games/fighter/assets/") + s.file + ".png");
if (!t) return std::nullopt;
(s.front ? stage.front : stage.back).push_back({std::move(*t), s.factor, s.layer});
}
for (int i = 0; i < kPetals; ++i) {
Petal p{{stage.rng.range(0.0f, 760.0f), stage.rng.range(-40.0f, 300.0f)},
{stage.rng.range(-28.0f, -12.0f), stage.rng.range(14.0f, 26.0f)}, stage.rng.range(0.0f, 6.28f)};
stage.petals.push_back(p);
}
return stage;
}
手前の層はファイターの後で描くので、別のリストに入ります。
灯籠はステージの両端の近くにしか立っていないので、ステージの真ん中では層は透明で、少しのフラグメントのブレンドしか掛かりません。
両端では、隅に追い込まれたファイターの前を灯籠が横切ります(下のラウンド勝利のスクリーンショットでは、倒れたジンの頭が灯籠に隠れています)。
ステージを背景画ではなく「場所」と感じさせる安上がりな方法です。
花びら
最後の一手間は、左下へ舞い落ちる28枚の桜の花びらです。
係数1.15の別の「層」で、画像ではなくコードで描きます:
void Stage::drawBack(SpriteBatch &batch, const Camera2D &camera) const {
for (const ParallaxLayer &l : back) drawLayer(batch, l, camera);
}
void Stage::drawFront(SpriteBatch &batch, const Camera2D &camera) const {
float left = camera.centre.x - camera.viewSize.x * 0.5f;
// 花びら:手前の層(factor 1.15)の上を左下へ。画面の外に出たら上から戻る(760幅で輪になる)
// Petals: drift down-left on a 1.15 layer, wrapping round a 760-wide band
for (const Petal &p : petals) {
float x = std::fmod(p.position.x - left * kPetalFactor, 760.0f);
if (x < 0.0f) x += 760.0f;
float sway = 4.0f * std::sin(time * 2.0f + p.phase);
Vec2 at = {left + std::round(x - 60.0f + sway), std::round(p.position.y)};
bool flat = std::sin(time * 5.0f + p.phase) > 0.3f; // くるくる回る:2×2と1×2 / tumbling: 2 × 2 or 1 × 2
batch.drawRect({at.x, at.y, flat ? 2.0f : 1.0f, 2.0f}, hexColor(0xffc8dcff), 11.0f);
}
for (const ParallaxLayer &l : front) drawLayer(batch, l, camera);
}
void Stage::update(float dt) {
time += dt;
for (Petal &p : petals) {
p.position += p.velocity * dt;
if (p.position.y > 370.0f) {
p.position.y = -10.0f;
p.position.x = rng.range(0.0f, 760.0f);
}
}
}
花びらのxは自分のスクロールする空間にあります。
p.position.x - left * kPetalFactorはカメラの1.15倍の速さでスクロールする帯の上での位置で、760でのstd::fmodが其れを輪にするので、左から出た花びらは右から戻ってきます。
帯の幅760 pxは、画面の640に両側の60 pxを足した物(- 60.0f)で、花びらは画面の端で突然現れずに、画面の外で出入りします。
各花びらは2 × 2か1 × 2の長方形で、sinで切り替えて回っている様に見せます。
y = 370より下に落ちた花びらは、Rng{32}の新しいランダムなxで上からやり直します。
花びらは飾りだけです。
対戦の中で花びらを読む物は何もありません。
決定性の話で此れが効いてきます。
32.3 カメラ
真ん中を追う
カメラは二人のファイターの真ん中を追い、画面がステージの外を映さない様に範囲に収めます:
なので、カメラの中心はに留まり、どちらの端でも画面の端は丁度ステージの端です。
描く時、対戦のシーンは補間した位置(第26章のalpha)からワールドのカメラを作るので、スクロールはファイターの動きと同じだけ滑らかで、中心は整数のピクセルに丸めます:
// 画面の端も壁:カメラは二人の真ん中を追い、舞台の中に収まる。二人ともその画面の中にいなければならない
// The view edges are walls too: the camera follows the midpoint, clamped to the stage, and both fighters must stay
// inside that view
void FightScene::keepInView() {
float centre = Stage::clampCamera(0.5f * (fighters[0].position.x + fighters[1].position.x), kViewSize.x);
float left = centre - kViewSize.x * 0.5f + kViewMargin, right = centre + kViewSize.x * 0.5f - kViewMargin;
for (Fighter &f : fighters) clampX(f, std::max(left, kStageLeft), std::min(right, kStageRight));
}
Camera2D FightScene::worldCamera(float alpha) const {
// 描くときは補間した位置の真ん中 / when drawing: the midpoint of the interpolated positions
float a = lerp(fighters[0].previous, fighters[0].position, alpha).x;
float b = lerp(fighters[1].previous, fighters[1].position, alpha).x;
Camera2D c = Camera2D::screen(kViewSize);
c.centre.x = std::round(Stage::clampCamera(0.5f * (a + b), kViewSize.x));
c.pixelSnap = true;
return c;
}
Camera2D::screen(kViewSize)は第25章のワールド = 画面のピクセルのカメラで、centre.xを変えるとスクロールし、pixelSnapが行列を整数のピクセルに保ちます。
追いかけるカメラには、よく平滑化(毎ステップ目標までの一部だけ動く)を付けます。
格闘ゲームには其の余裕が全くありません。
二人のプレイヤーは何時も二人のファイターを見ていなければならないので、カメラは丁度真ん中の所に行きます。
画面の端は壁
上のkeepInViewが、スクロールする格闘ゲームを成り立たせる決まりです。
此れが無いと、ハヤテが左に、ジンが右に歩き続けて900 px離れる事が出来て、二人の真ん中のカメラにはどちらも映りません。
其の為、押し合いの後で、各ファイターはカメラの画面から8 pxの余白を引いた範囲(とステージの両端から12 pxの壁)に収められます:
従って、二人が1画面より離れる事はありません。
立っているファイターの押し合いの箱は足元を中心に38 pxの幅なので、足元は画面の各端から少なくとも px内側にあり、立っている二人は最大で次の距離しか離れられません:
遊んでみると、此の壁は自然に感じます。
立っている相手から後ろに歩くと、画面は自分の半分の速さで付いてきて(真ん中は半分しか動きません)、間が586 pxになると壁に当たった様に止まります。
画面の端は他の意味でも壁です。
第31章では、食らった方がステージの端に追い詰められていると、攻撃した方が押し戻されました。
隅のファイターを永遠に殴り続けられない様にする為です。
此処では、壁はステージの端と画面の端の近い方です:
// 壁(舞台の端か画面の端)を背にした相手には、自分が下がる / against an opponent with their back to a wall (the
// stage end or the view edge) the attacker is pushed back instead
Rect vb = v.pushbox();
float wallLeft = std::max(kStageLeft, viewCentre - kViewSize.x * 0.5f + kViewMargin);
float wallRight = std::min(kStageRight, viewCentre + kViewSize.x * 0.5f - kViewMargin);
if (vb.left() <= wallLeft + 0.5f || vb.right() >= wallRight - 0.5f) push[i] = m.knockback * 0.7f;
viewCentreはkeepInViewと同じ範囲に収めた真ん中で、resolveHitsの最初で一度計算します。
第31章と同じく、此処では押し戻しをpush[i]に入れるだけで、全ての接触の後で当てるので、相打ちで攻撃側が受けたノックバックを消しません。
端での揺れ
第31章では重い攻撃でカメラを揺らし、道場を画面より8 px大きく描いて端を隠していました。
スクロールするステージでは、ステージの端の先に描く物がありません。
其の為、左端での揺れでクリアの色が2 px見えてしまいました(KOのスクリーンショットを作る時に見つかりました)。
直し方は、揺れを横だけにして、揺らした中心も範囲に収める事です:
// 揺れは横だけ、舞台の中で(端で舞台の外が見えないように) / the shake is horizontal only and stays inside the stage
// (so nothing outside the stage shows at the ends)
if (shake > 0) view.centre.x = Stage::clampCamera(view.centre.x + (shake % 2 ? 2.0f : -2.0f), kViewSize.x);
ステージの端では揺れは内側にしか動きませんが、層ごとに動く量が違うので、其れでもちゃんと見えます。
32.4 CPUの相手:見えないプレイヤー
人と同じControls
コンピューターの相手の書き方は2つあります。
一つは、AIにファイターを直接動かさせる方法です。
「プレイヤーが近ければstartMove(Kick)を呼ぶ」という様に。
もう一つは、AIにゲームを遊ばせる方法です。
AIは毎ステップ、readControlsが人の為に作るのと同じControls(左・右・上・下は押している間、パンチ・キックは此のステップで押した)を作り、其れが全く同じコードを通ります。
あたし達は2つ目を使います。
違いは全部、対戦のシーンの入力のループに見えます:
// 入力:人はキーボードとパッド、CPUはAiController。どちらも同じControlsになる / input: humans from the keyboard and
// pads, the CPU from AiController; both become the same Controls
Controls controls[2];
for (int i = 0; i < 2; ++i) {
Controls human = readControls(in, i, pads[i]);
controls[i] = ai[i] ? ai[i]->think(fighters[i], fighters[1 - i]) : human;
if (phase != RoundPhase::Fight) controls[i] = {}; // 始まりと決着の間は動けない / no control before and after
}
for (int i = 0; i < 2; ++i) {
fighters[i].buffer.record(controls[i]);
fighters[i].savePrevious();
}
此の作りの方が良い理由です:
- ルールを破れません。 CPUのキックは人のキックと同じ8フレームの発生、同じ入力バッファの窓、同じ「自由に動ける時だけ」の決まり、同じガードの条件を持ちます。同じコード其の物だからです。
startMoveを直接呼ぶAIは、うっかり自分の硬直中に攻撃出来てしまい、プレイヤーが「CPUがずるい」と文句を言う迄誰も気付きません。 - ファイターは誰が操作しているか知りません。
Fighterには「CPUかどうか」のフラグがありません。ファイターに足した機能(新しい技、新しい状態)は、触らなくてもCPUで動き、人の為に直したバグはCPUでも直ります。 - どの枠でも、どの組み合わせでも。
ai[i]は側ごとのstd::optional<AiController>なので、1P 対 CPU、CPU 対 CPU、2人で対戦は、枠の埋め方が違うだけの同じコードです。CPU 対 CPUは此の章で一番役に立つテストの道具になりました。二人のCPUは台本無しで何千ステップも戦い、32.4の最後の小節で説明する相打ちのクラッシュを見つけました。 - 入力を記録して再生出来ます。 ファイターを動かす物は全てステップごとの
Controlsなので、試合は2本のControlsの流れで完全に表せます。其れがリプレイの基礎で、今の格闘ゲームが使うロールバックのネットコードの基礎でもあります(課題7)。
CPUは「段階」の決まりにも従います。
ラウンドの始まりと決着の間は、CPUの物も含めて全員の入力が空になります。
公平さのもう半分は、CPUが何を見るかです。
thinkが読むのは、人が画面で見られる状態だけです。
位置、ファイターの状態、技の段階、そして技が始まったら其れがどの技か。
人のボタンは秘密の儘です。
読む入力は一つだけ、相手が下を押しているかどうかで、此れは画面ではどうせしゃがみとして見えます。
意図と決める間隔
CPUの頭脳は小さな状態機械です。
状態は意図、つまり今何をしようとしているかで、各意図にはタイマーがあります:
// コンピューターの相手:人と同じControlsを作る「見えないプレイヤー」。状態(意図)と決める間隔(タイマー)で動き、
// 反応の遅れと確率で強さが変わる
// The computer opponent: an invisible player that produces the same Controls a human does. It runs on states
// (intents) and a decision timer; reaction delays and probabilities set the difficulty
#pragma once
#include "controls.hh"
#include "fighter.hh"
#include "engine/rng.hh"
#include <cstdint>
enum class Difficulty { Easy, Normal, Hard };
const char *difficultyName(Difficulty d);
// 強さの数値。時間はフレーム / the difficulty numbers; times in frames
struct AiProfile {
int thinkFrames; // 意図を続ける長さの基準(普通 = 20) / the base for how long an intent lasts (Normal = 20)
int reactionFrames; // 相手の技を見てから反応するまで(人なら約12〜15) / from seeing a move to reacting (a human
// needs about 12-15)
float blockChance; // 見えた技をガードする確率 / chance to guard a move it saw
float antiAirChance; // 飛び込みを蹴りで落とす確率 / chance to kick a jump-in out of the air
float punishChance; // 相手の硬直に反撃する確率 / chance to punish recovery
float aggression; // 近づいて攻める割合 / how often it closes in and attacks
bool combos; // 突き → 突きをつなぐ / links punch → punch
};
const AiProfile &aiProfile(Difficulty d);
class AiController {
public:
AiController(Difficulty difficulty, std::uint32_t seed);
// 1ステップ分の入力を作る(ファイターの公開されている状態だけを見る:ずるはしない)
// Makes one step of input (looking only at the fighters' public state: no cheating with hidden data)
Controls think(const Fighter &self, const Fighter &opponent);
void reset();
const char *intentName() const;
private:
enum class Intent { Wait, Approach, Retreat, Attack, JumpIn, Guard, AntiAir };
void decide(const Fighter &opponent, float distance);
void setIntent(Intent next, int frames);
int thinkTime(float lo, float hi);
const AiProfile &profile;
Rng rng;
Intent intent = Intent::Wait;
int timer = 30; // 今の意図の残り / frames left for the current intent
int reaction = -1; // 反応までの残り(-1 = なし) / frames until the reaction (-1 = none)
bool guardLow = false;
bool sawAttack = false; // 相手の今の技をもう見た / already saw the opponent's current move
bool punished = false; // 相手の今の硬直にもう反撃した / already punished the current recovery
bool pressed = false; // この意図でボタンをもう押した / already pressed the button for this intent
MoveId planned = MoveId::Punch;
};
Wait:少しの間何もしない(相手を見るのも作戦の一つ)Approach:届く距離まで前に歩くRetreat:後ろに歩く(第31章の近接ガードのお陰で、此れはガードにもなります)Attack:決めておいた技のボタンを一度押す。パンチ、キック、足払い又はしゃがみパンチJumpIn:前に跳び、十分近ければ落ちながら蹴るGuard:見た技が続く間、後ろを押す(下段には後ろ下)AntiAir:跳んでいる相手が85 px以内に来たら蹴り落とす
今の意図のタイマーが切れて、且つファイターが自由に動ける時、decideが次の意図を引きます。
重みは二人の足元の間の距離で変わります:
// 意図の長さ:thinkFramesの lo〜hi 倍からくじで(倍率は普通の20で決めた値。易しいは長く、難しいは短く)
// An intent's duration: a draw from lo to hi times thinkFrames (the factors were tuned on Normal's 20; Easy keeps
// an intent longer, Hard changes its mind sooner)
int AiController::thinkTime(float lo, float hi) {
float t = static_cast<float>(profile.thinkFrames);
return rng.range(static_cast<int>(std::lround(lo * t)), static_cast<int>(std::lround(hi * t)));
}
// 意図を選ぶ:距離で重みを変えたくじ引き / picks an intent: a weighted draw that depends on the distance
void AiController::decide(const Fighter &opponent, float distance) {
float a = profile.aggression;
float r = rng.unit();
if (distance > 170.0f) {
if (r < 0.45f + 0.3f * a) setIntent(Intent::Approach, thinkTime(1.0f, 2.5f));
else if (r < 0.6f + 0.3f * a) setIntent(Intent::JumpIn, 40);
else setIntent(Intent::Wait, thinkTime(0.5f, 1.5f));
} else if (distance > kAttackRange) {
if (r < 0.35f + 0.3f * a) setIntent(Intent::Approach, thinkTime(0.6f, 1.5f));
else if (r < 0.5f + 0.3f * a) setIntent(Intent::JumpIn, 40);
else if (r < 0.8f) setIntent(Intent::Retreat, thinkTime(0.5f, 1.2f));
else setIntent(Intent::Wait, thinkTime(0.4f, 1.0f));
} else {
// 近い:攻めるか、下がるか / close: attack or back off
if (r < 0.45f + 0.45f * a) {
float m = rng.unit();
// 相手がしゃがんでいれば足払いを多めに / sweep more often against a crouching opponent
bool low = opponent.controls.down || opponent.state == FighterState::Crouch;
planned = m < (low ? 0.2f : 0.4f) ? MoveId::Punch
: m < (low ? 0.35f : 0.65f) ? MoveId::Kick
: m < (low ? 0.8f : 0.85f) ? MoveId::Sweep
: MoveId::CrouchPunch;
setIntent(Intent::Attack, moveData(planned).total() + thinkTime(0.2f, 0.7f));
} else if (r < 0.9f) setIntent(Intent::Retreat, thinkTime(0.5f, 1.2f));
else setIntent(Intent::Wait, thinkTime(0.3f, 0.8f));
}
}
距離の帯は3つです。
遠い(170 pxより上)、中くらい(62〜170 px)、届く(62 px未満、パンチとキックが届く所)。
aggression(上のa)は、待つ・下がるの重みを、近づく・攻めるに移します。
3つの難易度の攻め気0.35、0.55、0.70では、重みは次の様になります(各行の合計は100 %):
| 帯 | 意図 | Easy | Normal | Hard |
|---|---|---|---|---|
| 遠い | 近づく / 飛び込む / 待つ | 55.5 / 15 / 29.5 % | 61.5 / 15 / 23.5 % | 66 / 15 / 19 % |
| 中くらい | 近づく / 飛び込む / 下がる / 待つ | 45.5 / 15 / 19.5 / 20 % | 51.5 / 15 / 13.5 / 20 % | 56 / 15 / 9 / 20 % |
| 届く | 攻める / 下がる / 待つ | 60.75 / 29.25 / 10 % | 69.75 / 20.25 / 10 % | 76.5 / 13.5 / 10 % |
飛び込む確率が何時も15 %なのは、其の上と下の境目が攻め気で同じだけ動くからです。
届く距離では、出す技をもう一度くじで引きます。
パンチ40 %、キック25 %、足払い20 %、しゃがみパンチ15 %ですが、相手がしゃがんでいる(又は下を押している)と足払いが45 %に上がります。
低い構えには低い攻めで答える訳です。
攻める意図は、技の全体のフレーム数に短い間(Normalで4〜14フレーム)を足しただけ続くので、自分の技がまだ硬直の間にCPUが次を決める事はありません。
タイマーもランダムで、thinkTime(lo, hi)が難易度のthinkFramesのlo倍からhi倍の間で長さを引きます(Normalなら遠くから近づくのは20〜50フレーム、下がるのは10〜24フレーム、等)。
此の揺らぎのお陰でCPUがメトロノームの様に見えません。
倍率はthinkFramesが20のNormalで決めた物で、他の難易度で其れがどうなるかは下の「難易度は数値だけ」で見ます。
此れが、古典的なゲームAIの意味での「状態で決める」作りです。
少しの状態とタイマーと、重みの付いたサイコロ。
探索木や学習と比べると原始的に聞こえますが、世に出た格闘ゲームのCPUの殆どは正に此れに、手作業の調整を足した物です。
見る、反撃する、つなぐ、決める
CPUごとに毎ステップ一回動くthinkの前半です:
Controls AiController::think(const Fighter &self, const Fighter &opponent) {
Controls c;
float dx = opponent.position.x - self.position.x;
float distance = std::abs(dx);
auto hold = [&](bool towards) {
if ((dx > 0.0f) == towards) c.right = true;
else c.left = true;
};
// 1. 見る(遅れて反応する):相手が技を出し始めたら、反応の時間の後にガードするか決める
// 1. Perceive (with a delay): when the opponent starts a move, decide after the reaction time whether to guard
MovePhase op = opponent.phase();
if (op == MovePhase::Startup && !sawAttack) {
sawAttack = true;
reaction = profile.reactionFrames;
}
if (op == MovePhase::None) sawAttack = false;
if (reaction >= 0 && --reaction < 0 && opponent.move) {
// 飛び込み(空中の技)は対空を狙うこともある / a jump-in may be answered with an anti-air
bool air = opponent.move->air;
if (air && distance < 120.0f && rng.chance(profile.antiAirChance)) setIntent(Intent::AntiAir, 20);
else if (distance < 170.0f && rng.chance(profile.blockChance)) {
guardLow = opponent.move->height == AttackHeight::Low;
setIntent(Intent::Guard, opponent.move->startup + opponent.move->active + 6);
}
}
// 2. 反撃:相手が近くで硬直していれば(一度だけ判断) / 2. Punish: the opponent is recovering nearby (decided once)
if (op != MovePhase::Recovery) punished = false;
if (op == MovePhase::Recovery && !punished && self.actionable() && distance < kAttackRange + 4.0f) {
punished = true;
if (rng.chance(profile.punishChance)) {
planned = MoveId::Punch;
setIntent(Intent::Attack, moveData(planned).total() + 4);
}
}
// 3. つなぎ(強いときだけ):自分の突きが当たったら、硬直の終わりにもう一度押す(入力バッファが拾う)
// 3. Links (hard only): when our punch hit, press again near the end of the recovery (the input buffer catches it)
if (profile.combos && self.state == FighterState::Attack && self.moveHit && self.moveId == MoveId::Punch &&
opponent.state == FighterState::Hitstun && self.stateTime == self.move->total() - 3)
c.punch = true;
// 4. 決める:意図の時間が切れて、自由に動けるとき / 4. Decide: when the intent's time is up and the fighter is free
if (--timer <= 0 && self.actionable()) decide(opponent, distance);
1. 遅れて見る。 相手の技が発生に入ると、CPUは其れを覚え(sawAttack。一つの技は一度しか見ません)、reactionFramesの数え下ろしを始めます。
数え終わった時に初めて、確率でガードするか(blockChance。技の高さで立ちかしゃがみ)、120 px以内の飛び蹴りなら対空を狙うか(antiAirChance)を決めます。
此の遅れが、AI全体で一番大事な数です。
此れが無いと、CPUは相手の技が始まった其のステップに其れを知り、ガードすると決めた物は全部ガード出来てしまいます。
勝てませんし、面白くありません。
人が見た物に反応するには12〜15フレーム(200〜250 ms)位掛かり、難易度ごとの数値はCPUに24、14又は8フレームを与えます。
フレームの反応で何をガード出来るか、正確に数えてみる価値があります。
結果が少し意外だからです。
相手のキック(発生8、持続9〜12、硬直13〜28)が、ステップ0、つまり其のフレーム1で押されたとします。
thinkはファイターの更新の前に動くので、CPUが発生を初めて見るのはステップ1で、ステップ数え下ろし、ステップから後ろを押します。
其のステップのファイターの更新が処理するのは、キックのフレームです。
Hardではガードはフレーム10、キックの持続の2フレーム目に始まります。
Normalではフレーム16、Easyではフレーム26で、どちらもキックが終わったずっと後です。
従って、反応のガードで防げるのは、最初の持続フレームがフレーム以降に来る技だけです。
つまり発生が少なくともフレーム、Hardでも9フレーム要ります。
あたし達のフレームデータには、そんなに遅い地上の技はありません(パンチ4、しゃがみパンチ4、足払い7、キック8)。
(此の数え方はヒットストップが間に無い場合です。FightScene::updateではthinkがhitstop > 0の確認より前に動くので、ファイターが止まっている間もCPUの数え下ろしは進みます。止まっている間に始まった反応は、動きが戻る頃には殆ど終わっている事があり、ヒットの後の追撃に対してはCPUの助けになります。)
最初の持続フレームから届いているキックは、どの難易度のCPUにとっても、殆どの人にとっても、反応するには単純に速過ぎるのです。
此れは欠陥ではありません。
本物の格闘ゲームも同じで、「見てから反応出来る」技(中段、遅い突進、ジャンプ)の方が例外です。
其れでもガードの意図は色々な事をします:
- 飛び蹴りは着地まで持続し、15フレームより長い事も多いので、CPUは来るのを見て立ちガード出来ます(CPU 対 CPUのログに
HAYATE J.KICK -> JIN blockedがあります)。 - ガードは見た技の発生 + 持続 + 6フレーム続くので(キックなら後ろを押すのが17ステップ)、連携の次の技、パンチ → パンチの2発目や、ガードされたパンチの直後のキックを覆います。
- ログの其れ以外のガードは、CPUが元々後ろを押していた時、
Retreatの最中や前の技から残っていたガードの最中に起きています。第31章の近接ガードのお陰で、相手が近くで攻撃している時に後ろを押すのはガードです。
CPUは人と同じく、予想した物をガードし、遅い物に反応するのです。
2. 反撃。 相手が届く所で硬直していて、CPUが動ける時、punishChanceの確率でパンチします。
punishedで、一回の硬直につき判断は一度だけです。
此れが無いと毎ステップくじを引き直し、殆ど必ず反撃してしまいます。
ガードされたキックは−6、ガードされた足払いは−10で(第31章の表)、パンチの4フレームの発生はどちらにも間に合います。
3. つなぎ。 Hardでは、自分のパンチが当たった後、硬直が終わる3フレーム前にもう一度パンチを押します。
第31章の入力バッファが其の押下を覚えていて、出せる最初のフレームで2発目のパンチを出し、パンチはヒットで+7なのでつながります(「2 HITS」)。
CPUにフレーム単位のタイミングのコードは要りません。
人と同じく、バッファがタイミングのコードだからです。
4. 決める。 意図のタイマーが切れて、ファイターが自由な時(actionable():立ち、歩き、しゃがみ)だけです。
意図を実行する
後半は意図をボタンに変えます:
// 5. 実行 / 5. Execute
switch (intent) {
case Intent::Wait:
break;
case Intent::Approach:
hold(true);
if (distance < kAttackRange) setIntent(Intent::Wait, 2); // 着いた:すぐ次を決める / arrived: decide again soon
break;
case Intent::Retreat:
hold(false);
break;
case Intent::Attack:
if (!pressed && self.actionable()) {
pressed = true;
c.down = planned == MoveId::Sweep || planned == MoveId::CrouchPunch;
(planned == MoveId::Kick || planned == MoveId::Sweep ? c.kick : c.punch) = true;
}
break;
case Intent::JumpIn:
if (!pressed && self.actionable()) {
pressed = true;
c.up = true;
hold(true);
}
// 落ち始めて近ければ蹴る / kick once falling and close
if (self.state == FighterState::Air && self.velocity.y > -120.0f && distance < 90.0f) c.kick = true;
if (self.actionable() && pressed && timer < 30) setIntent(Intent::Wait, 4);
break;
case Intent::Guard:
hold(false);
c.down = guardLow;
break;
case Intent::AntiAir:
if (!pressed && self.actionable() && distance < 85.0f) {
pressed = true;
c.kick = true;
}
break;
}
return c;
}
hold(true)は相手の方へ、hold(false)は反対へ押します。
第31章の人のガードと同じく、位置から決めます。
pressedは、一つの意図でボタンを一度だけ押す為の物です。
Controls::punchは「此のステップで押した」という意味なので、此のフラグが無いとCPUは意図の間毎ステップ押し直し、2つ目の技をバッファに入れてしまいます。
飛び込みは、計画を持つ唯一の意図です。
上と前を一度押し、ジャンプの頂点の近くか落ちる途中で(velocity.y > -120、yは下向き)相手から90 px以内になったら蹴ります。
F1のデバッグ表示は、CPUの今の意図も状態の下に出す様になりました:
// CPUなら今の意図も / for the CPU also its current intent
if (ai[i] && n > 0 && static_cast<size_t>(n) < sizeof label)
std::snprintf(label + n, sizeof label - static_cast<size_t>(n), "\nAI %s", ai[i]->intentName());
ハヤテの意図はGUARDなのに、のけぞっています。
意図はCPUがしようとしている事で、ファイターが出来る事ではありません。
後ろを押してガードになるのは、ファイターがガード出来る状態の時だけです。
難易度は数値だけ
3つの難易度は3つのAIではありません。
一つの表の3つの行です:
// 考える 反応 ガード 対空 反撃 攻め つなぐ / think react guard anti-air punish aggro combo
constexpr AiProfile kProfiles[] = {
{34, 24, 0.20f, 0.10f, 0.15f, 0.35f, false}, // Easy
{20, 14, 0.50f, 0.35f, 0.45f, 0.55f, false}, // Normal
{10, 8, 0.80f, 0.70f, 0.80f, 0.70f, true}, // Hard
};
| Easy | Normal | Hard | |
|---|---|---|---|
意図の長さ(thinkFrames) |
× 1.7(34) | × 1(20) | × 0.5(10) |
| 反応 | 24フレーム(400 ms) | 14フレーム(233 ms) | 8フレーム(133 ms) |
| 見た技をガード | 20 % | 50 % | 80 % |
| 飛び蹴りを対空 | 10 % | 35 % | 70 % |
| 硬直に反撃 | 15 % | 45 % | 80 % |
| 攻め気 | 0.35 | 0.55 | 0.70 |
| パンチ → パンチをつなぐ | しない | しない | する |
動きのコードは3つとも同じです。
CPUを弱くしたり強くしたりするのはプログラミングではなく調整で、デザイナーがthinkを読まずに出来ます。
Normalの14フレームは丁度人の速さです。
Easyは人より遅いので勝てそうに感じ、Hardは人より速いです。
此れはよくある妥協です。
完璧で且つ人の速さのCPUを書くのは難しいので、高い難易度は人を超えた反応で強さを買います。
thinkFramesはテンポを決めます。
decideのランダムな長さは全て其の倍数の範囲なので、EasyはNormalの1.7倍長く1つの意図を続け(遠くから近づくのは20〜50フレームではなく34〜85フレーム)、Hardは2倍の頻度で考えを変えます(10〜25フレーム)。
Normalでは倍率が切りの良い範囲(20〜50、12〜30、10〜24、等)になり、其れがAIを調整した時の範囲です。
考える速さではなくゲームから来るタイマーは其の儘です:飛び込みは40フレーム、ガードは見た技の発生 + 持続 + 6、対空は20です。
CPUの難易度はタイトルで選び、Game::difficultyに残るので、タイトルに戻っても覚えています。
毎回同じ試合
各AiControllerは自分のRngを持ち、対戦のシーンは其れに定数の種を与えます:
// CPUの担当:1P対CPUなら2P、CPU対CPUなら両方。種は固定(同じ入力なら同じ試合) / who the computer plays: 2P in
// 1P vs CPU, both in CPU vs CPU. Fixed seeds (the same input gives the same match)
if (settings.mode == Mode::VsCpu || settings.mode == Mode::CpuVsCpu) ai[1].emplace(settings.difficulty, 3202u);
if (settings.mode == Mode::CpuVsCpu) ai[0].emplace(settings.difficulty, 3201u);
此れを第26章の2つの約束と組み合わせます。
ゲームの処理は画面の描く速さに関係無く1/60秒の固定ステップで進み、Rngはstd::mt19937のビットを自分のコードで範囲に変換するので、同じ種ならGCCでもClangでもMSVCでも同じ数が出ます。
すると、CPUの判断は種と対戦で起きた事だけで決まり、起きた事は人の入力だけで決まります。
同じ人の入力なら、ステップ単位で同じ試合になります。
勝利画面からのもう一度(新しいFightScene、同じ種の新しいAiController)は、人が同じ様に操作する限り、CPUの判断を其の儘再現します。
此の章の台本通りの動画は此れに頼っていて、デバッグも同じでした。
「CPU 対 CPU、Normal、ステップ1668で落ちる」は再現出来るバグ報告です。
花びらのRng{32}は共有のStageにあってリセットされませんが、ゲームの処理は花びらを読まないので、花びらの舞い方が違っても当たりは一つも変わりません。
第26章の何時もの注意は此処でも当てはまります。
違うコンパイラの間でビット単位で同じにするには、ゲームの状態の浮動小数点の計算も同じに計算される必要があり、其れは其れで一つの話題です。
一つのビルドの中では正確に同じです。
CPUは何時も同じ種で遊ぶので、人はCPUに勝つ「パターン」を覚えられます。
多くのアーケードゲームで文字通りそうでした。
再現性との引き換えです。
種を時計から取れば本物のプレイヤーには直りますが、上の性質を全部失います(課題3で両方を保つ方法を考えます)。
CPU 対 CPUが見つけた物
第31章のメモにもう書いてあります。
相打ちでは、二人のファイターが同じステップに互いに当てます。
一つ目のtakeHitが食らった方のmoveを消し、其の食らった方は2つ目の攻撃をした方でもあるので、2つ目の当たりはnullポインターを読みました。
人が二人だと、丁度同じステップに相打ちになる事は殆どありません。
NormalのCPUが二人だと、1分以内に起きました。
第31章のコードに既に入っている直し方は、何かを書き換える前に、各当たりに要る物を覚えておく事です:
// 技はここで覚える:相打ちだと、一つ目のtakeHitが二人目の技(move)を消してしまう
// The move is remembered here: in a trade the first takeHit clears the second attacker's move
struct Contact {
int attacker;
const MoveData *move;
Rect where;
bool blocked;
};
Contact contacts[2];
「集めてから当てはめる」は同時の当たりの為の第31章の決まりで、此処に其の2つ目の理由があります。
当てはめ始めたら、集めたデータは既に変えた物に頼ってはいけないのです。
32.5 ラウンドと試合
ルール
試合のルールは4つの定数です:
// 試合の設定(タイトルで選ぶ) / the match settings (chosen on the title screen)
#pragma once
#include "ai.hh"
enum class Mode {
VsCpu, // 1P 対 CPU / 1P vs the computer
TwoPlayers, // 二人で対戦 / two players
CpuVsCpu, // CPU 対 CPU(見るだけ) / computer vs computer (watch)
Training, // 練習:時間なし、KOで仕切り直し / training: no timer, a KO restarts
};
struct MatchSettings {
Mode mode = Mode::VsCpu;
Difficulty difficulty = Difficulty::Normal;
};
constexpr int kWinsNeeded = 2; // 3本勝負:先に2本 / best of three: first to two
constexpr int kMaxRounds = 5; // 引き分けが続いたら5本目で終わり / draws end the match after round 5
constexpr int kRoundSeconds = 60;
3本勝負は、ラウンドを2本取った方の勝ちです。
引き分けは誰にも1本を与えないので試合が続き得ますが、kMaxRoundsが第5ラウンドの後で、其の時の点数で終わらせます。
時間は秒ではなく更新のステップで数えます:
RoundPhase phase = RoundPhase::Intro;
int phaseTime = 0;
int round = 1;
int wins[2] = {0, 0};
int timer = kRoundSeconds * 60; // ラウンドの残り(ステップ) / time left in the round (steps)
int roundWinner = -1; // -1 = 引き分け / -1 = draw
bool timeOver = false;
int koTime = 0; // 練習モードのKOからの時間 / training mode: time since a KO
bool leaving = false; // 勝利画面への切り替えを頼んだ / the switch to the win screen was requested
kRoundSeconds * 60 = 3600ステップです。
ステップなので、ラウンドはどのマシンでもゲームの時間で丁度60秒続き、ヒットストップの間は止まります(hitstop > 0の間はラウンドの処理まで辿り着きません)。
其れで正しいのです。
40フレームのKOの停止が時計を食うべきではありません。
ラウンドの状態機械
ラウンドには3つの段階があります。
第29章のインベーダーのプレイのシーンと同じ、enum class Phaseの型です:
// ラウンドの流れ(ステップごと)。ヒットストップ中は進まない / the round flow (per step); frozen during hit stop
void FightScene::updateRound() {
++phaseTime;
if (settings.mode == Mode::Training) {
if (koTime > 0 && ++koTime > 180) startRound(); // 練習:3秒後に仕切り直し / training: restart after 3 s
return;
}
bool ko[2] = {fighters[0].health == 0, fighters[1].health == 0};
switch (phase) {
case RoundPhase::Intro:
if (phaseTime >= kIntroFrames) {
phase = RoundPhase::Fight;
phaseTime = 0;
}
break;
case RoundPhase::Fight:
if (ko[0] || ko[1]) finishRound(ko[0] && ko[1] ? -1 : ko[0] ? 1 : 0, false);
else if (--timer <= 0) {
// タイムアップ:体力の多い方の勝ち / time over: the one with more health wins
int h0 = fighters[0].health, h1 = fighters[1].health;
finishRound(h0 == h1 ? -1 : h0 > h1 ? 0 : 1, true);
}
break;
case RoundPhase::Finish:
if (phaseTime == kWinPoseAt && roundWinner >= 0) fighters[roundWinner].win();
if (leaving) phaseTime = kFinishFrames; // 暗いまま待つ / stay dark while the switch happens
else if (phaseTime >= kFinishFrames) {
bool over = wins[0] >= kWinsNeeded || wins[1] >= kWinsNeeded || round >= kMaxRounds;
if (over) {
int winner = wins[0] == wins[1] ? -1 : wins[0] > wins[1] ? 0 : 1;
// 置き換えは予約だけ(このシーンはこのupdateの後で消える) / the replacement is only queued (this scene goes
// away after this update)
scenes().replace(std::make_unique<ResultScene>(g, settings, winner, wins), {.duration = 0.6f});
leaving = true;
} else {
++round;
startRound();
}
}
break;
}
}
- Intro、100フレーム:「ROUND 1」(又は「FINAL ROUND」)を60、其れから「FIGHT!」を40。誰も動けません。
- Fight:時間が進みます。KOでラウンドが終わります(相打ちで同じステップに二人とも0ならダブルKOで引き分け)。時間が0になったら体力の多い方の勝ちで、同じなら引き分けです。
- Finish、230フレーム:「K.O.」、「TIME UP」又は「DOUBLE K.O.」を70、其れから勝った方の表示。其の後、次のラウンドが始まるか、試合が終わります。
finishRoundは結果を記録し、ログに出します:
void FightScene::finishRound(int winner, bool byTime) {
phase = RoundPhase::Finish;
phaseTime = 0;
roundWinner = winner;
timeOver = byTime;
if (winner >= 0) ++wins[winner];
printf("round %d: %s%s (wins %d-%d)\n", round, winner < 0 ? "draw" : fighters[winner].name.c_str(),
byTime ? " by time" : "", wins[0], wins[1]);
}
Finishのフレーム70で、勝った方に勝ちポーズを頼みます。
「頼む」のは、勝った方がまだ空中にいたり、最後のキックの硬直中だったりするかも知れないからです。
Fighterは其の頼みを覚えておき、地上で自由になってからWin状態を始めます:
// 勝ちポーズは、自由に動ける状態で地上にいるときに / the victory pose starts once free and on the ground
if (wantsWin && onGround && (actionable() || state == FighterState::Land)) {
velocity.x = 0.0f;
setState(FighterState::Win);
animator.play(winClip, true);
}
2種類のフェード
ラウンドの間、シーンは同じ儘です。
startRoundはファイター、時間、エフェクト、CPUの意図をリセットし(但しRngはリセットしないので、第2ラウンドは第1ラウンドの写しになりません)、対戦のシーンは自分でフェードを描きます。
Finishの最後の30フレームで暗くなり、Introの最初の20フレームで戻ります:
void FightScene::drawUi(float /*alpha*/) {
SpriteBatch &b = g.batch;
b.begin(g.screen.matrix());
// ラウンドの間の暗転(自前のフェード:シーンは変わらない) / the fade between rounds (our own: the scene stays)
float fade = 0.0f;
if (phase == RoundPhase::Finish && phaseTime > kFinishFrames - 30)
fade = static_cast<float>(phaseTime - (kFinishFrames - 30)) / 30.0f;
if (phase == RoundPhase::Intro && phaseTime < 20) fade = 1.0f - static_cast<float>(phaseTime) / 20.0f;
if (fade > 0.0f) b.drawRect({0, 0, 1280, 720}, {0.0f, 0.0f, 0.0f, std::clamp(fade, 0.0f, 1.0f)});
試合の終わりは本物のシーンの切り替え、第26章のフェード付きのscenes().replace(ResultScene, 0.6 s)です。
シーンを其のシーン自身のupdateから置き換えるのは、第26章が切り替えを予約にした正に其の場面です。
頼みは覚えられるだけで、leavingは、ラウンドの処理が次のステップでもう一度頼まない様にし、フェードが始まる迄画面を暗い儘にします。
第29章も面の読み直しで同じフラグを使いました。
HUD
時間は体力ゲージの間の箱にあり、最後の10秒で赤くなります:
// 時間(真ん中)。練習は「練習」 / the timer (center); training shows "練習"
b.drawRect({298, 4, 44, 30}, kOutline, 10.0f);
TextStyle centre = {.color = kGold, .scale = 2.0f, .align = TextAlign::Centre, .layer = 11.0f};
if (settings.mode == Mode::Training) {
centre.scale = 1.0f;
g.pixel.draw(b, "練習", {320, 12}, centre);
} else {
int seconds = (timer + 59) / 60;
centre.color = seconds <= 10 ? kRed : kGold;
g.pixel.draw(b, std::to_string(seconds), {320, 6}, centre);
}
(timer + 59) / 60は切り上げなので、最初の1秒は60、最後の1秒は1を表示し、丁度ラウンドが終わる時に0になります。
名前の横では、取ったラウンドごとに小さな四角が金色になり、CPUの枠には「(CPU)」が付きます。
ラウンドの表示は、第31章のK.O.と同じ輪郭付きのdrawBigTextを使います。
タイトルと勝利画面でも使える様に、今はhud.ccにあります:
if (phase == RoundPhase::Intro) {
bool final = round == kMaxRounds || (wins[0] == kWinsNeeded - 1 && wins[1] == kWinsNeeded - 1);
if (phaseTime < 60) {
drawBigText(b, g.pixel, final ? "FINAL ROUND" : "ROUND " + std::to_string(round), {320, 130}, kText, 4.0f);
g.pixel.draw(b, final ? "最終ラウンド" : "第" + std::to_string(round) + "ラウンド", {320, 162}, sub);
} else {
drawBigText(b, g.pixel, "FIGHT!", {320, 130}, kGold, 5.0f);
}
finalは第5ラウンドか、二人とも1本ずつ取った時に真になります。
どちらにしても次のラウンドで試合が決まるからです。
32.6 タイトル、一時停止、勝利画面
ゲームのシーンは4つになりました。
其の宣言はscenes.hhにまとめてあるので、タイトルが対戦を、対戦が結果を、結果が又タイトルを、インクルードの循環無しに作れます。
タイトル
メニューは遊び方の表と、難易度の行一つです:
constexpr Item kItems[] = {
{"1P VS CPU", "1P 対 CPU", Mode::VsCpu},
{"2P VS", "2人で対戦", Mode::TwoPlayers},
{"CPU VS CPU", "CPU 対 CPU", Mode::CpuVsCpu},
{"TRAINING", "練習", Mode::Training},
};
constexpr int kItemCount = 5; // 4つの遊び方 + 難易度 / four modes + the difficulty
const char *const kDifficultyJa[] = {"易しい", "普通", "難しい"};
void TitleScene::update(float dt) {
time += dt;
g.stage->update(dt);
Input &in = g.input;
if (in.pressed(GLFW_KEY_ESCAPE)) {
scenes().pop(); // 最後のシーン:終了 / the last scene: quit
return;
}
if (menuUp(in)) selected = (selected + kItemCount - 1) % kItemCount;
if (menuDown(in)) selected = (selected + 1) % kItemCount;
int d = static_cast<int>(g.difficulty);
if (menuLeft(in)) g.difficulty = static_cast<Difficulty>((d + 2) % 3);
if (menuRight(in)) g.difficulty = static_cast<Difficulty>((d + 1) % 3);
if (menuConfirm(in) && selected < 4)
scenes().replace(std::make_unique<FightScene>(g, MatchSettings{kItems[selected].mode, g.difficulty}),
{.duration = 0.8f});
}
メニューの後ろでは、ステージが勝手に流れます。
ただで手に入る視差の見本です。
カメラの中心はsinでステージの真ん中の周りを±150 px揺れ、カメラの範囲の中に収まります(512 ± 150 = 362〜662):
void TitleScene::draw(float /*alpha*/) {
SpriteBatch &b = g.batch;
// カメラはゆっくり左右に:視差の層がそれぞれの速さで動く / the camera drifts left and right: each parallax layer
// moves at its own speed
Camera2D view = Camera2D::screen(kViewSize);
view.centre.x = std::round(kStageWidth * 0.5f + 150.0f * std::sin(time * 0.3f));
b.begin(view.matrix(), SpriteSort::Layer);
g.stage->drawBack(b, view);
一時停止
一時停止メニューは重ねるシーンです(第26章:isOverlay()で下の対戦も描かれ、更新されるのは一番上のシーンだけです):
void PauseScene::update(float dt) {
time += dt;
Input &in = g.input;
if (in.pressed(GLFW_KEY_ESCAPE) || in.pressed(GLFW_KEY_P)) {
scenes().pop();
return;
}
if (menuUp(in) || menuDown(in)) selected = 1 - selected;
if (menuConfirm(in)) {
if (selected == 0) scenes().pop();
else scenes().replaceAll(std::make_unique<TitleScene>(g), {.duration = 0.8f});
}
}
対戦の側にも一つ細かい事があります。
一時停止が上に載ると、対戦は今の位置をpreviousに写すので、止まった絵が2つの違うステップの間を何時までも補間し続ける事はありません:
// 一時停止が上に載った:補間で震えないように前の位置 = 今 / the pause went on top: previous = current, so the
// interpolation does not wobble
void FightScene::pause() {
for (Fighter &f : fighters) f.savePrevious();
}
勝利画面
ResultSceneは勝った方を2倍の大きさの勝ちポーズで、負けた方を奥で倒れた姿で、そしてラウンドの点数を見せます。
Space又はFで同じ設定でもう一度、Escでタイトルに戻ります:
void ResultScene::update(float dt) {
time += dt;
pose.update(dt);
g.stage->update(dt);
Input &in = g.input;
if (in.pressed(GLFW_KEY_ESCAPE)) scenes().replace(std::make_unique<TitleScene>(g), {.duration = 0.8f});
else if (menuConfirm(in) && time > 0.5f)
scenes().replace(std::make_unique<FightScene>(g, settings), {.duration = 0.8f}); // もう一度 / rematch
}
time > 0.5fの条件は最初の半秒の決定を無視するので、対戦の終わりに連打したパンチで此の画面が飛ばされる事はありません。
勝った方をSpriteSheet::spriteの拡大で2倍に描くのは、此処ではピクセルアートでも問題ありません。
2は整数なので、どのテクセルもキャンバスの2 × 2ピクセルの塊になります。
2つ目の動画はCPU 対 CPUの試合の終わりです。
最後の打ち合い、K.O.、勝ちポーズ、暗転、勝利画面:
main.ccはスプライトシートの隣でステージを一度読み、対戦ではなくタイトルから始めます:
std::optional<Stage> stage = Stage::load();
if (!frameData || !stage) return 1;
SceneManager scenes;
scenes.push(std::make_unique<TitleScene>(game));
32.7 有る文字だけで
日本語が読める人には、此のゲームの日本語の文字列は少し変わって見えるかも知れません。
もっと自然な突き・蹴りの代わりに「パンチ」と「キック」、二人の代わりに「2人で対戦」、ヘルプの行では判定の箱を「当たり箱」、ラウンドの表示は「第Nラウンド」です。
此れは好みではなく、実際の制約です。
第26章の共有のフォントは、ASCII、仮名、そして普通のUIの文字列用に選んだ252字の漢字を持っていて、突 蹴 先 切 闘 二 移 判は其の中にありません。
Fontは無い文字を?で描き、標準エラーに警告を一つずつ出します。
其の為、ゲームの文字列はアトラスに有る文字で書きました。
第 ラウンド 最終 タイムアップ 勝ち 勝利 引き分け 対戦 練習 難易度 易しい 普通 難しい 一時停止 再開 タイトルへ もう一度は全部入っています。
コードのコメントは別で、画面には出ないので、突きも蹴りも自由に使っています。
const char *help = settings.mode == Mode::TwoPlayers || settings.mode == Mode::Training
? "1P: A D W S + F パンチ・G キック 2P: カーソルキー + K・L F1 当たり箱 Esc 一時停止 / pause"
: settings.mode == Mode::VsCpu
? "1P: A D 前後・W ジャンプ・S しゃがむ・F パンチ・G キック F1 当たり箱 Esc 一時停止 / pause"
: "CPU 対 CPU F1 当たり箱 Esc 一時停止 / pause";
言い換えで済むのは、メニューの文字列が少しの時だけです。
本物の会話のあるゲームでは済まないので、第35章のRPGは自分のフォントアトラスを作ります。
スクリプトが会話とソースの文字列を調べ、要る漢字を全部足したゲーム専用のpixel12の写しを作り、共有のフォントには触りません。
32.8 動かす
プロジェクトのルートから:
cmake --build build -j8
./build/games/fighter/fighter
Visual Studioでは、スタートアッププロジェクトにfighterを選んで下さい(build\games\fighter\Debug\fighter.exe)。
作業ディレクトリは既にプロジェクトのルートです。
プログラムは全ての当たりと全てのラウンドを標準出力に出すので、試合を確かめる一番早い方法です。
NormalのCPU 対 CPUの試合の初めと終わりです:
step 145: JIN J.KICK -> HAYATE hit, hp 90, combo 1, hit stop 10
step 253: HAYATE C.PUNCH -> JIN hit, hp 95, combo 1, hit stop 7
step 333: HAYATE C.PUNCH -> JIN blocked, hp 95, combo 0, hit stop 4
...
round 1: HAYATE (wins 1-0)
...
step 3152: HAYATE J.KICK -> JIN blocked, hp 14, combo 0, hit stop 7
step 3180: JIN KICK -> HAYATE blocked, hp 55, combo 0, hit stop 8
step 3208: HAYATE PUNCH -> JIN hit, hp 8, combo 1, hit stop 7
step 3235: HAYATE SWEEP -> JIN KO, hp 0, combo 1, hit stop 40
round 2: HAYATE (wins 2-0)
此の試合全体で当たりは46回、其の内10回がガードされ、何回動かしても同じ46回です。
キーに触らない人が二人だと、60秒後にround 1: draw by timeになります。
32.9 プラットフォームごとの注意
- Windows(Visual Studio): 何時ものゲームの章と同じく、日本語の文字列には
/utf-8が要ります。無いとMSVCはソースをシステムのコードページで読み、メニューが?になります。プロジェクトのCMakeがMSVCの時に既に付けています。 - 全て: 標準出力は端末では行ごとですが、ファイルや
lessにパイプすると全部バッファされるので、落ちる実行は何も出さない事があります。相打ちのクラッシュも最初はそう見えました。クラッシュはログを読むのではなく、デバッガで調べて下さい(Linuxではgdb -batch -ex run -ex bt ./build/games/fighter/fighter、FreeBSDではlldb、Visual StudioではF5)。 - 全て: メニューと対戦のキーは、第26章と同じく、USキーボードでの位置で名前の付いたGLFWのキーコードです。AZERTYでは「W A S D」はZ Q S Dです。
32.10 本物のゲームではどうしているか
- 視差: 2Dのエンジンには組み込まれています。Godotの
Parallax2Dノードは層ごとのスクロールの倍率(あたし達の係数)を取り、層を繰り返す事も出来ます。Unityの2Dのプロジェクトでは、大抵各背景をカメラの動きの何割かで動かします。多くのゲームは縦の視差や行ごとのスクロール(ラインスクロール)も足します。昔のハードウェアは走査線ごとにスクロールのレジスタを変え、床を遠近法で描けました。シェーダーなら、同じ効果はフラグメントシェーダーの中の行ごとのずらしです。 - 格闘ゲームのカメラ: 真ん中を追う他に、多くのゲームは二人が離れるとズームアウトし、ジャンプで上に動きます(課題5と6)。「画面の端は壁」の決まりは、2Dの格闘ゲームでは殆ど全部に共通です。
- CPUの相手: 市販の格闘ゲームのAIは、此処と同じく、反応時間と確率を調整した手書きの状態機械が圧倒的に多いです。そして多くのCPUは相手の入力を直接読み、技の最初のフレームで答えられる様にしていて、プレイヤーは其れを「入力読み」と呼びます。記録した試合からプレイヤーを真似る、学習するAIを足すゲームもあります。
- リプレイとロールバック: 決定的なゲームは入力だけで完全に表せるので、格闘ゲームはリプレイを入力の流れとして保存します。ロールバックのネットコード(GGPO)は相手の入力を予想して先に進め、本物の入力が届いたら最後に確定したステップからやり直します。其れには正にあたし達の性質が要ります。固定ステップ、種の付いた乱数、そして安く写して戻せるゲームの状態です。
32.11 格闘ゲームの振り返りと、此の先
3つの章で、パート5のエンジンの上に完全な2D格闘ゲームを作りました:
- 第30章:状態機械としてのファイター(立ち、歩き、ジャンプ、しゃがみ)、重力と地面のある2Dの物理、640 × 360の大きなピクセルアートのスプライト、一台のキーボードの二人のプレイヤー。
- 第31章:アニメーションより優先するフレームデータ、絵と同じ骨格から作る攻撃判定と食らい判定、ヒット硬直、ガード硬直、ノックバック、ヒットストップ、入力バッファ、そして体の部品とエフェクトの為の、2 × 3のアフィン行列を使う2Dのシーングラフ。
- 此の章:視差のステージ(層ごとのカメラ、ぴったりの層の幅)、端が壁になる範囲付きの追いかけるカメラ、意図と決める間隔と反応の遅れと数値だけの難易度を持ち、人と同じ入力の道を通るCPU、決定的な試合、そして其の周りのラウンド、試合、シーンの流れ。
GPUの側では、ゲーム全体がPixelCanvasに描く一つのSpriteBatchのスプライトです。
中身は別の所にありました。
フレームで数える時間、絵とルールの両方の元になるデータ、そしてシミュレーションを動かす唯一の物としての入力です。
最後の考え方は、此の章だけで3回報われました。
CPUは入力装置で、動画は台本の入力で、どの試合も再生出来ます。
次はパート6の3つ目のゲーム、トップダウンRPGです。
第33章はタイルマップから始まります。
タイルセットのアトラス、マップのデータの形式、何千ものタイルを一つのバッチで描く事、そして固いタイルとの当たり判定付きでキャラクターを動かす事です。
カメラはプレイヤーを追い、マップの端で止まります。
此の章のclampCameraを、今度は2次元でもう一度使う訳です。
32.12 まとめ
- 視差: 係数の層はワールドのx に描く( = 画面の左端)ので、層のカメラは倍動く。ピンホールカメラでは。空0.05、山0.25、寺0.5、地面1、手前1.3。並べ替えの層は後ろが0〜0.3、手前が12。縦の視差は無し(カメラの高さは固定)。
- 層の幅: (659、736、832、1024、1139 px)なので、カメラがステージの端に着いた時、どの層も丁度自分の端に着く。生成スクリプトとコードは同じ様に丸めるので、隙間も繰り返しも無い。あたしの自作スクリプトで作る(numpy、Bayerのディザ、固定の種)。
- 花びら: 係数1.15の層の上の28個の長方形、760 pxの帯で輪になる、
Rng{32}、見た目だけ。 - カメラ: 中心 = 二人の真ん中(描く時は補間した位置)、[320, 704]に収め、整数のピクセルに丸める。画面から8 px引いた所が壁(
keepInView)なので、立っている二人は最大586 px離れられる。壁際の押し戻しはステージの端と画面の端の近い方を使う。揺れは横だけで範囲に収める。 - 見えないプレイヤーとしてのCPU:
AiController::thinkはreadControlsと同じくControlsを返し、同じ入力バッファとルールを通る。見える状態だけを読む。 - 意図: Wait、Approach、Retreat、Attack、JumpIn、Guard、AntiAir。タイマーが切れてファイターが自由な時に、距離(170より上、62〜170、62 px未満)と攻め気で重みを付けて次を引く。
- 反応: 発生を見てから
reactionFrames後に初めてガードか対空。updateの前にthinkが動くので、ガードは技のフレームから始まり、届いている地上の技には間に合わない(発生は全部8以下)。飛び蹴りと連携の次の技には間に合う。反撃は一回の硬直に一度。Hardはバッファを通してつなぐ。 - 難易度: 一つの表、Easy / Normal / Hard:考える34 / 20 / 10(ランダムな意図の長さは全て其の倍数の範囲)、反応24 / 14 / 8、ガード0.2 / 0.5 / 0.8、対空0.1 / 0.35 / 0.7、反撃0.15 / 0.45 / 0.8、攻め気0.35 / 0.55 / 0.7、つなぎはHardだけ。
- 決定性: 固定の種3201 / 3202 + 第26章の固定ステップとどの環境でも同じ
Rng→ 同じ入力なら同じ試合で、もう一度はCPUを其の儘再現する。 - ラウンド: Intro 100 → Fight(3600ステップの時間、ヒットストップ中は止まる。KO、ダブルKO、時間切れは体力で)→ Finish 230(70で勝ちポーズ、自前のフェード)→ 次のラウンドか
ResultScene。3本勝負、最大5ラウンド。 - シーン: タイトル(遊び方、難易度、流れるステージ)、対戦、一時停止(重ねる)、結果(もう一度かタイトル)。宣言は
scenes.hh。 - フォント: 文字列は共有のアトラスにある文字だけ(突 蹴 先 切 闘 二 移 判は無い)。RPGは第35章で自分のアトラスを作る。
32.13 課題
- ★ アセットのZIPの
extras/ch32-stage-mid-1024/にある、同じ絵を1024 pxの幅で描いたstage_mid_1024.pngをgames/fighter/assets/にコピーし、Stage::loadでstage_midの代わりに係数1.0で使って下さい({"stage_mid_1024", 1.0f, 0.2f, false})。寺は地面と丁度同じに滑り、ステージ全体が急に一枚の平らな絵に見えるはずです。元に戻して奥行きが戻るのを見て下さい。係数0.75で正しくなるには、元の832 pxの画像は何ピクセルの幅が要るでしょうか? - ★ ラウンドを30秒にし、試合を5本勝負にして下さい(
kRoundSeconds = 30、kWinsNeeded = 3)。ラウンドはずっと多く時間切れで終わり、ラウンドの印は片側に3つになり、二人とも2本取った時に「FINAL ROUND」が出るはずです。引き分けが2回ある試合で、kMaxRounds = 5が今何を意味するか確かめて下さい。 - ★ Easyの
reactionFramesを0にして戦ってみて下さい。ガードはキックのフレーム2から始まり、飛び蹴りのガードは確実になります。たった20 %でも、ガードすると決めた物は殆ど全部ガードするはずです。次に、テストの為の再現出来るCPU 対 CPUを失わずに、本物のプレイヤーに試合ごとに違うCPUを与えるにはどうすれば良いか(時計からの種)考えて下さい。 - ★★ CPU 対 CPUの2人のCPUを別々の難易度にして下さい。
MatchSettingsに1PのCPU用の2つ目のDifficultyを足してai[0]に渡します(最初はHardを直接書けば十分で、タイトルの項目は後で)。ハヤテがHard、ジンがEasyなら(種は3201と3202の儘)ハヤテが2-0で勝ち、入れ替えればジンが2-0で勝つはずです。次にログでガードを数えて下さい。ハヤテがHardの時、Easyのジンは16回ガードし、ハヤテは2回だけです。弱いCPUの方が多くガードする理由を、32.4でCPUのガードが何処から来るかを使って説明して下さい。 - ★★ ファイターが跳んだらカメラを上げて下さい。中心のy = min(180, 高い方のファイターのy + 120)で、地面が画面から出ない様に範囲に収め、層には縦の係数も与えます。層の画像はもっと高くする必要があり、其の高さは32.2と同じ導き方で出ます。60 pxまで上がれるカメラの場合で求めて下さい。
- ★★ ズームを足して下さい。二人が150 px以内の時、
Camera2D::zoomを1.25まで大きくします。PixelCanvasでは整数でないズームで、あるテクセルはキャンバスの1ピクセル、他は2ピクセルの幅になるので、スクロールすると絵がちらつきます。次にワールドを1280 × 720のキャンバスに描いて比べて下さい。どちらを出荷しますか? - ★★★ 記録と再生:試合の全ステップの両側の
Controlsをstd::vectorに貯め、タイトルに「Replay」の項目を足して、キーボードを読む代わりにもthinkを呼ぶ代わりにも其れを流し込んで(同じ種で)、最後の試合を再生して下さい。再生はステップ単位で元の試合と同じになるはずです。標準出力のログをdiffで比べて下さい。次に、CPUの種を時計から取ってわざと失敗させ、ロールバックのネットコードが何故同じ性質を必要とするのか説明して下さい。
ファイル: a/games/fighter/CMakeLists.txt | b/games/fighter/CMakeLists.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -2,13 +2,19 @@ | |||
| 2 | # The 2D fighting game (chapters 30-32): its own executable linking the engine | 2 | # The 2D fighting game (chapters 30-32): its own executable linking the engine |
| 3 | add_executable(fighter | 3 | add_executable(fighter |
| 4 | src/main.cc | 4 | src/main.cc |
| 5 | src/ai.cc | ||
| 5 | src/controls.cc | 6 | src/controls.cc |
| 6 | src/effects.cc | 7 | src/effects.cc |
| 7 | src/fighter.cc | 8 | src/fighter.cc |
| 8 | src/fight_scene.cc | 9 | src/fight_scene.cc |
| 9 | src/frame_data.cc | 10 | src/frame_data.cc |
| 11 | src/hud.cc | ||
| 10 | src/moves.cc | 12 | src/moves.cc |
| 11 | src/scene_graph.cc) | 13 | src/pause_scene.cc |
| 14 | src/result_scene.cc | ||
| 15 | src/scene_graph.cc | ||
| 16 | src/stage.cc | ||
| 17 | src/title_scene.cc) | ||
| 12 | target_include_directories(fighter PRIVATE src) | 18 | target_include_directories(fighter PRIVATE src) |
| 13 | target_link_libraries(fighter PRIVATE engine) | 19 | target_link_libraries(fighter PRIVATE engine) |
| 14 | enable_warnings(fighter) | 20 | enable_warnings(fighter) |
ファイル: a/games/fighter/README.md | b/games/fighter/README.md
| 前 | 新 | ||
|---|---|---|---|
| @@ -7,6 +7,14 @@ | |||
| 7 | build\games\fighter\Debug\fighter.exe # Windows (or F5 with the "fighter" target) | 7 | build\games\fighter\Debug\fighter.exe # Windows (or F5 with the "fighter" target) |
| 8 | ``` | 8 | ``` |
| 9 | 9 | ||
| 10 | ## 遊び方 / Modes(第32章から / from chapter 32) | ||
| 11 | |||
| 12 | タイトルで選ぶ / chosen on the title screen (W S 選ぶ / select, A D 難易度 / difficulty, Space・Enter・F 決定 / start): | ||
| 13 | 1P 対 CPU / 1P vs CPU, 2人で対戦 / 2P vs, CPU 対 CPU / CPU vs CPU (watch), 練習 / training(時間なし / no timer)。 | ||
| 14 | 3本勝負(先に2本)、1ラウンド60秒、時間切れは体力の多い方の勝ち。難易度:EASY / NORMAL / HARD(CPUの反応の速さと確率)。 | ||
| 15 | Best of three (first to two rounds), 60 s per round, time over = more health wins. Difficulty: EASY / NORMAL / HARD | ||
| 16 | (the CPU's reaction time and probabilities). Esc / P 一時停止 / pause. | ||
| 17 | |||
| 10 | ## 操作 / Controls(一台のキーボードを二人で / two players on one keyboard) | 18 | ## 操作 / Controls(一台のキーボードを二人で / two players on one keyboard) |
| 11 | 19 | ||
| 12 | | | 1P | 2P | | 20 | | | 1P | 2P | |
| @@ -26,5 +34,6 @@ build\games\fighter\Debug\fighter.exe # Windows (or F5 with the "fighter" tar | |||
| 26 | ゲームパッド(GLFW 3.3のゲームパッドAPI):1台目が1P、2台目が2P(十字キーか左スティック、A/X パンチ、B/Y キック)。 | 34 | ゲームパッド(GLFW 3.3のゲームパッドAPI):1台目が1P、2台目が2P(十字キーか左スティック、A/X パンチ、B/Y キック)。 |
| 27 | Gamepads (GLFW 3.3's gamepad API): the first is 1P, the second 2P (d-pad or left stick, A/X punch, B/Y kick). | 35 | Gamepads (GLFW 3.3's gamepad API): the first is 1P, the second 2P (d-pad or left stick, A/X punch, B/Y kick). |
| 28 | 36 | ||
| 29 | F1 判定の箱(食らい = 青、攻撃 = 赤、押し合い = 緑、ソケット = 黄)と状態 / boxes (hurt blue, hit red, push green, | 37 | F1 判定の箱(食らい = 青、攻撃 = 赤、押し合い = 緑、ソケット = 黄)と状態、CPUの意図 / boxes (hurt blue, hit red, |
| 30 | sockets yellow) and states, Esc 終了 / quit. | 38 | push green, sockets yellow), states and the CPU's intent; Esc 一時停止 / pause (タイトルではEscで終了 / Esc quits on the |
| 39 | title screen). | ||
ファイル: a/games/fighter/assets/LICENSE.txt | b/games/fighter/assets/LICENSE.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -9,3 +9,11 @@ fighter.boxes コマごとの食らい判定・攻撃判定・ソケット | |||
| 9 | (made from the skeleton) (chapter 31) | 9 | (made from the skeleton) (chapter 31) |
| 10 | effects.png/.atlas 火花・ガードの火花・砂ぼこり・鉢巻の尾・星・影 / hit and guard sparks, dust, headband tails, stars, | 10 | effects.png/.atlas 火花・ガードの火花・砂ぼこり・鉢巻の尾・星・影 / hit and guard sparks, dust, headband tails, stars, |
| 11 | shadow (chapter 31) | 11 | shadow (chapter 31) |
| 12 | stage_sky.png 舞台の空(夕焼け、視差0.05) / the stage's sunset sky (parallax 0.05) (chapter 32) | ||
| 13 | stage_far.png 遠くの山(視差0.25) / distant mountains (parallax 0.25) (chapter 32) | ||
| 14 | stage_mid.png 鳥居・五重塔・桜・寺の塀(視差0.5) / torii, pagoda, cherry trees, temple wall (parallax 0.5) | ||
| 15 | (chapter 32) | ||
| 16 | stage_ground.png 石畳(視差1、ファイターが立つ面) / the stone paving the fighters stand on (parallax 1) | ||
| 17 | (chapter 32) | ||
| 18 | stage_front.png 手前の灯籠と草(視差1.3、ファイターより前) / foreground lanterns and grass (parallax 1.3, in front of | ||
| 19 | the fighters) (chapter 32) | ||
ファイル: /dev/null | b/games/fighter/assets/stage_far.png
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/games/fighter/assets/stage_front.png
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/games/fighter/assets/stage_ground.png
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/games/fighter/assets/stage_mid.png
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/games/fighter/assets/stage_sky.png
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/games/fighter/src/ai.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,179 @@ | |||
| 1 | // コンピューターの相手 / the computer opponent | ||
| 2 | #include "ai.hh" | ||
| 3 | |||
| 4 | #include <cmath> | ||
| 5 | |||
| 6 | namespace { | ||
| 7 | |||
| 8 | // 考える 反応 ガード 対空 反撃 攻め つなぐ / think react guard anti-air punish aggro combo | ||
| 9 | constexpr AiProfile kProfiles[] = { | ||
| 10 | {34, 24, 0.20f, 0.10f, 0.15f, 0.35f, false}, // Easy | ||
| 11 | {20, 14, 0.50f, 0.35f, 0.45f, 0.55f, false}, // Normal | ||
| 12 | {10, 8, 0.80f, 0.70f, 0.80f, 0.70f, true}, // Hard | ||
| 13 | }; | ||
| 14 | |||
| 15 | constexpr float kAttackRange = 62.0f; // 突き・蹴りが届く距離(足元の間) / where punches and kicks reach (feet to feet) | ||
| 16 | |||
| 17 | } // namespace | ||
| 18 | |||
| 19 | const char *difficultyName(Difficulty d) { | ||
| 20 | switch (d) { | ||
| 21 | case Difficulty::Easy: return "EASY"; | ||
| 22 | case Difficulty::Normal: return "NORMAL"; | ||
| 23 | case Difficulty::Hard: return "HARD"; | ||
| 24 | } | ||
| 25 | return "?"; | ||
| 26 | } | ||
| 27 | |||
| 28 | const AiProfile &aiProfile(Difficulty d) { return kProfiles[static_cast<int>(d)]; } | ||
| 29 | |||
| 30 | AiController::AiController(Difficulty difficulty, std::uint32_t seed) : profile(aiProfile(difficulty)), rng(seed) {} | ||
| 31 | |||
| 32 | void AiController::reset() { | ||
| 33 | intent = Intent::Wait; | ||
| 34 | timer = 30; | ||
| 35 | reaction = -1; | ||
| 36 | sawAttack = punished = pressed = false; | ||
| 37 | } | ||
| 38 | |||
| 39 | const char *AiController::intentName() const { | ||
| 40 | switch (intent) { | ||
| 41 | case Intent::Wait: return "WAIT"; | ||
| 42 | case Intent::Approach: return "APPROACH"; | ||
| 43 | case Intent::Retreat: return "RETREAT"; | ||
| 44 | case Intent::Attack: return "ATTACK"; | ||
| 45 | case Intent::JumpIn: return "JUMP-IN"; | ||
| 46 | case Intent::Guard: return "GUARD"; | ||
| 47 | case Intent::AntiAir: return "ANTI-AIR"; | ||
| 48 | } | ||
| 49 | return "?"; | ||
| 50 | } | ||
| 51 | |||
| 52 | void AiController::setIntent(Intent next, int frames) { | ||
| 53 | intent = next; | ||
| 54 | timer = frames; | ||
| 55 | pressed = false; | ||
| 56 | } | ||
| 57 | |||
| 58 | // 意図の長さ:thinkFramesの lo〜hi 倍からくじで(倍率は普通の20で決めた値。易しいは長く、難しいは短く) | ||
| 59 | // An intent's duration: a draw from lo to hi times thinkFrames (the factors were tuned on Normal's 20; Easy keeps | ||
| 60 | // an intent longer, Hard changes its mind sooner) | ||
| 61 | int AiController::thinkTime(float lo, float hi) { | ||
| 62 | float t = static_cast<float>(profile.thinkFrames); | ||
| 63 | return rng.range(static_cast<int>(std::lround(lo * t)), static_cast<int>(std::lround(hi * t))); | ||
| 64 | } | ||
| 65 | |||
| 66 | // 意図を選ぶ:距離で重みを変えたくじ引き / picks an intent: a weighted draw that depends on the distance | ||
| 67 | void AiController::decide(const Fighter &opponent, float distance) { | ||
| 68 | float a = profile.aggression; | ||
| 69 | float r = rng.unit(); | ||
| 70 | if (distance > 170.0f) { | ||
| 71 | if (r < 0.45f + 0.3f * a) setIntent(Intent::Approach, thinkTime(1.0f, 2.5f)); | ||
| 72 | else if (r < 0.6f + 0.3f * a) setIntent(Intent::JumpIn, 40); | ||
| 73 | else setIntent(Intent::Wait, thinkTime(0.5f, 1.5f)); | ||
| 74 | } else if (distance > kAttackRange) { | ||
| 75 | if (r < 0.35f + 0.3f * a) setIntent(Intent::Approach, thinkTime(0.6f, 1.5f)); | ||
| 76 | else if (r < 0.5f + 0.3f * a) setIntent(Intent::JumpIn, 40); | ||
| 77 | else if (r < 0.8f) setIntent(Intent::Retreat, thinkTime(0.5f, 1.2f)); | ||
| 78 | else setIntent(Intent::Wait, thinkTime(0.4f, 1.0f)); | ||
| 79 | } else { | ||
| 80 | // 近い:攻めるか、下がるか / close: attack or back off | ||
| 81 | if (r < 0.45f + 0.45f * a) { | ||
| 82 | float m = rng.unit(); | ||
| 83 | // 相手がしゃがんでいれば足払いを多めに / sweep more often against a crouching opponent | ||
| 84 | bool low = opponent.controls.down || opponent.state == FighterState::Crouch; | ||
| 85 | planned = m < (low ? 0.2f : 0.4f) ? MoveId::Punch | ||
| 86 | : m < (low ? 0.35f : 0.65f) ? MoveId::Kick | ||
| 87 | : m < (low ? 0.8f : 0.85f) ? MoveId::Sweep | ||
| 88 | : MoveId::CrouchPunch; | ||
| 89 | setIntent(Intent::Attack, moveData(planned).total() + thinkTime(0.2f, 0.7f)); | ||
| 90 | } else if (r < 0.9f) setIntent(Intent::Retreat, thinkTime(0.5f, 1.2f)); | ||
| 91 | else setIntent(Intent::Wait, thinkTime(0.3f, 0.8f)); | ||
| 92 | } | ||
| 93 | } | ||
| 94 | |||
| 95 | Controls AiController::think(const Fighter &self, const Fighter &opponent) { | ||
| 96 | Controls c; | ||
| 97 | float dx = opponent.position.x - self.position.x; | ||
| 98 | float distance = std::abs(dx); | ||
| 99 | auto hold = [&](bool towards) { | ||
| 100 | if ((dx > 0.0f) == towards) c.right = true; | ||
| 101 | else c.left = true; | ||
| 102 | }; | ||
| 103 | |||
| 104 | // 1. 見る(遅れて反応する):相手が技を出し始めたら、反応の時間の後にガードするか決める | ||
| 105 | // 1. Perceive (with a delay): when the opponent starts a move, decide after the reaction time whether to guard | ||
| 106 | MovePhase op = opponent.phase(); | ||
| 107 | if (op == MovePhase::Startup && !sawAttack) { | ||
| 108 | sawAttack = true; | ||
| 109 | reaction = profile.reactionFrames; | ||
| 110 | } | ||
| 111 | if (op == MovePhase::None) sawAttack = false; | ||
| 112 | if (reaction >= 0 && --reaction < 0 && opponent.move) { | ||
| 113 | // 飛び込み(空中の技)は対空を狙うこともある / a jump-in may be answered with an anti-air | ||
| 114 | bool air = opponent.move->air; | ||
| 115 | if (air && distance < 120.0f && rng.chance(profile.antiAirChance)) setIntent(Intent::AntiAir, 20); | ||
| 116 | else if (distance < 170.0f && rng.chance(profile.blockChance)) { | ||
| 117 | guardLow = opponent.move->height == AttackHeight::Low; | ||
| 118 | setIntent(Intent::Guard, opponent.move->startup + opponent.move->active + 6); | ||
| 119 | } | ||
| 120 | } | ||
| 121 | // 2. 反撃:相手が近くで硬直していれば(一度だけ判断) / 2. Punish: the opponent is recovering nearby (decided once) | ||
| 122 | if (op != MovePhase::Recovery) punished = false; | ||
| 123 | if (op == MovePhase::Recovery && !punished && self.actionable() && distance < kAttackRange + 4.0f) { | ||
| 124 | punished = true; | ||
| 125 | if (rng.chance(profile.punishChance)) { | ||
| 126 | planned = MoveId::Punch; | ||
| 127 | setIntent(Intent::Attack, moveData(planned).total() + 4); | ||
| 128 | } | ||
| 129 | } | ||
| 130 | // 3. つなぎ(強いときだけ):自分の突きが当たったら、硬直の終わりにもう一度押す(入力バッファが拾う) | ||
| 131 | // 3. Links (hard only): when our punch hit, press again near the end of the recovery (the input buffer catches it) | ||
| 132 | if (profile.combos && self.state == FighterState::Attack && self.moveHit && self.moveId == MoveId::Punch && | ||
| 133 | opponent.state == FighterState::Hitstun && self.stateTime == self.move->total() - 3) | ||
| 134 | c.punch = true; | ||
| 135 | |||
| 136 | // 4. 決める:意図の時間が切れて、自由に動けるとき / 4. Decide: when the intent's time is up and the fighter is free | ||
| 137 | if (--timer <= 0 && self.actionable()) decide(opponent, distance); | ||
| 138 | |||
| 139 | // 5. 実行 / 5. Execute | ||
| 140 | switch (intent) { | ||
| 141 | case Intent::Wait: | ||
| 142 | break; | ||
| 143 | case Intent::Approach: | ||
| 144 | hold(true); | ||
| 145 | if (distance < kAttackRange) setIntent(Intent::Wait, 2); // 着いた:すぐ次を決める / arrived: decide again soon | ||
| 146 | break; | ||
| 147 | case Intent::Retreat: | ||
| 148 | hold(false); | ||
| 149 | break; | ||
| 150 | case Intent::Attack: | ||
| 151 | if (!pressed && self.actionable()) { | ||
| 152 | pressed = true; | ||
| 153 | c.down = planned == MoveId::Sweep || planned == MoveId::CrouchPunch; | ||
| 154 | (planned == MoveId::Kick || planned == MoveId::Sweep ? c.kick : c.punch) = true; | ||
| 155 | } | ||
| 156 | break; | ||
| 157 | case Intent::JumpIn: | ||
| 158 | if (!pressed && self.actionable()) { | ||
| 159 | pressed = true; | ||
| 160 | c.up = true; | ||
| 161 | hold(true); | ||
| 162 | } | ||
| 163 | // 落ち始めて近ければ蹴る / kick once falling and close | ||
| 164 | if (self.state == FighterState::Air && self.velocity.y > -120.0f && distance < 90.0f) c.kick = true; | ||
| 165 | if (self.actionable() && pressed && timer < 30) setIntent(Intent::Wait, 4); | ||
| 166 | break; | ||
| 167 | case Intent::Guard: | ||
| 168 | hold(false); | ||
| 169 | c.down = guardLow; | ||
| 170 | break; | ||
| 171 | case Intent::AntiAir: | ||
| 172 | if (!pressed && self.actionable() && distance < 85.0f) { | ||
| 173 | pressed = true; | ||
| 174 | c.kick = true; | ||
| 175 | } | ||
| 176 | break; | ||
| 177 | } | ||
| 178 | return c; | ||
| 179 | } | ||
ファイル: /dev/null | b/games/fighter/src/ai.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,55 @@ | |||
| 1 | // コンピューターの相手:人と同じControlsを作る「見えないプレイヤー」。状態(意図)と決める間隔(タイマー)で動き、 | ||
| 2 | // 反応の遅れと確率で強さが変わる | ||
| 3 | // The computer opponent: an invisible player that produces the same Controls a human does. It runs on states | ||
| 4 | // (intents) and a decision timer; reaction delays and probabilities set the difficulty | ||
| 5 | #pragma once | ||
| 6 | |||
| 7 | #include "controls.hh" | ||
| 8 | #include "fighter.hh" | ||
| 9 | |||
| 10 | #include "engine/rng.hh" | ||
| 11 | |||
| 12 | #include <cstdint> | ||
| 13 | |||
| 14 | enum class Difficulty { Easy, Normal, Hard }; | ||
| 15 | const char *difficultyName(Difficulty d); | ||
| 16 | |||
| 17 | // 強さの数値。時間はフレーム / the difficulty numbers; times in frames | ||
| 18 | struct AiProfile { | ||
| 19 | int thinkFrames; // 意図を続ける長さの基準(普通 = 20) / the base for how long an intent lasts (Normal = 20) | ||
| 20 | int reactionFrames; // 相手の技を見てから反応するまで(人なら約12〜15) / from seeing a move to reacting (a human | ||
| 21 | // needs about 12-15) | ||
| 22 | float blockChance; // 見えた技をガードする確率 / chance to guard a move it saw | ||
| 23 | float antiAirChance; // 飛び込みを蹴りで落とす確率 / chance to kick a jump-in out of the air | ||
| 24 | float punishChance; // 相手の硬直に反撃する確率 / chance to punish recovery | ||
| 25 | float aggression; // 近づいて攻める割合 / how often it closes in and attacks | ||
| 26 | bool combos; // 突き → 突きをつなぐ / links punch → punch | ||
| 27 | }; | ||
| 28 | const AiProfile &aiProfile(Difficulty d); | ||
| 29 | |||
| 30 | class AiController { | ||
| 31 | public: | ||
| 32 | AiController(Difficulty difficulty, std::uint32_t seed); | ||
| 33 | // 1ステップ分の入力を作る(ファイターの公開されている状態だけを見る:ずるはしない) | ||
| 34 | // Makes one step of input (looking only at the fighters' public state: no cheating with hidden data) | ||
| 35 | Controls think(const Fighter &self, const Fighter &opponent); | ||
| 36 | void reset(); | ||
| 37 | const char *intentName() const; | ||
| 38 | |||
| 39 | private: | ||
| 40 | enum class Intent { Wait, Approach, Retreat, Attack, JumpIn, Guard, AntiAir }; | ||
| 41 | void decide(const Fighter &opponent, float distance); | ||
| 42 | void setIntent(Intent next, int frames); | ||
| 43 | int thinkTime(float lo, float hi); | ||
| 44 | |||
| 45 | const AiProfile &profile; | ||
| 46 | Rng rng; | ||
| 47 | Intent intent = Intent::Wait; | ||
| 48 | int timer = 30; // 今の意図の残り / frames left for the current intent | ||
| 49 | int reaction = -1; // 反応までの残り(-1 = なし) / frames until the reaction (-1 = none) | ||
| 50 | bool guardLow = false; | ||
| 51 | bool sawAttack = false; // 相手の今の技をもう見た / already saw the opponent's current move | ||
| 52 | bool punished = false; // 相手の今の硬直にもう反撃した / already punished the current recovery | ||
| 53 | bool pressed = false; // この意図でボタンをもう押した / already pressed the button for this intent | ||
| 54 | MoveId planned = MoveId::Punch; | ||
| 55 | }; | ||
ファイル: a/games/fighter/src/fight_scene.cc | b/games/fighter/src/fight_scene.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,63 +1,41 @@ | |||
| 1 | // 対戦の場面(第31章:技の当たり、ヒットストップ、体力、エフェクト。KOすると練習を仕切り直す) | 1 | // 対戦の場面(第32章:スクロールする舞台、CPU、ラウンド) / the fight scene (chapter 32: scrolling stage, CPU, rounds) |
| 2 | // The fight scene (chapter 31: hits, hit stop, health, effects; a KO restarts the training) | ||
| 3 | #include "fight_scene.hh" | 2 | #include "fight_scene.hh" |
| 4 | 3 | ||
| 4 | #include "hud.hh" | ||
| 5 | #include "scenes.hh" | ||
| 6 | |||
| 5 | #include "engine/collision.hh" | 7 | #include "engine/collision.hh" |
| 6 | 8 | ||
| 7 | #include <algorithm> | 9 | #include <algorithm> |
| 8 | #include <cmath> | 10 | #include <cmath> |
| 9 | #include <cstdio> | 11 | #include <cstdio> |
| 12 | #include <memory> | ||
| 10 | #include <string> | 13 | #include <string> |
| 11 | #include <string_view> | ||
| 12 | 14 | ||
| 13 | namespace { | 15 | namespace { |
| 14 | 16 | ||
| 15 | constexpr float kStageLeft = 16.0f; | 17 | constexpr float kStageLeft = 12.0f; // 舞台の端の壁 / the walls at the stage ends |
| 16 | constexpr float kStageRight = 624.0f; | 18 | constexpr float kStageRight = kStageWidth - 12.0f; |
| 17 | constexpr Vec2 kStart[2] = {{200.0f, kGroundY}, {440.0f, kGroundY}}; | 19 | constexpr float kViewMargin = 8.0f; // 画面の端からの余白(画面の端も壁) / margin to the view edges |
| 18 | 20 | // (the view edges are walls too) | |
| 19 | constexpr Vec4 kBeam = hexColor(0x3b2a2eff), kBeamLight = hexColor(0x5a4040ff); | 21 | constexpr Vec2 kStart[2] = {{kStageWidth * 0.5f - 110.0f, kGroundY}, {kStageWidth * 0.5f + 110.0f, kGroundY}}; |
| 20 | constexpr Vec4 kPlaster = hexColor(0xdccdaeff), kPlasterShade = hexColor(0xc4b393ff); | 22 | constexpr int kIntroFrames = 100; |
| 21 | constexpr Vec4 kShoji = hexColor(0xf4ecd8ff), kLattice = hexColor(0x8a6a50ff); | 23 | constexpr int kFinishFrames = 230; |
| 22 | constexpr Vec4 kWainscot = hexColor(0x6e4a36ff), kWainscotDark = hexColor(0x553626ff); | 24 | constexpr int kWinPoseAt = 70; |
| 23 | constexpr Vec4 kPlankA = hexColor(0xb07c50ff), kPlankB = hexColor(0xa16f47ff), kPlankLine = hexColor(0x6e4630ff); | 25 | const char *const kJapaneseNames[2] = {"ハヤテ", "ジン"}; |
| 24 | constexpr Vec4 kOutline = hexColor(0x1b1726ff); | ||
| 25 | constexpr Vec4 kText = hexColor(0xfff4d8ff), kGold = hexColor(0xf2c14eff); | ||
| 26 | |||
| 27 | void clampToStage(Fighter &f) { | ||
| 28 | Rect b = f.pushbox(); | ||
| 29 | if (b.left() < kStageLeft) f.position.x += kStageLeft - b.left(); | ||
| 30 | if (b.right() > kStageRight) f.position.x -= b.right() - kStageRight; | ||
| 31 | } | ||
| 32 | 26 | ||
| 33 | bool atWall(const Fighter &f) { | 27 | void clampX(Fighter &f, float left, float right) { |
| 34 | Rect b = f.pushbox(); | 28 | Rect b = f.pushbox(); |
| 35 | return b.left() <= kStageLeft + 0.5f || b.right() >= kStageRight - 0.5f; | 29 | if (b.left() < left) f.position.x += left - b.left(); |
| 30 | if (b.right() > right) f.position.x -= b.right() - right; | ||
| 36 | } | 31 | } |
| 37 | 32 | ||
| 38 | // 二つの箱の重なり(火花を出す場所) / the overlap of two boxes (where the spark goes) | ||
| 39 | Rect intersection(const Rect &a, const Rect &b) { | 33 | Rect intersection(const Rect &a, const Rect &b) { |
| 40 | float l = std::max(a.left(), b.left()), t = std::max(a.top(), b.top()); | 34 | float l = std::max(a.left(), b.left()), t = std::max(a.top(), b.top()); |
| 41 | float r = std::min(a.right(), b.right()), bt = std::min(a.bottom(), b.bottom()); | 35 | float r = std::min(a.right(), b.right()), bt = std::min(a.bottom(), b.bottom()); |
| 42 | return {l, t, r - l, bt - t}; | 36 | return {l, t, r - l, bt - t}; |
| 43 | } | 37 | } |
| 44 | 38 | ||
| 45 | // 大きな文字(K.O.など):8方向に輪郭を描いてから本体 / big text (K.O. and so on): an outline in 8 directions, then | ||
| 46 | // the text itself | ||
| 47 | void drawBigText(SpriteBatch &b, const Font &font, std::string_view text, Vec2 centre, Vec4 color, float scale) { | ||
| 48 | Vec2 size = font.measure(text, scale); | ||
| 49 | Vec2 at = {centre.x, std::round(centre.y - size.y * 0.5f)}; | ||
| 50 | TextStyle s = {.color = kOutline, .scale = scale, .align = TextAlign::Centre, .layer = 11.0f}; | ||
| 51 | for (Vec2 d : {Vec2{-2, -2}, Vec2{0, -2}, Vec2{2, -2}, Vec2{-2, 0}, Vec2{2, 0}, Vec2{-2, 2}, Vec2{0, 2}, Vec2{2, 2}, | ||
| 52 | Vec2{3, 4}, Vec2{0, 4}}) | ||
| 53 | font.draw(b, text, at + d, s); | ||
| 54 | s.color = color; | ||
| 55 | s.layer = 11.5f; | ||
| 56 | font.draw(b, text, at, s); | ||
| 57 | } | ||
| 58 | |||
| 59 | // 体力ゲージ:中央側に寄せて、外側から減る。白い「跡」は少し遅れて追いかける | ||
| 60 | // A health bar: anchored at the center side, it drains from the outer end. The white "trail" follows a little later | ||
| 61 | void drawHealthBar(SpriteBatch &b, Rect r, float health, float trail, bool rightSide) { | 39 | void drawHealthBar(SpriteBatch &b, Rect r, float health, float trail, bool rightSide) { |
| 62 | b.drawRect({r.x - 2, r.y - 2, r.w + 4, r.h + 4}, kOutline, 10.0f); | 40 | b.drawRect({r.x - 2, r.y - 2, r.w + 4, r.h + 4}, kOutline, 10.0f); |
| 63 | b.drawRect(r, hexColor(0x4a2434ff), 10.1f); | 41 | b.drawRect(r, hexColor(0x4a2434ff), 10.1f); |
| @@ -68,52 +46,73 @@ void drawHealthBar(SpriteBatch &b, Rect r, float health, float trail, bool right | |||
| 68 | b.drawRect(part(trail), hexColor(0xf6f0e8ff), 10.2f); | 46 | b.drawRect(part(trail), hexColor(0xf6f0e8ff), 10.2f); |
| 69 | bool low = health <= kMaxHealth * 0.25f; | 47 | bool low = health <= kMaxHealth * 0.25f; |
| 70 | Rect h = part(health); | 48 | Rect h = part(health); |
| 71 | b.drawRect(h, low ? hexColor(0xe8483cff) : kGold, 10.3f); | 49 | b.drawRect(h, low ? kRed : kGold, 10.3f); |
| 72 | b.drawRect({h.x, h.y, h.w, 2}, low ? hexColor(0xff8a70ff) : hexColor(0xffe48aff), 10.4f); | 50 | b.drawRect({h.x, h.y, h.w, 2}, low ? hexColor(0xff8a70ff) : hexColor(0xffe48aff), 10.4f); |
| 73 | b.drawRect({h.x, h.bottom() - 2, h.w, 2}, low ? hexColor(0xa82a30ff) : hexColor(0xc98a26ff), 10.4f); | 51 | b.drawRect({h.x, h.bottom() - 2, h.w, 2}, low ? hexColor(0xa82a30ff) : hexColor(0xc98a26ff), 10.4f); |
| 74 | } | 52 | } |
| 75 | 53 | ||
| 76 | } // namespace | 54 | } // namespace |
| 77 | 55 | ||
| 78 | FightScene::FightScene(Game &game) | 56 | FightScene::FightScene(Game &game, MatchSettings matchSettings) |
| 79 | : g(game), camera(Camera2D::screen(kViewSize)), | 57 | : g(game), settings(matchSettings), |
| 80 | fighters{Fighter(*game.fighters[0], *game.effects, *game.frameData, "HAYATE", "tail_hayate", kStart[0], 1.0f), | 58 | fighters{Fighter(*game.fighters[0], *game.effects, *game.frameData, "HAYATE", "tail_hayate", kStart[0], 1.0f), |
| 81 | Fighter(*game.fighters[1], *game.effects, *game.frameData, "JIN", "tail_jin", kStart[1], -1.0f)}, | 59 | Fighter(*game.fighters[1], *game.effects, *game.frameData, "JIN", "tail_jin", kStart[1], -1.0f)}, |
| 82 | effects(*game.effects) {} | 60 | effects(*game.effects) { |
| 61 | // CPUの担当:1P対CPUなら2P、CPU対CPUなら両方。種は固定(同じ入力なら同じ試合) / who the computer plays: 2P in | ||
| 62 | // 1P vs CPU, both in CPU vs CPU. Fixed seeds (the same input gives the same match) | ||
| 63 | if (settings.mode == Mode::VsCpu || settings.mode == Mode::CpuVsCpu) ai[1].emplace(settings.difficulty, 3202u); | ||
| 64 | if (settings.mode == Mode::CpuVsCpu) ai[0].emplace(settings.difficulty, 3201u); | ||
| 65 | startRound(); | ||
| 66 | } | ||
| 83 | 67 | ||
| 84 | void FightScene::resetRound() { | 68 | void FightScene::startRound() { |
| 85 | fighters[0].reset(kStart[0], 1.0f); | ||
| 86 | fighters[1].reset(kStart[1], -1.0f); | ||
| 87 | effects.clear(); | ||
| 88 | for (int i = 0; i < 2; ++i) { | 69 | for (int i = 0; i < 2; ++i) { |
| 70 | fighters[i].reset(kStart[i], i == 0 ? 1.0f : -1.0f); | ||
| 89 | trail[i] = kMaxHealth; | 71 | trail[i] = kMaxHealth; |
| 90 | comboTime[i] = 0; | 72 | comboTime[i] = 0; |
| 73 | if (ai[i]) ai[i]->reset(); | ||
| 91 | } | 74 | } |
| 75 | effects.clear(); | ||
| 92 | hitstop = shake = koTime = 0; | 76 | hitstop = shake = koTime = 0; |
| 93 | victim = -1; | 77 | victim = -1; |
| 78 | timer = kRoundSeconds * 60; | ||
| 79 | roundWinner = -1; | ||
| 80 | timeOver = false; | ||
| 81 | phase = settings.mode == Mode::Training ? RoundPhase::Fight : RoundPhase::Intro; | ||
| 82 | phaseTime = 0; | ||
| 83 | } | ||
| 84 | |||
| 85 | // 一時停止が上に載った:補間で震えないように前の位置 = 今 / the pause went on top: previous = current, so the | ||
| 86 | // interpolation does not wobble | ||
| 87 | void FightScene::pause() { | ||
| 88 | for (Fighter &f : fighters) f.savePrevious(); | ||
| 94 | } | 89 | } |
| 95 | 90 | ||
| 96 | void FightScene::update(float dt) { | 91 | void FightScene::update(float dt) { |
| 97 | ++steps; | 92 | ++steps; |
| 98 | Input &in = g.input; | 93 | Input &in = g.input; |
| 99 | if (in.pressed(GLFW_KEY_ESCAPE)) { | 94 | if (in.pressed(GLFW_KEY_ESCAPE) || in.pressed(GLFW_KEY_P)) { |
| 100 | scenes().pop(); | 95 | scenes().push(std::make_unique<PauseScene>(g)); |
| 101 | return; | 96 | return; |
| 102 | } | 97 | } |
| 103 | if (in.pressed(GLFW_KEY_F1)) g.showBoxes = !g.showBoxes; | 98 | if (in.pressed(GLFW_KEY_F1)) g.showBoxes = !g.showBoxes; |
| 104 | 99 | ||
| 105 | Controls controls[2] = {readControls(in, 0, pads[0]), readControls(in, 1, pads[1])}; | 100 | // 入力:人はキーボードとパッド、CPUはAiController。どちらも同じControlsになる / input: humans from the keyboard and |
| 106 | // バッファはヒットストップ中も記録する:止まっている間に押した技が、動き出した瞬間に出る | 101 | // pads, the CPU from AiController; both become the same Controls |
| 107 | // The buffers record during hit stop too: a move pressed while frozen comes out the moment things move again | 102 | Controls controls[2]; |
| 103 | for (int i = 0; i < 2; ++i) { | ||
| 104 | Controls human = readControls(in, i, pads[i]); | ||
| 105 | controls[i] = ai[i] ? ai[i]->think(fighters[i], fighters[1 - i]) : human; | ||
| 106 | if (phase != RoundPhase::Fight) controls[i] = {}; // 始まりと決着の間は動けない / no control before and after | ||
| 107 | } | ||
| 108 | for (int i = 0; i < 2; ++i) { | 108 | for (int i = 0; i < 2; ++i) { |
| 109 | fighters[i].buffer.record(controls[i]); | 109 | fighters[i].buffer.record(controls[i]); |
| 110 | fighters[i].savePrevious(); // 止まっていても前の位置 = 今(補間で震えない) / even when frozen (no wobble) | 110 | fighters[i].savePrevious(); |
| 111 | } | 111 | } |
| 112 | effects.update(dt); | 112 | effects.update(dt); |
| 113 | g.stage->update(dt); | ||
| 113 | for (int i = 0; i < 2; ++i) comboTime[i] = std::max(0, comboTime[i] - 1); | 114 | for (int i = 0; i < 2; ++i) comboTime[i] = std::max(0, comboTime[i] - 1); |
| 114 | shake = std::max(0, shake - 1); | 115 | shake = std::max(0, shake - 1); |
| 115 | // ヒットストップ:当たった瞬間、数フレーム全部止める(重さが伝わる)。火花のアニメーションだけ進む | ||
| 116 | // Hit stop: everything freezes for a few frames on contact (it sells the impact). Only the sparks keep animating | ||
| 117 | if (hitstop > 0) { | 116 | if (hitstop > 0) { |
| 118 | --hitstop; | 117 | --hitstop; |
| 119 | return; | 118 | return; |
| @@ -123,30 +122,27 @@ void FightScene::update(float dt) { | |||
| 123 | float startX[2] = {fighters[0].position.x, fighters[1].position.x}; | 122 | float startX[2] = {fighters[0].position.x, fighters[1].position.x}; |
| 124 | bool threat[2]; | 123 | bool threat[2]; |
| 125 | for (int i = 0; i < 2; ++i) { | 124 | for (int i = 0; i < 2; ++i) { |
| 126 | // 相手が近く(150ピクセル)で技の発生か持続にいる / the opponent is in a move's startup or active frames nearby | ||
| 127 | const Fighter &o = fighters[1 - i]; | 125 | const Fighter &o = fighters[1 - i]; |
| 128 | MovePhase p = o.phase(); | 126 | MovePhase p = o.phase(); |
| 129 | threat[i] = (p == MovePhase::Startup || p == MovePhase::Active) && std::abs(o.position.x - startX[i]) < 150.0f; | 127 | threat[i] = (p == MovePhase::Startup || p == MovePhase::Active) && std::abs(o.position.x - startX[i]) < 150.0f; |
| 130 | } | 128 | } |
| 131 | for (int i = 0; i < 2; ++i) fighters[i].update(dt, controls[i], startX[1 - i], threat[i]); | 129 | for (int i = 0; i < 2; ++i) fighters[i].update(dt, controls[i], startX[1 - i], threat[i]); |
| 132 | separate(); | 130 | separate(); |
| 131 | keepInView(); | ||
| 133 | resolveHits(); | 132 | resolveHits(); |
| 134 | for (Fighter &f : fighters) | 133 | for (Fighter &f : fighters) |
| 135 | if (f.landed) effects.dust(f.position, f.facing); | 134 | if (f.landed) effects.dust(f.position, f.facing); |
| 136 | |||
| 137 | // 体力の跡:0.5秒待ってから減る / the health trail: waits half a second, then drains | ||
| 138 | for (int i = 0; i < 2; ++i) { | 135 | for (int i = 0; i < 2; ++i) { |
| 139 | if (trailDelay[i] > 0) --trailDelay[i]; | 136 | if (trailDelay[i] > 0) --trailDelay[i]; |
| 140 | else trail[i] = std::max(static_cast<float>(fighters[i].health), trail[i] - 0.6f); | 137 | else trail[i] = std::max(static_cast<float>(fighters[i].health), trail[i] - 0.6f); |
| 141 | } | 138 | } |
| 142 | // 練習:KOから3秒で仕切り直し / training: restart 3 s after a KO | 139 | updateRound(); |
| 143 | if (koTime > 0 && ++koTime > 180) resetRound(); | ||
| 144 | } | 140 | } |
| 145 | 141 | ||
| 146 | void FightScene::separate() { | 142 | void FightScene::separate() { |
| 147 | Fighter &a = fighters[0], &b = fighters[1]; | 143 | Fighter &a = fighters[0], &b = fighters[1]; |
| 148 | clampToStage(a); | 144 | clampX(a, kStageLeft, kStageRight); |
| 149 | clampToStage(b); | 145 | clampX(b, kStageLeft, kStageRight); |
| 150 | Rect ra = a.pushbox(), rb = b.pushbox(); | 146 | Rect ra = a.pushbox(), rb = b.pushbox(); |
| 151 | if (!overlaps(ra, rb)) return; | 147 | if (!overlaps(ra, rb)) return; |
| 152 | float overlap = std::min(ra.right(), rb.right()) - std::max(ra.left(), rb.left()); | 148 | float overlap = std::min(ra.right(), rb.right()) - std::max(ra.left(), rb.left()); |
| @@ -154,17 +150,32 @@ void FightScene::separate() { | |||
| 154 | a.position.x += dir * overlap * 0.5f; | 150 | a.position.x += dir * overlap * 0.5f; |
| 155 | b.position.x -= dir * overlap * 0.5f; | 151 | b.position.x -= dir * overlap * 0.5f; |
| 156 | float ax = a.position.x, bx = b.position.x; | 152 | float ax = a.position.x, bx = b.position.x; |
| 157 | clampToStage(a); | 153 | clampX(a, kStageLeft, kStageRight); |
| 158 | clampToStage(b); | 154 | clampX(b, kStageLeft, kStageRight); |
| 159 | float da = a.position.x - ax, db = b.position.x - bx; | 155 | float da = a.position.x - ax, db = b.position.x - bx; |
| 160 | b.position.x += da; | 156 | b.position.x += da; |
| 161 | a.position.x += db; | 157 | a.position.x += db; |
| 162 | } | 158 | } |
| 163 | 159 | ||
| 164 | // 当たり判定:攻撃側の攻撃判定(持続フレーム)と相手の食らい判定が重なったら当たり。 | 160 | // 画面の端も壁:カメラは二人の真ん中を追い、舞台の中に収まる。二人ともその画面の中にいなければならない |
| 165 | // 先に二人分を調べてから当てる:同時に当たったら相打ち | 161 | // The view edges are walls too: the camera follows the midpoint, clamped to the stage, and both fighters must stay |
| 166 | // Hit detection: the attacker's hit box (active frames) overlapping one of the opponent's hurt boxes is a hit. | 162 | // inside that view |
| 167 | // Both directions are checked first and applied afterwards: simultaneous hits trade | 163 | void FightScene::keepInView() { |
| 164 | float centre = Stage::clampCamera(0.5f * (fighters[0].position.x + fighters[1].position.x), kViewSize.x); | ||
| 165 | float left = centre - kViewSize.x * 0.5f + kViewMargin, right = centre + kViewSize.x * 0.5f - kViewMargin; | ||
| 166 | for (Fighter &f : fighters) clampX(f, std::max(left, kStageLeft), std::min(right, kStageRight)); | ||
| 167 | } | ||
| 168 | |||
| 169 | Camera2D FightScene::worldCamera(float alpha) const { | ||
| 170 | // 描くときは補間した位置の真ん中 / when drawing: the midpoint of the interpolated positions | ||
| 171 | float a = lerp(fighters[0].previous, fighters[0].position, alpha).x; | ||
| 172 | float b = lerp(fighters[1].previous, fighters[1].position, alpha).x; | ||
| 173 | Camera2D c = Camera2D::screen(kViewSize); | ||
| 174 | c.centre.x = std::round(Stage::clampCamera(0.5f * (a + b), kViewSize.x)); | ||
| 175 | c.pixelSnap = true; | ||
| 176 | return c; | ||
| 177 | } | ||
| 178 | |||
| 168 | void FightScene::resolveHits() { | 179 | void FightScene::resolveHits() { |
| 169 | // 技はここで覚える:相打ちだと、一つ目のtakeHitが二人目の技(move)を消してしまう | 180 | // 技はここで覚える:相打ちだと、一つ目のtakeHitが二人目の技(move)を消してしまう |
| 170 | // The move is remembered here: in a trade the first takeHit clears the second attacker's move | 181 | // The move is remembered here: in a trade the first takeHit clears the second attacker's move |
| @@ -186,6 +197,7 @@ void FightScene::resolveHits() { | |||
| 186 | break; | 197 | break; |
| 187 | } | 198 | } |
| 188 | } | 199 | } |
| 200 | float viewCentre = Stage::clampCamera(0.5f * (fighters[0].position.x + fighters[1].position.x), kViewSize.x); | ||
| 189 | float push[2] = {0.0f, 0.0f}; // 壁際の押し返し(後でまとめて) / corner push-backs (applied at the end) | 201 | float push[2] = {0.0f, 0.0f}; // 壁際の押し返し(後でまとめて) / corner push-backs (applied at the end) |
| 190 | for (int c = 0; c < count; ++c) { | 202 | for (int c = 0; c < count; ++c) { |
| 191 | int i = contacts[c].attacker; | 203 | int i = contacts[c].attacker; |
| @@ -194,9 +206,12 @@ void FightScene::resolveHits() { | |||
| 194 | a.confirmHit(); | 206 | a.confirmHit(); |
| 195 | bool wasHit = v.state == FighterState::Hitstun; | 207 | bool wasHit = v.state == FighterState::Hitstun; |
| 196 | HitResult r = v.takeHit(m, a.facing, contacts[c].blocked); | 208 | HitResult r = v.takeHit(m, a.facing, contacts[c].blocked); |
| 197 | // 壁際:相手が下がれないので自分が下がる(壁で永久に固めさせない) / at the wall the opponent cannot move back, | 209 | // 壁(舞台の端か画面の端)を背にした相手には、自分が下がる / against an opponent with their back to a wall (the |
| 198 | // so the attacker is pushed back instead (no endless corner pressure) | 210 | // stage end or the view edge) the attacker is pushed back instead |
| 199 | if (atWall(v)) push[i] = m.knockback * 0.7f; | 211 | Rect vb = v.pushbox(); |
| 212 | float wallLeft = std::max(kStageLeft, viewCentre - kViewSize.x * 0.5f + kViewMargin); | ||
| 213 | float wallRight = std::min(kStageRight, viewCentre + kViewSize.x * 0.5f - kViewMargin); | ||
| 214 | if (vb.left() <= wallLeft + 0.5f || vb.right() >= wallRight - 0.5f) push[i] = m.knockback * 0.7f; | ||
| 200 | bool blocked = r == HitResult::Blocked; | 215 | bool blocked = r == HitResult::Blocked; |
| 201 | int stop = blocked ? m.hitstop - 3 : m.hitstop; | 216 | int stop = blocked ? m.hitstop - 3 : m.hitstop; |
| 202 | if (r == HitResult::KO) { | 217 | if (r == HitResult::KO) { |
| @@ -208,9 +223,7 @@ void FightScene::resolveHits() { | |||
| 208 | top = i; | 223 | top = i; |
| 209 | bool heavy = m.damage >= 10 || r == HitResult::KO; | 224 | bool heavy = m.damage >= 10 || r == HitResult::KO; |
| 210 | if (heavy && !blocked) shake = stop; | 225 | if (heavy && !blocked) shake = stop; |
| 211 | Rect w = contacts[c].where; | 226 | effects.spark(contacts[c].where.centre(), blocked, heavy); |
| 212 | effects.spark(w.centre(), blocked, heavy); | ||
| 213 | // 記録(台本で動かしたときの確認に) / a log line (to check scripted runs) | ||
| 214 | static const char *const kResult[] = {"hit", "blocked", "KO"}; | 227 | static const char *const kResult[] = {"hit", "blocked", "KO"}; |
| 215 | printf("step %d: %s %s -> %s %s, hp %d, combo %d, hit stop %d\n", steps, a.name.c_str(), m.name, | 228 | printf("step %d: %s %s -> %s %s, hp %d, combo %d, hit stop %d\n", steps, a.name.c_str(), m.name, |
| 216 | v.name.c_str(), kResult[static_cast<int>(r)], v.health, blocked ? 0 : v.combo, stop); | 229 | v.name.c_str(), kResult[static_cast<int>(r)], v.health, blocked ? 0 : v.combo, stop); |
| @@ -229,142 +242,194 @@ void FightScene::resolveHits() { | |||
| 229 | if (push[i] > 0.0f) fighters[i].pushBack(push[i]); | 242 | if (push[i] > 0.0f) fighters[i].pushBack(push[i]); |
| 230 | } | 243 | } |
| 231 | 244 | ||
| 232 | void FightScene::drawBackground() { | 245 | void FightScene::finishRound(int winner, bool byTime) { |
| 233 | SpriteBatch &b = g.batch; | 246 | phase = RoundPhase::Finish; |
| 234 | // 画面より8ピクセルずつ広く描く:画面が揺れても端に隙間ができない / drawn 8 pixels wider than the view on every side, | 247 | phaseTime = 0; |
| 235 | // so the screen shake never opens a gap at the edges | 248 | roundWinner = winner; |
| 236 | // 梁と漆喰の壁 / beams and the plaster wall | 249 | timeOver = byTime; |
| 237 | b.drawRect({-8, -8, 656, 376}, kPlaster); | 250 | if (winner >= 0) ++wins[winner]; |
| 238 | b.drawRect({-8, -8, 656, 42}, kBeam); | 251 | printf("round %d: %s%s (wins %d-%d)\n", round, winner < 0 ? "draw" : fighters[winner].name.c_str(), |
| 239 | b.drawRect({-8, 34, 656, 3}, kBeamLight); | 252 | byTime ? " by time" : "", wins[0], wins[1]); |
| 240 | b.drawRect({-8, 37, 656, 4}, kPlasterShade); | 253 | } |
| 241 | for (float x = 0; x < 640; x += 160) { | 254 | |
| 242 | b.drawRect({x, 37, 12, 200}, kBeam); // 柱 / pillars | 255 | // ラウンドの流れ(ステップごと)。ヒットストップ中は進まない / the round flow (per step); frozen during hit stop |
| 243 | b.drawRect({x + 9, 37, 3, 200}, kBeamLight); | 256 | void FightScene::updateRound() { |
| 244 | } | 257 | ++phaseTime; |
| 245 | // 障子:格子の窓 / shoji: lattice windows | 258 | if (settings.mode == Mode::Training) { |
| 246 | for (float x : {28.0f, 188.0f, 348.0f, 508.0f}) { | 259 | if (koTime > 0 && ++koTime > 180) startRound(); // 練習:3秒後に仕切り直し / training: restart after 3 s |
| 247 | if (x == 188.0f) continue; // 真ん中は掛け軸 / scroll in the middle instead | 260 | return; |
| 248 | Rect w = {x, 62, 104, 120}; | ||
| 249 | b.drawRect(w, kLattice); | ||
| 250 | b.drawRect({w.x + 3, w.y + 3, w.w - 6, w.h - 6}, kShoji); | ||
| 251 | for (float lx = w.x + 3 + 24; lx < w.right() - 4; lx += 25) b.drawRect({lx, w.y + 3, 2, w.h - 6}, kLattice); | ||
| 252 | for (float ly = w.y + 3 + 28; ly < w.bottom() - 4; ly += 29) b.drawRect({w.x + 3, ly, w.w - 6, 2}, kLattice); | ||
| 253 | } | 261 | } |
| 254 | // 掛け軸「練習」 / a hanging scroll: "practice" | 262 | bool ko[2] = {fighters[0].health == 0, fighters[1].health == 0}; |
| 255 | b.drawRect({212, 52, 64, 6}, kBeam); | 263 | switch (phase) { |
| 256 | b.drawRect({218, 58, 52, 132}, hexColor(0xf6f0e0ff)); | 264 | case RoundPhase::Intro: |
| 257 | b.drawRect({218, 58, 52, 4}, hexColor(0x9a4a3aff)); | 265 | if (phaseTime >= kIntroFrames) { |
| 258 | b.drawRect({218, 186, 52, 4}, hexColor(0x9a4a3aff)); | 266 | phase = RoundPhase::Fight; |
| 259 | b.drawRect({212, 190, 64, 6}, kBeam); | 267 | phaseTime = 0; |
| 260 | g.pixel.draw(b, "練", {244, 82}, {.color = kOutline, .scale = 2.0f, .align = TextAlign::Centre}); | 268 | } |
| 261 | g.pixel.draw(b, "習", {244, 122}, {.color = kOutline, .scale = 2.0f, .align = TextAlign::Centre}); | 269 | break; |
| 262 | b.drawRect({236, 166, 16, 8}, hexColor(0xc83c3cff)); // 落款 / the seal | 270 | case RoundPhase::Fight: |
| 263 | // 腰板 / wainscot | 271 | if (ko[0] || ko[1]) finishRound(ko[0] && ko[1] ? -1 : ko[0] ? 1 : 0, false); |
| 264 | b.drawRect({-8, 222, 656, 38}, kWainscot); | 272 | else if (--timer <= 0) { |
| 265 | b.drawRect({-8, 222, 656, 3}, kWainscotDark); | 273 | // タイムアップ:体力の多い方の勝ち / time over: the one with more health wins |
| 266 | for (float x = 0; x < 640; x += 40) b.drawRect({x, 225, 2, 35}, kWainscotDark); | 274 | int h0 = fighters[0].health, h1 = fighters[1].health; |
| 267 | // 床板:奥ほど細い(ゆるい遠近) / floor planks: thinner further back (a gentle perspective) | 275 | finishRound(h0 == h1 ? -1 : h0 > h1 ? 0 : 1, true); |
| 268 | float y = 260.0f; | 276 | } |
| 269 | int row = 0; | 277 | break; |
| 270 | // 最後の段は画面の下より先まで / the last row reaches past the bottom | 278 | case RoundPhase::Finish: |
| 271 | for (float h : {6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 12.0f, 13.0f, 15.0f, 28.0f}) { | 279 | if (phaseTime == kWinPoseAt && roundWinner >= 0) fighters[roundWinner].win(); |
| 272 | b.drawRect({-8, y, 656, h}, row % 2 ? kPlankA : kPlankB); | 280 | if (leaving) phaseTime = kFinishFrames; // 暗いまま待つ / stay dark while the switch happens |
| 273 | b.drawRect({-8, y, 656, 1}, kPlankLine); | 281 | else if (phaseTime >= kFinishFrames) { |
| 274 | float offset = static_cast<float>((row * 97) % 120); | 282 | bool over = wins[0] >= kWinsNeeded || wins[1] >= kWinsNeeded || round >= kMaxRounds; |
| 275 | for (float x = offset; x < 640; x += 120) b.drawRect({x, y, 1, h}, kPlankLine); | 283 | if (over) { |
| 276 | y += h; | 284 | int winner = wins[0] == wins[1] ? -1 : wins[0] > wins[1] ? 0 : 1; |
| 277 | ++row; | 285 | // 置き換えは予約だけ(このシーンはこのupdateの後で消える) / the replacement is only queued (this scene goes |
| 286 | // away after this update) | ||
| 287 | scenes().replace(std::make_unique<ResultScene>(g, settings, winner, wins), {.duration = 0.6f}); | ||
| 288 | leaving = true; | ||
| 289 | } else { | ||
| 290 | ++round; | ||
| 291 | startRound(); | ||
| 292 | } | ||
| 293 | } | ||
| 294 | break; | ||
| 278 | } | 295 | } |
| 279 | } | 296 | } |
| 280 | 297 | ||
| 281 | void FightScene::draw(float alpha) { | 298 | void FightScene::draw(float alpha) { |
| 282 | SpriteBatch &b = g.batch; | 299 | SpriteBatch &b = g.batch; |
| 283 | Camera2D view = camera; | 300 | Camera2D view = worldCamera(alpha); |
| 284 | // 画面の揺れ:重い一撃のヒットストップ中、カメラを2ピクセルずつ揺らす / screen shake: during a heavy hit's | 301 | // 揺れは横だけ、舞台の中で(端で舞台の外が見えないように) / the shake is horizontal only and stays inside the stage |
| 285 | // hit stop the camera jumps by 2 pixels | 302 | // (so nothing outside the stage shows at the ends) |
| 286 | if (shake > 0) view.centre += Vec2{shake % 2 ? 2.0f : -2.0f, shake % 4 < 2 ? 1.0f : -1.0f}; | 303 | if (shake > 0) view.centre.x = Stage::clampCamera(view.centre.x + (shake % 2 ? 2.0f : -2.0f), kViewSize.x); |
| 287 | b.begin(view.matrix(), SpriteSort::Layer); | 304 | b.begin(view.matrix(), SpriteSort::Layer); |
| 288 | drawBackground(); | 305 | g.stage->drawBack(b, view); |
| 289 | for (int i = 0; i < 2; ++i) | 306 | for (int i = 0; i < 2; ++i) |
| 290 | fighters[i].draw(b, alpha, i == top ? 3.0f : 2.0f, victim == i && hitstop > 0 ? hitstop : 0); | 307 | fighters[i].draw(b, alpha, i == top ? 3.0f : 2.0f, victim == i && hitstop > 0 ? hitstop : 0); |
| 291 | effects.draw(b); | 308 | effects.draw(b); |
| 292 | if (g.showBoxes) drawDebug(alpha); | 309 | g.stage->drawFront(b, view); |
| 293 | b.end(); | 310 | b.end(); |
| 294 | // HUDは揺らさない / the HUD does not shake | 311 | if (g.showBoxes) { |
| 295 | b.begin(camera.matrix(), SpriteSort::Layer); | 312 | b.begin(view.matrix(), SpriteSort::Layer); |
| 313 | drawDebug(); | ||
| 314 | b.end(); | ||
| 315 | } | ||
| 316 | b.begin(Camera2D::screen(kViewSize).matrix(), SpriteSort::Layer); | ||
| 296 | drawHud(); | 317 | drawHud(); |
| 297 | b.end(); | 318 | b.end(); |
| 298 | } | 319 | } |
| 299 | 320 | ||
| 300 | void FightScene::drawHud() { | 321 | void FightScene::drawHud() { |
| 301 | SpriteBatch &b = g.batch; | 322 | SpriteBatch &b = g.batch; |
| 302 | drawHealthBar(b, {16, 10, 272, 10}, static_cast<float>(fighters[0].health), trail[0], false); | 323 | drawHealthBar(b, {16, 10, 260, 10}, static_cast<float>(fighters[0].health), trail[0], false); |
| 303 | drawHealthBar(b, {352, 10, 272, 10}, static_cast<float>(fighters[1].health), trail[1], true); | 324 | drawHealthBar(b, {364, 10, 260, 10}, static_cast<float>(fighters[1].health), trail[1], true); |
| 304 | TextStyle name = {.color = kText, .layer = 11.0f, .shadow = kOutline}; | 325 | TextStyle name = {.color = kText, .layer = 11.0f, .shadow = kOutline}; |
| 305 | g.pixel.draw(b, "1P " + fighters[0].name, {16, 24}, name); | 326 | bool cpu[2] = {ai[0].has_value(), ai[1].has_value()}; |
| 327 | g.pixel.draw(b, "1P " + fighters[0].name + (cpu[0] ? " (CPU)" : ""), {16, 24}, name); | ||
| 306 | TextStyle right = name; | 328 | TextStyle right = name; |
| 307 | right.align = TextAlign::Right; | 329 | right.align = TextAlign::Right; |
| 308 | g.pixel.draw(b, fighters[1].name + " 2P", {624, 24}, right); | 330 | g.pixel.draw(b, (cpu[1] ? "(CPU) " : "") + fighters[1].name + " 2P", {624, 24}, right); |
| 309 | TextStyle centre = name; | 331 | // 取ったラウンド:名前の横の印 / rounds won: marks next to the names |
| 310 | centre.align = TextAlign::Centre; | 332 | for (int i = 0; i < 2; ++i) |
| 311 | centre.color = kGold; | 333 | for (int k = 0; k < kWinsNeeded; ++k) { |
| 312 | g.pixel.draw(b, "練習", {320, 8}, centre); | 334 | float x = i == 0 ? 266.0f - 12.0f * static_cast<float>(k) : 366.0f + 12.0f * static_cast<float>(k); |
| 313 | // コンボ数(攻撃した側に) / the combo count (on the attacker's side) | 335 | b.drawRect({x - 1, 25, 10, 10}, kOutline, 10.0f); |
| 336 | b.drawRect({x, 26, 8, 8}, wins[i] > k ? kGold : hexColor(0x4a2434ff), 10.1f); | ||
| 337 | } | ||
| 338 | // 時間(真ん中)。練習は「練習」 / the timer (center); training shows "練習" | ||
| 339 | b.drawRect({298, 4, 44, 30}, kOutline, 10.0f); | ||
| 340 | TextStyle centre = {.color = kGold, .scale = 2.0f, .align = TextAlign::Centre, .layer = 11.0f}; | ||
| 341 | if (settings.mode == Mode::Training) { | ||
| 342 | centre.scale = 1.0f; | ||
| 343 | g.pixel.draw(b, "練習", {320, 12}, centre); | ||
| 344 | } else { | ||
| 345 | int seconds = (timer + 59) / 60; | ||
| 346 | centre.color = seconds <= 10 ? kRed : kGold; | ||
| 347 | g.pixel.draw(b, std::to_string(seconds), {320, 6}, centre); | ||
| 348 | } | ||
| 314 | for (int i = 0; i < 2; ++i) { | 349 | for (int i = 0; i < 2; ++i) { |
| 315 | if (comboTime[i] <= 0) continue; | 350 | if (comboTime[i] <= 0) continue; |
| 316 | std::string text = std::to_string(comboHits[i]) + " HITS"; | ||
| 317 | TextStyle s = {.color = hexColor(0xff9a3cff), .scale = 2.0f, .align = i == 0 ? TextAlign::Left : TextAlign::Right, | 351 | TextStyle s = {.color = hexColor(0xff9a3cff), .scale = 2.0f, .align = i == 0 ? TextAlign::Left : TextAlign::Right, |
| 318 | .layer = 11.0f, .shadow = kOutline}; | 352 | .layer = 11.0f, .shadow = kOutline}; |
| 319 | g.pixel.draw(b, text, {i == 0 ? 16.0f : 624.0f, 44.0f}, s); | 353 | g.pixel.draw(b, std::to_string(comboHits[i]) + " HITS", {i == 0 ? 16.0f : 624.0f, 44.0f}, s); |
| 354 | } | ||
| 355 | |||
| 356 | // ラウンドの表示 / the round banners | ||
| 357 | TextStyle sub = {.color = kText, .scale = 2.0f, .align = TextAlign::Centre, .layer = 11.5f, .shadow = kOutline, | ||
| 358 | .shadowOffset = {1.0f, 1.0f}}; | ||
| 359 | if (phase == RoundPhase::Intro) { | ||
| 360 | bool final = round == kMaxRounds || (wins[0] == kWinsNeeded - 1 && wins[1] == kWinsNeeded - 1); | ||
| 361 | if (phaseTime < 60) { | ||
| 362 | drawBigText(b, g.pixel, final ? "FINAL ROUND" : "ROUND " + std::to_string(round), {320, 130}, kText, 4.0f); | ||
| 363 | g.pixel.draw(b, final ? "最終ラウンド" : "第" + std::to_string(round) + "ラウンド", {320, 162}, sub); | ||
| 364 | } else { | ||
| 365 | drawBigText(b, g.pixel, "FIGHT!", {320, 130}, kGold, 5.0f); | ||
| 366 | } | ||
| 367 | } else if (phase == RoundPhase::Finish) { | ||
| 368 | if (phaseTime < kWinPoseAt) { | ||
| 369 | bool doubleKo = roundWinner < 0 && !timeOver; | ||
| 370 | drawBigText(b, g.pixel, timeOver ? "TIME UP" : doubleKo ? "DOUBLE K.O." : "K.O.", {320, 130}, kRed, | ||
| 371 | timeOver || doubleKo ? 4.0f : 5.0f); | ||
| 372 | if (timeOver) g.pixel.draw(b, "タイムアップ", {320, 162}, sub); | ||
| 373 | } else if (roundWinner >= 0) { | ||
| 374 | drawBigText(b, g.pixel, fighters[roundWinner].name + " WINS", {320, 130}, kGold, 4.0f); | ||
| 375 | g.pixel.draw(b, std::string(kJapaneseNames[roundWinner]) + "の勝ち", {320, 162}, sub); | ||
| 376 | } else { | ||
| 377 | drawBigText(b, g.pixel, "DRAW", {320, 130}, kText, 4.0f); | ||
| 378 | g.pixel.draw(b, "引き分け", {320, 162}, sub); | ||
| 379 | } | ||
| 380 | } else if (koTime > 0) { | ||
| 381 | drawBigText(b, g.pixel, "K.O.", {320, 130}, kRed, 5.0f); | ||
| 320 | } | 382 | } |
| 321 | if (koTime > 0) drawBigText(b, g.pixel, "K.O.", {320, 130}, hexColor(0xe8483cff), 5.0f); | ||
| 322 | } | 383 | } |
| 323 | 384 | ||
| 324 | // F1:食らい判定(青)、攻撃判定(赤)、押し合い(緑)、ソケット(黄)、状態と技の段階 | 385 | void FightScene::drawDebug() { |
| 325 | // F1: hurt boxes (blue), hit boxes (red), push boxes (green), sockets (yellow), the state and the move's phase | ||
| 326 | void FightScene::drawDebug(float /*alpha*/) { | ||
| 327 | // 判定は今のステップの位置で描く(補間しない:当たりを決めたのはこの位置) / boxes at this step's positions (not | ||
| 328 | // interpolated: these are the positions the hits were decided at) | ||
| 329 | SpriteBatch &b = g.batch; | 386 | SpriteBatch &b = g.batch; |
| 330 | static const char *const kPhase[] = {"", "STARTUP", "ACTIVE", "RECOVERY"}; | 387 | static const char *const kPhase[] = {"", "STARTUP", "ACTIVE", "RECOVERY"}; |
| 331 | for (const Fighter &f : fighters) { | 388 | for (int i = 0; i < 2; ++i) { |
| 332 | for (const Rect &r : f.hurtboxes()) b.drawRectOutline(r, hexColor(0x5aaaffe0), 1.0f, 8.0f); | 389 | const Fighter &f = fighters[i]; |
| 390 | for (const Rect &r : f.hurtboxes()) b.drawRectOutline(r, hexColor(0x5aaaffe0), 1.0f, 20.0f); | ||
| 333 | Rect push = f.pushbox(); | 391 | Rect push = f.pushbox(); |
| 334 | b.drawRectOutline(push, hexColor(0x50e070c0), 1.0f, 8.1f); | 392 | b.drawRectOutline(push, hexColor(0x50e070c0), 1.0f, 20.1f); |
| 335 | const FrameBoxes &fb = (*g.frameData)[f.frame]; | 393 | const FrameBoxes &fb = (*g.frameData)[f.frame]; |
| 336 | // 攻撃判定:持続フレームの間ずっと。当たった後(もう当たらない)は薄く / the attack box for the whole active | ||
| 337 | // window; fainter once it has hit (it cannot hit again) | ||
| 338 | if (f.phase() == MovePhase::Active && fb.hit) | 394 | if (f.phase() == MovePhase::Active && fb.hit) |
| 339 | b.drawRect(toWorld(*fb.hit, f.position, f.facing), f.moveHit ? hexColor(0xff464650) : hexColor(0xff4646a0), 8.2f); | 395 | b.drawRect(toWorld(*fb.hit, f.position, f.facing), f.moveHit ? hexColor(0xff464650) : hexColor(0xff4646a0), 20.2f); |
| 340 | for (Vec2 s : {fb.head, fb.knot, fb.fist, fb.foot}) { | 396 | for (Vec2 s : {fb.head, fb.knot, fb.fist, fb.foot}) { |
| 341 | Rect r = toWorld({s.x, s.y, 0.0f, 0.0f}, f.position, f.facing); | 397 | Rect r = toWorld({s.x, s.y, 0.0f, 0.0f}, f.position, f.facing); |
| 342 | b.drawRect({std::round(r.x) - 1, std::round(r.y) - 1, 2, 2}, hexColor(0xffdc3cff), 8.3f); | 398 | b.drawRect({std::round(r.x) - 1, std::round(r.y) - 1, 2, 2}, hexColor(0xffdc3cff), 20.3f); |
| 343 | } | 399 | } |
| 344 | char label[96]; | 400 | char label[128]; |
| 345 | if (f.state == FighterState::Attack) | 401 | int n = f.state == FighterState::Attack |
| 346 | std::snprintf(label, sizeof label, "%s %s %d/%d\n%s", stateName(f.state), f.move->name, f.stateTime, | 402 | ? std::snprintf(label, sizeof label, "%s %s %d/%d\n%s", stateName(f.state), f.move->name, f.stateTime, |
| 347 | f.move->total(), kPhase[static_cast<int>(f.phase())]); | 403 | f.move->total(), kPhase[static_cast<int>(f.phase())]) |
| 348 | else std::snprintf(label, sizeof label, "%s %d\nHP %d", stateName(f.state), f.stateTime, f.health); | 404 | : std::snprintf(label, sizeof label, "%s %d\nHP %d", stateName(f.state), f.stateTime, f.health); |
| 349 | // 左の人の札は左へ、右の人の札は右へずらす(近づいても重ならない) / the left fighter's label goes left, the | 405 | // CPUなら今の意図も / for the CPU also its current intent |
| 350 | // right one's right (no overlap at close range) | 406 | if (ai[i] && n > 0 && static_cast<size_t>(n) < sizeof label) |
| 351 | const Fighter &other = &f == &fighters[0] ? fighters[1] : fighters[0]; | 407 | std::snprintf(label + n, sizeof label - static_cast<size_t>(n), "\nAI %s", ai[i]->intentName()); |
| 352 | bool leftOne = f.position.x < other.position.x || (f.position.x == other.position.x && &f == &fighters[0]); | 408 | const Fighter &other = fighters[1 - i]; |
| 409 | bool leftOne = f.position.x < other.position.x || (f.position.x == other.position.x && i == 0); | ||
| 353 | Vec2 size = g.tiny.measure(label); | 410 | Vec2 size = g.tiny.measure(label); |
| 354 | float x0 = std::round(leftOne ? f.position.x + 8.0f - size.x : f.position.x - 8.0f); | 411 | float x0 = std::round(leftOne ? f.position.x + 8.0f - size.x : f.position.x - 8.0f); |
| 355 | Vec2 at = {x0, std::round(push.y) - 16.0f}; | 412 | Vec2 at = {x0, std::round(push.y) - 22.0f}; |
| 356 | b.drawRect({x0 - 2.0f, at.y - 2.0f, size.x + 3.0f, size.y + 2.0f}, {0.11f, 0.09f, 0.15f, 0.8f}, 8.5f); | 413 | b.drawRect({x0 - 2.0f, at.y - 2.0f, size.x + 3.0f, size.y + 2.0f}, {0.11f, 0.09f, 0.15f, 0.8f}, 20.5f); |
| 357 | g.tiny.draw(b, label, at, {.color = kText, .layer = 9.0f}); | 414 | g.tiny.draw(b, label, at, {.color = kText, .layer = 21.0f}); |
| 358 | } | 415 | } |
| 359 | } | 416 | } |
| 360 | 417 | ||
| 361 | void FightScene::drawUi(float /*alpha*/) { | 418 | void FightScene::drawUi(float /*alpha*/) { |
| 362 | SpriteBatch &b = g.batch; | 419 | SpriteBatch &b = g.batch; |
| 363 | b.begin(g.screen.matrix()); | 420 | b.begin(g.screen.matrix()); |
| 421 | // ラウンドの間の暗転(自前のフェード:シーンは変わらない) / the fade between rounds (our own: the scene stays) | ||
| 422 | float fade = 0.0f; | ||
| 423 | if (phase == RoundPhase::Finish && phaseTime > kFinishFrames - 30) | ||
| 424 | fade = static_cast<float>(phaseTime - (kFinishFrames - 30)) / 30.0f; | ||
| 425 | if (phase == RoundPhase::Intro && phaseTime < 20) fade = 1.0f - static_cast<float>(phaseTime) / 20.0f; | ||
| 426 | if (fade > 0.0f) b.drawRect({0, 0, 1280, 720}, {0.0f, 0.0f, 0.0f, std::clamp(fade, 0.0f, 1.0f)}); | ||
| 364 | b.drawRect({0, 688, 1280, 32}, {0.11f, 0.09f, 0.15f, 0.75f}); | 427 | b.drawRect({0, 688, 1280, 32}, {0.11f, 0.09f, 0.15f, 0.75f}); |
| 365 | g.ui.draw(b, | 428 | const char *help = settings.mode == Mode::TwoPlayers || settings.mode == Mode::Training |
| 366 | "1P: A D W S + F パンチ・G キック 2P: カーソルキー + K・L 後ろでガード / back = guard " | 429 | ? "1P: A D W S + F パンチ・G キック 2P: カーソルキー + K・L F1 当たり箱 Esc 一時停止 / pause" |
| 367 | "F1 当たり箱 Esc 終了", | 430 | : settings.mode == Mode::VsCpu |
| 368 | {640, 694}, {.color = hexColor(0xe8e0d0ff), .align = TextAlign::Centre}); | 431 | ? "1P: A D 前後・W ジャンプ・S しゃがむ・F パンチ・G キック F1 当たり箱 Esc 一時停止 / pause" |
| 432 | : "CPU 対 CPU F1 当たり箱 Esc 一時停止 / pause"; | ||
| 433 | g.ui.draw(b, help, {640, 694}, {.color = hexColor(0xe8e0d0ff), .align = TextAlign::Centre}); | ||
| 369 | b.end(); | 434 | b.end(); |
| 370 | } | 435 | } |
ファイル: a/games/fighter/src/fight_scene.hh | b/games/fighter/src/fight_scene.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,40 +1,60 @@ | |||
| 1 | // 対戦の場面:二人のファイター、押し合い、技の当たり、ヒットストップ、体力ゲージ、エフェクト | 1 | // 対戦の場面:二人のファイター(人かCPU)、押し合い、技の当たり、ヒットストップ、体力ゲージ、エフェクト、 |
| 2 | // The fight scene: two fighters, pushing, hits, hit stop, health bars, effects | 2 | // スクロールする舞台とカメラ、ラウンド(3本勝負、時間、KO・タイムアップ) |
| 3 | // The fight scene: two fighters (human or CPU), pushing, hits, hit stop, health bars, effects, the scrolling stage | ||
| 4 | // and camera, rounds (best of three, a timer, KO / time over) | ||
| 3 | #pragma once | 5 | #pragma once |
| 4 | 6 | ||
| 7 | #include "ai.hh" | ||
| 5 | #include "effects.hh" | 8 | #include "effects.hh" |
| 6 | #include "fighter.hh" | 9 | #include "fighter.hh" |
| 7 | #include "game.hh" | 10 | #include "game.hh" |
| 11 | #include "match.hh" | ||
| 8 | 12 | ||
| 9 | #include "engine/scene.hh" | 13 | #include "engine/scene.hh" |
| 10 | 14 | ||
| 15 | #include <optional> | ||
| 16 | |||
| 11 | class FightScene : public Scene { | 17 | class FightScene : public Scene { |
| 12 | public: | 18 | public: |
| 13 | explicit FightScene(Game &game); | 19 | FightScene(Game &game, MatchSettings settings); |
| 20 | void pause() override; | ||
| 14 | void update(float dt) override; | 21 | void update(float dt) override; |
| 15 | void draw(float alpha) override; | 22 | void draw(float alpha) override; |
| 16 | void drawUi(float alpha) override; | 23 | void drawUi(float alpha) override; |
| 17 | 24 | ||
| 18 | private: | 25 | private: |
| 26 | // ラウンドの流れ:始まりの表示 → 戦い → 決着の表示 / the round flow: the intro banner → the fight → the result | ||
| 27 | enum class RoundPhase { Intro, Fight, Finish }; | ||
| 28 | |||
| 29 | void startRound(); | ||
| 19 | void separate(); | 30 | void separate(); |
| 31 | void keepInView(); | ||
| 20 | void resolveHits(); | 32 | void resolveHits(); |
| 21 | void resetRound(); | 33 | void finishRound(int winner, bool timeOver); |
| 22 | void drawBackground(); | 34 | void updateRound(); |
| 35 | Camera2D worldCamera(float alpha) const; | ||
| 23 | void drawHud(); | 36 | void drawHud(); |
| 24 | void drawDebug(float alpha); | 37 | void drawDebug(); |
| 25 | 38 | ||
| 26 | Game &g; | 39 | Game &g; |
| 27 | Camera2D camera; | 40 | MatchSettings settings; |
| 28 | Fighter fighters[2]; | 41 | Fighter fighters[2]; |
| 42 | std::optional<AiController> ai[2]; // ある方はCPUが操作する / where set, the computer plays that side | ||
| 29 | Effects effects; | 43 | Effects effects; |
| 30 | GamepadEdges pads[2]; | 44 | GamepadEdges pads[2]; |
| 31 | int steps = 0; | 45 | int steps = 0; |
| 32 | int hitstop = 0; // 残りのヒットストップ(二人とも止まる) / hit stop left (both fighters frozen) | 46 | int hitstop = 0, victim = -1, shake = 0, top = 0; |
| 33 | int victim = -1; // ヒットストップ中に震える方 / who shakes during the hit stop | 47 | float trail[2] = {kMaxHealth, kMaxHealth}; |
| 34 | int shake = 0; // 画面の揺れ / screen shake | ||
| 35 | int top = 0; // 手前に描くファイター(最後に攻撃した方) / the fighter drawn in front (the last attacker) | ||
| 36 | float trail[2] = {kMaxHealth, kMaxHealth}; // 体力ゲージの減っていく白い部分 / the health bar's draining trail | ||
| 37 | int trailDelay[2] = {0, 0}; | 48 | int trailDelay[2] = {0, 0}; |
| 38 | int comboTime[2] = {0, 0}, comboHits[2] = {0, 0}; // 「2 HITS」の表示 / the "2 HITS" display | 49 | int comboTime[2] = {0, 0}, comboHits[2] = {0, 0}; |
| 39 | int koTime = 0; // KOからの時間(練習では仕切り直す) / time since a KO (training resets) | 50 | |
| 51 | RoundPhase phase = RoundPhase::Intro; | ||
| 52 | int phaseTime = 0; | ||
| 53 | int round = 1; | ||
| 54 | int wins[2] = {0, 0}; | ||
| 55 | int timer = kRoundSeconds * 60; // ラウンドの残り(ステップ) / time left in the round (steps) | ||
| 56 | int roundWinner = -1; // -1 = 引き分け / -1 = draw | ||
| 57 | bool timeOver = false; | ||
| 58 | int koTime = 0; // 練習モードのKOからの時間 / training mode: time since a KO | ||
| 59 | bool leaving = false; // 勝利画面への切り替えを頼んだ / the switch to the win screen was requested | ||
| 40 | }; | 60 | }; |
ファイル: a/games/fighter/src/fighter.cc | b/games/fighter/src/fighter.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -49,6 +49,7 @@ const char *stateName(FighterState state) { | |||
| 49 | case FighterState::Knockdown: return "KNOCKDOWN"; | 49 | case FighterState::Knockdown: return "KNOCKDOWN"; |
| 50 | case FighterState::GetUp: return "GETUP"; | 50 | case FighterState::GetUp: return "GETUP"; |
| 51 | case FighterState::KO: return "KO"; | 51 | case FighterState::KO: return "KO"; |
| 52 | case FighterState::Win: return "WIN"; | ||
| 52 | } | 53 | } |
| 53 | return "?"; | 54 | return "?"; |
| 54 | } | 55 | } |
| @@ -57,7 +58,7 @@ Fighter::Fighter(const SpriteSheet &s, const SpriteSheet &effects, const FrameDa | |||
| 57 | const char *tail, Vec2 start, float startFacing) | 58 | const char *tail, Vec2 start, float startFacing) |
| 58 | : name(std::move(fighterName)), position(start), previous(start), facing(startFacing), sheet(s), data(frameData), | 59 | : name(std::move(fighterName)), position(start), previous(start), facing(startFacing), sheet(s), data(frameData), |
| 59 | idleClip(s.clip("idle")), walkClip(s.clip("walk")), walkBackClip(s.clip("walk_back")), | 60 | idleClip(s.clip("idle")), walkClip(s.clip("walk")), walkBackClip(s.clip("walk_back")), |
| 60 | fCrouchIn(findFrame(s, "crouch_in")), fCrouch(findFrame(s, "crouch")), fJumpUp(findFrame(s, "jump_up")), | 61 | winClip(s.clip("win")), fCrouchIn(findFrame(s, "crouch_in")), fCrouch(findFrame(s, "crouch")), fJumpUp(findFrame(s, "jump_up")), |
| 61 | fJumpTuck(findFrame(s, "jump_tuck")), fJumpDown(findFrame(s, "jump_down")), fBlock(findFrame(s, "block")), | 62 | fJumpTuck(findFrame(s, "jump_tuck")), fJumpDown(findFrame(s, "jump_down")), fBlock(findFrame(s, "block")), |
| 62 | fCBlock(findFrame(s, "cblock")), fHit0(findFrame(s, "hit0")), fHit1(findFrame(s, "hit1")), | 63 | fCBlock(findFrame(s, "cblock")), fHit0(findFrame(s, "hit0")), fHit1(findFrame(s, "hit1")), |
| 63 | fCHit(findFrame(s, "chit")), fKo0(findFrame(s, "ko0")), fKo1(findFrame(s, "ko1")) { | 64 | fCHit(findFrame(s, "chit")), fKo0(findFrame(s, "ko0")), fKo1(findFrame(s, "ko1")) { |
| @@ -75,6 +76,7 @@ void Fighter::reset(Vec2 start, float startFacing) { | |||
| 75 | health = kMaxHealth; | 76 | health = kMaxHealth; |
| 76 | move = nullptr; | 77 | move = nullptr; |
| 77 | onGround = true; | 78 | onGround = true; |
| 79 | wantsWin = false; | ||
| 78 | buffer.clear(); | 80 | buffer.clear(); |
| 79 | animator.play(idleClip, true); | 81 | animator.play(idleClip, true); |
| 80 | frame = animator.frame(); | 82 | frame = animator.frame(); |
| @@ -124,6 +126,8 @@ void Fighter::setState(FighterState next) { | |||
| 124 | stateTime = 0; | 126 | stateTime = 0; |
| 125 | } | 127 | } |
| 126 | 128 | ||
| 129 | void Fighter::win() { wantsWin = true; } | ||
| 130 | |||
| 127 | bool Fighter::actionable() const { | 131 | bool Fighter::actionable() const { |
| 128 | return state == FighterState::Idle || state == FighterState::Walk || state == FighterState::Crouch; | 132 | return state == FighterState::Idle || state == FighterState::Walk || state == FighterState::Crouch; |
| 129 | } | 133 | } |
| @@ -233,8 +237,15 @@ void Fighter::update(float dt, const Controls &c, float opponentX, bool threat) | |||
| 233 | if (stateTime >= kGetUpFrames) setState(FighterState::Idle); | 237 | if (stateTime >= kGetUpFrames) setState(FighterState::Idle); |
| 234 | break; | 238 | break; |
| 235 | case FighterState::KO: | 239 | case FighterState::KO: |
| 240 | case FighterState::Win: | ||
| 236 | break; | 241 | break; |
| 237 | } | 242 | } |
| 243 | // 勝ちポーズは、自由に動ける状態で地上にいるときに / the victory pose starts once free and on the ground | ||
| 244 | if (wantsWin && onGround && (actionable() || state == FighterState::Land)) { | ||
| 245 | velocity.x = 0.0f; | ||
| 246 | setState(FighterState::Win); | ||
| 247 | animator.play(winClip, true); | ||
| 248 | } | ||
| 238 | 249 | ||
| 239 | // 物理:空中は重力、地上は(歩き以外)摩擦で止まる / physics: gravity in the air; on the ground friction stops | 250 | // 物理:空中は重力、地上は(歩き以外)摩擦で止まる / physics: gravity in the air; on the ground friction stops |
| 240 | // everything except walking | 251 | // everything except walking |
| @@ -386,6 +397,8 @@ void Fighter::chooseFrame(float dt) { | |||
| 386 | case FighterState::KO: | 397 | case FighterState::KO: |
| 387 | frame = onGround ? fKo1 : fKo0; | 398 | frame = onGround ? fKo1 : fKo0; |
| 388 | return; | 399 | return; |
| 400 | case FighterState::Win: | ||
| 401 | break; // animatorの勝ちクリップ / the animator's win clip | ||
| 389 | } | 402 | } |
| 390 | animator.update(dt); | 403 | animator.update(dt); |
| 391 | frame = animator.frame(); | 404 | frame = animator.frame(); |
ファイル: a/games/fighter/src/fighter.hh | b/games/fighter/src/fighter.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -38,6 +38,7 @@ enum class FighterState { | |||
| 38 | Knockdown, // ダウン:飛ばされて倒れ、起き上がる / knocked down: thrown back, lying, then getting up | 38 | Knockdown, // ダウン:飛ばされて倒れ、起き上がる / knocked down: thrown back, lying, then getting up |
| 39 | GetUp, // 起き上がり(無敵) / getting up (invincible) | 39 | GetUp, // 起き上がり(無敵) / getting up (invincible) |
| 40 | KO, // 体力0:倒れたまま / health 0: stays down | 40 | KO, // 体力0:倒れたまま / health 0: stays down |
| 41 | Win, // 勝ちポーズ(ラウンドの勝者) / the victory pose (the round's winner) | ||
| 41 | }; | 42 | }; |
| 42 | const char *stateName(FighterState state); | 43 | const char *stateName(FighterState state); |
| 43 | 44 | ||
| @@ -79,6 +80,10 @@ public: | |||
| 79 | // the wall; a faster motion the same way (the knockback just taken in a trade) is kept | 80 | // the wall; a faster motion the same way (the knockback just taken in a trade) is kept |
| 80 | void pushBack(float speed) { velocity.x = -facing * std::max(speed, -facing * velocity.x); } | 81 | void pushBack(float speed) { velocity.x = -facing * std::max(speed, -facing * velocity.x); } |
| 81 | bool actionable() const; | 82 | bool actionable() const; |
| 83 | bool grounded() const { return onGround; } | ||
| 84 | // ラウンドに勝った:地上にいれば勝ちポーズ(空中なら着地してから) / won the round: the victory pose once on the | ||
| 85 | // ground | ||
| 86 | void win(); | ||
| 82 | 87 | ||
| 83 | // 体の部品(ノード)をこのステップの値に合わせてから描く / updates the part nodes for this frame, then draws them | 88 | // 体の部品(ノード)をこのステップの値に合わせてから描く / updates the part nodes for this frame, then draws them |
| 84 | void draw(SpriteBatch &batch, float alpha, float layer, int shake); | 89 | void draw(SpriteBatch &batch, float alpha, float layer, int shake); |
| @@ -114,11 +119,12 @@ private: | |||
| 114 | 119 | ||
| 115 | const SpriteSheet &sheet; | 120 | const SpriteSheet &sheet; |
| 116 | const FrameData &data; | 121 | const FrameData &data; |
| 117 | const AnimationClip *idleClip, *walkClip, *walkBackClip; | 122 | const AnimationClip *idleClip, *walkClip, *walkBackClip, *winClip; |
| 118 | Animator animator; | 123 | Animator animator; |
| 119 | float jumpDirection = 0.0f; | 124 | float jumpDirection = 0.0f; |
| 120 | bool onGround = true; | 125 | bool onGround = true; |
| 121 | bool airMoveUsed = false; | 126 | bool airMoveUsed = false; |
| 127 | bool wantsWin = false; | ||
| 122 | float time = 0.0f; | 128 | float time = 0.0f; |
| 123 | int fCrouchIn, fCrouch, fJumpUp, fJumpTuck, fJumpDown, fBlock, fCBlock, fHit0, fHit1, fCHit, fKo0, fKo1; | 129 | int fCrouchIn, fCrouch, fJumpUp, fJumpTuck, fJumpDown, fBlock, fCBlock, fHit0, fHit1, fCHit, fKo0, fKo1; |
| 124 | 130 | ||
ファイル: a/games/fighter/src/game.hh | b/games/fighter/src/game.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -2,7 +2,9 @@ | |||
| 2 | // The fighting game's shared data, one per game (main creates it, the scenes keep a reference) | 2 | // The fighting game's shared data, one per game (main creates it, the scenes keep a reference) |
| 3 | #pragma once | 3 | #pragma once |
| 4 | 4 | ||
| 5 | #include "ai.hh" | ||
| 5 | #include "frame_data.hh" | 6 | #include "frame_data.hh" |
| 7 | #include "stage.hh" | ||
| 6 | 8 | ||
| 7 | #include "engine/camera2d.hh" | 9 | #include "engine/camera2d.hh" |
| 8 | #include "engine/font.hh" | 10 | #include "engine/font.hh" |
| @@ -26,6 +28,9 @@ struct Game { | |||
| 26 | const SpriteSheet *fighters[2]; // ハヤテ(1P)とジン(2P) / Hayate (1P) and Jin (2P) | 28 | const SpriteSheet *fighters[2]; // ハヤテ(1P)とジン(2P) / Hayate (1P) and Jin (2P) |
| 27 | const SpriteSheet *effects; // 火花・砂ぼこり・鉢巻の尾・星・影 / sparks, dust, headband tails, stars, shadow | 29 | const SpriteSheet *effects; // 火花・砂ぼこり・鉢巻の尾・星・影 / sparks, dust, headband tails, stars, shadow |
| 28 | const FrameData *frameData; // コマごとの判定(二人共通:同じ骨格) / per-frame boxes (shared: same skeleton) | 30 | const FrameData *frameData; // コマごとの判定(二人共通:同じ骨格) / per-frame boxes (shared: same skeleton) |
| 31 | Stage *stage; // 視差の舞台(タイトルと勝利画面でも使う) / the parallax stage (also behind the | ||
| 32 | // title and the win screen) | ||
| 29 | Camera2D screen; // 1280×720のUI / the 1280 × 720 UI | 33 | Camera2D screen; // 1280×720のUI / the 1280 × 720 UI |
| 30 | bool showBoxes = false; // F1:判定の箱とデバッグ表示 / F1: boxes and debug labels | 34 | bool showBoxes = false; // F1:判定の箱とデバッグ表示 / F1: boxes and debug labels |
| 35 | Difficulty difficulty = Difficulty::Normal; // タイトルで選んだ強さ(戻っても覚えている) / chosen on the title (kept) | ||
| 31 | }; | 36 | }; |
ファイル: /dev/null | b/games/fighter/src/hud.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,17 @@ | |||
| 1 | // 画面の文字 / on-screen text | ||
| 2 | #include "hud.hh" | ||
| 3 | |||
| 4 | #include <cmath> | ||
| 5 | |||
| 6 | void drawBigText(SpriteBatch &b, const Font &font, std::string_view text, Vec2 centre, Vec4 color, float scale, | ||
| 7 | float layer) { | ||
| 8 | Vec2 size = font.measure(text, scale); | ||
| 9 | Vec2 at = {centre.x, std::round(centre.y - size.y * 0.5f)}; | ||
| 10 | TextStyle s = {.color = kOutline, .scale = scale, .align = TextAlign::Centre, .layer = layer}; | ||
| 11 | for (Vec2 d : {Vec2{-2, -2}, Vec2{0, -2}, Vec2{2, -2}, Vec2{-2, 0}, Vec2{2, 0}, Vec2{-2, 2}, Vec2{0, 2}, Vec2{2, 2}, | ||
| 12 | Vec2{3, 4}, Vec2{0, 4}}) | ||
| 13 | font.draw(b, text, at + d, s); | ||
| 14 | s.color = color; | ||
| 15 | s.layer = layer + 0.5f; | ||
| 16 | font.draw(b, text, at, s); | ||
| 17 | } | ||
ファイル: /dev/null | b/games/fighter/src/hud.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,17 @@ | |||
| 1 | // 画面の文字と色(どのシーンでも使う) / on-screen text and colors (used by every scene) | ||
| 2 | #pragma once | ||
| 3 | |||
| 4 | #include "engine/font.hh" | ||
| 5 | #include "engine/sprite_batch.hh" | ||
| 6 | |||
| 7 | #include <string_view> | ||
| 8 | |||
| 9 | constexpr Vec4 kOutline = hexColor(0x1b1726ff); | ||
| 10 | constexpr Vec4 kText = hexColor(0xfff4d8ff); | ||
| 11 | constexpr Vec4 kGold = hexColor(0xf2c14eff); | ||
| 12 | constexpr Vec4 kRed = hexColor(0xe8483cff); | ||
| 13 | |||
| 14 | // 大きな文字(K.O.、ROUND 1…):8方向の輪郭と影、それから本体。centreは文字の真ん中 | ||
| 15 | // Big text (K.O., ROUND 1...): an outline in 8 directions plus a drop shadow, then the text. centre is its middle | ||
| 16 | void drawBigText(SpriteBatch &batch, const Font &font, std::string_view text, Vec2 centre, Vec4 color, float scale, | ||
| 17 | float layer = 11.0f); | ||
ファイル: a/games/fighter/src/main.cc | b/games/fighter/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -6,6 +6,9 @@ | |||
| 6 | // 入力バッファ、体の部品とエフェクトのシーングラフ | 6 | // 入力バッファ、体の部品とエフェクトのシーングラフ |
| 7 | // Chapter 31: moves (frame data), hit / hurt boxes, damage, hit stun, knockback, hit stop, health bars, input | 7 | // Chapter 31: moves (frame data), hit / hurt boxes, damage, hit stun, knockback, hit stop, health bars, input |
| 8 | // buffering, a scene graph for body parts and effects | 8 | // buffering, a scene graph for body parts and effects |
| 9 | // 第32章:視差のある舞台とカメラ、CPUの相手(状態と決める間隔、難易度)、ラウンド(3本勝負・時間)、勝利画面 | ||
| 10 | // Chapter 32: a parallax stage and camera, the CPU opponent (states, a decision timer, difficulty), rounds (best of | ||
| 11 | // three, a timer), the win screen | ||
| 9 | // | 12 | // |
| 10 | // 操作(一台のキーボードを二人で) / Controls (two players on one keyboard): | 13 | // 操作(一台のキーボードを二人で) / Controls (two players on one keyboard): |
| 11 | // 1P A D 前後・W ジャンプ・S しゃがみ・F 突き・G 蹴り / A D walk, W jump, S crouch, F punch, G kick | 14 | // 1P A D 前後・W ジャンプ・S しゃがみ・F 突き・G 蹴り / A D walk, W jump, S crouch, F punch, G kick |
| @@ -13,9 +16,11 @@ | |||
| 13 | // 相手と反対に入れてガード(しゃがみガードは後ろ下) / hold away from the opponent to guard (down-back crouching) | 16 | // 相手と反対に入れてガード(しゃがみガードは後ろ下) / hold away from the opponent to guard (down-back crouching) |
| 14 | // ゲームパッド:1台目 = 1P、2台目 = 2P(十字キーか左スティック、A/X 突き、B/Y 蹴り) / gamepads: 1st = 1P, | 17 | // ゲームパッド:1台目 = 1P、2台目 = 2P(十字キーか左スティック、A/X 突き、B/Y 蹴り) / gamepads: 1st = 1P, |
| 15 | // 2nd = 2P (d-pad or left stick, A/X punch, B/Y kick) | 18 | // 2nd = 2P (d-pad or left stick, A/X punch, B/Y kick) |
| 16 | // F1 判定の箱と状態 / boxes and states Esc 終了 / quit | 19 | // F1 判定の箱と状態 / boxes and states Esc / P 一時停止 / pause |
| 17 | #include "fight_scene.hh" | 20 | // タイトル:W S 選ぶ、A D 難易度、Space・Enter・F 決定、Esc 終了 / title: W S select, A D difficulty, |
| 21 | // Space / Enter / F start, Esc quit | ||
| 18 | #include "game.hh" | 22 | #include "game.hh" |
| 23 | #include "scenes.hh" | ||
| 19 | 24 | ||
| 20 | #include "engine/pixel_canvas.hh" | 25 | #include "engine/pixel_canvas.hh" |
| 21 | #include "engine/window.hh" | 26 | #include "engine/window.hh" |
| @@ -40,7 +45,8 @@ int main() { | |||
| 40 | // 判定のデータは骨格から作ったもの:二人とも同じ(コマの名前と番号も同じ) / the box data comes from the skeleton: | 45 | // 判定のデータは骨格から作ったもの:二人とも同じ(コマの名前と番号も同じ) / the box data comes from the skeleton: |
| 41 | // the same for both (same frame names and indices) | 46 | // the same for both (same frame names and indices) |
| 42 | std::optional<FrameData> frameData = FrameData::load("games/fighter/assets/fighter.boxes", *hayate); | 47 | std::optional<FrameData> frameData = FrameData::load("games/fighter/assets/fighter.boxes", *hayate); |
| 43 | if (!frameData) return 1; | 48 | std::optional<Stage> stage = Stage::load(); |
| 49 | if (!frameData || !stage) return 1; | ||
| 44 | 50 | ||
| 45 | Input input; | 51 | Input input; |
| 46 | input.attach(window); | 52 | input.attach(window); |
| @@ -49,10 +55,10 @@ int main() { | |||
| 49 | GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); | 55 | GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); |
| 50 | PixelCanvas canvas(static_cast<int>(kViewSize.x), static_cast<int>(kViewSize.y)); | 56 | PixelCanvas canvas(static_cast<int>(kViewSize.x), static_cast<int>(kViewSize.y)); |
| 51 | Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .ui = *ui, .pixel = *pixel, | 57 | Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .ui = *ui, .pixel = *pixel, |
| 52 | .tiny = *tiny, .fighters = {&*hayate, &*jin}, .effects = &*effects, .frameData = &*frameData, .screen = Camera2D::screen({1280.0f, 720.0f})}; | 58 | .tiny = *tiny, .fighters = {&*hayate, &*jin}, .effects = &*effects, .frameData = &*frameData, .stage = &*stage, .screen = Camera2D::screen({1280.0f, 720.0f})}; |
| 53 | 59 | ||
| 54 | SceneManager scenes; | 60 | SceneManager scenes; |
| 55 | scenes.push(std::make_unique<FightScene>(game)); | 61 | scenes.push(std::make_unique<TitleScene>(game)); |
| 56 | 62 | ||
| 57 | loop.run( | 63 | loop.run( |
| 58 | window, input, | 64 | window, input, |
ファイル: /dev/null | b/games/fighter/src/match.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,20 @@ | |||
| 1 | // 試合の設定(タイトルで選ぶ) / the match settings (chosen on the title screen) | ||
| 2 | #pragma once | ||
| 3 | |||
| 4 | #include "ai.hh" | ||
| 5 | |||
| 6 | enum class Mode { | ||
| 7 | VsCpu, // 1P 対 CPU / 1P vs the computer | ||
| 8 | TwoPlayers, // 二人で対戦 / two players | ||
| 9 | CpuVsCpu, // CPU 対 CPU(見るだけ) / computer vs computer (watch) | ||
| 10 | Training, // 練習:時間なし、KOで仕切り直し / training: no timer, a KO restarts | ||
| 11 | }; | ||
| 12 | |||
| 13 | struct MatchSettings { | ||
| 14 | Mode mode = Mode::VsCpu; | ||
| 15 | Difficulty difficulty = Difficulty::Normal; | ||
| 16 | }; | ||
| 17 | |||
| 18 | constexpr int kWinsNeeded = 2; // 3本勝負:先に2本 / best of three: first to two | ||
| 19 | constexpr int kMaxRounds = 5; // 引き分けが続いたら5本目で終わり / draws end the match after round 5 | ||
| 20 | constexpr int kRoundSeconds = 60; | ||
ファイル: /dev/null | b/games/fighter/src/menu_keys.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,13 @@ | |||
| 1 | // メニューのキー(タイトル・一時停止・勝利画面で共通。1Pと2Pのどちらのキーでも) / menu keys (shared by the title, | ||
| 2 | // pause and win screens; either player's keys work) | ||
| 3 | #pragma once | ||
| 4 | |||
| 5 | #include "engine/input.hh" | ||
| 6 | |||
| 7 | inline bool menuUp(const Input &in) { return in.pressed(GLFW_KEY_W) || in.pressed(GLFW_KEY_UP); } | ||
| 8 | inline bool menuDown(const Input &in) { return in.pressed(GLFW_KEY_S) || in.pressed(GLFW_KEY_DOWN); } | ||
| 9 | inline bool menuLeft(const Input &in) { return in.pressed(GLFW_KEY_A) || in.pressed(GLFW_KEY_LEFT); } | ||
| 10 | inline bool menuRight(const Input &in) { return in.pressed(GLFW_KEY_D) || in.pressed(GLFW_KEY_RIGHT); } | ||
| 11 | inline bool menuConfirm(const Input &in) { | ||
| 12 | return in.pressed(GLFW_KEY_SPACE) || in.pressed(GLFW_KEY_ENTER) || in.pressed(GLFW_KEY_F) || in.pressed(GLFW_KEY_K); | ||
| 13 | } | ||
ファイル: /dev/null | b/games/fighter/src/pause_scene.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,37 @@ | |||
| 1 | // 一時停止:対戦の上に重ねる / pause: an overlay on top of the fight | ||
| 2 | #include "hud.hh" | ||
| 3 | #include "menu_keys.hh" | ||
| 4 | #include "scenes.hh" | ||
| 5 | |||
| 6 | #include <algorithm> | ||
| 7 | #include <memory> | ||
| 8 | |||
| 9 | void PauseScene::update(float dt) { | ||
| 10 | time += dt; | ||
| 11 | Input &in = g.input; | ||
| 12 | if (in.pressed(GLFW_KEY_ESCAPE) || in.pressed(GLFW_KEY_P)) { | ||
| 13 | scenes().pop(); | ||
| 14 | return; | ||
| 15 | } | ||
| 16 | if (menuUp(in) || menuDown(in)) selected = 1 - selected; | ||
| 17 | if (menuConfirm(in)) { | ||
| 18 | if (selected == 0) scenes().pop(); | ||
| 19 | else scenes().replaceAll(std::make_unique<TitleScene>(g), {.duration = 0.8f}); | ||
| 20 | } | ||
| 21 | } | ||
| 22 | |||
| 23 | void PauseScene::drawUi(float /*alpha*/) { | ||
| 24 | SpriteBatch &b = g.batch; | ||
| 25 | b.begin(g.screen.matrix()); | ||
| 26 | float dim = std::min(1.0f, time / 0.2f) * 0.55f; // 0.2秒で暗くなる / darkens over 0.2 s | ||
| 27 | b.drawRect({0, 0, 1280, 720}, {0.05f, 0.04f, 0.08f, dim}); | ||
| 28 | Rect panel = {440, 230, 400, 230}; | ||
| 29 | b.drawRect(panel, {0.11f, 0.09f, 0.15f, 0.92f}); | ||
| 30 | b.drawRectOutline(panel, kGold, 2.0f); | ||
| 31 | g.ui.draw(b, "一時停止 / PAUSED", {640, 256}, {.color = kText, .scale = 2.0f, .align = TextAlign::Centre}); | ||
| 32 | const char *items[2] = {"再開 / Resume", "タイトルへ / Back to title"}; | ||
| 33 | for (int i = 0; i < 2; ++i) | ||
| 34 | g.ui.draw(b, items[i], {640, 330.0f + 50.0f * static_cast<float>(i)}, | ||
| 35 | {.color = i == selected ? kGold : kText, .scale = 1.5f, .align = TextAlign::Centre}); | ||
| 36 | b.end(); | ||
| 37 | } | ||
ファイル: /dev/null | b/games/fighter/src/result_scene.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,92 @@ | |||
| 1 | // 勝利画面:勝った方を大きく、取ったラウンドの数、もう一度かタイトルへ / the win screen: the winner large, the rounds | ||
| 2 | // won, rematch or back to the title | ||
| 3 | #include "fight_scene.hh" | ||
| 4 | #include "hud.hh" | ||
| 5 | #include "menu_keys.hh" | ||
| 6 | #include "scenes.hh" | ||
| 7 | |||
| 8 | #include <cmath> | ||
| 9 | #include <memory> | ||
| 10 | #include <string> | ||
| 11 | |||
| 12 | namespace { | ||
| 13 | |||
| 14 | const char *const kNames[2] = {"HAYATE", "JIN"}; | ||
| 15 | const char *const kJapaneseNames[2] = {"ハヤテ", "ジン"}; | ||
| 16 | constexpr Vec2 kPivot = {0.5f, 116.0f / 120.0f}; | ||
| 17 | |||
| 18 | } // namespace | ||
| 19 | |||
| 20 | ResultScene::ResultScene(Game &game, MatchSettings matchSettings, int matchWinner, const int roundWins[2]) | ||
| 21 | : g(game), settings(matchSettings), winner(matchWinner), wins{roundWins[0], roundWins[1]} { | ||
| 22 | if (winner >= 0) pose.play(g.fighters[winner]->clip("win")); | ||
| 23 | } | ||
| 24 | |||
| 25 | void ResultScene::update(float dt) { | ||
| 26 | time += dt; | ||
| 27 | pose.update(dt); | ||
| 28 | g.stage->update(dt); | ||
| 29 | Input &in = g.input; | ||
| 30 | if (in.pressed(GLFW_KEY_ESCAPE)) scenes().replace(std::make_unique<TitleScene>(g), {.duration = 0.8f}); | ||
| 31 | else if (menuConfirm(in) && time > 0.5f) | ||
| 32 | scenes().replace(std::make_unique<FightScene>(g, settings), {.duration = 0.8f}); // もう一度 / rematch | ||
| 33 | } | ||
| 34 | |||
| 35 | void ResultScene::draw(float /*alpha*/) { | ||
| 36 | SpriteBatch &b = g.batch; | ||
| 37 | Camera2D view = Camera2D::screen(kViewSize); | ||
| 38 | view.centre.x = kStageWidth * 0.5f; | ||
| 39 | b.begin(view.matrix(), SpriteSort::Layer); | ||
| 40 | g.stage->drawBack(b, view); | ||
| 41 | float left = view.centre.x - kViewSize.x * 0.5f; | ||
| 42 | if (winner >= 0) { | ||
| 43 | // 勝者は2倍の大きさで勝ちポーズ、負けた方は奥で倒れている / the winner at twice the size in the victory pose, the | ||
| 44 | // loser lying further back | ||
| 45 | const SpriteSheet &ls = *g.fighters[1 - winner]; | ||
| 46 | Sprite lying = ls.sprite(ls.find("ko1"), {left + 470.0f, kGroundY - 26.0f}, kPivot); | ||
| 47 | lying.flipX = true; | ||
| 48 | lying.color = {0.75f, 0.7f, 0.8f, 1.0f}; | ||
| 49 | lying.layer = 1.0f; | ||
| 50 | b.draw(lying); | ||
| 51 | const SpriteSheet &ws = *g.fighters[winner]; | ||
| 52 | Sprite s = ws.sprite(pose.frame(), {left + 230.0f, kGroundY + 22.0f}, kPivot, 2.0f); | ||
| 53 | s.layer = 2.0f; | ||
| 54 | b.draw(s); | ||
| 55 | } else { | ||
| 56 | for (int i = 0; i < 2; ++i) { | ||
| 57 | const SpriteSheet &sh = *g.fighters[i]; | ||
| 58 | Sprite s = sh.sprite(sh.find("idle0"), {left + (i == 0 ? 220.0f : 420.0f), kGroundY}, kPivot); | ||
| 59 | s.flipX = i == 1; | ||
| 60 | s.layer = 2.0f; | ||
| 61 | b.draw(s); | ||
| 62 | } | ||
| 63 | } | ||
| 64 | g.stage->drawFront(b, view); | ||
| 65 | b.end(); | ||
| 66 | |||
| 67 | b.begin(Camera2D::screen(kViewSize).matrix(), SpriteSort::Layer); | ||
| 68 | TextStyle sub = {.color = kText, .scale = 2.0f, .align = TextAlign::Centre, .layer = 11.5f, .shadow = kOutline}; | ||
| 69 | if (winner >= 0) { | ||
| 70 | drawBigText(b, g.pixel, std::string(kNames[winner]) + " WINS!", {430, 70}, kGold, 4.0f); | ||
| 71 | g.pixel.draw(b, std::string(kJapaneseNames[winner]) + "の勝利", {430, 102}, sub); | ||
| 72 | } else { | ||
| 73 | drawBigText(b, g.pixel, "DRAW GAME", {320, 70}, kText, 4.0f); | ||
| 74 | g.pixel.draw(b, "引き分け", {320, 102}, sub); | ||
| 75 | } | ||
| 76 | // 取ったラウンド / the rounds won | ||
| 77 | std::string score = std::to_string(wins[0]) + " - " + std::to_string(wins[1]); | ||
| 78 | drawBigText(b, g.pixel, score, {winner >= 0 ? 430.0f : 320.0f, 150}, kText, 3.0f); | ||
| 79 | g.pixel.draw(b, "HAYATE JIN", {winner >= 0 ? 430.0f : 320.0f, 172}, | ||
| 80 | {.color = kText, .align = TextAlign::Centre, .layer = 11.5f, .shadow = kOutline}); | ||
| 81 | b.end(); | ||
| 82 | } | ||
| 83 | |||
| 84 | void ResultScene::drawUi(float /*alpha*/) { | ||
| 85 | SpriteBatch &b = g.batch; | ||
| 86 | b.begin(g.screen.matrix()); | ||
| 87 | b.drawRect({0, 688, 1280, 32}, {0.11f, 0.09f, 0.15f, 0.75f}); | ||
| 88 | float a = 0.55f + 0.45f * std::cos(time * 4.0f); | ||
| 89 | g.ui.draw(b, "Space / F もう一度 / rematch Esc タイトルへ / title", {640, 694}, | ||
| 90 | {.color = {0.91f, 0.88f, 0.82f, a}, .align = TextAlign::Centre}); | ||
| 91 | b.end(); | ||
| 92 | } | ||
ファイル: /dev/null | b/games/fighter/src/scenes.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,59 @@ | |||
| 1 | // 対戦以外のシーン:タイトル、一時停止、勝利画面 / the scenes besides the fight: title, pause, win screen | ||
| 2 | #pragma once | ||
| 3 | |||
| 4 | #include "game.hh" | ||
| 5 | #include "match.hh" | ||
| 6 | |||
| 7 | #include "engine/animation.hh" | ||
| 8 | #include "engine/scene.hh" | ||
| 9 | |||
| 10 | #include <string> | ||
| 11 | |||
| 12 | // タイトル:遊び方と難易度を選ぶ。後ろで舞台がゆっくり流れる / the title: pick the mode and difficulty; the stage pans | ||
| 13 | // slowly behind | ||
| 14 | class TitleScene : public Scene { | ||
| 15 | public: | ||
| 16 | explicit TitleScene(Game &game) : g(game) {} | ||
| 17 | void update(float dt) override; | ||
| 18 | void draw(float alpha) override; | ||
| 19 | void drawUi(float alpha) override; | ||
| 20 | |||
| 21 | private: | ||
| 22 | Game &g; | ||
| 23 | float time = 0.0f; | ||
| 24 | int selected = 0; | ||
| 25 | }; | ||
| 26 | |||
| 27 | // 一時停止(上に重ねる) / pause (an overlay) | ||
| 28 | class PauseScene : public Scene { | ||
| 29 | public: | ||
| 30 | explicit PauseScene(Game &game) : g(game) {} | ||
| 31 | bool isOverlay() const override { return true; } | ||
| 32 | void update(float dt) override; | ||
| 33 | void draw(float /*alpha*/) override {} | ||
| 34 | void drawUi(float alpha) override; | ||
| 35 | |||
| 36 | private: | ||
| 37 | Game &g; | ||
| 38 | float time = 0.0f; | ||
| 39 | int selected = 0; | ||
| 40 | }; | ||
| 41 | |||
| 42 | // 勝利画面:勝った方の勝ちポーズ、取った本数。もう一度・タイトルへ / the win screen: the winner's victory pose and the | ||
| 43 | // rounds won; rematch or back to the title | ||
| 44 | class ResultScene : public Scene { | ||
| 45 | public: | ||
| 46 | // winner = 0 / 1、-1 = 引き分け / winner = 0 / 1, -1 = a draw game | ||
| 47 | ResultScene(Game &game, MatchSettings settings, int winner, const int wins[2]); | ||
| 48 | void update(float dt) override; | ||
| 49 | void draw(float alpha) override; | ||
| 50 | void drawUi(float alpha) override; | ||
| 51 | |||
| 52 | private: | ||
| 53 | Game &g; | ||
| 54 | MatchSettings settings; | ||
| 55 | int winner; | ||
| 56 | int wins[2]; | ||
| 57 | float time = 0.0f; | ||
| 58 | Animator pose; | ||
| 59 | }; | ||
ファイル: /dev/null | b/games/fighter/src/stage.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,90 @@ | |||
| 1 | // スクロールする舞台 / the scrolling stage | ||
| 2 | #include "stage.hh" | ||
| 3 | |||
| 4 | #include "engine/sprite_sheet.hh" | ||
| 5 | |||
| 6 | #include <algorithm> | ||
| 7 | #include <cmath> | ||
| 8 | #include <string> | ||
| 9 | |||
| 10 | namespace { | ||
| 11 | |||
| 12 | constexpr float kPetalFactor = 1.15f; // 花びらは地面より少し手前 / petals are a little in front of the ground | ||
| 13 | constexpr int kPetals = 28; | ||
| 14 | |||
| 15 | } // namespace | ||
| 16 | |||
| 17 | std::optional<Stage> Stage::load() { | ||
| 18 | struct Spec { | ||
| 19 | const char *file; | ||
| 20 | float factor, layer; | ||
| 21 | bool front; | ||
| 22 | }; | ||
| 23 | // 幅は 640 + factor × (1024 − 640):カメラが端に着いたとき、層もちょうど端 / widths are 640 + factor × (1024 − 640): | ||
| 24 | // when the camera reaches an edge, so does every layer (the images have these widths) | ||
| 25 | const Spec specs[] = { | ||
| 26 | {"stage_sky", 0.05f, 0.0f, false}, {"stage_far", 0.25f, 0.1f, false}, {"stage_mid", 0.5f, 0.2f, false}, | ||
| 27 | {"stage_ground", 1.0f, 0.3f, false}, {"stage_front", 1.3f, 12.0f, true}, | ||
| 28 | }; | ||
| 29 | Stage stage; | ||
| 30 | for (const Spec &s : specs) { | ||
| 31 | std::optional<Texture2D> t = loadSpriteTexture(std::string("games/fighter/assets/") + s.file + ".png"); | ||
| 32 | if (!t) return std::nullopt; | ||
| 33 | (s.front ? stage.front : stage.back).push_back({std::move(*t), s.factor, s.layer}); | ||
| 34 | } | ||
| 35 | for (int i = 0; i < kPetals; ++i) { | ||
| 36 | Petal p{{stage.rng.range(0.0f, 760.0f), stage.rng.range(-40.0f, 300.0f)}, | ||
| 37 | {stage.rng.range(-28.0f, -12.0f), stage.rng.range(14.0f, 26.0f)}, stage.rng.range(0.0f, 6.28f)}; | ||
| 38 | stage.petals.push_back(p); | ||
| 39 | } | ||
| 40 | return stage; | ||
| 41 | } | ||
| 42 | |||
| 43 | float Stage::clampCamera(float centreX, float viewWidth) { | ||
| 44 | float half = viewWidth * 0.5f; | ||
| 45 | return std::clamp(centreX, half, kStageWidth - half); | ||
| 46 | } | ||
| 47 | |||
| 48 | // 視差:その層のカメラはfactor倍だけ動く。画面の左端が舞台のxなら、層は −x·factor だけずらして描く | ||
| 49 | // Parallax: a layer's camera moves `factor` times as far. If the view's left edge is at stage x, the layer is drawn | ||
| 50 | // shifted by −x·factor | ||
| 51 | void Stage::drawLayer(SpriteBatch &batch, const ParallaxLayer &l, const Camera2D &camera) const { | ||
| 52 | float left = camera.centre.x - camera.viewSize.x * 0.5f; | ||
| 53 | Vec2 size = {static_cast<float>(l.texture.width()), static_cast<float>(l.texture.height())}; | ||
| 54 | // ワールドの座標で描く:層の左端 = left − left·factor(整数に丸めてピクセルをそろえる) | ||
| 55 | // Drawn in world coordinates: the layer's left edge = left − left·factor (rounded to whole pixels) | ||
| 56 | float x = left - std::round(left * l.factor); | ||
| 57 | // 縦は動かない(カメラの高さは固定):層の上端はワールドのy = 0 / no vertical parallax (the camera height is fixed): | ||
| 58 | // a layer's top is at world y = 0 | ||
| 59 | batch.draw({.texture = &l.texture, .position = {x, 0.0f}, .size = size, .layer = l.layer}); | ||
| 60 | } | ||
| 61 | |||
| 62 | void Stage::drawBack(SpriteBatch &batch, const Camera2D &camera) const { | ||
| 63 | for (const ParallaxLayer &l : back) drawLayer(batch, l, camera); | ||
| 64 | } | ||
| 65 | |||
| 66 | void Stage::drawFront(SpriteBatch &batch, const Camera2D &camera) const { | ||
| 67 | float left = camera.centre.x - camera.viewSize.x * 0.5f; | ||
| 68 | // 花びら:手前の層(factor 1.15)の上を左下へ。画面の外に出たら上から戻る(760幅で輪になる) | ||
| 69 | // Petals: drift down-left on a 1.15 layer, wrapping round a 760-wide band | ||
| 70 | for (const Petal &p : petals) { | ||
| 71 | float x = std::fmod(p.position.x - left * kPetalFactor, 760.0f); | ||
| 72 | if (x < 0.0f) x += 760.0f; | ||
| 73 | float sway = 4.0f * std::sin(time * 2.0f + p.phase); | ||
| 74 | Vec2 at = {left + std::round(x - 60.0f + sway), std::round(p.position.y)}; | ||
| 75 | bool flat = std::sin(time * 5.0f + p.phase) > 0.3f; // くるくる回る:2×2と1×2 / tumbling: 2 × 2 or 1 × 2 | ||
| 76 | batch.drawRect({at.x, at.y, flat ? 2.0f : 1.0f, 2.0f}, hexColor(0xffc8dcff), 11.0f); | ||
| 77 | } | ||
| 78 | for (const ParallaxLayer &l : front) drawLayer(batch, l, camera); | ||
| 79 | } | ||
| 80 | |||
| 81 | void Stage::update(float dt) { | ||
| 82 | time += dt; | ||
| 83 | for (Petal &p : petals) { | ||
| 84 | p.position += p.velocity * dt; | ||
| 85 | if (p.position.y > 370.0f) { | ||
| 86 | p.position.y = -10.0f; | ||
| 87 | p.position.x = rng.range(0.0f, 760.0f); | ||
| 88 | } | ||
| 89 | } | ||
| 90 | } | ||
ファイル: /dev/null | b/games/fighter/src/stage.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,52 @@ | |||
| 1 | // スクロールする舞台:視差の層(遠いほどゆっくり動く)、カメラの範囲、舞い散る花びら | ||
| 2 | // The scrolling stage: parallax layers (the farther, the slower), the camera's limits, falling petals | ||
| 3 | #pragma once | ||
| 4 | |||
| 5 | #include "engine/camera2d.hh" | ||
| 6 | #include "engine/rng.hh" | ||
| 7 | #include "engine/sprite_batch.hh" | ||
| 8 | #include "engine/texture.hh" | ||
| 9 | |||
| 10 | #include <optional> | ||
| 11 | #include <vector> | ||
| 12 | |||
| 13 | constexpr float kStageWidth = 1024.0f; // 舞台の幅(ワールドのピクセル)。見えるのは640 / the stage width (world pixels); | ||
| 14 | // 640 are visible | ||
| 15 | |||
| 16 | // 一枚の層:factor = カメラに対する動きの割合(0 = 動かない空、1 = 地面と同じ、> 1 = 手前) | ||
| 17 | // One layer: factor = how much of the camera's motion it follows (0 = a still sky, 1 = with the ground, > 1 = in | ||
| 18 | // front) | ||
| 19 | struct ParallaxLayer { | ||
| 20 | Texture2D texture; | ||
| 21 | float factor; | ||
| 22 | float layer; // SpriteSort::Layerの順番 / order for SpriteSort::Layer | ||
| 23 | }; | ||
| 24 | |||
| 25 | class Stage { | ||
| 26 | public: | ||
| 27 | // games/fighter/assets/stage_*.png を読む / loads games/fighter/assets/stage_*.png | ||
| 28 | static std::optional<Stage> load(); | ||
| 29 | |||
| 30 | // カメラの中心のxを舞台の中に収める:画面の端が舞台の外を映さない / clamps the camera center's x so the view never | ||
| 31 | // shows anything outside the stage | ||
| 32 | static float clampCamera(float centreX, float viewWidth); | ||
| 33 | // ファイターの後ろの層(空・山・寺・地面)と、前の層(灯籠・花びら)。cameraはワールドのカメラ | ||
| 34 | // The layers behind the fighters (sky, mountains, temple, ground) and in front (lanterns, petals). camera is the | ||
| 35 | // world camera | ||
| 36 | void drawBack(SpriteBatch &batch, const Camera2D &camera) const; | ||
| 37 | void drawFront(SpriteBatch &batch, const Camera2D &camera) const; | ||
| 38 | void update(float dt); // 花びら / the petals | ||
| 39 | |||
| 40 | private: | ||
| 41 | struct Petal { | ||
| 42 | Vec2 position; // 画面の座標(花びらは手前の層:factor 1.15) / screen-ish coordinates (petals live on a 1.15 layer) | ||
| 43 | Vec2 velocity; | ||
| 44 | float phase; | ||
| 45 | }; | ||
| 46 | void drawLayer(SpriteBatch &batch, const ParallaxLayer &l, const Camera2D &camera) const; | ||
| 47 | |||
| 48 | std::vector<ParallaxLayer> back, front; | ||
| 49 | std::vector<Petal> petals; | ||
| 50 | Rng rng{32}; | ||
| 51 | float time = 0.0f; | ||
| 52 | }; | ||
ファイル: /dev/null | b/games/fighter/src/title_scene.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,105 @@ | |||
| 1 | // タイトル:遊び方と難易度を選ぶ / the title: pick a mode and the difficulty | ||
| 2 | #include "fight_scene.hh" | ||
| 3 | #include "hud.hh" | ||
| 4 | #include "menu_keys.hh" | ||
| 5 | #include "scenes.hh" | ||
| 6 | |||
| 7 | #include <cmath> | ||
| 8 | #include <memory> | ||
| 9 | #include <string> | ||
| 10 | |||
| 11 | namespace { | ||
| 12 | |||
| 13 | struct Item { | ||
| 14 | const char *english, *japanese; | ||
| 15 | Mode mode; | ||
| 16 | }; | ||
| 17 | constexpr Item kItems[] = { | ||
| 18 | {"1P VS CPU", "1P 対 CPU", Mode::VsCpu}, | ||
| 19 | {"2P VS", "2人で対戦", Mode::TwoPlayers}, | ||
| 20 | {"CPU VS CPU", "CPU 対 CPU", Mode::CpuVsCpu}, | ||
| 21 | {"TRAINING", "練習", Mode::Training}, | ||
| 22 | }; | ||
| 23 | constexpr int kItemCount = 5; // 4つの遊び方 + 難易度 / four modes + the difficulty | ||
| 24 | const char *const kDifficultyJa[] = {"易しい", "普通", "難しい"}; | ||
| 25 | |||
| 26 | // タイトルの後ろの二人(舞台のワールド座標、足元) / the two fighters behind the title (stage world coordinates, feet) | ||
| 27 | constexpr float kTitleX[2] = {kStageWidth * 0.5f - 210.0f, kStageWidth * 0.5f + 210.0f}; | ||
| 28 | |||
| 29 | } // namespace | ||
| 30 | |||
| 31 | void TitleScene::update(float dt) { | ||
| 32 | time += dt; | ||
| 33 | g.stage->update(dt); | ||
| 34 | Input &in = g.input; | ||
| 35 | if (in.pressed(GLFW_KEY_ESCAPE)) { | ||
| 36 | scenes().pop(); // 最後のシーン:終了 / the last scene: quit | ||
| 37 | return; | ||
| 38 | } | ||
| 39 | if (menuUp(in)) selected = (selected + kItemCount - 1) % kItemCount; | ||
| 40 | if (menuDown(in)) selected = (selected + 1) % kItemCount; | ||
| 41 | int d = static_cast<int>(g.difficulty); | ||
| 42 | if (menuLeft(in)) g.difficulty = static_cast<Difficulty>((d + 2) % 3); | ||
| 43 | if (menuRight(in)) g.difficulty = static_cast<Difficulty>((d + 1) % 3); | ||
| 44 | if (menuConfirm(in) && selected < 4) | ||
| 45 | scenes().replace(std::make_unique<FightScene>(g, MatchSettings{kItems[selected].mode, g.difficulty}), | ||
| 46 | {.duration = 0.8f}); | ||
| 47 | } | ||
| 48 | |||
| 49 | void TitleScene::draw(float /*alpha*/) { | ||
| 50 | SpriteBatch &b = g.batch; | ||
| 51 | // カメラはゆっくり左右に:視差の層がそれぞれの速さで動く / the camera drifts left and right: each parallax layer | ||
| 52 | // moves at its own speed | ||
| 53 | Camera2D view = Camera2D::screen(kViewSize); | ||
| 54 | view.centre.x = std::round(kStageWidth * 0.5f + 150.0f * std::sin(time * 0.3f)); | ||
| 55 | b.begin(view.matrix(), SpriteSort::Layer); | ||
| 56 | g.stage->drawBack(b, view); | ||
| 57 | for (int i = 0; i < 2; ++i) { | ||
| 58 | const SpriteSheet &sheet = *g.fighters[i]; | ||
| 59 | const AnimationClip *idle = sheet.clip("idle"); | ||
| 60 | int frame = idle->frames[static_cast<size_t>(time * idle->fps + static_cast<float>(i) * 2.0f) % idle->frames.size()]; | ||
| 61 | Sprite s = sheet.sprite(frame, {kTitleX[i], kGroundY}, {0.5f, 116.0f / 120.0f}); | ||
| 62 | s.flipX = i == 1; | ||
| 63 | s.layer = 2.0f; | ||
| 64 | b.draw(s); | ||
| 65 | } | ||
| 66 | g.stage->drawFront(b, view); | ||
| 67 | b.end(); | ||
| 68 | |||
| 69 | b.begin(Camera2D::screen(kViewSize).matrix(), SpriteSort::Layer); | ||
| 70 | drawBigText(b, g.pixel, "FIGHTER", {320, 62}, kGold, 6.0f); | ||
| 71 | g.pixel.draw(b, "2D 対戦アクション", {320, 104}, | ||
| 72 | {.color = kText, .scale = 2.0f, .align = TextAlign::Centre, .layer = 11.0f, .shadow = kOutline}); | ||
| 73 | // メニュー:英語と日本語の二列 / the menu: English and Japanese columns | ||
| 74 | Rect panel = {176, 150, 288, 116}; | ||
| 75 | b.drawRect(panel, {0.11f, 0.09f, 0.15f, 0.78f}, 10.0f); | ||
| 76 | b.drawRectOutline(panel, kGold, 1.0f, 10.1f); | ||
| 77 | for (int i = 0; i < kItemCount; ++i) { | ||
| 78 | bool on = i == selected; | ||
| 79 | Vec4 c = on ? kGold : kText; | ||
| 80 | float y = panel.y + 10.0f + 20.0f * static_cast<float>(i); | ||
| 81 | std::string en, ja; | ||
| 82 | if (i < 4) { | ||
| 83 | en = kItems[i].english; | ||
| 84 | ja = kItems[i].japanese; | ||
| 85 | } else { | ||
| 86 | en = std::string("< ") + difficultyName(g.difficulty) + " >"; | ||
| 87 | ja = std::string("難易度 ") + kDifficultyJa[static_cast<int>(g.difficulty)]; | ||
| 88 | } | ||
| 89 | if (on) g.pixel.draw(b, ">", {panel.x + 10.0f, y}, {.color = c, .layer = 11.0f}); | ||
| 90 | g.pixel.draw(b, en, {panel.x + 24.0f, y}, {.color = c, .layer = 11.0f}); | ||
| 91 | g.pixel.draw(b, ja, {panel.x + 160.0f, y}, {.color = c, .layer = 11.0f}); | ||
| 92 | } | ||
| 93 | b.end(); | ||
| 94 | } | ||
| 95 | |||
| 96 | void TitleScene::drawUi(float /*alpha*/) { | ||
| 97 | SpriteBatch &b = g.batch; | ||
| 98 | b.begin(g.screen.matrix()); | ||
| 99 | b.drawRect({0, 688, 1280, 32}, {0.11f, 0.09f, 0.15f, 0.75f}); | ||
| 100 | // 点滅する案内 / a blinking prompt | ||
| 101 | float a = 0.55f + 0.45f * std::cos(time * 4.0f); | ||
| 102 | g.ui.draw(b, "W S 選ぶ・A D 難易度・Space / F 決定・Esc 終了 select / difficulty / start / quit", {640, 694}, | ||
| 103 | {.color = {0.91f, 0.88f, 0.82f, a}, .align = TextAlign::Centre}); | ||
| 104 | b.end(); | ||
| 105 | } | ||
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。