PROMPT
Build a single-file HTML5 toy, "Pixel Table Tennis": a 1 v 1 table tennis match on a floating pixel-art island that plays itself forever (autopilot by default, endless matches), with REAL BALL SPIN (topspin, backspin, sidespin bend the flight and change the bounce), five switchable tables (blue, green, oak, park concrete, neon) that really change how the ball bounces, and optional human control of either player. three.js r128 from cdnjs, everything else procedural and inline, no asset files, no build step for the player.
LOOK
- Render the 3D scene to a low-res target (default 2 px art pixels on wide stages, 1 px on phones; slider 1-6), then a post pass: depth-based outlines, snap every pixel to one fixed 90-colour OKLab palette, ordered Bayer dither. Orthographic camera with smooth azimuth / elevation / zoom, pixel-snapped. Sun shadow map; day / dusk / night lighting with four floodlight poles registered as point lights BEFORE the lights are initialised.
- Island (about 84 x 64 m): the same floating island as the other games of the series: a slab of 1 m voxel columns with a rounded outline, a terraced rim, layered soil and slate strata, hanging roots and floating rocks underneath, bushes and flowers on a lawn rim, drifting birds. A 1024 px ground canvas paints a mown lawn, a paved plaza, gravel paths to a clubhouse and a shop container, and the ARENA MAT: two blues, a white boundary line, two ellipses round the table and "PIXEL OPEN" lettering at both ends. Static meshes are merged by material after building (before anything dynamic is added; the table top, the ball, the players live in a group that is never merged).
- Arena: low barrier boards on four sides (a repeating canvas texture "PIXEL OPEN | TABLE TENNIS", a coping rail), an umpire at a small table behind the far boards (he seated, turns his head to follow the ball and raises a flag after every point), towel boxes at both ends, a small flip scoreboard on the umpire's table and a big scoreboard sign over the far stand that share one canvas texture (redrawn only when the score changes). Four stands (4, 3, 2, 2 rows) hold an instanced crowd (body, head, hat, waving flags) that cheers louder after long rallies; each stand is a "lift sector" that rises out of the way when it stands between the camera and the table. Scenery: a clubhouse with a lit "TABLE TENNIS" sign, a shop container with an awning, parasols with chairs, two decor park tables with paddles, palms, cypresses, hedges, four flag poles in the player colours.
THE TABLE (real dimensions in metres: 2.74 x 1.525, top at 0.76, net 0.1525 above the top)
- The top is a plane with a 704 x 392 canvas texture (256 px per metre) that is repainted on demand: a white edge line, a faint centre line, the shadow of the net. Painters: tournament blue (speckle, sheen), club green, vintage oak (planks and grain), park concrete (blotches, cracks, worn chalk lines), neon (dark grid with glowing cyan edges and a magenta centre line, drawn with shadow blur).
- The frame belongs to the style: steel legs with feet and rails (blue, green, neon), solid concrete slabs (park), turned oak legs (oak); the body box changes colour and thickness. The net is a cloth net (an alpha-tested mesh that wobbles when hit) with a white tape, or a steel plate with holes on the park table.
- Changing the table: the new top is revealed from the middle outwards over 1 s with a bright seam; the old canvas is kept so a second change mid-wipe never shows a mixed top. The panel has five swatch buttons, three bar meters (Bounce, Pace, Grip) and a one-line note per table; key C cycles tables; an option "new table every match" (on by default in autopilot) walks through all five.
TABLES (the same numbers drive physics, sound and the UI)
- restitution e / friction mu: blue .89 / .26; green .88 / .27 (slower); oak .84 / .34 (low bounce, very grippy, spin bites hard); concrete .80 / .38 (dead, rough, skidding); neon .91 / .16 (lively, slippery, spin hardly bites).
- Also switchable: ball (40+ white; orange; old 44 mm: more drag, less Magnus), rubbers for both players (inverted = full spin; pimples = half the spin, less sensitive to incoming spin, a bit faster; hardbat = a quarter of the spin, slower), level (easy / normal / pro), format (one game to 11, best of 3, best of 5), speed (1/4x ... 2x).
THE BALL (the heart of the game)
- State: position, velocity AND angular velocity. Flight: quadratic drag (a = -kd |v| v, kd 0.10), gravity, the Magnus force a = km (omega x v) with km 9e-4 (topspin dips, backspin floats, sidespin curves), spin decay 0.35 / s. Real radius for spin physics 0.02 m; the geometry and collisions use a slightly inflated 0.034 m so the ball is visible in the pixel render.
- Table bounce: vertical speed times restitution; the contact point's slip velocity u = (vx + R wz, vz - R wx); friction removes min(mu (1 + e) vn, |u| / 2.5) of it (a hollow sphere: I = 2/3 m R^2) and the same impulse changes the spin (dw = 1.5 dv / R), so a topspin ball kicks forward, a backspin ball sits up or even stops, and a flat ball picks up topspin from the table. Floor bounce is dead (0.62). The net: a ball whose centre clips the tape continues slowly (a net cord), anything lower drops dead on the hitter's side.
- One launch solver: given the contact point, the landing spot on the table, the flight time and the spin vector, it iterates the initial velocity against the real flight model (drag + Magnus) so a shot lands where it is aimed; the net clearance is checked along the flight and the flight time is lengthened until it clears. A predictor integrates the live ball forward 1.8 s with all bounces and records, for every sample, how many bounces have happened on each half.
- The ball has a coloured logo patch and rotates visibly with its spin (display speed scaled down so it does not strobe); its trail changes colour with the spin: red topspin, blue backspin, green sidespin.
RULES (state machine: pre, serve, rally, point, fault, over)
- Serve: tossed from the free hand (about 0.3 m up), struck at about 0.24 m above the table behind the end line; it must bounce on the server's half first and then on the receiver's half. A net cord that still lands on the receiver's half is a let (replayed); anything else (no bounce on the own half, a double bounce on the own half, the net body, the floor first, a missed ball) is a fault and the point goes to the receiver (no second serve).
- Rally: after the opponent's shot the ball must bounce once on your half; you may not hit it before that (no volleys: the contact test refuses it, a human swinging early simply misses); a shot loses the point if it bounces on the hitter's own half first, hits the net body, or reaches the floor without touching the other half; the point is won when the ball bounces twice on the opponent's half or lands on the floor after a good bounce.
- Scoring: games to 11, win by 2; the serve changes every two points and every point from 10-10 (server for the n-th point of a game = first ^ ((n >> 1) & 1), and first ^ (n & 1) from n = 20); the first server alternates every game; players change ends after every game and, in the deciding game, when the first player reaches 5. Match formats: one game, best of 3, best of 5. After a match the winner celebrates for 8 s and a new match starts (with a new table if the option is on).
PLAYERS
- Jointed voxel figures (hips, torso, head, shoulders, elbows, wrists, knees) with a table tennis paddle (a wooden handle, a round blade with a red rubber on one side and a black one on the other) on a wrist group; two players, Azure and Amber, two different looks. Poses with keyframes and ease, every channel critically damped by a spring: ready crouch, run cycle, forehand and backhand strokes (low to high variants mixed by contact height), a compact punch for pushes and flicks (either hand), smash (jump, trophy pose), lob / chop (deep knee bend, low to high), the toss and the serve, celebration, dejection, the umpire's sit and flag.
- Each stroke has a duration, a contact window (0.1-0.36 s into the swing), a reach (a horizontal radius around a point in front of and beside the racket hand and a height range relative to the table) and a lead time. The ball is only played if it is inside the reach during the window and the rules allow it. Players are clamped to their own side, outside the table's footprint and inside the barrier boards.
AI (both players, any level)
- Planning: walk the predicted path; take the first sample that is on my side, after the bounce on my half and before the second, whose height and distance from the end line fit a stroke (smash: a high ball near the table; chop / lob: a ball far behind the end line; push / flick: a short ball low over the table; forehand / backhand otherwise) and which the player can reach in time (distance to the stand spot / run speed + the stroke's lead). Then look a few samples ahead for a higher feasible contact (the top of the bounce). The stand spot is chosen from forehand or backhand, whichever is closer. Defensive players (random per match) step back after heavy attacking shots and then only consider far contacts (chops and lobs).
- Style at the swing: heavy backspin coming in -> push (or loop against it with skill); short ball -> flick or push; a fast ball -> block; otherwise drive / loop / block by skill. Styles carry a spin (loop 430, drive 220, block 50, push -270, flick 330 with sidespin, smash 70, chop -400, lob 210 rad/s, times the rubber), a mean speed (13.5-25 m/s) and a landing depth range. The target is the best of 12 random table spots by distance from the opponent (wide balls) plus depth and noise. Errors: a random target error that depends on the level, the incoming ball speed, the player's running speed, the awkwardness of the height, how hard the incoming spin is to play with this style and rubber (topspin into heavy backspin, and so on) and a fatigue factor that grows with the rally length; unforced errors (long, wide, into the tape) with a per-style probability.
- Serves: for each serve type (short backspin, fast topspin, sidespin, flat) the AI generates 36 candidates (first bounce spot on its own half, flight time, spin), launches each, SIMULATES it with the real physics (own bounce, net, receiver's bounce) and keeps the best legal one by type (a short serve must bounce twice on the receiver's half, a fast one must be deep, a sidespin one must move sideways); a small execution error and a mis-hit probability create the occasional fault.
HUMAN CONTROL
- Modes: Watch (default), play Azure, play Amber, two players on one keyboard (WASD + Space / J / K, and the arrows + Enter / . / /). Space serves (press to toss, press again and the stroke is timed for you) and in a rally plays a drive (forehand or backhand by the side the ball comes to), a flick for a short ball, a smash for a high one, a lob from far back; J is the topspin attack (loop, smash, the fast topspin serve); K is backspin (push, chop, lob, the short backspin serve). The direction held while hitting aims: sideways picks the corner, towards the opponent makes it long, back makes it short; sideways while serving makes a sidespin serve. A ring on the table shows where the incoming ball will bounce. Shift sprints. Touch: a virtual stick and three round buttons (Hit, Loop, Cut) under the stage on coarse pointers.
CAMERAS AND UI
- Director camera (re-picks by rally): side TV, behind the server, behind a player, overhead, ball cam, a close celebration cut, an orbit after a match, a cut to the overhead view while the table is being changed; fixed cameras Side TV, Behind, Overhead, Ball cam, Island on keys 1-6. Zoom is given in metres of visible width, corrected for the stage aspect ratio. Drag to turn, wheel / pinch to zoom, Q / E rotate, L light, P pause, N new match, M sound, C change the table.
- Masthead with the live score; a framed stage with a score-bug (two rows: kit, name, serving ball, finished games, games won, points; a header line with the format), a radar-style box with the speed of the last shot in km/h and the shot number, call-out captions (FAST SERVE, BACKSPIN SERVE, LOOP, SMASH, CHOP, LOB, FLICK, NET CORD, LET, GAME POINT, DEUCE, CHANGE ENDS, ACE, OFF THE TABLE ...), chips and the latest log line. Panel (below on phones): the table painter first (swatches, bar meters, note, ball, rubbers, a legend for the spin colours), then match settings, how to play, view (camera, light, turn / zoom, pixel size, outlines, dither, raw 3D, sound, stands lift), a stats table (aces, winners, loop winners, smash winners, errors, service faults, matches won, fastest shot, most spin in rev/s, longest rally), the rally log, a "How it's drawn" note with the palette swatches. No horizontal scroll at 390 px. Fonts Alfa Slab One, Oswald, Public Sans; CSS tokens with a dark scheme.
- Sound with the Web Audio API only (off by default): the sharp "tick" of rubber on the ball (brighter and louder for fast shots, a big crack for smashes, soft for lobs), a table "tock" that sounds different on each table (bright glassy ring on neon, dull stone clack on concrete, wooden knock on oak), net tick, floor bounce, whistle, crowd cheer.
QUALITY BAR
- Headless checks (step the simulation deterministically; software GL is far too slow for real time; apply the player poses every few steps because the held ball follows the free hand): no console errors; soak runs of 1500-1800 simulated seconds at every level, format, table, ball and rubber with no NaN, no player outside the arena, no state stuck (pre < 3 s, serve < 3 s unless a human is serving, rally < 70 s), average rally 7-12 shots, a healthy mix of winners, errors, net points, serve faults and aces, all shot styles occurring (including chops and lobs); a unit test of the scoring that plays 600 random matches over all formats and verifies game scores, the serving order including the 10-10 alternation, the alternation of the first server and the change-of-ends flags; a scripted human completes serves and rallies; all panel buttons, keys and the touch buttons work; 390 px has no horizontal scroll; the table wipe is verified by sampling the canvas; scan the file for personal data before publishing.
来源:Vib3Coded · x.com