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)
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()
def run(self): numplanets = int(input()) sys.stderr.write("numplanets: " + str(numplanets) + "\n") for i in range(numplanets): a = input() sys.stderr.write(a + "\n") self.planets.append(Planet(a,i)) self.ai = Ai(self.planets) while(True): self.readInput() self.play()
def test2(ply): player_x = Player("x") player_y = Player("y") king_x = Piece(player_x, "K", 3, 5) rook_x = Piece(player_x, "R", 5, 7) king_y = Piece(player_y, "K", 4, 3) player_x.add_piece(rook_x) player_x.add_piece(king_x) player_y.add_piece(king_y) b = Board(player_x, player_y) b.display() ai = Ai(ply) for i in range(35): ai.move(b, player_x) b.display() ai.move(b, player_y) b.display() # row, col = input('Row Col:').split() # b.player_move(player_y, king_y, row, col) # b.display() # ai.move(b, player_x) # b.display() # b.player_move(player_y, 'K', 5, 5) # ai.create_tree(b, player_x) # ai.move(b, player_x) # b.display() # ai.create_tree(b, player_y) # ai.display_tree(ai.root_node) # print(ai.value(b)) # ai.bfs() print(ai.number_of_states)
class play(object): def __init__(self): self.planets = [] self.ai = None def run(self): numplanets = int(input()) sys.stderr.write("numplanets: " + str(numplanets) + "\n") for i in range(numplanets): a = input() sys.stderr.write(a + "\n") self.planets.append(Planet(a,i)) self.ai = Ai(self.planets) while(True): self.readInput() self.play() def readInput(self): print("STATUS") while(True): msg = input().split() if msg[0] == "PLANETS": msg = msg[1:] for i in range(len(self.planets)): self.planets[i].ships = float(msg[i*2]) self.planets[i].owner = int(msg[i*2+1]) self.ai.refresh() return elif msg[0] == "SEND": self.ai.addFlight(int(msg[1]), int(msg[2]), int(msg[3]), int(msg[4])) def play(self): # self.ai.invade(self.ai.mostProfitableNotOwn()) self.ai.invadeGoodPlanets()
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)
def register_ai(self, id): return Ai(id)
class Car(pygame.sprite.Sprite): 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) def __del__(self): self.__track.space.remove(self.__body, self.__shape) def _update_sensors(self): self.__sensor_data = {} self.__scan_intersections.clear() for scan_point in self.__scan_area: segment_info = self.__track.space.segment_query_first( self.pos, tuple(map(sum, zip(self.pos, scan_point))), 1, self.__filter) if segment_info: self.__scan_intersections.append(segment_info.point) else: self.reset() return self.__scan_intersections.rotate(1 + round( min(self.__scan_angles, key=lambda x: abs(x - (math.degrees(self.angle) % 360))) / (360 / self.__scan_density))) for angle, intersection in zip(self.__scan_angles, self.__scan_intersections): self.__sensor_data[angle] = intersection.get_distance(self.pos) def update(self): self.enable_collision(self.__track.collision) self.__image = pygame.transform.rotate(self.__base_image, -math.degrees(self.angle)) self._update_sensors() if pygame.key.get_pressed()[K_d]: if self.__sensor_data: self.__track.window.message( "{:.0f}".format(self.__sensor_data[0]), (1000, 200), "red") self.__track.window.message( "{:.0f}".format(self.__sensor_data[48]), (1100, 200), "green") self.__track.window.message( "{:.0f}".format(self.__sensor_data[312]), (1200, 200), "orange") for i, intersection in enumerate(self.__scan_intersections): if i == 0: pygame.draw.line(self.__track.screen, Color("red"), self.pos, intersection, 5) continue if i == 48 / (360 / self.__scan_density): pygame.draw.line(self.__track.screen, Color("green"), self.pos, intersection, 5) continue if i == 312 / (360 / self.__scan_density): pygame.draw.line(self.__track.screen, Color("orange"), self.pos, intersection, 5) continue pygame.draw.line(self.__track.screen, Color("black"), self.pos, intersection, 1) self.__track.screen.blit(self.__image, self.__image.get_rect(center=self.pos)) def drive(self): if self.__ai.enabled and self.__sensor_data: self.__ai.input(self.__sensor_data) self.__ai.process() steer, accelerate = self.__ai.output() self.__body.apply_force_at_local_point((0, steer), (0, 0)) self.__body.angular_velocity = steer / 250 self.__body.apply_force_at_local_point((accelerate, 0), (0, 0)) def turn_left(self): self.__body.apply_force_at_local_point((0, -500), (0, 0)) self.__body.angular_velocity = -2 def turn_right(self): self.__body.apply_force_at_local_point((0, 500), (0, 0)) self.__body.angular_velocity = 2 def accelerate(self): self.__body.apply_force_at_local_point((2000, 0), (0, 0)) def reverse(self): self.__body.apply_force_at_local_point((-2000, 0), (0, 0)) def reset(self): self.__body.position = self.__track.starting_pos self.__body.angle = math.radians(self.__track.starting_angle) self.__body.velocity = (0.0, 0.0) self.__ai.reset() def enable_collision(self, enable): if enable == self.__shape.sensor: if enable: self.__shape.sensor = False self.__filter = pymunk.ShapeFilter( mask=pymunk.ShapeFilter.ALL_MASKS ^ 0x1) self.__shape.filter = pymunk.ShapeFilter(categories=0x1) else: self.__shape.sensor = True self.__filter = pymunk.ShapeFilter( mask=pymunk.ShapeFilter.ALL_MASKS) self.__shape.filter = pymunk.ShapeFilter() def toggle_ai(self): self.__ai.enabled = not self.__ai.enabled @property def ai_enabled(self): return self.__ai.enabled @property def pos(self): return self.__body.position @property def angle(self): return self.__body.angle @property def velocity(self): return self.__body.velocity
from Ai import Ai ai = Ai() ai.load_classifier()
def main(): # Setup the game board board = [] for i in range(0, 3): board.append(["-", "-", "-"]) # Magic square to hold the values of each tile # Used to determine a winner magic_square = [[8, 1, 6], [3, 5, 7], [4, 9, 2]] # Used to count the number of moves taken to check for a draw num_moves = 0 # Prompt the user to see whether he/she would like to play the computer or not print "\nWelcome to TicTacToe" print_board(board) game_choice = raw_input("\nWould you like to play with another 'player', or the 'computer?' ").lower() # If the input was of incorrect format, ask the user again until he/she gets it right while game_choice != "player" and game_choice != "computer": print "Please enter either 'player' or 'computer'" game_choice = raw_input("Would you like to play with another player, or the computer? ") player_one = "X" player_two = "O" player_one_turn = True if game_choice == "player": print "Playing PvP" print "Player 1: " + player_one print "Player 2: " + player_two else: print "Playing against the computer" print "Player 1 (Human): " + player_one print "Player 2 (Computer): " + player_two print_board(board) # If there is no winner, then check for a draw, if no draw, then make a move. while not Game.winner(board, magic_square): if num_moves != 9: if player_one_turn: print "Player 1's turn" make_move(board, player_one) player_one_turn = False else: print "Player 2's turn" if game_choice == "player": make_move(board, player_two) else: Ai.make_move(board, player_two, player_one, False) player_one_turn = True print_board(board) else: print "It's a Draw!" sys.exit() num_moves += 1
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
def interactive(ply): g = Game() mode, end = g.game_type() end = int(end) if mode: # mode is true means new game player_x = Player("x") player_y = Player("y") b = Board(player_x, player_y) ai = Ai(ply) remain = ["PlayerX King", "PlayerX Rook", "PlayerY King"] g.ask_piece(b, player_x, player_y, remain) b.display() File.prompt("Who am I, PlayerX or PlayerY?") localPlayer = input("Player [x/y]: ") if re.match(r"[Xx]", localPlayer): localPlayer = "x" else: localPlayer = "y" # if local player is playerX, PlayerX is our ai moves # PlayerY is opponents moves inputted by us if localPlayer == "x": for i in range(0, end): # b.ai_move(player_x) ai.move(b, player_x) b.display() File.debug(ai.value(b)) File.debug(ai.number_of_states) ai.opponent_move(player_y, b) b.display() else: for i in range(0, end): ai.opponent_move(player_x, b) b.display() # b.ai_move(player_y) ai.move(b, player_y) b.display() File.debug(ai.value(b)) File.debug(ai.number_of_states) else: player_x = Player("x") player_y = Player("y") b = Board(player_x, player_y) File.test_file(b, g, player_x, player_y) ai = Ai(ply) # AI random moves test: for i in range(0, end): ai.move(b, player_x) b.display() File.debug(ai.value(b)) File.debug(ai.number_of_states) ai.move(b, player_y) b.display() File.debug(ai.value(b)) File.debug(ai.number_of_states)
class TestBoard: 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() #self.createPiece(Pawn,3,3,"black") #self.createPiece(Bishop,5,5,"white") #self.createPiece(Knight,2,2,"white") #self.createPiece(Piece,3,2,"white") #self.createPiece(King,2,7,"white") def getKing(self): for i in self.squares: for j in i: if j.piece != None: j.piece.getKing() def createPiece(self, Type, x, y, colour): a = Type(x, y, colour, self) self.squares[x][y].setPiece(a) return a def removePiece(self, x, y): self.squares[x][y].setPiece(None) def movePiece(self, x1, y1, x2, y2): self.squares[x2][y2].piece = self.squares[x1][y1].piece self.squares[x1][y1].piece = None if self.squares[x2][y2].piece != None: self.squares[x2][y2].piece.setPos(x2, y2) def startMoving(self, x, y): print("start") self.moving = True self.pieceMoving = (x, y) self.squares[x][y].highlight() for i in range(len(self.squares)): for j in range(len(self.squares[0])): if self.squares[x][y].piece.canMove(i, j): self.squares[i][j].highlight() def stopMoving(self): print("stop") self.moving = False self.pieceMoving = None self.removeHighlights() def pieces(self, colour=None): a = [] for i in self.squares: for j in i: if j.piece != None: if colour == None or j.piece.colour == colour: a.append(j.piece) return a def update(self): for i in self.squares: for j in i: j.update() def removeHighlights(self): for i in self.squares: for j in i: j.unHighlight() def changeTurn(self): self.whiteTurn = not self.whiteTurn self.master.title(["White Turn", "Black Turn"][int(not self.whiteTurn)]) if self.whiteTurn: white = False for i in self.pieces("white"): if i.hasMove(): white = True break if not white: if self.wKing.underAttack(): self.master.title("Black Wins") else: self.master.title("Stalemate") else: black = False for i in self.pieces("black"): if i.hasMove(): black = True break if not black: if self.bKing.underAttack(): self.master.title("White Wins") else: self.master.title("Stalemate") if not self.whiteTurn and self.aiOn: a = self.ai.evalMove() self.movePiece(*a) self.changeTurn()