GPT-5 Nano
by OpenAIReasoningClean
Running live in a sandboxed frame. Click inside it before using the keyboard.
How it went
- Total time
- 33.8 s
- Cost
- $0.0020
- Output tokens
- 5,026
- Spent thinking
- 448 tokens
- Speed
- 162.8 tok/s
- Console errors
- 0
- First token after
- 3.0 s
- First visible text after
- 7.4 s
- Prompt tokens
- 493
- Code size
- 14.7 KB
- Finish reason
- stop
- Served by
- OpenAI
- Model id
openai/gpt-5-nano- Reasoning sent
{"effort":"low"}- Max output
- 128,000 tokens
- Generated
- Nov 12, 2026
What it was asked
The prompt
Build a polished Snake game in a single HTML file using vanilla JavaScript and a <canvas>. Requirements: - A grid of at least 20×20 cells, centered on the page. - Arrow keys and WASD control the snake. Quick successive key presses must both be honored, but the snake can never reverse onto itself. - Eating food adds 10 points and grows the snake by one cell; new food never spawns on the snake. - Game over when the snake hits a wall or itself, with an overlay showing the score; Space or Enter restarts, P pauses. - Visual polish: smooth movement, a snake with a distinct head and eyes facing its direction, and a small particle burst when eating. - Display the current score and the best score of the session.
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 · 572 lines
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Snake - Vanilla JS</title>
<style>
:root{
--bg: #0f1220;
--panel: rgba(20,20,40,.9);
--primary: #4cd964;
--accent: #34b5f8;
--snake: #4be2a3;
--snake-head: #1bd1a0;
--food: #ff5a5a;
--shadow: rgba(0,0,0,.25);
}
html,body{
height:100%;
margin:0;
background: radial-gradient( circle at 50% 20%, rgba(80,60,120,.25), transparent 40%), var(--bg);
font-family: system-ui, -apple-system, "Segoe UI", Roboto, Arial;
color:#e9e9e9;
}
.wrap{
min-height:100%;
display:flex;
align-items:center;
justify-content:center;
padding:40px 20px;
}
.stage{
width: min(90vmin, 900px);
display:grid;
grid-template-columns: 1fr;
justify-items:center;
gap:14px;
}
.canvasWrap{
position:relative;
display:flex;
align-items:center;
justify-content:center;
background: linear-gradient(#1a1f33, #0b0f22);
border-radius:16px;
padding:18px;
box-shadow: 0 20px 40px rgba(0,0,0,.25);
}
canvas{
display:block;
image-rendering: crisp-edges;
width: 100%;
height: auto;
max-width: 720px;
border-radius:12px;
}
.hud{
display:flex;
gap:14px;
align-items:center;
flex-wrap:wrap;
}
.badge{
padding:6px 12px;
border-radius:999px;
background: rgba(0,0,0,.35);
border:1px solid rgba(255,255,255,.08);
font-weight:600;
font-family: ui-sans-serif;
font-size: 14px;
}
.overlay{
position:absolute;
inset:0;
display:flex;
align-items:center;
justify-content:center;
background: rgba(0,0,0,.55);
backdrop-filter: blur(2px);
border-radius:12px;
}
.card{
background: var(--panel);
border-radius:14px;
padding:22px 26px;
text-align:center;
max-width: 420px;
box-shadow: 0 6px 20px rgba(0,0,0,.4);
border:1px solid rgba(255,255,255,.08);
}
h1{ font-size:16px; margin:0 0 8px; letter-spacing:.4px; }
p{ margin:8px 0; color:#d8d8d8; }
.row{ display:flex; gap:12px; justify-content:center; flex-wrap:wrap; margin-top:6px; }
.btn{
padding:10px 14px; border-radius:8px;
border:1px solid rgba(255,255,255,.2);
background: #1a1f2b; color:#e9f1ff;
cursor:pointer; font-weight:600;
}
.btn.secondary{ background:#2b2f3a; }
.hint{ font-size:12px; opacity:.9; margin-top:6px; }
@media (max-width: 700px){
canvas{ width: 100%;}
}
/* Eyes glossy highlight */
.eye{ filter: brightness(1.2); }
/* Accessibility: indicate that keyboard controls are needed to start */
.startHint{
position:absolute;
bottom:10px;
left:50%;
transform: translateX(-50%);
font-size:12px;
color:#d8d8d8;
text-shadow:0 1px 0 rgba(0,0,0,.4);
background: rgba(0,0,0,.25);
padding:6px 10px; border-radius:999px;
}
</style>
</head>
<body>
<div class="wrap" id="app">
<div class="stage">
<div class="canvasWrap" style="aspect-ratio:1/1; width: min(78vmin, 720px);">
<canvas id="game" width="520" height="520" aria-label="Snake game canvas"></canvas>
<div class="startHint" id="startHint">Click to start. Use Arrow keys or WASD. Press P to pause. Space/Enter to restart when game over.</div>
<div class="overlay" id="overlay" style="display:none;">
<div class="card" role="dialog" aria-label="Game over dialog">
<h1>Game Over</h1>
<p>Your score: <strong id="scoreShow">0</strong></p>
<p>Best score this session: <strong id="bestShow">0</strong></p>
<div class="row">
<button class="btn" id="restartBtn">Restart (Space / Enter)</button>
<button class="btn secondary" id="closeHintBtn" style="display:none;">Hide Hint</button>
</div>
<p class="hint" style="opacity:.8">Tip: Quick directional input is allowed, but you cannot reverse directly.</p>
</div>
</div>
</div>
<div class="hud" aria-label="Scoreboard" role="group">
<span class="badge" id="score">Score: 0</span>
<span class="badge" id="best">Best: 0</span>
<span class="badge" id="speed">Speed: 10 t/s</span>
<span class="badge" id="state" style="opacity:.8;">Running</span>
</div>
</div>
</div>
<script>
(function(){
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const overlay = document.getElementById('overlay');
const startHint = document.getElementById('startHint');
const scoreEl = document.getElementById('score');
const bestEl = document.getElementById('best');
const scoreShow = document.getElementById('scoreShow');
const bestShow = document.getElementById('bestShow');
const speedEl = document.getElementById('speed');
const stateEl = document.getElementById('state');
const restartBtn = document.getElementById('restartBtn');
const closeHintBtn = document.getElementById('closeHintBtn');
// Grid configuration
const GRID = 25; // at least 20x20
const CELL = 20; // pixels per cell (will scale canvas)
const CANVAS_SIZE = GRID * CELL;
canvas.width = CANVAS_SIZE;
canvas.height = CANVAS_SIZE;
// Game state
let snake = [];
let dir = {x:1, y:0}; // current direction
let nextDir = {x:1, y:0};
let food = {x: 7, y: 7};
let running = false;
let paused = false;
let gameOver = false;
let score = 0;
let best = 0;
// Timing
const TICK = 120; // ms per move
let lastTime = 0;
let accum = 0;
let speedFactor = 1; // can tweak for effect
// Particles
const particles = [];
// Input state
let started = false;
let keyPressedSinceStart = false;
// Init
function spawnSnake() {
const mid = Math.floor(GRID/2);
snake = [
{x: mid-1, y: mid},
{x: mid, y: mid},
{x: mid+1, y: mid}
];
}
function randInt(n){
return Math.floor(Math.random()*n);
}
function spawnFood() {
while(true){
const f = {x: randInt(GRID), y: randInt(GRID)};
if (!snake.some(p => p.x===f.x && p.y===f.y)) {
food = f;
break;
}
}
}
function resetGame(){
score = 0;
scoreEl.textContent = "Score: 0";
snake = [];
spawnSnake();
dir = {x:1, y:0};
nextDir = {x:1, y:0};
spawnFood();
running = false;
paused = false;
gameOver = false;
stateEl.textContent = "Ready";
overlay.style.display = "none";
startHint.style.display = "block";
lastTime = 0;
accum = 0;
}
function startGame(){
running = true;
paused = false;
gameOver = false;
stateEl.textContent = "Running";
overlay.style.display = "none";
startHint.style.display = "none";
}
function endGame(){
gameOver = true;
running = false;
stateEl.textContent = "Game Over";
best = Math.max(best, score);
bestEl.textContent = "Best: " + best;
bestShow.textContent = best;
scoreShow.textContent = score;
scoreEl.textContent = "Score: " + score;
overlay.style.display = "flex";
// keep key events to restart
}
function eatFood(){
score += 10;
scoreEl.textContent = "Score: " + score;
spawnFood();
// particles burst at head
const head = snake[snake.length-1];
for(let i=0;i<12;i++){
const a = (Math.PI*2) * (i/12);
particles.push({
x: head.x + 0.5,
y: head.y + 0.5,
vx: Math.cos(a) * 0.25,
vy: Math.sin(a) * 0.25,
life: 40 + Math.random()*20,
color: i%2? '#ffd166' : '#4ecdc4'
});
}
}
function isOpposite(a,b){
return a.x + b.x === 0 && a.y + b.y === 0;
}
function spawnInitial(){
resetGame();
spawnSnake();
spawnFood();
}
// Input
window.addEventListener('keydown', (e)=>{
if(!started){
// ignore until started
if(e.key === 'Enter' || e.key === ' '){
e.preventDefault();
started = true;
startGame();
}
return;
}
if(gameOver) {
if(e.key===" " || e.key==="Enter"){
e.preventDefault();
resetGame();
startGame();
}
return;
}
const k = e.key;
const map = {
ArrowUp: {x:0, y:-1},
ArrowDown:{x:0, y:1},
ArrowLeft:{x:-1, y:0},
ArrowRight:{x:1, y:0},
w:{x:0, y:-1},
W:{x:0, y:-1},
a:{x:-1, y:0},
A:{x:-1, y:0},
s:{x:0, y:1},
S:{x:0, y:1},
d:{x:1, y:0},
D:{x:1, y:0}
};
if(map[k]){
const nd = map[k];
// prevent reverse
if(!(nd.x === -dir.x && nd.y === -dir.y)){
nextDir = nd;
}
e.preventDefault();
} else if(k === 'p' || k === 'P'){
togglePause();
e.preventDefault();
}
});
// Pause toggle
function togglePause(){
if(gameOver) return;
paused = !paused;
stateEl.textContent = paused ? "Paused" : "Running";
}
// Drawing
function drawGrid(){
ctx.clearRect(0,0,CANVAS_SIZE,CANVAS_SIZE);
// faint grid
ctx.globalAlpha = 0.15;
ctx.strokeStyle = '#2a2a2a';
ctx.lineWidth = 1;
for(let i=0;i<=GRID;i++){
ctx.beginPath();
ctx.moveTo(i*CELL+0.5, 0);
ctx.lineTo(i*CELL+0.5, CANVAS_SIZE);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0, i*CELL+0.5);
ctx.lineTo(CANVAS_SIZE, i*CELL+0.5);
ctx.stroke();
}
ctx.globalAlpha = 1;
}
function drawSnake(){
if(snake.length===0) return;
for(let i=0;i<snake.length;i++){
const s = snake[i];
const x = s.x*CELL;
const y = s.y*CELL;
const isHead = i===snake.length-1;
// body
ctx.fillStyle = isHead ? '#2bd36e' : '#1e9a5f';
ctx.strokeStyle = '#0a5138';
ctx.lineWidth = 2;
ctx.fillRect(x+2, y+2, CELL-4, CELL-4);
ctx.strokeRect(x+1, y+1, CELL-2, CELL-2);
// head eyes
if(isHead){
ctx.fillStyle = '#000';
const ey = Math.floor(y + CELL/2);
const ex = Math.floor(x + CELL/2);
// direction facing
const dirV = dir;
const eyeOffset = 4;
const left = {x: ex - dirV.y*eyeOffset, y: ey - dirV.x*eyeOffset};
const right = {x: ex + dirV.y*eyeOffset, y: ey + dirV.x*eyeOffset};
ctx.fillRect(left.x-2, left.y-2, 4, 4);
ctx.fillRect(right.x-2, right.y-2, 4, 4);
}
}
}
function drawFood(){
const x = food.x*CELL;
const y = food.y*CELL;
const r = CELL*0.38;
// body
ctx.fillStyle = '#ff6b6b';
ctx.beginPath();
ctx.arc(food.x*CELL + CELL/2, food.y*CELL + CELL/2, r, 0, Math.PI*2);
ctx.fill();
// highlight
ctx.fillStyle = '#ffd6d6';
ctx.fillRect(food.x*CELL + CELL*0.3, food.y*CELL + CELL*0.3, CELL*0.4, CELL*0.4);
}
function drawParticles(){
for(let i=particles.length-1; i>=0; i--){
const p = particles[i];
p.x += p.vx;
p.y += p.vy;
p.life--;
if(p.life<=0){
particles.splice(i,1);
continue;
}
ctx.fillStyle = p.color;
ctx.fillRect(p.x*CELL, p.y*CELL, 2, 2);
}
}
function updateParticles(){
// cleanup handled in draw loop
}
function drawDebug(){
// optional: nothing heavy
}
// Update logic per tick
function tick(){
// update direction
dir = nextDir;
// compute next head
const head = snake[snake.length-1];
const nx = head.x + dir.x;
const ny = head.y + dir.y;
const newHead = {x: nx, y: ny};
// collision with walls
if(nx < 0 || ny < 0 || nx >= GRID || ny >= GRID){
endGame();
return;
}
// collision with self
if(snake.some(p => p.x===newHead.x && p.y===newHead.y)){
endGame();
return;
}
// move
snake.push(newHead);
// check food
if(newHead.x === food.x && newHead.y === food.y){
eatFood();
} else {
// remove tail
snake.shift();
}
}
// Main loop
function loop(t){
if(!lastTime) lastTime = t;
const dt = t - lastTime;
lastTime = t;
if(running && !paused && !gameOver){
accum += dt * speedFactor;
const step = TICK;
while(accum >= step){
tick();
accum -= step;
}
}
// render
drawGrid();
drawSnake();
drawFood();
drawParticles();
requestAnimationFrame(loop);
}
// Init
function init(){
// scale to fit nicely in 1280x800, keep grid centered by CSS
spawnInitial();
best = 0;
bestEl.textContent = "Best: " + best;
bestShow.textContent = best;
scoreEl.textContent = "Score: " + score;
// Start in demo mode: AI plays (self-playing)
// We'll implement a simple AI: each tick set nextDir toward food if not reversing
started = false;
// Self-playing demo: a light AI that adjusts nextDir towards food while avoiding immediate death
function aiStep(){
if(gameOver || paused) return;
// basic greedy: prioritize axis that reduces distance
const head = snake[snake.length-1];
const dx = food.x - head.x;
const dy = food.y - head.y;
const candidates = [];
if(dx !== 0) candidates.push({x: Math.sign(dx), y:0});
if(dy !== 0) candidates.push({x:0, y: Math.sign(dy)});
// shuffle to add variety
for(let i=candidates.length-1;i>0;i--){
const j = Math.floor(Math.random()*(i+1));
[candidates[i], candidates[j]] = [candidates[j], candidates[i]];
}
// try candidates in order
for(const c of candidates){
if(!(c.x === -dir.x && c.y === -dir.y)){
const nd = c;
// simulate a quick safety check: next head position not colliding with body or wall
const nx = head.x + nd.x;
const ny = head.y + nd.y;
if(nx>=0 && ny>=0 && nx<GRID && ny<GRID && !snake.some(p => p.x===nx && p.y===ny)){
nextDir = nd;
break;
}
}
}
// schedule next update by nudging the global loop's tick
}
// run aiStep on a timer by hooking into requestAnimationFrame loop through a small chance to adjust
setInterval(aiStep, Math.max(60, TICK*0.9));
}
// Bind restart
restartBtn.addEventListener('click', ()=>{
resetGame();
startGame();
});
closeHintBtn.addEventListener('click', ()=>{
startHint.style.display = 'none';
});
// Start in demo AI mode with overlay prompt
// We override user click requirement: we show hint until user interacts
canvas.addEventListener('click', ()=> {
if(!started){
started = true;
startGame();
}
}, {once:true});
// Keyboard to start too (space/enter)
window.addEventListener('keydown', (e)=>{
if(!started && (e.key === ' ' || e.key === 'Enter')){
e.preventDefault();
started = true;
startGame();
}
});
// Kickoff
resetGame();
init();
// Start render loop
requestAnimationFrame(loop);
// Resize handling (keep grid crisp)
function resize(){
// optional: no dynamic scaling to keep grid consistent
}
window.addEventListener('resize', resize);
})();
</script>
</body>
</html>Reasoning trace (448 tokens)
**Planning HTML output for game** I'm designing an HTML file for a self-playing demo of a game. It should start automatically with a message prompting the user to click or press a key. I'll implement simple AI that moves toward food while avoiding walls and itself. For simplicity, I’ll use a greedy approach to choose directions that minimize the distance to food without hitting obstacles. The game will also support controls, display the score on game over, and allow for restarting the game. I'll use a grid size of 25x25 for performance!**Designing game mechanics** I'm considering how to implement particle effects when the snake eats, generating small particles from its head. I need to track the best score during a session, keeping it stored in a variable. After clicking the canvas, I’ll start listening for key events and display a "Click to start" overlay. I must keep everything self-contained with inline CSS and JavaScript. I’ll manage the snake’s direction to avoid reversing and set rules for food spawning and particle generation during the game. It sounds fun to animate everything with a tick every 120ms!**Implementing game score display** I'm planning to display the current score and the best score. When the game is over, I'll show an overlay that includes both scores and a restart button that can be activated with Space or Enter. There will be a "Click to start" overlay until the game begins, which starts with any key press or the Space bar. If the game is paused, movement will stop, but rendering will continue, and I'll display a "Paused" message. I'll keep the best score in memory since I'm not allowed to use localStorage. Let's get coding!