Projects / One-player battleship

One-player battleship

Intermediate1.8 hGuided buildReviewed

Build it step by step

0 of 7 done
  1. NANO

    Place the buttons

    In a cross for up, down, left and right with fire beside it.

  2. NANO

    Wire the buttons

    D2 to D6, each other leg to GND.

  3. NANO14.6 mA

    Wire the matrix and buzzer

    DIN through 330 ohms to D11, 5V and GND, buzzer to D8.

  4. NANO

    Upload the sketch

    A blinking white cursor appears.

  5. NANO

    Move and fire

    Blue for a miss, red for a hit.

  6. NANO

    Sink all three ships

    The ships turn green and a new game waits.

  7. NANO

    Check the serial monitor

    It prints the shots you used.

In short

How do you build a one-player battleship?

Hide three ships on an eight by eight matrix and find them with four direction buttons and a fire button. A hit lights red, a miss lights blue, and a sunk ship gives a beep. A small puzzle in grids, arrays and random placement. You need Arduino Nano, WS2812B 8x8 RGB LED matrix, Tactile push button 6 mm × 5, Passive buzzer, Resistor 330 Ω, Breadboard 830 Tie Points and Jumper wires male to male (40 pcs, 20 cm). It takes 7 steps and about 110 minutes.

Level
Intermediate
Time
About 110 min
Parts
7

Parts list

Tick what you already own. It saves to My Garage, so “Build with what I have” knows.

Wiring

FromToWhy
Matrix DINNano D11 through a 330 ohm resistorData to the first LED
Matrix 5V and GNDNano 5V and GNDPower, kept dim in the sketch
Up, down, left, right buttonsNano D2, D3, D4 and D5 and GNDMove the cursor
Fire buttonNano D6 and GNDShoot at the cursor square
Passive buzzer + and -Nano D8 and GNDHit, miss and sunk sounds

Code

The sketch hides three ships, two squares and three squares long, by picking a random start and direction and trying again if the ship would overlap another. Move the white blinking cursor with the four direction buttons and press fire: a miss turns the square blue and a hit turns it red. When every square of a ship is hit the buzzer gives a rising beep, and when all three are sunk the ships show in green and the serial monitor prints the number of shots, with any button starting a new game. The best possible game uses seven shots, and a random shooter needs far more, so try to keep a pattern, such as shooting every second square, which finds every ship of length two or more. Install "Adafruit NeoPixel" from the Library Manager. If the picture looks scrambled, change SERPENTINE to false. Brightness is kept low, so USB power is fine, and the 330 ohm resistor on the data line protects the first LED.

Runs on a virtual Arduino Nano in your browser, with sliders for the sensors. Happy with it? Verify and upload to your real board from the same page (Chrome or Edge on a computer).

// Library: Adafruit NeoPixel.
#include <Adafruit_NeoPixel.h>

const uint8_t DATA_PIN = 11;
const uint8_t BTN[5] = {2, 3, 4, 5, 6};   // up, down, left, right, fire
const uint8_t BUZZ = 8;
const bool SERPENTINE = true;             // set to false if your matrix rows all run the same way

Adafruit_NeoPixel strip(64, DATA_PIN, NEO_GRB + NEO_KHZ800);

uint8_t shipId[8][8];                     // 0 = water, 1 to 3 = ship number
uint8_t shot[8][8];                       // 0 = not fired at, 1 = miss, 2 = hit
const uint8_t shipLen[4] = {0, 3, 2, 2};
uint8_t shipHits[4];
uint8_t shipsLeft;
uint8_t shots;
int8_t cx = 0, cy = 0;
bool prevDown[5];
bool finished = false;

uint16_t px(uint8_t x, uint8_t y) {
  if (SERPENTINE && (y & 1)) x = 7 - x;
  return y * 8 + x;
}

bool fits(uint8_t x, uint8_t y, bool horiz, uint8_t len) {
  for (uint8_t i = 0; i < len; i++) {
    uint8_t xx = horiz ? x + i : x;
    uint8_t yy = horiz ? y : y + i;
    if (shipId[yy][xx] != 0) return false;
  }
  return true;
}

void newGame() {
  for (uint8_t y = 0; y < 8; y++)
    for (uint8_t x = 0; x < 8; x++) { shipId[y][x] = 0; shot[y][x] = 0; }
  for (uint8_t id = 1; id <= 3; id++) {
    shipHits[id] = 0;
    uint8_t len = shipLen[id];
    while (true) {                        // keep trying until the ship fits
      bool horiz = random(2);
      uint8_t x = random(horiz ? 9 - len : 8);
      uint8_t y = random(horiz ? 8 : 9 - len);
      if (!fits(x, y, horiz, len)) continue;
      for (uint8_t i = 0; i < len; i++) shipId[horiz ? y : y + i][horiz ? x + i : x] = id;
      break;
    }
  }
  shipsLeft = 3;
  shots = 0;
  cx = 0; cy = 0;
  finished = false;
}

void draw() {
  bool blink = (millis() / 300) % 2;
  for (uint8_t y = 0; y < 8; y++)
    for (uint8_t x = 0; x < 8; x++) {
      uint32_t c = 0;
      if (shot[y][x] == 1) c = strip.Color(0, 0, 40);
      if (shot[y][x] == 2) c = strip.Color(60, 0, 0);
      if (x == cx && y == cy && blink && !finished) c = strip.Color(40, 40, 40);
      strip.setPixelColor(px(x, y), c);
    }
  strip.show();
}

void fire() {
  if (shot[cy][cx] != 0) return;          // already shot here
  shots++;
  uint8_t id = shipId[cy][cx];
  if (id == 0) {
    shot[cy][cx] = 1;
    tone(BUZZ, 400, 120);
    return;
  }
  shot[cy][cx] = 2;
  shipHits[id]++;
  if (shipHits[id] == shipLen[id]) {
    shipsLeft--;
    tone(BUZZ, 1200, 100); delay(120);
    tone(BUZZ, 1600, 200);
    Serial.println("Ship sunk!");
  } else {
    tone(BUZZ, 900, 120);
  }
  if (shipsLeft == 0) {
    finished = true;
    Serial.print("All ships sunk in ");
    Serial.print(shots);
    Serial.println(" shots.");
  }
}

void setup() {
  for (uint8_t i = 0; i < 5; i++) pinMode(BTN[i], INPUT_PULLUP);
  pinMode(BUZZ, OUTPUT);
  Serial.begin(9600);
  strip.begin();
  strip.setBrightness(60);
  randomSeed(analogRead(A0) ^ micros());
  newGame();
}

void loop() {
  for (uint8_t i = 0; i < 5; i++) {
    bool down = (digitalRead(BTN[i]) == LOW);
    if (down && !prevDown[i]) {
      delay(20);
      if (finished) { newGame(); }
      else if (i == 0 && cy > 0) cy--;
      else if (i == 1 && cy < 7) cy++;
      else if (i == 2 && cx > 0) cx--;
      else if (i == 3 && cx < 7) cx++;
      else if (i == 4) fire();
    }
    prevDown[i] = down;
  }
  if (finished) {                          // show the sunk ships in green for the win
    for (uint8_t y = 0; y < 8; y++)
      for (uint8_t x = 0; x < 8; x++)
        strip.setPixelColor(px(x, y), shipId[y][x] ? strip.Color(0, 60, 0) : 0);
    strip.show();
  } else {
    draw();
  }
}

Test checklist

What you should see at each check. If a reading is far off, stop and use the troubleshooting list.

CheckExpected
CursorBlinks white and moves with the buttons
MissSquare turns blue with a low beep
HitSquare turns red with a mid beep
Ship sunkRising beep and a serial message
All ships sunkGreen ships and a shot count

If it does not work

Picture looks scrambled

Change SERPENTINE to false.

Nothing lights

Check DIN goes to the input end of the matrix.

A button does nothing

Check its legs and the GND connection.

Cursor stays put at an edge

It cannot move past the grid.

Same ships every game

Check the randomSeed line is in setup.

Still stuck? Find the fault step by step with your multimeter →

Ask Lark AI

Common questions

What parts do I need for the one-player battleship?

Arduino Nano, WS2812B 8x8 RGB LED matrix, Tactile push button 6 mm × 5, Passive buzzer, Resistor 330 Ω, Breadboard 830 Tie Points and Jumper wires male to male (40 pcs, 20 cm).

How long does the one-player battleship take to build?

About 110 minutes for a intermediate maker, in 7 steps.

How do I know the one-player battleship works?

Cursor: Blinks white and moves with the buttons. Miss: Square turns blue with a low beep. Hit: Square turns red with a mid beep.

Picture looks scrambled: what should I check?

Change SERPENTINE to false.

Nothing lights: what should I check?

Check DIN goes to the input end of the matrix.

A button does nothing: what should I check?

Check its legs and the GND connection.

Cursor stays put at an edge: what should I check?

It cannot move past the grid.