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.
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 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.
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.
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).
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
function CHOOSE-SHOT(knowledge, rng): # ProbabilityAgent.choose
belief ← SHIP-PROBABILITIES(knowledge, rng, SAMPLES, EXACT_BUDGET)
unknown ← UNKNOWN-CELLS(knowledge) # cells not fired at, row by row
if belief.method = none or unknown is empty:
return rng.choice(unknown) # no consistent layout: uniform
best ← max(belief.probs[c] for c in unknown)
ties ← [c for c in unknown if belief.probs[c] ≥ best − 1e-12]
return rng.choice(ties) # ties are broken at random
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.
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"
function SHIP-PROBABILITIES(knowledge, rng, samples, budget):
probs ← 0 for every cell
for each hit c (sunk ships included): probs[c] ← 1.0
lengths ← remaining lengths, longest first
if lengths is empty:
return (probs, "done", 0)
free[n] ← placements of length n avoiding misses and sunk cells, for each n in lengths
if free[n] is empty for some n in lengths:
return (probs, "none", 0)
hits ← open hits
bound ← the product of |free[n]| over n in lengths # ignores overlaps
counts ← none
if bound ≤ budget / 2:
try:
counts ← COUNT-EXACT(lengths, free, hits, budget)
on time-limit reached:
counts ← none # the bound is loose: sample instead
if counts is not none:
total ← sum of the values of counts
if total = 0:
return (probs, "none", 0)
for each cell c with a nonzero share:
probs[c] ← (sum of counts[U] over the sets U that contain c) / total
return (probs, "exact", total)
estimate ← SAMPLE(lengths, free, hits, rng, samples)
if estimate is none:
return (probs, "none", 0)
for each cell c that is not a hit: probs[c] ← estimate[c]
return (probs, "sampled", samples)
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 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).
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.
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)
function COUNT-EXACT(lengths, free, hits, budget):
tail[i] ← the total length of ships i to the last, and 0 after the last
counts ← an empty tally; work ← 0
function PLACE(i, used):
if i is past the last ship:
if hits − used is empty: # every open hit is covered
counts[used] ← counts[used] + 1
return
if |hits − used| > tail[i]: # prune: too few cells left
return
options ← free[lengths[i]]
work ← work + |options|
if work > budget:
raise time-limit reached
for each placement m in options:
if m does not overlap used:
PLACE(i + 1, used ∪ m)
PLACE(first ship, no cells used)
return counts
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.
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.
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).
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
function SAMPLE(lengths, free, hits, rng, samples):
gen ← a random generator seeded from rng
used[s] ← no cells; weight[s] ← 1 # for all samples at once
for each ship length n in lengths:
cand ← free[n]
valid[s][p] ← placement p of cand does not overlap used[s]
weight[s] ← weight[s] × (the number of valid p) # 0 if none fits
key[s][p] ← a random number in [0, 1) if valid, else −1
pick[s] ← the p with the largest key[s][p] # uniform among the valid p
used[s] ← used[s] ∪ cand[pick[s]]
keep[s] ← weight[s] > 0 and used[s] covers every open hit
w[s] ← weight[s] if keep[s] else 0
total ← sum of w[s]
if total = 0:
return none
return, for each cell c, (sum over s of w[s] × [c in used[s]]) / total
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 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).
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.
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).
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).
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
function HUNT-TARGET(knowledge, rng):
targets ← LINE-TARGETS(knowledge)
if targets is not empty:
return rng.choice(targets)
unknown ← the cells not yet fired at, row by row
parity ← [c in unknown if (row(c) + col(c)) mod 2 = 0]
return rng.choice(parity or unknown) # parity is empty only when every even cell is fired
function LINE-TARGETS(knowledge):
hits ← the open hits, in ascending order
if hits is empty: return []
for each pair (a, b) of hits, with a < b:
if row(a) = row(b): step ← 1
else if col(a) = col(b): step ← 10
else: continue
line ← a, a + step, …, b
beyond ← [a − step, b + step]
cands ← [c in line + beyond if 0 ≤ c < 100 and c is not fired
and c is on the same row (step 1) or column (step 10) as a]
if cands is not empty: return cands
return sorted([n for h in hits for n in NEIGHBOURS(h) if n is not fired])
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 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).
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).
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)
constants profile ← (1, 2, 3, 4, 4, 4, 4, 3, 2, 1)
function WEIGHT(c):
return profile[row(c)] × profile[col(c)] # row(c) = c div 10, col(c) = c mod 10
function CHANCE-SHOT(knowledge, rng):
unknown ← the cells not yet fired at, row by row
return rng.choices(unknown, weights = [WEIGHT(c) for c in unknown])[0]
function CHANCE-ODDS(knowledge):
odds ← 0 for every cell
total ← the sum of WEIGHT(u) over the unknown cells u
for each unknown cell c: odds[c] ← WEIGHT(c) / total
return odds
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).
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).
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
function RACE(ai_name, rng, ai_first):
ai_fleet ← Fleet(random_fleet(rng)) # chance fires at this
chance_fleet ← Fleet(random_fleet(rng)) # the AI fires at this
ai ← make_agent(ai_name, rng); chance ← ChanceAgent(rng)
ai_k ← Knowledge(); chance_k ← Knowledge()
turns ← [(ai, ai_k, chance_fleet), (chance, chance_k, ai_fleet)], reversed if not ai_first
shots ← {ai: 0, chance: 0}
loop:
for each (side, agent, know, enemy) in turns:
cell ← agent.choose(know)
shot ← enemy.fire(cell)
know.observe(cell, shot.result, shot.ship)
shots[side] ← shots[side] + 1
if enemy.all_sunk:
return (side, shots)
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).
| Constant | What it controls | Value |
|---|---|---|
| Fleet | Ship lengths, straight and not overlapping (may touch) | 5, 4, 3, 3, 2 (17 cells) on a 10 × 10 grid |
| SAMPLES | Samples drawn when exact counting is too large | 1,000 |
| EXACT_BUDGET | Candidate checks the exact search may spend | 60,000 |
| Exact gate | Exact counting is tried only if the unpruned placement product fits | ≤ 30,000 (half the budget) |
| Tie tolerance | Probabilities this close count as tied | 1e-12 |
| Known cells | Probability of a cell already shot: a hit or a sunk cell, or a miss | 1.0 and 0.0 |
| Sampling error | Typical error on one cell's probability with SAMPLES | 0.02 to 0.03 |
| Checkerboard | Hunt and target's search pattern | (row + column) even |
| CHANCE_PROFILE | Chance's weight per row and column; a cell weighs the product | 1, 2, 3, 4, 4, 4, 4, 3, 2, 1 |
| Glow cap | Largest opacity of the odds glow | 0.8 |
| Shot pause | Time between shots in a watched race, slow / normal / fast | 1,500 / 1,000 / 800 ms |
| MOVES_PER_MIN | Requests per minute per client on move endpoints | 120 |
| GAME_TTL | How long an unfinished server game is kept | 30 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).
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).
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.