示例#1
0
 def __init__(self,
              track,
              color=None,
              pos=None,
              angle=None,
              enable_ai=True):
     super().__init__()
     cars = {0: "white", 1: "yellow", 2: "red", 3: "green", 4: "blue"}
     if type(color) == int and color in cars.keys():
         color = cars[color]
     elif color is None or color not in cars.values():
         color = cars[random.randint(0, 4)]
     if pos is None:
         pos = track.starting_pos
     if angle is None:
         angle = track.starting_angle
     self.__track = track
     self.__base_image = pygame.image.load(
         os.path.join("pictures", "car_" + color + ".png")).convert_alpha()
     self.__image = self.__base_image.copy()
     rect = self.__image.get_rect(center=pos)
     self.__body = pymunk.Body(
         1, pymunk.moment_for_box(1, (rect.w - 14, rect.h - 16)))
     self.__body.position = pos
     self.__body.angle = math.radians(angle)
     self.__shape = pymunk.Poly.create_box(self.__body,
                                           (rect.w - 14, rect.h - 16), 5)
     self.__shape.friction = 1
     self.__shape.sensor = True
     self.__shape.filter = pymunk.ShapeFilter()
     track.space.add(self.__body, self.__shape)
     self.__filter = pymunk.ShapeFilter(mask=pymunk.ShapeFilter.ALL_MASKS)
     self.__scan_density = 120
     self.__scan_range = math.sqrt(self.__track.screen.get_width()**2 +
                                   self.__track.screen.get_height()**2)
     self.__scan_angles = [
         round(x / self.__scan_density * 360)
         for x in range(self.__scan_density)
     ]
     self.__scan_area = [(math.cos(2 * math.pi / self.__scan_density * x) *
                          self.__scan_range,
                          math.sin(2 * math.pi / self.__scan_density * x) *
                          self.__scan_range)
                         for x in range(0, self.__scan_density + 1)][:-1]
     self.__scan_area.reverse()
     self.__scan_intersections = deque()
     self.__sensor_data = {}
     self._update_sensors()
     self.__ai = Ai(math.degrees(self.angle), self.velocity, enable_ai)
示例#2
0
    def __init__(self):
        self.w = 8
        self.h = 8
        self.moving = False
        self.pieceMoving = None
        self.squares = []
        self.bKing = None
        self.wKing = None
        self.aiOn = True
        if self.aiOn:
            self.ai = Ai(self)
        for i in range(self.w):
            self.squares.append([])
            for j in range(self.h):
                self.squares[-1].append(TestSquare(self, i, j))
        a = layout().split("\n")
        for i, j in zip(a, range(len(a))):
            for k, l in zip(i, range(len(i))):
                if k != "-":
                    if k == "k":
                        self.wKing = self.createPiece(misc.getPiece(k.lower()),
                                                      l, j,
                                                      ["white", "black"
                                                       ][int(misc.isUpper(k))])

                    elif k == "K":
                        self.bKing = self.createPiece(misc.getPiece(k.lower()),
                                                      l, j,
                                                      ["white", "black"
                                                       ][int(misc.isUpper(k))])
                    else:
                        self.createPiece(misc.getPiece(k.lower()), l, j,
                                         ["white",
                                          "black"][int(misc.isUpper(k))])

        self.whiteTurn = True

        self.getKing()
示例#3
0
from Ai import Ai
from LanguageClassifier import LanguageClassifier
import settings

ai = Ai()
ai.read_classifier(settings.OCR_DATA_FNAME_GZ)

lc = LanguageClassifier()
lc.load_classifier(settings.LC_DATA_FNAME_GZ)
示例#4
0
 def register_ai(self, id):
     return Ai(id)
示例#5
0
async def agent_loop(server_address="localhost:8000", agent_name="student"):
    async with websockets.connect(
            f"ws://{server_address}/player") as websocket:

        # Receive information about static game properties
        await websocket.send(json.dumps({"cmd": "join", "name": agent_name}))
        msg = await websocket.recv()
        game_properties = json.loads(msg)

        # You can create your own map representation or use the game representation:
        mapa = Map(size=game_properties["size"], mapa=game_properties["map"])

        agent = Ai()
        agent.map = mapa
        agent.xmap = len(mapa.map)
        agent.ymap = len(mapa.map[0])

        mapa_inicial = []
        for i in range(agent.xmap):
            mapa_inicial = mapa_inicial + [[0] * agent.ymap]

        for i in range(agent.xmap):
            for j in range(agent.ymap):
                if agent.map.map[i][j] != 2:
                    mapa_inicial[i][j] = agent.map.map[i][j]
                else:
                    agent.map.map[i][j] = 0

        i = 0
        while True:
            try:
                state = json.loads(
                    await websocket.recv()
                )  # receive game state, this must be called timely or your game will get out of sync with the server

                agent.update(state, mapa)
                agent.update_map(state, mapa_inicial)

                if agent.action != "Perseguir" and agent.action != "Fugir":
                    if agent.cb:

                        if len(agent.bombs) == 0:
                            agent.cb = False
                        agent.action = "Fugir"
                        agent.think()
                    else:
                        if agent.enemysAlive() and agent.enemysInRange():
                            agent.action = "Hunt"
                            agent.think()
                        else:
                            #if agent.existItem() and not (agent.level ==3 or agent.level ==8):
                            if agent.existItem() and agent.needItem():
                                agent.action = "GetItem"
                                agent.think()
                            else:
                                if (agent.level == 4 or agent.level == 3
                                        or agent.level == 2):
                                    if not agent.enemysAlive():
                                        if len(agent.exit) != 0 and (
                                                agent.powersTest[agent.level -
                                                                 1] or
                                            (not agent.powersTest[agent.level -
                                                                  1]
                                             and agent.needItem())):
                                            agent.action = "Exit"
                                            agent.think()
                                        else:
                                            agent.action = "Wall"
                                            agent.think()
                                    else:
                                        agent.next = agent.getEnemy()
                                        agent.action = "Assassin"
                                        agent.think()
                                elif agent.level == 1:
                                    if len(agent.exit) != 0 and (
                                            agent.powersTest[agent.level - 1]
                                            or
                                        (not agent.powersTest[agent.level - 1]
                                         and agent.needItem())):
                                        if not agent.enemysAlive():
                                            agent.action = "Exit"
                                            agent.think()
                                        else:
                                            agent.next = agent.getStrongEnemy()
                                            if agent.next is None:
                                                agent.action = "Porco"
                                                agent.think()
                                            else:
                                                agent.action = "Assassin"
                                                agent.think()
                                    else:
                                        agent.action = "Wall"
                                        agent.think()
                                else:
                                    if not agent.enemysAlive():
                                        if (agent.level == 15):
                                            return 0
                                        if len(agent.exit) != 0 and (
                                                agent.powersTest[agent.level -
                                                                 1] or
                                            (not agent.powersTest[agent.level -
                                                                  1]
                                             and agent.needItem())):
                                            agent.action = "Exit"
                                            agent.think()
                                        else:
                                            agent.action = "Wall"
                                            agent.think()
                                    else:
                                        agent.next = agent.getStrongEnemy()
                                        if agent.next is None:
                                            agent.action = "Porco"
                                            agent.think()
                                        else:
                                            agent.action = "Assassin"
                                            agent.think()

                #print(agent.action)
                #print(agent.moves)
                #print(agent.powersTest)
                if agent.action == "Perseguir":
                    if agent.map2[agent.pos[0]][
                            agent.pos[1]] == 2 or agent.map2[agent.pos[0]][
                                agent.pos[1]] == 3 and not agent.override:
                        agent.moves = []
                        await websocket.send(
                            json.dumps({
                                "cmd": "key",
                                "key": "B"
                            })
                        )  # send key command to server - you must implement this send in the AI agent
                        agent.cb = True
                        agent.action = ""
                    elif len(agent.moves) != 0:
                        key = agent.move()
                        if key == "B" and not agent.wallInRange:
                            agent.action = ""
                        else:
                            await websocket.send(
                                json.dumps({
                                    "cmd": "key",
                                    "key": key
                                })
                            )  # send key command to server - you must implement this send in the AI agent
                            if key == "B":
                                agent.cb = True
                                agent.action = ""
                            if len(agent.moves) == 0:
                                agent.action = ""
                    else:
                        agent.override = False
                        agent.action = ""

                elif agent.action == "Fugir":
                    #if agent.map2[agent.pos[0]][agent.pos[1]] == 2 or agent.map2[agent.pos[0]][agent.pos[1]] == 3:
                    #   agent.moves.queue.clear()
                    #  agent.think()
                    if len(agent.moves) != 0:
                        if agent.moveIsSafe():

                            if len(agent.moves) != 0:
                                key = agent.move()
                                if key == 'A' and not agent.isSafe():
                                    agent.moves = []
                                    agent.action = ""
                                else:
                                    await websocket.send(
                                        json.dumps({
                                            "cmd": "key",
                                            "key": key
                                        })
                                    )  # send key command to server - you must implement this send in the AI agent
                                    if len(agent.moves) == 0:
                                        agent.action = ""
                                        agent.cb = False
                            else:
                                agent.action = ""
                        else:
                            agent.moves = []
                            agent.think()
                            agent.cb = False
                    else:
                        agent.action = ""
                        if len(agent.bombs) == 0:
                            agent.cb = False

            except websockets.exceptions.ConnectionClosedOK:
                print("Server has cleanly disconnected us")
                return