Train snakeOne-line
Gemini 3.1 Flash Lite
by GoogleReasoningClean
Running live in a sandboxed frame. Click inside it before using the keyboard.
How it went
- Total time
- 18.5 s
- Cost
- $0.011
- Output tokens
- 7,125
- Spent thinking
- 4,716 tokens
- Speed
- 415.7 tok/s
- Console errors
- 0
- First token after
- 1.3 s
- First visible text after
- 13.7 s
- Prompt tokens
- 367
- Code size
- 8.0 KB
- Finish reason
- stop
- Served by
- Model id
google/gemini-3.1-flash-lite- Reasoning sent
{"effort":"high"}- Max output
- 65,536 tokens
- Generated
- Nov 12, 2026
What it was asked
The prompt
“make me a snake game where the snake is a little train with a locomotive and colorful wagons, picking up passengers waiting on the platform”
System prompt, sent with every prompt
You are generating a self-contained web demo. It will be rendered automatically in a sandboxed iframe and compared side by side with the output of other AI models given the exact same task. Output rules: - Reply with exactly ONE fenced code block containing the complete file: ```html (or ```svg when the task asks for an SVG). No text before or after the code block. - Everything must be inline: CSS in <style>, JavaScript in <script>. No external files, images, fonts or network requests, except the CDN URLs explicitly allowed by the task. - Do not use localStorage, sessionStorage, cookies, IndexedDB, alert(), confirm(), prompt() or window.open(): they are blocked in the sandbox and will throw. - The page must look right in a 1280×800 viewport and adapt gracefully down to 375px wide. No horizontal scrollbar. - Something meaningful must be visible on first paint: a screenshot is taken automatically about 3 seconds after load, without any interaction. - Everything that makes the demo interesting must be visible within the first seconds: nothing hidden behind a high score, a later level or a long play session. - Games must start in a self-playing demo mode (a simple AI plays) behind a "Click or press a key to start" message, so the game can be judged in action without playing. - The iframe only receives keyboard events after the user clicks it: if the demo uses the keyboard, display a clear "Click or press a key to start" message. - The code must run with zero errors in the console of the latest Chrome.
Code run-1.html · 256 lines
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Train Snake</title>
<style>
body {
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
background-color: #2c3e50;
color: white;
font-family: 'Segoe UI', sans-serif;
overflow: hidden;
}
#gameContainer {
position: relative;
width: 90vw;
max-width: 600px;
aspect-ratio: 1/1;
}
canvas {
width: 100%;
height: 100%;
background-color: #ecf0f1;
border-radius: 8px;
box-shadow: 0 4px 15px rgba(0,0,0,0.3);
}
#ui {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: rgba(44, 62, 80, 0.7);
border-radius: 8px;
text-align: center;
cursor: pointer;
}
h1 { margin-bottom: 10px; }
.score-board {
position: absolute;
top: -40px;
left: 0;
width: 100%;
text-align: center;
font-size: 24px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="score-board">Passengers Picked Up: <span id="score">0</span></div>
<div id="gameContainer">
<canvas id="gameCanvas" width="600" height="600"></canvas>
<div id="ui">
<h1>TRAIN SNAKE</h1>
<p>Click or press a key to start</p>
</div>
</div>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreEl = document.getElementById('score');
const ui = document.getElementById('ui');
const GRID_SIZE = 20;
const CELL = canvas.width / GRID_SIZE;
let snake = [{x: 10, y: 10}];
let direction = {x: 1, y: 0};
let nextDirection = {x: 1, y: 0};
let passenger = {x: 5, y: 5};
let score = 0;
let isAttractMode = true;
let isGameOver = false;
let gameLoopId = null;
const wagonColors = ['#e74c3c', '#f1c40f', '#2ecc71', '#9b59b6', '#3498db'];
function init() {
snake = [{x: 10, y: 10}];
direction = {x: 1, y: 0};
nextDirection = {x: 1, y: 0};
score = 0;
scoreEl.innerText = score;
spawnPassenger();
isGameOver = false;
}
function spawnPassenger() {
passenger = {
x: Math.floor(Math.random() * GRID_SIZE),
y: Math.floor(Math.random() * GRID_SIZE)
};
// Ensure not on snake
snake.forEach(s => {
if(s.x === passenger.x && s.y === passenger.y) spawnPassenger();
});
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw Passenger
ctx.fillStyle = '#ff00ff';
ctx.beginPath();
ctx.arc((passenger.x + 0.5) * CELL, (passenger.y + 0.5) * CELL, CELL * 0.3, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = '#fff';
ctx.beginPath();
ctx.arc((passenger.x + 0.5) * CELL, (passenger.y + 0.4) * CELL, CELL * 0.1, 0, Math.PI * 2);
ctx.fill();
// Draw Snake
snake.forEach((s, i) => {
const x = s.x * CELL;
const y = s.y * CELL;
if (i === 0) {
// Locomotive
ctx.fillStyle = '#2c3e50';
ctx.fillRect(x + 2, y + 2, CELL - 4, CELL - 4);
ctx.fillStyle = '#7f8c8d';
ctx.fillRect(x + CELL * 0.3, y + CELL * 0.1, CELL * 0.4, CELL * 0.2); // Funnel
} else {
// Wagon
ctx.fillStyle = wagonColors[(i - 1) % wagonColors.length];
ctx.fillRect(x + 2, y + 2, CELL - 4, CELL - 4);
// Wheels
ctx.fillStyle = '#333';
ctx.beginPath();
ctx.arc(x + CELL * 0.25, y + CELL * 0.85, CELL * 0.15, 0, Math.PI * 2);
ctx.arc(x + CELL * 0.75, y + CELL * 0.85, CELL * 0.15, 0, Math.PI * 2);
ctx.fill();
}
});
}
function getAiMove() {
const head = snake[0];
const moves = [
{x: 1, y: 0}, {x: -1, y: 0},
{x: 0, y: 1}, {x: 0, y: -1}
];
let bestMove = direction;
let minDistance = Infinity;
for (let move of moves) {
// Prevent reversing
if (move.x === -direction.x && move.y === -direction.y) continue;
const nextX = head.x + move.x;
const nextY = head.y + move.y;
// Collision with walls
if (nextX < 0 || nextX >= GRID_SIZE || nextY < 0 || nextY >= GRID_SIZE) continue;
// Collision with self
let collision = false;
for(let i=0; i<snake.length-1; i++) {
if(snake[i].x === nextX && snake[i].y === nextY) collision = true;
}
if (collision) continue;
const dist = Math.abs(nextX - passenger.x) + Math.abs(nextY - passenger.y);
if (dist < minDistance) {
minDistance = dist;
bestMove = move;
}
}
return bestMove;
}
function update() {
if (isAttractMode) {
direction = getAiMove();
} else {
direction = nextDirection;
}
const head = {x: snake[0].x + direction.x, y: snake[0].y + direction.y};
// Wall collision
if (head.x < 0 || head.x >= GRID_SIZE || head.y < 0 || head.y >= GRID_SIZE) {
gameOver();
return;
}
// Self collision
for (let i = 0; i < snake.length; i++) {
if (snake[i].x === head.x && snake[i].y === head.y) {
gameOver();
return;
}
}
snake.unshift(head);
if (head.x === passenger.x && head.y === passenger.y) {
score++;
scoreEl.innerText = score;
spawnPassenger();
} else {
snake.pop();
}
draw();
}
function gameOver() {
if (isAttractMode) {
init();
} else {
isAttractMode = true;
ui.style.display = 'flex';
ui.innerHTML = '<h1>GAME OVER</h1><p>Score: ' + score + '</p><p>Click to restart</p>';
}
}
function startGame() {
if (isAttractMode) {
isAttractMode = false;
ui.style.display = 'none';
init();
}
}
window.addEventListener('keydown', e => {
startGame();
switch(e.key) {
case 'ArrowUp': if(direction.y === 0) nextDirection = {x: 0, y: -1}; break;
case 'ArrowDown': if(direction.y === 0) nextDirection = {x: 0, y: 1}; break;
case 'ArrowLeft': if(direction.x === 0) nextDirection = {x: -1, y: 0}; break;
case 'ArrowRight': if(direction.x === 0) nextDirection = {x: 1, y: 0}; break;
}
});
ui.addEventListener('click', () => {
startGame();
});
setInterval(update, 120);
</script>
</body>
</html>Reasoning trace (4,716 tokens)
**Developing Train Aesthetics** I'm focused on bringing the train concept to life visually. My current thoughts are on how to best represent the locomotive and its trailing wagons, ensuring it captures that distinct train look while still adhering to the core snake game mechanics of movement and growth. **Designing Core Mechanics** I'm currently conceptualizing the game's fundamental systems. My focus is on how the train, represented by an array of segments with distinct locomotive and wagon visuals, will move autonomously and interact with passengers, aiming for a simple AI approach to guide its path. **Refining Movement Logic** I'm working on the AI for movement. The core idea is to have the train greedily move towards the nearest passenger. I'm prioritizing direct paths, ensuring it avoids collisions with itself and walls. This should provide a responsive and engaging gameplay feel. **Updating Movement Algorithms** My current focus is on refining the AI for train movement. I'm implementing a greedy approach that prioritizes the nearest passenger, employing Manhattan distance for direction selection and ensuring collision avoidance. Responsive canvas sizing via CSS is also being integrated. **Improving Collision Avoidance** I'm iterating on the AI's movement, specifically refining how the train handles collisions. Instead of just stopping, I'm implementing logic to choose a random valid move if the greedy path leads to a wall or itself. This should prevent deadlocks and enhance player agency. **Implementing Self-Play** I'm now focusing on the initial game state, ensuring it begins in a self-playing demo mode as per the instructions. I'm setting up the logic for the train to autonomously navigate and interact with passengers from the outset, awaiting user input to take control. **Adding Train Visuals** I'm now incorporating specific visual elements for the train. My focus is on distinguishing the locomotive with a funnel and smokestack, while assigning alternating colors to the wagons to enhance the overall train aesthetic. **Refining AI Scoring** I'm currently refining the AI's decision-making process. My thoughts are on how to effectively score valid directions, prioritizing proximity to the next available passenger to ensure the train moves efficiently. **Handling Game States** I'm considering how to manage different game states. My current focus is on implementing the "Game Over" condition and ensuring the game stops gracefully when it occurs. **Simplifying Gameplay** I'm revisiting the core gameplay loop. My priority is to maintain simplicity, deciding that a 15x15 grid offers a good balance of challenge and clarity for the train's movement. **Integrating User Control** I'm working on the transition from self-play to user control. My current thoughts involve how to best register user input, likely via mouse clicks, to disable attract mode and allow direct manipulation of the train. **Improving AI Safety** I'm addressing a critical flaw in the greedy AI. If all moves are blocked, it currently risks self-collision. My focus is on implementing a fallback mechanism, defaulting to any valid move to prevent game-ending deadlocks, thereby enhancing robustness. **Designing Train Visuals** I'm now focusing on the visual representation of the train. My thoughts are on how to create distinct shapes for the locomotive, complete with a smokestack, and simpler wagon segments, each with small wheels, to clearly define the train's appearance. **Consolidating Project Structure** My current focus is on streamlining the project's architecture. I'm consolidating all game logic, styling, and the user interaction overlay into a single HTML file for efficient development and deployment. **Implementing Self-Play Initiation** I'm working on the initial user interaction for the self-play mode. My thoughts are on how a mouse click will seamlessly transition the game from its automated demonstration state to active user control, also serving to reset the game. **Developing Scoring System** I'm refining the scoring mechanism. My focus is on implementing a straightforward counter that increments each time the train successfully picks up a passenger, providing immediate feedback on player progress. **Clarifying Passenger Interaction** I'm addressing the specific requirement of passengers waiting on platforms. My current thoughts are on how to visually and functionally represent these stationary passengers for the train to interact with. **Refining Visuals and Interaction** I'm focusing on passenger representation as small figures and distinct train colors: dark blue for the locomotive and bright alternating colors for wagons. The canvas will be responsive, using `max-width: 90vw` and `aspect-ratio: 1/1`. Self-play will initiate with a "Click to start" message, transitioning to keyboard control, with a graceful restart on game over. **Drawing Game Elements** I'm currently solidifying the visual representation of game entities. My thoughts are on how to efficiently draw the grid, distinctly style the locomotive and wagons, and render the passenger as a simple figure, ensuring clear on-screen differentiation. **Refining Train Movement** I'm concentrating on the train's visual dynamism and movement logic. My thoughts are on ensuring the head segment always leads and the tail naturally extends with passenger consumption, all while reinforcing the core greedy AI's Manhattan distance calculation for optimal pathfinding. **Finalizing Visuals and Playback** I've refined the train's appearance with cute wheel details and confirmed the responsive canvas sizing. The "Click to start" overlay will vanish instantly, ensuring the self-play demo is immediately visible and engaging from the outset. Everything seems ready. **Clarifying Attract Mode** I'm clarifying the initial game state. The game will begin in an attract mode with an overlay message. User interaction, like a click or key press, will then transition it to player control, disabling the overlay and allowing direct manipulation. **Confirming Attract Mode Logic** I'm solidifying the attract mode mechanics. The game will indeed start playing autonomously behind a "Click to start" overlay. A user click will disable this overlay and transition control, while a "Game Over" event will now seamlessly return the game to this attract mode for continuous playback. **Addressing Final Details** I'm reviewing the last few points. I've noted the need to prevent horizontal scrollbars and confirmed the attract mode's seamless transition to self-play and then to player control via a click. I'm also ensuring the game looks good on various screen sizes and that the AI logic is well-structured.