惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

TaoSecurity Blog
TaoSecurity Blog
L
LINUX DO - 最新话题
Help Net Security
Help Net Security
N
News | PayPal Newsroom
www.infosecurity-magazine.com
www.infosecurity-magazine.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
The Last Watchdog
The Last Watchdog
S
Security @ Cisco Blogs
W
WeLiveSecurity
C
CXSECURITY Database RSS Feed - CXSecurity.com
Webroot Blog
Webroot Blog
T
Troy Hunt's Blog
V
Vulnerabilities – Threatpost
Google Online Security Blog
Google Online Security Blog
N
News and Events Feed by Topic
T
Threat Research - Cisco Blogs
Security Archives - TechRepublic
Security Archives - TechRepublic
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tor Project blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
D
Darknet – Hacking Tools, Hacker News & Cyber Security
PCI Perspectives
PCI Perspectives
Google DeepMind News
Google DeepMind News
T
Tailwind CSS Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Apple Machine Learning Research
Apple Machine Learning Research
IT之家
IT之家
S
SegmentFault 最新的问题
J
Java Code Geeks
P
Privacy & Cybersecurity Law Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园 - 【当耐特】
博客园_首页
H
Hacker News: Front Page
T
Threatpost
Jina AI
Jina AI
博客园 - Franky
月光博客
月光博客
L
LINUX DO - 热门话题
The Cloudflare Blog
H
Heimdal Security Blog
博客园 - 司徒正美
酷 壳 – CoolShell
酷 壳 – CoolShell
Cloudbric
Cloudbric
雷峰网
雷峰网
Hugging Face - Blog
Hugging Face - Blog
S
Secure Thoughts
T
Tenable Blog
I
Intezer
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
600 Snakes on the Edge: How I Built a Slither.io Server with Trail Algorithms, Spatial Hashing & Bot AI
monkeymore s · 2026-05-11 · via DEV Community

I spent one week building a multiplayer Slither.io clone. The server runs on PartyKit + TypeScript, the client on Phaser 3 + React. Honestly the code is far from perfect — there are hard-coded magic numbers, TODO comments, and parts I would definitely refactor if I had more time — but it works. One room supports 600 snakes (100 real players + 500 bots) and the latency feels fine.

This post is about the core algorithms and the bugs I stepped on.


1. Why PartyKit?

I initially wanted to write the server with plain Node.js + WebSocket, but deployment and horizontal scaling looked like a nightmare. Then I found PartyKit. It compiles to Cloudflare Workers / Durable Objects, so each room is a single Durable Object with all state in memory. No Redis, no database, no ops headache. For a one-week side project, that was perfect.

My goal: one room, 100 human players + 500 AI bots, on a 16,000 × 16,000 world. Not huge, but not tiny either — one sloppy algorithm and the event loop stutters, sending every snake teleporting forward.

I gave myself three hard constraints:

  • Authoritative server: All movement, collision, and scoring computed server-side. The client only renders.
  • Low bandwidth: Cannot broadcast full state every tick or 600 entities would saturate the pipe.
  • Client-prediction friendly: The server must tolerate small client-side prediction errors, or players will scream "I clearly ate that!"

2. Fixed-Timestep Game Loop: Why I Cap maxSteps at 3

My first game loop was naive: setInterval(() => tick(), 16). During testing I noticed that whenever the event loop hiccuped — garbage collection, a burst of messages — deltaTime would balloon to 100 ms and tick() would fire six times in a row. The snakes would lurch forward in a sickening speed-up. Players hated it.

I switched to a semi-fixed timestep:

fixedTimeStep = 1000 / 60  16.667 ms
maxStepsPerFrame = 3

function runGameLoop():
    now = currentTime()
    deltaTime = now - lastTickTime
    lastTickTime = now
    elapsedTime += deltaTime

    steps = 0
    while elapsedTime >= fixedTimeStep and steps < maxStepsPerFrame:
        elapsedTime -= fixedTimeStep
        fixedTick(fixedTimeStep)
        steps += 1

    schedule next runGameLoop after fixedTimeStep

Enter fullscreen mode Exit fullscreen mode

Why cap maxSteps?

Without the cap, an event-loop stall causes the server to simulate a dozen frames at once. The snakes teleport. I set the cap to 3 steps (~50 ms of catch-up). I would rather drop temporal accuracy than let players see that teleport.

Here is the full loop flow:

Per-Tick Pipeline (fixedTick)

Phase Description
1. Bot AI update Every 3rd tick (20 Hz) to save CPU
2. Snake movement Process input queues, advance trail, update segments
3. Collision detection Spatial-grid broadphase + narrowphase
4. Food physics Apply magnetic attraction velocities
5. Bot lifecycle Spawn, respawn check every 5 s
6. State broadcast Every 3rd tick (~50 ms)


3. Snake Movement: The Trail-Following Algorithm I'm Most Proud Of

My first idea was to simulate every body segment as an independent rigid body — head pulls segment 1, segment 1 pulls segment 2, and so on. It failed for two reasons: 400 segments per snake crushed the CPU, and the body would glitch out — snapping, bunching, occasionally detaching.

Then I flipped the problem: simulate only the head, derive the entire body from a history trail.

Data Structures

class ServerSnake {
  x, y: number;           // Head position
  angle: number;          // Heading in radians
  trail: Vector2[];       // Dense history of head positions
  segmentsX: number[];    // Derived body segment X positions
  segmentsY: number[];    // Derived body segment Y positions
  bodySegments: number;   // Count of visible segments
}

Enter fullscreen mode Exit fullscreen mode

  • trail is a dense array of head positions sampled every TRAIL_STEP = 2 pixels.
  • segmentsX/Y are not independently simulated — they are read-only lookups into the trail.

Head Movement

Each tick the head moves forward based on its angle:

speed = isBoosting ? BOOST_SPEED(380) : BASE_SPEED(180)  // px/s
vx = cos(angle) * speed * dt
vy = sin(angle) * speed * dt
newHeadX = x + vx
newHeadY = y + vy

Enter fullscreen mode Exit fullscreen mode

Trail Recording with Linear Interpolation

When the head moves farther than TRAIL_STEP, I interpolate intermediate points so the trail stays uniformly spaced:

distMoved = distance(lastHeadPosition, newHeadPosition)
if distMoved >= TRAIL_STEP:
    steps = floor(distMoved / TRAIL_STEP)
    for i = 1 to steps:
        t = i / steps
        interX = lastHeadPosition.x + (newHeadX - lastHeadPosition.x) * t
        interY = lastHeadPosition.y + (newHeadY - lastHeadPosition.y) * t
        trail.unshift({x: interX, y: interY})   // newest at front

    lastHeadPosition = {x: newHeadX, y: newHeadY}

    // Trim to prevent memory leaks
    maxPoints = (bodySegments + 2) * (SEGMENT_DISTANCE / TRAIL_STEP)
    if trail.length > maxPoints:
        trail.splice(maxPoints)

Enter fullscreen mode Exit fullscreen mode

Interpolation is critical. Without it, high-speed movement lets the head outrun the body, creating visible gaps.

Segment Derivation

Body segments sample the trail at fixed intervals:

pointsPerSegment = SEGMENT_DISTANCE / TRAIL_STEP   // 10 / 2 = 5
for i = 0 to bodySegments - 1:
    trailIndex = floor((i + 1) * pointsPerSegment)
    segmentsX[i] = trail[trailIndex].x
    segmentsY[i] = trail[trailIndex].y

Enter fullscreen mode Exit fullscreen mode

Segment 0 is the neck, the last segment is the tail. Because the trail is dense and pre-interpolated, the body follows the head with zero additional physics.

Growth & Shrinking

When a snake eats food or boosts, bodySegments changes. I reconcile the trail length like this:

newSegments = calculateBodySegments(score)
newRadius   = calculateSnakeRadius(newSegments)

// Extend trail if needed
pointsNeeded = (newSegments + 2) * (SEGMENT_DISTANCE / TRAIL_STEP)
while trail.length < pointsNeeded:
    trail.push(copy of last trail point)

// Extend segment arrays
while segmentsX.length < newSegments:
    segmentsX.push(lastTrailPoint.x)
    segmentsY.push(lastTrailPoint.y)

Enter fullscreen mode Exit fullscreen mode

New segments spawn at the tail position, so the snake visibly grows from the back.

The complete movement flow:


4. Spatial-Grid Collision: How I Dropped O(n²) to O(n)

Brute-force snake-to-snake collision for 600 snakes is 180,000 checks per tick — instant death.

I implemented a uniform spatial grid for broadphase culling.

Grid Construction

gridSize = 200 px
grid: Map<string, Snake[]>   // key = "gridX,gridY"

for each snake:
    if not alive: continue
    gridX = floor(snake.x / gridSize)
    gridY = floor(snake.y / gridSize)
    key = "${gridX},${gridY}"
    grid[key].push(snake)

Enter fullscreen mode Exit fullscreen mode

Neighbor Query Only

For each snake I only check the same cell plus the 8 adjacent cells:

for each cell in grid:
    for each snake in cell:
        checkFoodCollisions(snake)

        gx, gy = parse cell key
        for dx = -1 to 1:
            for dy = -1 to 1:
                neighborKey = "${gx+dx},${gy+dy}"
                for other in grid[neighborKey]:
                    if other != snake and other.isAlive:
                        checkSnakeCollision(snake, other)

        // World boundary
        if snake.x < 0 or snake.x > mapWidth or snake.y < 0 or snake.y > mapHeight:
            handleSnakeDeath(snake)

Enter fullscreen mode Exit fullscreen mode

On a 16,000×16,000 map with 200 px cells there are 6,400 cells. With 600 snakes, most cells hold 0 or 1 snake. The inner loop runs in effectively O(n).

Narrowphase: Snake vs. Snake

The collision shape is the head circle tested against all opponent segment circles:

segments = [{x: other.x, y: other.y}]   // opponent head
for i = 0 to other.bodySegments - 1:
    segments.push({x: other.segmentsX[i], y: other.segmentsY[i]})

collisionDist = snake.radius + other.radius - 5   // 5px forgiveness
for segment in segments:
    dist = distance(snake.head, segment)
    if dist < collisionDist:
        handleSnakeDeath(snake)
        return

Enter fullscreen mode Exit fullscreen mode

That -5 is my forgiveness margin. Without it, network jitter causes false-positive deaths and players rage-quit.

Full collision flow:

Food Collision & Magnetic Attraction

I skipped spatial partitioning for food. There are only 1,600 items, so O(1,600) per snake per tick is ~1M distance checks — well within what a PartyKit Durable Object can handle.

The magnetic attraction uses linear attenuation:

attractSpeed = 150 * (1 - dist / (snake.radius * 6))

Enter fullscreen mode Exit fullscreen mode

Strongest at contact, zero at 6×radius. It feels great and costs almost nothing.


5. Bot AI: Keeping 500 Bots from Melting the CPU

I needed bots to fill rooms and give human players targets. The AI had to be stupidly cheap because 500 bots updating at 20 Hz adds up fast.

State Machine

Two states:

  • WANDERING — pick a random target, steer toward it
  • AVOIDING — threat within 150 px, steer away

Target Selection

margin = 200 px
targetX = margin + random() * (WORLD_SIZE - margin * 2)
targetY = margin + random() * (WORLD_SIZE - margin * 2)
changeTargetTimer = 3000 + random() * 4000 ms

Enter fullscreen mode Exit fullscreen mode

Threat Detection

for each otherSnake in world:
    if otherSnake == this or not alive: continue
    dist = distance(this.head, otherSnake.head)
    if dist < 150:
        threatAngle = atan2(this.y - otherSnake.y, this.x - otherSnake.x)
        state = AVOIDING
        avoidTimer = 1000 ms

Enter fullscreen mode Exit fullscreen mode

Only head-to-head distance. Bots do not anticipate body collisions — too expensive.

Smooth Steering

angleDiff = targetAngle - currentAngle
while angleDiff > PI:  angleDiff -= 2*PI
while angleDiff < -PI: angleDiff += 2*PI

maxTurn = 3 * dt
angleDiff = clamp(angleDiff, -maxTurn, maxTurn)
currentAngle += angleDiff

Enter fullscreen mode Exit fullscreen mode

The ±2π wrap and turn-rate clamp were deliberate. Without them bots snap-turn instantly and look fake.

Boosting

shouldBoost = random() < 0.05

Enter fullscreen mode Exit fullscreen mode

Completely random. I added BOOST_MIN_SCORE = 20 so bots don't boost themselves to death immediately after spawn.

Bot decision flow:


6. Growth & Scoring Formulas

Constant Value Meaning
INITIAL_SNAKE_LENGTH 20 Segments at spawn
MAX_BODY_SEGMENTS 400 Hard cap
POINTS_PER_SEGMENT 10 Score per +1 segment
INITIAL_RADIUS 14 px Base thickness
MAX_RADIUS 30 px Thickness cap
RADIUS_GROWTH_INTERVAL 30 segments +1 radius every N

Score → Segments

segments = INITIAL_SNAKE_LENGTH + floor(score / POINTS_PER_SEGMENT)
segments = min(segments, MAX_BODY_SEGMENTS)

Enter fullscreen mode Exit fullscreen mode

Segments → Radius

growth = floor(segments / RADIUS_GROWTH_INTERVAL)
radius = min(INITIAL_RADIUS + growth, MAX_RADIUS)

Enter fullscreen mode Exit fullscreen mode

Boost Cost: Why I Use an Accumulator

My first attempt was score -= 15 * dt. Floating-point drift gave ugly decimal scores. I switched to an accumulator:

boostCostAccumulator += dt * BOOST_COST_PER_SECOND
if boostCostAccumulator >= 1:
    cost = floor(boostCostAccumulator)
    score = max(0, score - cost)
    boostCostAccumulator -= cost
    updateBody()

Enter fullscreen mode Exit fullscreen mode

Now the score stays integer-clean.


7. Networking: The Compromises I Made for Client Prediction

Input Queue

The client sends inputs as fast as it wants. The server queues them:

snake.inputQueue.push({ angle, boosting })
while (input = snake.inputQueue.shift()) {
    snake.angle = input.angle;
    snake.isBoosting = input.boosting;
}

Enter fullscreen mode Exit fullscreen mode

If two inputs arrive in the same tick window, the queue preserves order.

Lenient Food Validation

The client predicts eating food and hides it immediately. To avoid feeling laggy, I accept eat_food messages with a relaxed radius:

maxEatDist = snake.radius + food.size + 60   // +60 px leniency
if dist < maxEatDist:
    approve eat

Enter fullscreen mode Exit fullscreen mode

That +60 is a deliberate anti-cheat compromise. Smooth gameplay beats strict validation in this genre.

Broadcast Throttling

Full state every tick would saturate bandwidth. I broadcast every 3rd tick (~50 ms, 20 Hz):

broadcastCounter++
if broadcastCounter % 3 === 0:
    room.broadcast(JSON.stringify({...}))

Enter fullscreen mode Exit fullscreen mode

At 20 Hz with ~600 entities, payload is roughly 100–300 KB/s per client — comfortable for WebSocket.

Client-server message flow:


8. Performance Numbers

Metric Configuration Cost
Game tick 60 Hz fixed
Broadcast 20 Hz
Bot AI 20 Hz 500 bots × O(n) scan
Collision grid 200 px O(n) average
Max players 100 + 500 bots
World 16,000 × 16,000
Trail resolution 2 px/step ~20K points max-length snake

9. One Week Later: What I Learned

The code works, but looking back there is plenty I would refactor:

  1. Trail-based movement beats rigid-body chains. Simulate one head, look up the body from history. Zero physics glitches, tiny CPU cost. This is the design decision I'm happiest with.
  2. Spatial hashing is non-negotiable. My first O(n²) brute-force version choked at 50 snakes. The grid dropped it to effectively linear.
  3. The maxSteps cap saved the feel. Event-loop stalls are real. Cap at 3, swallow the time debt, never let snakes teleport.
  4. Be lenient with clients. +60px eat radius, loose validation — players notice lag way more than they notice mild server-side forgiveness.
  5. Dumb AI scales. 500 bots running A* would melt the CPU. Random wander + flee is indistinguishable to most players and costs nothing.

Deployment is one command: npx partykit deploy. Global edge nodes in seconds. If you want to ship a playable multiplayer game in a week, PartyKit removes a mountain of infrastructure work.

Want to try it yourself? Head over to Hi! Snake and see how long you can survive against 500 bots.