DEV Community

Cover image for Gemma 4 Plays Snake: A Real-Time AI Game Loop
Denis Arruda
Denis Arruda

Posted on

Gemma 4 Plays Snake: A Real-Time AI Game Loop

Gemma 4 Challenge: Build With Gemma 4 Submission

This is a submission for the Gemma 4 Challenge: Build with Gemma 4

What I Built

I built a Snake game where the snake is driven entirely by Gemma 4. The model reads the board, reasons about the move, and the snake follows.

The backend is a Quarkus application written in Java 26 with virtual threads. A scheduler fires every 200 ms, advances the snake one cell, checks for collisions and food, and broadcasts the updated board as JSON to every connected browser over WebSocket. The UI is a plain HTML5 Canvas that renders the live game in real time.

What makes the architecture interesting is how the AI fits in. Every tick, if Gemma 4 is not already busy, the engine snapshots the board state, builds a structured prompt and fires it off asynchronously via langChain4j. The game never waits for a response. If the model is still thinking when the next tick fires, the snake keeps going straight. When the answer arrives, the direction is stored atomically and picked up on the next tick.

Demo

Gemma 4 playing Snake in real time — every move decided by the model, every frame rendered live over WebSocket.

Snake game board

Code

Project on Github: https://github.com/denis-arruda/gemma4-snake-ai

How I Used Gemma 4

Gemma 4 (gemini-4-flash) is the right model for this loop: low latency, strong instruction-following, and capable enough to respect the safety constraints in the prompt and navigate toward food. A slower model stalls the game; a weaker one ignores the labels and dies.

Top comments (0)