diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4adf8d4..dcc1f13 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,7 +7,7 @@ on: jobs: scan_ruby: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - name: Checkout code @@ -25,7 +25,7 @@ jobs: run: bin/bundler-audit scan_js: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - name: Checkout code @@ -40,7 +40,7 @@ jobs: run: bin/importmap audit lint: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 env: RUBOCOP_CACHE_ROOT: tmp/rubocop steps: @@ -66,7 +66,7 @@ jobs: run: bin/rubocop -f github test: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 # services: # redis: @@ -91,7 +91,7 @@ jobs: run: bin/rails db:test:prepare test system-test: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 # services: # redis: diff --git a/Gemfile.lock b/Gemfile.lock index b1d367e..bf77e3a 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,31 +1,31 @@ GEM remote: https://rubygems.org/ specs: - action_text-trix (2.1.15) + action_text-trix (2.1.19) railties - actioncable (8.1.1) - actionpack (= 8.1.1) - activesupport (= 8.1.1) + actioncable (8.1.4.1) + actionpack (= 8.1.4.1) + activesupport (= 8.1.4.1) nio4r (~> 2.0) websocket-driver (>= 0.6.1) zeitwerk (~> 2.6) - actionmailbox (8.1.1) - actionpack (= 8.1.1) - activejob (= 8.1.1) - activerecord (= 8.1.1) - activestorage (= 8.1.1) - activesupport (= 8.1.1) + actionmailbox (8.1.4.1) + actionpack (= 8.1.4.1) + activejob (= 8.1.4.1) + activerecord (= 8.1.4.1) + activestorage (= 8.1.4.1) + activesupport (= 8.1.4.1) mail (>= 2.8.0) - actionmailer (8.1.1) - actionpack (= 8.1.1) - actionview (= 8.1.1) - activejob (= 8.1.1) - activesupport (= 8.1.1) + actionmailer (8.1.4.1) + actionpack (= 8.1.4.1) + actionview (= 8.1.4.1) + activejob (= 8.1.4.1) + activesupport (= 8.1.4.1) mail (>= 2.8.0) rails-dom-testing (~> 2.2) - actionpack (8.1.1) - actionview (= 8.1.1) - activesupport (= 8.1.1) + actionpack (8.1.4.1) + actionview (= 8.1.4.1) + activesupport (= 8.1.4.1) nokogiri (>= 1.8.5) rack (>= 2.2.4) rack-session (>= 1.0.1) @@ -33,36 +33,36 @@ GEM rails-dom-testing (~> 2.2) rails-html-sanitizer (~> 1.6) useragent (~> 0.16) - actiontext (8.1.1) + actiontext (8.1.4.1) action_text-trix (~> 2.1.15) - actionpack (= 8.1.1) - activerecord (= 8.1.1) - activestorage (= 8.1.1) - activesupport (= 8.1.1) + actionpack (= 8.1.4.1) + activerecord (= 8.1.4.1) + activestorage (= 8.1.4.1) + activesupport (= 8.1.4.1) globalid (>= 0.6.0) nokogiri (>= 1.8.5) - actionview (8.1.1) - activesupport (= 8.1.1) + actionview (8.1.4.1) + activesupport (= 8.1.4.1) builder (~> 3.1) erubi (~> 1.11) rails-dom-testing (~> 2.2) - rails-html-sanitizer (~> 1.6) - activejob (8.1.1) - activesupport (= 8.1.1) + rails-html-sanitizer (~> 1.6, >= 1.7.2) + activejob (8.1.4.1) + activesupport (= 8.1.4.1) globalid (>= 0.3.6) - activemodel (8.1.1) - activesupport (= 8.1.1) - activerecord (8.1.1) - activemodel (= 8.1.1) - activesupport (= 8.1.1) + activemodel (8.1.4.1) + activesupport (= 8.1.4.1) + activerecord (8.1.4.1) + activemodel (= 8.1.4.1) + activesupport (= 8.1.4.1) timeout (>= 0.4.0) - activestorage (8.1.1) - actionpack (= 8.1.1) - activejob (= 8.1.1) - activerecord (= 8.1.1) - activesupport (= 8.1.1) + activestorage (8.1.4.1) + actionpack (= 8.1.4.1) + activejob (= 8.1.4.1) + activerecord (= 8.1.4.1) + activesupport (= 8.1.4.1) marcel (~> 1.0) - activesupport (8.1.1) + activesupport (8.1.4.1) base64 bigdecimal concurrent-ruby (~> 1.0, >= 1.3.1) @@ -75,20 +75,20 @@ GEM securerandom (>= 0.3) tzinfo (~> 2.0, >= 2.0.5) uri (>= 0.13.1) - addressable (2.8.7) - public_suffix (>= 2.0.2, < 7.0) + addressable (2.9.2) + public_suffix (>= 2.0.2, < 8.0) ast (2.4.3) base64 (0.3.0) - bcrypt_pbkdf (1.1.1) - bigdecimal (3.3.1) + bcrypt_pbkdf (1.1.2) + bigdecimal (4.1.3) bindex (0.8.1) - bootsnap (1.18.6) - msgpack (~> 1.2) - brakeman (7.1.1) + bootsnap (1.26.1) + msgpack (~> 1.5) + brakeman (8.1.0) racc builder (3.3.0) - bundler-audit (0.9.2) - bundler (>= 1.2.0, < 3) + bundler-audit (0.9.3) + bundler (>= 1.2.0) thor (~> 1.0) capybara (3.40.0) addressable @@ -99,51 +99,52 @@ GEM rack-test (>= 0.6.3) regexp_parser (>= 1.5, < 3.0) xpath (~> 3.2) - concurrent-ruby (1.3.5) - connection_pool (2.5.4) - crass (1.0.6) - date (3.5.0) - debug (1.11.0) + concurrent-ruby (1.3.8) + connection_pool (3.0.2) + crass (1.0.8) + date (3.6.0) + debug (1.11.1) irb (~> 1.10) reline (>= 0.3.8) - dotenv (3.1.8) + dotenv (3.2.0) drb (2.2.3) ed25519 (1.4.0) - erb (6.0.0) + erb (6.0.7) erubi (1.13.1) - et-orbi (1.4.0) + et-orbi (1.4.2) tzinfo - ffi (1.17.2-aarch64-linux-gnu) - ffi (1.17.2-aarch64-linux-musl) - ffi (1.17.2-arm-linux-gnu) - ffi (1.17.2-arm-linux-musl) - ffi (1.17.2-arm64-darwin) - ffi (1.17.2-x86_64-linux-gnu) - ffi (1.17.2-x86_64-linux-musl) - fugit (1.12.1) + ffi (1.17.4-aarch64-linux-gnu) + ffi (1.17.4-aarch64-linux-musl) + ffi (1.17.4-arm-linux-gnu) + ffi (1.17.4-arm-linux-musl) + ffi (1.17.4-arm64-darwin) + ffi (1.17.4-x86_64-linux-gnu) + ffi (1.17.4-x86_64-linux-musl) + fugit (1.14.0) et-orbi (~> 1.4) raabro (~> 1.4) - globalid (1.3.0) + globalid (1.4.0) activesupport (>= 6.1) - i18n (1.14.7) + i18n (1.15.2) concurrent-ruby (~> 1.0) image_processing (1.14.0) mini_magick (>= 4.9.5, < 6) ruby-vips (>= 2.0.17, < 3) - importmap-rails (2.2.2) + importmap-rails (2.2.3) actionpack (>= 6.0.0) activesupport (>= 6.0.0) railties (>= 6.0.0) - io-console (0.8.1) - irb (1.15.3) + io-console (0.9.5) + irb (1.19.0) pp (>= 0.6.0) + prism (>= 1.3.0) rdoc (>= 4.0.0) reline (>= 0.4.2) - jbuilder (2.14.1) + jbuilder (2.15.1) actionview (>= 7.0.0) activesupport (>= 7.0.0) - json (2.16.0) - kamal (2.8.2) + json (3.1.0) + kamal (2.12.0) activesupport (>= 7.0) base64 (~> 0.2) bcrypt_pbkdf (~> 1.0) @@ -154,107 +155,113 @@ GEM sshkit (>= 1.23.0, < 2.0) thor (~> 1.3) zeitwerk (>= 2.6.18, < 3.0) - language_server-protocol (3.17.0.5) + language_server-protocol (3.17.0.6) lint_roller (1.1.0) logger (1.7.0) - loofah (2.24.1) + loofah (2.25.3) crass (~> 1.0.2) - nokogiri (>= 1.12.0) - mail (2.9.0) + nokogiri (>= 1.19.5) + mail (2.9.1) logger mini_mime (>= 0.1.1) net-imap net-pop net-smtp - marcel (1.1.0) + marcel (1.2.1) matrix (0.4.3) - mini_magick (5.3.1) + mini_magick (5.4.0) logger mini_mime (1.1.5) - minitest (5.26.1) - msgpack (1.8.0) - net-imap (0.5.12) + minitest (6.1.0) + drb (~> 2.0) + prism (>= 1.5, < 3) + msgpack (1.8.7) + net-imap (0.6.8) date net-protocol net-pop (0.1.2) net-protocol - net-protocol (0.2.2) + net-protocol (0.4.0) timeout - net-scp (4.1.0) - net-ssh (>= 2.6.5, < 8.0.0) - net-sftp (4.0.0) - net-ssh (>= 5.0.0, < 8.0.0) - net-smtp (0.5.1) + net-scp (4.2.1) + net-ssh (>= 2.6.5, < 9.0.0) + net-sftp (4.1.1) + net-ssh (>= 5.0.0, < 9.0.0) + net-smtp (0.5.2) net-protocol - net-ssh (7.3.0) + net-ssh (7.3.10) + logger nio4r (2.7.5) - nokogiri (1.18.10-aarch64-linux-gnu) + nokogiri (1.19.7-aarch64-linux-gnu) racc (~> 1.4) - nokogiri (1.18.10-aarch64-linux-musl) + nokogiri (1.19.7-aarch64-linux-musl) racc (~> 1.4) - nokogiri (1.18.10-arm-linux-gnu) + nokogiri (1.19.7-arm-linux-gnu) racc (~> 1.4) - nokogiri (1.18.10-arm-linux-musl) + nokogiri (1.19.7-arm-linux-musl) racc (~> 1.4) - nokogiri (1.18.10-arm64-darwin) + nokogiri (1.19.7-arm64-darwin) racc (~> 1.4) - nokogiri (1.18.10-x86_64-linux-gnu) + nokogiri (1.19.7-x86_64-linux-gnu) racc (~> 1.4) - nokogiri (1.18.10-x86_64-linux-musl) + nokogiri (1.19.7-x86_64-linux-musl) racc (~> 1.4) ostruct (0.6.3) - parallel (1.27.0) - parser (3.3.10.0) + parallel (2.3.0) + parser (3.3.13.0) ast (~> 2.4.1) racc - pp (0.6.3) + pp (0.6.4) prettyprint - prettyprint (0.2.0) - prism (1.6.0) - propshaft (1.3.1) + prettyprint (0.2.1) + prism (2.1.0-aarch64-linux-gnu) + prism (2.1.0-aarch64-linux-musl) + prism (2.1.0-arm-linux-gnu) + prism (2.1.0-arm-linux-musl) + prism (2.1.0-arm64-darwin) + prism (2.1.0-x86_64-linux-gnu) + prism (2.1.0-x86_64-linux-musl) + propshaft (1.3.2) actionpack (>= 7.0.0) activesupport (>= 7.0.0) rack - psych (5.2.6) - date - stringio - public_suffix (6.0.2) - puma (7.1.0) + public_suffix (7.0.5) + puma (8.0.2) nio4r (~> 2.0) - raabro (1.4.0) + raabro (1.5.0) racc (1.8.1) - rack (3.2.4) - rack-session (2.1.1) + rack (3.2.8) + rack-session (2.1.2) base64 (>= 0.1.0) rack (>= 3.0.0) - rack-test (2.2.0) + rack-test (2.3.0) rack (>= 1.3) - rackup (2.2.1) + rackup (2.3.1) rack (>= 3) - rails (8.1.1) - actioncable (= 8.1.1) - actionmailbox (= 8.1.1) - actionmailer (= 8.1.1) - actionpack (= 8.1.1) - actiontext (= 8.1.1) - actionview (= 8.1.1) - activejob (= 8.1.1) - activemodel (= 8.1.1) - activerecord (= 8.1.1) - activestorage (= 8.1.1) - activesupport (= 8.1.1) + rails (8.1.4.1) + actioncable (= 8.1.4.1) + actionmailbox (= 8.1.4.1) + actionmailer (= 8.1.4.1) + actionpack (= 8.1.4.1) + actiontext (= 8.1.4.1) + actionview (= 8.1.4.1) + activejob (= 8.1.4.1) + activemodel (= 8.1.4.1) + activerecord (= 8.1.4.1) + activestorage (= 8.1.4.1) + activesupport (= 8.1.4.1) bundler (>= 1.15.0) - railties (= 8.1.1) + railties (= 8.1.4.1) rails-dom-testing (2.3.0) activesupport (>= 5.0.0) minitest nokogiri (>= 1.6) - rails-html-sanitizer (1.6.2) - loofah (~> 2.21) + rails-html-sanitizer (1.7.2) + loofah (~> 2.25, >= 2.25.3) nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0) - railties (8.1.1) - actionpack (= 8.1.1) - activesupport (= 8.1.1) + railties (8.1.4.1) + actionpack (= 8.1.4.1) + activesupport (= 8.1.4.1) irb (~> 1.13) rackup (>= 1.0.0) rake (>= 12.2) @@ -262,56 +269,59 @@ GEM tsort (>= 0.2) zeitwerk (~> 2.6) rainbow (3.1.1) - rake (13.3.1) - rdoc (6.15.1) + rake (13.4.2) + rbs (4.2.0) + logger + prism (>= 1.6.0) + tsort + rdoc (8.1.0) erb - psych (>= 4.0.0) + prism (>= 1.6.0) + rbs (>= 4.0.0) tsort - regexp_parser (2.11.3) - reline (0.6.3) + regexp_parser (2.13.1) + reline (0.7.0) io-console (~> 0.5) - rexml (3.4.4) - rubocop (1.81.7) - json (~> 2.3) + rubocop (1.92.2) + json (>= 2.3) language_server-protocol (~> 3.17.0.2) lint_roller (~> 1.1.0) - parallel (~> 1.10) + parallel (>= 1.10) parser (>= 3.3.0.2) rainbow (>= 2.2.2, < 4.0) - regexp_parser (>= 2.9.3, < 3.0) - rubocop-ast (>= 1.47.1, < 2.0) + regexp_parser (>= 2.11.3, < 3.0) + rubocop-ast (>= 1.49.0, < 2.0) ruby-progressbar (~> 1.7) unicode-display_width (>= 2.4.0, < 4.0) - rubocop-ast (1.48.0) + rubocop-ast (1.51.0) parser (>= 3.3.7.2) - prism (~> 1.4) - rubocop-performance (1.26.1) + prism (>= 1.7) + rubocop-performance (1.27.0) lint_roller (~> 1.1) - rubocop (>= 1.75.0, < 2.0) + rubocop (>= 1.89.0, < 2.0) rubocop-ast (>= 1.47.1, < 2.0) - rubocop-rails (2.33.4) + rubocop-rails (2.38.0) activesupport (>= 4.2.0) lint_roller (~> 1.1) rack (>= 1.1) - rubocop (>= 1.75.0, < 2.0) + rubocop (>= 1.89.0, < 2.0) rubocop-ast (>= 1.44.0, < 2.0) rubocop-rails-omakase (1.1.0) rubocop (>= 1.72) rubocop-performance (>= 1.24) rubocop-rails (>= 2.30) ruby-progressbar (1.13.0) - ruby-vips (2.2.5) + ruby-vips (2.3.0) ffi (~> 1.12) logger - rubyzip (3.2.2) + rubyzip (3.7.0) securerandom (0.4.1) - selenium-webdriver (4.38.0) + selenium-webdriver (4.52.0) base64 (~> 0.2) logger (~> 1.4) - rexml (~> 3.2, >= 3.2.5) rubyzip (>= 1.2.2, < 4.0) websocket (~> 1.0) - solid_cable (3.0.12) + solid_cable (4.1.0) actioncable (>= 7.2) activejob (>= 7.2) activerecord (>= 7.2) @@ -320,21 +330,21 @@ GEM activejob (>= 7.2) activerecord (>= 7.2) railties (>= 7.2) - solid_queue (1.2.4) + solid_queue (1.7.2) activejob (>= 7.1) activerecord (>= 7.1) concurrent-ruby (>= 1.3.1) fugit (~> 1.11) railties (>= 7.1) thor (>= 1.3.1) - sqlite3 (2.8.0-aarch64-linux-gnu) - sqlite3 (2.8.0-aarch64-linux-musl) - sqlite3 (2.8.0-arm-linux-gnu) - sqlite3 (2.8.0-arm-linux-musl) - sqlite3 (2.8.0-arm64-darwin) - sqlite3 (2.8.0-x86_64-linux-gnu) - sqlite3 (2.8.0-x86_64-linux-musl) - sshkit (1.24.0) + sqlite3 (2.10.2-aarch64-linux-gnu) + sqlite3 (2.10.2-aarch64-linux-musl) + sqlite3 (2.10.2-arm-linux-gnu) + sqlite3 (2.10.2-arm-linux-musl) + sqlite3 (2.10.2-arm64-darwin) + sqlite3 (2.10.2-x86_64-linux-gnu) + sqlite3 (2.10.2-x86_64-linux-musl) + sshkit (1.25.1) base64 logger net-scp (>= 1.1.2) @@ -343,37 +353,35 @@ GEM ostruct stimulus-rails (1.3.4) railties (>= 6.0.0) - stringio (3.1.8) - thor (1.4.0) - thruster (0.1.16) - thruster (0.1.16-aarch64-linux) - thruster (0.1.16-arm64-darwin) - thruster (0.1.16-x86_64-linux) - timeout (0.4.4) + thor (1.5.0) + thruster (0.1.27) + thruster (0.1.27-aarch64-linux) + thruster (0.1.27-arm64-darwin) + thruster (0.1.27-x86_64-linux) + timeout (0.6.1) tsort (0.2.0) - turbo-rails (2.0.20) + turbo-rails (2.0.23) actionpack (>= 7.1.0) railties (>= 7.1.0) tzinfo (2.0.6) concurrent-ruby (~> 1.0) - unicode-display_width (3.2.0) - unicode-emoji (~> 4.1) - unicode-emoji (4.1.0) - uri (1.1.1) + unicode-display_width (3.3.0) + unicode-emoji (~> 4.3) + unicode-emoji (4.3.0) + uri (1.1.2) useragent (0.16.11) - web-console (4.2.1) - actionview (>= 6.0.0) - activemodel (>= 6.0.0) + web-console (4.3.0) + actionview (>= 8.0.0) bindex (>= 0.4.0) - railties (>= 6.0.0) + railties (>= 8.0.0) websocket (1.2.11) - websocket-driver (0.8.0) + websocket-driver (0.8.2) base64 websocket-extensions (>= 0.1.0) websocket-extensions (0.1.5) xpath (3.2.0) nokogiri (~> 1.8) - zeitwerk (2.7.3) + zeitwerk (2.8.3) PLATFORMS aarch64-linux diff --git a/README.md b/README.md index fe4aa98..ed4822d 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,14 @@ # Rails Battleship +[![CI](https://github.com/jbutton/rails_battleship/actions/workflows/ci.yml/badge.svg)](https://github.com/jbutton/rails_battleship/actions/workflows/ci.yml) + A real-time, two-player Battleship game built with Rails 8 and Hotwire. Two people open the app, get matched, place their fleets, and take turns firing. Both screens update live over Action Cable, with no page reloads and no custom JavaScript framework. ## How a game works 1. **Pick a name.** No accounts; the player is kept in the session. 2. **Join a game.** Matchmaking either drops you into a waiting game or opens a new one and waits for an opponent. -3. **Place your ships.** Once two players are matched, both get a 10×10 grid and a 10-minute timer to place the standard fleet (Carrier 5, Battleship 4, Cruiser 3, Submarine 3, Destroyer 2). If the timer runs out, a background job places any remaining fleet at random. +3. **Place your ships.** Once two players are matched, both get a 10×10 grid and a 10-minute timer to place the standard fleet (Carrier 5, Battleship 4, Cruiser 3, Submarine 3, Destroyer 2). Press `R` to rotate. If the timer runs out, a background job places any remaining fleet at random. 4. **Battle.** Players alternate shots. Each shot comes back as a miss, hit, or sink and is pushed to both players right away. The game ends when one fleet is fully sunk. ## Technical highlights @@ -17,6 +19,7 @@ A real-time, two-player Battleship game built with Rails 8 and Hotwire. Two peop - **Live updates with Turbo Streams.** Phase changes (matched → placing → playing → game over) and shot results are broadcast to per-player streams, so each player gets their own view of the shared game. - **Timed fallback with Active Job.** `AutoPlaceShipsJob` is scheduled for the placement deadline and starts the game if both boards end up ready. - **Placement validation in two places.** A Stimulus controller previews valid and invalid positions on hover, and the server re-checks length, bounds, overlap, and straight-line contiguity before saving. +- **Access checks.** Only the two players in a game can view it or fire in it, and only a board's owner can place ships on it. - **Rails 8 defaults.** SQLite, Solid Queue, Solid Cable, Solid Cache, Propshaft, importmap, and a Kamal deploy config. No Node, Redis, or Postgres needed. ## Tech stack @@ -30,7 +33,7 @@ A real-time, two-player Battleship game built with Rails 8 and Hotwire. Two peop | Jobs | Active Job (Solid Queue in prod) | | Database | SQLite | | Deploy | Docker + Kamal | -| CI | GitHub Actions: Brakeman, bundler-audit, importmap audit, RuboCop | +| CI | GitHub Actions: Minitest, RuboCop, Brakeman, bundler-audit, importmap audit | ## Domain model @@ -63,6 +66,14 @@ bin/dev # http://localhost:3000 To play against yourself, open the app in two separate browser sessions (for example, a normal window and a private window), enter a different name in each, and click join in both. +## Running the tests + +```bash +bin/rails test +``` + +The suite covers the board rules (placement, shots, sinking, the hidden opponent view), each game service, the auto-placement job, and the HTTP endpoints, including access checks. + ## Project layout ``` @@ -73,10 +84,11 @@ app/ javascript/controllers/ ship_placement, battleship_board, timer (Stimulus) views/games/ one partial per game phase, swapped via Turbo Streams +test/ + models/ services/ jobs/ controllers/ ``` ## Known limitations -- Manual placement is horizontal only. The rotate control isn't wired up yet, though auto-placement uses both orientations. - Players are session-based, so closing the browser loses your identity. -- The test suite is still mostly generator scaffolding and needs real model and service tests. +- There are no browser-level system tests yet; gameplay is covered by model, service and request tests. diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index af67da1..95dbb53 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -14,4 +14,16 @@ def current_player @current_player ||= Player.find_by(id: session[:player_id]) end + + def require_player + redirect_to new_player_path, alert: "Please enter your name first" unless current_player + end + + def find_game_for_current_player(id) + game = Game.find_by(id: id) + return game if game && [ game.player1_id, game.player2_id ].include?(current_player.id) + + redirect_to games_path, alert: "Game not found" + nil + end end diff --git a/app/controllers/boards_controller.rb b/app/controllers/boards_controller.rb index 13710f7..f0342a9 100644 --- a/app/controllers/boards_controller.rb +++ b/app/controllers/boards_controller.rb @@ -3,59 +3,23 @@ class BoardsController < ApplicationController before_action :set_board def update - ships_data = JSON.parse(params[:ships_data]) - result = GamePlay::ShipPlacementService.new( board: @board, - ships_data: ships_data + ships_data: JSON.parse(params.require(:ships_data)) ).call + game = @board.game.reload respond_to do |format| format.turbo_stream do - if result[:success] - # Reload game to get latest state - game = @board.game.reload - - # If game has started, show play screen. Otherwise show waiting screen - if game.in_progress? - render turbo_stream: turbo_stream.replace( - "game-container", - partial: "games/play", - locals: { game: game, player: current_player } - ) - else - render turbo_stream: turbo_stream.replace( - "game-container", - partial: "games/waiting_for_opponent", - locals: { game: game, player: current_player } - ) + if result[:success] || game.in_progress? + streams = [ turbo_stream.replace("game-container", partial: screen_for(game), locals: { game: game, player: current_player }) ] + unless result[:success] + streams << turbo_stream.update("flash-messages", partial: "shared/flash", + locals: { notice: "Ships were placed automatically. Game has started!" }) end + render turbo_stream: streams else - # Even if placement failed, check if the game has started (e.g., due to auto-placement) - game = @board.game.reload - - if game.in_progress? - # Game has started, show play screen instead of error - render turbo_stream: [ - turbo_stream.replace( - "game-container", - partial: "games/play", - locals: { game: game, player: current_player } - ), - turbo_stream.replace( - "flash-messages", - partial: "shared/flash", - locals: { notice: "Ships were placed automatically. Game has started!" } - ) - ] - else - # Show error message - render turbo_stream: turbo_stream.replace( - "flash-messages", - partial: "shared/flash", - locals: { alert: result[:error] } - ) - end + render turbo_stream: turbo_stream.update("flash-messages", partial: "shared/flash", locals: { alert: result[:error] }) end end format.json do @@ -66,19 +30,18 @@ def update end end end + rescue JSON::ParserError + head :bad_request end private def set_board - @board = Board.find(params[:id]) - rescue ActiveRecord::RecordNotFound - redirect_to games_path, alert: "Board not found" + @board = current_player.boards.find_by(id: params[:id]) + redirect_to games_path, alert: "Board not found" unless @board end - def require_player - unless current_player - redirect_to new_player_path, alert: "Please enter your name first" - end + def screen_for(game) + game.in_progress? ? "games/play" : "games/waiting_for_opponent" end end diff --git a/app/controllers/games_controller.rb b/app/controllers/games_controller.rb index 2c27ecc..610a5fb 100644 --- a/app/controllers/games_controller.rb +++ b/app/controllers/games_controller.rb @@ -1,17 +1,15 @@ class GamesController < ApplicationController before_action :require_player - before_action :set_game, only: [ :show, :fire ] + before_action :set_game, only: :show def index - @current_game = current_player.current_game + current_game = current_player.current_game + @current_game = current_game unless current_game&.finished? @player = current_player end def show @player = current_player - @my_board = @game.board_for(@player) - @opponent = @game.opponent_of(@player) - @opponent_board = @game.board_for(@opponent) if @opponent end def join @@ -22,55 +20,13 @@ def join else redirect_to game_path(game), notice: "Searching for opponent..." end - rescue => e + rescue ActiveRecord::ActiveRecordError => e redirect_to games_path, alert: "Error joining game: #{e.message}" end - def fire - result = GamePlay::FireShotService.new( - game: @game, - shooter: current_player, - x: params[:x].to_i, - y: params[:y].to_i - ).call - - respond_to do |format| - format.turbo_stream do - if result[:success] - render turbo_stream: turbo_stream.replace( - "game-container", - partial: "games/play", - locals: { game: @game, player: current_player } - ) - else - render turbo_stream: turbo_stream.replace( - "flash-messages", - partial: "shared/flash", - locals: { alert: result[:error] } - ) - end - end - format.html do - if result[:success] - redirect_to game_path(@game), notice: "Shot fired!" - else - redirect_to game_path(@game), alert: result[:error] - end - end - end - end - private def set_game - @game = Game.find(params[:id]) - rescue ActiveRecord::RecordNotFound - redirect_to games_path, alert: "Game not found" - end - - def require_player - unless current_player - redirect_to new_player_path, alert: "Please enter your name first" - end + @game = find_game_for_current_player(params[:id]) end end diff --git a/app/controllers/shots_controller.rb b/app/controllers/shots_controller.rb index 7d5c9ea..d237030 100644 --- a/app/controllers/shots_controller.rb +++ b/app/controllers/shots_controller.rb @@ -10,50 +10,16 @@ def create y: params[:y].to_i ).call - respond_to do |format| - format.turbo_stream do - if result[:success] - render turbo_stream: [ - turbo_stream.replace( - "game-board", - partial: "games/board", - locals: { game: @game, player: current_player } - ), - turbo_stream.prepend( - "shots-log", - partial: "shots/shot", - locals: { shot: result[:shot] } - ) - ] - else - render turbo_stream: turbo_stream.replace( - "flash-messages", - partial: "shared/flash", - locals: { alert: result[:error] } - ), status: :unprocessable_entity - end - end - format.json do - if result[:success] - render json: { success: true, result: result[:result] }, status: :ok - else - render json: { success: false, error: result[:error] }, status: :unprocessable_entity - end - end + if result[:success] + render json: { success: true, result: result[:result] }, status: :ok + else + render json: { success: false, error: result[:error] }, status: :unprocessable_entity end end private def set_game - @game = Game.find(params[:game_id]) - rescue ActiveRecord::RecordNotFound - redirect_to games_path, alert: "Game not found" - end - - def require_player - unless current_player - redirect_to new_player_path, alert: "Please enter your name first" - end + @game = find_game_for_current_player(params[:game_id]) end end diff --git a/app/helpers/boards_helper.rb b/app/helpers/boards_helper.rb deleted file mode 100644 index 8b8af15..0000000 --- a/app/helpers/boards_helper.rb +++ /dev/null @@ -1,2 +0,0 @@ -module BoardsHelper -end diff --git a/app/helpers/games_helper.rb b/app/helpers/games_helper.rb deleted file mode 100644 index 2ef8c1f..0000000 --- a/app/helpers/games_helper.rb +++ /dev/null @@ -1,2 +0,0 @@ -module GamesHelper -end diff --git a/app/helpers/players_helper.rb b/app/helpers/players_helper.rb deleted file mode 100644 index e8f775c..0000000 --- a/app/helpers/players_helper.rb +++ /dev/null @@ -1,2 +0,0 @@ -module PlayersHelper -end diff --git a/app/helpers/shots_helper.rb b/app/helpers/shots_helper.rb deleted file mode 100644 index 273db17..0000000 --- a/app/helpers/shots_helper.rb +++ /dev/null @@ -1,2 +0,0 @@ -module ShotsHelper -end diff --git a/app/javascript/controllers/battleship_board_controller.js b/app/javascript/controllers/battleship_board_controller.js index 7465260..c4055c6 100644 --- a/app/javascript/controllers/battleship_board_controller.js +++ b/app/javascript/controllers/battleship_board_controller.js @@ -6,10 +6,6 @@ export default class extends Controller { canFire: Boolean } - connect() { - console.log("Battleship board connected", this.gameIdValue, this.canFireValue) - } - async fire(event) { if (!this.canFireValue) { return diff --git a/app/javascript/controllers/hello_controller.js b/app/javascript/controllers/hello_controller.js deleted file mode 100644 index 5975c07..0000000 --- a/app/javascript/controllers/hello_controller.js +++ /dev/null @@ -1,7 +0,0 @@ -import { Controller } from "@hotwired/stimulus" - -export default class extends Controller { - connect() { - this.element.textContent = "Hello World!" - } -} diff --git a/app/javascript/controllers/ship_placement_controller.js b/app/javascript/controllers/ship_placement_controller.js index 4b08efc..915ff7c 100644 --- a/app/javascript/controllers/ship_placement_controller.js +++ b/app/javascript/controllers/ship_placement_controller.js @@ -1,16 +1,33 @@ import { Controller } from "@hotwired/stimulus" +import { Turbo } from "@hotwired/turbo-rails" export default class extends Controller { - static targets = ["grid", "shipInfo", "shipStatus", "submitButton"] + static targets = ["grid", "shipInfo", "shipStatus", "submitButton", "orientationLabel"] static values = { boardId: Number } connect() { this.placedShips = [] this.currentShipIndex = 0 - this.currentOrientation = "horizontal" // or "vertical" + this.currentOrientation = "horizontal" this.gridSize = 10 this.ships = this.getShipsConfig() this.updateCurrentShip() + this.handleKeydown = (event) => { + if (event.key === "r" || event.key === "R") this.rotate() + } + document.addEventListener("keydown", this.handleKeydown) + } + + disconnect() { + document.removeEventListener("keydown", this.handleKeydown) + } + + rotate() { + this.currentOrientation = this.currentOrientation === "horizontal" ? "vertical" : "horizontal" + if (this.hasOrientationLabelTarget) { + this.orientationLabelTarget.textContent = this.currentOrientation === "horizontal" ? "Horizontal" : "Vertical" + } + if (this.lastHoveredCell) this.cellHover({ currentTarget: this.lastHoveredCell }) } getShipsConfig() { @@ -42,6 +59,7 @@ export default class extends Controller { if (this.currentShipIndex >= this.ships.length) return const cell = event.currentTarget + this.lastHoveredCell = cell const x = parseInt(cell.dataset.x) const y = parseInt(cell.dataset.y) const ship = this.ships[this.currentShipIndex] @@ -111,6 +129,9 @@ export default class extends Controller { this.currentShipIndex++ this.updateCurrentShip() + // Refresh the hover preview for the next ship + this.gridTarget.querySelectorAll('.cell').forEach(c => c.classList.remove('hover-valid', 'hover-invalid')) + // Check if all ships placed if (this.currentShipIndex >= this.ships.length) { this.submitButtonTarget.disabled = false @@ -151,20 +172,28 @@ export default class extends Controller { return } - const response = await fetch(`/boards/${this.boardIdValue}`, { - method: 'PATCH', - headers: { - 'Content-Type': 'application/json', - 'X-CSRF-Token': document.querySelector('[name="csrf-token"]').content - }, - body: JSON.stringify({ - ships_data: JSON.stringify(this.placedShips) + this.submitButtonTarget.disabled = true + + try { + const response = await fetch(`/boards/${this.boardIdValue}`, { + method: 'PATCH', + headers: { + 'Content-Type': 'application/json', + 'Accept': 'text/vnd.turbo-stream.html', + 'X-CSRF-Token': document.querySelector('[name="csrf-token"]').content + }, + body: JSON.stringify({ + ships_data: JSON.stringify(this.placedShips) + }) }) - }) - if (!response.ok) { - const error = await response.json() - alert(`Error: ${error.error || 'Failed to place ships'}`) + // The server answers with a Turbo Stream: the next screen, or a flash message on error + Turbo.renderStreamMessage(await response.text()) + } catch (error) { + console.error('Error placing ships:', error) + alert('Failed to place ships. Please try again.') + } finally { + if (this.element.isConnected) this.submitButtonTarget.disabled = false } } } diff --git a/app/models/game.rb b/app/models/game.rb index 5ae18c0..1e537cc 100644 --- a/app/models/game.rb +++ b/app/models/game.rb @@ -70,7 +70,12 @@ def check_winner! end def broadcast_game_over - broadcast_replace_to "game_#{id}", partial: "games/game_over", locals: { game: self } + [ player1, player2 ].each do |player| + broadcast_replace_to "player_#{player.id}", + target: "game-container", + partial: "games/game_over", + locals: { game: self, player: player } + end end private diff --git a/app/models/shot.rb b/app/models/shot.rb index 7842dbf..376add5 100644 --- a/app/models/shot.rb +++ b/app/models/shot.rb @@ -12,20 +12,8 @@ class Shot < ApplicationRecord validates :x, :y, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than: Board::GRID_SIZE } validates :x, uniqueness: { scope: [ :game_id, :target_player_id, :y ] } - # Callbacks - after_create :broadcast_shot - # Scopes scope :for_game, ->(game_id) { where(game_id: game_id) } scope :hits, -> { where(result: [ :hit, :sink ]) } scope :misses, -> { where(result: :miss) } - - private - - def broadcast_shot - broadcast_prepend_to "game_#{game_id}_log", - partial: "shots/shot", - locals: { shot: self }, - target: "shots-log" - end end diff --git a/app/services/game_play/fire_shot_service.rb b/app/services/game_play/fire_shot_service.rb index a2b490e..9bfcde3 100644 --- a/app/services/game_play/fire_shot_service.rb +++ b/app/services/game_play/fire_shot_service.rb @@ -70,15 +70,14 @@ def process_shot # Switch turn if game is still in progress game.switch_turn! if game.in_progress? - # Broadcast updates - broadcast_shot_result + broadcast_shot_result unless game.finished? end + # Re-render each player's own view of the game (boards, turn indicator, battle log). def broadcast_shot_result - # Broadcast to both players [ game.player1, game.player2 ].each do |player| Turbo::StreamsChannel.broadcast_replace_to( - "player_#{player.id}_game_#{game.id}", + "player_#{player.id}", target: "game-container", partial: "games/play", locals: { game: game, player: player } diff --git a/app/services/game_play/matchmaking_service.rb b/app/services/game_play/matchmaking_service.rb index b22735f..c79ed97 100644 --- a/app/services/game_play/matchmaking_service.rb +++ b/app/services/game_play/matchmaking_service.rb @@ -10,7 +10,7 @@ def call ActiveRecord::Base.transaction do game = find_or_create_game - if game.player2.present? + if game.waiting_for_players? && game.player2.present? # Game is full, start ship placement phase start_ship_placement_phase(game) end @@ -24,8 +24,11 @@ def call attr_reader :player def find_or_create_game - # Try to find a waiting game - waiting_game = Game.waiting.lock.first + # Clicking "Find Opponent" twice should not open a second game + current = player.current_game + return current if current && !current.finished? + + waiting_game = Game.waiting.where.not(player1: player).lock.first if waiting_game # Join as player 2 diff --git a/app/services/game_play/ship_placement_service.rb b/app/services/game_play/ship_placement_service.rb index e1c3adf..09a287b 100644 --- a/app/services/game_play/ship_placement_service.rb +++ b/app/services/game_play/ship_placement_service.rb @@ -60,23 +60,13 @@ def check_if_both_ready end def broadcast_game_started - # Broadcast to both players on both their channels [ game.player1, game.player2 ].each do |player| - # Broadcast to player channel Turbo::StreamsChannel.broadcast_replace_to( "player_#{player.id}", target: "game-container", partial: "games/play", locals: { game: game, player: player } ) - - # Also broadcast to player_game channel for reliability - Turbo::StreamsChannel.broadcast_replace_to( - "player_#{player.id}_game_#{game.id}", - target: "game-container", - partial: "games/play", - locals: { game: game, player: player } - ) end end end diff --git a/app/views/boards/_board.html.erb b/app/views/boards/_board.html.erb index 3aba7f7..b4e45f0 100644 --- a/app/views/boards/_board.html.erb +++ b/app/views/boards/_board.html.erb @@ -31,7 +31,7 @@
+ <%= "data-action='click->battleship-board#fire'" if can_fire && !(cell["shot"] || cell["hit"]) %> title="<%= "#{('A'.ord + y).chr}#{x + 1}" %>"> <% if cell.is_a?(Hash) %> <% if cell["hit"] %> diff --git a/app/views/boards/update.html.erb b/app/views/boards/update.html.erb deleted file mode 100644 index cd1f2c7..0000000 --- a/app/views/boards/update.html.erb +++ /dev/null @@ -1,2 +0,0 @@ -

Boards#update

-

Find me in app/views/boards/update.html.erb

diff --git a/app/views/games/_place_ships.html.erb b/app/views/games/_place_ships.html.erb index 4dd6485..18a06f4 100644 --- a/app/views/games/_place_ships.html.erb +++ b/app/views/games/_place_ships.html.erb @@ -23,7 +23,10 @@ <% end %> -

Click on the grid to place ships horizontally. Click ship in list to rotate.

+

Click the grid to place each ship. Press R or use the button below to rotate.

+
diff --git a/app/views/games/fire.html.erb b/app/views/games/fire.html.erb deleted file mode 100644 index c71cd47..0000000 --- a/app/views/games/fire.html.erb +++ /dev/null @@ -1,2 +0,0 @@ -

Games#fire

-

Find me in app/views/games/fire.html.erb

diff --git a/app/views/games/join.html.erb b/app/views/games/join.html.erb deleted file mode 100644 index e46f880..0000000 --- a/app/views/games/join.html.erb +++ /dev/null @@ -1,2 +0,0 @@ -

Games#join

-

Find me in app/views/games/join.html.erb

diff --git a/app/views/games/show.html.erb b/app/views/games/show.html.erb index 22d79a7..b9de7d9 100644 --- a/app/views/games/show.html.erb +++ b/app/views/games/show.html.erb @@ -13,5 +13,3 @@
<%= turbo_stream_from "player_#{@player.id}" %> -<%= turbo_stream_from "player_#{@player.id}_game_#{@game.id}" %> -<%= turbo_stream_from "game_#{@game.id}_log" %> diff --git a/app/views/players/create.html.erb b/app/views/players/create.html.erb deleted file mode 100644 index 94f9c9e..0000000 --- a/app/views/players/create.html.erb +++ /dev/null @@ -1,2 +0,0 @@ -

Players#create

-

Find me in app/views/players/create.html.erb

diff --git a/app/views/shots/create.html.erb b/app/views/shots/create.html.erb deleted file mode 100644 index 603e9ae..0000000 --- a/app/views/shots/create.html.erb +++ /dev/null @@ -1,2 +0,0 @@ -

Shots#create

-

Find me in app/views/shots/create.html.erb

diff --git a/config/routes.rb b/config/routes.rb index 2ec03aa..40f26fc 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -7,9 +7,6 @@ # Game routes resources :games, only: [ :index, :show ] do - member do - post :fire - end resources :shots, only: [ :create ] end diff --git a/test/controllers/boards_controller_test.rb b/test/controllers/boards_controller_test.rb index f3a386b..93dd633 100644 --- a/test/controllers/boards_controller_test.rb +++ b/test/controllers/boards_controller_test.rb @@ -1,8 +1,34 @@ require "test_helper" class BoardsControllerTest < ActionDispatch::IntegrationTest - test "should get update" do - get boards_update_url + setup do + @dave = sign_in_as("Dave") + @game = start_matched_game(@dave, players(:bob)) + end + + def place(board, fleet = fleet_in_rows) + patch board_path(board), params: { ships_data: fleet.to_json }, as: :turbo_stream + end + + test "placing ships shows the waiting screen" do + place(@game.board_for(@dave)) + assert_response :success + assert_match "waiting-for-opponent", response.body + assert @game.board_for(@dave).ready? + end + + test "an invalid fleet shows an error" do + place(@game.board_for(@dave), fleet_in_rows.first(2)) + + assert_match "Invalid ship placement", response.body + assert_not @game.board_for(@dave).ready? + end + + test "cannot place ships on the opponent's board" do + place(@game.board_for(players(:bob))) + + assert_redirected_to games_path + assert_not @game.board_for(players(:bob)).ready? end end diff --git a/test/controllers/games_controller_test.rb b/test/controllers/games_controller_test.rb index f4de6eb..e714965 100644 --- a/test/controllers/games_controller_test.rb +++ b/test/controllers/games_controller_test.rb @@ -1,23 +1,43 @@ require "test_helper" class GamesControllerTest < ActionDispatch::IntegrationTest - test "should get index" do - get games_index_url - assert_response :success + test "lobby requires a player" do + get games_path + assert_redirected_to new_player_path end - test "should get show" do - get games_show_url + test "joining creates a game and shows it" do + sign_in_as("Dave") + post join_game_path + + game = Game.last + assert_redirected_to game_path(game) + follow_redirect! assert_response :success end - test "should get join" do - get games_join_url + test "players can see their own game" do + dave = sign_in_as("Dave") + game = start_battle(dave, players(:bob)) + + get game_path(game) assert_response :success end - test "should get fire" do - get games_fire_url - assert_response :success + test "players cannot open someone else's game" do + game = start_battle + sign_in_as("Dave") + + get game_path(game) + assert_redirected_to games_path + end + + test "lobby offers a new match after a finished game" do + dave = sign_in_as("Dave") + game = start_battle(dave, players(:bob)) + game.update!(state: :finished, winner: dave) + + get games_path + assert_select "button", text: "Find Opponent" end end diff --git a/test/controllers/players_controller_test.rb b/test/controllers/players_controller_test.rb index 75f30e0..3576350 100644 --- a/test/controllers/players_controller_test.rb +++ b/test/controllers/players_controller_test.rb @@ -1,13 +1,20 @@ require "test_helper" class PlayersControllerTest < ActionDispatch::IntegrationTest - test "should get new" do - get players_new_url + test "shows the name form" do + get root_path assert_response :success end - test "should get create" do - get players_create_url - assert_response :success + test "creating a player signs them in" do + assert_difference "Player.count" do + post players_path, params: { player: { name: "Dave" } } + end + assert_redirected_to games_path + end + + test "a blank name is rejected" do + post players_path, params: { player: { name: "" } } + assert_response :unprocessable_entity end end diff --git a/test/controllers/shots_controller_test.rb b/test/controllers/shots_controller_test.rb index 8781a07..200b2d6 100644 --- a/test/controllers/shots_controller_test.rb +++ b/test/controllers/shots_controller_test.rb @@ -1,8 +1,30 @@ require "test_helper" class ShotsControllerTest < ActionDispatch::IntegrationTest - test "should get create" do - get shots_create_url + setup do + @dave = sign_in_as("Dave") + @game = start_battle(@dave, players(:bob)) + end + + test "firing on your turn" do + post game_shots_path(@game), params: { x: 0, y: 0 }, as: :json + assert_response :success + assert_equal "hit", response.parsed_body["result"] + end + + test "firing out of turn is rejected" do + @game.update!(current_turn_player: players(:bob)) + post game_shots_path(@game), params: { x: 0, y: 0 }, as: :json + + assert_response :unprocessable_entity + assert_equal "It's not your turn", response.parsed_body["error"] + end + + test "outsiders cannot fire in a game" do + other = start_battle(players(:alice), players(:carol)) + post game_shots_path(other), params: { x: 0, y: 0 }, as: :json + + assert_redirected_to games_path end end diff --git a/test/fixtures/boards.yml b/test/fixtures/boards.yml deleted file mode 100644 index b372f6c..0000000 --- a/test/fixtures/boards.yml +++ /dev/null @@ -1,15 +0,0 @@ -# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html - -one: - game_id: 1 - player_id: 1 - grid_json: MyText - ships_json: MyText - ready: false - -two: - game_id: 1 - player_id: 1 - grid_json: MyText - ships_json: MyText - ready: false diff --git a/test/fixtures/games.yml b/test/fixtures/games.yml deleted file mode 100644 index e4bc4d9..0000000 --- a/test/fixtures/games.yml +++ /dev/null @@ -1,17 +0,0 @@ -# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html - -one: - state: 1 - player1_id: 1 - player2_id: 1 - current_turn_player_id: 1 - winner_id: 1 - ships_placement_deadline: 2025-11-13 17:02:05 - -two: - state: 1 - player1_id: 1 - player2_id: 1 - current_turn_player_id: 1 - winner_id: 1 - ships_placement_deadline: 2025-11-13 17:02:05 diff --git a/test/fixtures/players.yml b/test/fixtures/players.yml index 9ba9c93..511a160 100644 --- a/test/fixtures/players.yml +++ b/test/fixtures/players.yml @@ -1,11 +1,11 @@ -# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html +alice: + name: Alice + status: idle -one: - name: MyString - status: 1 - current_game_id: 1 +bob: + name: Bob + status: idle -two: - name: MyString - status: 1 - current_game_id: 1 +carol: + name: Carol + status: idle diff --git a/test/fixtures/shots.yml b/test/fixtures/shots.yml deleted file mode 100644 index 91a9bdb..0000000 --- a/test/fixtures/shots.yml +++ /dev/null @@ -1,17 +0,0 @@ -# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html - -one: - game_id: 1 - shooter_id: 1 - target_player_id: 1 - x: 1 - 'y': 1 - result: 1 - -two: - game_id: 1 - shooter_id: 1 - target_player_id: 1 - x: 1 - 'y': 1 - result: 1 diff --git a/test/jobs/auto_place_ships_job_test.rb b/test/jobs/auto_place_ships_job_test.rb index 20f65f5..3900742 100644 --- a/test/jobs/auto_place_ships_job_test.rb +++ b/test/jobs/auto_place_ships_job_test.rb @@ -1,7 +1,22 @@ require "test_helper" class AutoPlaceShipsJobTest < ActiveJob::TestCase - # test "the truth" do - # assert true - # end + include GameHelpers + + test "places missing fleets and starts the game" do + game = start_matched_game + game.board_for(players(:alice)).place_ships(fleet_in_rows) + + AutoPlaceShipsJob.perform_now(game.id) + + assert game.reload.in_progress? + assert game.boards.all?(&:ready) + end + + test "does nothing once the game has started" do + game = start_battle + assert_no_changes -> { game.reload.updated_at } do + AutoPlaceShipsJob.perform_now(game.id) + end + end end diff --git a/test/models/board_test.rb b/test/models/board_test.rb index efde2c3..5e2bb07 100644 --- a/test/models/board_test.rb +++ b/test/models/board_test.rb @@ -1,7 +1,84 @@ require "test_helper" class BoardTest < ActiveSupport::TestCase - # test "the truth" do - # assert true - # end + include GameHelpers + + setup do + @board = start_matched_game.board_for(players(:alice)) + end + + test "starts with an empty 10x10 grid" do + assert_equal Board::GRID_SIZE, @board.grid.size + assert @board.grid.flatten.all?(&:empty?) + end + + test "accepts a valid fleet and marks the board ready" do + assert @board.place_ships(fleet_in_rows) + assert @board.reload.ready? + end + + test "rejects a fleet with a missing ship" do + assert_not @board.place_ships(fleet_in_rows.first(4)) + end + + test "rejects overlapping ships" do + fleet = fleet_in_rows + fleet[1]["coordinates"] = (0...4).map { |x| { "x" => x, "y" => 0 } } + assert_not @board.place_ships(fleet) + end + + test "rejects ships that leave the grid" do + fleet = fleet_in_rows + fleet[0]["coordinates"] = (7...12).map { |x| { "x" => x, "y" => 0 } } + assert_not @board.place_ships(fleet) + end + + test "rejects diagonal or gapped ships" do + fleet = fleet_in_rows + fleet[4]["coordinates"] = [ { "x" => 0, "y" => 4 }, { "x" => 2, "y" => 4 } ] + assert_not @board.place_ships(fleet) + end + + test "accepts vertical ships" do + fleet = Board::SHIPS.each_with_index.map do |(type, length), col| + { "type" => type.to_s, "coordinates" => (0...length).map { |y| { "x" => col, "y" => y } } } + end + assert @board.place_ships(fleet) + end + + test "process_shot reports miss, hit, sink and repeats" do + @board.place_ships(fleet_in_rows) + + assert_equal :miss, @board.process_shot(9, 9) + assert_equal :hit, @board.process_shot(0, 4) + assert_equal :already_shot, @board.process_shot(0, 4) + assert_equal :sink, @board.process_shot(1, 4) + assert_equal :invalid, @board.process_shot(10, 0) + end + + test "all_ships_sunk? once every ship cell is hit" do + @board.place_ships(fleet_in_rows) + cells = fleet_in_rows.flat_map { |s| s["coordinates"] } + + cells[0..-2].each { |c| @board.process_shot(c["x"], c["y"]) } + assert_not @board.all_ships_sunk? + + @board.process_shot(cells.last["x"], cells.last["y"]) + assert @board.all_ships_sunk? + end + + test "opponent view only reveals shots, never ship positions" do + @board.place_ships(fleet_in_rows) + @board.process_shot(0, 0) + @board.process_shot(9, 9) + + view = @board.to_opponent_view.flatten + assert view.none? { |cell| cell.key?("type") } + assert_equal 2, view.count { |cell| cell["shot"] } + end + + test "auto_place_ships! produces a legal fleet" do + assert @board.auto_place_ships! + assert_equal Board::SHIPS.values.sum, @board.grid.flatten.count { |c| c["type"] } + end end diff --git a/test/models/game_test.rb b/test/models/game_test.rb index 6628fae..784642b 100644 --- a/test/models/game_test.rb +++ b/test/models/game_test.rb @@ -1,7 +1,38 @@ require "test_helper" class GameTest < ActiveSupport::TestCase - # test "the truth" do - # assert true - # end + include GameHelpers + + test "new games start waiting for players" do + assert Game.new(player1: players(:alice)).waiting_for_players? + end + + test "a player cannot play against themselves" do + game = Game.new(player1: players(:alice), player2: players(:alice)) + assert_not game.valid? + end + + test "opponent_of returns the other player" do + game = start_matched_game + assert_equal players(:bob), game.opponent_of(players(:alice)) + assert_equal players(:alice), game.opponent_of(players(:bob)) + assert_nil game.opponent_of(players(:carol)) + end + + test "switch_turn! hands the turn to the opponent" do + game = start_battle + game.switch_turn! + assert game.my_turn?(players(:bob)) + end + + test "check_winner! finishes the game when a fleet is sunk" do + game = start_battle + bob_board = game.board_for(players(:bob)) + fleet_in_rows.flat_map { |s| s["coordinates"] }.each { |c| bob_board.process_shot(c["x"], c["y"]) } + + game.reload.check_winner! + + assert game.finished? + assert_equal players(:alice), game.winner + end end diff --git a/test/models/player_test.rb b/test/models/player_test.rb index 961f674..8735ea6 100644 --- a/test/models/player_test.rb +++ b/test/models/player_test.rb @@ -1,7 +1,15 @@ require "test_helper" class PlayerTest < ActiveSupport::TestCase - # test "the truth" do - # assert true - # end + test "requires a name" do + assert_not Player.new(name: "").valid? + end + + test "limits name length" do + assert_not Player.new(name: "x" * 51).valid? + end + + test "defaults to idle" do + assert Player.new(name: "Dave").idle? + end end diff --git a/test/models/shot_test.rb b/test/models/shot_test.rb index 0a65271..02280cf 100644 --- a/test/models/shot_test.rb +++ b/test/models/shot_test.rb @@ -1,7 +1,18 @@ require "test_helper" class ShotTest < ActiveSupport::TestCase - # test "the truth" do - # assert true - # end + include GameHelpers + + test "coordinates must be on the grid" do + game = start_battle + shot = game.shots.build(shooter: players(:alice), target_player: players(:bob), x: 10, y: 0, result: :miss) + assert_not shot.valid? + end + + test "the same cell cannot be shot twice" do + game = start_battle + attrs = { shooter: players(:alice), target_player: players(:bob), x: 3, y: 3, result: :miss } + game.shots.create!(attrs) + assert_not game.shots.build(attrs).valid? + end end diff --git a/test/services/fire_shot_service_test.rb b/test/services/fire_shot_service_test.rb new file mode 100644 index 0000000..282de92 --- /dev/null +++ b/test/services/fire_shot_service_test.rb @@ -0,0 +1,41 @@ +require "test_helper" + +class FireShotServiceTest < ActiveSupport::TestCase + include GameHelpers + + setup { @game = start_battle } + + test "a hit is recorded and the turn passes" do + result = fire(@game, players(:alice), 0, 0) + + assert result[:success] + assert_equal :hit, result[:result] + assert @game.reload.my_turn?(players(:bob)) + end + + test "cannot fire out of turn" do + result = fire(@game, players(:bob), 0, 0) + assert_equal "It's not your turn", result[:error] + end + + test "cannot fire at the same cell twice" do + fire(@game, players(:alice), 5, 5) + fire(@game, players(:bob), 5, 5) + + assert_match "Already shot", fire(@game, players(:alice), 5, 5)[:error] + end + + test "sinking the last ship wins the game" do + targets = fleet_in_rows.flat_map { |s| s["coordinates"] } + misses = (0...Board::GRID_SIZE).flat_map { |x| (5...Board::GRID_SIZE).map { |y| [ x, y ] } } + + targets.each_with_index do |c, i| + assert fire(@game, players(:alice), c["x"], c["y"])[:success] + break if @game.reload.finished? + assert fire(@game, players(:bob), *misses[i])[:success] + end + + assert @game.reload.finished? + assert_equal players(:alice), @game.winner + end +end diff --git a/test/services/matchmaking_service_test.rb b/test/services/matchmaking_service_test.rb new file mode 100644 index 0000000..063453c --- /dev/null +++ b/test/services/matchmaking_service_test.rb @@ -0,0 +1,39 @@ +require "test_helper" + +class MatchmakingServiceTest < ActiveSupport::TestCase + include ActiveJob::TestHelper + include GameHelpers + + test "first player creates a waiting game" do + game = GamePlay::MatchmakingService.new(players(:alice)).call + + assert game.waiting_for_players? + assert players(:alice).reload.searching? + end + + test "second player joins and starts ship placement" do + game = nil + assert_enqueued_with(job: AutoPlaceShipsJob) { game = start_matched_game } + + assert game.placing_ships? + assert_equal players(:bob), game.player2 + assert_equal 2, game.boards.count + assert game.ships_placement_deadline.future? + end + + test "joining twice returns the same game instead of matching with yourself" do + first = GamePlay::MatchmakingService.new(players(:alice)).call + second = GamePlay::MatchmakingService.new(players(:alice).reload).call + + assert_equal first, second + assert_nil second.player2 + end + + test "a player whose last game finished can find a new one" do + old = start_battle + old.update!(state: :finished, winner: players(:alice)) + + game = GamePlay::MatchmakingService.new(players(:alice).reload).call + assert_not_equal old, game + end +end diff --git a/test/services/ship_placement_service_test.rb b/test/services/ship_placement_service_test.rb new file mode 100644 index 0000000..c49e8ca --- /dev/null +++ b/test/services/ship_placement_service_test.rb @@ -0,0 +1,30 @@ +require "test_helper" + +class ShipPlacementServiceTest < ActiveSupport::TestCase + include GameHelpers + + setup { @game = start_matched_game } + + def place(player, fleet = fleet_in_rows) + GamePlay::ShipPlacementService.new(board: @game.board_for(player), ships_data: fleet).call + end + + test "game starts once both players have placed" do + assert place(players(:alice))[:success] + assert @game.reload.placing_ships? + + assert place(players(:bob))[:success] + assert @game.reload.in_progress? + assert @game.my_turn?(players(:alice)) + end + + test "rejects an invalid fleet" do + result = place(players(:alice), fleet_in_rows.first(2)) + assert_not result[:success] + end + + test "rejects placement after the deadline" do + @game.update!(ships_placement_deadline: 1.minute.ago) + assert_match "expired", place(players(:alice))[:error] + end +end diff --git a/test/support/game_helpers.rb b/test/support/game_helpers.rb new file mode 100644 index 0000000..6bcab99 --- /dev/null +++ b/test/support/game_helpers.rb @@ -0,0 +1,24 @@ +module GameHelpers + # Ships laid out in rows 0-4, starting at column 0. + def fleet_in_rows + Board::SHIPS.each_with_index.map do |(type, length), row| + { "type" => type.to_s, "coordinates" => (0...length).map { |x| { "x" => x, "y" => row } } } + end + end + + def start_matched_game(p1 = players(:alice), p2 = players(:bob)) + GamePlay::MatchmakingService.new(p1).call + GamePlay::MatchmakingService.new(p2).call.reload + end + + def start_battle(p1 = players(:alice), p2 = players(:bob)) + game = start_matched_game(p1, p2) + game.boards.each { |board| board.place_ships(fleet_in_rows) } + game.update!(state: :in_progress, current_turn_player: p1) + game + end + + def fire(game, shooter, x, y) + GamePlay::FireShotService.new(game: game.reload, shooter: shooter, x: x, y: y).call + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb index 0c22470..60dba4d 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,6 +1,7 @@ ENV["RAILS_ENV"] ||= "test" require_relative "../config/environment" require "rails/test_help" +Dir[File.expand_path("support/**/*.rb", __dir__)].each { |f| require f } module ActiveSupport class TestCase @@ -9,7 +10,15 @@ class TestCase # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. fixtures :all + end +end + +class ActionDispatch::IntegrationTest + include GameHelpers - # Add more helper methods to be used by all tests here... + # Signs in through the real name form; returns the new Player. + def sign_in_as(name) + post players_path, params: { player: { name: name } } + Player.find(session[:player_id]) end end