How to Make a Browser Game With AI: From Prompt to Playable HTML5

Build your first browser game with AI using a complete HTML5 example. Learn game prompts, Canvas, movement, scoring, debugging, testing and how to publish.

Dark workstation with multiple computer monitors showing software development tools

Can you make a browser game with AI? Yes. For a small game, you can describe the rules in plain English, use an AI coding assistant to help write HTML and JavaScript, and test the result in a web browser. The important part is the last step: actually playing the game and correcting what does not work. A persuasive-looking block of generated code is not proof of a playable game.

In this beginner-friendly tutorial, you’ll build a tiny arcade game called Star Catch. You move a paddle across the bottom of the screen, collect falling gold stars, avoid red meteors, and aim for 100 points before the 60-second timer ends. We’ll use a single HTML file so you can understand every moving part without needing an account, an AI API key, an external library, or a complicated build process.

What you’ll learn: how to write an actionable AI game prompt, structure an HTML5 canvas game, handle keyboard input, animate with elapsed time, detect collisions, track game state, debug AI-generated code, and prepare a prototype for publishing.

This is a small teaching example, not a finished commercial game. The steps work whether you generate the first version with ChatGPT, Claude, another coding assistant, or write the code yourself. Use the AI to accelerate implementation; use your own judgment to validate the design.

1. Choose a game with one clear goal

Many first attempts at AI game development fail because the request is too vague: “Make me an amazing multiplayer game with realistic physics and a huge world.” That gives a coding assistant no stable boundary for deciding what belongs in version one. Start instead with a loop you can explain in a sentence: move left and right, catch safe items, avoid dangerous items, score points, and restart.

Our first milestone has six rules: arrow keys or A/D move the paddle; gold collectibles add ten points; red meteors remove one life; the player starts with three lives; the round lasts up to 60 seconds; reaching 100 points wins. You lose if the timer reaches zero or you lose all your lives.

The output is intentionally modest. Once this loop is responsive and understandable, it will be much easier to decide whether extra effects, music, levels, upgrades, or different hazards are worth adding.

2. Get the minimum tools ready

You need a modern desktop browser, a plain-text code editor, and optionally an AI coding assistant. A text editor such as VS Code is convenient because it offers syntax highlighting and a file explorer, but this tutorial does not depend on any one application. Save the project in a new folder as index.html — not index.html.txt.

This example uses the browser’s <canvas> element to draw the game. Canvas is widely supported in modern browsers and can draw shapes and animations using JavaScript. There is no game engine to install. For larger Phaser, Three.js, or module-based projects, plan on using a local web server because browser security restrictions can prevent modules or assets from loading directly from a file:// address. MDN’s Canvas tutorial and Phaser’s development environment guide explain these distinctions.

3. Prompt the AI with acceptance criteria

The best starting prompt says what the player does, which technologies to use, what to avoid, and how to confirm that the output works. Copy and adapt this example:

Game-building prompt: Create a complete, self-contained desktop browser game called Star Catch in one index.html file using HTML, CSS, vanilla JavaScript, and Canvas. A paddle moves left and right with A/D or arrow keys. Gold stars fall and add 10 points when collected. Red meteors remove a life. The player starts with three lives and 60 seconds. Reaching 100 points wins; running out of lives or time loses. Include an obvious Start / Restart button, visible score/lives/time, and clear win/loss messages. No external assets, libraries, logins, or networking. Use elapsed time for movement; prevent multiple animation loops when restarting. Return the complete file and a manual test checklist.

Notice how much this improves on “make a fun game.” It identifies the platform, input, loop, values, states, and exclusions. If the AI ignores a condition, point to that condition and request the smallest possible correction rather than starting over from scratch.

A useful second prompt is: “Before adding new features, explain the current game’s state variables and input loop. Identify three likely bugs and describe reproducible tests.” This encourages inspection before expansion.

4. Build and run the first playable HTML5 game

The starter code below is deliberately small enough to read. It contains the page, styling, canvas, input, spawning, collisions, scoring, game-over logic, and one persistent animation loop. Save the complete example as index.html and open the file in a browser. Press Start / Restart, move using A/D or the arrow keys, and try to reach 100 points.

Starter source code: Expand the code below to inspect or copy the complete minimal game. You can improve the visuals after the rules are working.

View the complete HTML5 Star Catch source (single-file example)
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Star Catch</title>
<style>
body{background:#0b1530;color:white;font:18px system-ui;text-align:center}
canvas{display:block;width:min(95vw,800px);height:auto;margin:20px auto;border:2px solid #5ac9ff;border-radius:12px;background:#101f44}
button{font:inherit;padding:10px 24px;cursor:pointer}
</style>
<h1>Star Catch</h1>
<p id="hud" aria-live="polite">Score 0 · Lives 3 · Time 60</p>
<button id="play">Start / Restart</button>
<canvas id="game" width="800" height="450" aria-label="Catch yellow stars and avoid red meteors"></canvas>
<p>Move with A / D or the arrow keys. Reach 100 points to win.</p>
<script>
const canvas=document.querySelector('#game'), ctx=canvas.getContext('2d');
const hud=document.querySelector('#hud'), keys=new Set();
let state='ready', score=0, lives=3, time=60, playerX=400;
let items=[], spawnTimer=0, last=null;
document.querySelector('#play').onclick=()=>{
  state='playing';score=0;lives=3;time=60;playerX=400;
  items=[];spawnTimer=0;last=null;showHud();
};
function showHud(){hud.textContent='Score '+score+' · Lives '+lives+' · Time '+Math.ceil(time);}
addEventListener('keydown',e=>{
  if(['ArrowLeft','ArrowRight'].includes(e.code))e.preventDefault();
  keys.add(e.code);
});
addEventListener('keyup',e=>keys.delete(e.code));
addEventListener('blur',()=>keys.clear());
document.addEventListener('visibilitychange',()=>{
  if(document.hidden&&state==='playing')state='paused';
});
canvas.addEventListener('pointerdown',e=>{
  if(state==='playing'){
    const rect=canvas.getBoundingClientRect();
    playerX=(e.clientX-rect.left)*800/rect.width;
  }
});
function update(dt){
  if(state!=='playing')return;
  time=Math.max(0,time-dt);
  const move=Number(keys.has('ArrowRight')||keys.has('KeyD'))
    -Number(keys.has('ArrowLeft')||keys.has('KeyA'));
  playerX=Math.max(45,Math.min(755,playerX+move*430*dt));
  spawnTimer-=dt;
  if(spawnTimer<=0){
    items.push({x:30+Math.random()*740,y:-20,bad:Math.random()<.25});
    spawnTimer=.45;
  }
  for(let i=items.length-1;i>=0;i--){
    const o=items[i];o.y+=210*dt;
    if(Math.abs(o.x-playerX)<50&&Math.abs(o.y-405)<27){
      if(o.bad)lives--;else score+=10;
      items.splice(i,1);
    }else if(o.y>480)items.splice(i,1);
  }
  if(score>=100)state='won';
  else if(lives<=0||time===0)state='lost';
  showHud();
}
function draw(){
  ctx.clearRect(0,0,800,450);
  ctx.fillStyle='#60d9ff';
  ctx.fillRect(playerX-45,395,90,20);
  for(const o of items){
    ctx.fillStyle=o.bad?'#ff617d':'#ffd166';
    ctx.beginPath();ctx.arc(o.x,o.y,16,0,Math.PI*2);ctx.fill();
  }
  if(state!=='playing'){
    ctx.fillStyle='#fff';ctx.textAlign='center';
    ctx.font='bold 32px system-ui';
    ctx.fillText(({ready:'Press Start',won:'You win!',lost:'Game over',paused:'Paused — press Restart'})[state],400,215);
  }
}
function frame(now){
  const dt=last===null?0:Math.min((now-last)/1000,.05);
  last=now;update(dt);draw();requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
</script>
</html>

This reference game uses only browser features, and its visuals are deliberately simple: a cyan paddle, yellow collectibles, and red hazards. That makes movement and collision rules easy to inspect. An extended, more polished version can add a starfield, particle effects, pause/resume controls, and pointer steering. Start with this smaller baseline first.

If you get a blank screen, first confirm you copied the opening and closing <script> tags and did not save the file as text with a hidden .txt extension. Open the browser developer console to find the exact JavaScript error before changing anything else.

5. Understand the five systems that make it playable

Game state: what is happening right now?

The state variable records whether a round is waiting to start, playing, won, lost, or paused. The other important values — score, lives, time, and playerX — describe the current run. When the player clicks Start / Restart, the program resets them and empties the falling-object list. Without that reset, restarting can leave old hazards on screen or preserve the previous result.

Keyboard input: record key presses, don’t guess

The program stores active keys in a Set. Every update calculates a direction from held keys: left is -1, right is +1, neither or both is 0. This prevents movement from continuing after a key is released. We also clear the set if the browser window loses focus. That matters because the browser may not always deliver the release event after a user switches tabs.

Animation: use time, not frame counts

The browser calls requestAnimationFrame() before painting an animation frame. The callback receives a timestamp. Subtracting the previous timestamp gives elapsed time, or dt. We multiply movement speed by dt, expressed in seconds, so a display refreshing faster does not automatically produce a faster game. This is the basic pattern shown in MDN’s Canvas animation guide.

The example caps dt at 0.05 seconds. That prevents an unexpectedly large single update after a long frame, although a more sophisticated game might instead use a fixed simulation timestep. Crucially, it starts the requestAnimationFrame() loop once, outside the Restart handler. A common AI-generated bug is to create a second loop each time the user starts over.

Objects and collision: update, detect, remove

Each falling item is a simple object with an x/y position and a bad flag. The game advances it downward, checks whether it intersects the paddle area, and changes the score or lives. It loops backwards through the array when removing items so no object is skipped. For a teaching prototype, this rectangular collision approximation is adequate. For precise character shapes or complex worlds, you’d use more sophisticated collision geometry and likely a game framework.

Drawing: keep it separate from the rules

The update() function changes positions and rules. The draw() function renders those values on Canvas. Separating them makes debugging easier. If your score increases correctly but the sprite is invisible, you can look at rendering without rewriting the scoring system.

6. Test your game before asking for more features

Don’t judge completion by whether the first frame looks attractive. Open the game in a fresh browser tab and play several rounds. The starter source above is deliberately predictable enough to check with a small acceptance-test list.

  1. Start: Confirm the instructions and Start / Restart button appear. Click it. The paddle and falling items should appear.
  2. Move: Hold the right arrow, release it, then hold A. Verify the paddle moves in the expected screen direction and stops on release.
  3. Bounds: Hold left or right at the edge. The paddle must remain inside the canvas instead of disappearing offscreen.
  4. Score: Catch one yellow object. Your score should increase by 10, not by an arbitrary number or on every frame of contact.
  5. Damage: Touch a red object. Your lives should decrease by exactly one.
  6. End states: Confirm that reaching 100 points wins. Running out of lives or reaching zero time should stop the round and show a result.
  7. Restart: Restart several times in succession. Score, lives, timer, and falling items must reset. The simulation must not run faster after repeated restarts.
  8. Resize: Make the browser window narrower. Verify that Canvas still fits the page and the button remains usable.
  9. Focus: Switch away and return. The minimal sample deliberately enters a paused state when the tab becomes hidden; press Restart to begin a fresh run.
  10. Console: Open developer tools and check for JavaScript errors or failed file loads.

The example is intended for desktop-first learning, although the Canvas sizing adapts to smaller screens and tapping the canvas can reposition the paddle. For a touch-first commercial release, add visible touch controls, test actual devices, and account for accessibility needs beyond a single Canvas label.

How to record a bug: Save the browser name, exact reproduction steps, expected behavior, actual behavior, error message, and — if the failure is visual — a screenshot. This evidence lets you ask the AI for a narrow, testable fix rather than another full rewrite.

7. Use AI to debug without breaking the game

When an AI coding assistant receives a vague request such as “fix the game,” it may change unrelated systems. Provide a compact bug report that identifies the existing working baseline and the exact behavior to repair.

Example debugging prompt: In my single-file Canvas game, pressing Restart repeatedly makes falling objects appear too quickly. Expected: the original spawn interval stays the same no matter how often I restart. Inspect the animation loop and spawn timer. Identify the root cause, change as few lines as possible, preserve controls and scoring, and give me three manual regression tests.

If you find the direction reversed, say which key was pressed and how the paddle moved. If the game starts but nothing renders, include the developer-console message and confirm the canvas has a nonzero width and height. If the timer counts down too fast, inspect whether elapsed time is being measured in milliseconds instead of seconds — or whether multiple loops are running.

Use source-control commits or timestamped copies of your HTML file before every major change. Keep a short changelog: version 0.1 — playable loop; 0.2 — control fix; 0.3 — audio; 0.4 — mobile adaptation. A new version should preserve the previous tests unless the design intentionally changes them.

There is also a distinction between a bug and a design preference. “The timer displays a negative value” is objectively broken. “The game feels too slow” requires a tuning target: for example, increase paddle speed from 430 to 520 pixels per second and ask three testers whether it improves control.

8. Make the first version feel like a real game

After the base version passes its tests, improve one layer at a time. This is where the AI is useful for proposing small additions, but each proposal needs a way to evaluate it.

Upgrade A: readable visual feedback

Replace flat rectangles with a consistent visual language. Give gold collectibles a warm glow, give hazards a clearly different shape as well as color, add a short particle burst on collision, and animate the paddle subtly. Use a simple palette so the gameplay objects stand out from the background. Do not rely on color alone to communicate danger. Keep text and controls readable against the artwork.

Upgrade B: audio and feel

Add one short sound when collecting an item and a distinct hit sound for damage. Start playback only after a user interaction because browsers commonly restrict automatic audio. Provide a mute control; avoid playing the same effect dozens of times at once. For more action-oriented games, experiment with acceleration and slight screen feedback, then test whether the feedback helps or distracts.

Upgrade C: progression and retention

Try a simple combo, a faster falling speed every 15 seconds, or a temporary shield. Add only one new rule per iteration. If the player doesn’t understand why they lost, adding more objects won’t solve the problem. A good first session should teach the controls, communicate success and failure, and offer a reason to try again.

One useful follow-up AI prompt: “Improve the Star Catch graphics with a cohesive midnight-blue arcade style. Add subtle stars and a small collection burst. Do not change scoring, controls, win/loss thresholds, or game-state transitions. Respect reduced-motion preferences where practical. Give me a screenshot checklist and changed lines.”

Remember that an AI-generated mockup is not the same as integrated game art. Test the actual render at the intended canvas size. Artwork that looks impressive at full resolution may become unreadable at the size players see on a game portal.

9. Share the HTML5 game and prepare for publishing

For this simple example, the deliverable is one HTML file. Open it in your browser, verify it works, and keep a working copy. You can deploy it to a suitable static web host once the controls, assets, and instructions are ready. If you expand into separate scripts, textures, or audio files, preserve the folder structure and test via a local development server first.

For WordPress, prefer a dedicated game page that links to or embeds a separately hosted build. A WordPress blog post is not a general-purpose JavaScript execution environment: editors and security plugins may strip inline scripts, and iframe or upload policies vary between hosts. Use staging before enabling a new embed on a public gaming website. Never disable important site protections merely to make one untrusted script run.

Before making the game publicly available, check the title and description, cover image, controls, mobile/desktop support statement, restart behavior, console output, keyboard focus, any data collection, and rights to third-party assets. If you use AI-generated graphics, music, or code from external sources, review the relevant tool terms and licences. Publishing a page does not automatically give you rights to every component it contains.

A portal can make the playable build easier to discover with a dedicated game landing page, instructions, screenshots, links to related tutorials, and accurate metadata. These help readers who found the game from search understand both how to play and how the game was made.

10. Common questions

Do I need a game engine to make an HTML5 game with AI?

No. A simple Canvas game can be written with HTML, CSS and JavaScript. A framework becomes useful when you need bigger levels, more animation systems, asset pipelines or more complex collisions.

Should I choose Phaser or Three.js next?

For most straightforward 2D browser arcade and platform games, Phaser provides useful game-oriented structures. For custom 3D scenes, Three.js is a rendering library you can build on. Choose based on the experience you want and test the intended deployment format early.

Does AI-generated code always run on the first attempt?

No. Even apparently complete answers may include syntax errors, missing files, broken controls or incorrect assumptions. Running acceptance tests and reviewing the resulting code are part of development, not optional extras.

Can I make a game without prior programming experience?

You can start with a small example, but understanding basic variables, functions, arrays and browser developer tools will help you fix problems and become less dependent on trial-and-error prompting.

What should I build after Star Catch?

Try an obstacle-dodging runner, a small puzzle game or a one-level platformer. Keep the next project narrow enough to finish, and add a game design document before making it substantially larger.

Next steps: keep learning at Blinkcade Academy

Your first milestone is not writing the perfect prompt. It’s obtaining a playable build, understanding how it works, and making it better through controlled changes. Once you can play and restart Star Catch reliably, experiment with visuals, sound, difficulty and presentation — one measurable improvement at a time.

Explore the complete Vibe Coding Games guide for the full development workflow, visit Blinkcade Academy for additional lessons, and play Blinkcade games for inspiration.

Further reading: MDN Canvas tutorial, Canvas animation guide, and Phaser’s local development guidance.

Keep learning

The complete guide Vibe Coding Games: The Complete Guide to Building Games With AI
  1. Three.js & 3D Games Intermediate 15 min read

    Build a Match-3 Browser Game With Three.js and AI (Complete Tutorial + Source Code)

    Build a Three.js match-3 browser game with AI: 3D runes, an 8×8 board, legal swaps, gravity, cascades, scoring, raycasting, tests and downloadable source code.

  2. AI Tools & Prompts Beginner 21 min read

    Best AI Prompts for Game Mechanics, Movement and Controls (Copy-and-Paste Guide)

    Use practical AI prompts to design and debug player movement, jumping, collisions, combat, camera controls, mobile input and game feel in HTML5, Phaser and Three.js games.

  3. Game Design Beginner 16 min read

    How to Write a Game Design Document With AI (+ Free GDD Template)

    Write a game design document with AI using a free GDD template, a filled-in game example, copyable prompts and practical checklists for development.

All Academy tutorials

5 comments

Leave a Reply

Your email address will not be published. Required fields are marked *