Skip to content
lumnairePublic

About

Real-time 1v1 Jack en Poy with matchmaking, match history, and competitive gameplay.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Latest commit

 

History

11 Commits

Folders and files

Repository files navigation

JackEnPoy Online

Web-based 1v1 Jack en Poy (Bato / Gunting / Papel) with real-time matchmaking, accounts and persistent match history.

Status: Phase 3 complete — game modes, Elo ranking, rank tiers, leaderboards and the player dashboard are live. Tournaments (Phase 4) are next.

Layout

packages/game-core   Shared rules: throws, round resolution, match scoring, socket contract
packages/db          Prisma schema and client, shared by both apps
apps/realtime        Node + Socket.io game server (separate deployable service)
apps/web             Next.js 14 App Router + Tailwind frontend

game-core is the single source of truth for the rules, imported by both the server and the browser, and it is where the logic tests live.

The realtime server is deliberately not a Next.js API route — Vercel does not hold persistent WebSocket connections, so it deploys separately (Render/Railway).

Setting up Neon

  1. Sign up at https://neon.tech (free tier, no card).

  2. Create a project — name it jackenpoy, pick the region closest to you (ap-southeast-1 Singapore is the nearest to PH). Keep the default database name neondb.

  3. On the project dashboard, hit Connect and copy the connection string.

  4. Put it in .env at the repo root, twice — the difference is one -pooler:

    # app queries: host HAS -pooler
    DATABASE_URL="postgresql://...@ep-xxxx-pooler.region.aws.neon.tech/neondb?sslmode=require"
    # migrations: same string, -pooler REMOVED
    DIRECT_DATABASE_URL="postgresql://...@ep-xxxx.region.aws.neon.tech/neondb?sslmode=require"
    

    Getting these the wrong way round still works, but the app then opens a direct connection per request and will hit Neon's free-tier connection limit under load.

Both strings must end with ?sslmode=require.

Configuration

One .env at the repo root configures every service. next.config.mjs and the realtime server both load it, so there is only one file to fill in.

cp .env.example .env
Variable Meaning
DATABASE_URL Neon pooled connection string
DIRECT_DATABASE_URL Neon direct (unpooled) string, for migrations
NEXTAUTH_SECRET Session signing key — openssl rand -base64 32
NEXTAUTH_URL http://localhost:3000 in development
REALTIME_TOKEN_SECRET Shared secret between web and realtime; must match
PORT, CORS_ORIGIN Realtime server
ROUND_DURATION_MS Countdown before a throw is forfeited (default 5000)
REVEAL_DURATION_MS How long the reveal is held (default 2500)
RECONNECT_GRACE_MS Seat held open for a disconnected player (default 30000)
DEFAULT_BEST_OF Match format, 3 or 5
NEXT_PUBLIC_REALTIME_URL Socket endpoint the browser dials

Running locally

npm install
npm run db:migrate    # first time only, after Neon is configured
npm run dev           # realtime server on :4000, web on :3000

Open http://localhost:3000 in two browser windows (one normal, one private — they need separate localStorage) and hit Play Now in both to get paired.

Other scripts:

npm test              # game-core unit tests (rules + scoring)
npm run smoke         # end-to-end socket test of the match loop
npm run typecheck
npm run build
npm run db:studio     # browse the database
npm run db:purge-guests  # clear guest player records (dry run without --yes)
npm run ranked:check  # play a real ranked match and assert Elo moved

After changing the schema

npm run dev no longer regenerates the Prisma client — it is generated on npm install and on demand:

npm run db:generate   # after editing schema.prisma
npm run db:migrate    # to apply the change to Neon

Both rewrite the query engine in node_modules/.prisma, and Windows will not let them replace a file that a running process has open. Stop the dev server first, or you get:

EPERM: operation not permitted, rename '...query_engine-windows.dll.node.tmp'

If that happens, stop every node process for this project and re-run. Keeping the repo inside a synced OneDrive folder makes the lock more likely, so excluding node_modules from sync is worth doing.

How a match works

The server is authoritative. It owns the countdown, decides when a round resolves, and sends each player a snapshot rendered from their own point of view — a player's socket never carries the opponent's throw before the reveal.

  1. Both players queue:join; the two who have waited longest are paired (FIFO).
  2. Each round opens a countdown. Throws are hidden until both are in, or the timer expires — whichever comes first.
  3. A missed countdown is a forfeited throw and loses to any real throw. Two rounds where both players miss ends the match as abandoned.
  4. Drawn rounds are replayed rather than counted, with a round cap as a backstop; at the cap, whoever is ahead wins.
  5. First to a majority (2 of 3, or 3 of 5) takes the match.

Reconnecting

The browser keeps a clientId in localStorage. On refresh the client says hello with the same id and drops straight back into its seat with the full match state. Round timers keep running while a player is away — being disconnected forfeits throws, not the match — until RECONNECT_GRACE_MS elapses, at which point the match is forfeited to the opponent.

Accounts and identity

Sign-in is optional: guests can still play, exactly as in Phase 1.

Email and password only, through NextAuth with bcrypt (12 rounds). Sessions are JWTs and there is no database adapter — an adapter exists to store OAuth accounts and server-side sessions, and this app has neither. A useful side effect: a sleeping database can never invalidate a live session.

Guests

Anyone can play without signing up. The server issues a handle of the form guest_12345 — clients cannot choose their own, so nobody can pick a name that impersonates another player, and the guest_ prefix is reserved at registration.

A guest gets a real user row, keyed by the browser's stored client id, created the first time they queue. That means their wins appear on the classic leaderboard and their opponents' match history reads correctly. Coming back to the same browser keeps their handle and their record.

Guests cannot play ranked: clearing browser storage would hand them a fresh 1200 whenever they liked, which would make the ladder meaningless.

Signing out fully drops the account, including the display name. The server owns handles and the client sends none, so a signed-out browser can never keep playing under the account it just left.

The realtime server runs on a different origin and never sees the session cookie. Instead the browser fetches a five-minute token from /api/realtime-token, signed with REALTIME_TOKEN_SECRET, and presents it in the socket handshake. An absent or unverifiable token simply means "guest", so a misconfigured deployment degrades to Phase 1 behaviour rather than breaking.

Artwork

Two images live in apps/web/public and are referenced by name:

File Where
logo-jackenpoy.png Header, beside the wordmark
hero-img-jackenpoy.png Landing page hero, right-hand panel

Both degrade quietly if missing — the header keeps its wordmark and the hero panel is dropped — so a missing file never leaves a broken box on the page. Drop a square copy at apps/web/src/app/icon.png to use the logo as the tab icon; Next.js picks that path up on its own.

Game modes

Two queues, kept entirely separate by the matchmaker:

Classic Ranked
Who can play Anyone, guests included Signed-in players only
Elo Never moves Moves on every result
Counted in Classic win totals Ranked totals and the ladder

Ranked needs an account because there is nowhere to store a guest's rating, so the server refuses a guest's ranked join rather than silently downgrading it.

Ranking

Standard Elo, in packages/game-core/src/elo.ts:

E = 1 / (1 + 10^((opponentRating - rating) / 400))
newRating = rating + K * (score - E)

Score is 1 for a win, 0.5 for a draw, 0 for a loss. Everyone starts at 1200.

The K-factor adapts, so new ratings settle quickly and established ones don't swing on a single match:

Condition K
Fewer than 30 ranked matches 40
2400 and above 16
Otherwise 32

Because each player is rated with their own K, a settled player beating a provisional one does not lose exactly what the newcomer gains. That asymmetry is deliberate. Ratings are floored at 100, and the reported delta is the movement that actually happened, so history never disagrees with the stored rating.

Rank tiers

Tier From
Bronze 0
Silver 1300
Gold 1450
Platinum 1600
Diamond 1750
Master 1900
Legendary 2100

Everyone starts at 1200, inside Bronze, so a new player climbs out of the bottom tier rather than starting halfway up the ladder.

Leaderboards

/leaderboard has two boards: Ranked (by Elo) and Classic (by classic wins). Ten per page with Previous/Next, up to the top 100, and search by username. Only players who have actually played a mode appear on its board, and the viewer's own row is highlighted.

Both boards list registered accounts only. Guests still play and still appear in their opponents' match history, but they are not ranked — a guest can reset themselves by clearing browser storage, so a board built from them would not mean anything. npm run db:purge-guests clears out accumulated guest rows (dry run by default, -- --yes to commit); match history survives, since participant rows keep the handle they were played under.

Tournament standings are marked coming soon — there is nothing to rank until the bracket engine exists.

Reads come straight from Postgres. Every result updates denormalised counters on User in the same transaction as the match write, so a leaderboard page is one indexed query rather than an aggregate over the whole match table. The Redis sorted-set cache from the original plan is not wired up: it needs Upstash credentials, and at this scale Postgres answers these queries comfortably.

Match history

The realtime server writes finished matches directly to Postgres — no extra network hop through the web app. Matches between two guests are skipped; a match with one signed-in player is stored with a null userId on the guest side, so the real player's record stays complete.

Persistence never blocks gameplay: the match is over and both players already have their result on screen, so a database hiccup is logged and dropped.

Profiles live at /u/<username> and show a win/loss/draw record, win rate, and the last 25 matches with opponents and scores.

Tests

  • packages/game-core/src/__tests__/throws.test.ts — the full 3×3 outcome table written out longhand, plus symmetry and forfeit rules.
  • packages/game-core/src/__tests__/match.test.ts — majority scoring, draws, round cap.
  • packages/game-core/src/__tests__/elo.test.ts — the expected-score formula against textbook anchors, K-factor tiers, the rating floor, symmetry, and convergence over long runs.
  • packages/game-core/src/__tests__/ranks.test.ts — tier boundaries and progress, checked to be monotonic and bounded.
  • apps/realtime/scripts/smoke.ts — boots the real server and drives two scripted clients through a sweep, a timeout forfeit, a mid-match refresh, a grace-period forfeit, an explicit leave, and a guest's refused ranked join.
  • apps/realtime/scripts/ranked-check.mts — plays a full ranked match against the real database, then asserts the Elo movement, the counters, the rating history and the stored match. Cleans up after itself.

Deploying

Two services: the Next.js app on Vercel, and the realtime server somewhere that holds WebSocket connections. They talk over a shared secret, not cookies.

1. Push to GitHub

.env is gitignored — only .env.example is committed. Confirm before pushing:

git check-ignore -v .env    # must print a .gitignore line
git remote add origin https://github.com/<you>/<repo>.git
git branch -M main
git push -u origin main

2. Web app on Vercel

Import the repo and leave Root Directory as the repo root. vercel.json does the rest.

Three things this monorepo needs that a single-package app does not, all of them already configured:

  • prisma generate runs in the build command, not just postinstall. Vercel caches dependencies between deploys, so postinstall can be skipped and leave you with a Prisma Client that predates your latest schema.
  • PrismaPlugin in next.config.mjs. Prisma lives in packages/db, so its query engine sits outside apps/web and Next's output tracing misses it. Without the plugin the deploy succeeds and then every query fails at runtime with "could not locate the Query Engine" — a failure that never reproduces locally.
  • binaryTargets includes rhel-openssl-3.0.x, the runtime Vercel's functions execute on, alongside native for local work.

Environment variables to set:

Variable Value
DATABASE_URL Neon pooled string (host has -pooler)
DIRECT_DATABASE_URL Neon direct string
NEXTAUTH_SECRET openssl rand -base64 32
NEXTAUTH_URL https://<your-app>.vercel.app
REALTIME_TOKEN_SECRET Long random string — must match the realtime server
NEXT_PUBLIC_REALTIME_URL https://<your-realtime-host>

3. Realtime server on Render

render.yaml is ready — create a Blueprint from the repo, then set the secrets marked sync: false in the dashboard. CORS_ORIGIN must be your exact Vercel URL, and REALTIME_TOKEN_SECRET must be byte-identical to the one on Vercel or every signed-in player silently drops to guest.

Render's free web service sleeps after ~15 minutes idle and takes about a minute to wake, so the first player after a quiet spell will wait. Everything else about the free tier is fine for this game.

4. Migrate the production database

npm run db:deploy

npm 12 and install scripts

npm 12 blocks dependency install scripts by default. Prisma downloads its query engines in a postinstall, and esbuild fetches a native binary the same way, so both are listed in allowScripts in the root package.json:

"allowScripts": {
  "@prisma/client": true,
  "@prisma/engines": true,
  "prisma": true,
  "esbuild": true
}

Without those entries the install prints an "install scripts not yet covered by allowScripts" warning, and on npm 12 the scripts are skipped outright — which leaves a Prisma Client with no engine behind it. Entries are name-only so a version bump doesn't silently drop the approval. If you add a dependency that needs an install script, run npm approve-scripts <pkg> and commit the change.

Free-tier gotchas

Neon suspends the compute after a few minutes of inactivity, and the first query afterwards can fail outright with Can't reach database server. That is transient, so withRetry() in packages/db wraps the paths where it would actually hurt: the sign-in handshake, the session refresh, and the match write that moves Elo.

The session refresh matters most. NextAuth's jwt callback runs on every request, and a throw there destroys an otherwise valid session — which showed up as only not-yet-onboarded players being unable to stay signed in, since they are the only ones whose token triggers a database read. It now retries, and on failure keeps the session alive with what the token already knows.

Roadmap

Phase 4 tournaments (brackets, registration, live standings) · Phase 5 polish (sound, throw animations, chant variants, replays).

About

Real-time 1v1 Jack en Poy with matchmaking, match history, and competitive gameplay.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages