Compare commits

...

17 Commits

Author SHA1 Message Date
semantic-release-bot
325daeb0d9 chore(release): 4.4.10 [skip ci]
## [4.4.10](https://github.com/antialias/soroban-abacus-flashcards/compare/v4.4.9...v4.4.10) (2025-10-17)

### Bug Fixes

* **complement-race:** correct passenger boarding to use multiplayer fields ([7ed1b94](7ed1b94b8f))
2025-10-17 13:07:12 +00:00
Thomas Hallock
7ed1b94b8f fix(complement-race): correct passenger boarding to use multiplayer fields
Passengers weren't boarding because the arcade room version was still checking for single-player fields (isBoarded/isDelivered) instead of multiplayer fields (claimedBy/deliveredBy).

Changes:
- Update useSteamJourney to check claimedBy/deliveredBy instead of isBoarded/isDelivered
- Update Validator to skip position validation in sprint mode (position is client-side)
- Trust client-side spatial checking for boarding/delivery in sprint mode

Sprint mode architecture:
- Client (useSteamJourney) continuously checks if train is at stations
- Client sends CLAIM_PASSENGER / DELIVER_PASSENGER moves when conditions met
- Server validates passenger availability (not position, since position is client-side)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 08:06:06 -05:00
semantic-release-bot
43f1f92900 chore(release): 4.4.9 [skip ci]
## [4.4.9](https://github.com/antialias/soroban-abacus-flashcards/compare/v4.4.8...v4.4.9) (2025-10-17)

### Bug Fixes

* **complement-race:** reduce initial momentum from 50 to 10 to prevent train sailing past first station ([5f146b0](5f146b0daf))
2025-10-17 12:58:50 +00:00
Thomas Hallock
5f146b0daf fix(complement-race): reduce initial momentum from 50 to 10 to prevent train sailing past first station
The train was starting with too much momentum (50), causing it to sail past the first station without requiring user input. Reduced to 10 for a gentle push that still requires player engagement.

Changes:
- Reduce initial momentum from 50 to 10 in all three locations:
  - Initial state (useState)
  - Game start initialization
  - Route reset when advancing to next route
- Update pressure calculation to match new starting momentum

With momentum=10: speed = 1.5% per second (gentle start requiring answers to progress)
vs momentum=50: speed = 7.5% per second (too aggressive, reaches station without input)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 07:57:56 -05:00
semantic-release-bot
734da610b7 chore(release): 4.4.8 [skip ci]
## [4.4.8](https://github.com/antialias/soroban-abacus-flashcards/compare/v4.4.7...v4.4.8) (2025-10-17)

### Bug Fixes

* **complement-race:** implement client-side momentum with continuous decay for smooth train movement ([ea19ff9](ea19ff918b))
2025-10-17 12:51:40 +00:00
Thomas Hallock
ea19ff918b fix(complement-race): implement client-side momentum with continuous decay for smooth train movement
Fixes train jumping backward and pressure not decaying to zero in sprint mode by moving momentum/position/pressure tracking entirely to the client.

Changes:
- Remove momentum/pressure from server PlayerState type (sprint mode only)
- Remove all momentum updates from Validator (server tracks only scoring)
- Add client-side momentum state with 50ms game loop for smooth 20fps movement
- Implement continuous momentum decay based on skill level (2.0-13.0/sec)
- Calculate position and pressure client-side from momentum
- Handle answer boosts (+15 correct, -10 wrong) in client

This matches the arcade room's event-driven architecture where visual elements are client-side and the server maintains authoritative game state (score, streak, passengers).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 07:50:45 -05:00
semantic-release-bot
ea1e548e61 chore(release): 4.4.7 [skip ci]
## [4.4.7](https://github.com/antialias/soroban-abacus-flashcards/compare/v4.4.6...v4.4.7) (2025-10-17)

### Bug Fixes

* **complement-race:** add missing useRef import ([d43829a](d43829ad48))
2025-10-17 12:32:46 +00:00
Thomas Hallock
d43829ad48 fix(complement-race): add missing useRef import
- TypeScript error: Cannot find name 'useRef'
- Added useRef to React imports in Provider.tsx

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 07:31:43 -05:00
semantic-release-bot
dbcedb7144 chore(release): 4.4.6 [skip ci]
## [4.4.6](https://github.com/antialias/soroban-abacus-flashcards/compare/v4.4.5...v4.4.6) (2025-10-17)

### Bug Fixes

* **complement-race:** restore smooth train movement with client-side game loop ([46a80cb](46a80cbcc8))
2025-10-17 12:30:51 +00:00
Thomas Hallock
46a80cbcc8 fix(complement-race): restore smooth train movement with client-side game loop
**Problem**: Train was jumping discretely on each answer instead of moving smoothly

**Root Cause**: Ported incorrectly - position updated on answer submission instead of continuously

**Original Mechanics** (from useSteamJourney.ts):
- 50ms game loop (20fps) runs continuously
- Position calculated from momentum: `position += (momentum * 0.15 * deltaTime) / 1000`
- Pressure calculated from momentum: `pressure = (momentum / 100) * 150` (0-150 PSI)
- Answers only affect momentum (+15 correct, -10 wrong)

**Fixed Implementation**:
- Client-side game loop at 50ms interval
- Position calculated continuously from server momentum
- Pressure calculated continuously from momentum (0-150 PSI)
- Server only tracks momentum (authoritative)
- Removed discrete position jumps from Validator
- Position/pressure are derived values, not stored

**Files Changed**:
- Provider.tsx: Added client game loop, use calculated position/pressure
- Validator.ts: Removed position updates, only track momentum
- types.ts: Removed pressure field (calculated client-side)

This matches the original smooth movement behavior.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 07:29:34 -05:00
semantic-release-bot
5d89ad7ada chore(release): 4.4.5 [skip ci]
## [4.4.5](https://github.com/antialias/soroban-abacus-flashcards/compare/v4.4.4...v4.4.5) (2025-10-17)

### Bug Fixes

* **complement-race:** add missing useEffect import ([3054130](30541304dd))
2025-10-17 12:24:38 +00:00
Thomas Hallock
30541304dd fix(complement-race): add missing useEffect import
- Runtime error: useEffect is not defined
- Added useEffect to React imports in Provider.tsx

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 07:23:39 -05:00
semantic-release-bot
376c8eb901 chore(release): 4.4.4 [skip ci]
## [4.4.4](https://github.com/antialias/soroban-abacus-flashcards/compare/v4.4.3...v4.4.4) (2025-10-17)

### Bug Fixes

* **complement-race:** add pressure decay system and improve logging ([66992e8](66992e8770))
2025-10-17 12:23:29 +00:00
Thomas Hallock
66992e8770 fix(complement-race): add pressure decay system and improve logging
**1. Smart Logging (event-based instead of frame-based)**
- Only logs on answer submission, not every frame
- Format: "🚂 Answer #X: momentum=Y pos=Z pressure=P streak=S"
- Prevents console overflow in real-time game

**2. Pressure Decay System**
- Added `pressure` field to PlayerState type
- Pressure now independent from momentum (was stuck at 100)
- Correct answer: +20 pressure (add steam)
- Wrong answer: +5 pressure (less steam)
- Decay: -8 pressure per answer (steam escapes over time)
- Range: 0-100 with min/max caps

**3. Implementation**
- types.ts: Added pressure field to PlayerState
- Validator.ts: Initialize pressure=60, update with decay
- Provider.tsx: Use actual pressure from server (not calculated)
- Route reset: Reset pressure to 60 on new routes

This fixes the pressure gauge being pinned at 100 constantly.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 07:22:37 -05:00
semantic-release-bot
52019a24c2 chore(release): 4.4.3 [skip ci]
## [4.4.3](https://github.com/antialias/soroban-abacus-flashcards/compare/v4.4.2...v4.4.3) (2025-10-17)

### Bug Fixes

* **complement-race:** train now moves in sprint mode ([54b46e7](54b46e771e))

### Code Refactoring

* simplify train debug logs to strings only ([334a49c](334a49c92e))
2025-10-17 12:15:31 +00:00
Thomas Hallock
54b46e771e fix(complement-race): train now moves in sprint mode
**THE BUG**: Validator was only updating momentum in Sprint mode,
but NEVER updating position! This caused trainPosition to stay at 0.

**THE FIX**: Added position calculation based on momentum:
- moveDistance = momentum / 20
- Starting momentum (50) → 2.5 units per answer
- Max momentum (100) → 5 units per answer
- Creates progression: higher momentum = faster train movement

Position updates per answer now work:
- Correct answer: momentum +15, then position +=(momentum/20)
- Wrong answer: momentum -10, then position +=(momentum/20)
- Position capped at 100 (end of route)

This matches the original single-player behavior where the train
speed was tied to momentum.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-17 07:14:30 -05:00
Thomas Hallock
334a49c92e refactor: simplify train debug logs to strings only
Changed from logging objects to simple string format:
- Before: { momentum: 50, trainPosition: 0, pressure: 60, ... }
- After: Sprint: momentum=50 pos=0 pressure=60

Issue identified from logs: trainPosition stuck at 0!
This is why train isn't appearing/moving.
2025-10-17 07:13:24 -05:00
8 changed files with 266 additions and 69 deletions

View File

@@ -1,3 +1,64 @@
## [4.4.10](https://github.com/antialias/soroban-abacus-flashcards/compare/v4.4.9...v4.4.10) (2025-10-17)
### Bug Fixes
* **complement-race:** correct passenger boarding to use multiplayer fields ([7ed1b94](https://github.com/antialias/soroban-abacus-flashcards/commit/7ed1b94b8fa620cb4f64ba43e160ef511704f3ce))
## [4.4.9](https://github.com/antialias/soroban-abacus-flashcards/compare/v4.4.8...v4.4.9) (2025-10-17)
### Bug Fixes
* **complement-race:** reduce initial momentum from 50 to 10 to prevent train sailing past first station ([5f146b0](https://github.com/antialias/soroban-abacus-flashcards/commit/5f146b0daf74d54e1c7b9a57d3a2f37e73849ff2))
## [4.4.8](https://github.com/antialias/soroban-abacus-flashcards/compare/v4.4.7...v4.4.8) (2025-10-17)
### Bug Fixes
* **complement-race:** implement client-side momentum with continuous decay for smooth train movement ([ea19ff9](https://github.com/antialias/soroban-abacus-flashcards/commit/ea19ff918bc70ad3eb0339e18dbd32195f34816e))
## [4.4.7](https://github.com/antialias/soroban-abacus-flashcards/compare/v4.4.6...v4.4.7) (2025-10-17)
### Bug Fixes
* **complement-race:** add missing useRef import ([d43829a](https://github.com/antialias/soroban-abacus-flashcards/commit/d43829ad48f7ee879a46879f5e6ac1256db1f564))
## [4.4.6](https://github.com/antialias/soroban-abacus-flashcards/compare/v4.4.5...v4.4.6) (2025-10-17)
### Bug Fixes
* **complement-race:** restore smooth train movement with client-side game loop ([46a80cb](https://github.com/antialias/soroban-abacus-flashcards/commit/46a80cbcc8ec39224d4edaf540da25611d48fbdd))
## [4.4.5](https://github.com/antialias/soroban-abacus-flashcards/compare/v4.4.4...v4.4.5) (2025-10-17)
### Bug Fixes
* **complement-race:** add missing useEffect import ([3054130](https://github.com/antialias/soroban-abacus-flashcards/commit/30541304dd0f0801860dd62967f7f7cae717bcdd))
## [4.4.4](https://github.com/antialias/soroban-abacus-flashcards/compare/v4.4.3...v4.4.4) (2025-10-17)
### Bug Fixes
* **complement-race:** add pressure decay system and improve logging ([66992e8](https://github.com/antialias/soroban-abacus-flashcards/commit/66992e877065a42d00379ef8fae0a6e252b0ffcb))
## [4.4.3](https://github.com/antialias/soroban-abacus-flashcards/compare/v4.4.2...v4.4.3) (2025-10-17)
### Bug Fixes
* **complement-race:** train now moves in sprint mode ([54b46e7](https://github.com/antialias/soroban-abacus-flashcards/commit/54b46e771e654721e7fabb1f45ecd45daf8e447f))
### Code Refactoring
* simplify train debug logs to strings only ([334a49c](https://github.com/antialias/soroban-abacus-flashcards/commit/334a49c92e112c852c483b5dbe3a3d0aef8a5c03))
## [4.4.2](https://github.com/antialias/soroban-abacus-flashcards/compare/v4.4.1...v4.4.2) (2025-10-17)

View File

@@ -5,7 +5,6 @@ import { useComplementRace } from '@/arcade-games/complement-race/Provider'
import { useAdaptiveDifficulty } from '../hooks/useAdaptiveDifficulty'
import { useAIRacers } from '../hooks/useAIRacers'
import { useSoundEffects } from '../hooks/useSoundEffects'
import { useSteamJourney } from '../hooks/useSteamJourney'
import { generatePassengers } from '../lib/passengerGenerator'
import { AbacusTarget } from './AbacusTarget'
import { CircularTrack } from './RaceTrack/CircularTrack'
@@ -16,10 +15,9 @@ import { RouteCelebration } from './RouteCelebration'
type FeedbackAnimation = 'correct' | 'incorrect' | null
export function GameDisplay() {
const { state, dispatch } = useComplementRace()
const { state, dispatch, boostMomentum } = useComplementRace()
useAIRacers() // Activate AI racer updates (not used in sprint mode)
const { trackPerformance, getAdaptiveFeedbackMessage } = useAdaptiveDifficulty()
const { boostMomentum } = useSteamJourney()
const { playSound } = useSoundEffects()
const [feedbackAnimation, setFeedbackAnimation] = useState<FeedbackAnimation>(null)
@@ -109,7 +107,7 @@ export function GameDisplay() {
// Boost momentum for sprint mode
if (state.style === 'sprint') {
boostMomentum()
boostMomentum(true)
// Play train whistle for milestones in sprint mode (line 13222-13235)
if (newStreak >= 5 && newStreak % 3 === 0) {
@@ -144,6 +142,11 @@ export function GameDisplay() {
// Play incorrect sound (from web_generator.py line 11589)
playSound('incorrect')
// Reduce momentum for sprint mode
if (state.style === 'sprint') {
boostMomentum(false)
}
// Show adaptive feedback
const feedback = getAdaptiveFeedbackMessage(pairKey, false, responseTime)
if (feedback) {

View File

@@ -93,23 +93,10 @@ export function SteamTrainJourney({
currentQuestion,
currentInput,
}: SteamTrainJourneyProps) {
console.log('🚂 [SteamTrainJourney] Render:', {
momentum,
trainPosition,
pressure,
elapsedTime,
currentQuestion,
currentInput,
})
const { state } = useComplementRace()
console.log('🚂 [SteamTrainJourney] State from provider:', {
stations: state.stations,
passengers: state.passengers,
currentRoute: state.currentRoute,
gamePhase: state.gamePhase,
isGameActive: state.isGameActive,
})
console.log(
`🚂 Train: mom=${momentum} pos=${trainPosition} stations=${state.stations.length} passengers=${state.passengers.length}`
)
const { getSkyGradient, getTimeOfDayPeriod } = useSteamJourney()
const _skyGradient = getSkyGradient()

View File

@@ -114,7 +114,9 @@ export function useSteamJourney() {
const CAR_SPACING = 7 // Must match SteamTrainJourney component
const maxPassengers = calculateMaxConcurrentPassengers(state.passengers, state.stations)
const maxCars = Math.max(1, maxPassengers)
const currentBoardedPassengers = state.passengers.filter((p) => p.isBoarded && !p.isDelivered)
const currentBoardedPassengers = state.passengers.filter(
(p) => p.claimedBy !== null && p.deliveredBy === null
)
// Debug logging flag - enable when debugging passenger boarding issues
// TO ENABLE: Change this to true, save, and the logs will appear in the browser console
@@ -150,7 +152,7 @@ export function useSteamJourney() {
const dest = state.stations.find((s) => s.id === p.destinationStationId)
console.log(` [${idx}] ${p.name} (ID: ${p.id})`)
console.log(
` Status: ${p.isDelivered ? 'DELIVERED' : p.isBoarded ? 'BOARDED' : 'WAITING'}`
` Status: ${p.deliveredBy !== null ? 'DELIVERED' : p.claimedBy !== null ? 'BOARDED' : 'WAITING'}`
)
console.log(
` Route: ${origin?.emoji} ${origin?.name} (pos ${origin?.position}) → ${dest?.emoji} ${dest?.name} (pos ${dest?.position})`
@@ -180,7 +182,7 @@ export function useSteamJourney() {
// FIRST: Identify which passengers will be delivered in this frame
const passengersToDeliver = new Set<string>()
currentBoardedPassengers.forEach((passenger, carIndex) => {
if (!passenger || passenger.isDelivered) return
if (!passenger || passenger.deliveredBy !== null) return
const station = state.stations.find((s) => s.id === passenger.destinationStationId)
if (!station) return
@@ -232,7 +234,7 @@ export function useSteamJourney() {
// Find waiting passengers whose origin station has an empty car nearby
state.passengers.forEach((passenger) => {
if (passenger.isBoarded || passenger.isDelivered) return
if (passenger.claimedBy !== null || passenger.deliveredBy !== null) return
const station = state.stations.find((s) => s.id === passenger.originStationId)
if (!station) return
@@ -300,7 +302,7 @@ export function useSteamJourney() {
// Check for deliverable passengers
// Passengers disembark when THEIR car reaches their destination
currentBoardedPassengers.forEach((passenger, carIndex) => {
if (!passenger || passenger.isDelivered) return
if (!passenger || passenger.deliveredBy !== null) return
const station = state.stations.find((s) => s.id === passenger.destinationStationId)
if (!station) return
@@ -393,7 +395,8 @@ export function useSteamJourney() {
if (!state.isGameActive || state.style !== 'sprint') return
// Check if all passengers are delivered
const allDelivered = state.passengers.length > 0 && state.passengers.every((p) => p.isDelivered)
const allDelivered =
state.passengers.length > 0 && state.passengers.every((p) => p.deliveredBy !== null)
if (allDelivered) {
// Generate new passengers after a short delay

View File

@@ -5,7 +5,16 @@
'use client'
import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react'
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from 'react'
import {
type GameMove,
buildPlayerMetadata,
@@ -102,6 +111,7 @@ interface ComplementRaceContextValue {
setConfig: (field: keyof ComplementRaceConfig, value: unknown) => void
clearError: () => void
exitSession: () => void
boostMomentum: (correct: boolean) => void // Client-side momentum boost/reduce
}
const ComplementRaceContext = createContext<ComplementRaceContextValue | null>(null)
@@ -240,6 +250,32 @@ export function ComplementRaceProvider({ children }: { children: ReactNode }) {
})
}, [activePlayers, players])
// Debug logging ref (track last logged values)
const lastLogRef = useState({ key: '', count: 0 })[0]
// Client-side game state (NOT synced to server - purely visual/gameplay)
const [clientMomentum, setClientMomentum] = useState(10) // Start at 10 for gentle push
const [clientPosition, setClientPosition] = useState(0)
const [clientPressure, setClientPressure] = useState(0)
const lastUpdateRef = useRef(Date.now())
const gameStartTimeRef = useRef(0)
// Decay rates based on skill level (momentum lost per second)
const MOMENTUM_DECAY_RATES = {
preschool: 2.0,
kindergarten: 3.5,
relaxed: 5.0,
slow: 7.0,
normal: 9.0,
fast: 11.0,
expert: 13.0,
}
const MOMENTUM_GAIN_PER_CORRECT = 15
const MOMENTUM_LOSS_PER_WRONG = 10
const SPEED_MULTIPLIER = 0.15 // momentum * 0.15 = % per second
const UPDATE_INTERVAL = 50 // 50ms = ~20fps
// Transform multiplayer state to look like single-player state
const compatibleState = useMemo((): CompatibleGameState => {
const localPlayer = localPlayerId ? multiplayerState.players[localPlayerId] : null
@@ -303,10 +339,10 @@ export function ComplementRaceProvider({ children }: { children: ReactNode }) {
previousPosition: ai.position,
})),
// Sprint mode specific
momentum: localPlayer?.momentum || 0,
trainPosition: localPlayer?.position || 0,
pressure: localPlayer?.momentum ? Math.min(100, localPlayer.momentum + 10) : 0,
// Sprint mode specific (all client-side for smooth movement)
momentum: clientMomentum, // Client-only state with continuous decay
trainPosition: clientPosition, // Client-calculated from momentum
pressure: clientPressure, // Client-calculated from momentum (0-150 PSI)
elapsedTime: multiplayerState.gameStartTime ? Date.now() - multiplayerState.gameStartTime : 0,
lastCorrectAnswerTime: localPlayer?.lastAnswerTime || Date.now(),
currentRoute: multiplayerState.currentRoute,
@@ -328,16 +364,103 @@ export function ComplementRaceProvider({ children }: { children: ReactNode }) {
adaptiveFeedback: localUIState.adaptiveFeedback,
difficultyTracker: localUIState.difficultyTracker,
}
}, [multiplayerState, localPlayerId, localUIState])
}, [multiplayerState, localPlayerId, localUIState, clientPosition, clientPressure])
console.log('🚂 [Provider] Transformed sprint values:', {
momentum: compatibleState.momentum,
trainPosition: compatibleState.trainPosition,
pressure: compatibleState.pressure,
stations: compatibleState.stations?.length,
passengers: compatibleState.passengers?.length,
currentRoute: compatibleState.currentRoute,
})
// Initialize game start time when game becomes active
useEffect(() => {
if (compatibleState.isGameActive && compatibleState.style === 'sprint') {
if (gameStartTimeRef.current === 0) {
gameStartTimeRef.current = Date.now()
lastUpdateRef.current = Date.now()
// Reset client state for new game
setClientMomentum(10) // Start with gentle push
setClientPosition(0)
setClientPressure((10 / 100) * 150) // Initial pressure from starting momentum
}
} else {
// Reset when game ends
gameStartTimeRef.current = 0
}
}, [compatibleState.isGameActive, compatibleState.style])
// Main client-side game loop: momentum decay and position calculation
useEffect(() => {
if (!compatibleState.isGameActive || compatibleState.style !== 'sprint') return
const interval = setInterval(() => {
const now = Date.now()
const deltaTime = now - lastUpdateRef.current
lastUpdateRef.current = now
// Get decay rate based on skill level
const decayRate =
MOMENTUM_DECAY_RATES[compatibleState.timeoutSetting as keyof typeof MOMENTUM_DECAY_RATES] ||
MOMENTUM_DECAY_RATES.normal
setClientMomentum((prevMomentum) => {
// Calculate momentum decay for this frame
const momentumLoss = (decayRate * deltaTime) / 1000
// Update momentum (don't go below 0)
const newMomentum = Math.max(0, prevMomentum - momentumLoss)
// Calculate speed from momentum (% per second)
const speed = newMomentum * SPEED_MULTIPLIER
// Update position (accumulate, never go backward)
const positionDelta = (speed * deltaTime) / 1000
setClientPosition((prev) => prev + positionDelta)
// Calculate pressure (0-150 PSI)
const pressure = Math.min(150, (newMomentum / 100) * 150)
setClientPressure(pressure)
return newMomentum
})
}, UPDATE_INTERVAL)
return () => clearInterval(interval)
}, [
compatibleState.isGameActive,
compatibleState.style,
compatibleState.timeoutSetting,
MOMENTUM_DECAY_RATES,
SPEED_MULTIPLIER,
UPDATE_INTERVAL,
])
// Reset client position when route changes
useEffect(() => {
const currentRoute = multiplayerState.currentRoute
// When route changes, reset position and give starting momentum
if (currentRoute > 1 && compatibleState.style === 'sprint') {
setClientPosition(0)
setClientMomentum(10) // Reset to starting momentum (gentle push)
}
}, [multiplayerState.currentRoute, compatibleState.style])
// Debug logging: only log on answer submission or significant events
useEffect(() => {
if (compatibleState.style === 'sprint' && compatibleState.isGameActive) {
const key = `${compatibleState.correctAnswers}`
// Only log on new answers (not every frame)
if (lastLogRef.key !== key) {
console.log(
`🚂 Answer #${compatibleState.correctAnswers}: momentum=${compatibleState.momentum} pos=${Math.floor(compatibleState.trainPosition)} pressure=${compatibleState.pressure} streak=${compatibleState.streak}`
)
lastLogRef.key = key
}
}
}, [
compatibleState.correctAnswers,
compatibleState.momentum,
compatibleState.trainPosition,
compatibleState.pressure,
compatibleState.streak,
compatibleState.style,
compatibleState.isGameActive,
])
// Action creators
const startGame = useCallback(() => {
@@ -609,6 +732,22 @@ export function ComplementRaceProvider({ children }: { children: ReactNode }) {
]
)
// Client-side momentum boost/reduce (sprint mode only)
const boostMomentum = useCallback(
(correct: boolean) => {
if (compatibleState.style !== 'sprint') return
setClientMomentum((prevMomentum) => {
if (correct) {
return Math.min(100, prevMomentum + MOMENTUM_GAIN_PER_CORRECT)
} else {
return Math.max(0, prevMomentum - MOMENTUM_LOSS_PER_WRONG)
}
})
},
[compatibleState.style, MOMENTUM_GAIN_PER_CORRECT, MOMENTUM_LOSS_PER_WRONG]
)
const contextValue: ComplementRaceContextValue = {
state: compatibleState, // Use transformed state
dispatch,
@@ -624,6 +763,7 @@ export function ComplementRaceProvider({ children }: { children: ReactNode }) {
setConfig,
clearError,
exitSession,
boostMomentum, // Client-side momentum control
}
return (

View File

@@ -168,8 +168,7 @@ export class ComplementRaceValidator
bestStreak: 0,
correctAnswers: 0,
totalQuestions: 0,
position: 0,
momentum: 50, // Start with some momentum in sprint mode
position: 0, // Only used for practice/survival; sprint mode is client-side
isReady: false,
isActive: true,
currentAnswer: null,
@@ -317,12 +316,9 @@ export class ComplementRaceValidator
updatedPlayer.position = Math.min(100, player.position + 100 / state.config.raceGoal)
}
} else if (state.config.style === 'sprint') {
// Sprint: Update momentum
if (correct) {
updatedPlayer.momentum = Math.min(100, player.momentum + 15)
} else {
updatedPlayer.momentum = Math.max(0, player.momentum - 10)
}
// Sprint: All momentum/position handled client-side for smooth 20fps movement
// Server only tracks scoring, passengers, and game progression
// No server-side position updates needed
} else if (state.config.style === 'survival') {
// Survival: Always move forward, speed based on accuracy
const moveDistance = correct ? 5 : 2
@@ -418,15 +414,19 @@ export class ComplementRaceValidator
return { valid: false, error: 'Passenger already claimed' }
}
// Check if player is at the origin station (within 5% tolerance)
const originStation = state.stations.find((s) => s.id === passenger.originStationId)
if (!originStation) {
return { valid: false, error: 'Origin station not found' }
}
// Sprint mode: Position is client-side, trust client's spatial checking
// (Client checks position in useSteamJourney before sending CLAIM move)
// Other modes: Validate position server-side
if (state.config.style !== 'sprint') {
const originStation = state.stations.find((s) => s.id === passenger.originStationId)
if (!originStation) {
return { valid: false, error: 'Origin station not found' }
}
const distance = Math.abs(player.position - originStation.position)
if (distance > 5) {
return { valid: false, error: 'Not at origin station' }
const distance = Math.abs(player.position - originStation.position)
if (distance > 5) {
return { valid: false, error: 'Not at origin station' }
}
}
// Claim passenger
@@ -481,15 +481,19 @@ export class ComplementRaceValidator
return { valid: false, error: 'Passenger already delivered' }
}
// Check if player is at destination station (within 5% tolerance)
const destStation = state.stations.find((s) => s.id === passenger.destinationStationId)
if (!destStation) {
return { valid: false, error: 'Destination station not found' }
}
// Sprint mode: Position is client-side, trust client's spatial checking
// (Client checks position in useSteamJourney before sending DELIVER move)
// Other modes: Validate position server-side
if (state.config.style !== 'sprint') {
const destStation = state.stations.find((s) => s.id === passenger.destinationStationId)
if (!destStation) {
return { valid: false, error: 'Destination station not found' }
}
const distance = Math.abs(player.position - destStation.position)
if (distance > 5) {
return { valid: false, error: 'Not at destination station' }
const distance = Math.abs(player.position - destStation.position)
if (distance > 5) {
return { valid: false, error: 'Not at destination station' }
}
}
// Deliver passenger and award points
@@ -522,12 +526,12 @@ export class ComplementRaceValidator
return { valid: false, error: 'Routes only available in sprint mode' }
}
// Reset all player positions to 0
// Reset all player positions to 0 for new route (client handles momentum reset)
const resetPlayers: Record<string, PlayerState> = {}
for (const [playerId, player] of Object.entries(state.players)) {
resetPlayers[playerId] = {
...player,
position: 0,
position: 0, // Server position not used in sprint; client will reset
passengers: [], // Clear any remaining passengers
}
}

View File

@@ -61,8 +61,7 @@ export interface PlayerState {
totalQuestions: number
// Position & Progress
position: number // 0-100% for practice/sprint, lap count for survival
momentum: number // 0-100 (sprint mode only)
position: number // 0-100% for practice/survival only (sprint mode: client-side)
// Current state
isReady: boolean

View File

@@ -1,6 +1,6 @@
{
"name": "soroban-monorepo",
"version": "4.4.2",
"version": "4.4.10",
"private": true,
"description": "Beautiful Soroban Flashcard Generator - Monorepo",
"workspaces": [