Exemplo n.º 1
0
def move():
    data = bottle.request.json

    """
    TODO: Using the data from the endpoint request object, your
            snake AI must choose a direction to move in.
    """
    print(json.dumps(data))

    directions = ['up', 'left', 'down', 'right']
        #direction = random.choice(directions)

    board = getBoardInfo(data)
    snake = getSnakeInfo(data)
    head_x = snake['head']['x']
    head_y = snake['head']['y']
    width = data['board']['width']
    height = data['board']['height']

    if (board[head_x+1][head_y] == 0 or board[head_x+1][head_y] == 5) and ((head_x+1) < width-1):
        return move_response(directions[3])
    elif (board[head_x][head_y+1] == 0 or board[head_x][head_y+1] == 5) and ((head_y+1) < height-1):
        return move_response(directions[2])
    elif (board[head_x-1][head_y] == 0 or board[head_x-1][head_y] == 5) and ((head_x-1) > 0):
        return move_response(directions[1])
    elif (board[head_x][head_y-1] == 0 or board[head_x][head_y-1] == 5) and ((head_y-1) > 0):
        return move_response(directions[0])
Exemplo n.º 2
0
def move():
    data = dict(bottle.request.json)
    bad_moves = get_disallowed_coords(data)

    """
    TODO: Using the data from the endpoint request object, your
            snake AI must choose a direction to move in.
    """
    #print(data['game'])

    directions = ['up', 'down', 'left', 'right']
    risky_directions = []
    non_risky_directions = []
    food_directions = []
    directions_info = {'bad': ['up', 'down', 'left', 'right'],
                        'risky': [],
                        'risky_food': [],
                        'non_risky': [],
                        'non_risky_food': []}
    move_check = False
    count = 0

    for direction in directions:
        new_head = get_new_head(data, direction)
        is_risky = check_if_risky(data, new_head)
        has_food = check_if_food(data, new_head)

        if new_head not in bad_moves:
            directions_info['risky'].append(direction)
            if has_food:
                directions_info['risky_food'].append(direction)

        if new_head not in bad_moves and not is_risky:
            directions_info['non_risky'].append(direction)
            if has_food:
                directions_info['non_risky_food'].append(direction)

    if len(directions_info['non_risky_food']) > 0:
        print('Turn' + str(data['turn']) + ': non-risky-food option available for ' + data['you']['name'])
        return move_response(random.choice(directions_info['non_risky_food']))

    if len(directions_info['non_risky']) > 0:
        print('Turn' + str(data['turn']) + ': non-risky option available for ' + data['you']['name'])
        return move_response(random.choice(directions_info['non_risky']))

    if len(directions_info['risky_food']) > 0:
        print('Turn' + str(data['turn']) + ': risky-food option available for ' + data['you']['name'])
        return move_response(random.choice(directions_info['risky_food']))

    if len(directions_info['risky']) > 0:
        print('Turn' + str(data['turn']) + ': risky option available for ' + data['you']['name'])
        return move_response(random.choice(directions_info['risky']))

    print('Turn' + str(data['turn']) + ': no options available for ' + data['you']['name'])
    return move_response('up')
Exemplo n.º 3
0
def move():
    start = time.time()
    data = bottle.request.json
    if data["board"]["width"] in [7, 11, 19] and data["board"]["height"] in [7, 11, 19]:
        comm.giveNewData(data)
        sendMove = None
        while sendMove == None:
            sendMove = comm.getNewMove()
        print("move made in " + str(time.time() - start))
        return move_response(sendMove)
    else:
        return move_response('left')
Exemplo n.º 4
0
def move():
    data = bottle.request.json

    dangerSquares = danger_squares(data)
    currentSquare = data['you']['body'][0]  ##my head

    safeMoves = []
    directions = ['up', 'down', 'left', 'right']
    for move in directions:
        if one_move(currentSquare, move) not in dangerSquares:
            safeMoves.append(move)

    if len(safeMoves) == 0:
        direction = random.choice(
            directions)  # when there are no safe moves, chaos ensues
    elif len(safeMoves) == 1:
        direction = safeMoves[
            0]  # take the only safe move if that's the only choice!
    elif len(safeMoves) > 1:
        direction = safeMoves[0]
        for move in safeMoves:
            if square_score(one_move(currentSquare, move), data) > \
            square_score(one_move(currentSquare, direction), data):
                direction = move

    return move_response(direction)
Exemplo n.º 5
0
def move():
    # Get request data
    data = bottle.request.json
    """
    TODO: Using the data from the endpoint request object, your
            snake AI must choose a direction to move in.
    """
    print(json.dumps(data))
    direction = []
    global myLocation

    gameID = data['game']['id']

    myLocation = getMyLocation(data)
    print("myLocation: ", myLocation)
    adjacentCells = getAdjacentCells(myLocation, data)
    print("adjacentCells: ", adjacentCells)
    potentialMove = isSafeSpace(adjacentCells, data)
    print("potentialMove: ", potentialMove)
    findFood = getClosestFood(potentialMove, data)
    print("findFood: ", findFood)

    if findFood:
        direction = random.choice(findFood)
        print("Direction to food: ", direction)
    else:
        direction = random.choice(potentialMove.keys())
        print("Direction in potentialMove: ", direction)

    if len(direction) == 0:
        direction = ['up', 'down', 'left', 'right']
        print("Direction length 0: ", direction)

    return move_response(direction)
Exemplo n.º 6
0
def move():
    data = bottle.request.json
    gamestate = APIGameState(data)
    controller = SnakeController(ControllerMode.ALGO)
    if mode == 'NN':
        pass
    else:
        direction = controller.move(gamestate)
        dir_str = ""
        if direction == Direction.UP:
            dir_str = 'up'
        elif direction == Direction.DOWN:
            dir_str = 'down'
        elif direction == Direction.LEFT:
            dir_str = 'left'
        elif direction == Direction.RIGHT:
            dir_str = 'right'
        else:
            return Direction.NONE
        guiboard = apigamestate_to_simu(gamestate)
        guiboard.render()
    """
    TODO: Using the data from the endpoint request object, your
            snake AI must choose a direction to move in.
    """

    return move_response(dir_str)
Exemplo n.º 7
0
def move():
    data = bottle.request.json
    """
    TODO: Using the data from the endpoint request object, your
            snake AI must choose a direction to move in.
    """
    print(json.dumps(data, indent=2))

    global last_move

    directions = ['up', 'down', 'left', 'right']
    #direction = random.choice(directions)
    if last_move == '':
        direction = 'down'

    if last_move == 'down':
        direction = 'right'

    if last_move == 'right':
        direction = 'up'

    if last_move == 'up':
        direction = 'left'

    if last_move == 'left':
        direction = 'down'

    last_move = direction
    return move_response(direction)
Exemplo n.º 8
0
def move():
    data = bottle.request.json

    head_pos = {
        'x': data['you']['body'][0]['x'],
        'y': data['you']['body'][0]['y']
    }

    obstacleFlag = {
        'up': checkForObstacle(data, head_pos['x'], head_pos['y'] - 1),
        'right': checkForObstacle(data, head_pos['x'] + 1, head_pos['y']),
        'down': checkForObstacle(data, head_pos['x'], head_pos['y'] + 1),
        'left': checkForObstacle(data, head_pos['x'] - 1, head_pos['y'])
    }
    direction = 'right'

    if not obstacleFlag['up']:
        direction = 'up'
    if not obstacleFlag['right']:
        direction = 'right'
    if not obstacleFlag['left']:
        direction = 'left'
    if not obstacleFlag['down']:
        direction = 'down'

    print(json.dumps(data, indent=4))

    directions = ['up', 'down', 'left', 'right']

    return move_response(direction)
Exemplo n.º 9
0
def move():
data = bottle.request.json

	"""
	TODO: Using the data from the endpoint request object, your
	snake AI must choose a direction to move in.
	"""
	print(json.dumps(data))

	snakeDataJson = json.dumps(x)
	snakeData = json.loads(snakeDataJson)

	board_x = snakeData['board']['width'] - 1 
	board_y = snakeData['board']['height'] - 1

	snake_x = snakeData['you']['body'][0]['x']
	snake_y = snakeData['you']['body'][0]['y']

	possible_direction = ['down', 'left', 'up' 'right']

	if(snake_x == 0):
		possible_direction.remove('left')
	if (snake_x == board_x):
		possible_direction.remove('right')
	if (snake_y == 0):
		possible_direction.remove('up')
	if (snake_y == board_y):
		possible_direction.remove('left')

	direction = random.choice(possible_directions)
    
	return move_response(direction)
Exemplo n.º 10
0
def move():
    data = bottle.request.json
    """
    TODO: Using the data from the endpoint request object, your
            snake AI must choose a direction to move in.
    """
    return move_response(minimax.get_move(data))
Exemplo n.º 11
0
def move():
    data = bottle.request.json
    """
    TODO: Using the data from the endpoint request object, your
            snake AI must choose a direction to move in.
    """
    print(json.dumps(data))

    global last_direction
    direction = last_direction

    global last_axis
    print("{}".format(last_axis))

    if (last_axis.get("x", 0) < -0.5):
        direction = 'left'
    elif (last_axis.get("x", 0) > 0.5):
        direction = 'right'

    if (last_axis.get("y", 0) < -0.5):
        direction = 'up'
    elif (last_axis.get("y", 0) > 0.5):
        direction = 'down'

    last_direction = direction

    return move_response(direction)
Exemplo n.º 12
0
def move():
    data = bottle.request.json

    """
    TODO: Using the data from the endpoint request object, your
            snake AI must choose a direction to move in.
    """
    print(json.dumps(data))

    """ s = data['board']['snakes']
    s_count = len(s)
    for snake in s:
        snakes[snake['id']] = snake
    """

    body = data['you']['body']
    x = int(body[0]['x'])
    y = int(body[0]['y'])
    uuid = data['you']['id']


    snake_state = board.State(data)


    direction = board.find_free_space(snake_state)




    
    return move_response(direction)
Exemplo n.º 13
0
def move():
    game_state = bottle.request.json
    new_board = update_board(game_state)
    turn = game_state['turn']  # for testing
    direction = calculate_move(new_board, game_state)

    return move_response(direction)
Exemplo n.º 14
0
def errMove():
    """for when there is no good option
    
    Returns:
        move_response("up")
    """
    return move_response("up")
Exemplo n.º 15
0
def move():
    data = bottle.request.json

    me = data['you']
    #num_snakes = len(data['board']['snakes'])
    rival = []
    for i in data['board']['snakes']:
        if i['id'] != me['id']:
            rival.append(i)

    n = len(rival)
    a = ['u', 'd', 'l', 'r']
    b = ['u', 'd', 'l', 'r']
    if n == 0:
        move_comb = ['u', 'd', 'l', 'r']
    else:
        for k in range(n):
            move_comb = []
            for i in range(len(a)):
                for j in range(len(b)):
                    move_comb.append(a[i] + b[j])
            b = move_comb[:]

    all_moves = []
    for i in ['u', 'd', 'l', 'r']:
        all_moves.append(game_status(data, i))

    nm = 'u'
    final0 = []
    final1 = []

    for i in all_moves:
        if i.rank == 0:
            final0.append(i.result)
        if i.rank == 1:
            final1.append(i.result)

    if len(final1) != 0:
        nm = random.choice(final1)
    elif len(final0) != 0:
        nm = random.choice(final0)
    else:
        nm = random.choice(['u', 'd', 'l', 'r'])

    if nm == 'u':
        direction = 'up'
    elif nm == 'd':
        direction = 'down'
    elif nm == 'l':
        direction = 'left'
    else:
        direction = 'right'

    #print(json.dumps(data))

    #directions = ['up', 'down', 'left', 'right']
    #direction = random.choice(directions)

    return move_response(direction)
Exemplo n.º 16
0
def move():
    global envi
    data = bottle.request.json
    if data != None:
        # Send new data to envrionment
        envi.sendNewData(data)
        move = None
        noMoveTimeoutCounter = 0
        # Wait for network to generate move or timeout.
        while move == None and noMoveTimeoutCounter < 9000:
            move = envi.getMove()
            time.sleep(0.0001)
            noMoveTimeoutCounter += 1
        if move == None:
            move = "left"
        return move_response(move)
    return move_response("left")
Exemplo n.º 17
0
def move():
    data = bottle.request.json
    height = data["board"]["height"]
    width = data["board"]["width"]
    body = data["you"]["body"]
    head = body[0]
    """
    TODO: Using the data from the endpoint request object, your
            snake AI must choose a direction to move in.
    """
    print(json.dumps(data))

    # Check if move left is valid
    if {
            "x": head["x"] - 1,
            "y": head["y"]
    } not in body and head["x"] - 1 >= 0 and head[
            "y"] >= 0 and head["x"] - 1 < width and head["y"] < height:
        return move_response('left')
    # Check if move down is valid
    elif {
            "x": head["x"],
            "y": head["y"] + 1
    } not in body and head["x"] >= 0 and head["y"] + 1 >= 0 and head[
            "x"] < width and head["y"] + 1 < height:
        return move_response('down')
    # Check if move right is valid
    elif {
            "x": head["x"] + 1,
            "y": head["y"]
    } not in body and head["x"] + 1 >= 0 and head[
            "y"] >= 0 and head["x"] + 1 < width and head["y"] < height:
        return move_response('right')
    # Check if move up is valid
    elif {
            "x": head["x"],
            "y": head["y"] - 1
    } not in body and head["x"] >= 0 and head["y"] - 1 >= 0 and head[
            "x"] < width and head["y"] - 1 < height:
        return move_response('up')

    directions = ['up', 'down', 'left', 'right']
    direction = random.choice(directions)

    return move_response(direction)
Exemplo n.º 18
0
def move():
    data = bottle.request.json
    """
    TODO: Using the data from the endpoint request object, your
            snake AI must choose a direction to move in.
    """
    direction = move_process(data)

    return move_response(direction)
Exemplo n.º 19
0
def move():

    directions = ['up', 'down', 'left', 'right']
    game_state = bottle.request.json

    new_board = update_board(game_state)
    direction = calculate_move(new_board, game_state)

    return move_response(direction)
Exemplo n.º 20
0
def move():
    data = bottle.request.json

    print(json.dumps(data))

    directions = ['up', 'down', 'left', 'right']
    direction = random.choice(directions)

    return move_response(direction)
Exemplo n.º 21
0
def move():
    data = bottle.request.json
    our_snek = data['you']
    health = our_snek['health']
    board = game_board(data)
    directions = ['up', 'down', 'left', 'right']
    direction = find_best_move(directions)

    return move_response(direction)
Exemplo n.º 22
0
def move():
    data = bottle.request.json
    """
    TODO: Using the data from the endpoint request object, your
            snake AI must choose a direction to move in.
    """
    # dictionary with reward to choose each
    directions = {'up': 1, 'down': 1, 'left': 1, 'right': 1}

    turn = data['turn']
    board_height = data['board']['height']
    board_width = data['board']['width']

    head_x = data['you']['body'][0]['x']
    head_y = data['you']['body'][0]['y']

    # no neck on first turn
    if turn != 1:
        neck_x = data['you']['body'][1]['x']
        neck_y = data['you']['body'][1]['y']

    for direction in ['up', 'down', 'left', 'right']:
        reward = 0

        # check if any of the moves will run you into a wall
        if hit_wall(head_x, head_y, board_height, board_width, direction):
            reward += -np.inf

        # check which of the moves will run your head into your neck
        if turn != 1:
            if head_hit_neck(head_x, head_y, neck_x, neck_y, direction):
                reward += -np.inf

        # check if it's going to hit its own tail
        if head_hit_tail(head_x, head_y, data, direction):
            reward += -np.inf

        # check if any of the moves will run you into another snake
        if hit_other_snek(head_x, head_y, data, direction):
            reward += -np.inf

        # check which move will bring you closest to food
        # assign rewards based on how much closer the food is
        reward += assign_food_reward(head_x, head_y, data, direction)

        # update directions dict with new reward
        directions[direction] += reward

    # choose direction with greatest reward
    direction = keywithmaxval(directions)

    # for the log
    print(directions)
    print('Chose to go {} on turn {}'.format(direction, turn))

    return move_response(direction)
Exemplo n.º 23
0
def move():
    start_time = time.time()
    game_state = bottle.request.json
    new_board = update_board(game_state)
    turn = game_state['turn']  # for testing
    print("Turn:",turn)
    direction = calculate_move(new_board, game_state)
    total_time = time.time() - start_time
    print('TOTAL TIME FOR MOVE: ' + str(total_time))
    return move_response(direction)
Exemplo n.º 24
0
def move():
    data = bottle.request.json
    last = "unknown"
    """
    TODO: Using the data from the endpoint request object, your
            snake AI must choose a direction to move in.
    """
    # print(json.dumps(data))
    print(food_direction())
    return move_response(food_direction())
Exemplo n.º 25
0
def move():
    data = bottle.request.json
    directions = ['up', 'down', 'left', 'right']

    food = []
    body = []
    enemies = []
    health = -1

	#Process Data from JSON request
	#food,body,enemies stored as list of tuples containing x,y positions [(x,y)]
    #health is stored as an integer between 0-100
    width,height,food, body, enemies, health = process_data(data)
    board = Board(width,height,food, body, enemies, health)

    head = body[0]
    head_x, head_y = head
    tail = body[-1]
    print(tail)

    if(len(body) <= 8 or health <= 35 and len(food) != 0):
        try:
            direction = calc_move(board,a_star(board,head,food[0]))
        except:
            neighbours = []
            if(is_safe(([head_x+1,head_y]),board)):
                neighbours.append(("right"))
            if(is_safe(([head_x-1,head_y]),board)):
                neighbours.append(("left"))
            if(is_safe(([head_x,head_y-1]),board)):
                neighbours.append(("up"))
            if(is_safe(([head_x,head_y+1]),board)):
                neighbours.append(("down"))       
            if (len(neighbours) > 0):
                direction = neighbours[0]
            else:
                direction = 'right'
		    
    else:
        neighbours = []
        if(is_safe(([head_x+1,head_y]),board)):
            neighbours.append(("right"))
        if(is_safe(([head_x-1,head_y]),board)):
            neighbours.append(("left"))
        if(is_safe(([head_x,head_y-1]),board)):
            neighbours.append(("up"))
        if(is_safe(([head_x,head_y+1]),board)):
            neighbours.append(("down"))
        
        if (len(neighbours) > 0):
            direction = neighbours[0]
        else:
            direction = 'right'
	    
    return move_response(direction)
Exemplo n.º 26
0
def move():
    data = bottle.request.json
    games[data['game']['id']] = data
    """
    TODO: Using the data from the endpoint request object, your
            snake AI must choose a direction to move in.
    """

    direction = nextMove(data)

    return move_response(direction)
Exemplo n.º 27
0
def move():
    data = bottle.request.json
    grid = createGrid(data)
    # print (grid)
    # print(json.dumps(data, indent=4, sort_keys=True))

    directions = ['up', 'down', 'left', 'right']

    direction = generatePath(grid, data)

    return move_response(directions[direction])
def move():
    data = bottle.request.json
    move = None
    counter = 0
    if data != None:
        # Make sure we are only playing our current game
        if  data["game"]["id"] == envi.getCurrentGame() \
        and data["you"]["id"] == envi.getCurrentSnake():
            envi.sendNewData(data)
            while move == None and counter < 9000:
                move = envi.getMove()
                time.sleep(0.0001)
                counter += 1
            if counter >= 9000:
                return move_response("left")
        else:
            move = "left"
    else:
        move = "left"
    return move_response(move)
Exemplo n.º 29
0
def move():
    data = bottle.request.json
    """
    TODO: Using the data from the endpoint request object, your
            snake AI must choose a direction to move in.
    """
    print(json.dumps(data))

    direction = decideMove(data)

    return move_response(direction)
Exemplo n.º 30
0
def move():
    data = bottle.request.json

    game_id, grid, food, charlie, enemies = init(data)

    # TODO - thhe print grid function does not work on rectangles
    # print_grid(grid, game_id)

    # # Only check eat kills if length greater than 3
    if charlie['length'] >= 3 and charlie['health'] >= 20:
        path = eat_snake(charlie, enemies, grid)
        if path:
            # log('eat snake path ', path)
            return move_response(direction(path[0], path[1]))

    # # Only check wall kills if length greater than 3
    if charlie['length'] >= 3 and charlie['health'] >= 20:
        path = wall_kill(charlie, enemies, grid)
        if path:
            # log('wall kill path ', path)
            return move_response(direction(path[0], path[1]))

    # Eat food when length or health below threshhold
    if len(enemies) >= 2 or charlie['length'] <= 30 or charlie['health'] <= 60:
        path = eat_food(charlie, grid, food)
        if path:
            # log('eat path ', path)
            return move_response(direction(path[0], path[1]))

    # # if our length is greater than threshold and no other path was available
    if charlie['length'] >= 3:
        path = find_my_tail(charlie, grid)
        if path:
            # log('find my tail path ', path)
            return move_response(direction(path[0], path[1]))

    # # if no path available to tail check if there is an enemies available
    if not path:
        path = find_enemy_tail(charlie, enemies, grid)
        if path:
            # log('find enemy tail path ', path)
            return move_response(direction(path[0], path[1]))

    # # if our length is greater than threshold and no other path was available
    if charlie['length'] >= 3:
        path = find_my_tail_emergency(charlie, grid)
        if path:
            # log('find my tail emergency path ', path)
            return move_response(direction(path[0], path[1]))

    # Choose a random free space if no available enemy tail
    if not path:
        path = trouble(charlie, grid)
        if path:
            # log('trouble path ', path)
            return move_response(direction(path[0], path[1]))