Snake Game: Play Free Online + Complete Strategy Guide

The Snake Game, Explained: History, Strategy, Scoring Maths and How We Rebuilt It for the Modern Web

Almost everyone reading this has played Snake. On a Nokia handset waiting for a bus. On a graphing calculator during a lesson that had stopped making sense. In a browser tab that was supposed to be a spreadsheet. It is one of the few video games that genuinely crosses generations, and it does it while asking almost nothing of you: four directions, one growing line, one piece of food.

That apparent simplicity is a trap, and it is the reason we spent so long rebuilding it. Snake looks like a beginner project. It is not. A Snake game that feels right — that never eats an input, never kills you for a turn you made correctly, never stutters, never gets easier or harder depending on your screen refresh rate — is a genuinely demanding piece of engineering. Most versions you find online get at least two of those wrong.

This article is the long version of everything we learned. It covers where Snake came from, what the rules actually mean, the exact mathematics behind the scoring in our version, the timing tables you need to play well, the strategies that separate a score of 200 from a score of 2,000, the surprising computer science hiding inside a 21×21 grid, and the engineering decisions that make the difference between a toy and a tool. If you only want to get better at the game, jump to the strategy section. If you want to understand it, start at the beginning.

What this guide covers

juego de la serpiente

The rules of Snake, and why they are so well designed

The complete ruleset of Snake fits in four sentences. You control a line made of connected cells. The head moves forward one cell at a time and never stops. You may steer it up, down, left or right, but never directly backwards into your own neck. When the head reaches a piece of food the snake grows by one cell and a new piece appears somewhere else; when the head hits a wall or any part of its own body, the run is over.

What makes this a great design rather than merely a simple one is the feedback loop. In almost every other arcade game, getting better at the game makes the game easier. In Snake, every success makes the next moment harder, because the reward is the obstacle. The apple you ate three minutes ago is now a wall you have to navigate around. Nothing else in early game design compressed risk and reward into a single object quite so cleanly.

There is a second, subtler piece of design at work. Because the snake never stops, you cannot pause to think inside the game world. Every second of hesitation is a cell of forward motion you did not plan. Snake is therefore not a reflex game pretending to be a puzzle; it is a puzzle game played at a fixed tempo, which is a much rarer and more interesting thing.

Finally, Snake has an almost perfect skill ramp. A complete beginner can survive thirty seconds and eat three apples. An experienced player can fill a third of the board. A player who understands the geometry can, in principle, fill the entire board. The distance between those outcomes is entirely knowledge and planning, not hardware, not luck, and not money.

A complete history of Snake: from Blockade to the modern browser

1976: Blockade, the ancestor nobody called Snake

The genre begins in November 1976 with an arcade cabinet called Blockade, developed at Gremlin Industries in San Diego and designed by Lane Hauck, with programming work by Ago Kiss. It was black and white, it was two-player, and the word "snake" appeared nowhere in it. Each player steered a marker around the screen with four directional buttons; the marker left a solid trail behind it, and the loser was whoever crashed into a wall or a trail first.

The idea reportedly grew out of Hauck experimenting in assembly language with a simple concept: a moving object that could never revisit a place it had already been. Gremlin showed it at the Music Operators of America expo in Chicago in 1976, where it was received extremely well — so well that several other manufacturers had their own versions on the market before Gremlin could ship in volume. The first great Snake game was cloned before it was even released.

1977 to 1982: the clone wave and the birth of single-player Snake

Atari released Surround for the Atari 2600 in 1977 as one of the console's launch titles; Sears sold the same game under the name Chase. On home computers, a version called Worm appeared on the TRS-80 in 1978, written by P. Trefonas and distributed through CLOAD magazine, with Commodore PET and Apple II versions following.

The decisive change came in December 1982, when Rock-Ola released Nibbler. This is the moment the genre becomes the game we recognise. Nibbler was single-player, it had thirty-two distinct mazes, and crucially it had food — the snake grew because you fed it, not merely because time passed. Almost every Snake game since is a descendant of Nibbler rather than of Blockade.

Nibbler also produced one of the greatest stories in arcade history. It was the first arcade game with a nine-digit score counter, meaning a score of one billion was theoretically possible, and Rock-Ola offered a free cabinet to the first player to roll it over. Tom Asaki came close at the Twin Galaxies arcade in Ottumwa, Iowa, once reaching 793 million before the joystick physically broke. In January 1984, Tim McVey played for more than forty hours on a single quarter and finished with 1,000,042,270 points — the first billion-point score in video game history. The city of Ottumwa declared 28 January 1984 "Tim McVey Day", making him the first video game player with a civic holiday named after him. The whole saga was later documented in the film Man vs Snake.

1991: Snake escapes into the operating system

When Microsoft shipped MS-DOS 5.0 in 1991, it included QBasic, and QBasic shipped with a sample program called NIBBLES.BAS. For a very large number of people who later became programmers, this was the first game whose source code they ever read. It is difficult to overstate how much that mattered: Snake became not just a game but the canonical "first real program", the thing you built to prove to yourself that you could build things.

Around the same period, Snake spread onto graphing calculators. The Texas Instruments machines that dominated classrooms had exactly enough screen and exactly enough processor to run it, and none of the distractions that would have made anything more ambitious worthwhile.

1997: the Nokia 6110, and the largest audience any game had ever had

In December 1997 Nokia launched the 6110, a business handset with a monochrome screen of just 84 by 48 pixels. Nokia's marketing team had asked a software engineer named Taneli Armanto to build a few small games for it. He produced three: Memory, Logic, and Snake.

Armanto designed within brutal constraints — two tones, dark pixels on a green-tinted LCD, a numeric keypad instead of a joystick, and a processor with nothing to spare. Those constraints are exactly why the game endured. There was nothing to strip away. Estimates put the original Snake on roughly 350 million devices; between 1997 and 2007 Nokia shipped over 400 million handsets with some version of it preloaded. For a stretch in the early 2000s, more people on Earth were playing Snake on a given day than any other video game.

One detail from Armanto's design deserves to be much better known, because we borrowed the philosophy behind it. He deliberately introduced a tiny delay immediately before a crash — a handful of milliseconds in which a late input could still save you. It is a small, humane piece of design that quietly acknowledges that the player is a human being with a nervous system, not a state machine.

Snake II arrived on the Nokia 3310 in 2000, on a handset that went on to sell more than 126 million units. It added the three features that most modern versions still copy: a wrapping playfield where you exit one edge and re-enter the opposite one, maze obstacles inside the arena, and time-limited bonus food worth extra points. Our Portal mode, Maze mode and golden berries are direct descendants of Snake II, and we say so happily.

2016 onwards: slither.io and the browser era

In March 2016 a self-taught developer named Steve Howse released slither.io for browsers, iOS and Android. It took the Snake concept, made it massively multiplayer, made the snakes smooth and curved rather than grid-locked, and inverted the core rule: you die when your head hits another player, but you may cross yourself freely. Promoted heavily by large YouTube channels, it topped the App Store, became one of the most visited websites on the web that summer, and passed a hundred million downloads on Android alone.

slither.io proved something important about the genre. Snake is not a specific game; it is a mechanic — a growing line that must not intersect anything — and that mechanic can carry an enormous range of designs. The classic grid version did not disappear; it simply became the "canonical" version that every browser games site, every search engine easter egg and every learn-to-code tutorial reaches for.

Timeline at a glance

Key milestones in the history of the Snake game genre
YearTitle or eventPlatformWhy it mattered
1976Blockade (Gremlin Industries, designed by Lane Hauck)ArcadeCreated the trail-that-kills-you mechanic; two-player only
1977Surround (also sold as Chase)Atari 2600Brought the concept into the home as a launch title
1978Worm by P. TrefonasTRS-80First widely circulated personal computer version
1982Nibbler (Rock-Ola)ArcadeSingle-player, food-driven growth, 32 mazes; the true template
1984Tim McVey scores 1,000,042,270 on NibblerArcadeFirst billion-point score in video game history
1991NIBBLES.BAS ships with QBasic in MS-DOS 5.0PCBecame the first game source code a generation ever read
1997Snake by Taneli ArmantoNokia 6110Roughly 350 million devices; started mobile gaming
2000Snake IINokia 3310Added wrapping edges, mazes and bonus food
2016slither.io by Steve HowseBrowser, iOS, AndroidMassively multiplayer reinvention; global phenomenon
TodayBrowser-native versions like this oneAny deviceNo install, no account, instant play, full accessibility

Inside our Snake game: what we built and why

Our version was built from scratch as a single self-contained file with no external libraries, no web fonts and no network requests. That constraint was deliberate. A game embedded inside an article has to load instantly, must never slow down the page it sits in, and must never break because a third-party server had a bad day.

Visually we went in a direction most Snake games do not. The default look for the genre is neon green on black — an arcade cliché that is easy to reach for and hard to make feel considered. We built a "vivarium" instead: a warm sand-coloured playfield inside a deep petrol-green shell, with a jade snake that has a tapered body, a proper head, eyes that track the direction of travel, and a tongue that flicks occasionally. The food is a berry with a stem and a highlight rather than a square.

The single biggest visual decision, though, is not a colour. It is motion. In most Snake implementations the snake teleports from cell to cell, because the renderer draws exactly the game state and the game state is a list of grid coordinates. Ours interpolates: between one logical move and the next, every segment slides smoothly from where it was to where it is going. The game logic is still a strict grid — that matters for fairness — but the presentation is continuous. It is the difference between a prototype and a product, and it costs perhaps thirty lines of code.

Feature summary

What the tool includes
AreaDetail
BoardFixed 21 × 21 grid (441 cells) at every screen size, so scores stay comparable
ModesWalls, Portal, Maze (five rotating maze layouts)
SpeedsCalm, Classic, Swift, Frantic — each with its own acceleration curve and floor
ScoringLevel bonus, combo multiplier up to five times, golden berries worth triple
RecordsBest score stored separately for each mode and speed combination
StatisticsGames played, berries eaten, longest snake, total time played
ControlsArrow keys, WASD, AZERTY keys, on-screen pad, and swipe gestures
DisplayLight and dark themes, true fullscreen with a two-column layout on wide screens
LanguagesEnglish, French, Spanish, Chinese, Hindi and Arabic with right-to-left support
AudioSynthesised tones generated in the browser, off by default, with haptic feedback on mobile
AccessibilityKeyboard operable, screen-reader announcements, reduced-motion support

Why the grid never changes size

This is the design decision we argued about most, so it deserves an explanation. Many browser Snake games scale the grid with the window: a bigger screen gets more cells. It looks generous. It is actually unfair, because it means a score of 500 on a phone and a score of 500 on a desktop are measuring different games. A larger board is easier — more room to manoeuvre, longer runway before your own tail becomes a problem.

We fixed the grid at 21 by 21 and scaled the cell size instead. On a phone each cell might be sixteen pixels; in fullscreen on a large monitor each cell can reach almost fifty. The board occupies whatever space is available, but the game is identical everywhere. Your personal best means the same thing on every device you own.

The choice of 21 rather than 20 was also deliberate: an odd number of rows and columns gives a true centre cell, which makes the starting position symmetric. As we will see later, it also has a genuinely interesting mathematical consequence.

The complete scoring reference

Everything in the scoring system uses integer arithmetic, which means every score is exactly reproducible and there are no floating-point surprises. Here is the whole system, written out.

The core equations

Every formula used by the game
QuantityEquationNotes
Levellevel = 1 + floor(berries ÷ 5)Berries counted since the run started
Base value of a berrybase = 10 + 2 × (level − 1)Rises by 2 points per level, forever
Combo multipliermultiplier = min(5, 1 + floor(chain ÷ 3))Chain resets if more than 5 seconds pass between berries
Points awardedgain = base × multiplier × goldgold = 3 for a golden berry, otherwise 1
Move intervalstep = max(floor, start − (level − 1) × decay)Milliseconds between logical moves
Snake speedcells per second = 1000 ÷ stepDirect conversion from the move interval
Board crossing timeseconds = 21 × step ÷ 1000Time to travel the full width of the board
Reaction distancecells = reaction time ÷ stepHow far the snake travels while you react
Snake lengthlength = 3 + berriesThe snake always starts three cells long

Constants at a glance

Fixed values that drive the whole game
ConstantValueEffect
Grid size21 × 21 = 441 cellsThe complete playfield
Starting length3 cellsHead plus two body segments
Base points10Value of a berry at level 1 with no combo
Level bonus+2 points per levelCompounds with the multiplier
Berries per level5Every 5 berries raises the level by 1
Combo window5,000 msMaximum gap between berries to keep a chain
Combo step3 berriesEvery 3 chained berries adds 1 to the multiplier
Combo ceiling×5The multiplier never exceeds five
Golden berry payout×3Applied on top of the combo multiplier
Golden berry lifetime7,000 msThen it fades away and is gone
Golden berry frequencyEvery 4th berryOnly when none is already on the board

Level progression

Berries required, snake length and berry value by level
LevelBerries eatenSnake lengthBase berry valueValue at ×5 comboGolden berry at ×5
10–43–71050150
25–98–121260180
310–1413–171470210
415–1918–221680240
520–2423–271890270
625–2928–3220100300
730–3433–3722110330
835–3938–4224120360
940–4443–4726130390
1045–4948–5228140420
1570–7473–7738190570
2095–9998–10248240720
30145–149148–152683401,020

The combo multiplier

The combo is the part of the scoring most players ignore, and it is worth more than everything else combined. Each berry eaten within five seconds of the previous one extends your chain. Every third berry in the chain raises the multiplier by one, up to five.

Combo chain length and the resulting multiplier
Berries in the current chainMultiplierBerry value at level 1Berry value at level 10
1st to 3rd×11028
4th to 6th×22056
7th to 9th×33084
10th to 12th×440112
13th and beyond×550140

Full points-per-berry matrix

Points for one ordinary berry, by level and multiplier. Multiply by three for a golden berry.
Level×1×2×3×4×5
11020304050
21224364860
31428425670
41632486480
51836547290
620406080100
722446688110
824487296120
9265278104130
10285684112140

A worked example from real play

When we tested the finished game we wrote an automated player that reads the berry position directly from the rendered canvas and steers towards it. In one recorded run it ate five berries and finished with a score of exactly 70, a length of 8 and level 2. That number is worth walking through, because it shows the whole system in one line.

  1. Berry 1 — level 1, chain position 1, multiplier ×1 → 10 points (running total 10)
  2. Berry 2 — level 1, chain position 2, multiplier ×1 → 10 points (total 20)
  3. Berry 3 — level 1, chain position 3, multiplier ×1 → 10 points (total 30)
  4. Berry 4 — level 1, chain position 4, multiplier ×2 → 20 points (total 50)
  5. Berry 5 — level 1, chain position 5, multiplier ×2 → 20 points (total 70), and the level then advances to 2

Notice that the fourth berry is worth double the first even though nothing about the board has changed. That is the entire strategic argument for playing aggressively: hesitation does not merely waste time, it actively resets your income.

Score benchmarks and the theoretical maximum

The table below shows what a given number of berries is worth if you never build a combo at all — treat these as the floor, not the target. A player holding a five-times multiplier for most of a run will land near five times these figures.

Score benchmarks with no combo, and the same run played at maximum multiplier
Berries eatenSnake lengthLevel reachedScore with no comboScore at sustained ×5
10133110550
252863501,750
5053119504,750
100103212,90014,500
200203419,80049,000
438 (perfect run)441 (full board)8842,312211,560

That last row is the ceiling. The board holds 441 cells, the snake starts with 3, so a perfect run eats 438 berries and ends with the snake occupying every single cell. At that point the level is 88 and each berry is worth 184 points before the multiplier. Nobody has done this. If you ever do, the "Longest" figure in your record panel will read 441 and there will be nowhere left to move.

Speed, timing and reaction windows

Every difficulty setting is defined by three numbers: the interval between moves at level 1, how many milliseconds that interval shrinks per level, and the floor below which it never goes.

Speed profiles for the four difficulty settings
SettingStarting intervalReduction per levelFastest intervalLevel at which top speed is reached
Calm170 ms6 ms110 ms11
Classic130 ms6 ms80 ms10
Swift100 ms5 ms60 ms9
Frantic78 ms4 ms45 ms10

Move interval by level

Milliseconds between moves at each level, for every difficulty
LevelCalmClassicSwiftFrantic
117013010078
21641249574
31581189070
41521128566
51461068062
61401007558
7134947054
8128886550
9122826046
10 and above116 then 110806045

Converting milliseconds into something you can feel

A number like "80 milliseconds per move" is meaningless until you convert it into cells per second and into board-crossing time. This table does that, and then does something more useful: it shows how far the snake travels during a typical human reaction. Simple visual reaction time in adults is usually somewhere around 200 to 250 milliseconds. We have used 250 milliseconds as the conservative figure.

Speed conversions and reaction distance at 250 ms of reaction time
Setting and levelIntervalCells per secondSeconds to cross the boardCells travelled while you react
Calm, level 1170 ms5.93.571.5
Calm, top speed110 ms9.12.312.3
Classic, level 1130 ms7.72.731.9
Classic, top speed80 ms12.51.683.1
Swift, level 1100 ms10.02.102.5
Swift, top speed60 ms16.71.264.2
Frantic, level 178 ms12.81.643.2
Frantic, top speed45 ms22.20.955.6

Read the last column carefully, because it contains the single most important insight in this article. At Frantic top speed, by the time you have seen a problem and moved your finger, the snake has already travelled more than five cells — a quarter of the width of the board. You cannot react your way through fast Snake. You can only plan your way through it. Every good player is effectively playing two or three seconds in the future, and the visible present is only there to confirm the plan is still valid.

The golden berry window

A golden berry lives for exactly seven seconds. Whether you can reach it depends entirely on your current move interval. The worst case on a 21 × 21 board is a corner-to-corner trip, which is a Manhattan distance of 40 cells.

Moves available during a golden berry's seven-second life
Setting and levelIntervalMoves available in 7 secondsWorst case is 40 cells — reachable?
Calm, level 1170 ms41Only just, with a perfectly clear path
Calm, top speed110 ms63Comfortably
Classic, level 1130 ms53Yes, with room for one detour
Classic, top speed80 ms87Easily
Swift, level 1100 ms70Easily
Frantic, top speed45 ms155Almost always

This produces a genuinely counter-intuitive conclusion: golden berries are hardest to collect on the slowest setting. Calm gives you more thinking time per move but fewer moves inside a fixed seven-second timer. If you are chasing bonus points rather than survival, Classic or Swift are better hunting grounds than Calm.

The combo window in moves, not seconds

The same logic applies to the five-second combo window, and the effect is even stronger. The average Manhattan distance between two random cells on a 21 × 21 board is almost exactly 14 cells, so that is the typical trip between one berry and the next.

How many moves the five-second combo window actually gives you
Setting and levelIntervalMoves inside the 5-second windowMargin over the average 14-cell trip
Calm, level 1170 ms29Around 2.1 times
Classic, level 1130 ms38Around 2.7 times
Swift, level 1100 ms50Around 3.6 times
Frantic, level 178 ms64Around 4.6 times
Frantic, top speed45 ms111Around 7.9 times

In other words, the fast settings are not merely riskier — they are also where the highest scores live, because they make sustained five-times multipliers realistic. Calm is the setting to learn on. It is not the setting to set records on.

The three modes

Walls

The original 1997 ruleset. The border is solid; touching it ends the run. This is the purest version of the game and the one your score should be measured on if you want to compare yourself to the classics. Walls mode punishes drifting: with no escape at the edges, the perimeter becomes the most dangerous real estate on the board rather than the safest.

Portal

Inherited from Snake II on the Nokia 3310. Leave through any edge and you re-enter from the opposite one. This sounds like it makes the game easier, and for the first thirty seconds it does. It then makes it considerably harder, for a reason most players never articulate: in Walls mode your own body and the border form one connected barrier, so the board has a simple inside and outside. In Portal mode the board is topologically a torus, your body can wrap around it, and the region you have trapped yourself in is far less obvious. Long Portal runs demand real spatial imagination.

Portal mode is also where the highest scores are theoretically possible, because the edge is no longer a hazard and every berry is reachable by two routes rather than one — sometimes the wrap-around path is shorter than the direct one, which matters enormously for keeping a combo alive.

Maze

Five stone layouts rotate as you level up, and the arrangement changes underneath you every five berries. The layouts are symmetric and deterministic — the same level always produces the same walls — so they can be learned rather than merely survived. Two rules protect you: no stone is ever placed on the rim of the board, and the central row where the snake spawns is always kept clear.

Maze mode changes the fundamental skill being tested. Walls and Portal are about managing the space your own body consumes. Maze is about route-finding under time pressure, which is much closer to what Nibbler was doing in 1982 than to what Nokia was doing in 1997.

Choosing a mode
ModeEdgesObstaclesBest forMain risk
WallsFatalNoneLearning, and fair score comparisonCornering yourself against the border
PortalWrap aroundNoneLong runs and high scoresLosing track of which region you are in
MazeFatalFive rotating layoutsRoute planning and varietyThe board changing shape mid-run

Strategy: how to actually get better at Snake

Most Snake advice online amounts to "be careful" and "don't crash". Here is something more useful. These are ordered roughly by the point in your development where they start to matter.

1. Stop chasing the berry

Beginners steer directly at the food. This works until the snake is about ten cells long, then it starts killing you, because a direct route optimises for the current berry and ignores where your tail will be afterwards. Intermediate players ask a different question: not "how do I get there?" but "what will the board look like once I have?"

The practical version of this rule is simple. Before you commit to a route, check that there is a way out of the berry's location. Eating a berry in a dead end is how good runs end.

2. Keep your body against the edges

Space in Snake is not fungible. A hundred free cells scattered in pockets is worthless; a hundred free cells in one open region is a whole game. The way to keep your free space in one piece is to keep your body along the perimeter and let the middle stay open, rather than the reverse. A snake coiled around the outside of the board leaves a single large hole. A snake wandering through the middle chops the board into fragments.

3. Learn the zigzag

The classic space-filling pattern — sometimes called boustrophedon, from the Greek for "as the ox ploughs" — is to travel the full length of a row, drop down one, travel back, and repeat. It looks slow and it is, but it guarantees you sweep every cell in a region without ever cutting yourself off. When a berry appears far away and your snake is long, walking a zigzag towards it is almost always safer than taking the direct line.

4. Follow your own tail

If you are ever unsure what to do, chase your own tail. Because the tail moves away one cell every time the head moves, a snake following its own tail can survive indefinitely. This is the emergency manoeuvre: when the board looks bad and you cannot see a plan, get behind your tail and buy yourself time while a new berry spawns somewhere better.

5. Understand the tail-vacating rule

Here is a rule that most implementations get wrong and that most players therefore never learn to exploit. When the snake moves and does not eat, the tail leaves its cell in the same instant the head enters a new one. That means the cell currently occupied by the end of your tail is safe to move into — it will be empty by the time you arrive.

Our version implements this correctly. The consequence is that you can execute genuinely tight turns that look impossible, following your own body one cell behind it. But note the exception: if you eat a berry on that same move, the snake grows and the tail does not vacate. Moving into your tail cell while eating is fatal. Experienced players internalise this as "tight turns are safe unless there is food in the way".

6. Play the combo, not the berry

Given the tables above, the arithmetic is stark. A calm, careful player eating a berry every eight seconds scores at ×1 forever. An aggressive player eating one every three seconds is at ×5 within thirteen berries and is earning five times as much per berry from then on. The aggressive player will die sooner. They will also finish with a score several times higher.

The practical rule: as soon as a berry appears, start moving towards it. Do not finish your current loop first. Do not wait to see where it is going — it is not going anywhere.

7. Route around golden berries, do not detour to them

A golden berry is worth three ordinary ones, which is excellent, but it appears in a random cell and expires in seven seconds. If it is roughly on the way, take it. If collecting it would break your combo on the ordinary berry, skip it. Three times one berry is worth less than the five-times multiplier you would lose.

8. Manage the level-up moment

Every fifth berry, the game speeds up — and in Maze mode the walls also change. That instant is the single most dangerous moment in any run. If you are approaching your fifth, tenth or fifteenth berry, make sure you arrive with open space ahead of you rather than in a tight corner.

Common mistakes and their fixes

What kills most runs, and what to do instead
MistakeWhy it kills youFix
Taking the direct line to every berryLeaves your body scattered through the middle of the boardRoute along the perimeter and enter the centre only to collect
Turning twice in one move intervalThe second turn is what actually happens; the first is discardedOne decisive input per move, not a burst of taps
Panicking when the snake gets longPanic produces short-range decisions, which fragment the boardFall back to following your own tail until a plan appears
Eating a berry in a cornerYou arrive with only one exit, and your new segment blocks itApproach corners along the wall, not perpendicular to it
Playing on Calm to score highlyFewer moves per second means fewer moves inside the combo windowLearn on Calm, score on Classic or Swift
Ignoring level-up momentsThe speed changes while you are mid-manoeuvreCount your berries; arrive at every fifth one in open space

The mathematics of Snake

Snake looks like a reflex game and behaves like a graph theory problem. This section is optional, but it contains one fact about our specific board that we have not seen discussed anywhere else, and it changes how a perfect run would have to be played.

Snake as a grid graph

Model the board as a graph: every cell is a vertex, and two vertices are connected if their cells are orthogonally adjacent. The snake is a path through this graph that moves one step per turn, cannot reverse, and grows by one vertex every time it lands on food. Almost every interesting question about Snake becomes a question about paths and cycles in grid graphs.

Why "just follow a cycle" is the standard perfect strategy

The best-known way to guarantee a Snake never dies is to find a Hamiltonian cycle — a closed loop that visits every cell exactly once — and simply follow it forever. Because the loop covers every cell, all food eventually lands in front of you; because it is a single closed loop and the snake is shorter than the loop, you can never collide with yourself. It is perfect, and it is unbearably slow, but it always wins.

Why our 21 × 21 board has no such cycle

Here is the interesting part. Colour the board like a chessboard. Every move takes the snake from a light cell to a dark cell or vice versa, so any closed loop must alternate colours — which means a Hamiltonian cycle can only exist if the number of light cells equals the number of dark cells.

On a 21 × 21 board there are 441 cells: 221 of one colour and 220 of the other. They are not equal, and they cannot be, because 441 is odd. Therefore no Hamiltonian cycle exists on our board at all. The classic "safe loop" strategy is mathematically impossible here.

What does exist is a Hamiltonian path — an open route through all 441 cells. So a perfect run is still possible, but it cannot be a mindless loop. Any player or algorithm attempting to fill the board would have to either work within a 20 × 21 sub-region of 420 cells, which is even and does admit a cycle, and handle the remaining row separately, or plan an open path and reposition at the end. This is not an accident of our design; it is a property of every odd-by-odd Snake board, including a great many of the ones you will find online.

Board parity and whether a perfect closed loop can exist
BoardTotal cellsCell colour splitHamiltonian cycle possible?
20 × 20400200 / 200Yes
21 × 21 (this game)441221 / 220No — an open path only
20 × 21 sub-board420210 / 210Yes
Any odd × odd boardOddUnequal by oneNo

How hard is Snake, formally?

Hard enough that computer scientists have published on it. In 2016, Marzio De Biasi and Tim Ophelders presented a paper titled "The Complexity of Snake" at the International Conference on Fun with Algorithms, later extended in Theoretical Computer Science. They showed that deciding whether a snake can collect all the food on a solid grid graph is NP-hard, and that on general grid graphs the problem is PSPACE-complete — as is the simpler question of whether a snake can get from one configuration to another, even with no food on the board at all.

Put plainly: there is no known efficient algorithm that plays Snake optimally, and there is good reason to believe none exists. When you feel that a position is unsolvable, you may be objectively right. The problem has also attracted researchers in robotics, because a snake that must not collide with its own body is a reasonable model for motion planning with articulated snake-like robots.

Some numbers about the board

Geometry of the 21 × 21 playfield
QuantityValue
Total cells441
Perimeter cells80
Interior cells361 (a 19 × 19 region)
Free cells at the start of a run437 (441 minus 3 snake segments and 1 berry)
Maximum Manhattan distance between two cells40
Average Manhattan distance between two random cellsApproximately 14.0
Maximum snake length441
Berries in a perfect run438
Final level in a perfect run88

Under the hood: building a Snake that does not lie to the player

This section is for developers, and for anyone curious about why some browser Snake games feel good and others feel cheap. Every item below is a bug we either fixed or deliberately designed around.

Fixed timestep instead of setInterval

The naïve way to run a Snake game is to call a move function on a timer. It seems to work. It is wrong in three ways: browser timers drift, they are throttled in background tabs, and the interval never lines up with the display refresh, so the animation stutters.

The correct approach is a fixed timestep accumulator. Each animation frame, measure how much real time has elapsed, add it to an accumulator, and run as many logical moves as that time contains. The game logic advances in exact, identical increments regardless of frame rate; only the drawing follows the display. Two additional guards matter: clamp the elapsed time so a backgrounded tab does not fast-forward the snake into a wall on return, and cap the number of catch-up moves per frame so a slow device cannot spiral.

Timer approaches compared
ApproachBehaviour on a 144 Hz monitorBehaviour in a background tabFairness
setIntervalStutters; move timing drifts from display timingThrottled unpredictablySpeed varies by device
One move per animation frameRuns at 144 moves per secondStops entirelyCompletely unfair
Fixed timestep accumulatorSmooth, exactly correct move rateClamped, then resumes cleanlyIdentical everywhere

The input queue, and the bug that kills every first draft

Almost every homemade Snake game contains the same fatal bug. The player is moving right, quickly presses up and then left, and both inputs are applied before the next move — so the snake reverses into its own neck and dies for no visible reason. It is the single most common source of "this game is broken" complaints, and it is not the player's fault.

The fix is to queue inputs rather than apply them immediately. Each logical move consumes at most one direction from the queue, and rejects any direction that is the exact reverse of the current one. The player can buffer a turn slightly early — which feels responsive — but can never accidentally fold the snake in half.

Collision, done exactly

As described in the strategy section, the tail vacates its cell on any move that does not grow the snake. A correct implementation checks the head's target against all body segments except the last one, unless the move is an eating move, in which case every segment counts. Getting this wrong in either direction produces a game that feels either unfairly harsh or suspiciously forgiving. We verified this behaviour with automated tests before shipping.

Interpolated rendering on a discrete grid

The logic runs on integer cell coordinates; the drawing runs on fractional positions. Between moves, each segment is drawn at a blend of where it was and where it is going, weighted by how far through the current interval we are. The result is a snake that glides rather than jumps, without any compromise to the fairness of the underlying grid.

One subtlety: in Portal mode a segment can wrap from one edge of the board to the other, and interpolating that transition would draw a streak straight across the screen. The fix is to detect any jump longer than one cell and snap instead of blend, and to break the drawn body path at that point.

Food placement without rejection sampling

The common approach is to pick a random cell, check whether it is occupied, and try again if it is. This works fine early and becomes pathological late: when the snake fills most of the board, the loop may run hundreds of times, and if the board is completely full it never terminates. We build the list of genuinely free cells and choose from it uniformly. It is both faster in the worst case and provably terminating.

Not breaking the page it lives in

An embedded game has obligations to its host. Ours never registers a global keyboard handler that steals arrow keys from the page — input is only captured while you are actually interacting with the game, and it releases the moment you click elsewhere, pausing itself as it goes. It pauses when the tab is hidden and when it scrolls out of view. All of its styling is scoped so it cannot leak into the article around it, and nothing from the surrounding site can leak in.

Two real bugs we found by testing

We will be honest about these, because articles like this usually pretend development is frictionless. During final testing, an automated browser found two problems that manual play had missed.

The first was a variable name collision: a newly added reference to the board element shadowed the render loop function of the same name, which silently disabled the entire game. It threw a single console error and nothing moved. The lesson is unglamorous and universal — name things carefully, and run the thing you shipped.

The second was subtler and more instructive. To size the board we were measuring the width of the very element whose width we were setting, which creates a feedback loop: the board can shrink but can never grow back. The fix was structural — one element measures the available space and never has its size set, a separate element inside it is the board and is sized in pixels. If you take one architectural idea away from this article, make it that one: never measure a box whose dimensions you control.

Languages, accessibility and playing on any screen

The game ships in six languages, with English as the source. It detects the appropriate one automatically by checking, in order: an explicit language parameter in the page address, an attribute on the game element itself, the language declared by the page, the locale in the page's social metadata, the content-language declaration, and finally the browser's own preference. If none of these produce a supported language, it falls back to English. You can always override the result with the selector in the corner.

Supported languages
LanguageCodeTitle in that languageText direction
EnglishenSnakeLeft to right
FrenchfrSnakeLeft to right
SpanishesSnakeLeft to right
Chinesezh贪吃蛇Left to right
Hindihiस्नेकLeft to right
Arabicarلعبة الثعبانRight to left

Arabic switches the whole interface to right-to-left, with one deliberate exception: the direction pad stays in its physical arrangement, because "left" on a game controller means left on the screen regardless of the language you read in.

On accessibility, the game is fully operable from the keyboard, every control is a real button with a proper label, and score changes and the end of a run are announced to screen readers through a live region. If your system is set to reduce motion, the decorative animation, the crash shake and the pulsing effects are all disabled while the gameplay itself is untouched.

On responsiveness, the layout adapts to the width of the game rather than the width of the browser — which matters, because an embedded game inside a narrow article column should behave like a narrow game even on a wide monitor. In fullscreen on a landscape screen it switches to a two-column arrangement with the board on one side and the controls on the other, and the board can grow to over a thousand pixels across.

Full controls reference

Every input the game accepts
InputActionNotes
Arrow keysSteerThe standard layout
W, A, S, DSteerFor QWERTY keyboards
Z, Q, S, DSteerFor AZERTY keyboards
SpacePause or resumeAlso starts a run from the title screen
RRestartBegins a fresh run immediately
FFullscreenToggles in and out
MMuteSound is off by default
EnterConfirmActivates the button on the current card
EscapeLeave fullscreenStandard browser behaviour
Swipe on the boardSteerChained swipes are recognised without lifting your finger
Tap the boardStart or resumeLike putting a coin in an arcade cabinet
On-screen padSteerAppears automatically on touch devices

Frequently asked questions

Who invented the Snake game?

No single person, which is why the question keeps getting different answers. The mechanic was created by Lane Hauck at Gremlin Industries for the 1976 arcade game Blockade. The single-player, food-eating format that we now call Snake was established by Rock-Ola's Nibbler in 1982. The version that made it famous worldwide was written by Taneli Armanto at Nokia for the 6110 in 1997. All three answers are defensible; they are answers to different questions.

What is the highest possible score in this game?

211,560, achieved by eating all 438 available berries while holding a five-times multiplier throughout, and ignoring golden berries. In practice, golden berries would push a theoretically perfect run higher still. A very strong human run on Classic typically lands somewhere between 2,000 and 10,000.

Does the game get faster forever?

No. Each difficulty has a floor. Classic bottoms out at 80 milliseconds per move at level 10 and never gets faster; Frantic bottoms out at 45 milliseconds. Everything after that point gets harder purely because your snake is longer, which is the honest kind of difficulty.

Is a longer snake worth more points?

Indirectly. Length itself is not scored, but length tracks berries eaten, berries eaten determines your level, and level raises the base value of every future berry by two points. The multiplier, however, has nothing to do with length — it is purely about how quickly you eat.

Why is my score lower on Calm than on Classic?

Because the combo window is measured in seconds, not moves. A slower snake covers less ground in five seconds, so chains break more often. Calm is easier to survive and harder to score on. This surprises almost everyone.

Do my scores and statistics get sent anywhere?

No. Everything — best scores per mode, games played, berries eaten, longest snake, total time — is stored locally in your own browser. There is no account, no server, no leaderboard and no tracking. Clearing your browser data clears your records, and the reset button in the record panel does the same thing deliberately.

Can I play with the keyboard on a phone, or with touch on a laptop?

Yes to both. The direction pad appears automatically on touch devices but the keyboard remains active if one is attached, and touchscreen laptops can swipe on the board.

Why does the game pause when I click elsewhere on the page?

Deliberately. An embedded game that keeps consuming your arrow keys after you have moved on to reading the article is a nuisance. When you interact with something outside the game, it releases the keyboard and pauses itself so you do not return to a dead snake.

What is the fastest way to improve?

Play twenty runs on Classic in Walls mode and, on each one, force yourself to route along the perimeter rather than through the middle. It will feel slower and your first few scores will drop. By the tenth run they will be higher than they were before, because you will have stopped fragmenting the board.

Glossary

Terms used in this article and in the wider Snake community
TermMeaning
TickOne logical move of the snake, one cell forward
Move intervalThe time in milliseconds between two ticks
Fixed timestepRunning game logic in exact, identical time increments regardless of frame rate
InterpolationDrawing a segment partway between its previous and current cell for smooth motion
Input queueA short buffer of pending direction changes, consumed one per tick
Tail vacatingThe rule that the last segment leaves its cell on any non-eating move
Combo chainConsecutive berries eaten within the five-second window
Portal or wrap modeA playfield where leaving one edge returns you at the opposite one
Grid graphA graph whose vertices are grid cells and whose edges join adjacent cells
Hamiltonian cycleA closed route visiting every cell exactly once
Hamiltonian pathAn open route visiting every cell exactly once
BoustrophedonA back-and-forth sweeping pattern that fills a region without self-trapping
Manhattan distanceThe number of horizontal plus vertical steps between two cells
NP-hardAt least as hard as the hardest problems verifiable in polynomial time
PSPACE-completeAmong the hardest problems solvable with a polynomial amount of memory

Why we still build things like this

There is a version of this article that ends with a line about nostalgia, and it would not be wrong. Snake is fifty years old this decade. A very large number of people have a specific memory attached to it — a specific handset, a specific classroom, a specific green-tinted screen.

But nostalgia is not why the game is still worth building well. Snake survives because it is one of the very few games where the rules are completely visible and the depth is completely hidden. Nothing is concealed from you. There is no unlock, no meta-progression, no stat you have not been shown. Everything you need to reach a perfect run is on the screen from the first second — and you still cannot do it, because the difficulty was never in the information, it was in the planning.

That is a rare and honest kind of game design, and it is worth the effort of a fixed timestep, a correct collision rule, an input queue that respects the player, and a snake that glides instead of jumping. Everything in this article — every table, every formula, every millisecond — exists so that when you lose, you know it was your decision that lost it.

Now go and beat 2,000 on Classic. Route along the edges. Do not stop for the golden berries.

َAdmin
Written by َAdmin

As a digital content enthusiast, I dedicate myself to sharing my personal insights and documenting the knowledge I gain from the web. My goal is to create valuable, purpose-driven content that informs, inspires, and delivers real benefits to others.

Newer Post
This is the newest
Older Post

OFF
enabled: true page: /p/redirect.html protect: true in_post: true new_tab: true delay: 5
enabled: true shape: solid scope: standalone
enabled: true title: Rate this article