@vibe-engine/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/LICENSE-MIT +22 -0
  3. package/README.md +10 -2
  4. package/dist/assets.d.ts +9 -0
  5. package/dist/assets.js +76 -0
  6. package/dist/bin.d.ts +2 -0
  7. package/dist/bin.js +7 -0
  8. package/dist/boundary.d.ts +12 -0
  9. package/dist/boundary.js +63 -0
  10. package/dist/create.d.ts +7 -0
  11. package/dist/create.js +53 -0
  12. package/dist/game-test.d.ts +60 -0
  13. package/dist/game-test.js +129 -0
  14. package/dist/index.d.ts +5 -0
  15. package/dist/index.js +5 -0
  16. package/dist/info.d.ts +41 -0
  17. package/dist/info.js +57 -0
  18. package/dist/main.d.ts +9 -0
  19. package/dist/main.js +106 -0
  20. package/dist/map.d.ts +21 -0
  21. package/dist/map.js +29 -0
  22. package/dist/project.d.ts +74 -0
  23. package/dist/project.js +273 -0
  24. package/dist/registry.d.ts +62 -0
  25. package/dist/registry.js +27 -0
  26. package/dist/run.d.ts +18 -0
  27. package/dist/run.js +132 -0
  28. package/dist/save-store.d.ts +2 -0
  29. package/dist/save-store.js +19 -0
  30. package/dist/serve.d.ts +6 -0
  31. package/dist/serve.js +63 -0
  32. package/dist/source.d.ts +7 -0
  33. package/dist/source.js +20 -0
  34. package/dist/test-run.d.ts +17 -0
  35. package/dist/test-run.js +94 -0
  36. package/dist/vite-plugin.d.ts +17 -0
  37. package/dist/vite-plugin.js +211 -0
  38. package/dist/web.d.ts +32 -0
  39. package/dist/web.js +195 -0
  40. package/package.json +52 -3
  41. package/templates/arena-3d/AGENTS.md +169 -0
  42. package/templates/arena-3d/CLAUDE.md +3 -0
  43. package/templates/arena-3d/README.md +13 -0
  44. package/templates/arena-3d/assets/audio/coin.wav +0 -0
  45. package/templates/arena-3d/assets/fonts/LICENSE-kenney-fonts.txt +23 -0
  46. package/templates/arena-3d/assets/fonts/kenney-future.ttf +0 -0
  47. package/templates/arena-3d/assets/models/LICENSE-kenney-blocky-characters.txt +28 -0
  48. package/templates/arena-3d/assets/models/character.glb +0 -0
  49. package/templates/arena-3d/assets/ui/LICENSE-kenney-ui-pack.txt +23 -0
  50. package/templates/arena-3d/assets/ui/panel.meta.json +1 -0
  51. package/templates/arena-3d/assets/ui/panel.png +0 -0
  52. package/templates/arena-3d/package.json +22 -0
  53. package/templates/arena-3d/src/components/game.component.ts +11 -0
  54. package/templates/arena-3d/src/components/player.component.ts +16 -0
  55. package/templates/arena-3d/src/controls.input.ts +7 -0
  56. package/templates/arena-3d/src/level/build.ts +40 -0
  57. package/templates/arena-3d/src/maps/arena.map.ts +50 -0
  58. package/templates/arena-3d/src/scenes/arena.scene.ts +10 -0
  59. package/templates/arena-3d/src/systems/player-controller.system.ts +46 -0
  60. package/templates/arena-3d/src/systems/rules.system.ts +58 -0
  61. package/templates/arena-3d/src/ui/hud.ui.ts +11 -0
  62. package/templates/arena-3d/tests/arena.test.ts +111 -0
  63. package/templates/arena-3d/vibe.config.ts +21 -0
  64. package/templates/platformer-2d/AGENTS.md +172 -0
  65. package/templates/platformer-2d/CLAUDE.md +3 -0
  66. package/templates/platformer-2d/README.md +17 -0
  67. package/templates/platformer-2d/assets/KENNEY-LICENSE.txt +30 -0
  68. package/templates/platformer-2d/assets/audio/coin.wav +0 -0
  69. package/templates/platformer-2d/assets/audio/enemy-defeat.wav +0 -0
  70. package/templates/platformer-2d/assets/audio/enemy-hit.wav +0 -0
  71. package/templates/platformer-2d/assets/audio/game-over.wav +0 -0
  72. package/templates/platformer-2d/assets/audio/hurt.wav +0 -0
  73. package/templates/platformer-2d/assets/audio/jump.wav +0 -0
  74. package/templates/platformer-2d/assets/audio/level-complete.wav +0 -0
  75. package/templates/platformer-2d/assets/audio/music-theme.wav +0 -0
  76. package/templates/platformer-2d/assets/audio/shoot.wav +0 -0
  77. package/templates/platformer-2d/assets/audio/stomp.wav +0 -0
  78. package/templates/platformer-2d/assets/fonts/LICENSE-kenney-fonts.txt +23 -0
  79. package/templates/platformer-2d/assets/fonts/kenney-pixel.ttf +0 -0
  80. package/templates/platformer-2d/assets/sprites/bullet.png +0 -0
  81. package/templates/platformer-2d/assets/sprites/characters.meta.json +9 -0
  82. package/templates/platformer-2d/assets/sprites/characters.png +0 -0
  83. package/templates/platformer-2d/assets/sprites/heart-empty.png +0 -0
  84. package/templates/platformer-2d/assets/sprites/heart.png +0 -0
  85. package/templates/platformer-2d/assets/sprites/pistol.png +0 -0
  86. package/templates/platformer-2d/assets/sprites/tiles.meta.json +7 -0
  87. package/templates/platformer-2d/assets/sprites/tiles.png +0 -0
  88. package/templates/platformer-2d/assets/ui/button-focus.meta.json +1 -0
  89. package/templates/platformer-2d/assets/ui/button-focus.png +0 -0
  90. package/templates/platformer-2d/assets/ui/button-hover.meta.json +1 -0
  91. package/templates/platformer-2d/assets/ui/button-hover.png +0 -0
  92. package/templates/platformer-2d/assets/ui/button-pressed.meta.json +1 -0
  93. package/templates/platformer-2d/assets/ui/button-pressed.png +0 -0
  94. package/templates/platformer-2d/assets/ui/button.meta.json +1 -0
  95. package/templates/platformer-2d/assets/ui/button.png +0 -0
  96. package/templates/platformer-2d/assets/ui/panel.meta.json +1 -0
  97. package/templates/platformer-2d/assets/ui/panel.png +0 -0
  98. package/templates/platformer-2d/package.json +22 -0
  99. package/templates/platformer-2d/src/components/enemy.component.ts +12 -0
  100. package/templates/platformer-2d/src/components/gun.component.ts +18 -0
  101. package/templates/platformer-2d/src/components/level.component.ts +10 -0
  102. package/templates/platformer-2d/src/components/pickup.component.ts +7 -0
  103. package/templates/platformer-2d/src/components/player.component.ts +25 -0
  104. package/templates/platformer-2d/src/components/shockwave.component.ts +7 -0
  105. package/templates/platformer-2d/src/controls.input.ts +10 -0
  106. package/templates/platformer-2d/src/events/gameplay.events.ts +11 -0
  107. package/templates/platformer-2d/src/level/build.ts +89 -0
  108. package/templates/platformer-2d/src/listeners/feedback.listener.ts +22 -0
  109. package/templates/platformer-2d/src/listeners/particles.listener.ts +21 -0
  110. package/templates/platformer-2d/src/listeners/progress.listener.ts +18 -0
  111. package/templates/platformer-2d/src/listeners/sound-effects.listener.ts +16 -0
  112. package/templates/platformer-2d/src/maps/legend.ts +9 -0
  113. package/templates/platformer-2d/src/maps/level-1.map.ts +22 -0
  114. package/templates/platformer-2d/src/maps/level-2.map.ts +22 -0
  115. package/templates/platformer-2d/src/saves/progress.save.ts +11 -0
  116. package/templates/platformer-2d/src/scenes/level-1.scene.ts +17 -0
  117. package/templates/platformer-2d/src/scenes/level-2.scene.ts +16 -0
  118. package/templates/platformer-2d/src/scenes/main-menu.scene.ts +36 -0
  119. package/templates/platformer-2d/src/systems/contacts.system.ts +74 -0
  120. package/templates/platformer-2d/src/systems/enemy-patrol.system.ts +28 -0
  121. package/templates/platformer-2d/src/systems/gameplay.ts +17 -0
  122. package/templates/platformer-2d/src/systems/gun.system.ts +65 -0
  123. package/templates/platformer-2d/src/systems/hud.system.ts +23 -0
  124. package/templates/platformer-2d/src/systems/pause.system.ts +22 -0
  125. package/templates/platformer-2d/src/systems/player-controller.system.ts +46 -0
  126. package/templates/platformer-2d/src/systems/player-damage.system.ts +61 -0
  127. package/templates/platformer-2d/src/systems/player-juice.system.ts +40 -0
  128. package/templates/platformer-2d/src/systems/shockwave.system.ts +15 -0
  129. package/templates/platformer-2d/src/ui/hud.ui.ts +16 -0
  130. package/templates/platformer-2d/src/ui/main-menu.ui.ts +7 -0
  131. package/templates/platformer-2d/src/ui/pause-menu.ui.ts +12 -0
  132. package/templates/platformer-2d/tests/gameplay.test.ts +492 -0
  133. package/templates/platformer-2d/tests/jump.test.ts +41 -0
  134. package/templates/platformer-2d/vibe.config.ts +32 -0
  135. package/templates/shooter-2d-pvp/AGENTS.md +181 -0
  136. package/templates/shooter-2d-pvp/CLAUDE.md +3 -0
  137. package/templates/shooter-2d-pvp/README.md +14 -0
  138. package/templates/shooter-2d-pvp/assets/KENNEY-LICENSE.txt +30 -0
  139. package/templates/shooter-2d-pvp/assets/audio/enemy-defeat.wav +0 -0
  140. package/templates/shooter-2d-pvp/assets/audio/enemy-hit.wav +0 -0
  141. package/templates/shooter-2d-pvp/assets/audio/game-over.wav +0 -0
  142. package/templates/shooter-2d-pvp/assets/audio/hurt.wav +0 -0
  143. package/templates/shooter-2d-pvp/assets/audio/jump.wav +0 -0
  144. package/templates/shooter-2d-pvp/assets/audio/shoot.wav +0 -0
  145. package/templates/shooter-2d-pvp/assets/fonts/LICENSE-kenney-fonts.txt +23 -0
  146. package/templates/shooter-2d-pvp/assets/fonts/kenney-pixel.ttf +0 -0
  147. package/templates/shooter-2d-pvp/assets/sprites/bullet.png +0 -0
  148. package/templates/shooter-2d-pvp/assets/sprites/characters.meta.json +84 -0
  149. package/templates/shooter-2d-pvp/assets/sprites/characters.png +0 -0
  150. package/templates/shooter-2d-pvp/assets/sprites/heart.png +0 -0
  151. package/templates/shooter-2d-pvp/assets/sprites/pistol.png +0 -0
  152. package/templates/shooter-2d-pvp/assets/sprites/tiles.meta.json +7 -0
  153. package/templates/shooter-2d-pvp/assets/sprites/tiles.png +0 -0
  154. package/templates/shooter-2d-pvp/assets/ui/button-focus.meta.json +1 -0
  155. package/templates/shooter-2d-pvp/assets/ui/button-focus.png +0 -0
  156. package/templates/shooter-2d-pvp/assets/ui/button-hover.meta.json +1 -0
  157. package/templates/shooter-2d-pvp/assets/ui/button-hover.png +0 -0
  158. package/templates/shooter-2d-pvp/assets/ui/button-pressed.meta.json +1 -0
  159. package/templates/shooter-2d-pvp/assets/ui/button-pressed.png +0 -0
  160. package/templates/shooter-2d-pvp/assets/ui/button.meta.json +1 -0
  161. package/templates/shooter-2d-pvp/assets/ui/button.png +0 -0
  162. package/templates/shooter-2d-pvp/assets/ui/panel.meta.json +1 -0
  163. package/templates/shooter-2d-pvp/assets/ui/panel.png +0 -0
  164. package/templates/shooter-2d-pvp/package.json +23 -0
  165. package/templates/shooter-2d-pvp/src/components/fighter.component.ts +33 -0
  166. package/templates/shooter-2d-pvp/src/components/gun.component.ts +60 -0
  167. package/templates/shooter-2d-pvp/src/controls.input.ts +14 -0
  168. package/templates/shooter-2d-pvp/src/events/combat.events.ts +15 -0
  169. package/templates/shooter-2d-pvp/src/level/build.ts +46 -0
  170. package/templates/shooter-2d-pvp/src/listeners/effects.listener.ts +71 -0
  171. package/templates/shooter-2d-pvp/src/listeners/players.listener.ts +32 -0
  172. package/templates/shooter-2d-pvp/src/maps/arena.map.ts +26 -0
  173. package/templates/shooter-2d-pvp/src/rooms/arena.room.ts +22 -0
  174. package/templates/shooter-2d-pvp/src/rules/damage.ts +56 -0
  175. package/templates/shooter-2d-pvp/src/saves/player.save.ts +9 -0
  176. package/templates/shooter-2d-pvp/src/scenes/arena.scene.ts +15 -0
  177. package/templates/shooter-2d-pvp/src/scenes/lobby.scene.ts +11 -0
  178. package/templates/shooter-2d-pvp/src/systems/combat.system.ts +95 -0
  179. package/templates/shooter-2d-pvp/src/systems/fighter-controller.system.ts +54 -0
  180. package/templates/shooter-2d-pvp/src/systems/gun.system.ts +147 -0
  181. package/templates/shooter-2d-pvp/src/systems/lobby.system.ts +52 -0
  182. package/templates/shooter-2d-pvp/src/systems/view.system.ts +35 -0
  183. package/templates/shooter-2d-pvp/src/ui/hud.ui.ts +10 -0
  184. package/templates/shooter-2d-pvp/src/ui/lobby.ui.ts +18 -0
  185. package/templates/shooter-2d-pvp/tests/pvp.test.ts +258 -0
  186. package/templates/shooter-2d-pvp/vibe.config.ts +39 -0
@@ -0,0 +1,15 @@
1
+ import { defineEvent } from '@vibe-engine/core';
2
+
3
+ export const FighterJumped = defineEvent<{ fighter: string }>('fighter.jumped');
4
+ export const FighterLanded = defineEvent<{ fighter: string; airTicks: number }>('fighter.landed');
5
+ export const ShotFired = defineEvent<{ gun: string; bullet: string; dir: { x: number; y: number } }>('gun.fired');
6
+ export const FighterHit = defineEvent<{ fighter: string; by: string; hpLeft: number }>('fighter.hit');
7
+ export const FighterKilled = defineEvent<{ fighter: string; by: string; x: number; y: number }>('fighter.killed');
8
+ export const FighterRespawned = defineEvent<{ fighter: string }>('fighter.respawned');
9
+ export const MatchOver = defineEvent<{ winner: string }>('match.over');
10
+ export const RifleFired = defineEvent<{ gun: string; from: { x: number; y: number }; to: { x: number; y: number }; hit: string }>('gun.rifle-fired');
11
+ export const KnifeSwung = defineEvent<{ fighter: string; x: number; y: number; dir: { x: number; y: number }; hits: number }>('knife.swung');
12
+ export const WeaponSwapped = defineEvent<{ gun: string; weapon: string }>('gun.swapped');
13
+ export const BulletImpact = defineEvent<{ x: number; y: number }>('bullet.impact');
14
+ export const RocketFired = defineEvent<{ gun: string; rocket: string; dir: { x: number; y: number } }>('gun.rocket-fired');
15
+ export const RocketExploded = defineEvent<{ rocket: string; owner: string; x: number; y: number; radius: number; tiles: number; hits: number }>('rocket.exploded');
@@ -0,0 +1,46 @@
1
+ /** Monta a arena a partir do mapa: chão e plataformas viram um Tilemap; câmera e HUD são locais de cada jogador. */
2
+ import type { GridMap, SceneSetupContext } from '@vibe-engine/core';
3
+ import type { RoomParams } from '@vibe-engine/net';
4
+ import ArenaRoom from '../rooms/arena.room.ts';
5
+ import { Camera2D, Tilemap, Transform2D, autotile, cellCenter, edges, standingY, tilemapFromGrid } from '@vibe-engine/2d';
6
+ import { Arena, Connection } from '../components/gun.component.ts';
7
+ import { hud, waiting } from '../ui/hud.ui.ts';
8
+
9
+ export const TILE = 18;
10
+ export const FIGHTER_HEIGHT = 24;
11
+
12
+ /** Pontos de nascimento, em ordem de leitura do mapa. O jogador pN nasce no ponto (N-1) % total. */
13
+ export function spawnPoints(map: GridMap): Array<{ x: number; y: number }> {
14
+ return map.cells('spawn').map((c) => ({ x: cellCenter(c, TILE).x, y: standingY(c, TILE, FIGHTER_HEIGHT) }));
15
+ }
16
+
17
+ export function buildArena({ spawn, params }: SceneSetupContext, map: GridMap): void {
18
+ // Regras da sala (sem sala, como em `vibe run` e nos testes: os defaults).
19
+ const room = params as RoomParams<ReturnType<typeof ArenaRoom.resolveRules>> | undefined;
20
+ const rules = room?.rules ?? ArenaRoom.resolveRules();
21
+ spawn('arena-map', [Transform2D({ x: 0, y: 0 }), Tilemap(tilemapFromGrid(map, {
22
+ tileset: 'sprites/tiles',
23
+ tileWidth: TILE,
24
+ layers: {
25
+ ground: {
26
+ match: 'ground', collides: true,
27
+ tiles: autotile({
28
+ alone: { single: 0, left: 1, mid: 2, right: 3 },
29
+ top: { single: 20, left: 21, mid: 22, right: 23 },
30
+ middle: { single: 120, left: 121, mid: 122, right: 123 },
31
+ bottom: { single: 140, left: 141, mid: 142, right: 143 },
32
+ }),
33
+ },
34
+ planks: { match: 'plank', collides: true, tiles: edges({ single: 47, left: 48, mid: 49, right: 50 }) },
35
+ // Borda e fundo: `destroyTiles` (bazuca) não remove esta camada.
36
+ bedrock: { match: 'bedrock', collides: true, indestructible: true, tiles: 29 },
37
+ },
38
+ }))]);
39
+ const size = { width: map.width * TILE, height: map.height * TILE };
40
+ spawn('arena', [Arena({ ...size, room: room?.room.name ?? '', killLimit: rules.killLimit, respawnTicks: Math.round(rules.respawnSeconds * 60), gravityScale: rules.lowGravity ? 0.5 : 1 })]);
41
+ // Local (net: 'local'): cada cliente tem a sua; o system camera.follow-local aponta para o próprio lutador.
42
+ spawn('camera', [Camera2D({ zoom: 2, deadzone: { x: 16, y: 24 }, smoothing: 0.12, lookahead: { x: 24, y: 0 }, bounds: { x: 0, y: 0, ...size } })]);
43
+ spawn('connection', [Connection()]);
44
+ spawn('hud', hud());
45
+ spawn('waiting', waiting());
46
+ }
@@ -0,0 +1,71 @@
1
+ import { defineListener, type World } from '@vibe-engine/core';
2
+ import { CameraShake, ParticleBurst, TilesDestroyed, Transform2D } from '@vibe-engine/2d';
3
+ import { TILE } from '../level/build.ts';
4
+ import { BulletImpact, FighterHit, FighterJumped, FighterKilled, FighterLanded, FighterRespawned, KnifeSwung, RifleFired, RocketExploded, RocketFired, ShotFired, WeaponSwapped } from '../events/combat.events.ts';
5
+
6
+ const pos = (world: World, id: string) => (world.exists(id) ? world.entity(id).read(Transform2D) : null);
7
+ /** Tremor só para quem está envolvido: o seu tiro, você levando ou dando dano. */
8
+ const mine = (world: World, ...ids: string[]) => ids.some((id) => id === `fighter-${world.localPlayer}` || id === `gun-${world.localPlayer}` || id === world.localPlayer);
9
+
10
+ /** Som (posicional: `at`), partículas, tremor e hit-stop. As regras só emitem eventos; o feedback é decidido aqui. */
11
+ export const Effects = defineListener('arena.effects', (on) => {
12
+ on(FighterJumped, (e, { world, audio, random, emit }) => {
13
+ audio.play('audio/jump', { volume: 0.5, pitch: 0.95 + random.float() * 0.1, at: e.fighter });
14
+ const p = pos(world, e.fighter);
15
+ if (p) emit(ParticleBurst, { x: p.x, y: p.y + 12, preset: 'dust' });
16
+ });
17
+ on(FighterLanded, (e, { world, emit }) => {
18
+ const p = pos(world, e.fighter);
19
+ if (p) emit(ParticleBurst, { x: p.x, y: p.y + 12, preset: 'dust', config: { count: e.airTicks > 40 ? 12 : 6 } });
20
+ });
21
+ on(ShotFired, (e, { world, audio, random, emit }) => {
22
+ audio.play('audio/shoot', { volume: 0.4, pitch: 0.9 + random.float() * 0.2, at: e.gun });
23
+ const g = pos(world, e.gun);
24
+ if (g) emit(ParticleBurst, { x: g.x + e.dir.x * 10, y: g.y + e.dir.y * 10, preset: 'sparks', config: { count: 4, angle: [-25, 25], speed: [60, 120], gravity: 0 }, angle: (Math.atan2(e.dir.y, e.dir.x) * 180) / Math.PI });
25
+ if (mine(world, e.gun)) emit(CameraShake, { amount: 0.6, seconds: 0.06 });
26
+ });
27
+ on(RifleFired, (e, { world, audio, emit }) => {
28
+ audio.play('audio/shoot', { volume: 0.55, pitch: 0.6, at: e.from });
29
+ const deg = (Math.atan2(e.to.y - e.from.y, e.to.x - e.from.x) * 180) / Math.PI;
30
+ emit(ParticleBurst, { x: e.from.x, y: e.from.y, preset: 'sparks', config: { count: 6, angle: [-15, 15], speed: [80, 160], gravity: 0 }, angle: deg });
31
+ if (!e.hit.startsWith('fighter-')) emit(ParticleBurst, { x: e.to.x, y: e.to.y, preset: 'sparks', config: { count: 6 } });
32
+ if (mine(world, e.gun)) emit(CameraShake, { amount: 1.5, seconds: 0.1 });
33
+ });
34
+ on(KnifeSwung, (e, { audio, emit }) => {
35
+ audio.play('audio/jump', { volume: 0.35, pitch: 1.8, at: { x: e.x, y: e.y } }); // shortcut: assobio do golpe com o som do pulo até ter um som próprio
36
+ emit(ParticleBurst, { x: e.x, y: e.y, preset: 'dust', config: { count: 5, angle: [-40, 40], speed: [40, 90], gravity: 0 }, angle: (Math.atan2(e.dir.y, e.dir.x) * 180) / Math.PI });
37
+ });
38
+ on(WeaponSwapped, (e, { audio }) => audio.play('audio/jump', { volume: 0.25, pitch: 0.7, at: e.gun }));
39
+ on(FighterHit, (e, { world, audio, emit, hitStop }) => {
40
+ audio.play('audio/enemy-hit', { volume: 0.6, at: e.fighter });
41
+ const p = pos(world, e.fighter);
42
+ if (p) emit(ParticleBurst, { x: p.x, y: p.y + 4, preset: 'sparks' });
43
+ if (mine(world, e.fighter, e.by)) { emit(CameraShake, { amount: 2, seconds: 0.12 }); hitStop(2); }
44
+ });
45
+ on(FighterKilled, (e, { world, audio, emit }) => {
46
+ audio.play('audio/enemy-defeat', { volume: 0.8, at: { x: e.x, y: e.y } });
47
+ emit(ParticleBurst, { x: e.x, y: e.y + 4, preset: 'explosion' });
48
+ if (mine(world, e.fighter, e.by)) emit(CameraShake, { amount: 3.5, seconds: 0.3 });
49
+ });
50
+ on(FighterRespawned, (e, { world, emit }) => { const p = pos(world, e.fighter); if (p) emit(ParticleBurst, { x: p.x, y: p.y, preset: 'smoke' }); });
51
+ on(RocketFired, (e, { world, audio, emit }) => {
52
+ audio.play('audio/shoot', { volume: 0.6, pitch: 0.45, at: e.gun });
53
+ const g = pos(world, e.gun);
54
+ if (g) emit(ParticleBurst, { x: g.x - e.dir.x * 8, y: g.y - e.dir.y * 8, preset: 'smoke' });
55
+ if (mine(world, e.gun)) emit(CameraShake, { amount: 1.5, seconds: 0.1 });
56
+ });
57
+ on(RocketExploded, (e, { world, audio, emit }) => {
58
+ audio.play('audio/enemy-defeat', { volume: 0.9, pitch: 0.6, at: { x: e.x, y: e.y } }); // shortcut: estrondo com o som de derrota grave até ter um som próprio
59
+ emit(ParticleBurst, { x: e.x, y: e.y, preset: 'explosion', config: { count: 30, speed: [60, 200] } });
60
+ emit(ParticleBurst, { x: e.x, y: e.y, preset: 'smoke', config: { count: 4 } });
61
+ const me = pos(world, `fighter-${world.localPlayer}`);
62
+ if (me && Math.hypot(me.x - e.x, me.y - e.y) < 160) emit(CameraShake, { amount: 3, seconds: 0.25 });
63
+ });
64
+ // Terra voando de cada tile que a explosão arrancou (cor do chão, para cima).
65
+ on(TilesDestroyed, (e, { world, emit }) => {
66
+ const map = pos(world, e.map);
67
+ if (!map) return;
68
+ for (const c of e.cells) emit(ParticleBurst, { x: map.x + (c.x + 0.5) * TILE, y: map.y + (c.y + 0.5) * TILE, preset: 'dust', config: { count: 3, color: ['#b0764a', '#6b4a32'], speed: [40, 110], gravity: 260 } });
69
+ });
70
+ on(BulletImpact, (e, { emit }) => emit(ParticleBurst, { x: e.x, y: e.y, preset: 'sparks', config: { count: 6 } }));
71
+ });
@@ -0,0 +1,32 @@
1
+ import { defineListener } from '@vibe-engine/core';
2
+ import { Collider2D, Label2D, RigidBody2D, Sprite, Transform2D } from '@vibe-engine/2d';
3
+ import { NetPlayerJoined, NetPlayerLeft } from '@vibe-engine/net';
4
+ import { COLORS, Fighter } from '../components/fighter.component.ts';
5
+ import { Arena, Gun } from '../components/gun.component.ts';
6
+ import { spawnPoints } from '../level/build.ts';
7
+ import map from '../maps/arena.map.ts';
8
+
9
+ /** Entrou: ganha lutador + arma num ponto de nascimento, uma cor e o nome do perfil acima da cabeça. Saiu: some. (Roda no servidor; o cliente vê pelo snapshot.) */
10
+ export const Players = defineListener('arena.players', (on) => {
11
+ on(NetPlayerJoined, ({ player, profile }, { world }) => {
12
+ const n = Number(player.slice(1)) - 1 || 0;
13
+ const points = spawnPoints(map);
14
+ const at = points[n % points.length]!;
15
+ const color = COLORS[n % COLORS.length]!;
16
+ // O servidor já validou e limpou o nome (arena.room.ts). Sem nome: a cor (com número quando a cor se repete, do 5º jogador em diante).
17
+ const name = (profile?.name as string | undefined) || (n < COLORS.length ? color : `${color} ${Math.floor(n / COLORS.length) + 1}`);
18
+ world.spawn(`fighter-${player}`, [
19
+ Transform2D(at),
20
+ Sprite({ asset: 'sprites/characters', animation: `${color}-idle`, layer: 3 }),
21
+ RigidBody2D({ ccd: true, lockRotation: true, gravityScale: world.entity('arena').read(Arena).gravityScale }),
22
+ Collider2D.box({ width: 14, height: 18, offset: { x: 0, y: 3 }, friction: 0 }),
23
+ Fighter({ owner: player, color, name, spawn: at, invulnerable: 90 }),
24
+ Label2D({ text: name, offset: { x: 0, y: -13 }, size: 16, background: '#f4f4f2b3', owner: player }), // o próprio sai com as cores trocadas
25
+ ]);
26
+ world.spawn(`gun-${player}`, [Transform2D(at), Sprite({ asset: 'sprites/pistol', layer: 4, anchor: { x: 0.25, y: 0.5 } }), Gun({ owner: player })]);
27
+ });
28
+ on(NetPlayerLeft, ({ player }, { world }) => {
29
+ if (world.exists(`fighter-${player}`)) world.despawn(`fighter-${player}`);
30
+ if (world.exists(`gun-${player}`)) world.despawn(`gun-${player}`);
31
+ });
32
+ });
@@ -0,0 +1,26 @@
1
+ import { defineMap } from '@vibe-engine/core';
2
+
3
+ /** A arena. `S` = ponto de nascimento (um por jogador, em ordem de entrada); `%` = rocha (a bazuca não destrói). `vibe map show arena`. */
4
+ export default defineMap('arena', {
5
+ legend: { '#': 'ground', '=': 'plank', '%': 'bedrock', S: 'spawn' },
6
+ needsBelow: { S: ['ground', 'plank', 'bedrock'] },
7
+ // prettier-ignore
8
+ rows: [
9
+ '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%',
10
+ '%........................................%',
11
+ '%........................................%',
12
+ '%....S..............................S....%',
13
+ '%..======........................======..%',
14
+ '%..................S.....................%',
15
+ '%..............==========................%',
16
+ '%........................................%',
17
+ '%......====....................====......%',
18
+ '%........................................%',
19
+ '%...................S....................%',
20
+ '%.................======.................%',
21
+ '%..S..................................S..%',
22
+ '%######.......####......####.......######%',
23
+ '%######.......####......####.......######%',
24
+ '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%',
25
+ ],
26
+ });
@@ -0,0 +1,22 @@
1
+ import { t } from '@vibe-engine/core';
2
+ import { defineRoom } from '@vibe-engine/net';
3
+
4
+ /**
5
+ * A sala da arena: até 6 jogadores (um ponto de nascimento `S` por vaga no mapa). As regras são escolhidas ao criar a sala (o lobby
6
+ * mostra e oferece presets) e chegam à cena em `params.rules`, iguais no servidor e no cliente.
7
+ * O perfil (nome digitado no lobby) chega validado em `NetPlayerJoined`.
8
+ */
9
+ export default defineRoom('arena', {
10
+ scene: 'arena',
11
+ maxPlayers: 6,
12
+ open: 3, // três salas sempre abertas na lista (mais salas são criadas pelo lobby e fecham vazias)
13
+ name: 'Arena',
14
+ rules: {
15
+ killLimit: t.int({ default: 10, min: 1, max: 50, doc: 'abates para vencer a partida' }),
16
+ respawnSeconds: t.number({ default: 2, min: 0.5, max: 10, unit: 's' }),
17
+ lowGravity: t.boolean({ doc: 'metade da gravidade: pulos longos' }),
18
+ },
19
+ profile: {
20
+ name: t.string({ maxLength: 16, doc: 'vazio = o nome da cor do lutador' }),
21
+ },
22
+ });
@@ -0,0 +1,56 @@
1
+ /** Dano, morte e explosão, usados pela bala, pelo rifle, pela faca e pela bazuca (rodam igual no servidor e na predição do cliente). */
2
+ import type { EntityRef, EventDef, World } from '@vibe-engine/core';
3
+ import { RigidBody2D, Sprite, Transform2D, destroyTiles, overlap } from '@vibe-engine/2d';
4
+ import { Fighter } from '../components/fighter.component.ts';
5
+ import { Arena, Rocket } from '../components/gun.component.ts';
6
+ import { FighterHit, FighterKilled, RocketExploded } from '../events/combat.events.ts';
7
+
8
+ type Emit = <P>(event: EventDef<P>, payload: P) => void;
9
+
10
+ /** Dano num lutador (bala, rifle, faca): vida, knockback para o lado `dirX`, morte e placar. Falso se não valeu (morto, escudo, o próprio). */
11
+ export function hurt(world: World, target: EntityRef, by: string, damage: number, dirX: number, emit: Emit): boolean {
12
+ const f = target.write(Fighter);
13
+ if (f.owner === by || f.respawn > 0 || f.invulnerable > 0) return false;
14
+ f.hp = Math.max(0, f.hp - damage);
15
+ f.lastHitBy = by;
16
+ target.write(RigidBody2D).velocity = { x: Math.sign(dirX || 1) * 160, y: -140 };
17
+ f.stun = 8;
18
+ emit(FighterHit, { fighter: target.id, by, hpLeft: f.hp });
19
+ if (f.hp === 0) kill(world, target, by, emit);
20
+ return true;
21
+ }
22
+
23
+ export function kill(world: World, e: EntityRef, by: string, emit: Emit) {
24
+ const f = e.write(Fighter);
25
+ const arena = world.entity('arena').read(Arena);
26
+ const at = e.read(Transform2D);
27
+ emit(FighterKilled, { fighter: e.id, by, x: at.x, y: at.y });
28
+ f.hp = 0;
29
+ f.deaths++;
30
+ f.respawn = arena.respawnTicks;
31
+ if (by && world.exists(`fighter-${by}`) && by !== f.owner) world.entity(`fighter-${by}`).write(Fighter).kills++;
32
+ // Morto: fora do mapa, sem gravidade, invisível (as balas o ignoram pelo `respawn`).
33
+ const t = e.write(Transform2D);
34
+ t.x = f.spawn.x;
35
+ t.y = -200;
36
+ const body = e.write(RigidBody2D);
37
+ body.velocity = { x: 0, y: 0 };
38
+ body.gravityScale = 0;
39
+ e.write(Sprite).alpha = 0;
40
+ }
41
+
42
+ /**
43
+ * O foguete explode onde está: abre um buraco no cenário (a rocha fica) e fere quem estiver no raio.
44
+ * `overlap` sem `by`: ninguém mira uma explosão, então não há lag compensation. Os tiles saem antes,
45
+ * então a parede que a explosão derrubou não protege ninguém.
46
+ */
47
+ export function explode(world: World, rocket: EntityRef, emit: Emit): void {
48
+ const r = rocket.read(Rocket);
49
+ const at = rocket.read(Transform2D);
50
+ const tiles = destroyTiles(world.entity('arena-map'), { x: at.x, y: at.y, radius: r.radius }, emit);
51
+ const hits = overlap(world, { at, radius: r.radius, filter: (e) => e.has(Fighter) && e.read(Fighter).respawn === 0 });
52
+ let landed = 0;
53
+ for (const h of hits) if (hurt(world, world.entity(h.entity), r.owner, r.damage, world.entity(h.entity).read(Transform2D).x - at.x, emit)) landed++;
54
+ emit(RocketExploded, { rocket: rocket.id, owner: r.owner, x: at.x, y: at.y, radius: r.radius, tiles: tiles.length, hits: landed });
55
+ world.despawn(rocket.id);
56
+ }
@@ -0,0 +1,9 @@
1
+ import { defineSave, t } from '@vibe-engine/core';
2
+
3
+ /** O jogador neste browser: o nome digitado no lobby volta preenchido na próxima visita. */
4
+ export const PlayerSave = defineSave('player', {
5
+ version: 1,
6
+ schema: {
7
+ name: t.string({ maxLength: 16, doc: 'nome mostrado acima do lutador e no placar' }),
8
+ },
9
+ });
@@ -0,0 +1,15 @@
1
+ import { defineScene } from '@vibe-engine/core';
2
+ import map from '../maps/arena.map.ts';
3
+ import { buildArena } from '../level/build.ts';
4
+ import { FighterController } from '../systems/fighter-controller.system.ts';
5
+ import { BulletLifetime, GunControl, RocketLifetime, TracerFade } from '../systems/gun.system.ts';
6
+ import { Combat, MatchRules, Respawn } from '../systems/combat.system.ts';
7
+ import { ConnectionStatus, LocalView } from '../systems/view.system.ts';
8
+ import { Players } from '../listeners/players.listener.ts';
9
+ import { Effects } from '../listeners/effects.listener.ts';
10
+
11
+ export default defineScene({
12
+ systems: [FighterController, GunControl, BulletLifetime, RocketLifetime, TracerFade, Combat, Respawn, MatchRules, LocalView],
13
+ listeners: [Players, Effects, ConnectionStatus],
14
+ setup: (ctx) => buildArena(ctx, map),
15
+ });
@@ -0,0 +1,11 @@
1
+ import { defineScene } from '@vibe-engine/core';
2
+ import { LobbyActions, LobbyRefresh, LobbyRooms } from '../systems/lobby.system.ts';
3
+ import { lobbyPanel } from '../ui/lobby.ui.ts';
4
+ import { PlayerSave } from '../saves/player.save.ts';
5
+
6
+ /** Cena inicial no browser: local (não vai para a rede). Escolher uma sala abre a cena `arena` com as regras dela; o nome vai junto como perfil. */
7
+ export default defineScene({
8
+ systems: [LobbyRefresh, LobbyActions],
9
+ listeners: [LobbyRooms],
10
+ setup({ spawn, saves }) { spawn('lobby', lobbyPanel({ name: saves.load(PlayerSave).name })); },
11
+ });
@@ -0,0 +1,95 @@
1
+ import { defineSystem } from '@vibe-engine/core';
2
+ import { RigidBody2D, Sprite, Tilemap, Transform2D, TriggerEnter, pairWith } from '@vibe-engine/2d';
3
+ import { Fighter } from '../components/fighter.component.ts';
4
+ import { Arena, Bullet, Rocket } from '../components/gun.component.ts';
5
+ import { BulletImpact, FighterRespawned, MatchOver } from '../events/combat.events.ts';
6
+ import { explode, hurt, kill } from '../rules/damage.ts';
7
+
8
+ const SPAWN_SHIELD = 90;
9
+
10
+ /** Bala × lutador (dano, knockback, morte, placar), bala × cenário e foguete × qualquer um dos dois (explosão). Autoritativo no servidor; o cliente prevê e é corrigido. */
11
+ export const Combat = defineSystem('combat.hits', {
12
+ stage: 'postPhysics',
13
+ reads: [TriggerEnter],
14
+ update({ world, events, emit }) {
15
+ const exploded = new Set<string>(); // despawn só vale no fim do stage: um foguete que toca duas coisas no mesmo tick explode uma vez
16
+ for (const hit of events.read(TriggerEnter)) {
17
+ const blast = pairWith(world, hit, Rocket);
18
+ if (blast) {
19
+ const [rocket, target] = blast;
20
+ if (exploded.has(rocket.id)) continue;
21
+ const f = target.has(Fighter) ? target.read(Fighter) : null;
22
+ // Explode no cenário ou num lutador vivo que não seja quem atirou (a saída do cano não conta).
23
+ if (target.has(Tilemap) || (f && f.owner !== rocket.read(Rocket).owner && f.respawn === 0)) { exploded.add(rocket.id); explode(world, rocket, emit); }
24
+ continue;
25
+ }
26
+ const shot = pairWith(world, hit, Bullet);
27
+ if (!shot) continue;
28
+ const [bullet, target] = shot;
29
+ if (!world.exists(bullet.id) || !world.exists(target.id)) continue;
30
+ const b = bullet.read(Bullet);
31
+ if (target.has(Tilemap)) {
32
+ const at = bullet.read(Transform2D);
33
+ emit(BulletImpact, { x: at.x, y: at.y });
34
+ world.despawn(bullet.id);
35
+ continue;
36
+ }
37
+ if (!target.has(Fighter)) continue;
38
+ const f = target.read(Fighter);
39
+ if (f.owner === b.owner || f.respawn > 0) continue; // a própria bala e quem já morreu
40
+ hurt(world, target, b.owner, b.damage, bullet.read(RigidBody2D).velocity.x, emit);
41
+ world.despawn(bullet.id);
42
+ }
43
+ },
44
+ });
45
+
46
+ /** Cair do mapa mata (crédito para quem acertou por último); morto renasce depois de 2 s com escudo. */
47
+ export const Respawn = defineSystem('fighter.respawn', {
48
+ stage: 'postPhysics',
49
+ after: ['combat.hits'],
50
+ query: [Fighter, Transform2D, RigidBody2D, Sprite],
51
+ update({ entities, world, emit }) {
52
+ const arena = world.entity('arena').read(Arena);
53
+ for (const e of entities) {
54
+ const f = e.write(Fighter);
55
+ if (f.respawn === 0 && e.read(Transform2D).y > arena.height + 48) kill(world, e, f.lastHitBy, emit);
56
+ if (f.respawn > 0) {
57
+ if (--f.respawn > 0) continue;
58
+ const t = e.write(Transform2D);
59
+ t.x = f.spawn.x;
60
+ t.y = f.spawn.y;
61
+ e.write(RigidBody2D).gravityScale = arena.gravityScale;
62
+ f.hp = f.maxHp;
63
+ f.lastHitBy = '';
64
+ f.invulnerable = SPAWN_SHIELD;
65
+ emit(FighterRespawned, { fighter: e.id });
66
+ }
67
+ if (f.invulnerable > 0) f.invulnerable--;
68
+ e.write(Sprite).alpha = f.respawn > 0 ? 0 : f.invulnerable > 0 && Math.floor(f.invulnerable / 5) % 2 === 0 ? 0.4 : 1;
69
+ }
70
+ },
71
+ });
72
+
73
+ /** Fim de partida: alguém chegou ao limite de abates → mostra o vencedor por 4 s e começa outra (placar zerado, todos renascem). */
74
+ export const MatchRules = defineSystem('match.rules', {
75
+ stage: 'postPhysics',
76
+ after: ['fighter.respawn'],
77
+ update({ world, emit }) {
78
+ const arena = world.entity('arena').write(Arena);
79
+ const fighters = world.query(Fighter);
80
+ if (arena.status === 'playing') {
81
+ const best = fighters.find((e) => e.read(Fighter).kills >= arena.killLimit);
82
+ if (best) { arena.status = 'over'; arena.winner = best.read(Fighter).owner; arena.resetIn = 240; emit(MatchOver, { winner: arena.winner }); }
83
+ return;
84
+ }
85
+ if (--arena.resetIn > 0) return;
86
+ arena.status = 'playing';
87
+ arena.winner = '';
88
+ for (const e of fighters) {
89
+ const f = e.write(Fighter);
90
+ f.kills = 0;
91
+ f.deaths = 0;
92
+ f.respawn = 1; // renasce no próximo tick, no ponto de nascimento
93
+ }
94
+ },
95
+ });
@@ -0,0 +1,54 @@
1
+ import { defineSystem } from '@vibe-engine/core';
2
+ import { Grounded, RigidBody2D, Sprite, Transform2D } from '@vibe-engine/2d';
3
+ import { Fighter } from '../components/fighter.component.ts';
4
+ import { FighterJumped, FighterLanded } from '../events/combat.events.ts';
5
+
6
+ /**
7
+ * Input de cada jogador (`inputOf(owner)`) → velocidade, com o game feel do
8
+ * platformer: aceleração, coyote time, jump buffer, pulo variável e queda pesada.
9
+ * Roda igual no servidor e na predição do cliente.
10
+ */
11
+ export const FighterController = defineSystem('fighter.controller', {
12
+ query: [Fighter, RigidBody2D, Sprite, Transform2D],
13
+ optional: [Grounded],
14
+ update({ entities, inputOf, emit, time }) {
15
+ for (const e of entities) {
16
+ const f = e.write(Fighter);
17
+ if (f.respawn > 0) continue;
18
+ const input = inputOf(f.owner);
19
+ const body = e.write(RigidBody2D);
20
+ const grounded = e.has(Grounded);
21
+ if (f.stun > 0) f.stun--;
22
+ const step = (grounded ? f.accel : f.airAccel) * time.dt;
23
+ if (f.stun === 0) body.velocity.x += Math.max(-step, Math.min(step, input.axis('move') * f.speed - body.velocity.x));
24
+
25
+ f.coyote = grounded ? f.coyoteTicks : Math.max(0, f.coyote - 1);
26
+ f.buffer = input.pressed('jump') ? f.bufferTicks : Math.max(0, f.buffer - 1);
27
+ let jumped = false;
28
+ if (f.buffer > 0 && f.coyote > 0) {
29
+ jumped = true;
30
+ body.velocity.y = -f.jump;
31
+ f.buffer = 0;
32
+ f.coyote = 0;
33
+ emit(FighterJumped, { fighter: e.id });
34
+ }
35
+ if (input.released('jump') && body.velocity.y < 0) body.velocity.y *= f.jumpCut;
36
+ if (body.velocity.y > 0) body.velocity.y = Math.min(f.maxFall, body.velocity.y + f.fallGravity * time.dt);
37
+
38
+ // Squash & stretch e pouso.
39
+ const t = e.write(Transform2D);
40
+ if (grounded) {
41
+ if (f.airTicks > 8) { t.scaleX = 1.25; t.scaleY = 0.78; emit(FighterLanded, { fighter: e.id, airTicks: f.airTicks }); }
42
+ f.airTicks = 0;
43
+ } else f.airTicks++;
44
+ if (jumped) { t.scaleX = 0.78; t.scaleY = 1.25; }
45
+ t.scaleX += (1 - t.scaleX) * 0.22;
46
+ t.scaleY += (1 - t.scaleY) * 0.22;
47
+ if (Math.abs(t.scaleX - 1) < 0.01) t.scaleX = 1;
48
+ if (Math.abs(t.scaleY - 1) < 0.01) t.scaleY = 1;
49
+
50
+ const walking = Math.abs(body.velocity.x) > 10 && grounded;
51
+ e.write(Sprite).animation = `${f.color}-${!grounded ? 'jump' : walking ? 'walk' : 'idle'}`;
52
+ }
53
+ },
54
+ });
@@ -0,0 +1,147 @@
1
+ import { defineSystem, type EntityRef } from '@vibe-engine/core';
2
+ import { Collider2D, Grounded, RigidBody2D, Sprite, Transform2D, overlap, raycast } from '@vibe-engine/2d';
3
+ import { Fighter } from '../components/fighter.component.ts';
4
+ import { Arena, Bullet, Gun, Rocket, Tracer } from '../components/gun.component.ts';
5
+ import { KnifeSwung, RifleFired, RocketFired, ShotFired, WeaponSwapped } from '../events/combat.events.ts';
6
+ import { explode, hurt } from '../rules/damage.ts';
7
+
8
+ const NEXT_WEAPON = { pistol: 'rifle', rifle: 'bazooka', bazooka: 'pistol' } as const;
9
+ const KNIFE = { radius: 20, angle: 1.1, damage: 2, cooldown: 24 };
10
+ /** Só lutadores vivos são alvo (morto fica escondido fora do mapa). */
11
+ const alive = (e: EntityRef) => e.has(Fighter) && e.read(Fighter).respawn === 0;
12
+
13
+ /**
14
+ * Mira, troca de arma, tiro e faca de cada jogador. Ids das balas e dos traços são
15
+ * `<tipo>-<player>-<n>`: o que o cliente prevê é o mesmo que o servidor cria.
16
+ * Rifle e faca passam `by: gun.owner`: no multiplayer, vale o que esse jogador viu
17
+ * na tela dele (lag compensation da engine), dentro dos limites do servidor.
18
+ */
19
+ export const GunControl = defineSystem('gun.control', {
20
+ after: ['fighter.controller'],
21
+ query: [Gun, Transform2D, Sprite],
22
+ update({ entities, world, inputOf, emit }) {
23
+ const playing = world.entity('arena').read(Arena).status === 'playing';
24
+ for (const g of entities) {
25
+ const gun = g.write(Gun);
26
+ const fighterId = `fighter-${gun.owner}`;
27
+ if (!world.exists(fighterId)) continue;
28
+ const owner = world.entity(fighterId);
29
+ const f = owner.read(Fighter);
30
+ const input = inputOf(gun.owner);
31
+ g.write(Sprite).alpha = f.respawn > 0 ? 0 : 1;
32
+ const [ax, ay] = input.vector('aim');
33
+ const len = Math.hypot(ax, ay);
34
+ if (len > 0) gun.aim = { x: ax / len, y: ay / len };
35
+ const dir = gun.aim;
36
+ const p = owner.read(Transform2D);
37
+ owner.write(Sprite).flipX = dir.x < 0;
38
+ if (input.pressed('swap')) {
39
+ gun.weapon = NEXT_WEAPON[gun.weapon];
40
+ gun.cooldown = 10;
41
+ emit(WeaponSwapped, { gun: g.id, weapon: gun.weapon });
42
+ }
43
+ const t = g.write(Transform2D);
44
+ gun.kick *= 0.6;
45
+ if (gun.kick < 0.1) gun.kick = 0;
46
+ t.x = p.x + dir.x * (4 - gun.kick);
47
+ t.y = p.y + 5 + dir.y * (4 - gun.kick);
48
+ t.rotation = Math.atan2(dir.y, dir.x);
49
+ t.scaleX = gun.weapon === 'rifle' ? 1.6 : gun.weapon === 'bazooka' ? 1.3 : 1; // shortcut: rifle e bazuca são a pistola esticada até terem arte própria
50
+ t.scaleY = (dir.x < 0 ? -1 : 1) * (gun.weapon === 'bazooka' ? 1.6 : 1);
51
+ if (gun.cooldown > 0) gun.cooldown--;
52
+ if (gun.knifeCooldown > 0) gun.knifeCooldown--;
53
+ if (f.respawn > 0 || !playing) continue;
54
+
55
+ // Faca: arco curto na frente, na direção da mira.
56
+ if (input.pressed('knife') && gun.knifeCooldown === 0) {
57
+ gun.knifeCooldown = KNIFE.cooldown;
58
+ const at = { x: p.x, y: p.y + 3 };
59
+ const hits = overlap(world, { at, radius: KNIFE.radius, dir, angle: KNIFE.angle, by: gun.owner, ignore: [fighterId], filter: alive });
60
+ let landed = 0;
61
+ for (const h of hits) if (hurt(world, world.entity(h.entity), gun.owner, KNIFE.damage, dir.x, emit)) landed++;
62
+ emit(KnifeSwung, { fighter: fighterId, x: at.x + dir.x * 12, y: at.y + dir.y * 12, dir: { x: dir.x, y: dir.y }, hits: landed });
63
+ }
64
+
65
+ if (!input.down('fire') || gun.cooldown > 0) continue;
66
+ gun.shots++;
67
+ const body = owner.write(RigidBody2D);
68
+ const muzzle = { x: t.x + dir.x * 10, y: t.y + dir.y * 10 };
69
+
70
+ if (gun.weapon === 'rifle') {
71
+ gun.cooldown = gun.rifleRate;
72
+ gun.kick = 5;
73
+ body.velocity.x -= dir.x * gun.recoil * 2;
74
+ // Do centro do lutador (encostado na parede não atira através dela).
75
+ const from = { x: p.x, y: t.y };
76
+ const hit = raycast(world, { from, dir, range: gun.rifleRange, by: gun.owner, ignore: [fighterId], filter: (e) => !e.has(Fighter) || alive(e) });
77
+ const to = hit ? hit.point : { x: from.x + dir.x * gun.rifleRange, y: from.y + dir.y * gun.rifleRange };
78
+ if (hit && world.entity(hit.entity).has(Fighter)) hurt(world, world.entity(hit.entity), gun.owner, gun.rifleDamage, dir.x, emit);
79
+ const length = Math.hypot(to.x - muzzle.x, to.y - muzzle.y);
80
+ world.spawn(`tracer-${gun.owner}-${gun.shots}`, [
81
+ Transform2D({ x: muzzle.x, y: muzzle.y, rotation: t.rotation }),
82
+ Sprite({ width: length, height: 1, color: '#fff6c8', anchor: { x: 0, y: 0.5 }, layer: 5 }),
83
+ Tracer(),
84
+ ]);
85
+ emit(RifleFired, { gun: g.id, from: muzzle, to, hit: hit?.entity ?? '' });
86
+ continue;
87
+ }
88
+
89
+ if (gun.weapon === 'bazooka') {
90
+ gun.cooldown = gun.bazookaRate;
91
+ gun.kick = 6;
92
+ body.velocity.x -= dir.x * gun.recoil * 2.5;
93
+ const id = `rocket-${gun.owner}-${gun.shots}`;
94
+ world.spawn(id, [
95
+ Transform2D({ ...muzzle, rotation: t.rotation }),
96
+ Sprite({ width: 8, height: 4, color: '#2a2a2a', layer: 4 }), // shortcut: retângulo até ter arte própria
97
+ RigidBody2D({ type: 'kinematic', velocity: { x: dir.x * gun.rocketSpeed, y: dir.y * gun.rocketSpeed } }),
98
+ Collider2D.circle({ radius: 3, trigger: true }),
99
+ Rocket({ owner: gun.owner }),
100
+ ]);
101
+ emit(RocketFired, { gun: g.id, rocket: id, dir: { x: dir.x, y: dir.y } });
102
+ continue;
103
+ }
104
+
105
+ gun.cooldown = gun.rate;
106
+ gun.kick = 3;
107
+ body.velocity.x -= dir.x * gun.recoil;
108
+ if (!owner.has(Grounded)) body.velocity.y -= dir.y * gun.recoil * 0.6;
109
+ const id = `bullet-${gun.owner}-${gun.shots}`;
110
+ world.spawn(id, [
111
+ Transform2D(muzzle),
112
+ Sprite({ asset: 'sprites/bullet', layer: 4 }),
113
+ RigidBody2D({ type: 'kinematic', velocity: { x: dir.x * gun.bulletSpeed, y: dir.y * gun.bulletSpeed } }),
114
+ Collider2D.circle({ radius: 2, trigger: true }),
115
+ Bullet({ owner: gun.owner }),
116
+ ]);
117
+ emit(ShotFired, { gun: g.id, bullet: id, dir: { x: dir.x, y: dir.y } });
118
+ }
119
+ },
120
+ });
121
+
122
+ export const BulletLifetime = defineSystem('gun.bullet-lifetime', {
123
+ query: [Bullet],
124
+ update({ entities, world }) {
125
+ for (const e of entities) if (--e.write(Bullet).ttl <= 0) world.despawn(e.id);
126
+ },
127
+ });
128
+
129
+ /** Foguete que não acertou nada explode no fim do alcance. */
130
+ export const RocketLifetime = defineSystem('gun.rocket-lifetime', {
131
+ query: [Rocket],
132
+ update({ entities, world, emit }) {
133
+ for (const e of entities) if (--e.write(Rocket).ttl <= 0) explode(world, e, emit);
134
+ },
135
+ });
136
+
137
+ /** O traço do rifle esmaece e some. */
138
+ export const TracerFade = defineSystem('gun.tracer-fade', {
139
+ query: [Tracer, Sprite],
140
+ update({ entities, world }) {
141
+ for (const e of entities) {
142
+ const ttl = --e.write(Tracer).ttl;
143
+ if (ttl <= 0) world.despawn(e.id);
144
+ else e.write(Sprite).alpha = ttl / 8;
145
+ }
146
+ },
147
+ });