Implement client-side prediction with input broadcasting

Reduces perceived lag over internet by broadcasting player inputs immediately
and predicting next positions on all clients before server update arrives.

Protocol changes:
- Added PLAYER_INPUT message type for broadcasting inputs
- Server broadcasts player inputs to all clients on every MOVE message
- Includes player_id, current direction, and full input_buffer (max 3)

Desktop client (Python):
- Tracks input buffers and predicted head positions for all players
- On PLAYER_INPUT: predicts next head position using buffered input
- On STATE_UPDATE: clears predictions, uses authoritative state
- Renderer draws predicted positions with darker color (60% brightness)

Web client (JavaScript):
- Same prediction logic as desktop client
- Added darkenColor() helper for visual differentiation
- Predicted heads shown at 60% brightness

Benefits:
- Instant visual feedback for own movements (no round-trip wait)
- See other players' inputs before server tick (better collision avoidance)
- Smooth experience bridging input-to-update gap
- Low bandwidth (only direction tuples, not full state)
- Backward compatible (server authoritative, old clients work)

All 39 tests passing.

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Vladyslav Doloman
2025-10-04 21:21:49 +03:00
parent ce492b0dc2
commit 4dbbf44638
7 changed files with 129 additions and 9 deletions

View File

@@ -59,13 +59,13 @@
<script src="protocol.js"></script>
<script src="game.js"></script>
<script>
// Auto-detect WebSocket URL
// Auto-detect WebSocket URL based on page hostname
const wsUrl = document.getElementById('server-url');
if (window.location.protocol === 'file:') {
wsUrl.value = 'ws://localhost:8889';
} else {
const host = window.location.hostname;
const port = window.location.port ? parseInt(window.location.port) + 889 : 8889;
const port = 8889; // Default WebSocket port
wsUrl.value = `ws://${host}:${port}`;
}
</script>