示例#1
0
def test_populate():
    w = World(4)

    w.populate(
        Individual(),
        1, 3
    )

    assert 1 == len(w.get_population())
示例#2
0
def test_queeu_when_zombie_is_populated():
    w = World(4)

    w.populate(
        Individual(is_zombie = True),
        1, 3
    )

    assert 1 == len(w.get_queue())
示例#3
0
def test_simulation():
    w = World(4)

    w.populate(
        Individual(is_zombie = True),
        2, 1
    )

    w.populate(
        Individual(),
        1, 2
    )

    w.simulate(moves = "DLUURR")

    score, positions = w.get_stats()

    # One victim
    assert 1 == score

    # Two zombies
    assert 2 == len(positions)

    # First at (3, 0)
    assert 3 == positions[0]['x']
    assert 0 == positions[0]['y']

    # Second at (2, 1)
    assert 2 == positions[1]['x']
    assert 1 == positions[1]['y']
def go_to(world: World, target: Vector2D):
    head_pos = world.get_self().get_head()
    my_next_heads = get_nearest_pos(head_pos)  # [d, u, r, l]
    next_head_wall = [False for _ in range(4)]
    next_head_snake = [False for _ in range(4)]
    next_head_phead = [False for _ in range(4)]
    next_head_target = [False for _ in range(4)]
    next_head_dist = [0 for _ in range(4)]
    action_eval = [0 for _ in range(4)]

    h = 0
    for nhead in my_next_heads:
        if world.board[nhead.i][nhead.j] == -1:
            next_head_wall[h] = True
        if world.board[nhead.i][nhead.j] in [1, 2, 3, 4]:
            next_head_snake[h] = True
        if world.board[nhead.i][nhead.j] == 5:
            next_head_target[h] = True
        other_snake_phead = []
        for i in [1, 2, 3, 4]:
            if i == world.self_id:
                continue
            res = get_nearest_pos(world.get_snake(i).get_head())
            for r in res:
                other_snake_phead.append(r)
        if nhead in other_snake_phead:
            next_head_phead[h] = True
        next_head_dist[h] = get_nearest_path(world, nhead, target,
                                             world.self_id)
        h += 1

    best_action_number = 0
    best_action_eval = 1000000
    for a in range(4):
        action_eval[a] = next_head_dist[a][0]
        if next_head_target[a]:
            action_eval[a] = 0
        action_eval[a] += 1
        if next_head_wall[a] or next_head_snake[a]:
            action_eval[a] *= 1000
        if next_head_phead[a]:
            action_eval[a] *= 100

        if action_eval[a] < best_action_eval:
            best_action_eval = action_eval[a]
            best_action_number = a
        # print(my_next_heads[a], next_head_wall[a], next_head_snake[a], next_head_phead[a], next_head_dist[a],
        #       next_head_target[a], action_eval[a])

    actions = ['d', 'u', 'r', 'l']
    # print('best action:', best_action_number, actions[best_action_number])
    return actions[best_action_number]
def get_snakes_dist_to_goal(world: World):
    res = []
    for i in [1, 2, 3, 4]:
        head_pos = world.get_snake(i).get_head()
        dist_action = get_nearest_path(world, head_pos, world.goal_position, i)
        res.append(dist_action)
    return res
示例#6
0
def run():
    parser = ArgumentParser()
    parser.add_argument("-n", "--name", dest="name", type=str, default='team_name' + str(random.randint(0, 10000)),
                        help="Client Name", metavar="NAME")
    parser.add_argument("-c", "--client", dest="client_type", type=str, default='auto',
                        help="greedy, random, hand, best, your", metavar="ClientType")
    parser.add_argument("-p", "--port", dest="server_port", type=int, default=20002,
                        help="server port", metavar="ServerPort")
    parser.add_argument("-s", "--server", dest="server_address", type=str, default='localhost',
                        help="server address", metavar="ServerAddress")
    args = parser.parse_args()
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.settimeout(1)
    server_address = (args.server_address, args.server_port)
    world = World()
    message_snd = MessageClientConnectRequest(args.name).build()

    while is_run:
        sock.sendto(message_snd, server_address)
        try:
            message_rcv = sock.recvfrom(4096)
        except:
            continue
        message = parse(message_rcv[0])
        if message.type == 'MessageClientConnectResponse':
            if message.id == -1:
                print('your name is duplicated!!!')
                exit(-1)
            print('my id is ' + str(message.id))
            world.set_id(message.id, message.ground_config['goal_id'])
            break

    while is_run:
        try:
            r = sock.recvfrom(4096)
        except:
            continue
        message = parse(r[0])
        if message.type == 'MessageClientDisconnect':
            break
        elif message.type == 'MessageClientWorld':
            world.update(message)
            world.print()

            action = ""
            if args.client_type == 'greedy' or (args.client_type == 'auto' and world.self_id == 1):
                action = c_greedy.get_action(world)
            elif args.client_type == 'random' or (args.client_type == 'auto' and world.self_id >= 2):
                action = c_random.get_action(world)
            elif args.client_type == 'best':
                action = c_best.get_action(world)
            elif args.client_type == 'your':
                action = c_your.get_action(world)
            elif args.client_type == 'hand':
                action = input('enter action (u or d or l or r:')

            sock.sendto(MessageClientAction(string_action=action).build(), server_address)
示例#7
0
def get_action(world: World):
    head_pos = world.get_self().get_head()
    next_head = []
    next_head.append(head_pos + Vector2D(1, 0))
    next_head.append(head_pos + Vector2D(0, 1))
    next_head.append(head_pos + Vector2D(-1, 0))
    next_head.append(head_pos + Vector2D(0, -1))
    next_head_price = [0, 0, 0, 0]
    actions = ['d', 'r', 'u', 'l']

    obstacle_1 = []
    obstacle_2 = []

    obstacle_1 += world.get_walls()
    for s in world.snakes:
        snake_temp = world.snakes[s]
        snake_temp_head = world.snakes[s].get_head()

        obstacle_1 += snake_temp.get_body()

        if snake_temp_head is not head_pos:
            obstacle_2.append(snake_temp_head + Vector2D(1, 0))
            obstacle_2.append(snake_temp_head + Vector2D(0, 1))
            obstacle_2.append(snake_temp_head + Vector2D(-1, 0))
            obstacle_2.append(snake_temp_head + Vector2D(0, -1))

    h_number = -1
    for h in next_head:
        h_number += 1

        if h in obstacle_1:
            next_head_price[h_number] += 60
        if h in obstacle_2:
            next_head_price[h_number] += 20 * obstacle_2.count(h)

        next_head_price[h_number] += world.goal_position.dist(h)

    print(next_head_price)
    print(actions)
    mini = min(next_head_price)
    for h_number in range(4):
        if next_head_price[h_number] == mini:
            return actions[h_number]
def get_action(world: World):
    head_pos = world.get_self().get_head()
    next_head = []
    next_head.append(head_pos + Vector2D(1, 0))
    next_head.append(head_pos + Vector2D(0, 1))
    next_head.append(head_pos + Vector2D(-1, 0))
    next_head.append(head_pos + Vector2D(0, -1))
    next_head_ok = [True, True, True, True]

    h_number = 0
    for h in next_head:
        accident = False
        for s in world.snakes:
            if h in world.snakes[s].get_body():
                accident = True
                break
        if accident:
            print(h, 'snake')
        if h in world.get_walls():
            accident = True
            print(h, 'wall')
        if accident:
            next_head_ok[h_number] = False
        h_number += 1

    print(next_head)
    print(next_head_ok)
    min_dist = 1000
    h_best = -1
    for h in range(4):
        if not next_head_ok[h]:
            continue
        dist = next_head[h].dist(world.goal_position)
        if dist < min_dist:
            min_dist = dist
            h_best = h

    print(h_best)

    actions = ['d', 'r', 'u', 'l']
    if h_best > 0:
        return actions[h_best]
    return actions[0]
示例#9
0
    def play(self) -> None:
        """ Run the world simulation
        """

        i = 0

        for inp in self.inputs:

            i += 1

            print("Simulation: ", i)
            print("World: " + str(inp['n']) + " x " + str(inp['n']))
            print()

            # Create world
            world = World(inp['n'])

            # Place zombie
            world.populate(Individual(is_zombie=True), inp['zombie']['x'],
                           inp['zombie']['y'])

            # Place creatures
            for creature in inp['creatures']:
                world.populate(Individual(), creature['x'], creature['y'])

            # Simulate
            world.simulate(inp['moves'])

            # Get stats
            score, positions = world.get_stats()

            print("zombies' score: ", score)
            print("zombies' positions:")

            for position in positions:
                print("(" + str(position['x']) + ", " + str(position['y']) +
                      ")",
                      end=" ")

            print()
            print("---")
            print()
示例#10
0
def get_action(world: World):
    set_max(world)
    # for s in [1,2,3,4]:
    #     print(world.get_snake(s).body)
    dists_to_goal = get_snakes_dist_to_goal(world)
    # print('dist to goal=', dists_to_goal)
    dist_action = dists_to_goal[world.self_id - 1]
    mindist = 10000
    for da in dists_to_goal:
        if mindist > da[0]:
            mindist = da[0]
    near_snake = 0
    for da in dists_to_goal:
        if mindist == da[0]:
            near_snake += 1

    if dist_action[0] == mindist and near_snake == 1:
        # print('want to target')
        return go_to(world, world.goal_position)
    else:  # GO OTHER POS
        free_pos = []
        free_pos.append(Vector2D(6, 6))
        free_pos.append(Vector2D(6, 14))
        free_pos.append(Vector2D(6, 23))
        free_pos.append(Vector2D(14, 6))
        free_pos.append(Vector2D(14, 14))
        free_pos.append(Vector2D(14, 23))
        free_pos.append(Vector2D(23, 6))
        free_pos.append(Vector2D(23, 14))
        free_pos.append(Vector2D(23, 23))
        snake_heads = []
        for s in [1, 2, 3, 4]:
            if s == world.self_id:
                continue
            snake_heads.append(world.get_snake(s).get_head())
        best_free = None
        best_eval = 0
        for f in free_pos:
            e = get_eval_free_pos(snake_heads, f)
            if world.board[f.i][f.j] != 0:
                continue
            if e > best_eval:
                best_eval = e
                best_free = f

        # print('want to best free:', best_free)
        return go_to(world, best_free)
示例#11
0
def get_action(world: World):
    head_pos = world.get_self().get_head()
    next_head = []
    next_head.append(head_pos + Vector2D(1, 0))
    next_head.append(head_pos + Vector2D(0, 1))
    next_head.append(head_pos + Vector2D(-1, 0))
    next_head.append(head_pos + Vector2D(0, -1))

    min_dist = 1000
    h_best = -1
    for h in range(4):
        dist = next_head[h].dist(world.goal_position)
        if dist < min_dist:
            min_dist = dist
            h_best = h

    print(h_best)

    actions = ['d', 'r', 'u', 'l']
    if h_best > 0:
        return actions[h_best]
    return actions[0]
示例#12
0
def get_action(world: World):

    goal = world.goal_position
    head_pos = world.get_self().get_head()

    next_head = []
    next_head.append(head_pos + Vector2D(1, 0))
    next_head.append(head_pos + Vector2D(0, 1))
    next_head.append(head_pos + Vector2D(-1, 0))
    next_head.append(head_pos + Vector2D(0, -1))
    next_head_price = [0, 0, 0, 0]
    actions = ['d', 'r', 'u', 'l']

    staticVar = Snakes()
    staticVar.update_snake(0, world.get_self().get_body(), head_pos, goal)
    print(staticVar.tail(0))

    obstacle_1 = []
    obstacle_2 = []

    obstacle_1 += world.get_walls()

    min_dist = 1000
    my_dist = goal.dist(head_pos)
    c = 0
    for s in world.snakes:
        c += 1
        t = world.snakes[s].get_head().dist(goal)
        if min_dist > t:
            min_dist = t

        snake_temp = world.snakes[s]
        snake_temp_head = world.snakes[s].get_head()

        # print('Snake num ', c, '  :  ', snake_temp.get_body())
        obstacle_1 += snake_temp.get_body()

        if snake_temp_head is not head_pos:
            obstacle_2.append(snake_temp_head + Vector2D(1, 0))
            obstacle_2.append(snake_temp_head + Vector2D(0, 1))
            obstacle_2.append(snake_temp_head + Vector2D(-1, 0))
            obstacle_2.append(snake_temp_head + Vector2D(0, -1))

    a_star = []

    if ((2.5 * min_dist) < my_dist) or (min_dist < 10 and
                                        (my_dist - min_dist) > 3):
        heu = 1
        newGoal = Vector2D(14, 15)
        if head_pos.i > 15 and head_pos.j > 15:
            newGoal = Vector2D(10, 10)
        elif head_pos.i < 15 and head_pos.j > 15:
            newGoal = Vector2D(20, 10)
        elif head_pos.i > 15 and head_pos.j < 15:
            newGoal = Vector2D(10, 20)
        else:
            newGoal = Vector2D(20, 20)

        toCenter = head_pos.dist(newGoal)
        # print('goal ', newGoal)

        if toCenter > 30:
            heu = 4
        elif toCenter > 20:
            heu = 3
        elif toCenter > 10:
            heu = 2
        a_star = aStar(Node(head_pos), Vector2D(14, 15), obstacle_1, heu, 30)

        if len(a_star) == 0:
            next_head_price = my_fast_selection(next_head, goal, obstacle_1,
                                                obstacle_2)
    else:
        # print('goal ', goal)
        heu = 1
        if my_dist > 30:
            heu = 4
        elif my_dist > 20:
            heu = 3
        elif my_dist > 10:
            heu = 2
        a_star = aStar(Node(head_pos), goal, obstacle_1, heu, 30)

        if len(a_star) == 0:
            next_head_price = my_fast_selection(next_head, goal, obstacle_1,
                                                obstacle_2)

    next_price = check_next(head_pos, obstacle_1, obstacle_2)
    h_number = -1
    for h in next_head:
        h_number += 1

        next_head_price[h_number] += next_price[h_number]

        if h in a_star:
            next_head_price[h_number] -= 20  # resideG
    # print('Rezaaaaaaaaaaaaaaaaaaaaaaa')
    # print('aStar output ', a_star)
    # print(actions)
    # print(next_price)
    # print(next_head_price)
    mini = min(next_head_price)
    for h_number in range(4):
        if next_head_price[h_number] == mini:
            return actions[h_number]
示例#13
0
def get_nearest_path(world: World, start: Vector2D, target: Vector2D, id):
    board = copy(world.board)
    dist_table = [[0 for _ in range(len(board[0]))]
                  for __ in range(len(board))]
    for i in range(len(board)):
        for j in range(len(board[0])):
            if board[i][j] == -1:
                dist_table[i][j] = -1000  # Wall
            elif board[i][j] > 0 and board[i][j] != 5:
                dist_table[i][j] = -1  # snakes
            elif board[i][j] in [0, 5]:
                dist_table[i][j] = -2000  # Free
    for s in [1, 2, 3, 4]:
        e = -world.get_snake(s).lenght
        for p in world.get_snake(s).get_body():
            dist_table[p.i][p.j] = e
            e += 1
    # for i in dist_table:
    #     print(i)
    dist_table[start.i][start.j] = 0
    candidates = [start]
    n = 0
    find = False
    last_dist = 0
    while find is False:
        if n == len(candidates):
            break
        candid = candidates[n]
        if dist_table[candid.i][candid.j] > last_dist:
            last_dist = dist_table[candid.i][candid.j]
            for I in range(len(dist_table)):
                for J in range(len(dist_table[I])):
                    if dist_table[I][J] > -1000 and dist_table[I][J] < 0:
                        dist_table[I][J] += 1
                        if dist_table[I][J] == 0:
                            dist_table[I][J] = -2000
        dist = dist_table[candid.i][candid.j]
        actions = get_nearest_pos(candid)
        for action in actions:
            if is_valid(action) is False:
                continue
            if action == target:
                find = True
                dist_table[action.i][action.j] = dist + 1
                break
            if dist_table[action.i][action.j] == -2000:
                dist_table[action.i][action.j] = dist + 1
                candidates.append(action)
        n += 1
    # print(find)
    # for i in dist_table:
    #     print(i)
    if find:
        find = False
        path_table = [[0 for _ in range(len(board[0]))]
                      for __ in range(len(board))]
        last = target
        dir_number = 0
        while find is False:
            actions = get_nearest_pos(last)
            dir_number = 1
            for action in actions:
                if is_valid(action) is False:
                    continue
                if dist_table[action.i][
                        action.j] == dist_table[last.i][last.j] - 1:
                    path_table[action.i][action.j] = dir_number
                    last = action
                if action == start:
                    find = True
                    break
                dir_number += 1
        dir_dic = ['u', 'd', 'l', 'r']
        # for i in path_table:
        #     print(i)
        return dist_table[target.i][target.j], dir_dic[dir_number - 1]
    return 1000, 'n'
示例#14
0
def get_action(world: World):
    head_pos = world.get_self().get_head()
    next_head = []
    next_head.append(head_pos + Vector2D(1, 0))  #d
    next_head.append(head_pos + Vector2D(0, 1))  #r
    next_head.append(head_pos + Vector2D(-1, 0))  #u
    next_head.append(head_pos + Vector2D(0, -1))  #l
    next_head_ok = [True, True, True, True]

    h_number = 0
    for h in next_head:
        accident = False
        if h in Map.get_obstacles(world):
            accident = True
            print('obstacle')
        if accident:
            next_head_ok[h_number] = False
        h_number += 1

    min_dist = 1000
    h_best = -1
    h_safe = -1
    h_risky = -1
    for h in range(4):
        if not next_head_ok[h]:
            continue
        dist = next_head[h].dist(world.goal_position)
        if dist < min_dist:
            if not is_surrounded(world, next_head[h],
                                 from_where(head_pos, next_head[h])):
                if not is_risky(world, next_head[h]):
                    min_dist = dist
                    h_best = h
                else:
                    h_risky = h
        else:
            if not is_surrounded(world, next_head[h],
                                 from_where(head_pos, next_head[h])):
                if not is_risky(world, next_head[h]):
                    h_safe = h

    debug = 0
    for s in world.snakes:
        debug += 1
    print('debug', debug)
    print(h_best)
    print('cycle', world.cycle)
    print("salam")

    if h_best == -1:
        if h_safe != -1:
            h_best = h_safe
        else:
            h_best = h_risky

    actions = ['d', 'r', 'u', 'l']
    if h_best > 0:
        return actions[h_best]

    # if h_safe > 0:
    #     return actions[h_safe]
    # if h_risky > 0:
    #     return actions[h_risky]
    return actions[0]
def get_action(world: World):
    goal = world.goal_position
    head_pos = world.get_self().get_head()

    next_head = []
    next_head.append(head_pos + Vector2D(1, 0))
    next_head.append(head_pos + Vector2D(0, 1))
    next_head.append(head_pos + Vector2D(-1, 0))
    next_head.append(head_pos + Vector2D(0, -1))
    next_head_price = [0, 0, 0, 0]
    actions = ['d', 'r', 'u', 'l']

    if goal in next_head:
        for i in range(4):
            if next_head[i] is goal:
                return actions[i]

    obstacle_1 = []
    obstacle_2 = []

    obstacle_1 += world.get_walls()

    min_dist = 1000
    my_dist = goal.dist(head_pos)
    for s in world.snakes:
        t = world.snakes[s].get_head().dist(goal)
        if min_dist > t:
            min_dist = t

        snake_temp = world.snakes[s]
        snake_temp_head = world.snakes[s].get_head()

        obstacle_1 += snake_temp.get_body()

        if snake_temp_head is not head_pos:
            obstacle_2.append(snake_temp_head + Vector2D(1, 0))
            obstacle_2.append(snake_temp_head + Vector2D(0, 1))
            obstacle_2.append(snake_temp_head + Vector2D(-1, 0))
            obstacle_2.append(snake_temp_head + Vector2D(0, -1))

    a_star = []

    if (2.5 * min_dist) < my_dist:
        # fast selection to center
        next_head_price = my_fast_selection(next_head, Vector2D(14, 14),
                                            obstacle_1, obstacle_2)
    elif my_dist > 25:
        # fast selection to goal
        next_head_price = my_fast_selection(next_head, goal, obstacle_1,
                                            obstacle_2)
    else:
        a_star = aStar(Node(head_pos), goal, obstacle_1)

        if a_star is []:
            next_head_price = my_fast_selection(next_head, goal, obstacle_1,
                                                obstacle_2)

    next_price = check_next(head_pos, obstacle_1, obstacle_2)
    h_number = -1
    for h in next_head:
        h_number += 1

        next_head_price[h_number] += next_price[h_number]

        # if h in obstacle_1:
        #     next_head_price[h_number] += 60
        # if h in obstacle_2:
        #     next_head_price[h_number] += 15*obstacle_2.count(h)
        if h in a_star:
            next_head_price[h_number] -= 20  # resideG

    print(next_head_price)
    print(actions)
    mini = min(next_head_price)
    for h_number in range(4):
        if next_head_price[h_number] == mini:
            return actions[h_number]
def get_action(world: World):
    goal = world.goal_position
    head_pos = world.get_self().get_head()

    next_head = []
    next_head.append(head_pos + Vector2D(1, 0))
    next_head.append(head_pos + Vector2D(0, 1))
    next_head.append(head_pos + Vector2D(-1, 0))
    next_head.append(head_pos + Vector2D(0, -1))
    next_head_price = [0, 0, 0, 0]
    actions = ['d', 'r', 'u', 'l']


    obstacle_1 = []
    obstacle_2 = []

    obstacle_1 += world.get_walls()

    min_dist = 1000
    my_dist = goal.dist(head_pos)
    for s in world.snakes:
        t = world.snakes[s].get_head().dist(goal)
        if min_dist > t:
            min_dist = t

        snake_temp = world.snakes[s]
        snake_temp_head = world.snakes[s].get_head()

        obstacle_1 += snake_temp.get_body()

        if snake_temp_head is not head_pos:
            obstacle_2.append(snake_temp_head + Vector2D(1, 0))
            obstacle_2.append(snake_temp_head + Vector2D(0, 1))
            obstacle_2.append(snake_temp_head + Vector2D(-1, 0))
            obstacle_2.append(snake_temp_head + Vector2D(0, -1))

    a_star = []

    if ((2.5*min_dist) < my_dist) or (min_dist<6 and my_dist>7):
        heu = 1
        newGoal = Vector2D(14, 15)
        if head_pos.i > 15 and head_pos.j > 15:
            newGoal = Vector2D(10, 10)
        elif head_pos.i < 15 and head_pos.j > 15:
            newGoal = Vector2D(20, 10)
        elif head_pos.i > 15 and head_pos.j < 15:
            newGoal = Vector2D(10, 20)
        else:
            newGoal = Vector2D(20, 20)

        toCenter = head_pos.dist(newGoal)

        if toCenter > 30:
            heu = 4
        elif toCenter > 20:
            heu = 3
        elif toCenter > 10:
            heu = 2
        a_star = aStar(Node(head_pos), Vector2D(14, 15), obstacle_1, heu, 30)

        if len(a_star) == 0:
            next_head_price = my_fast_selection(
                next_head, goal, obstacle_1, obstacle_2)
    else:
        heu = 1
        if my_dist > 30:
            heu = 4
        elif my_dist > 20:
            heu = 3
        elif my_dist > 10:
            heu = 2
        a_star = aStar(Node(head_pos), goal, obstacle_1, heu, 30)

        if len(a_star) == 0:
            next_head_price = my_fast_selection(
                next_head, goal, obstacle_1, obstacle_2)

    next_price = check_next(head_pos, obstacle_1, obstacle_2)
    h_number = -1
    for h in next_head:
        h_number += 1

        next_head_price[h_number] += next_price[h_number]

        if h in a_star:
            next_head_price[h_number] -= 20             # resideG

    mini = min(next_head_price)
    for h_number in range(4):
        if next_head_price[h_number] == mini:
            return actions[h_number]