Skip to content

Instantly share code, notes, and snippets.

@dutc
Last active May 22, 2018 23:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dutc/1372599c96e589d4bcf9c584101ace89 to your computer and use it in GitHub Desktop.
Save dutc/1372599c96e589d4bcf9c584101ace89 to your computer and use it in GitHub Desktop.
simple program for playing Battleship
#!/usr/bin/env python3
from itertools import product
from battleserver import Board
if __name__ == '__main__':
board = Board()
for x, y in product(range(5), range(5)):
action = x, y
result = board(x, y)
print(f'{action} → {result}')
if not board:
print('I won!')
break
#!/usr/bin/env python3
from random import choice
from sys import stdin, stderr
class Board:
def __init__(self, ships={'carrier': 5, 'battleship': 3}, size=5):
empty = {(x, y): None for x in range(size) for y in range(size)}
self.ships = {}
for name, size in ships.items():
self.ships[name] = []
while True:
x, y = choice(list(empty))
candidates = [
[(x, y)] + [(x, y - i) for i in range(1, size)],
[(x, y)] + [(x, y + i) for i in range(1, size)],
[(x, y)] + [(x - i, y) for i in range(1, size)],
[(x, y)] + [(x + i, y) for i in range(1, size)],
]
candidates = [c for c in candidates
if all(pos in empty for pos in c)]
if not candidates:
continue
direction = choice(candidates)
self.ships[name].extend(direction)
for x, y in self.ships[name]:
del empty[x, y]
break
self.board = {(x, y): (name, pos) for name, pos in self.ships.items()
for x, y in pos}
def __call__(self, x, y):
if (x, y) not in self.board:
return 'miss'
name, pos = self.board[x, y]
if (x, y) not in pos:
return 'miss'
pos.remove((x, y))
if not pos:
del self.ships[name]
return f'sunk {name}'
return f'hit {name}'
def __len__(self):
return len(self.ships)
if __name__ == '__main__':
board = Board()
while True:
try:
action = next(stdin)
if not action.strip():
break
x, y = action.split()
x, y = int(x), int(y)
except Exception as e:
print(f'invalid action {action}', file=stderr)
continue
result = board(x, y)
print(result)
if not board:
print('you win')
break
@dutc
Copy link
Author

dutc commented May 22, 2018

Run python battleplayer.py. Output should look like:

(0, 0) → miss
(0, 1) → miss
(0, 2) → miss
(0, 3) → miss
(0, 4) → miss
(1, 0) → miss
(1, 1) → miss
(1, 2) → miss
(1, 3) → miss
(1, 4) → miss
(2, 0) → hit battleship
(2, 1) → hit battleship
(2, 2) → miss
(2, 3) → miss
(2, 4) → miss
(3, 0) → sunk battleship
(3, 1) → hit carrier
(3, 2) → hit carrier
(3, 3) → hit carrier
(3, 4) → miss
(4, 0) → miss
(4, 1) → miss
(4, 2) → hit carrier
(4, 3) → sunk carrier
I won!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment