Exemplo n.º 1
0
 def add_node_to_network(self, game_board: GameBoard,
                         chosen_node: [str, str]):
     self.__network.add_node(game_board.get_nodes().get(chosen_node[0]))
     edge = game_board.get_edges().get(chosen_node[0] + chosen_node[1])
     if edge is None:
         edge = game_board.get_edges().get(chosen_node[1] + chosen_node[0])
     try:
         self.__network.add_edge(edge[0], edge[1], weight=edge[2])
     except TypeError:
         print("Well done.....")
Exemplo n.º 2
0
 def add_node_to_network(self, game_board: GameBoard,
                         chosen_node: [str, str]):
     self._network.add_node(game_board.get_nodes().get(chosen_node[0]))
     edge = game_board.get_edges().get(chosen_node[0] + chosen_node[1])
     if edge is None:
         edge = game_board.get_edges().get(chosen_node[1] + chosen_node[0])
     try:
         game_board.get_map()[edge[0]][edge[1]]['weight'] = 0
         self._network.add_edge(edge[0], edge[1], weight=0)
     except TypeError as err:
         print("error: {0}".format(err))
Exemplo n.º 3
0
	def choose_start_pos(self, game_board: GameBoard) -> str:
		group_weights = []
		sublists = self._generate_sublists()
		rem = 0
		while rem < len(sublists):
			if len(sublists[rem]) != self._x:
				sublists.remove(sublists[rem])
				rem -= 1
			rem += 1
		for sublist in sublists:
			path_lengths = []
			for j in range(0, len(sublist)):
				for k in range(j + 1, len(sublist)):
					path_lengths.append(networkx.shortest_path_length(game_board.get_map(), sublist[j], sublist[k]))
			while len(path_lengths) >= self._x:
				path_lengths.remove(max(path_lengths))
			group_weights.append([sublist, sum(path_lengths)])
		closest_group = group_weights[0]
		dist = group_weights[0][1]
		for sublist in range(0, len(group_weights)):
			if group_weights[sublist][1] < dist:
				closest_group = group_weights[sublist]
				dist = group_weights[sublist][1]
		start_city = closest_group[0][0]
		self.add_start_node(start_city)
		return start_city.get_id()
Exemplo n.º 4
0
	def get_next_path(self, game_board: GameBoard):
		if self.network_merge(game_board):
			self._sort_cities(game_board)
		if not self.has_won():
			paths = networkx.single_source_dijkstra(game_board.get_map(),
			                        self._target_cities[0], weight='weight')
			paths = self.collapse_paths(paths)
			possible_paths = []
			for path in paths:
				if (path[1][len(path[1]) - 1] in self._network.nodes) and path[2] != 0:
					possible_paths.append(path)
			i = 0
			while i < len(possible_paths):
				inter = len(set(possible_paths[i][1]) & set(self._network.nodes))
				if inter > 1 and len(possible_paths) > 1:
					possible_paths.remove(possible_paths[i])
					i -= 1
				i += 1
			sorted_paths = sorted(possible_paths, key=lambda tup: tup[2])
			if len(sorted_paths) <= 0:
				return self.get_next_path(game_board)
			optimal_path = sorted_paths[0]
			optimal_path[1].reverse()
			return optimal_path[1]
		else:
			return 'w'
Exemplo n.º 5
0
	def _sort_cities(self, game_board: GameBoard):
		lengths = {}
		start_city = self._target_cities[0]
		for i in range(0, len(self._target_cities)):
			lengths[self._target_cities[i]] =\
				networkx.shortest_path_length(game_board.get_map(),
				                    start_city, self._target_cities[i])
		lengths = dict(sorted(lengths.items(), key=lambda item: item[1]))
		self._target_cities = list(lengths.keys())
Exemplo n.º 6
0
 def print_cities_in_network(self, game_board: GameBoard):
     groups = NetworkToPoints.get_city_points(self.__network)
     for group in groups:
         if group:
             for point in group:
                 city = game_board.get_cities().get(
                     str(point[0]).rjust(2, "0") +
                     str(point[1]).rjust(2, "0"))
                 print(city.get_name() + ": " +
                       str(point[0]).rjust(2, "0") + "," +
                       str(point[1]).rjust(2, "0"))
Exemplo n.º 7
0
 def __init__(self,
              players: [],
              map_filepath: str,
              debug_level: int = 0,
              draw: int = 0):
     self.__players = players
     random.shuffle(self.__players)
     self._map_filepath = map_filepath
     self.__board = GameBoard(self.__players, self._map_filepath)
     self.draw = draw
     if self.draw:
         self.__drawer = BasicNetworkDrawer(self.__board.get_map(),
                                            self.__board.get_cities())
         self.__win = psychopy.visual.Window(size=[1280, 720],
                                             units="pix",
                                             fullscr=False,
                                             color=[0.9, 0.9, 0.9])
     self.dl = debug_level
     self.turn_count = 0
     self.MAX_TURNS = 50
Exemplo n.º 8
0
	def network_merge(self, game_board: GameBoard):
		ret = False
		for player in game_board.get_players():
			if player != self:
				for node in player.get_network().nodes:
					if node in self._network:
						self._network = networkx.compose(self._network,
						                                 player.get_network())
						ret = True
						break
		return ret
Exemplo n.º 9
0
	def get_next_path(self, game_board: GameBoard):
		paths = networkx.single_source_dijkstra(game_board.get_map(),
		                        self._target_cities[0], weight='weight')
		self._target_cities.remove(self._target_cities[0])
		paths = self.collapse_paths(paths)
		possible_paths = []
		for path in paths:
			if path[1][len(path[1]) - 1] in self._network:
				possible_paths.append(path)
		sorted_paths = sorted(possible_paths, key=lambda tup: tup[2])
		sorted_paths[0][1].reverse()
		return sorted_paths[0][1]
Exemplo n.º 10
0
	def get_next_path(self, game_board: GameBoard):
		if self.network_merge(game_board):
			self._sort_cities(game_board)
		if self._connected_players < self._players_to_connect:
			unconnected_players = []
			self._connected_players = 0
			for player in game_board.get_players():
				if not networkx.is_isomorphic(self._network, player.get_network()):
					unconnected_players.append(player)
				else:
					self._connected_players += 1
			shortest_path = [None, None, 0]
			for player in unconnected_players:
				player_nodes = player.get_network().nodes
				for node in player_nodes:
					player_paths = networkx.single_source_dijkstra(game_board.get_map(), node, weight='weight')
					player_paths = self.collapse_paths(player_paths)
					for path in player_paths:
						if path[1][len(path[1]) - 1] in self._network:
							if path[2] < shortest_path[2]:
								shortest_path = path
			if shortest_path[2] > 0:
				return shortest_path
		return ClosestFirst.get_next_path(self, game_board)
Exemplo n.º 11
0
 def add_start_node(self, game_board: GameBoard, chosen_node: str):
     self.__network.add_node(game_board.get_nodes().get(chosen_node))
Exemplo n.º 12
0
class TransEuropa:
    def __init__(self,
                 players: [],
                 map_filepath: str,
                 debug_level: int = 0,
                 draw: int = 0):
        self.__players = players
        random.shuffle(self.__players)
        self._map_filepath = map_filepath
        self.__board = GameBoard(self.__players, self._map_filepath)
        self.draw = draw
        if self.draw:
            self.__drawer = BasicNetworkDrawer(self.__board.get_map(),
                                               self.__board.get_cities())
            self.__win = psychopy.visual.Window(size=[1280, 720],
                                                units="pix",
                                                fullscr=False,
                                                color=[0.9, 0.9, 0.9])
        self.dl = debug_level
        self.turn_count = 0
        self.MAX_TURNS = 50

    def reset_game(self):
        self.__board = GameBoard(self.__players, self._map_filepath)
        self.turn_count = 0
        for player in self.__players:
            player.reset()

    def play_game(self):
        for player in self.__board.get_players():
            player.choose_start_pos(self.__board)
        game_won = False
        self.turn_count = 0
        while not game_won and self.turn_count < self.MAX_TURNS:
            self.turn_count += 1
            if self.dl >= 2:
                print("Turn " + str(self.turn_count) + ":")
            if self.turn_count >= self.MAX_TURNS:
                print("MAX TURNS EXCEEDED")
            for player in self.__board.get_players():
                if not player.has_won() and not game_won:
                    valid = 0
                    while valid < 2 and not player.has_won():
                        co_ords = player.make_move(self.__board)
                        if co_ords == 'w':
                            game_won = True
                            break
                        else:
                            if self.__board.is_valid_move(player, co_ords):
                                player.add_node_to_network(
                                    self.__board, co_ords)
                                valid += 1
                else:
                    game_won = True
                    break
                if self.draw >= 2:
                    self.draw_board()
        self.end_game(self.turn_count)

    def end_game(self, turns):
        for player in self.__players:
            if player.has_won():
                if self.dl:
                    print(player.name + " Has Won!!")
        if self.dl:
            print("Winning Turn: " + str(turns))
        if self.draw:
            self.draw_board()
        if self.draw:
            self.__win.close()

    def generate_player_scores(self) -> []:
        for player in self.__players:
            # protected access allowed in this case as this is driver code, it is protected to prevent access by other players
            unconnected_cities = player._cities not in player.get_network()
            for city in unconnected_cities:
                paths = networkx.single_source_dijkstra(self.__board,
                                                        city,
                                                        weight='weight')
                paths = self.collapse_paths(paths, player)
                # TODO

    @staticmethod
    def collapse_paths(found_paths, player):
        distances = found_paths[0]
        paths = found_paths[1]
        collapsed = []
        for path in paths:
            if path[len(path) - 1] in player.get_network():
                collapsed.append((path, paths.get(path), distances.get(path)))
        return collapsed

    def draw_board(self):
        self.__drawer.draw_edges(self.__win)
        self.__drawer.draw_nodes(self.__win)
        self.__drawer.draw_cities(self.__win)
        self.__win.flip()

    def get_players(self) -> []:
        return self.__players
Exemplo n.º 13
0
 def reset_game(self):
     self.__board = GameBoard(self.__players, self._map_filepath)
     self.turn_count = 0
     for player in self.__players:
         player.reset()