← MAIN
06 // PROBABILITY TARGETING

BATTLESHIP

Fire at an opponent that counts the fleet layouts still possible, or at one that shoots from fixed odds.
STATUS PLACE YOUR FLEET YOUR FLEET 0 / 5 ENEMY ? SHOTS 0 / 0

HOW TO PLAY

Sink the opponent's five ships before it sinks yours. Place your fleet on your grid, then fire at the enemy waters, and the opponent fires back at your fleet.

Click a tray ship and then a square to place it, press R or ROTATE to turn it, and use RANDOM FLEET for a quick start. Click an enemy square to fire; the opponent answers once its reticle settles.

WATCH AI VS OPPONENT runs a race in which the AI and the opponent fire at each other's fleets, and AUTO-RESTART (under More settings) starts the next race. Choose AI ALONE in WATCH to see the AI hunt your fleet by itself.

YOUR FLEET
ENEMY WATERS
Pick a ship from the tray, then click your grid. Click a placed ship to pick it up. R rotates.
WHAT THE SHOOTER SEES
Its odds appear once the battle starts.
Layouts counted—
How—
Ships still afloat—
    Battle log
    FLEET
    MATCH
    WATCH
    OPPONENT
    More settings
    WATCH SPEED

    HOW IT WORKS

    The two sides fire at each other's fleets. The AI uses probability targeting: it fires at the cell most likely to hold a ship, and it gets those probabilities by counting, or sampling, the fleet layouts that fit the shots so far. That counting is a Bayesian calculation, in which a belief is revised as evidence arrives. The opponent is either the same agent or chance, which fires from a fixed table and never reads its results. The first fleet sunk loses, so a race cannot end in a draw.

    The board, the fleet and the rules

    The board is a 10 × 10 grid. Cells are numbered 0 to 99 row by row, so a cell in row r and column k has the number 10r + k, and players name it by a column letter and a row number. Cell 62 is C7 (1, 2).

    The fleet has one ship of each length in the list 5, 4, 3, 3, 2: the Carrier, Battleship, Cruiser, Submarine and Destroyer, 17 cells in all. A ship is a straight run of consecutive cells, horizontal or vertical, lying wholly on the board. Ships may touch but may not overlap (3, 4).

    A shot is a miss or a hit. The shot that hits a ship's last unhit cell sinks the ship, and the shooter then learns every cell of it (5, 6).

    A shooter's knowledge is the set of cells it has fired at, the misses, the hits, the cells of sunk ships, and the lengths of the ships sunk so far (7). Two derived sets matter. The open hits are the hits on ships not yet sunk, and each one is certainly part of a ship still afloat (8). The remaining lengths are the lengths of the ships still afloat, longest first (9).

    Example. Before any shot, the remaining lengths are 5, 4, 3, 3, 2 and all 100 cells are unknown.

    Probability targeting

    The agent keeps a belief about each cell, the probability that it holds a ship given the shots so far. The belief is built from configurations. A configuration is one placement of each ship still afloat that agrees with everything observed: no ship covers a miss or a sunk cell, every open hit is covered by some ship, and no two ships overlap (10).

    The model takes every legal fleet as equally likely to have been placed. The server draws the fleet that the AI fires at in exactly this way, by rejecting any random draw in which two ships overlap (11). The page's RANDOM FLEET, and the fleets its watch mode places, use the same rule. Each ship gets a uniformly drawn start cell and orientation, a draw that runs off the board is redrawn, and the whole fleet is redrawn if two ships overlap (12). So a fleet that the page draws is uniform too, and the uniform assumption holds for it. Under the assumption every configuration is equally likely, and the probability that a cell holds a ship is the share of configurations that cover it.

    1314
    P(c) = \frac{\left|\{\,x \in \mathcal{C} : c \in x\,\}\right|}{|\mathcal{C}|}

    Here c is a cell, \mathcal{C} is the set of configurations that agree with the knowledge, and x is one configuration, viewed as the set of cells its ships cover. The numerator counts the configurations that cover c, and the denominator counts all of them. Known cells are fixed: a hit, including a cell of a sunk ship, has probability 1, and a miss has probability 0 (15).

    Every configuration covers exactly the cells of the ships still afloat. The probabilities of all cells therefore sum to the sum of the remaining lengths, and the unknown cells sum to that total minus the number of open hits. At the start the total is 17, so the average cell has probability 0.17.

    An open hit makes its neighbours rise without any special rule. The ship through that hit has length 2 or more, so it must cover at least one orthogonal neighbour of the hit, and a neighbour is therefore covered by a larger share of the configurations.

    The agent fires at the unknown cell with the highest belief. Ties are common in exact counts, so cells within 10^{-12} of the best value count as tied, and the choice among them is random (16).

    1716
    function CHOOSE-SHOT(knowledge):
        belief ← SHIP-PROBABILITIES(knowledge)
        unknown ← the cells not yet fired at
        if belief is "none" or unknown is empty:
            return a random cell from unknown
        best ← the largest belief[c] over the unknown cells c
        ties ← the unknown cells c with belief[c] ≥ best − 1e-12
        return a random cell from ties

    Ties in the full version are matched with a small tolerance, so cells whose exact counts are equal are treated as equal despite floating-point rounding. The none case means no consistent layout was found, which happens only with inconsistent input, since a legal game always leaves at least one configuration. In that case the choice is uniform.

    1819
    function SHIP-PROBABILITIES(knowledge):
        probs ← 0 for every cell, and 1 for every hit (sunk ships included)
        lengths ← the lengths of the ships afloat, longest first
        if lengths is empty:
            return probs, method "done"
        free[n] ← the placements of length n that avoid misses and sunk cells
        if some free[n] is empty:
            return probs, method "none"
        if the product of the sizes of free[n] is at most 30,000:
            counts ← COUNT-EXACT(lengths, free, open hits, 60,000)
            if the count finished:
                return the exact shares, method "exact"
        return SAMPLE(lengths, free, open hits, 1,000), method "sampled"

    Over budget means the exact search did more work than allowed and was abandoned part-way. Its partial counts are discarded and the sampler runs instead, so the answer never depends on a half-finished count. Done means no ship is afloat, and then only the known cells have values.

    Exact counting

    Exact counting lists the configurations with a depth-first search. The search places the ships still afloat one at a time, in length order, and tries every free placement of each. A placement is free if it avoids every miss and every sunk cell (20, 21).

    The search prunes, which means it stops exploring a branch that cannot succeed. A branch is cut when the open hits still uncovered outnumber the cells that the ships still to be placed can cover. Let T_i be the total length of ships i to the last, H the open hits, and U_i the cells covered by the ships placed before ship i. The branch is cut when |H \setminus U_i| > T_i (22).

    23
    B = \prod_{n \in L} |F_n| \le \tfrac{1}{2} \cdot 60\,000 = 30\,000

    Here L is the list of remaining lengths and F_n is the set of free placements of length n. The bound counts the placements of every ship with overlaps ignored, so it is an upper limit on the work. Exact counting is attempted only when B is at most 30,000, half of the budget of 60,000 candidate checks (19). Each node adds the number of options it examines to the work, and the search stops once the work passes the budget (24). The bound is loose, so the budget can still run out, and then the code samples.

    While both 3-cell ships are afloat, the search places them in both orders. Each set of ships is therefore counted twice, which is the same factor for every configuration and so cancels from the shares (25).

    Example. With no shots fired, the free placements are 120 for the 5-cell ship, 140 for the 4-cell ship, 160 for each 3-cell ship and 180 for the 2-cell ship. Their product is 77,414,400,000, far above 30,000, so the start of a game is always sampled.

    21
    function COUNT-EXACT(lengths, free, hits, budget):
        counts ← an empty tally of cell sets
        PLACE(ship 1, no cells used)
        return counts
    
    function PLACE(i, used):
        if every ship is placed:
            if every open hit is in used: counts[used] ← counts[used] + 1
            return
        if more open hits are uncovered than the ships still to place can cover:
            return                                         # prune
        for each free placement m of ship i that does not overlap used:
            PLACE(i + 1, used ∪ m)

    Pruning is safe, because a cut branch cannot lead to any configuration that covers all the open hits. The tail is the most cells the remaining ships can cover, and it is the only bound the test needs. Work counts the placement options examined, which is the cost the budget caps.

    Importance sampling

    When exact counting is too costly, the agent estimates the probabilities with importance sampling. It draws S = 1{,}000 random configurations and gives each a weight, so that the weighted sample stands in for the uniform set of all configurations (26, 27).

    Each sample places the remaining ships in length order. Each ship goes on a placement chosen uniformly from those that avoid the cells already used, and the sample's weight is multiplied by the number of such placements, k. A sample's weight is therefore w_s = \prod_i k_{s,i}, which is the reciprocal of the probability with which the sampler drew it (28).

    A sample is kept only if it covers every open hit. A discarded sample gets weight 0 (29). The probability of a cell is then the weighted share of the kept samples that cover it.

    30
    P(c) \approx \frac{\sum_{s} \kappa_s\, w_s\, \mathbf{1}[c \in U_s]}{\sum_{s} \kappa_s\, w_s}

    Here U_s is the set of cells covered by sample s, \kappa_s is 1 if the sample is kept and 0 otherwise, and \mathbf{1}[\cdot] is 1 when its condition holds and 0 otherwise. The code's error on a cell's probability is about 0.02 to 0.03 with 1,000 samples (31). Known hits keep their value of 1, and known misses stay at 0, since samples never cover a miss or a sunk cell (32).

    27
    function SAMPLE(lengths, free, hits, samples):
        for each of the samples:
            used ← no cells;  weight ← 1
            for each ship length n in lengths:
                valid ← the placements of length n in free that avoid used
                weight ← weight × |valid|
                if valid is not empty:
                    used ← used ∪ (a placement drawn uniformly from valid)
            keep the sample if its weight is above 0 and it covers every open hit
        return, for each cell, the weighted share of kept samples that cover it

    Uniform choice by random keys gives each valid placement an independent random key and takes the largest, which picks one valid placement uniformly without building a list. A sample with no valid placement picks an invalid one, but its weight is already 0. The membership matrix unpacks each sample's cells into a row of 0s and 1s, so the weighted sum over samples is one matrix product (33).

    The odds glow

    The glow shades each board in proportion to the odds of a ship in each unknown cell. The odds are nearly flat early in a game, so the shading is measured from the mean rather than from zero. The mean and the span are computed first, where U is the set of unknown cells (34).

    35
    \mu = \frac{1}{|U|} \sum_{u \in U} P(u), \qquad \operatorname{span} = \max\!\big(10^{-9},\ \max_{u \in U} P(u) - \mu\big)
    36
    \alpha(c) = 0.8 \cdot \min\!\Big(1,\ \max\!\Big(0,\ \frac{P(c) - \mu}{\operatorname{span}}\Big)\Big)

    Here \mu is the mean of the unknown cells' odds, \operatorname{span} is the distance from that mean to the highest odds, floored at 10^{-9}, \alpha(c) is the opacity of the glow on cell c, and P(c) is its odds. Known cells never glow. Cells above the mean glow, the hottest one brightest, and cells at or below the mean stay clear. The cap of 0.8 keeps the glow from hiding the board.

    Hunt and target and random (benchmark baselines)

    The page does not offer these, but the benchmark and the command-line race do. Hunt and target is the textbook method. It searches a checkerboard, the cells whose row and column sum to an even number, until a hit appears. Every ship of length 2 or more covers at least one such cell, so the checkerboard eventually touches every ship (37).

    38
    (r + k) \bmod 2 = 0

    Here r is the row and k the column of a cell, counted from 0. Once a hit is open, the agent works on its line. If two open hits share a row or a column, it fires only along that line, at the unknown cells between the hits and the two cells just beyond them. Otherwise it fires at every unknown orthogonal neighbour of an open hit (39).

    Random fires at a uniformly random unknown cell and ignores every hit. It is the floor that a real strategy should beat (40).

    41
    function HUNT-TARGET(knowledge):
        targets ← LINE-TARGETS(knowledge)
        if targets is not empty:
            return a random cell from targets
        unknown ← the cells not yet fired at
        parity ← the cells in unknown whose row + column is even
        return a random cell from parity, or from unknown if parity is empty
    
    function LINE-TARGETS(knowledge):
        for each pair of open hits (a, b) with a before b:
            if a and b share a row: the line is horizontal
            else if they share a column: the line is vertical
            else: skip this pair
            cands ← the unfired cells from a to b on the line, and the two cells beyond
            if cands is not empty: return cands
        return the unfired orthogonal neighbours of every open hit

    The checkerboard works because every ship of length 2 or more contains at least one even cell, so a search of the even cells cannot miss a ship. The odd cells are fired at only when the even cells are used up, or when they are neighbours of a hit. Lines turn a second hit into a direction. Once two hits are aligned, the code fires only along their line, and the two cells beyond the ends test whether the ship continues past either hit.

    Chance (fixed odds)

    Chance draws each shot from a fixed table of weights and never looks at its hits or misses. The weight of the cell in row r and column k is the product of two values from the profile p = (1, 2, 3, 4, 4, 4, 4, 3, 2, 1). The profile rises from the edge to the middle of the board (42).

    43
    w(r,k) = p_r \cdot p_k
    44
    q(c) = \frac{w(c)}{\sum_{u \in U} w(u)}

    Here p_r and p_k are the profile values for the row and the column, and U is the set of unknown cells. Chance fires at cell c with probability q(c), so the weights are renormalised over the cells it has not fired at. A centre cell weighs 16 times a corner cell. The code explains the shape by the placements: a ship can lie under more placements through the middle of the board, so a centre cell is a little likelier to hold a ship. Chance does not know this; it fires where the table says (45).

    46
    function CHANCE-SHOT(knowledge):
        unknown ← the cells not yet fired at
        return a cell from unknown, drawn with probability weight(c) / (the sum of weight(u) over unknown)

    The table is fixed for the whole game, so the shooter is a dice roller with no reasoning. Only unknown cells are candidates, so every shot is legal and the weights are renormalised over them (47). The page's table is the same product, and its odds are the renormalised list shown in the odds panel (44).

    The chance race and solo watch

    A race pits the AI against chance. Each side has a random legal fleet, and the two sides take turns firing at each other's fleets. The first side to sink the other's fleet wins. The first shooter alternates from one race to the next (48, 49).

    48
    function RACE(ai, ai_first):
        ai_fleet ← a random legal fleet            # chance fires at this one
        chance_fleet ← a random legal fleet        # the AI fires at this one
        turns ← the AI, then chance (reversed if not ai_first)
        loop:
            for each side in turns:
                cell ← the side's choice from its own knowledge
                the enemy fleet answers, and the side records the answer
                if the enemy fleet has no ship afloat:
                    return the side as the winner

    Shots alternate, so the side that sinks the other fleet first wins, and a race cannot be drawn. Each side keeps its own knowledge and sees only the answers to its own shots. The race's first shooter alternates by game index, so neither side always fires first, and every race is seeded, so a run repeats exactly (50).

    On the page, the race is split between the server and the browser. The AI's fleet lives on the server, and each AI shot is a request for the shot, followed by a request for the AI's next odds (51, 52). The opponent's fleet is on the page, so the browser resolves the opponent's shots itself and sends only their results to the server for fresh odds (53). The server computes the odds from that history and never sees the player's fleet (54).

    Solo watch (AI alone) runs the same loop with only one shooter: the AI fires at your fleet, and nothing fires back. The page then shows the AI's odds over your fleet (55, 56). A pause of 1,500, 1,000 or 800 ms separates shots, for slow, normal and fast. After a race, a fresh race starts after 1.8 s if auto-restart is on (57, 58).

    Rules and parameters

    ConstantWhat it controlsValue
    FleetShip lengths, straight and not overlapping (may touch)5, 4, 3, 3, 2 (17 cells) on a 10 × 10 grid
    SAMPLESSamples drawn when exact counting is too large1,000
    EXACT_BUDGETCandidate checks the exact search may spend60,000
    Exact gateExact counting is tried only if the unpruned placement product fits≤ 30,000 (half the budget)
    Tie toleranceProbabilities this close count as tied1e-12
    Known cellsProbability of a cell already shot: a hit or a sunk cell, or a miss1.0 and 0.0
    Sampling errorTypical error on one cell's probability with SAMPLES0.02 to 0.03
    CheckerboardHunt and target's search pattern(row + column) even
    CHANCE_PROFILEChance's weight per row and column; a cell weighs the product1, 2, 3, 4, 4, 4, 4, 3, 2, 1
    Glow capLargest opacity of the odds glow0.8
    Shot pauseTime between shots in a watched race, slow / normal / fast1,500 / 1,000 / 800 ms
    MOVES_PER_MINRequests per minute per client on move endpoints120
    GAME_TTLHow long an unfinished server game is kept30 minutes

    How these were chosen: CHANCE_PROFILE is a hand-picked shape: symmetric, rising from the edge to the middle, with four equal middle rows. Nothing is learned or tuned. SAMPLES and EXACT_BUDGET are hand-picked constants, and the repository has no sweep that justifies them. The 30,000 gate is half the budget, so an exact attempt can finish before the budget runs out. The checkerboard follows from the ship lengths, not from a search. The server's request limit and game lifetime are set in the server modules (59, 60).

    Results

    Benchmark: 100 random fleets, seed 1, the same fleets for every agent. The mean shots to sink a fleet were 95.4 for random, 51.9 for hunt and target, and 45.9 for the Bayesian agent, with medians of 97.0, 54.0 and 45.5 and worst cases of 100, 67 and 64 (61).

    Paired on the same fleets, the Bayesian agent needed fewer shots than hunt and target on 67 fleets, more on 30, and tied on 3. The mean saving is 5.96 shots. The 95% interval uses the paired per-fleet differences d_i, with mean \bar d and sample standard deviation s over n = 100 fleets (62).

    62
    \bar d \pm t_{0.975,\,99}\,\frac{s}{\sqrt{n}} = 5.96 \pm 1.9842 \cdot \frac{11.46}{\sqrt{100}} \approx 3.7 \text{ to } 8.2

    Here d_i is the number of shots hunt and target needed minus the number the Bayesian agent needed on fleet i, so a positive value favours the Bayesian agent. The interval is a t interval with 99 degrees of freedom, and the file also gives a normal interval, which is nearly the same.

    Per fleet, the Bayesian agent took 1.12 s on average against 7 ms for hunt and target, measured on a loaded shared laptop, so its cost per shot is far higher. Its strength is the number of shots, not the speed (63).

    Race: 100 races, seed 1, python -m battleship match --games 100 --seed 1. The Bayesian AI won all 100 races against chance, and hunt and target also won all 100. The mean shots when the race ended were 46.0 for the Bayesian AI and 45.5 for chance. The full output is in 64.