diff --git a/games/fighter/CMakeLists.txt b/games/fighter/CMakeLists.txt index 2141b2a..9a62259 100644 --- a/games/fighter/CMakeLists.txt +++ b/games/fighter/CMakeLists.txt @@ -2,13 +2,19 @@ # 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/scene_graph.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) diff --git a/games/fighter/README.md b/games/fighter/README.md index f1f2171..1e2788c 100644 --- a/games/fighter/README.md +++ b/games/fighter/README.md @@ -7,6 +7,14 @@ build\games\fighter\Debug\fighter.exe # Windows (or F5 with the "fighter" target) ``` +## 遊び方 / Modes(第32章から / from chapter 32) + +タイトルで選ぶ / chosen on the title screen (W S 選ぶ / select, A D 難易度 / difficulty, Space・Enter・F 決定 / start): +1P 対 CPU / 1P vs CPU, 2人で対戦 / 2P vs, CPU 対 CPU / CPU vs CPU (watch), 練習 / training(時間なし / no timer)。 +3本勝負(先に2本)、1ラウンド60秒、時間切れは体力の多い方の勝ち。難易度:EASY / NORMAL / HARD(CPUの反応の速さと確率)。 +Best of three (first to two rounds), 60 s per round, time over = more health wins. Difficulty: EASY / NORMAL / HARD +(the CPU's reaction time and probabilities). Esc / P 一時停止 / pause. + ## 操作 / Controls(一台のキーボードを二人で / two players on one keyboard) | | 1P | 2P | @@ -26,5 +34,6 @@ build\games\fighter\Debug\fighter.exe # Windows (or F5 with the "fighter" tar ゲームパッド(GLFW 3.3のゲームパッドAPI):1台目が1P、2台目が2P(十字キーか左スティック、A/X パンチ、B/Y キック)。 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). -F1 判定の箱(食らい = 青、攻撃 = 赤、押し合い = 緑、ソケット = 黄)と状態 / boxes (hurt blue, hit red, push green, -sockets yellow) and states, Esc 終了 / quit. +F1 判定の箱(食らい = 青、攻撃 = 赤、押し合い = 緑、ソケット = 黄)と状態、CPUの意図 / boxes (hurt blue, hit red, +push green, sockets yellow), states and the CPU's intent; Esc 一時停止 / pause (タイトルではEscで終了 / Esc quits on the +title screen). diff --git a/games/fighter/assets/LICENSE.txt b/games/fighter/assets/LICENSE.txt index d1f82b1..6737a2a 100644 --- a/games/fighter/assets/LICENSE.txt +++ b/games/fighter/assets/LICENSE.txt @@ -9,3 +9,11 @@ fighter.boxes コマごとの食らい判定・攻撃判定・ソケット (made from the skeleton) (chapter 31) effects.png/.atlas 火花・ガードの火花・砂ぼこり・鉢巻の尾・星・影 / hit and guard sparks, dust, headband tails, stars, shadow (chapter 31) +stage_sky.png 舞台の空(夕焼け、視差0.05) / the stage's sunset sky (parallax 0.05) (chapter 32) +stage_far.png 遠くの山(視差0.25) / distant mountains (parallax 0.25) (chapter 32) +stage_mid.png 鳥居・五重塔・桜・寺の塀(視差0.5) / torii, pagoda, cherry trees, temple wall (parallax 0.5) + (chapter 32) +stage_ground.png 石畳(視差1、ファイターが立つ面) / the stone paving the fighters stand on (parallax 1) + (chapter 32) +stage_front.png 手前の灯籠と草(視差1.3、ファイターより前) / foreground lanterns and grass (parallax 1.3, in front of + the fighters) (chapter 32) diff --git a/games/fighter/assets/stage_far.png b/games/fighter/assets/stage_far.png new file mode 100644 index 0000000..c9800d3 Binary files /dev/null and b/games/fighter/assets/stage_far.png differ diff --git a/games/fighter/assets/stage_front.png b/games/fighter/assets/stage_front.png new file mode 100644 index 0000000..20667e4 Binary files /dev/null and b/games/fighter/assets/stage_front.png differ diff --git a/games/fighter/assets/stage_ground.png b/games/fighter/assets/stage_ground.png new file mode 100644 index 0000000..ff730be Binary files /dev/null and b/games/fighter/assets/stage_ground.png differ diff --git a/games/fighter/assets/stage_mid.png b/games/fighter/assets/stage_mid.png new file mode 100644 index 0000000..e7a50b0 Binary files /dev/null and b/games/fighter/assets/stage_mid.png differ diff --git a/games/fighter/assets/stage_sky.png b/games/fighter/assets/stage_sky.png new file mode 100644 index 0000000..3598a47 Binary files /dev/null and b/games/fighter/assets/stage_sky.png differ diff --git a/games/fighter/src/ai.cc b/games/fighter/src/ai.cc new file mode 100644 index 0000000..3dd4fb4 --- /dev/null +++ b/games/fighter/src/ai.cc @@ -0,0 +1,179 @@ +// コンピューターの相手 / the computer opponent +#include "ai.hh" + +#include + +namespace { + +// 考える 反応 ガード 対空 反撃 攻め つなぐ / 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 +}; + +constexpr float kAttackRange = 62.0f; // 突き・蹴りが届く距離(足元の間) / where punches and kicks reach (feet to feet) + +} // namespace + +const char *difficultyName(Difficulty d) { + switch (d) { + case Difficulty::Easy: return "EASY"; + case Difficulty::Normal: return "NORMAL"; + case Difficulty::Hard: return "HARD"; + } + return "?"; +} + +const AiProfile &aiProfile(Difficulty d) { return kProfiles[static_cast(d)]; } + +AiController::AiController(Difficulty difficulty, std::uint32_t seed) : profile(aiProfile(difficulty)), rng(seed) {} + +void AiController::reset() { + intent = Intent::Wait; + timer = 30; + reaction = -1; + sawAttack = punished = pressed = false; +} + +const char *AiController::intentName() const { + switch (intent) { + case Intent::Wait: return "WAIT"; + case Intent::Approach: return "APPROACH"; + case Intent::Retreat: return "RETREAT"; + case Intent::Attack: return "ATTACK"; + case Intent::JumpIn: return "JUMP-IN"; + case Intent::Guard: return "GUARD"; + case Intent::AntiAir: return "ANTI-AIR"; + } + return "?"; +} + +void AiController::setIntent(Intent next, int frames) { + intent = next; + timer = frames; + pressed = false; +} + +// 意図の長さ: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(profile.thinkFrames); + return rng.range(static_cast(std::lround(lo * t)), static_cast(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)); + } +} + +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); + + // 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; +} diff --git a/games/fighter/src/ai.hh b/games/fighter/src/ai.hh new file mode 100644 index 0000000..77b360e --- /dev/null +++ b/games/fighter/src/ai.hh @@ -0,0 +1,55 @@ +// コンピューターの相手:人と同じ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 + +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; +}; diff --git a/games/fighter/src/fight_scene.cc b/games/fighter/src/fight_scene.cc index 461d012..b6a2c12 100644 --- a/games/fighter/src/fight_scene.cc +++ b/games/fighter/src/fight_scene.cc @@ -1,63 +1,41 @@ -// 対戦の場面(第31章:技の当たり、ヒットストップ、体力、エフェクト。KOすると練習を仕切り直す) -// The fight scene (chapter 31: hits, hit stop, health, effects; a KO restarts the training) +// 対戦の場面(第32章:スクロールする舞台、CPU、ラウンド) / the fight scene (chapter 32: scrolling stage, CPU, rounds) #include "fight_scene.hh" +#include "hud.hh" +#include "scenes.hh" + #include "engine/collision.hh" #include #include #include +#include #include -#include namespace { -constexpr float kStageLeft = 16.0f; -constexpr float kStageRight = 624.0f; -constexpr Vec2 kStart[2] = {{200.0f, kGroundY}, {440.0f, kGroundY}}; - -constexpr Vec4 kBeam = hexColor(0x3b2a2eff), kBeamLight = hexColor(0x5a4040ff); -constexpr Vec4 kPlaster = hexColor(0xdccdaeff), kPlasterShade = hexColor(0xc4b393ff); -constexpr Vec4 kShoji = hexColor(0xf4ecd8ff), kLattice = hexColor(0x8a6a50ff); -constexpr Vec4 kWainscot = hexColor(0x6e4a36ff), kWainscotDark = hexColor(0x553626ff); -constexpr Vec4 kPlankA = hexColor(0xb07c50ff), kPlankB = hexColor(0xa16f47ff), kPlankLine = hexColor(0x6e4630ff); -constexpr Vec4 kOutline = hexColor(0x1b1726ff); -constexpr Vec4 kText = hexColor(0xfff4d8ff), kGold = hexColor(0xf2c14eff); - -void clampToStage(Fighter &f) { - Rect b = f.pushbox(); - if (b.left() < kStageLeft) f.position.x += kStageLeft - b.left(); - if (b.right() > kStageRight) f.position.x -= b.right() - kStageRight; -} +constexpr float kStageLeft = 12.0f; // 舞台の端の壁 / the walls at the stage ends +constexpr float kStageRight = kStageWidth - 12.0f; +constexpr float kViewMargin = 8.0f; // 画面の端からの余白(画面の端も壁) / margin to the view edges + // (the view edges are walls too) +constexpr Vec2 kStart[2] = {{kStageWidth * 0.5f - 110.0f, kGroundY}, {kStageWidth * 0.5f + 110.0f, kGroundY}}; +constexpr int kIntroFrames = 100; +constexpr int kFinishFrames = 230; +constexpr int kWinPoseAt = 70; +const char *const kJapaneseNames[2] = {"ハヤテ", "ジン"}; -bool atWall(const Fighter &f) { +void clampX(Fighter &f, float left, float right) { Rect b = f.pushbox(); - return b.left() <= kStageLeft + 0.5f || b.right() >= kStageRight - 0.5f; + if (b.left() < left) f.position.x += left - b.left(); + if (b.right() > right) f.position.x -= b.right() - right; } -// 二つの箱の重なり(火花を出す場所) / the overlap of two boxes (where the spark goes) Rect intersection(const Rect &a, const Rect &b) { float l = std::max(a.left(), b.left()), t = std::max(a.top(), b.top()); float r = std::min(a.right(), b.right()), bt = std::min(a.bottom(), b.bottom()); return {l, t, r - l, bt - t}; } -// 大きな文字(K.O.など):8方向に輪郭を描いてから本体 / big text (K.O. and so on): an outline in 8 directions, then -// the text itself -void drawBigText(SpriteBatch &b, const Font &font, std::string_view text, Vec2 centre, Vec4 color, float scale) { - Vec2 size = font.measure(text, scale); - Vec2 at = {centre.x, std::round(centre.y - size.y * 0.5f)}; - TextStyle s = {.color = kOutline, .scale = scale, .align = TextAlign::Centre, .layer = 11.0f}; - 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}, - Vec2{3, 4}, Vec2{0, 4}}) - font.draw(b, text, at + d, s); - s.color = color; - s.layer = 11.5f; - font.draw(b, text, at, s); -} - -// 体力ゲージ:中央側に寄せて、外側から減る。白い「跡」は少し遅れて追いかける -// A health bar: anchored at the center side, it drains from the outer end. The white "trail" follows a little later void drawHealthBar(SpriteBatch &b, Rect r, float health, float trail, bool rightSide) { b.drawRect({r.x - 2, r.y - 2, r.w + 4, r.h + 4}, kOutline, 10.0f); b.drawRect(r, hexColor(0x4a2434ff), 10.1f); @@ -68,52 +46,73 @@ void drawHealthBar(SpriteBatch &b, Rect r, float health, float trail, bool right b.drawRect(part(trail), hexColor(0xf6f0e8ff), 10.2f); bool low = health <= kMaxHealth * 0.25f; Rect h = part(health); - b.drawRect(h, low ? hexColor(0xe8483cff) : kGold, 10.3f); + b.drawRect(h, low ? kRed : kGold, 10.3f); b.drawRect({h.x, h.y, h.w, 2}, low ? hexColor(0xff8a70ff) : hexColor(0xffe48aff), 10.4f); b.drawRect({h.x, h.bottom() - 2, h.w, 2}, low ? hexColor(0xa82a30ff) : hexColor(0xc98a26ff), 10.4f); } } // namespace -FightScene::FightScene(Game &game) - : g(game), camera(Camera2D::screen(kViewSize)), +FightScene::FightScene(Game &game, MatchSettings matchSettings) + : g(game), settings(matchSettings), fighters{Fighter(*game.fighters[0], *game.effects, *game.frameData, "HAYATE", "tail_hayate", kStart[0], 1.0f), Fighter(*game.fighters[1], *game.effects, *game.frameData, "JIN", "tail_jin", kStart[1], -1.0f)}, - effects(*game.effects) {} + effects(*game.effects) { + // 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); + startRound(); +} -void FightScene::resetRound() { - fighters[0].reset(kStart[0], 1.0f); - fighters[1].reset(kStart[1], -1.0f); - effects.clear(); +void FightScene::startRound() { for (int i = 0; i < 2; ++i) { + fighters[i].reset(kStart[i], i == 0 ? 1.0f : -1.0f); trail[i] = kMaxHealth; comboTime[i] = 0; + if (ai[i]) ai[i]->reset(); } + effects.clear(); hitstop = shake = koTime = 0; victim = -1; + timer = kRoundSeconds * 60; + roundWinner = -1; + timeOver = false; + phase = settings.mode == Mode::Training ? RoundPhase::Fight : RoundPhase::Intro; + phaseTime = 0; +} + +// 一時停止が上に載った:補間で震えないように前の位置 = 今 / the pause went on top: previous = current, so the +// interpolation does not wobble +void FightScene::pause() { + for (Fighter &f : fighters) f.savePrevious(); } void FightScene::update(float dt) { ++steps; Input &in = g.input; - if (in.pressed(GLFW_KEY_ESCAPE)) { - scenes().pop(); + if (in.pressed(GLFW_KEY_ESCAPE) || in.pressed(GLFW_KEY_P)) { + scenes().push(std::make_unique(g)); return; } if (in.pressed(GLFW_KEY_F1)) g.showBoxes = !g.showBoxes; - Controls controls[2] = {readControls(in, 0, pads[0]), readControls(in, 1, pads[1])}; - // バッファはヒットストップ中も記録する:止まっている間に押した技が、動き出した瞬間に出る - // The buffers record during hit stop too: a move pressed while frozen comes out the moment things move again + // 入力:人はキーボードとパッド、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(); // 止まっていても前の位置 = 今(補間で震えない) / even when frozen (no wobble) + fighters[i].savePrevious(); } effects.update(dt); + g.stage->update(dt); for (int i = 0; i < 2; ++i) comboTime[i] = std::max(0, comboTime[i] - 1); shake = std::max(0, shake - 1); - // ヒットストップ:当たった瞬間、数フレーム全部止める(重さが伝わる)。火花のアニメーションだけ進む - // Hit stop: everything freezes for a few frames on contact (it sells the impact). Only the sparks keep animating if (hitstop > 0) { --hitstop; return; @@ -123,30 +122,27 @@ void FightScene::update(float dt) { float startX[2] = {fighters[0].position.x, fighters[1].position.x}; bool threat[2]; for (int i = 0; i < 2; ++i) { - // 相手が近く(150ピクセル)で技の発生か持続にいる / the opponent is in a move's startup or active frames nearby const Fighter &o = fighters[1 - i]; MovePhase p = o.phase(); threat[i] = (p == MovePhase::Startup || p == MovePhase::Active) && std::abs(o.position.x - startX[i]) < 150.0f; } for (int i = 0; i < 2; ++i) fighters[i].update(dt, controls[i], startX[1 - i], threat[i]); separate(); + keepInView(); resolveHits(); for (Fighter &f : fighters) if (f.landed) effects.dust(f.position, f.facing); - - // 体力の跡:0.5秒待ってから減る / the health trail: waits half a second, then drains for (int i = 0; i < 2; ++i) { if (trailDelay[i] > 0) --trailDelay[i]; else trail[i] = std::max(static_cast(fighters[i].health), trail[i] - 0.6f); } - // 練習:KOから3秒で仕切り直し / training: restart 3 s after a KO - if (koTime > 0 && ++koTime > 180) resetRound(); + updateRound(); } void FightScene::separate() { Fighter &a = fighters[0], &b = fighters[1]; - clampToStage(a); - clampToStage(b); + clampX(a, kStageLeft, kStageRight); + clampX(b, kStageLeft, kStageRight); Rect ra = a.pushbox(), rb = b.pushbox(); if (!overlaps(ra, rb)) return; float overlap = std::min(ra.right(), rb.right()) - std::max(ra.left(), rb.left()); @@ -154,17 +150,32 @@ void FightScene::separate() { a.position.x += dir * overlap * 0.5f; b.position.x -= dir * overlap * 0.5f; float ax = a.position.x, bx = b.position.x; - clampToStage(a); - clampToStage(b); + clampX(a, kStageLeft, kStageRight); + clampX(b, kStageLeft, kStageRight); float da = a.position.x - ax, db = b.position.x - bx; b.position.x += da; a.position.x += db; } -// 当たり判定:攻撃側の攻撃判定(持続フレーム)と相手の食らい判定が重なったら当たり。 -// 先に二人分を調べてから当てる:同時に当たったら相打ち -// Hit detection: the attacker's hit box (active frames) overlapping one of the opponent's hurt boxes is a hit. -// Both directions are checked first and applied afterwards: simultaneous hits trade +// 画面の端も壁:カメラは二人の真ん中を追い、舞台の中に収まる。二人ともその画面の中にいなければならない +// 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; +} + void FightScene::resolveHits() { // 技はここで覚える:相打ちだと、一つ目のtakeHitが二人目の技(move)を消してしまう // The move is remembered here: in a trade the first takeHit clears the second attacker's move @@ -186,6 +197,7 @@ void FightScene::resolveHits() { break; } } + float viewCentre = Stage::clampCamera(0.5f * (fighters[0].position.x + fighters[1].position.x), kViewSize.x); float push[2] = {0.0f, 0.0f}; // 壁際の押し返し(後でまとめて) / corner push-backs (applied at the end) for (int c = 0; c < count; ++c) { int i = contacts[c].attacker; @@ -194,9 +206,12 @@ void FightScene::resolveHits() { a.confirmHit(); bool wasHit = v.state == FighterState::Hitstun; HitResult r = v.takeHit(m, a.facing, contacts[c].blocked); - // 壁際:相手が下がれないので自分が下がる(壁で永久に固めさせない) / at the wall the opponent cannot move back, - // so the attacker is pushed back instead (no endless corner pressure) - if (atWall(v)) push[i] = m.knockback * 0.7f; + // 壁(舞台の端か画面の端)を背にした相手には、自分が下がる / 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; bool blocked = r == HitResult::Blocked; int stop = blocked ? m.hitstop - 3 : m.hitstop; if (r == HitResult::KO) { @@ -208,9 +223,7 @@ void FightScene::resolveHits() { top = i; bool heavy = m.damage >= 10 || r == HitResult::KO; if (heavy && !blocked) shake = stop; - Rect w = contacts[c].where; - effects.spark(w.centre(), blocked, heavy); - // 記録(台本で動かしたときの確認に) / a log line (to check scripted runs) + effects.spark(contacts[c].where.centre(), blocked, heavy); static const char *const kResult[] = {"hit", "blocked", "KO"}; printf("step %d: %s %s -> %s %s, hp %d, combo %d, hit stop %d\n", steps, a.name.c_str(), m.name, v.name.c_str(), kResult[static_cast(r)], v.health, blocked ? 0 : v.combo, stop); @@ -229,142 +242,194 @@ void FightScene::resolveHits() { if (push[i] > 0.0f) fighters[i].pushBack(push[i]); } -void FightScene::drawBackground() { - SpriteBatch &b = g.batch; - // 画面より8ピクセルずつ広く描く:画面が揺れても端に隙間ができない / drawn 8 pixels wider than the view on every side, - // so the screen shake never opens a gap at the edges - // 梁と漆喰の壁 / beams and the plaster wall - b.drawRect({-8, -8, 656, 376}, kPlaster); - b.drawRect({-8, -8, 656, 42}, kBeam); - b.drawRect({-8, 34, 656, 3}, kBeamLight); - b.drawRect({-8, 37, 656, 4}, kPlasterShade); - for (float x = 0; x < 640; x += 160) { - b.drawRect({x, 37, 12, 200}, kBeam); // 柱 / pillars - b.drawRect({x + 9, 37, 3, 200}, kBeamLight); - } - // 障子:格子の窓 / shoji: lattice windows - for (float x : {28.0f, 188.0f, 348.0f, 508.0f}) { - if (x == 188.0f) continue; // 真ん中は掛け軸 / scroll in the middle instead - Rect w = {x, 62, 104, 120}; - b.drawRect(w, kLattice); - b.drawRect({w.x + 3, w.y + 3, w.w - 6, w.h - 6}, kShoji); - for (float lx = w.x + 3 + 24; lx < w.right() - 4; lx += 25) b.drawRect({lx, w.y + 3, 2, w.h - 6}, kLattice); - for (float ly = w.y + 3 + 28; ly < w.bottom() - 4; ly += 29) b.drawRect({w.x + 3, ly, w.w - 6, 2}, kLattice); +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]); +} + +// ラウンドの流れ(ステップごと)。ヒットストップ中は進まない / 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; } - // 掛け軸「練習」 / a hanging scroll: "practice" - b.drawRect({212, 52, 64, 6}, kBeam); - b.drawRect({218, 58, 52, 132}, hexColor(0xf6f0e0ff)); - b.drawRect({218, 58, 52, 4}, hexColor(0x9a4a3aff)); - b.drawRect({218, 186, 52, 4}, hexColor(0x9a4a3aff)); - b.drawRect({212, 190, 64, 6}, kBeam); - g.pixel.draw(b, "練", {244, 82}, {.color = kOutline, .scale = 2.0f, .align = TextAlign::Centre}); - g.pixel.draw(b, "習", {244, 122}, {.color = kOutline, .scale = 2.0f, .align = TextAlign::Centre}); - b.drawRect({236, 166, 16, 8}, hexColor(0xc83c3cff)); // 落款 / the seal - // 腰板 / wainscot - b.drawRect({-8, 222, 656, 38}, kWainscot); - b.drawRect({-8, 222, 656, 3}, kWainscotDark); - for (float x = 0; x < 640; x += 40) b.drawRect({x, 225, 2, 35}, kWainscotDark); - // 床板:奥ほど細い(ゆるい遠近) / floor planks: thinner further back (a gentle perspective) - float y = 260.0f; - int row = 0; - // 最後の段は画面の下より先まで / the last row reaches past the bottom - for (float h : {6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 12.0f, 13.0f, 15.0f, 28.0f}) { - b.drawRect({-8, y, 656, h}, row % 2 ? kPlankA : kPlankB); - b.drawRect({-8, y, 656, 1}, kPlankLine); - float offset = static_cast((row * 97) % 120); - for (float x = offset; x < 640; x += 120) b.drawRect({x, y, 1, h}, kPlankLine); - y += h; - ++row; + 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(g, settings, winner, wins), {.duration = 0.6f}); + leaving = true; + } else { + ++round; + startRound(); + } + } + break; } } void FightScene::draw(float alpha) { SpriteBatch &b = g.batch; - Camera2D view = camera; - // 画面の揺れ:重い一撃のヒットストップ中、カメラを2ピクセルずつ揺らす / screen shake: during a heavy hit's - // hit stop the camera jumps by 2 pixels - if (shake > 0) view.centre += Vec2{shake % 2 ? 2.0f : -2.0f, shake % 4 < 2 ? 1.0f : -1.0f}; + Camera2D view = worldCamera(alpha); + // 揺れは横だけ、舞台の中で(端で舞台の外が見えないように) / 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); b.begin(view.matrix(), SpriteSort::Layer); - drawBackground(); + g.stage->drawBack(b, view); for (int i = 0; i < 2; ++i) fighters[i].draw(b, alpha, i == top ? 3.0f : 2.0f, victim == i && hitstop > 0 ? hitstop : 0); effects.draw(b); - if (g.showBoxes) drawDebug(alpha); + g.stage->drawFront(b, view); b.end(); - // HUDは揺らさない / the HUD does not shake - b.begin(camera.matrix(), SpriteSort::Layer); + if (g.showBoxes) { + b.begin(view.matrix(), SpriteSort::Layer); + drawDebug(); + b.end(); + } + b.begin(Camera2D::screen(kViewSize).matrix(), SpriteSort::Layer); drawHud(); b.end(); } void FightScene::drawHud() { SpriteBatch &b = g.batch; - drawHealthBar(b, {16, 10, 272, 10}, static_cast(fighters[0].health), trail[0], false); - drawHealthBar(b, {352, 10, 272, 10}, static_cast(fighters[1].health), trail[1], true); + drawHealthBar(b, {16, 10, 260, 10}, static_cast(fighters[0].health), trail[0], false); + drawHealthBar(b, {364, 10, 260, 10}, static_cast(fighters[1].health), trail[1], true); TextStyle name = {.color = kText, .layer = 11.0f, .shadow = kOutline}; - g.pixel.draw(b, "1P " + fighters[0].name, {16, 24}, name); + bool cpu[2] = {ai[0].has_value(), ai[1].has_value()}; + g.pixel.draw(b, "1P " + fighters[0].name + (cpu[0] ? " (CPU)" : ""), {16, 24}, name); TextStyle right = name; right.align = TextAlign::Right; - g.pixel.draw(b, fighters[1].name + " 2P", {624, 24}, right); - TextStyle centre = name; - centre.align = TextAlign::Centre; - centre.color = kGold; - g.pixel.draw(b, "練習", {320, 8}, centre); - // コンボ数(攻撃した側に) / the combo count (on the attacker's side) + g.pixel.draw(b, (cpu[1] ? "(CPU) " : "") + fighters[1].name + " 2P", {624, 24}, right); + // 取ったラウンド:名前の横の印 / rounds won: marks next to the names + for (int i = 0; i < 2; ++i) + for (int k = 0; k < kWinsNeeded; ++k) { + float x = i == 0 ? 266.0f - 12.0f * static_cast(k) : 366.0f + 12.0f * static_cast(k); + b.drawRect({x - 1, 25, 10, 10}, kOutline, 10.0f); + b.drawRect({x, 26, 8, 8}, wins[i] > k ? kGold : hexColor(0x4a2434ff), 10.1f); + } + // 時間(真ん中)。練習は「練習」 / 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); + } for (int i = 0; i < 2; ++i) { if (comboTime[i] <= 0) continue; - std::string text = std::to_string(comboHits[i]) + " HITS"; TextStyle s = {.color = hexColor(0xff9a3cff), .scale = 2.0f, .align = i == 0 ? TextAlign::Left : TextAlign::Right, .layer = 11.0f, .shadow = kOutline}; - g.pixel.draw(b, text, {i == 0 ? 16.0f : 624.0f, 44.0f}, s); + g.pixel.draw(b, std::to_string(comboHits[i]) + " HITS", {i == 0 ? 16.0f : 624.0f, 44.0f}, s); + } + + // ラウンドの表示 / the round banners + TextStyle sub = {.color = kText, .scale = 2.0f, .align = TextAlign::Centre, .layer = 11.5f, .shadow = kOutline, + .shadowOffset = {1.0f, 1.0f}}; + 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); + } + } else if (phase == RoundPhase::Finish) { + if (phaseTime < kWinPoseAt) { + bool doubleKo = roundWinner < 0 && !timeOver; + drawBigText(b, g.pixel, timeOver ? "TIME UP" : doubleKo ? "DOUBLE K.O." : "K.O.", {320, 130}, kRed, + timeOver || doubleKo ? 4.0f : 5.0f); + if (timeOver) g.pixel.draw(b, "タイムアップ", {320, 162}, sub); + } else if (roundWinner >= 0) { + drawBigText(b, g.pixel, fighters[roundWinner].name + " WINS", {320, 130}, kGold, 4.0f); + g.pixel.draw(b, std::string(kJapaneseNames[roundWinner]) + "の勝ち", {320, 162}, sub); + } else { + drawBigText(b, g.pixel, "DRAW", {320, 130}, kText, 4.0f); + g.pixel.draw(b, "引き分け", {320, 162}, sub); + } + } else if (koTime > 0) { + drawBigText(b, g.pixel, "K.O.", {320, 130}, kRed, 5.0f); } - if (koTime > 0) drawBigText(b, g.pixel, "K.O.", {320, 130}, hexColor(0xe8483cff), 5.0f); } -// F1:食らい判定(青)、攻撃判定(赤)、押し合い(緑)、ソケット(黄)、状態と技の段階 -// F1: hurt boxes (blue), hit boxes (red), push boxes (green), sockets (yellow), the state and the move's phase -void FightScene::drawDebug(float /*alpha*/) { - // 判定は今のステップの位置で描く(補間しない:当たりを決めたのはこの位置) / boxes at this step's positions (not - // interpolated: these are the positions the hits were decided at) +void FightScene::drawDebug() { SpriteBatch &b = g.batch; static const char *const kPhase[] = {"", "STARTUP", "ACTIVE", "RECOVERY"}; - for (const Fighter &f : fighters) { - for (const Rect &r : f.hurtboxes()) b.drawRectOutline(r, hexColor(0x5aaaffe0), 1.0f, 8.0f); + for (int i = 0; i < 2; ++i) { + const Fighter &f = fighters[i]; + for (const Rect &r : f.hurtboxes()) b.drawRectOutline(r, hexColor(0x5aaaffe0), 1.0f, 20.0f); Rect push = f.pushbox(); - b.drawRectOutline(push, hexColor(0x50e070c0), 1.0f, 8.1f); + b.drawRectOutline(push, hexColor(0x50e070c0), 1.0f, 20.1f); const FrameBoxes &fb = (*g.frameData)[f.frame]; - // 攻撃判定:持続フレームの間ずっと。当たった後(もう当たらない)は薄く / the attack box for the whole active - // window; fainter once it has hit (it cannot hit again) if (f.phase() == MovePhase::Active && fb.hit) - b.drawRect(toWorld(*fb.hit, f.position, f.facing), f.moveHit ? hexColor(0xff464650) : hexColor(0xff4646a0), 8.2f); + b.drawRect(toWorld(*fb.hit, f.position, f.facing), f.moveHit ? hexColor(0xff464650) : hexColor(0xff4646a0), 20.2f); for (Vec2 s : {fb.head, fb.knot, fb.fist, fb.foot}) { Rect r = toWorld({s.x, s.y, 0.0f, 0.0f}, f.position, f.facing); - b.drawRect({std::round(r.x) - 1, std::round(r.y) - 1, 2, 2}, hexColor(0xffdc3cff), 8.3f); + b.drawRect({std::round(r.x) - 1, std::round(r.y) - 1, 2, 2}, hexColor(0xffdc3cff), 20.3f); } - char label[96]; - if (f.state == FighterState::Attack) - std::snprintf(label, sizeof label, "%s %s %d/%d\n%s", stateName(f.state), f.move->name, f.stateTime, - f.move->total(), kPhase[static_cast(f.phase())]); - else std::snprintf(label, sizeof label, "%s %d\nHP %d", stateName(f.state), f.stateTime, f.health); - // 左の人の札は左へ、右の人の札は右へずらす(近づいても重ならない) / the left fighter's label goes left, the - // right one's right (no overlap at close range) - const Fighter &other = &f == &fighters[0] ? fighters[1] : fighters[0]; - bool leftOne = f.position.x < other.position.x || (f.position.x == other.position.x && &f == &fighters[0]); + char label[128]; + int n = f.state == FighterState::Attack + ? std::snprintf(label, sizeof label, "%s %s %d/%d\n%s", stateName(f.state), f.move->name, f.stateTime, + f.move->total(), kPhase[static_cast(f.phase())]) + : std::snprintf(label, sizeof label, "%s %d\nHP %d", stateName(f.state), f.stateTime, f.health); + // CPUなら今の意図も / for the CPU also its current intent + if (ai[i] && n > 0 && static_cast(n) < sizeof label) + std::snprintf(label + n, sizeof label - static_cast(n), "\nAI %s", ai[i]->intentName()); + const Fighter &other = fighters[1 - i]; + bool leftOne = f.position.x < other.position.x || (f.position.x == other.position.x && i == 0); Vec2 size = g.tiny.measure(label); float x0 = std::round(leftOne ? f.position.x + 8.0f - size.x : f.position.x - 8.0f); - Vec2 at = {x0, std::round(push.y) - 16.0f}; - 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); - g.tiny.draw(b, label, at, {.color = kText, .layer = 9.0f}); + Vec2 at = {x0, std::round(push.y) - 22.0f}; + 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); + g.tiny.draw(b, label, at, {.color = kText, .layer = 21.0f}); } } 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(phaseTime - (kFinishFrames - 30)) / 30.0f; + if (phase == RoundPhase::Intro && phaseTime < 20) fade = 1.0f - static_cast(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)}); b.drawRect({0, 688, 1280, 32}, {0.11f, 0.09f, 0.15f, 0.75f}); - g.ui.draw(b, - "1P: A D W S + F パンチ・G キック 2P: カーソルキー + K・L 後ろでガード / back = guard " - "F1 当たり箱 Esc 終了", - {640, 694}, {.color = hexColor(0xe8e0d0ff), .align = TextAlign::Centre}); + 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"; + g.ui.draw(b, help, {640, 694}, {.color = hexColor(0xe8e0d0ff), .align = TextAlign::Centre}); b.end(); } diff --git a/games/fighter/src/fight_scene.hh b/games/fighter/src/fight_scene.hh index f80f7fc..6f397fd 100644 --- a/games/fighter/src/fight_scene.hh +++ b/games/fighter/src/fight_scene.hh @@ -1,40 +1,60 @@ -// 対戦の場面:二人のファイター、押し合い、技の当たり、ヒットストップ、体力ゲージ、エフェクト -// The fight scene: two fighters, pushing, hits, hit stop, health bars, effects +// 対戦の場面:二人のファイター(人かCPU)、押し合い、技の当たり、ヒットストップ、体力ゲージ、エフェクト、 +// スクロールする舞台とカメラ、ラウンド(3本勝負、時間、KO・タイムアップ) +// The fight scene: two fighters (human or CPU), pushing, hits, hit stop, health bars, effects, the scrolling stage +// and camera, rounds (best of three, a timer, KO / time over) #pragma once +#include "ai.hh" #include "effects.hh" #include "fighter.hh" #include "game.hh" +#include "match.hh" #include "engine/scene.hh" +#include + class FightScene : public Scene { public: - explicit FightScene(Game &game); + FightScene(Game &game, MatchSettings settings); + void pause() override; void update(float dt) override; void draw(float alpha) override; void drawUi(float alpha) override; private: + // ラウンドの流れ:始まりの表示 → 戦い → 決着の表示 / the round flow: the intro banner → the fight → the result + enum class RoundPhase { Intro, Fight, Finish }; + + void startRound(); void separate(); + void keepInView(); void resolveHits(); - void resetRound(); - void drawBackground(); + void finishRound(int winner, bool timeOver); + void updateRound(); + Camera2D worldCamera(float alpha) const; void drawHud(); - void drawDebug(float alpha); + void drawDebug(); Game &g; - Camera2D camera; + MatchSettings settings; Fighter fighters[2]; + std::optional ai[2]; // ある方はCPUが操作する / where set, the computer plays that side Effects effects; GamepadEdges pads[2]; int steps = 0; - int hitstop = 0; // 残りのヒットストップ(二人とも止まる) / hit stop left (both fighters frozen) - int victim = -1; // ヒットストップ中に震える方 / who shakes during the hit stop - int shake = 0; // 画面の揺れ / screen shake - int top = 0; // 手前に描くファイター(最後に攻撃した方) / the fighter drawn in front (the last attacker) - float trail[2] = {kMaxHealth, kMaxHealth}; // 体力ゲージの減っていく白い部分 / the health bar's draining trail + int hitstop = 0, victim = -1, shake = 0, top = 0; + float trail[2] = {kMaxHealth, kMaxHealth}; int trailDelay[2] = {0, 0}; - int comboTime[2] = {0, 0}, comboHits[2] = {0, 0}; // 「2 HITS」の表示 / the "2 HITS" display - int koTime = 0; // KOからの時間(練習では仕切り直す) / time since a KO (training resets) + int comboTime[2] = {0, 0}, comboHits[2] = {0, 0}; + + 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 }; diff --git a/games/fighter/src/fighter.cc b/games/fighter/src/fighter.cc index cf0a5c3..7447d01 100644 --- a/games/fighter/src/fighter.cc +++ b/games/fighter/src/fighter.cc @@ -49,6 +49,7 @@ const char *stateName(FighterState state) { case FighterState::Knockdown: return "KNOCKDOWN"; case FighterState::GetUp: return "GETUP"; case FighterState::KO: return "KO"; + case FighterState::Win: return "WIN"; } return "?"; } @@ -57,7 +58,7 @@ Fighter::Fighter(const SpriteSheet &s, const SpriteSheet &effects, const FrameDa const char *tail, Vec2 start, float startFacing) : name(std::move(fighterName)), position(start), previous(start), facing(startFacing), sheet(s), data(frameData), idleClip(s.clip("idle")), walkClip(s.clip("walk")), walkBackClip(s.clip("walk_back")), - fCrouchIn(findFrame(s, "crouch_in")), fCrouch(findFrame(s, "crouch")), fJumpUp(findFrame(s, "jump_up")), + winClip(s.clip("win")), fCrouchIn(findFrame(s, "crouch_in")), fCrouch(findFrame(s, "crouch")), fJumpUp(findFrame(s, "jump_up")), fJumpTuck(findFrame(s, "jump_tuck")), fJumpDown(findFrame(s, "jump_down")), fBlock(findFrame(s, "block")), fCBlock(findFrame(s, "cblock")), fHit0(findFrame(s, "hit0")), fHit1(findFrame(s, "hit1")), fCHit(findFrame(s, "chit")), fKo0(findFrame(s, "ko0")), fKo1(findFrame(s, "ko1")) { @@ -75,6 +76,7 @@ void Fighter::reset(Vec2 start, float startFacing) { health = kMaxHealth; move = nullptr; onGround = true; + wantsWin = false; buffer.clear(); animator.play(idleClip, true); frame = animator.frame(); @@ -124,6 +126,8 @@ void Fighter::setState(FighterState next) { stateTime = 0; } +void Fighter::win() { wantsWin = true; } + bool Fighter::actionable() const { return state == FighterState::Idle || state == FighterState::Walk || state == FighterState::Crouch; } @@ -233,8 +237,15 @@ void Fighter::update(float dt, const Controls &c, float opponentX, bool threat) if (stateTime >= kGetUpFrames) setState(FighterState::Idle); break; case FighterState::KO: + case FighterState::Win: break; } + // 勝ちポーズは、自由に動ける状態で地上にいるときに / 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); + } // 物理:空中は重力、地上は(歩き以外)摩擦で止まる / physics: gravity in the air; on the ground friction stops // everything except walking @@ -386,6 +397,8 @@ void Fighter::chooseFrame(float dt) { case FighterState::KO: frame = onGround ? fKo1 : fKo0; return; + case FighterState::Win: + break; // animatorの勝ちクリップ / the animator's win clip } animator.update(dt); frame = animator.frame(); diff --git a/games/fighter/src/fighter.hh b/games/fighter/src/fighter.hh index 7d81a6c..f7a691b 100644 --- a/games/fighter/src/fighter.hh +++ b/games/fighter/src/fighter.hh @@ -38,6 +38,7 @@ enum class FighterState { Knockdown, // ダウン:飛ばされて倒れ、起き上がる / knocked down: thrown back, lying, then getting up GetUp, // 起き上がり(無敵) / getting up (invincible) KO, // 体力0:倒れたまま / health 0: stays down + Win, // 勝ちポーズ(ラウンドの勝者) / the victory pose (the round's winner) }; const char *stateName(FighterState state); @@ -79,6 +80,10 @@ public: // the wall; a faster motion the same way (the knockback just taken in a trade) is kept void pushBack(float speed) { velocity.x = -facing * std::max(speed, -facing * velocity.x); } bool actionable() const; + bool grounded() const { return onGround; } + // ラウンドに勝った:地上にいれば勝ちポーズ(空中なら着地してから) / won the round: the victory pose once on the + // ground + void win(); // 体の部品(ノード)をこのステップの値に合わせてから描く / updates the part nodes for this frame, then draws them void draw(SpriteBatch &batch, float alpha, float layer, int shake); @@ -114,11 +119,12 @@ private: const SpriteSheet &sheet; const FrameData &data; - const AnimationClip *idleClip, *walkClip, *walkBackClip; + const AnimationClip *idleClip, *walkClip, *walkBackClip, *winClip; Animator animator; float jumpDirection = 0.0f; bool onGround = true; bool airMoveUsed = false; + bool wantsWin = false; float time = 0.0f; int fCrouchIn, fCrouch, fJumpUp, fJumpTuck, fJumpDown, fBlock, fCBlock, fHit0, fHit1, fCHit, fKo0, fKo1; diff --git a/games/fighter/src/game.hh b/games/fighter/src/game.hh index 5750a3e..d042a87 100644 --- a/games/fighter/src/game.hh +++ b/games/fighter/src/game.hh @@ -2,7 +2,9 @@ // The fighting game's shared data, one per game (main creates it, the scenes keep a reference) #pragma once +#include "ai.hh" #include "frame_data.hh" +#include "stage.hh" #include "engine/camera2d.hh" #include "engine/font.hh" @@ -26,6 +28,9 @@ struct Game { const SpriteSheet *fighters[2]; // ハヤテ(1P)とジン(2P) / Hayate (1P) and Jin (2P) const SpriteSheet *effects; // 火花・砂ぼこり・鉢巻の尾・星・影 / sparks, dust, headband tails, stars, shadow const FrameData *frameData; // コマごとの判定(二人共通:同じ骨格) / per-frame boxes (shared: same skeleton) + Stage *stage; // 視差の舞台(タイトルと勝利画面でも使う) / the parallax stage (also behind the + // title and the win screen) Camera2D screen; // 1280×720のUI / the 1280 × 720 UI bool showBoxes = false; // F1:判定の箱とデバッグ表示 / F1: boxes and debug labels + Difficulty difficulty = Difficulty::Normal; // タイトルで選んだ強さ(戻っても覚えている) / chosen on the title (kept) }; diff --git a/games/fighter/src/hud.cc b/games/fighter/src/hud.cc new file mode 100644 index 0000000..3c3ead4 --- /dev/null +++ b/games/fighter/src/hud.cc @@ -0,0 +1,17 @@ +// 画面の文字 / on-screen text +#include "hud.hh" + +#include + +void drawBigText(SpriteBatch &b, const Font &font, std::string_view text, Vec2 centre, Vec4 color, float scale, + float layer) { + Vec2 size = font.measure(text, scale); + Vec2 at = {centre.x, std::round(centre.y - size.y * 0.5f)}; + TextStyle s = {.color = kOutline, .scale = scale, .align = TextAlign::Centre, .layer = layer}; + 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}, + Vec2{3, 4}, Vec2{0, 4}}) + font.draw(b, text, at + d, s); + s.color = color; + s.layer = layer + 0.5f; + font.draw(b, text, at, s); +} diff --git a/games/fighter/src/hud.hh b/games/fighter/src/hud.hh new file mode 100644 index 0000000..256e737 --- /dev/null +++ b/games/fighter/src/hud.hh @@ -0,0 +1,17 @@ +// 画面の文字と色(どのシーンでも使う) / on-screen text and colors (used by every scene) +#pragma once + +#include "engine/font.hh" +#include "engine/sprite_batch.hh" + +#include + +constexpr Vec4 kOutline = hexColor(0x1b1726ff); +constexpr Vec4 kText = hexColor(0xfff4d8ff); +constexpr Vec4 kGold = hexColor(0xf2c14eff); +constexpr Vec4 kRed = hexColor(0xe8483cff); + +// 大きな文字(K.O.、ROUND 1…):8方向の輪郭と影、それから本体。centreは文字の真ん中 +// Big text (K.O., ROUND 1...): an outline in 8 directions plus a drop shadow, then the text. centre is its middle +void drawBigText(SpriteBatch &batch, const Font &font, std::string_view text, Vec2 centre, Vec4 color, float scale, + float layer = 11.0f); diff --git a/games/fighter/src/main.cc b/games/fighter/src/main.cc index 8e3e945..a480090 100644 --- a/games/fighter/src/main.cc +++ b/games/fighter/src/main.cc @@ -6,6 +6,9 @@ // 入力バッファ、体の部品とエフェクトのシーングラフ // Chapter 31: moves (frame data), hit / hurt boxes, damage, hit stun, knockback, hit stop, health bars, input // buffering, a scene graph for body parts and effects +// 第32章:視差のある舞台とカメラ、CPUの相手(状態と決める間隔、難易度)、ラウンド(3本勝負・時間)、勝利画面 +// Chapter 32: a parallax stage and camera, the CPU opponent (states, a decision timer, difficulty), rounds (best of +// three, a timer), the win screen // // 操作(一台のキーボードを二人で) / Controls (two players on one keyboard): // 1P A D 前後・W ジャンプ・S しゃがみ・F 突き・G 蹴り / A D walk, W jump, S crouch, F punch, G kick @@ -13,9 +16,11 @@ // 相手と反対に入れてガード(しゃがみガードは後ろ下) / hold away from the opponent to guard (down-back crouching) // ゲームパッド:1台目 = 1P、2台目 = 2P(十字キーか左スティック、A/X 突き、B/Y 蹴り) / gamepads: 1st = 1P, // 2nd = 2P (d-pad or left stick, A/X punch, B/Y kick) -// F1 判定の箱と状態 / boxes and states Esc 終了 / quit -#include "fight_scene.hh" +// F1 判定の箱と状態 / boxes and states Esc / P 一時停止 / pause +// タイトル:W S 選ぶ、A D 難易度、Space・Enter・F 決定、Esc 終了 / title: W S select, A D difficulty, +// Space / Enter / F start, Esc quit #include "game.hh" +#include "scenes.hh" #include "engine/pixel_canvas.hh" #include "engine/window.hh" @@ -40,7 +45,8 @@ int main() { // 判定のデータは骨格から作ったもの:二人とも同じ(コマの名前と番号も同じ) / the box data comes from the skeleton: // the same for both (same frame names and indices) std::optional frameData = FrameData::load("games/fighter/assets/fighter.boxes", *hayate); - if (!frameData) return 1; + std::optional stage = Stage::load(); + if (!frameData || !stage) return 1; Input input; input.attach(window); @@ -49,10 +55,10 @@ int main() { GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); PixelCanvas canvas(static_cast(kViewSize.x), static_cast(kViewSize.y)); Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .ui = *ui, .pixel = *pixel, - .tiny = *tiny, .fighters = {&*hayate, &*jin}, .effects = &*effects, .frameData = &*frameData, .screen = Camera2D::screen({1280.0f, 720.0f})}; + .tiny = *tiny, .fighters = {&*hayate, &*jin}, .effects = &*effects, .frameData = &*frameData, .stage = &*stage, .screen = Camera2D::screen({1280.0f, 720.0f})}; SceneManager scenes; - scenes.push(std::make_unique(game)); + scenes.push(std::make_unique(game)); loop.run( window, input, diff --git a/games/fighter/src/match.hh b/games/fighter/src/match.hh new file mode 100644 index 0000000..1455b09 --- /dev/null +++ b/games/fighter/src/match.hh @@ -0,0 +1,20 @@ +// 試合の設定(タイトルで選ぶ) / 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; diff --git a/games/fighter/src/menu_keys.hh b/games/fighter/src/menu_keys.hh new file mode 100644 index 0000000..f1e2631 --- /dev/null +++ b/games/fighter/src/menu_keys.hh @@ -0,0 +1,13 @@ +// メニューのキー(タイトル・一時停止・勝利画面で共通。1Pと2Pのどちらのキーでも) / menu keys (shared by the title, +// pause and win screens; either player's keys work) +#pragma once + +#include "engine/input.hh" + +inline bool menuUp(const Input &in) { return in.pressed(GLFW_KEY_W) || in.pressed(GLFW_KEY_UP); } +inline bool menuDown(const Input &in) { return in.pressed(GLFW_KEY_S) || in.pressed(GLFW_KEY_DOWN); } +inline bool menuLeft(const Input &in) { return in.pressed(GLFW_KEY_A) || in.pressed(GLFW_KEY_LEFT); } +inline bool menuRight(const Input &in) { return in.pressed(GLFW_KEY_D) || in.pressed(GLFW_KEY_RIGHT); } +inline bool menuConfirm(const Input &in) { + return in.pressed(GLFW_KEY_SPACE) || in.pressed(GLFW_KEY_ENTER) || in.pressed(GLFW_KEY_F) || in.pressed(GLFW_KEY_K); +} diff --git a/games/fighter/src/pause_scene.cc b/games/fighter/src/pause_scene.cc new file mode 100644 index 0000000..9b87ba9 --- /dev/null +++ b/games/fighter/src/pause_scene.cc @@ -0,0 +1,37 @@ +// 一時停止:対戦の上に重ねる / pause: an overlay on top of the fight +#include "hud.hh" +#include "menu_keys.hh" +#include "scenes.hh" + +#include +#include + +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(g), {.duration = 0.8f}); + } +} + +void PauseScene::drawUi(float /*alpha*/) { + SpriteBatch &b = g.batch; + b.begin(g.screen.matrix()); + float dim = std::min(1.0f, time / 0.2f) * 0.55f; // 0.2秒で暗くなる / darkens over 0.2 s + b.drawRect({0, 0, 1280, 720}, {0.05f, 0.04f, 0.08f, dim}); + Rect panel = {440, 230, 400, 230}; + b.drawRect(panel, {0.11f, 0.09f, 0.15f, 0.92f}); + b.drawRectOutline(panel, kGold, 2.0f); + g.ui.draw(b, "一時停止 / PAUSED", {640, 256}, {.color = kText, .scale = 2.0f, .align = TextAlign::Centre}); + const char *items[2] = {"再開 / Resume", "タイトルへ / Back to title"}; + for (int i = 0; i < 2; ++i) + g.ui.draw(b, items[i], {640, 330.0f + 50.0f * static_cast(i)}, + {.color = i == selected ? kGold : kText, .scale = 1.5f, .align = TextAlign::Centre}); + b.end(); +} diff --git a/games/fighter/src/result_scene.cc b/games/fighter/src/result_scene.cc new file mode 100644 index 0000000..1ad14ef --- /dev/null +++ b/games/fighter/src/result_scene.cc @@ -0,0 +1,92 @@ +// 勝利画面:勝った方を大きく、取ったラウンドの数、もう一度かタイトルへ / the win screen: the winner large, the rounds +// won, rematch or back to the title +#include "fight_scene.hh" +#include "hud.hh" +#include "menu_keys.hh" +#include "scenes.hh" + +#include +#include +#include + +namespace { + +const char *const kNames[2] = {"HAYATE", "JIN"}; +const char *const kJapaneseNames[2] = {"ハヤテ", "ジン"}; +constexpr Vec2 kPivot = {0.5f, 116.0f / 120.0f}; + +} // namespace + +ResultScene::ResultScene(Game &game, MatchSettings matchSettings, int matchWinner, const int roundWins[2]) + : g(game), settings(matchSettings), winner(matchWinner), wins{roundWins[0], roundWins[1]} { + if (winner >= 0) pose.play(g.fighters[winner]->clip("win")); +} + +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(g), {.duration = 0.8f}); + else if (menuConfirm(in) && time > 0.5f) + scenes().replace(std::make_unique(g, settings), {.duration = 0.8f}); // もう一度 / rematch +} + +void ResultScene::draw(float /*alpha*/) { + SpriteBatch &b = g.batch; + Camera2D view = Camera2D::screen(kViewSize); + view.centre.x = kStageWidth * 0.5f; + b.begin(view.matrix(), SpriteSort::Layer); + g.stage->drawBack(b, view); + float left = view.centre.x - kViewSize.x * 0.5f; + if (winner >= 0) { + // 勝者は2倍の大きさで勝ちポーズ、負けた方は奥で倒れている / the winner at twice the size in the victory pose, the + // loser lying further back + const SpriteSheet &ls = *g.fighters[1 - winner]; + Sprite lying = ls.sprite(ls.find("ko1"), {left + 470.0f, kGroundY - 26.0f}, kPivot); + lying.flipX = true; + lying.color = {0.75f, 0.7f, 0.8f, 1.0f}; + lying.layer = 1.0f; + b.draw(lying); + const SpriteSheet &ws = *g.fighters[winner]; + Sprite s = ws.sprite(pose.frame(), {left + 230.0f, kGroundY + 22.0f}, kPivot, 2.0f); + s.layer = 2.0f; + b.draw(s); + } else { + for (int i = 0; i < 2; ++i) { + const SpriteSheet &sh = *g.fighters[i]; + Sprite s = sh.sprite(sh.find("idle0"), {left + (i == 0 ? 220.0f : 420.0f), kGroundY}, kPivot); + s.flipX = i == 1; + s.layer = 2.0f; + b.draw(s); + } + } + g.stage->drawFront(b, view); + b.end(); + + b.begin(Camera2D::screen(kViewSize).matrix(), SpriteSort::Layer); + TextStyle sub = {.color = kText, .scale = 2.0f, .align = TextAlign::Centre, .layer = 11.5f, .shadow = kOutline}; + if (winner >= 0) { + drawBigText(b, g.pixel, std::string(kNames[winner]) + " WINS!", {430, 70}, kGold, 4.0f); + g.pixel.draw(b, std::string(kJapaneseNames[winner]) + "の勝利", {430, 102}, sub); + } else { + drawBigText(b, g.pixel, "DRAW GAME", {320, 70}, kText, 4.0f); + g.pixel.draw(b, "引き分け", {320, 102}, sub); + } + // 取ったラウンド / the rounds won + std::string score = std::to_string(wins[0]) + " - " + std::to_string(wins[1]); + drawBigText(b, g.pixel, score, {winner >= 0 ? 430.0f : 320.0f, 150}, kText, 3.0f); + g.pixel.draw(b, "HAYATE JIN", {winner >= 0 ? 430.0f : 320.0f, 172}, + {.color = kText, .align = TextAlign::Centre, .layer = 11.5f, .shadow = kOutline}); + b.end(); +} + +void ResultScene::drawUi(float /*alpha*/) { + SpriteBatch &b = g.batch; + b.begin(g.screen.matrix()); + b.drawRect({0, 688, 1280, 32}, {0.11f, 0.09f, 0.15f, 0.75f}); + float a = 0.55f + 0.45f * std::cos(time * 4.0f); + g.ui.draw(b, "Space / F もう一度 / rematch Esc タイトルへ / title", {640, 694}, + {.color = {0.91f, 0.88f, 0.82f, a}, .align = TextAlign::Centre}); + b.end(); +} diff --git a/games/fighter/src/scenes.hh b/games/fighter/src/scenes.hh new file mode 100644 index 0000000..d57da61 --- /dev/null +++ b/games/fighter/src/scenes.hh @@ -0,0 +1,59 @@ +// 対戦以外のシーン:タイトル、一時停止、勝利画面 / the scenes besides the fight: title, pause, win screen +#pragma once + +#include "game.hh" +#include "match.hh" + +#include "engine/animation.hh" +#include "engine/scene.hh" + +#include + +// タイトル:遊び方と難易度を選ぶ。後ろで舞台がゆっくり流れる / the title: pick the mode and difficulty; the stage pans +// slowly behind +class TitleScene : public Scene { +public: + explicit TitleScene(Game &game) : g(game) {} + void update(float dt) override; + void draw(float alpha) override; + void drawUi(float alpha) override; + +private: + Game &g; + float time = 0.0f; + int selected = 0; +}; + +// 一時停止(上に重ねる) / pause (an overlay) +class PauseScene : public Scene { +public: + explicit PauseScene(Game &game) : g(game) {} + bool isOverlay() const override { return true; } + void update(float dt) override; + void draw(float /*alpha*/) override {} + void drawUi(float alpha) override; + +private: + Game &g; + float time = 0.0f; + int selected = 0; +}; + +// 勝利画面:勝った方の勝ちポーズ、取った本数。もう一度・タイトルへ / the win screen: the winner's victory pose and the +// rounds won; rematch or back to the title +class ResultScene : public Scene { +public: + // winner = 0 / 1、-1 = 引き分け / winner = 0 / 1, -1 = a draw game + ResultScene(Game &game, MatchSettings settings, int winner, const int wins[2]); + void update(float dt) override; + void draw(float alpha) override; + void drawUi(float alpha) override; + +private: + Game &g; + MatchSettings settings; + int winner; + int wins[2]; + float time = 0.0f; + Animator pose; +}; diff --git a/games/fighter/src/stage.cc b/games/fighter/src/stage.cc new file mode 100644 index 0000000..5be3744 --- /dev/null +++ b/games/fighter/src/stage.cc @@ -0,0 +1,90 @@ +// スクロールする舞台 / the scrolling stage +#include "stage.hh" + +#include "engine/sprite_sheet.hh" + +#include +#include +#include + +namespace { + +constexpr float kPetalFactor = 1.15f; // 花びらは地面より少し手前 / petals are a little in front of the ground +constexpr int kPetals = 28; + +} // namespace + +std::optional 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 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; +} + +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(l.texture.width()), static_cast(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}); +} + +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); + } + } +} diff --git a/games/fighter/src/stage.hh b/games/fighter/src/stage.hh new file mode 100644 index 0000000..5d9facc --- /dev/null +++ b/games/fighter/src/stage.hh @@ -0,0 +1,52 @@ +// スクロールする舞台:視差の層(遠いほどゆっくり動く)、カメラの範囲、舞い散る花びら +// 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 +#include + +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 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 back, front; + std::vector petals; + Rng rng{32}; + float time = 0.0f; +}; diff --git a/games/fighter/src/title_scene.cc b/games/fighter/src/title_scene.cc new file mode 100644 index 0000000..d0f2819 --- /dev/null +++ b/games/fighter/src/title_scene.cc @@ -0,0 +1,105 @@ +// タイトル:遊び方と難易度を選ぶ / the title: pick a mode and the difficulty +#include "fight_scene.hh" +#include "hud.hh" +#include "menu_keys.hh" +#include "scenes.hh" + +#include +#include +#include + +namespace { + +struct Item { + const char *english, *japanese; + Mode mode; +}; +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[] = {"易しい", "普通", "難しい"}; + +// タイトルの後ろの二人(舞台のワールド座標、足元) / the two fighters behind the title (stage world coordinates, feet) +constexpr float kTitleX[2] = {kStageWidth * 0.5f - 210.0f, kStageWidth * 0.5f + 210.0f}; + +} // namespace + +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(g.difficulty); + if (menuLeft(in)) g.difficulty = static_cast((d + 2) % 3); + if (menuRight(in)) g.difficulty = static_cast((d + 1) % 3); + if (menuConfirm(in) && selected < 4) + scenes().replace(std::make_unique(g, MatchSettings{kItems[selected].mode, g.difficulty}), + {.duration = 0.8f}); +} + +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); + for (int i = 0; i < 2; ++i) { + const SpriteSheet &sheet = *g.fighters[i]; + const AnimationClip *idle = sheet.clip("idle"); + int frame = idle->frames[static_cast(time * idle->fps + static_cast(i) * 2.0f) % idle->frames.size()]; + Sprite s = sheet.sprite(frame, {kTitleX[i], kGroundY}, {0.5f, 116.0f / 120.0f}); + s.flipX = i == 1; + s.layer = 2.0f; + b.draw(s); + } + g.stage->drawFront(b, view); + b.end(); + + b.begin(Camera2D::screen(kViewSize).matrix(), SpriteSort::Layer); + drawBigText(b, g.pixel, "FIGHTER", {320, 62}, kGold, 6.0f); + g.pixel.draw(b, "2D 対戦アクション", {320, 104}, + {.color = kText, .scale = 2.0f, .align = TextAlign::Centre, .layer = 11.0f, .shadow = kOutline}); + // メニュー:英語と日本語の二列 / the menu: English and Japanese columns + Rect panel = {176, 150, 288, 116}; + b.drawRect(panel, {0.11f, 0.09f, 0.15f, 0.78f}, 10.0f); + b.drawRectOutline(panel, kGold, 1.0f, 10.1f); + for (int i = 0; i < kItemCount; ++i) { + bool on = i == selected; + Vec4 c = on ? kGold : kText; + float y = panel.y + 10.0f + 20.0f * static_cast(i); + std::string en, ja; + if (i < 4) { + en = kItems[i].english; + ja = kItems[i].japanese; + } else { + en = std::string("< ") + difficultyName(g.difficulty) + " >"; + ja = std::string("難易度 ") + kDifficultyJa[static_cast(g.difficulty)]; + } + if (on) g.pixel.draw(b, ">", {panel.x + 10.0f, y}, {.color = c, .layer = 11.0f}); + g.pixel.draw(b, en, {panel.x + 24.0f, y}, {.color = c, .layer = 11.0f}); + g.pixel.draw(b, ja, {panel.x + 160.0f, y}, {.color = c, .layer = 11.0f}); + } + b.end(); +} + +void TitleScene::drawUi(float /*alpha*/) { + SpriteBatch &b = g.batch; + b.begin(g.screen.matrix()); + b.drawRect({0, 688, 1280, 32}, {0.11f, 0.09f, 0.15f, 0.75f}); + // 点滅する案内 / a blinking prompt + float a = 0.55f + 0.45f * std::cos(time * 4.0f); + g.ui.draw(b, "W S 選ぶ・A D 難易度・Space / F 決定・Esc 終了 select / difficulty / start / quit", {640, 694}, + {.color = {0.91f, 0.88f, 0.82f, a}, .align = TextAlign::Centre}); + b.end(); +}