Battleship Game Engine with Canvas: Mastering 8x8 Grid Ship Placement
Have you ever wondered how to create a classic Battleship game but don't want to spend hours coding it from scratch? With AI coding tools like ChatGPT, Claude, and Bolt, you can now build your own version of this popular game in a matter of minutes. In this detailed tutorial, we'll walk you through every step of the process, from setting up the development environment to deploying your game. Whether you're a beginner or an experienced coder, this tutorial is here to help you build your own Battleship game using AI coding tools.
What you need
- A computer with internet access
- An AI coding tool like ChatGPT, Claude, or Bolt
- Basic knowledge of HTML, CSS, and JavaScript
- A text editor or IDE for coding
The full prompt
Build Battleship Game Engine (BGE) using HTML5 canvas to create a single-page browser game. The project is designed to be a 3-tier architecture where the BGE (Business Logic Layer) handles game state, while a text-based presentation layer manages user interaction. The BGE will generate a random 8x8 board with three ships (Destroyer: 2 squares, Cruiser: 3 squares, Battleship: 4 squares) and allow players to shoot at targets. The text-based layer will present the game board, allow users to input coordinates, and display the outcome of each shot.
### Tech Stack
- **Frontend:** HTML5 canvas, CSS (for styling)
- **Backend:** None, written in JavaScript
### Features
- **BGE (Business Logic Layer):**
- `[ ] startGame()` function to initialize the game.
- `[ ] shoot()` function to handle shooting at targets.
- `[ ] gameStats()` function to return game statistics.
- **Text-based Presentation Layer:**
- `[ ] Display the hits and misses array as a 2D character representation of the game board.
- `[ ] Prompt user to enter target coordinates.
- `[ ] Update hits and misses array after each shot.
- `[ ] Display message indicating shot result (hit or miss).
- `[ ] Display congratulatory message when the last ship is sunk.
- `[ ] Allow user to play again or exit.
- **Bonus Features:**
- `[ ] Ability to specify the number of rows and columns in the game board.
- `[ ] Ability to specify the number of players (1 or 2) for two-player games.
- `[ ] Display game statistics when user enters `stats` as coordinates.
### Visual Design
- **Colours:** Use a neutral color scheme with dark grey for the board and light grey for highlights.
- **Typography:** Use a simple, clean font for readability.
- **Layout:** Keep the interface simple with a clear area for the game board, input field, and status display.
- **Animation:** None, but consider adding basic transitions for shot results to enhance interactivity.
### Controls and User Flows
- **Game Start:**
1. Load the page and click the start button or enter coordinates to begin a new game.
2. The game board and input field appear.
3. The BGE generates a random board with three ships and returns the placement array.
- **Game Play:**
1. Player enters coordinates to shoot.
2. The BGE updates the hits and misses array and the UI displays the outcome.
3. If a ship is sunk, a congratulatory message appears.
4. Player can choose to play again or exit.
- **Game End:**
1. If the player wins or loses, a message displays.
2. Player can choose to play again or exit.
### Data/State Handling
- **Game Board:** Stored in the BGE as a 2D array.
- **Hits/Misses:** Updated in the BGE and displayed in the text-based layer.
- **Game Statistics:** Stored in the BGE and displayed in the text-based layer.
### Responsive and Accessibility Requirements
- **Responsive Design:** The game should work on various devices, including desktops, tablets, and smartphones.
- **Accessibility:** Ensure the game is accessible to users with disabilities, including screen readers.
### Output
- **File Structure:**
```
battleship-game-engine/
├── index.html
└── styles.css
```
- **Run Instructions:**
1. Open `index.html` in a web browser.
2. Click the start button or enter coordinates to begin a new game.
3. Use the input field to shoot at targets and follow the on-screen instructions.1Step 1: Set Up Your Development Environment
Open your AI coding tool. Paste the full prompt above into the tool. Click the run button to generate an HTML file. This file will serve as the foundation for your Battleship Game Engine. Save it in a new folder named battleship-game-engine. The file will be named index.html. Open index.html in a web browser to see your game in action.

Pro tip: Ensure the AI tool is set to generate JavaScript code.
2Step 2: Implement the Game Board
In the index.html file, add an HTML5 canvas element to serve as the game board. Use CSS to style the canvas and add any necessary elements for the game UI, such as buttons for starting the game and displaying game statistics. Position the canvas within a container for better layout control. Consider adding a grid overlay to help users visualize the board's layout. Use CSS to set the canvas size and background color, and position it appropriately within the container. Make sure to include a class or ID for easy styling and scripting in the styles.css file.
Pro tip: Use the canvas' width and height properties to set the size of the game board.
3Step 3: Initialize the Game
In the JavaScript file, define a function called startGame() that initializes the game by setting up the game board, placing the ships, and creating arrays to track hits and misses. The startGame() function should:
- Initialize the Game Board:
- Create a 2D array to represent the game board, initialized with water (
O). - Use a random number generator to place three ships on the board, ensuring they do not overlap and cover at least their respective sizes (Destroyer: 2 squares, Cruiser: 3 squares, Battleship: 4 squares).
- Place the Ships:
- Randomly generate the starting row and column for each ship.
- Ensure the ship is placed within the board boundaries.
- Create a temporary array to track the positions of the ship on the board.
- Place the ship's squares on the board, marking them as
S(for ship).
- Initialize Hit and Miss Arrays:
- Create two arrays,
hitsandmisses, both of the same size as the game board. - Initialize these arrays with
nullvalues to track the outcomes of each shot.
- Display the Game Board:
- Update the HTML canvas to display the game board.
- Use the
hitsandmissesarrays to highlight hits and misses on the board.
- Reset Game State:
- Clear any previous game state by reinitializing the game board, hit/miss arrays, and any other relevant variables.
- Start the Game Loop:
- Optionally, you can start a game loop to handle continuous game play if desired.
By following these steps, the startGame() function sets up the initial state of the game, ready for players to begin shooting.
Pro tip: Use the Math.random() function to generate random ship positions on the game board.
4Step 4: Handle Player Input
Step 4: Handle Player Input
To handle player input, we need to add event listeners to the canvas element. This will allow us to capture mouse clicks or keyboard input when the player interacts with the game board. When a player clicks on the canvas, we need to determine the coordinates of the clicked area and pass them to the shoot() function in the BGE layer.
- Add Event Listeners to the Canvas:
- For mouse clicks, we can use the
addEventListenermethod to listen for theclickevent on the canvas element. - For keyboard input, we can use the
addEventListenermethod to listen for thekeydownevent on the document. This will allow us to capture arrow key inputs for two-player games.
canvas.addEventListener('click', handleCanvasClick);
document.addEventListener('keydown', handleKeyPress);
- Determine Coordinates of the Clicked Area:
- When a mouse click event is detected, we need to calculate the coordinates of the clicked area on the canvas.
- This can be done by converting the mouse event coordinates relative to the canvas to the game board coordinates.
function handleCanvasClick(event) {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
const col = Math.floor(x / cellSize);
const row = Math.floor(y / cellSize);
shoot(row, col);
}
- Handle Keyboard Inputs for Two-Player Games:
- When a
keydownevent is detected, we need to check if the arrow keys (left, right, up, down) are pressed. - If an arrow key is pressed, we need to determine the direction and update the current position of the computer-controlled player's ship.
function handleKeyPress(event) {
const direction = event.key;
if (direction === 'ArrowLeft') {
// Move ship to the left
} else if (direction === 'ArrowRight') {
// Move ship to the right
} else if (direction === 'ArrowUp') {
// Move ship upwards
} else if (direction === 'ArrowDown') {
// Move ship downwards
}
}
By adding event listeners to the canvas and handling player input, we can allow the player to interact with the game board and control the behavior of the computer-controlled player's ship in a two-player game.
Pro tip: Use the getBoundingClientRect() method to determine the coordinates of the clicked area on the canvas.
5Step 5: Update Game State
In the shoot() function, we need to update the game state to reflect whether the shot was a hit or miss. This involves marking the shot as either true (hit) or false (miss) in the hits array. Additionally, we need to update the misses array to keep track of the locations where shots have missed. Finally, we need to redraw the game board to display the updated state.
Code Snippet:
function shoot(x, y) {
// Check if the shot is within the board boundaries
if (x >= 0 && x < 8 && y >= 0 && y < 8) {
// Mark the shot as a hit or miss
if (bge.board[x][y] === true) {
hits.push([x, y]);
bge.board[x][y] = false; // Mark as hit
console.log("Hit!");
} else {
misses.push([x, y]);
console.log("Miss!");
}
// Redraw the game board
drawBoard();
} else {
console.log("Invalid shot coordinates. Please enter valid coordinates.");
}
}
Explanation:
- Boundary Check: We first check if the coordinates
(x, y)are within the 8x8 board boundaries. If they are not, we display an error message.
- Hit or Miss Check: We then check if the cell at
(x, y)contains a ship (i.e., it istruein theboardarray). If it is, we register a hit and mark the cell asfalseto indicate it has been hit. If it is not, we register a miss.
- Update Arrays: We update the
hitsandmissesarrays accordingly.
- Redraw the Board: Finally, we call the
drawBoard()function to update the visual representation of the game board on the screen, reflecting the changes made during theshoot()function.
Pro tip: Use the ctx object to draw the game board on the canvas.
6Step 6: Display Game Statistics
Step 6: Display Game Statistics
Create a function called gameStats() that returns the game statistics, such as the number of hits and misses. Display this information in the text-based presentation layer.
- Function Definition:
- Inside the text-based presentation layer, define a function named
gameStats(). - The function should return an object containing the number of hits and misses.
function gameStats() {
// Calculate the number of hits and misses
const hits = this.hits.filter(cell => cell === 'H').length;
const misses = this.hits.filter(cell => cell === 'M').length;
// Return the game statistics as an object
return {
hits: hits,
misses: misses
};
}
- Display Game Statistics:
- Create a function to update the game statistics display in the text-based layer.
- Inside the
gameStats()function, call this update function to display the number of hits and misses.
function displayGameStats() {
const stats = this.gameStats();
const hitsDisplay = document.getElementById('hitsDisplay');
const missesDisplay = document.getElementById('missesDisplay');
hitsDisplay.textContent = `Hits: ${stats.hits}`;
missesDisplay.textContent = `Misses: ${stats.misses}`;
}
- Integration:
- Ensure that the
displayGameStats()function is called after each shot or when the game ends. - This will update the display in real-time, providing players with clear feedback on their performance.
// Example usage in the shoot() function
shoot() {
const target = prompt('Enter target coordinates (e.g., A1)');
const result = this.checkHit(target);
this.updateBoard(result);
this.displayGameStats();
}
By following these steps, you will be able to display the game statistics in the text-based presentation layer, giving players a clear understanding of their progress and performance during the game.
Pro tip: Use the innerHTML property to update the text-based presentation layer with the game statistics.
7Step 7: Add Bonus Features
Step 7: Add Bonus Features
Consider adding the following bonus features to enhance the Battleship Game Engine:
- Specify the number of rows and columns:
- Allow users to specify the number of rows and columns for the game board. This can be done by adding an input field in the text-based presentation layer where users can enter the desired dimensions. The BGE should update the game board accordingly, ensuring that the ships are placed within the new size constraints.
- Allow two-player games:
- Implement a two-player mode by introducing a second player's input field. The BGE should handle the turns of both players, updating the game board and UI accordingly. Each player should have their own shots and hits/misses arrays, and the game should display the current player's turn.
- Display game statistics:
- Add a feature that allows users to enter 'stats' as coordinates to display game statistics. The text-based presentation layer should fetch the game statistics from the BGE and update the UI to show the total number of hits, misses, and the number of ships sunk. This can be done by adding a new function in the BGE that returns these statistics and updating the text-based layer to display them.
By implementing these bonus features, the Battleship Game Engine will become more versatile and enjoyable for players, offering more options to customize the game experience.
Pro tip: Use the prompt() function to get user input from the text-based presentation layer.
8Step 8: Test Every Feature
Run your game locally and test every feature listed in the prompt above. Look for any bugs or issues and fix them. You can also add more features to improve the game.
- Start Game Functionality: Start the game by clicking the start button or entering coordinates. Ensure the game board and input field appear correctly.
- Shooting Functionality: Enter coordinates to shoot at targets. The BGE updates the hits and misses array and the UI displays the outcome. Ensure that ships are correctly placed and that the game board reflects the hits and misses accurately.
- Game End Conditions: Ensure that the game correctly identifies when a ship is sunk and congratulates the player. Also, ensure that the game correctly identifies when the player has lost and displays the appropriate message.
- Game Statistics: Ensure that the game correctly displays game statistics based on the number of hits and misses.
- Responsive Design: Ensure that the game works on various devices, including desktops, tablets, and smartphones.
- Accessibility: Ensure that the game is accessible to users with disabilities, including screen readers.
- Bonus Features: Ensure that the ability to specify the number of rows and columns in the game board, the ability to specify the number of players for two-player games, and the ability to display game statistics when the user enters "stats" as coordinates work correctly.
Pro tip: Use the browser's developer tools to debug any issues in your game.
9Step 9: Deploy Your Game
Once you're satisfied with your game, you can deploy it free using services like GitHub Pages, Netlify, or Vercel. Follow the deployment instructions provided by the service to make your game accessible to the world.
- GitHub Pages:
- Create a new repository on GitHub.
- Copy the code from your
battleship-game-enginefolder into the repository. - Navigate to your repository on GitHub and select "Settings".
- Under "Pages", choose the default branch and the root directory (
/). - Click "Save".
- Your game will be live at
https://<your-username>.github.io/battleship-game-engine/.
- Netlify:
- Sign up for a Netlify account at netlify.com.
- Click "New site from Git".
- Link your GitHub repository.
- Select the branch you want to deploy.
- Click "Deploy site".
- Netlify will build your site and make it live.
- Vercel:
- Sign up for a Vercel account at vercel.com.
- Click "New Project".
- Select the repository you want to deploy.
- Follow the setup wizard to configure your project.
- Click "Deploy".
- Vercel will build your site and make it live.
Once deployed, your game will be accessible to anyone with the URL. You can share the link with your friends or even on social media to play and compete!
Pro tip: Use the build instructions provided by the AI tool to generate a deployment-ready version of your game.
10Step 10: Customize Your Game
Feel free to customize your game by changing the colors, fonts, and layout to match your brand. You can also add additional features or modify the existing ones to create a unique and engaging game.
- Colors: Use a neutral color scheme with dark grey for the board and light grey for highlights. You can choose vibrant colors that align with your brand's identity.
- Fonts: Use a simple, clean font for readability. Consider using a font that complements your brand's style.
- Layout: Keep the interface simple with a clear area for the game board, input field, and status display. You can add additional elements like scoreboards or timers to enhance engagement.
- Animation: Consider adding basic transitions for shot results to enhance interactivity. This could include animations for hit or miss indicators or animations for the game board to change when a ship is sunk.
- Additional Features: You can add features like ship rotation, different ship sizes, or a high score leaderboard to make the game more challenging and engaging. Additionally, you can add sound effects and music to improve the overall gaming experience.
- Accessibility: Ensure the game is accessible to users with disabilities, including screen readers. This includes providing alt text for images and ensuring that the game board is keyboard navigable.
By customizing your game, you can make it stand out and provide a more personalized experience for your players.
Pro tip: Use the AI tool to generate additional code or modify existing code to customize your game.
11Step 11: Common Mistakes and Fixes
When building a Battleship game, several common mistakes can lead to bugs and difficulties. Here are some of the most frequent issues and how to avoid or fix them:
- Initializing the Game Board Incorrectly: Make sure the game board is properly initialized in the BGE. This includes setting up the 2D array that represents the board and populating it with the initial positions of the ships. Common mistakes include leaving spaces or missing ships on the board. Use the AI tool to ensure the board is generated correctly by checking the placement logic and ensuring all ships are accounted for.
- Updating the Game State Properly: The BGE should update the game state correctly after each shot. This includes marking hits and misses, updating the game stats, and displaying the outcome to the user. Common mistakes include not updating the board state correctly after a shot or not updating the game stats correctly. Use the AI tool to verify that the game state updates are accurate and that the game stats are being calculated correctly.
- Handling Player Input Incorrectly: The text-based layer should handle player input correctly to allow users to enter coordinates and shoot at targets. Common mistakes include not validating the input or not updating the game state based on the user's input. Use the AI tool to ensure that the input handling is robust and that the game state is updated correctly based on the user's input.
- Displaying the Outcome Inaccurately: The text-based layer should display the outcome of each shot accurately. Common mistakes include not displaying the correct message (hit or miss) or not updating the display correctly after each shot. Use the AI tool to ensure that the display is accurate and that the game state is updated correctly after each shot.
- Handling Game End Conditions Incorrectly: The text-based layer should handle game end conditions correctly to determine when the game is over and display the appropriate message. Common mistakes include not checking the game state correctly or not displaying the correct message when the game ends. Use the AI tool to ensure that the game end conditions are handled correctly and that the game state is updated correctly after each shot.
- Ensuring Responsive and Accessibility: The game should be responsive and accessible to users with disabilities. Common mistakes include not using sufficient color contrast or not providing sufficient keyboard navigation. Use the AI tool to ensure that the game is responsive and accessible to users with disabilities.
Pro tip: Use the AI tool to generate additional code or modify existing code to fix these issues.
Adapt it to your own brand
- Change the colors and fonts to match your brand.
- Add additional features like a timer or score system.
- Create a multiplayer version of the game.
- Implement a high score table.
- Add sound effects and music to enhance the gaming experience.
- Create a user-friendly interface for players to interact with the game.
Common mistakes and fixes
- Not initializing the game board correctly.
- Not updating the game state properly.
- Not handling player input correctly.
- Not adding enough ships.
- Not implementing game statistics.
- Not adding any bonus features.
Frequently asked questions
What are the main features of the Battleship Game Engine?
The BGE will generate a random 8x8 board with three ships: Destroyer (2 squares), Cruiser (3 squares), and Battleship (4 squares). Players will be able to shoot at targets and the game will update the hits and misses array. The text-based layer will display the game board, allow users to input coordinates, and display the outcome of each shot.
What are the bonus features of the Battleship Game Engine?
The Battleship Game Engine will allow users to specify the number of rows and columns in the game board, play two-player games, and display game statistics when the user enters 'stats' as coordinates.
How is the Battleship Game Engine designed to be accessible?
The game will be responsive and accessible to users with disabilities, including screen readers, ensuring a smooth and enjoyable gaming experience.
What are the file structure and run instructions for the Battleship Game Engine?
The file structure includes index.html and styles.css. Run instructions involve opening index.html in a web browser and following on-screen instructions to begin a new game and shoot at targets.
Final thoughts
Building a Battleship game using AI coding tools is a fun and rewarding experience. With this tutorial, you've learned how to set up your development environment, implement game logic, and deploy your game. Don't forget to customize your game to match your brand and add more features to make it more engaging. Copy the full prompt from this page and build your own version of the Battleship game today!