STR Coding Club logo STR Coding ClubLearn to code, together
Games

Coding Snake Teaches Beginners Why Queues Exist

Every year someone in my Python group builds Snake, and every year the first version works. The snake moves, it eats, it grows, it dies when it hits a wall.

A snake made of grid squares moving across squared paper

Every year someone in my Python group builds Snake, and every year the first version works. The snake moves, it eats, it grows, it dies when it hits a wall. Then I ask the student a question that makes them frown: "What is the snake, as data?" Almost always the answer is "a list of coordinates", and almost always they cannot explain why the list behaves the way it does when the snake moves.

That gap matters more than the game. Snake is one of the cleanest introductions to a queue that I know of, a structure where things join at one end and leave at the other. Most beginners build one by accident and never notice. When I taught maths, the most useful lessons were the ones where students discovered an idea they had already been using. Snake gives you that moment for free, if you slow down and look at what the code is doing.

What actually happens when the snake moves

Picture a snake three segments long on a grid, heading right, with its head at column 5, row 2. Its body might be stored as [(5, 2), (4, 2), (3, 2)], head first. On each tick, two things happen. A new head appears one cell to the right, at (6, 2). The last segment, (3, 2), disappears. The middle segment does not move at all; it simply stays where it was, and now it is second instead of first.

This is the part students find surprising. The snake does not move every segment forward. It adds one cell at the front and removes one at the back. When it eats, it adds at the front and skips the removal, and that is the whole growth mechanic. Items enter at one end and leave from the other in the order they arrived. That is a queue, first in, first out.

Once a student sees this, three things follow. They stop writing loops that shift every coordinate. Their code gets shorter. And they can explain the game to someone else, which is my real test of whether they understood it.

Lists work, until you ask them to do this

A Python list can do the job. You insert the new head at position 0 and pop the last item. The trouble is that inserting at position 0 makes Python shift every other element along by one place in memory. The bigger the list, the more shifting.

The collections module has a structure made for exactly this pattern, the deque (pronounced "deck"). Its appendleft and pop methods both run in constant time, however long the snake gets. I measured it on my laptop with Python 3.14, timing a single "add head, remove tail" step averaged over ten thousand runs:

Snake lengthList, insert(0) then pop()Deque, appendleft() then pop()
400 segmentsabout 0.41 microsecondsabout 0.10 microseconds
100,000 segmentsabout 140 microsecondsabout 0.12 microseconds

Notice what the first row says. A 20 by 20 grid holds at most 400 cells, so a real Snake game never goes past that first row, and the list is fast enough. I tell students this directly, because I do not want them to swap in a deque because a teacher told them it is "faster". The reason to use a deque here is that it says what the code means. When another student reads appendleft and pop, the queue is visible in the code itself.

The second row is for the moment, months later, when that student writes a message queue or a breadth first search and wonders why their program crawls.

The collision bug nearly everyone writes

The standard way to detect the snake biting itself is to check whether the new head is already in the body. With a deque or list that check walks the whole body, which is fine for 400 cells. The more interesting problem is logical, not speed.

Consider a snake that is about to move into the cell its own tail occupies. In most versions of Snake that is a legal move, because the tail leaves that cell on the same tick. But if you add the new head first and then check for a collision before removing the tail, the game kills the snake for touching a cell that should already be empty. Students hit this bug in roughly half the projects I have reviewed, usually when the snake is long and circling tightly, and it looks random to them because it only happens in that exact configuration.

The fix is ordering. Decide whether the snake is eating, remove the tail if it is not, and only then check whether the new head lands on the body. Getting students to write out those steps on paper before touching the code solves it faster than any debugger. For more on that habit, Selene's article on debugging game bugs patiently is worth reading.

A sequence I use in club sessions

Over three sessions of about fifty minutes, this is the order that has worked best with mixed groups of eleven to fifteen year olds:

Session one is paper only. Students draw a five segment snake on squared paper, write its coordinates as a list, and move it three ticks by hand. Then they write the move step with a plain list, inserting the new head and popping the tail, and print the list each tick instead of drawing anything.

Session two adds eating. I ask students where in their code growth happens, and the answer, "nowhere, we just skip the pop", is the lesson of the day. After that they swap the list for a deque, change only two lines, and confirm nothing else changed.

Session three adds the self collision check, and students deliberately steer into the tail cell to see whether it is handled correctly. Only then do we add graphics, with pygame or the turtle module.

Leaving graphics until the end is the part teachers argue with me about. I understand the worry that students lose interest without something on screen. In my experience the printed coordinates are interesting enough for two sessions, and students who build the data first produce games with far fewer bugs. For other early projects that suit a group, see simple games beginners can code in Python.

Where the idea goes next

Once a student has seen a queue in Snake, they start noticing them. The order players join a lobby. The list of keys pressed but not yet processed. The cells waiting to be visited when a maze solver spreads outwards. I would not claim Snake teaches all of computer science, but I have not found a cheaper way to make "first in, first out" feel obvious.

Try this before your next session

Open your own Snake code, or any beginner's, and find the line where the snake grows. If you cannot point to it in under a minute, rewrite the move step as "add head, maybe remove tail" with a deque, and see how much shorter it becomes. More project ideas are in our games section.

BN
Bartholomew Ng

Bartholomew taught maths for years before switching to teaching Python. He writes about the basics of the language and about teaching code without drowning learners in syntax.

More posts by Bartholomew

More in Games

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu haskell iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips tetapatrium topselller uneplanteartificielle vipertechcr webtech1223411 wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto ankertoto