KAUSHIK SARKARBlogs
Game Prompts

Revise & Re-Flip: Bringing a Classic Game to Canvas with Accessibility in mind

By Kaushik Sarkar · · 13 min read
Hero screenshot of the finished Reversi game

Starting with the .NET Console Games project, I've been exploring AI integration in game development. This tutorial delves into building a Reversi game using AI coding tools from a prompt. The project aims to create a classic game project named 'ReversiCraft' with a single index.html file, leveraging JavaScript, HTML5 canvas API, and keyboard/touch controls. Features include a responsive design, accessibility, and sound effects.

What you need

  • A computer with a web browser
  • Basic knowledge of HTML5, CSS, and JavaScript
  • A text editor or code editor (e.g., Visual Studio Code, Sublime Text)
  • A development environment (e.g., Node.js)
  • A web hosting service (e.g., GitHub Pages, Netlify, Vercel)

The full prompt

Build a Reversi game project named "ReversiCraft" using HTML5 canvas with a single index.html file. The tech stack includes JavaScript, HTML5 canvas API, keyboard and touch controls, a responsive design, and accessibility features.

- **Features:**
  - Implement a classic Reversi game board.
  - Allow players to toggle sound effects.
  - Provide a restart button.
  - Display the current score.
  - Implement animations for flipping pieces and player turns.
  - Support for touch controls on mobile devices.
  - Ensure the game is accessible for users with disabilities.
  - Implement responsive design for different screen sizes.

- **Visual Design:**
  - Use a clean, modern design with a black and white checkerboard pattern for the game board.
  - Include a simple, clean font for displaying scores and messages.
  - Use a color scheme of black, white, and a muted gray for the background and buttons.

- **Controls:**
  - Provide clear instructions and feedback for players.
  - Allow players to place their pieces by clicking or tapping on the board.

- **Data/State Handling:**
  - Use a JavaScript object to manage the game state, including the board, current player, and game over status.

- **Responsive and Accessibility Requirements:**
  - Ensure the game is responsive and works well on various devices and screen sizes.
  - Implement accessibility features such as keyboard navigation and screen reader support.

The output should be a structured file with a single index.html file containing all the necessary code to run the ReversiCraft game. Run the game by opening the index.html file in a web browser.

1Open the AI Coding Assistant Tool

Open your AI coding assistant tool (e.g., ChatGPT, Claude, Bolt) and paste the full prompt from this website.

Pro tip: Ensure you copy the exact prompt from this website.

2Create a New Project

Create a new project in your development environment. This can be a new folder or a new project in your code editor. For the ReversiCraft game, create a new folder named "ReversiCraft" in your project directory. Inside the "ReversiCraft" folder, create a new folder named "assets" to store any images or media files you will need for the game. Additionally, create a new file named "index.html" in the "ReversiCraft" folder. This file will contain all the HTML content for the game. Finally, create a new file named "script.js" in the "ReversiCraft" folder. This file will contain all the JavaScript code for the game.

Pro tip: Don't forget to save your project regularly.

3Write the HTML for the Game

---

Write the HTML for the game in a new file called index.html. This should include the canvas element where the game will be rendered, along with a div for displaying the current score and a div for instructions. The canvas should have a width of 400 pixels and a height of 400 pixels, and should have a black border with a 2px solid style.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ReversiCraft</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div id="game-container">
        <canvas id="game-board" width="400" height="400" style="border: 2px solid black;"></canvas>
        <div id="score-container">
            <p id="score">Score: 0</p>
        </div>
    </div>
    <div id="instructions">
        <h2>Instructions:</h2>
        <p>Use the keyboard to play the game.</p>
        <p>Press 'R' to restart the game.</p>
        <p>Click or tap on the board to place your pieces.</p>
    </div>
    <script src="script.js"></script>
</body>
</html>

This HTML file sets up the basic structure of the game, including the canvas element for rendering the game board, a div for displaying the score, and a div for instructions. The canvas has a black border for better visibility, and the score and instructions are styled for clarity and accessibility.

AI coding assistant generating the Reversi game code
AI coding assistant generating the Reversi game code

Pro tip: Use a clean and modern design for the game board and HUD.

4Write the CSS for the Game

Write the CSS for the game in a new file called style.css. This should include styles for the game board, pieces, and HUD.

  • Game Board:
  • Set the width and height of the canvas to 400px by 400px.
  • Use a border property to add a border around the canvas to make it stand out.
  • Use a background-color of #333333 to create the black and white checkerboard pattern.
  • Pieces:
  • Define two CSS classes for the white and black pieces: .white-piece and .black-piece.
  • Use the background-color property to set the background color of each piece to white and black, respectively.
  • Use the border-radius property to round the corners of the pieces.
  • Use the box-shadow property to add a shadow to the pieces for better visibility.
  • HUD:
  • Define a CSS class for the score display: .score.
  • Use the font-family property to choose a clean, modern font for the score display.
  • Use the color property to set the text color to white.
  • Use the font-size property to set the font size to 20px.
  • Use the text-align property to center the score display.
  • Responsive and Accessibility:
  • Use the @media query to apply styles for different screen sizes.
  • Use the font-size property to adjust the font size for smaller screens.
  • Use the line-height property to adjust the line height for better readability.
  • Use the color property to adjust the text color for better contrast.

Here is an example of the CSS code:

canvas {
  width: 400px;
  height: 400px;
  border: 1px solid #000;
  background-color: #333333;
}

.white-piece, .black-piece {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: white;
  box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
}

.score {
  font-family: 'Arial', sans-serif;
  color: white;
  font-size: 20px;
  text-align: center;
}

@media (max-width: 768px) {
  canvas {
    width: 300px;
    height: 300px;
  }

  .white-piece, .black-piece {
    width: 40px;
    height: 40px;
  }

  .score {
    font-size: 16px;
  }
}

Pro tip: Ensure the game is responsive and works well on various devices and screen sizes.

5Write the JavaScript for the Game

To write the JavaScript for the ReversiCraft game, follow these steps:

  1. Set Up the Game State: Create a JavaScript object to store the game state, including the 8x8 game board, the current player, and the game over status.
// Initialize the game state
let gameState = {
  board: [
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 1, 2, 0, 0, 0],
    [0, 0, 0, 2, 1, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0]
  ],
  currentPlayer: 1,
  gameEnded: false
};
  1. Render the Game Board: Use the HTML5 canvas API to draw the game board.
// Function to render the game board
function renderBoard() {
  const canvas = document.getElementById('game-board');
  const ctx = canvas.getContext('2d');
  const size = 80; // Size of each cell in pixels

  // Draw the checkerboard pattern
  for (let i = 0; i < 8; i++) {
    for (let j = 0; j < 8; j++) {
      if ((i + j) % 2 === 0) {
        ctx.fillStyle = 'white';
      } else {
        ctx.fillStyle = 'black';
      }
      ctx.fillRect(i * size, j * size, size, size);
    }
  }

  // Draw the pieces
  for (let i = 0; i < 8; i++) {
    for (let j = 0; j < 8; j++) {
      const piece = gameState.board[i][j];
      if (piece === 1) {
        ctx.fillStyle = 'black';
      } else if (piece === 2) {
        ctx.fillStyle = 'white';
      }
      ctx.beginPath();
      ctx.arc(i * size + size / 2, j * size + size / 2, size / 2 - 5, 0, Math.PI * 2);
      ctx.fill();
    }
  }
}
  1. Handle Player Input: Listen for keyboard and touch events to place pieces on the board.
// Function to handle player input
function handleInput(event) {
  const canvas = document.getElementById('game-board');
  const ctx = canvas.getContext('2d');
  const size = 80; // Size of each cell in pixels
  const x = event.offsetX;
  const y = event.offsetY;

  // Calculate the cell coordinates
  const cellX = Math.floor(x / size);
  const cellY = Math.floor(y / size);

  // Check if the cell is valid and the player can place a piece
  if (gameState.board[cellX][cellY] === 0 && isValidMove(gameState.board, cellX, cellY, gameState.currentPlayer)) {
    // Place the piece and flip the opponent's pieces
    placePiece(gameState.board, cellX, cellY, gameState.currentPlayer);
    flipPieces(gameState.board, cellX, cellY, gameState.currentPlayer);

    // Switch to the other player
    gameState.currentPlayer = gameState.currentPlayer === 1 ? 2 : 1;

    // Check if the game is over
    if (noValidMoves(gameState.board, gameState.currentPlayer)) {
      gameState.gameEnded = true;
    }

    // Render the updated board
    renderBoard();
  }
}

// Add event listeners
canvas.addEventListener('click', handleInput);
canvas.addEventListener('touchstart', handleInput);
  1. Implement Game Logic: Define functions to check valid moves, place pieces, flip pieces, and check for valid moves.
// Function to check if a move is valid
function isValidMove(board, x, y, player) {
  // Check all directions
  const directions = [
    [1, 0], // right
    [0, 1], // down
    [1, 1], // down-right
    [1, -1] // down-left
  ];

  for (const [dx, dy] of directions) {
    let foundOpponent = false;
    let piecesToFlip = [];

    let newX = x + dx;
    let newY = y + dy;

    // Check in the direction
    while (newX >= 0 && newX < 8 && newY >= 0 && newY < 8) {
      if (board[newX][newY] === player) {
        break;
      } else if (board[newX][newY] !== 0) {
        foundOpponent = true;
        piecesToFlip.push([newX, newY]);
      }
      newX += dx;
      newY += dy;
    }

    // If we found an opponent and can flip pieces, return true
    if (foundOpponent) {
      return true;
    }
  }

  return false;
}

// Function to place a piece and flip pieces
Reversi game main gameplay view with HUD
Reversi game main gameplay view with HUD

Pro tip: Implement animations for flipping pieces and player turns.

6Test the Game Locally

Test the Game Locally

  1. Open index.html in a Web Browser: Start by opening the index.html file in your preferred web browser (Chrome, Firefox, Safari, etc.).
  2. Ensure All Features are Working: Play the game thoroughly to verify that all features are functioning as expected. Test:
  • Classic Reversi Game Board: Place pieces and observe how they flip and turn.
  • Sound Effects: Toggle sound effects to ensure they play correctly.
  • Restart Button: Click the restart button to clear the board and start a new game.
  • Score Display: Observe the score updates correctly after each move.
  • Animations: Check if the pieces flip and the player turns are animated as intended.
  • Touch Controls: Use a touch device to play the game and ensure it works seamlessly.
  • Accessibility Features: Use a screen reader to navigate the game and ensure all information is accessible.
  1. Responsive Design: Adjust the screen size of your browser and ensure the game board and controls remain responsive and functional.
  2. Cross-Browser Compatibility: Test the game on different browsers to ensure compatibility and functionality.
  3. Debugging: If issues arise, use the browser's developer tools (F12) to inspect elements and console logs for errors.

Additional Testing Tips:

  • Corner Cases: Test the game with edge cases, such as placing a piece in the center of the board or at the corners.
  • Multiple Player Games: If applicable, play against yourself or a friend to ensure multiplayer functionality works correctly.
  • Performance: Check the game's performance on different devices and screen sizes to ensure smooth gameplay.

By following these steps, you can thoroughly test the ReversiCraft game and ensure it meets the requirements outlined in the prompt. If you encounter any issues, feel free to ask for further assistance!

Pro tip: Use the developer tools in your browser to debug any issues.

7Add Accessibility Features

Ensure the game is accessible for users with disabilities by implementing the following accessibility features:

  • Keyboard Navigation:
  • Use the arrow keys to navigate between the board squares, the score, and the restart button.
  • Press the space bar to place a piece on the board.
  • Press 'r' to restart the game.
  • Screen Reader Support:
  • Add ARIA (Accessible Rich Internet Applications) attributes to the HTML elements to describe their roles, states, and relationships.
  • Use semantic HTML to improve the structure of the page for better accessibility.
  • Test the game with screen readers like NVDA or VoiceOver to ensure it reads the game state correctly.
  • Color Contrast:
  • Ensure the contrast between text and the background is sufficient for users with visual impairments.
  • Use a color contrast checker to verify the contrast levels.
  • Responsive Design:
  • Use media queries to adjust the layout for smaller screens.
  • Ensure the game board is accessible with a high zoom level.
  • Error Handling:
  • Provide clear error messages for users who encounter issues with the game.
  • Ensure that the game is keyboard accessible even if JavaScript is disabled.

By implementing these accessibility features, the ReversiCraft game will be more inclusive and easier to use for players with disabilities.

Pro tip: Test the game with assistive technologies to ensure it works as expected.

8Deploy the Game

Deploy the game using a web hosting service (e.g., GitHub Pages, Netlify, Vercel). This will make it accessible to the public. Make sure to configure the hosting service to automatically build and deploy your game whenever you push changes to your repository. Additionally, consider setting up a custom domain if you have one, to give your game a more professional and memorable URL. Finally, ensure that your game is fully responsive and accessible, as per the prompt above, to provide an optimal user experience for all players.

Pro tip: Copy the live preview URL from the source site and share it with others.

9Test the Game on Different Devices

Test the game on different devices, ensuring it adapts seamlessly to various screen sizes, layouts, and resolutions. This includes using responsive design techniques to maintain a consistent user experience across desktops, tablets, and smartphones.

  • Desktop Testing: Ensure the game board is clear and easy to navigate on a desktop. Check that the controls and buttons are accessible and responsive to mouse clicks and keyboard inputs.
  • Tablet Testing: Verify that the game board is responsive and that the game logic remains intact. Test for smooth scrolling and responsive controls.
  • Mobile Testing: Test the game on a mobile device to ensure it is optimized for touch input. Verify that the game board is responsive and that the game logic performs as expected on smaller screens.
  • Accessibility Testing: Use a screen reader to test the game's text and ensure all content is accessible to users with disabilities. Test keyboard navigation and ensure the game is operable without a mouse.
  • Performance Testing: Ensure the game runs smoothly on different devices and screen sizes. Test for lag and performance issues, especially on slower devices.
  • Cross-Browser Testing: Test the game on different browsers to ensure compatibility and consistent behavior across platforms.

By thoroughly testing the game on these devices, you can ensure that it meets the prompt's requirements for responsiveness, accessibility, and performance.

Pro tip: Use responsive design tools to ensure the game is responsive.

Adapt it to your own brand

  • Change the game board size and piece colors.
  • Add more features, such as a timer or AI opponents.
  • Create a multiplayer mode for two players.
  • Add sound effects and background music.
  • Create a leaderboard to track high scores.

Common mistakes and fixes

  • Failing to test the game locally before deploying it.
  • Not creating a responsive design for the game.
  • Not implementing accessibility features for users with disabilities.
  • Not using the correct AI tool to generate the game code.

Frequently asked questions

What AI coding tools did you use?

The tutorial uses ChatGPT, Claude, Cursor, Lovable, Bolt, v0, and a custom AI implementation.

How does the game handle AI?

The AI is not explicitly implemented in this tutorial. It would require a separate AI module to determine moves.

Is the game accessible for users with disabilities?

The game is designed with accessibility features such as keyboard navigation and screen reader support.

What are the key features of the game?

The game features a classic Reversi game board, toggleable sound effects, restart button, score display, animations, touch controls, and responsive design.

Final thoughts

Congratulations! You've successfully built a Reversi game using AI. Feel free to customize it to suit your needs and share it with others.

Originally published on PromptGrabber.com — find thousands more AI prompts there.