Last active
May 22, 2018 23:21
-
-
Save dutc/1372599c96e589d4bcf9c584101ace89 to your computer and use it in GitHub Desktop.
simple program for playing Battleship
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run
python battleplayer.py
. Output should look like: