Skip to content

Instantly share code, notes, and snippets.

@jpboudreault
Created December 24, 2020 06:45
Show Gist options
  • Save jpboudreault/fbd80d9550195faa6b568d978760885a to your computer and use it in GitHub Desktop.
Save jpboudreault/fbd80d9550195faa6b568d978760885a to your computer and use it in GitHub Desktop.
Sample Battleship AI
import random
import requests
import sys
# service endpoint
# WARNING: the server is a hackathon project not built for scale (yet), please don't kill it with ML or heavy load!
service_url = "https://appdirect-jpb-battleship.herokuapp.com"
# game seed
seed = 0 # a fixed seed makes the board predictable (easier when testing)
# seed = random.randint(0, 99999999) # uncomment this line to do the real thing
def get_next_play(game_state):
# TODO implement me, return an array of the next play [x,y]
# for now, play the first open spot
for x in range(9):
for y in range(9):
square_state = game_state['board'][x][y]
if square_state is None:
return [x, y]
# value in a square is either "MISSED", "SUNKEN", "HIT" or null
def create_game():
response = requests.post(f'{service_url}/api/game/{seed}')
if response.status_code >= 300:
sys.exit(f'Error creating game {response.status_code}')
return response.json()['id']
def play(game_id, x, y):
response = requests.post(f'{service_url}/api/game/{game_id}/play', json={"x": x, "y": y})
if response.status_code >= 300:
sys.exit(f'Error {response.status_code} playing at x,y: {x},{y}')
def get_game_state(game_id):
return requests.get(f'{service_url}/api/game/{game_id}').json()
if __name__ == '__main__':
print('Hello, lets play Battleship')
game_id = create_game()
print(f'View the game here: {service_url}/view/{game_id}')
while True:
# refresh game state
state = get_game_state(game_id)
if state['ended']:
print(f'Game finished in : {state["moveCount"]}')
break
next_play = get_next_play(state)
play(game_id, next_play[0], next_play[1])
print('Program ended')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment