sodcalculator

10 Tech How-To

TypeScript Arcade: 8 Classic Games in One Browser Cabinet

Guide 10-45164 · Updated · Step by step

This guide shows you how to build a single-page TypeScript arcade that hosts eight classic games—Snake, Tetris, Pong, Breakout, Space Invaders, Pac-Man, Minesweeper, and Frogger—all selectable from a shared on-screen cabinet. You’ll get a unified menu, common score tracking, and a consistent control scheme, all running in any modern browser. You’ll need a basic understanding of TypeScript, HTML canvas, and object-oriented programming, plus Node.js and npm installed.

What You’ll Need

  • Node.js (v18 or later) and npm
  • A code editor (VS Code recommended)
  • Basic TypeScript knowledge (classes, interfaces, modules)
  • Familiarity with HTML5 Canvas API
  • Git (optional, for version control)

Step-by-Step

  1. Set up the project skeleton. Create a new directory and run npm init -y. Install TypeScript and Vite as dev dependencies: npm install -D typescript vite. Create a tsconfig.json with "target": "ES2020", "module": "ESNext", and "strict": true.
  2. Create the HTML shell. Make an index.html with a full-screen canvas element and a div for the cabinet frame. Include a menu overlay with buttons for each game. Link your TypeScript entry file via a module script.
  3. Define the game interface. Create src/types.ts and export an interface Game with methods: init(), update(deltaTime: number), render(ctx: CanvasRenderingContext2D), handleInput(event: KeyboardEvent), and destroy(). Also define a GameState enum for menu, playing, paused, and game over.
  4. Build the game manager. Create src/GameManager.ts as a singleton class that holds the current game instance, manages the game loop using requestAnimationFrame, and handles switching between games. It should also maintain a shared score and high-score list.
  5. Implement a base class. Create src/BaseGame.ts that implements the Game interface with common logic: canvas context reference, input state (keys pressed), a simple collision helper, and a score property. Extend this for each game.
  6. Code the first game: Snake. Create src/games/Snake.ts. Use a grid-based approach: store the snake as an array of {x, y} points, move on a timer, check for food collision, and detect self-collision. Render as filled rectangles.
  7. Code the second game: Tetris. Create src/games/Tetris.ts. Define the seven tetromino shapes as 2D arrays. Implement rotation, collision detection against the board and walls, line clearing, and piece locking. Use a simple gravity timer.
  8. Code the third game: Pong. Create src/games/Pong.ts. Use two paddles controlled by keyboard (W/S and arrow keys). Implement ball movement, bounce off top/bottom walls, and paddle collisions. Track score when ball passes left or right edge.
  9. Code the fourth game: Breakout. Create src/games/Breakout.ts. Create a paddle at the bottom, a ball, and a grid of bricks. Handle ball-brick collisions by checking overlap and reversing direction. Remove bricks on hit and increase score.
  10. Code the fifth game: Space Invaders. Create src/games/SpaceInvaders.ts. Create a player ship, a grid of aliens, and bullets. Move aliens side to side and down. Detect bullet-alien collisions and alien-player collisions.
  11. Code the sixth game: Pac-Man. Create src/games/PacMan.ts. This is the most complex. Define a maze as a 2D array of walls. Implement Pac-Man movement with direction input, pellet collection, and ghost AI using simple chase and scatter modes. Use a tile-based rendering.
  12. Code the seventh game: Minesweeper. Create src/games/Minesweeper.ts. Generate a grid of cells with random mines. Implement left-click to reveal, right-click to flag, and flood-fill for empty cells. Check for win/loss conditions.
  13. Code the eighth game: Frogger. Create src/games/Frogger.ts. Move a frog across lanes with cars and logs. Detect collisions with cars (death) and water (need to be on a log). Reach the top to score points.
  14. Create the cabinet UI. In index.html, style the cabinet with CSS: a wooden frame, a marquee with the game title, and a button panel. Use CSS grid or flexbox for the menu. When a game is selected, hide the menu and show the canvas.
  15. Wire up the menu. In src/main.ts, import the GameManager and all game classes. Add click listeners to menu buttons that call gameManager.startGame(gameName). Also add keyboard shortcuts (e.g., Escape to return to menu).
  16. Implement the game loop. In GameManager, use requestAnimationFrame to call update and render on the current game. Use performance.now() to calculate deltaTime and clamp it to avoid huge jumps.
  17. Add shared controls. In the GameManager, listen for keydown/keyup events and pass them to the current game’s handleInput. Also handle global keys: P for pause, M for mute (if you add sound), and Escape to return to menu.
  18. Test each game. Run npm run dev to start the Vite dev server. Click through each game and verify basic functionality. Fix any bugs in collision detection or rendering.
  19. Build for production. Run npm run build to compile TypeScript and bundle with Vite. The output will be in the dist folder. Deploy that folder to any static host.

Common Mistakes

  • Using a single global game loop without deltaTime. This causes games to run at different speeds on different monitors. Always pass deltaTime to update.
  • Not resetting game state when switching games. Ensure each game’s init() resets all variables, otherwise you’ll start with leftover state from a previous session.
  • Hardcoding canvas size. The canvas should resize to fit the cabinet. Use window.innerWidth and window.innerHeight or a fixed aspect ratio with CSS scaling.
  • Forgetting to clear the canvas each frame. Without ctx.clearRect() or ctx.fillRect() with a background color, you’ll get motion trails.
  • Not handling keyboard events on the correct element. Attach listeners to window or document, not the canvas, to avoid focus issues.

Tips

  • Use a fixed timestep for physics-based games like Pong and Breakout to ensure consistent behavior regardless of frame rate.
  • For grid-based games (Snake, Tetris, Pac-Man, Minesweeper), define a tile size constant and use it for all positioning.
  • Keep the game logic separate from rendering. This makes testing easier and allows you to add a headless mode for automated tests.
  • Use a shared color palette and font to give the cabinet a cohesive retro look.
  • Add a simple sound system using the Web Audio API to generate beeps for collisions and scoring—no external files needed.
  • Consider adding a pause overlay that also shows the current score and high score.

Troubleshooting

  • Game runs too fast or too slow. Check that you’re using deltaTime in update. If you’re using a fixed timestep, ensure the step is reasonable (e.g., 60 updates per second).
  • Canvas is blank. Verify that the canvas context is obtained correctly and that you’re calling render after clearing. Also check for JavaScript errors in the console.
  • Keyboard input not working. Ensure the window has focus. Add a click listener on the canvas to focus it, or attach key listeners to window.
  • Game crashes when switching. Make sure each game’s destroy() method removes any event listeners or intervals it created. Also call init() when starting a game.
  • Collision detection is off. For rectangle collisions, use the AABB (axis-aligned bounding box) method: check if a.x < b.x + b.width and similar. Log positions to debug.
  • Build fails with TypeScript errors. Run npx tsc --noEmit to see errors. Common issues: missing types for canvas, or strict null checks. Fix by adding proper type annotations.

Frequently Asked Questions

Can I add more games later?

Yes. Create a new class that implements the Game interface and add it to the menu. The GameManager will handle it automatically.

Do I need a server to run this?

No. The built files are static. You can open dist/index.html directly, though some browsers may restrict certain APIs. A simple local server is recommended for development.

How do I save high scores?

Use localStorage to store the high scores per game. In the GameManager, read and write to localStorage when a game ends.

Can I use this on mobile?

Touch controls would need to be added. The current implementation is keyboard-only. You can add on-screen buttons for mobile.

What if I want to change the cabinet's look?

All styling is in CSS. Modify the cabinet frame, marquee, and button styles to match your preferred theme.

Is it okay to use this for a commercial project?

Yes, as long as you own the code you write. The game concepts are classic and not copyrighted, but ensure any assets you create are original.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →