diff --git a/games/fighter/CMakeLists.txt b/games/fighter/CMakeLists.txt new file mode 100644 index 0000000..321c0f5 --- /dev/null +++ b/games/fighter/CMakeLists.txt @@ -0,0 +1,11 @@ +# 2D格闘ゲーム(第30〜32章):エンジンにリンクする自分の実行ファイル +# The 2D fighting game (chapters 30-32): its own executable linking the engine +add_executable(fighter + src/main.cc + src/controls.cc + src/fighter.cc + src/fight_scene.cc) +target_include_directories(fighter PRIVATE src) +target_link_libraries(fighter PRIVATE engine) +enable_warnings(fighter) +set_working_directory(fighter) diff --git a/games/fighter/README.md b/games/fighter/README.md new file mode 100644 index 0000000..e05ef59 --- /dev/null +++ b/games/fighter/README.md @@ -0,0 +1,21 @@ +# Fighter(2D格闘ゲーム / 2D fighting game, chapters 30-32) + +プロジェクトのルートから実行 / Run from the project root: + +```sh +./build/games/fighter/fighter # Linux / FreeBSD +build\games\fighter\Debug\fighter.exe # Windows (or F5 with the "fighter" target) +``` + +## 操作 / Controls(一台のキーボードを二人で / two players on one keyboard) + +| | 1P | 2P | +|---|---|---| +| 前後に歩く / walk | A D | ← → | +| ジャンプ / jump (+ 前・後ろ / forward, back) | W | ↑ | +| しゃがむ / crouch | S | ↓ | + +ゲームパッド(GLFW 3.3のゲームパッドAPI):1台目が1P、2台目が2P(十字キーか左スティック)。 +Gamepads (GLFW 3.3's gamepad API): the first is 1P, the second 2P (d-pad or left stick). + +F1 押し合いの箱と状態の表示 / push boxes and states, Esc 終了 / quit. diff --git a/games/fighter/assets/LICENSE.txt b/games/fighter/assets/LICENSE.txt new file mode 100644 index 0000000..4e11703 --- /dev/null +++ b/games/fighter/assets/LICENSE.txt @@ -0,0 +1,7 @@ +games/fighter/assets/ のファイルはこのチュートリアルのために作者が自作したもの(作者のPythonのスクリプトで生成。スクリプトはこのプロジェクトには含まれない)。自由に使ってよい。 +The files in games/fighter/assets/ were made for this tutorial by the author (generated with the author's own Python scripts, which are not part of this project). Free to use for any purpose. + +hayate.png/.atlas 1Pのファイター「ハヤテ」(白い道着、128×120のコマ38枚) / player 1's fighter "Hayate" (white gi, + 38 frames of 128 × 120) (chapter 30) +jin.png/.atlas 2Pのファイター「ジン」(紺の道着、同じコマ割りの色違い) / player 2's fighter "Jin" (indigo gi, the + same frames in other colors) (chapter 30) diff --git a/games/fighter/assets/hayate.atlas b/games/fighter/assets/hayate.atlas new file mode 100644 index 0000000..7f6978d --- /dev/null +++ b/games/fighter/assets/hayate.atlas @@ -0,0 +1,44 @@ +# hayate: fighter frames 128x120, feet pivot at (64, 116), facing right (generated by the author's own script) +image hayate.png +sprite idle0 1 1 128 120 +sprite idle1 131 1 128 120 +sprite idle2 261 1 128 120 +sprite idle3 391 1 128 120 +sprite walk0 521 1 128 120 +sprite walk1 651 1 128 120 +sprite walk2 781 1 128 120 +sprite walk3 911 1 128 120 +sprite walk4 1 123 128 120 +sprite walk5 131 123 128 120 +sprite crouch_in 261 123 128 120 +sprite crouch 391 123 128 120 +sprite jump_up 521 123 128 120 +sprite jump_tuck 651 123 128 120 +sprite jump_down 781 123 128 120 +sprite punch0 911 123 128 120 +sprite punch1 1 245 128 120 +sprite punch2 131 245 128 120 +sprite kick0 261 245 128 120 +sprite kick1 391 245 128 120 +sprite kick2 521 245 128 120 +sprite sweep0 651 245 128 120 +sprite sweep1 781 245 128 120 +sprite sweep2 911 245 128 120 +sprite jkick0 1 367 128 120 +sprite jkick1 131 367 128 120 +sprite cpunch0 261 367 128 120 +sprite cpunch1 391 367 128 120 +sprite cpunch2 521 367 128 120 +sprite block 651 367 128 120 +sprite cblock 781 367 128 120 +sprite hit0 911 367 128 120 +sprite hit1 1 489 128 120 +sprite chit 131 489 128 120 +sprite ko0 261 489 128 120 +sprite ko1 391 489 128 120 +sprite win0 521 489 128 120 +sprite win1 651 489 128 120 +clip idle 7 loop idle0 idle1 idle2 idle3 +clip walk 10 loop walk0 walk1 walk2 walk3 walk4 walk5 +clip walk_back 10 loop walk5 walk4 walk3 walk2 walk1 walk0 +clip win 4 loop win0 win1 diff --git a/games/fighter/assets/hayate.png b/games/fighter/assets/hayate.png new file mode 100644 index 0000000..505cf06 Binary files /dev/null and b/games/fighter/assets/hayate.png differ diff --git a/games/fighter/assets/jin.atlas b/games/fighter/assets/jin.atlas new file mode 100644 index 0000000..84a3b2c --- /dev/null +++ b/games/fighter/assets/jin.atlas @@ -0,0 +1,44 @@ +# jin: fighter frames 128x120, feet pivot at (64, 116), facing right (generated by the author's own script) +image jin.png +sprite idle0 1 1 128 120 +sprite idle1 131 1 128 120 +sprite idle2 261 1 128 120 +sprite idle3 391 1 128 120 +sprite walk0 521 1 128 120 +sprite walk1 651 1 128 120 +sprite walk2 781 1 128 120 +sprite walk3 911 1 128 120 +sprite walk4 1 123 128 120 +sprite walk5 131 123 128 120 +sprite crouch_in 261 123 128 120 +sprite crouch 391 123 128 120 +sprite jump_up 521 123 128 120 +sprite jump_tuck 651 123 128 120 +sprite jump_down 781 123 128 120 +sprite punch0 911 123 128 120 +sprite punch1 1 245 128 120 +sprite punch2 131 245 128 120 +sprite kick0 261 245 128 120 +sprite kick1 391 245 128 120 +sprite kick2 521 245 128 120 +sprite sweep0 651 245 128 120 +sprite sweep1 781 245 128 120 +sprite sweep2 911 245 128 120 +sprite jkick0 1 367 128 120 +sprite jkick1 131 367 128 120 +sprite cpunch0 261 367 128 120 +sprite cpunch1 391 367 128 120 +sprite cpunch2 521 367 128 120 +sprite block 651 367 128 120 +sprite cblock 781 367 128 120 +sprite hit0 911 367 128 120 +sprite hit1 1 489 128 120 +sprite chit 131 489 128 120 +sprite ko0 261 489 128 120 +sprite ko1 391 489 128 120 +sprite win0 521 489 128 120 +sprite win1 651 489 128 120 +clip idle 7 loop idle0 idle1 idle2 idle3 +clip walk 10 loop walk0 walk1 walk2 walk3 walk4 walk5 +clip walk_back 10 loop walk5 walk4 walk3 walk2 walk1 walk0 +clip win 4 loop win0 win1 diff --git a/games/fighter/assets/jin.png b/games/fighter/assets/jin.png new file mode 100644 index 0000000..662156f Binary files /dev/null and b/games/fighter/assets/jin.png differ diff --git a/games/fighter/src/controls.cc b/games/fighter/src/controls.cc new file mode 100644 index 0000000..3dbf32a --- /dev/null +++ b/games/fighter/src/controls.cc @@ -0,0 +1,54 @@ +// 一人分の操作 / one player's controls +#include "controls.hh" + +namespace { + +// 行動の名前(プレイヤーごと) / action names per player +struct ActionNames { + const char *left, *right, *up, *down; +}; +constexpr ActionNames kActions[2] = { + {"p1.left", "p1.right", "p1.up", "p1.down"}, + {"p2.left", "p2.right", "p2.up", "p2.down"}, +}; + +// ゲームパッド(GLFW 3.3以上のSDL互換マッピング):十字キーか左スティック。つながっていなければ何もしない +// A gamepad (GLFW 3.3+'s SDL-style mapping): the d-pad or the left stick. Does nothing when none is connected +void addGamepad(int player, Controls &c) { + int jid = GLFW_JOYSTICK_1 + player; + GLFWgamepadstate pad; + if (!glfwJoystickIsGamepad(jid) || !glfwGetGamepadState(jid, &pad)) return; + constexpr float kDeadZone = 0.5f; + float x = pad.axes[GLFW_GAMEPAD_AXIS_LEFT_X], y = pad.axes[GLFW_GAMEPAD_AXIS_LEFT_Y]; + c.left |= pad.buttons[GLFW_GAMEPAD_BUTTON_DPAD_LEFT] == GLFW_PRESS || x < -kDeadZone; + c.right |= pad.buttons[GLFW_GAMEPAD_BUTTON_DPAD_RIGHT] == GLFW_PRESS || x > kDeadZone; + c.up |= pad.buttons[GLFW_GAMEPAD_BUTTON_DPAD_UP] == GLFW_PRESS || y < -kDeadZone; + c.down |= pad.buttons[GLFW_GAMEPAD_BUTTON_DPAD_DOWN] == GLFW_PRESS || y > kDeadZone; +} + +} // namespace + +void bindPlayerActions(Input &input) { + for (int p = 0; p < 2; ++p) { + const PlayerKeys &k = kPlayerKeys[p]; + const ActionNames &a = kActions[p]; + input.bind(a.left, {InputBinding::key(k.left)}); + input.bind(a.right, {InputBinding::key(k.right)}); + input.bind(a.up, {InputBinding::key(k.up)}); + input.bind(a.down, {InputBinding::key(k.down)}); + } +} + +Controls readControls(const Input &input, int player) { + const ActionNames &a = kActions[player]; + Controls c; + c.left = input.actionHeld(a.left); + c.right = input.actionHeld(a.right); + c.up = input.actionHeld(a.up); + c.down = input.actionHeld(a.down); + addGamepad(player, c); + // 左右同時は「どちらでもない」(格闘ゲームの決まり:SOCD) / left + right together = neither (the fighting-game + // rule for simultaneous opposite directions, "SOCD") + if (c.left && c.right) c.left = c.right = false; + return c; +} diff --git a/games/fighter/src/controls.hh b/games/fighter/src/controls.hh new file mode 100644 index 0000000..2ea42ad --- /dev/null +++ b/games/fighter/src/controls.hh @@ -0,0 +1,30 @@ +// 一人分の操作:キーボード(一台を二人で分ける)とゲームパッド(あれば) +// One player's controls: the keyboard (one keyboard shared by two players) and a gamepad (if there is one) +#pragma once + +#include "engine/input.hh" + +// 1ステップ分の入力。方向は押している間、ファイターはこれだけを見る(キーもパッドも知らない) +// One step of input. Directions are "held". The fighter only sees this (it knows nothing about keys or pads) +struct Controls { + bool left = false, right = false, up = false, down = false; +}; + +// 一人分のキー(GLFW_KEY_…) / one player's keys (GLFW_KEY_...) +struct PlayerKeys { + int left, right, up, down; +}; + +// 1P:WASD、2P:矢印キー / 1P: WASD, 2P: the arrow keys +constexpr PlayerKeys kPlayerKeys[2] = { + {GLFW_KEY_A, GLFW_KEY_D, GLFW_KEY_W, GLFW_KEY_S}, + {GLFW_KEY_LEFT, GLFW_KEY_RIGHT, GLFW_KEY_UP, GLFW_KEY_DOWN}, +}; + +// 二人分の行動をInputに登録する("p1.left"、"p2.up"…) / registers both players' actions with Input ("p1.left", +// "p2.up"...) +void bindPlayerActions(Input &input); + +// キーボードの行動と、ゲームパッド(GLFW_JOYSTICK_1 + player)を合わせて読む。playerは0か1 +// Reads the keyboard actions together with the gamepad (GLFW_JOYSTICK_1 + player). player is 0 or 1 +Controls readControls(const Input &input, int player); diff --git a/games/fighter/src/fight_scene.cc b/games/fighter/src/fight_scene.cc new file mode 100644 index 0000000..8f068d3 --- /dev/null +++ b/games/fighter/src/fight_scene.cc @@ -0,0 +1,189 @@ +// 対戦の場面(第30章:二人が動き回る練習モード) / the fight scene (chapter 30: a training mode where both move) +#include "fight_scene.hh" + +#include "engine/collision.hh" + +#include +#include +#include +#include + +namespace { + +// 画面の端(押し合いの箱がこの外に出ない) / the stage edges (push boxes never leave them) +constexpr float kStageLeft = 16.0f; +constexpr float kStageRight = 624.0f; + +// 道場の色 / the dojo's colors +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); + +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; +} + +} // namespace + +FightScene::FightScene(Game &game) + : g(game), camera(Camera2D::screen(kViewSize)), + fighters{Fighter(*game.fighters[0], "HAYATE", {200.0f, kGroundY}, 1.0f), + Fighter(*game.fighters[1], "JIN", {440.0f, kGroundY}, -1.0f)} {} + +void FightScene::update(float dt) { + Input &in = g.input; + if (in.pressed(GLFW_KEY_ESCAPE)) { + scenes().pop(); // 最後のシーン:終了 / the last scene: quit + return; + } + if (in.pressed(GLFW_KEY_F1)) g.showBoxes = !g.showBoxes; + + // 二人の入力を先に全部読み、相手の位置もステップの最初の値を使う:1Pを先に動かしても2Pが得をしない + // Read both inputs first and use the opponents' positions from the start of the step: updating 1P first gives + // neither player an advantage + Controls controls[2] = {readControls(in, 0), readControls(in, 1)}; + float startX[2] = {fighters[0].position.x, fighters[1].position.x}; + for (Fighter &f : fighters) f.savePrevious(); + for (int i = 0; i < 2; ++i) fighters[i].update(dt, controls[i], startX[1 - i]); + separate(); +} + +// 押し合い:箱が重なったら半分ずつ離す。片方が壁で止まったら、もう片方がその分も下がる +// Pushing: overlapping push boxes are moved apart by half the overlap each. If one is stopped by a wall, the other +// takes the rest +void FightScene::separate() { + Fighter &a = fighters[0], &b = fighters[1]; + clampToStage(a); + clampToStage(b); + 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()); + float dir = a.position.x < b.position.x ? -1.0f : a.position.x > b.position.x ? 1.0f : -a.facing; // aの動く向き / + // a's direction + 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); + // 壁が押し返した分を先に両方覚えてから、相手に渡す / remember both wall corrections first, then pass each one on + float da = a.position.x - ax, db = b.position.x - bx; + b.position.x += da; + a.position.x += db; +} + +void FightScene::drawBackground() { + SpriteBatch &b = g.batch; + // 梁と漆喰の壁 / beams and the plaster wall + b.drawRect({0, 0, 640, 360}, kPlaster); + b.drawRect({0, 0, 640, 34}, kBeam); + b.drawRect({0, 34, 640, 3}, kBeamLight); + b.drawRect({0, 37, 640, 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); + } + // 掛け軸「練習」 / 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({0, 222, 640, 38}, kWainscot); + b.drawRect({0, 222, 640, 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; + for (float h : {6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 12.0f, 13.0f, 15.0f, 20.0f}) { + b.drawRect({0, y, 640, h}, row % 2 ? kPlankA : kPlankB); + b.drawRect({0, y, 640, 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; + } +} + +void FightScene::draw(float alpha) { + SpriteBatch &b = g.batch; + b.begin(camera.matrix(), SpriteSort::Layer); + drawBackground(); + // 影:地面に。高く跳ぶほど小さく / shadows on the ground, smaller the higher the jump + for (const Fighter &f : fighters) { + Vec2 p = lerp(f.previous, f.position, alpha); + float height = std::clamp((kGroundY - p.y) / 100.0f, 0.0f, 1.0f); + float w = std::round(44.0f * (1.0f - 0.4f * height)); + float x = std::round(p.x); + Vec4 c = {0.11f, 0.09f, 0.15f, 0.35f}; + b.drawRect({x - w * 0.5f + 4.0f, kGroundY - 3.0f, w - 8.0f, 6.0f}, c, 1.0f); + b.drawRect({x - w * 0.5f, kGroundY - 2.0f, 4.0f, 4.0f}, c, 1.0f); + b.drawRect({x + w * 0.5f - 4.0f, kGroundY - 2.0f, 4.0f, 4.0f}, c, 1.0f); + } + fighters[0].draw(b, alpha, 2.0f); + fighters[1].draw(b, alpha, 3.0f); + if (g.showBoxes) drawDebug(alpha); + + // 名前(キャンバスの中のピクセル文字) / names (pixel text inside the canvas) + TextStyle name = {.color = hexColor(0xfff4d8ff), .layer = 10.0f, .shadow = kOutline}; + b.drawRect({0, 0, 640, 22}, {0.11f, 0.09f, 0.15f, 0.55f}, 9.5f); + g.pixel.draw(b, "1P " + fighters[0].name, {12, 4}, name); + TextStyle right = name; + right.align = TextAlign::Right; + g.pixel.draw(b, fighters[1].name + " 2P", {628, 4}, right); + TextStyle centre = name; + centre.align = TextAlign::Centre; + centre.color = hexColor(0xf2c14eff); + g.pixel.draw(b, "練習 TRAINING", {320, 4}, centre); + b.end(); +} + +// F1:押し合いの箱、足元、状態の名前と時間 / F1: push boxes, the feet, the state name and its time +void FightScene::drawDebug(float alpha) { + SpriteBatch &b = g.batch; + for (const Fighter &f : fighters) { + Vec2 p = lerp(f.previous, f.position, alpha); + Rect box = f.pushbox().translated(p - f.position); + box = {std::round(box.x), std::round(box.y), box.w, box.h}; + b.drawRectOutline(box, hexColor(0x50e070ff), 1.0f, 8.0f); + b.drawRect({std::round(p.x) - 3, std::round(p.y), 7, 1}, hexColor(0xffffffff), 8.0f); + b.drawRect({std::round(p.x), std::round(p.y) - 3, 1, 7}, hexColor(0xffffffff), 8.0f); + char label[64]; + std::snprintf(label, sizeof label, "%s %d\nVX %.0f VY %.0f", stateName(f.state), f.stateTime, + static_cast(f.velocity.x + 0.0f), static_cast(f.velocity.y + 0.0f)); // +0:-0を0に / +0 turns -0 into 0 + // 3×5の小さな文字は影なし、暗い下地の上に / the tiny 3 × 5 font without a shadow, on a dark plate + Vec2 size = g.tiny.measure(label); + Vec2 at = {std::round(p.x), std::round(box.y) - 16.0f}; + b.drawRect({std::round(at.x - size.x * 0.5f) - 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 = hexColor(0xfff4d8ff), .align = TextAlign::Centre, .layer = 9.0f}); + } +} + +void FightScene::drawUi(float /*alpha*/) { + // 操作の説明(画面の下、1280×720の文字) / the controls (bottom of the screen, 1280 × 720 text) + SpriteBatch &b = g.batch; + b.begin(g.screen.matrix()); + b.drawRect({0, 688, 1280, 32}, {0.11f, 0.09f, 0.15f, 0.75f}); + TextStyle s = {.color = hexColor(0xe8e0d0ff)}; + g.ui.draw(b, "1P: A D 左右・W ジャンプ・S しゃがむ 2P: カーソルキー / arrow keys F1 当たり箱 / boxes Esc 終了 / quit", + {640, 694}, {.color = s.color, .align = TextAlign::Centre}); + b.end(); +} diff --git a/games/fighter/src/fight_scene.hh b/games/fighter/src/fight_scene.hh new file mode 100644 index 0000000..6693950 --- /dev/null +++ b/games/fighter/src/fight_scene.hh @@ -0,0 +1,25 @@ +// 対戦の場面:二人のファイター、押し合い、画面の端、道場の背景 +// The fight scene: two fighters, pushing apart, the stage edges, the dojo background +#pragma once + +#include "fighter.hh" +#include "game.hh" + +#include "engine/scene.hh" + +class FightScene : public Scene { +public: + explicit FightScene(Game &game); + void update(float dt) override; + void draw(float alpha) override; + void drawUi(float alpha) override; + +private: + void separate(); + void drawBackground(); + void drawDebug(float alpha); + + Game &g; + Camera2D camera; // 640×360のキャンバス / the 640 × 360 canvas + Fighter fighters[2]; +}; diff --git a/games/fighter/src/fighter.cc b/games/fighter/src/fighter.cc new file mode 100644 index 0000000..3812a4d --- /dev/null +++ b/games/fighter/src/fighter.cc @@ -0,0 +1,156 @@ +// ファイター:状態機械と2Dの物理 / a fighter: the state machine and 2D physics +#include "fighter.hh" + +#include + +namespace { + +// 動きの数値。時間はフレーム(60 Hzのステップ)、速さはピクセル毎秒 / movement tuning. Times in frames (60 Hz +// steps), speeds in pixels per second +constexpr float kWalkForward = 130.0f; +constexpr float kWalkBack = 100.0f; +constexpr float kJumpSpeed = 560.0f; // 上向きの初速 / initial upward speed +constexpr float kJumpForward = 150.0f; // 前後ジャンプの横の速さ / horizontal speed of a forward / back jump +constexpr float kGravity = 1800.0f; // 高さ v²/2g ≈ 87 px、滞空 2v/g ≈ 0.62 s(37フレーム) / height v²/2g ≈ 87 px, + // air time 2v/g ≈ 0.62 s (37 frames) +constexpr int kJumpSquatFrames = 4; +constexpr int kLandFrames = 4; +constexpr int kCrouchInFrames = 3; // しゃがみ始めのコマを見せる時間 / how long the "going down" frame shows + +// コマの原点:128×120のセルの中の足元(64, 116) / the frame origin: the feet at (64, 116) in the 128 × 120 cell +constexpr Vec2 kPivot = {64.0f / 128.0f, 116.0f / 120.0f}; + +int findFrame(const SpriteSheet &sheet, const char *name) { + int i = sheet.find(name); + return i >= 0 ? i : 0; +} + +} // namespace + +const char *stateName(FighterState state) { + switch (state) { + case FighterState::Idle: return "IDLE"; + case FighterState::Walk: return "WALK"; + case FighterState::Crouch: return "CROUCH"; + case FighterState::JumpSquat: return "JUMPSQUAT"; + case FighterState::Air: return "AIR"; + case FighterState::Land: return "LAND"; + } + return "?"; +} + +Fighter::Fighter(const SpriteSheet &s, std::string fighterName, Vec2 start, float startFacing) + : name(std::move(fighterName)), position(start), previous(start), facing(startFacing), sheet(s), + 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")), + fJumpTuck(findFrame(s, "jump_tuck")), fJumpDown(findFrame(s, "jump_down")) { + animator.play(idleClip); + frame = animator.frame(); +} + +// 状態を変える。同じ状態なら時間を数え続ける / changes the state; the same state keeps counting +void Fighter::setState(FighterState next) { + if (next == state) return; + state = next; + stateTime = 0; +} + +void Fighter::update(float dt, const Controls &c, float opponentX) { + ++stateTime; + switch (state) { + case FighterState::Idle: + case FighterState::Walk: + case FighterState::Crouch: { + // 地上で自由に動ける状態:いつも相手の方を向く(ぴったり重なったら向きを変えない) + // Free on the ground: always face the opponent (keep the facing when exactly on top of each other) + if (std::abs(opponentX - position.x) > 1.0f) facing = opponentX > position.x ? 1.0f : -1.0f; + bool fwd = forward(c, facing), bwd = back(c, facing); + if (c.up) { + jumpDirection = fwd ? 1.0f : bwd ? -1.0f : 0.0f; + velocity = {0.0f, 0.0f}; + setState(FighterState::JumpSquat); + } else if (c.down) { + velocity.x = 0.0f; + setState(FighterState::Crouch); + } else if (fwd || bwd) { + walkingBack = bwd; + velocity.x = facing * (fwd ? kWalkForward : -kWalkBack); + setState(FighterState::Walk); + } else { + velocity.x = 0.0f; + setState(FighterState::Idle); + } + break; + } + case FighterState::JumpSquat: + // 「ため」の間はまだ地面。終わったら跳ぶ:上向きの速度と、決めた向きへの横の速度 + // Still on the ground during the squat. Then take off: an upward velocity plus the chosen horizontal one + if (stateTime >= kJumpSquatFrames) { + velocity = {facing * jumpDirection * kJumpForward, -kJumpSpeed}; + setState(FighterState::Air); + } + break; + case FighterState::Air: + velocity.y += kGravity * dt; // 重力:速度を変える(位置は下で速度から) / gravity changes the velocity (the + // position follows from the velocity below) + break; + case FighterState::Land: + if (stateTime >= kLandFrames) setState(FighterState::Idle); + break; + } + + // 半陰的オイラー法:速度を先に、その速度で位置を / semi-implicit Euler: velocity first, then the position with it + position += velocity * dt; + + // 地面:落ちてきて地面より下なら、地面に置いて着地 / the ground: when falling below it, put the fighter on it and land + if (state == FighterState::Air && velocity.y > 0.0f && position.y >= kGroundY) { + position.y = kGroundY; + velocity = {0.0f, 0.0f}; + setState(FighterState::Land); + } + chooseFrame(dt); +} + +// 状態からコマを選ぶ。ループする動き(立ち・歩き)はAnimator、それ以外は状態と速度で決める +// Picks the frame from the state. Looping motions (idle, walk) use the Animator; the rest depend on state and velocity +void Fighter::chooseFrame(float dt) { + switch (state) { + case FighterState::Idle: + animator.play(idleClip); + break; + case FighterState::Walk: + animator.play(walkingBack ? walkBackClip : walkClip); + break; + case FighterState::Crouch: + frame = stateTime < kCrouchInFrames ? fCrouchIn : fCrouch; + return; + case FighterState::JumpSquat: + case FighterState::Land: + frame = fCrouchIn; + return; + case FighterState::Air: + // 上昇中・頂点の近く・落下中 / rising, near the top, falling + frame = velocity.y < -180.0f ? fJumpUp : velocity.y < 180.0f ? fJumpTuck : fJumpDown; + return; + } + animator.update(dt); + frame = animator.frame(); +} + +Rect Fighter::pushbox() const { + // 足元からの箱。空中は脚をたたむので下が空く(相手の上を越えられる) / boxes from the feet; in the air the legs are + // tucked, so the bottom is open (a fighter can pass over the other) + Rect local = state == FighterState::Crouch ? Rect{-15.0f, -60.0f, 30.0f, 60.0f} + : state == FighterState::Air ? Rect{-13.0f, -86.0f, 26.0f, 58.0f} + : Rect{-14.0f, -88.0f, 28.0f, 88.0f}; + return local.translated(position); +} + +void Fighter::draw(SpriteBatch &batch, float alpha, float layer) const { + // 補間した位置を整数に丸める(ピクセルアートは整数の位置に) / the interpolated position, rounded to whole pixels + Vec2 p = lerp(previous, position, alpha); + Sprite s = sheet.sprite(frame, {std::round(p.x), std::round(p.y)}, kPivot); + s.flipX = facing < 0.0f; // 絵は右向き:左向きは左右反転 / the art faces right; facing left mirrors it + s.layer = layer; + batch.draw(s); +} diff --git a/games/fighter/src/fighter.hh b/games/fighter/src/fighter.hh new file mode 100644 index 0000000..ff010a1 --- /dev/null +++ b/games/fighter/src/fighter.hh @@ -0,0 +1,67 @@ +// ファイター:状態機械(立ち・歩き・しゃがみ・ジャンプ)、2Dの物理(重力・速度・地面)、コマ送りのアニメーション +// A fighter: a state machine (idle, walk, crouch, jump), 2D physics (gravity, velocity, the ground) and frame +// animation +#pragma once + +#include "controls.hh" + +#include "engine/animation.hh" +#include "engine/rect.hh" +#include "engine/sprite_batch.hh" +#include "engine/sprite_sheet.hh" + +#include + +// キャンバスは640×360(画面に2倍)。足元のy座標 / the canvas is 640 × 360 (×2 on screen). The y of the feet +constexpr float kGroundY = 320.0f; + +// 状態。どの状態でも「何ステップ目か」(stateTime)を数える:格闘ゲームの時間はフレーム数 +// The states. Every state counts its steps (stateTime): in fighting games time is measured in frames +enum class FighterState { + Idle, // 立ち / standing + Walk, // 歩き(前・後ろ) / walking (forwards or backwards) + Crouch, // しゃがみ / crouching + JumpSquat, // 跳ぶ前のため(数フレーム、まだ地面) / the crouch before take-off (a few frames, still on the ground) + Air, // 空中(放物線、空中では向きも軌道も変えられない) / in the air (a parabola; neither facing nor arc can + // change) + Land, // 着地の硬さ(数フレーム動けない) / landing recovery (a few frames without control) +}; +const char *stateName(FighterState state); + +class Fighter { +public: + Fighter(const SpriteSheet &sheet, std::string name, Vec2 start, float facing); + + // 1ステップ(1/60秒)進める。opponentXで相手の方を向く / advances one step (1/60 s); faces the opponent at opponentX + void update(float dt, const Controls &controls, float opponentX); + // ステップの最初に呼ぶ:描くときの補間用に今の位置を覚える / call at the start of a step: remembers the position + // for interpolation when drawing + void savePrevious() { previous = position; } + + // 押し合いの箱(ワールド座標):二人が重ならないための箱 / the push box (world): keeps the two fighters apart + Rect pushbox() const; + void draw(SpriteBatch &batch, float alpha, float layer) const; + // 前を押しているか(向きに対して) / is "forward" held (relative to the facing) + static bool forward(const Controls &c, float facing) { return facing > 0.0f ? c.right : c.left; } + static bool back(const Controls &c, float facing) { return facing > 0.0f ? c.left : c.right; } + + std::string name; + Vec2 position; // 足元の中心(ワールドのピクセル、y下向き) / the feet center (world pixels, y down) + Vec2 previous; // 前のステップの位置 / last step's position + Vec2 velocity; // ピクセル毎秒 / pixels per second + float facing = 1.0f; // +1 = 右向き、-1 = 左向き / +1 = facing right, -1 = facing left + FighterState state = FighterState::Idle; + int stateTime = 0; // この状態で何ステップ目か / steps spent in this state + bool walkingBack = false; + int frame = 0; // 今のコマ(スプライトシートの番号) / the current frame (sprite-sheet index) + +private: + void setState(FighterState next); + void chooseFrame(float dt); + + const SpriteSheet &sheet; + const AnimationClip *idleClip, *walkClip, *walkBackClip; + Animator animator; + float jumpDirection = 0.0f; // -1 後ろ、0 垂直、+1 前 / -1 back, 0 straight up, +1 forwards + int fCrouchIn, fCrouch, fJumpUp, fJumpTuck, fJumpDown; +}; diff --git a/games/fighter/src/game.hh b/games/fighter/src/game.hh new file mode 100644 index 0000000..79b2834 --- /dev/null +++ b/games/fighter/src/game.hh @@ -0,0 +1,27 @@ +// 格闘ゲーム全体で一つの共有データ(mainが作り、シーンは参照で持つ) +// The fighting game's shared data, one per game (main creates it, the scenes keep a reference) +#pragma once + +#include "engine/camera2d.hh" +#include "engine/font.hh" +#include "engine/game_loop.hh" +#include "engine/input.hh" +#include "engine/sprite_batch.hh" +#include "engine/sprite_sheet.hh" + +// 仮想解像度:640×360(1280×720に2倍)。ファイターが大きく描ける / the virtual resolution: 640 × 360 (×2 in +// 1280 × 720), so the fighters can be big +constexpr Vec2 kViewSize = {640.0f, 360.0f}; + +struct Game { + Window &window; + Input &input; + GameLoop &loop; + SpriteBatch &batch; + const Font &ui; // mono16:1280×720のUI / the 1280 × 720 UI + const Font &pixel; // pixel12:キャンバスの中 / inside the canvas + const Font &tiny; // pixel5:デバッグ表示 / debug labels + const SpriteSheet *fighters[2]; // ハヤテ(1P)とジン(2P) / Hayate (1P) and Jin (2P) + Camera2D screen; // 1280×720のUI / the 1280 × 720 UI + bool showBoxes = false; // F1:判定の箱とデバッグ表示 / F1: boxes and debug labels +}; diff --git a/games/fighter/src/main.cc b/games/fighter/src/main.cc new file mode 100644 index 0000000..2f5598b --- /dev/null +++ b/games/fighter/src/main.cc @@ -0,0 +1,63 @@ +// 2D格闘ゲーム(第30〜32章) / The 2D fighting game (chapters 30-32) +// +// 第30章:ファイターの状態機械(立ち・歩き・しゃがみ・ジャンプ)、2Dの物理、コマ送りのアニメーション、二人の入力 +// Chapter 30: the fighter state machine (idle, walk, crouch, jump), 2D physics, frame animation, two players' input +// +// 操作(一台のキーボードを二人で) / Controls (two players on one keyboard): +// 1P A D 前後・W ジャンプ・S しゃがみ / A D walk, W jump, S crouch +// 2P ← → 前後・↑ ジャンプ・↓ しゃがみ / arrow keys +// ゲームパッド:1台目 = 1P、2台目 = 2P(十字キーか左スティック) / gamepads: 1st = 1P, 2nd = 2P (d-pad or left stick) +// F1 押し合いの箱と状態 / push boxes and states Esc 終了 / quit +#include "fight_scene.hh" +#include "game.hh" + +#include "engine/pixel_canvas.hh" +#include "engine/window.hh" + +#include +#include + +int main() { + Window window; + if (!window.create(1280, 720, "OpenGL Tutorial - Fighter")) return 1; + + std::optional batch = SpriteBatch::create(); + std::optional ui = Font::load("assets/fonts/mono16.fnt"); + std::optional pixel = Font::load("assets/fonts/pixel12.fnt", TextureFilter::Nearest); + std::optional tiny = Font::load("assets/fonts/pixel5.fnt", TextureFilter::Nearest); + // 二人のファイター:同じ骨格・同じコマ割りで色だけ違う(パレットスワップ) / the two fighters: same skeleton and + // frame layout, different colors (a palette swap) + std::optional hayate = SpriteSheet::loadAtlas("games/fighter/assets/hayate.atlas"); + std::optional jin = SpriteSheet::loadAtlas("games/fighter/assets/jin.atlas"); + if (!batch || !ui || !pixel || !tiny || !hayate || !jin) return 1; + + Input input; + input.attach(window); + bindPlayerActions(input); + + 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}, .screen = Camera2D::screen({1280.0f, 720.0f})}; + + SceneManager scenes; + scenes.push(std::make_unique(game)); + + loop.run( + window, input, + [&](float dt) { + scenes.update(dt); + if (scenes.empty()) window.close(); + }, + [&](float alpha) { + // 世界は640×360のキャンバスへ(2倍で画面に)、UIは1280×720で / the world into the 640 × 360 canvas (×2 on + // screen), the UI at 1280 × 720 + canvas.begin(hexColor(0x1b1726ff)); + scenes.draw(alpha); + canvas.present(window.width(), window.height()); + letterbox(window.width(), window.height(), game.screen.viewSize, false).apply(); + scenes.drawUi(alpha); + scenes.drawFade(*batch, game.screen.matrix(), game.screen.viewSize); + }); + return 0; +}