def __init__(self, filename1: str, filename2: str, max_time: float,
                 max_turn: int, map_args: dict):
        """初始化一局游戏,具体规则请参见文档(文档组加油!

        Args:
            filename1 (str): 玩家1的脚本
            filename2 (str): 玩家2的脚本目录
            max_time (float): 单步的最大思考时间
            max_turn (int): 允许进行的最大回合数
            map_args (dict): 包含地图配置的字典
        """
        self.__max_time = max_time
        self.__map = GameMap(map_args)
        self.__winner = None
        self.__game_end = False
        self.__game_end_reason = "游戏未结束。"
        self.__max_turn = max_turn
        self.__history_map = {
            "map": self.__map.export_map_as_dic(),
            "player_name": {
                0: filename1,
                1: filename2,
                -1: "No player(draw)",
                None: "玩家函数错误"
            },
            "result": "游戏还没结束。",
            "history": [self.__map.update([], [])]
        }  #开局的地图也要记录

        try:
            exec(
                "from AIs.{} import player_func; self.player_func1 = player_func"
                .format(filename1))
        except:
            # if function is not found, the opposite wins
            self.__winner = 1
            self.__game_end = True

        try:
            exec(
                "from AIs.{} import player_func; self.player_func2 = player_func"
                .format(filename2))
        except:
            if self.__game_end:
                # both players fail to write a correct function, no one wins
                self.__winner = None
            else:
                self.__winner = 0
                self.__game_end = True

        history = self.get_history()
        filename = os.path.join(os.path.dirname(__file__), 'debug.json')
        with open(filename, 'w') as f:
            f.write('')
            json.dump(history, f)
        self.web = SeleniumClass()
        self.web.openJson('debug.json')
Exemple #2
0
 def __init__(self):
     self.tile_size = 64
     self.map_dim = 16
     self.map_size = self.tile_size * self.map_dim
     self.screen = pygame.display.set_mode((self.map_size, self.map_size))
     self.sheet = SpriteSheet("allSprites_default.png",
                              "allSprites_default.xml")
     self.map = GameMap("map.txt", self.map_dim, self.tile_size)
     self.players = []
     self.init_tanks()
Exemple #3
0
    def __init__(self, Player1, Player2, parent=None):
        super(Game, self).__init__(parent)
        self.setFixedSize(645, 415)
        self.setWindowTitle("King of Siam")
        self.setStyleSheet(
            "background-color: #2d3436; color: white; font-size: 18px;")
        self.setWindowIcon(QtGui.QIcon('./content/boulder.png'))
        self.title = QtWidgets.QLabel(self)

        self.title.setText("King of Siam")
        self.title.setStyleSheet(
            "font-size: 41px; font-family: Bradley Hand ITC; font-weight: bold; color: #ee5253;"
        )
        self.title.setGeometry(375, 10, 300, 50)

        self.namePlayer1 = Player1
        self.namePlayer2 = Player2

        # Game setup
        self.g = GameMap()
        if self.g.playerTurn == 'Elephant':
            self.currentPlayer1 = True
        else:
            self.currentPlayer1 = False
        self.ndir = np.array([1, 0])
        self.ndirDeg = 270

        self.startpoint = True
        self.selectValid = False

        # Showing the gamemap
        label = QtWidgets.QLabel(self)
        Pixmap = QtGui.QPixmap('./content/gamemap.png')
        label.setPixmap(Pixmap)
        label.setGeometry(10, 5, 360, 360)

        self.setTiles()
        self.refresh()

        # Creating the buttons
        self.cancelButton()
        self.deleteButton()
        self.validButton()
        self.playerBoard()
        self.turnWidget()
        self.saveWidget()

        self.show()
 def __init__(self, map_height=12, map_width=12, num_of_cheese=3):
     self.map_height = map_height
     self.map_width = map_width
     self.num_of_cheese = num_of_cheese
     self.visited_cheese_pos = []
     self.visited_mouse_pos = []
     self.visited_cat_pos = []
     self.game_states = []
     self.mouse_path = []
     self.mouse_initial_pos = []
     self.random_coordinates = []
     self.generate_resources()
     self.cheese_pos.sort(key=self.compare_by_distance)
     self.game_state = GameState.BasicGameState(self.mouse.current_pos,
                                                self.cat.current_pos,
                                                self.cheese_pos)
     self.game_states.append(self.game_state)
     self.game_map = GameMap(self.game_state, map_height, map_width)
     self.canvas = Canvas(self.game_map)
Exemple #5
0
    def __init__(self, controller):
        self._window = tk.Tk()
        self._ctrler = controller
        # ustawianie parametrów okna
        self._window.title("Saper")
        self._window.iconbitmap("icon.ico")
        x = (self._window.winfo_screenwidth() / 4)
        y = (self._window.winfo_screenheight() / 4)
        self._window.geometry('+%d+%d' % (x, y))

        self._window.bind("<Key>", lambda event: controller.keyPressed(
            event.char))  # wykrywanie wciskanych przycisków

        # view1
        self.menu = Menu(self._window, controller)
        # view2
        self.map = GameMap(self._window, controller)

        self.map.timer()
Exemple #6
0
    def __init__(self, filename1: str, filename2: str, map_args: dict):
        """初始化一局游戏,具体规则请参见文档(文档组加油!

        Args:
            filename1 (str): 玩家1的脚本
            filename2 (str): 玩家2的脚本目录
            map_args (dict): 包含地图配置的字典
        """
        self.__max_time = config.MAX_TIME
        self.__map = GameMap(map_args)
        self.__winner = None
        self.__game_end = False
        self.__game_end_reason = "游戏未结束。"
        self.__max_turn = config.MAX_TURN
        self.__player = []
        self.__history_map = {
            "map": self.__map.export_map_as_dic(),
            "player_name": {0: filename1, 1: filename2, -1: "No player(draw)", None: "玩家函数错误" },
            "result": "游戏还没结束。",
            "history": [self.__map.update([], [])]
        }#开局的地图也要记录

        try:
            exec("""from AIs.{} import player_class as player_class1
self.addPlayer(player_class1(0))""".format(filename1))
        except:
            # if function is not found, the opposite wins
            self.__winner = 1
            self.__game_end = True

        try:
            exec("""from AIs.{} import player_class as player_class2
self.addPlayer(player_class2(1))""".format(filename2))
        except:
            if self.__game_end:
                # both players fail to write a correct function, no one wins
                self.__winner = None
            else:
                self.__winner = 0
                self.__game_end = True
    def __init__(self,
                 size,
                 init_fruits=None,
                 init_pos=None,
                 draw_settings=None,
                 default_direction=Direction.LEFT):
        self.size = size

        self.game_controller = GameController(default_direction)

        if init_fruits is None:
            init_fruits = get_init_fruits(size)

        if init_pos is None:
            init_pos = get_init_pos(size)

        self.game_map = GameMap(size, init_fruits, init_pos)

        if draw_settings is None:
            draw_settings = DrawGameSettings()

        self.game_drawer = GameDrawer(self.game_map, draw_settings)
Exemple #8
0
    def initGameMap(self, entityList: [GameEntity] = None):

        gm = GameMap(self.size)

        spotsLeft = [pos for pos in gm.data if gm.data[pos] == None]

        random.shuffle(spotsLeft)

        if entityList == None:
            entityList = []
            for t in NUM_TYPES:
                for n in range(NUM_TYPES[t]):
                    entityList.append(GameEntity(t, KillAI()))

        if len(spotsLeft) < len(entityList):
            raise "Not enough spots for entites"

        spotsLeft = spotsLeft[:len(entityList)]

        for x in zip(spotsLeft, entityList):
            gm.data[x[0]] = x[1]

        return gm
Exemple #9
0
    def __init__(self, filename1: str, filename2: str, max_time: float,
                 max_turn: int, map_args: dict):
        """
        player's python file should include a function which looks like

        player_func(map: GameMap) -> [Tuple[int, int, float].....]

        when illegal moves are given, player would be considered to make no moves

        :param filename1: player 1's python file
        :param filename2: player 2's python file
        :param max_time: time limitation in seconds
        :param max_turn: maximum turn numbers
        :param map_args: game map's initialization parameters
        """
        self.__max_time = max_time
        self.__map = GameMap(map_args)
        self.__winner = None
        self.__game_end = False
        self.__max_turn = max_turn
        self.__history_map = [self.__map.export_as_dic([], [])]  #开局的地图也要记录
        try:
            self.player_func1 = __import__(filename1).player_func
        except:
            # if function is not found, the opposite wins
            self.__winner = 'player2'
            self.__game_end = True

        try:
            self.player_func2 = __import__(filename2).player_func
        except:
            if self.__game_end:
                # both players fail to write a correct function, no one wins
                self.__winner = None
            else:
                self.__winner = 'player1'
                self.__game_end = True
    except:
        print('Invalid port')
        sys.exit()
    if not 1025 <= port <= 65535:
        print('Invalid port')
        sys.exit()

    socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        socket.connect(('localhost', port))
    except ConnectionRefusedError:
         print('Connection refused, check host is running')
         sys.exit()

    player = Player()
    game_map = GameMap(player)
    goals = Goals(game_map)
    while True:
        data = receive_socket_data(socket)
        if not data:
            socket.close()
            sys.exit()
        #print_view(data)
        game_map.update_map(data)
        #game_map.print_map()

        #action = get_action()
        action = goals.find_next_goal()
        if not action:
            action = goals.extended_searches()
        player.player_action(action)
Exemple #11
0
 def __init__(self):
     self.game = Game()
     self.gameMap = GameMap()
Exemple #12
0
def draw_food(map_len, screen, food_pos, map_length):
    food_color = (0, 166, 244)
    pygame.draw.rect(screen, food_color,
                     (food_pos[1] * map_length / map_len + 1, food_pos[0] * map_length / map_len + 1,
                      map_length / map_len, map_length / map_len))


if len(sys.argv) > 0:
    # x = ReadFile(sys.argv[1], "map-out.txt")
    x = ReadFile("test.txt", "map-out.txt")
    t = x.read_file()

    food_fen = FoodGenerator()

    for m in range(0,11):
        init_state = GameMap(t, None, [0, 2], [[0, 2], [0, 1], [0, 0]], True)
        init_state_diagonal = GameMap(t, None, [0, 2], [[0, 2], [0, 1], [0, 0]], False)
        init_state.set_food_position(food_fen.generate_food(init_state.game_map))
        init_state_diagonal.set_food_position(food_fen.generate_food(init_state.game_map))

        movement_list_manhattan = []
        movement_list_diagonal = []
        for i in range(0, 30):
            # print "Score=", i
            mySearch = AStarSearch(init_state)
            diagonalSearch = AStarSearch(init_state_diagonal)
            diagonalSearch.start_search(False)
            mySearch.start_search(True)
            answer = mySearch.get_answer()
            answer_diagonal = diagonalSearch.get_answer()
            movement_list_manhattan.append(len(answer) - 1)
Exemple #13
0
 def start_search(self, which_h):
     self.open_list.append(self.init_state)
     main_node = None
     while len(self.open_list) > 0:
         # print "openList Size =", len(self.open_list)
         main_node = self.open_list.pop(0)
         # print "pop node :"
         # main_node.print_matrix()
         # print "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
         self.close_list.append(main_node)
         if main_node.heuristic == 0:
             # print "exist answer"
             self.print_answer(main_node)
             break
         # print "================================================"
         # print "bottom:"
         bottom_node = GameMap(main_node.get_matrix(), main_node,
                               main_node.head, main_node.snake_position,
                               which_h)
         bottom_node.snake_move_bottom()
         # bottom_node.print_matrix()
         if not self.exist_in_close(bottom_node):
             bottom_node.g = main_node.g + 1
             bottom_node.f = max(bottom_node.f,
                                 bottom_node.g + bottom_node.heuristic)
             # print "f=", bottom_node.f
             self.update_open_list(bottom_node)
         # print "================================================"
         # print "left:"
         # print "snake_pos main", main_node.snake_position
         left_node = GameMap(main_node.get_matrix(), main_node,
                             main_node.head, main_node.snake_position,
                             which_h)
         left_node.snake_move_left()
         # left_node.print_matrix()
         if not self.exist_in_close(left_node):
             left_node.g = main_node.g + 1
             left_node.f = max(left_node.f,
                               left_node.g + left_node.heuristic)
             # print "f=", left_node.f
             self.update_open_list(left_node)
         # print "================================================"
         # print "right:"
         right_node = GameMap(main_node.get_matrix(), main_node,
                              main_node.head, main_node.snake_position,
                              which_h)
         right_node.snake_move_right()
         # right_node.print_matrix()
         if not self.exist_in_close(right_node):
             right_node.g = main_node.g + 1
             right_node.f = max(right_node.f,
                                right_node.g + right_node.heuristic)
             # print "f=", right_node.f
             self.update_open_list(right_node)
         # print "================================================"
         # print "top:"
         top_node = GameMap(main_node.get_matrix(), main_node,
                            main_node.head, main_node.snake_position,
                            which_h)
         top_node.snake_move_top()
         # top_node.print_matrix()
         if not self.exist_in_close(top_node):
             top_node.g = main_node.g + 1
             top_node.f = max(top_node.f, top_node.g + top_node.heuristic)
             # print "f=", top_node.f
             self.update_open_list(top_node)
Exemple #14
0
    return actions[action](gm, pos)


def removeDead(gm: GameMap):
    for pos in gm.data:
        if gm.data[pos] != None and gm.data[pos].health <= 0:
            gm.data[pos] = None


if __name__ == "__main__":

    import GameEntity

    print("Move right test")
    gm = GameMap(3)

    gm.data[(1, 1)] = "o"

    gm.printMap()

    execute(gm, (1, 1), MOVE_RIGHT)
    print()

    gm.printMap()
    print("\n")

    print("Move down test")
    gm = GameMap(3)

    gm.data[(1, 1)] = "o"
Exemple #15
0
    def displayGame(self, timePerTurn: float = 0.5):
        i = 1
        for state in self.getAllStates():
            utils.clearScreen()
            state.printMap()
            print("%d / %d" % (i, len(self.actions)+1))
            i += 1
            time.sleep(timePerTurn)

if __name__ == "__main__":

    import GameEntity
    from GameConstants import *

    gm = GameMap(5)

    gm.data[(2, 2)] = GameEntity.GameEntity(TYPE_MALE)

    gh = GameHistory(gm)

    gh.actions.append(((2, 2), GameMove.MOVE_UP))
    gh.actions.append(((2, 1), GameMove.MOVE_UP))

    for state in gh.getAllStates():
        state.printMap()
        print()
    
    for i in range(len(gh.actions)+1):
        gh.calcState(i).printMap()
        print()
Exemple #16
0
class Player:
    logged_in = False
    gm = GameMap()
    tn = None
    z = 0
    x = 0
    y = 0
    details = {"username": "******", "password": "******"}

    def __print_response(self):
        response = self.tn.read_until(b"\r\n\r\n> ", timeout=.1)
        print("---")
        for i, line in enumerate(response.decode('ascii').split("\n")):
            print(i, line)

    def get_detail(self, detail):
        return f"{self.details[detail]}\n".encode('ascii')

    def login(self):
        line = self.tn.read_very_eager()
        line = line.decode('ascii')
        # if line != "":
        #     print(line.strip())
        if not self.logged_in:
            if "what name do you wish to be known?" in line:
                self.tn.write(self.get_detail("username"))

            if "Password:"******"password"))
            if "PRESS RETURN" in line:
                self.tn.write("\n".encode('ascii'))
            if "Make your choice:" in line:
                self.tn.write("1\n".encode('ascii'))
                self.logged_in = True
            if "Reconnecting." in line:
                self.logged_in = True

    def move_west(self):
        self.tn.write('w\n'.encode('ascii'))
        self.x -= 1

    def move_east(self):
        self.tn.write('e\n'.encode('ascii'))
        self.x += 1

    def move_south(self):
        self.tn.write('s\n'.encode('ascii'))
        self.y -= 1

    def move_north(self):
        self.tn.write('n\n'.encode('ascii'))
        self.y += 1

    def move_up(self):
        self.tn.write('u\n'.encode('ascii'))
        self.z += 1

    def move_down(self):
        self.tn.write('d\n'.encode('ascii'))
        self.z -= 1

    def get_room_info(self):
        self.tn.write('l\n'.encode('ascii'))
        response = self.tn.read_until(b"\r\n\r\n> ", timeout=.1)
        self.gm.current = Tile(
            response.decode('ascii').split("\n")[0], self.z, self.x, self.y)
        # for i, line in enumerate(response.decode('ascii').split("\n")):
        #     if i == 0:
        #         if self.gm.current is None:
        #             self.gm.current = Tile(line)
        #             break

    def get_tile_in_direction(self, direction):
        temp = None
        success = True
        if direction == "n":
            self.move_north()
        elif direction == "e":
            self.move_east()
        elif direction == "s":
            self.move_south()
        elif direction == "w":
            self.move_west()
        elif direction == "u":
            self.move_up()
        elif direction == "d":
            self.move_down()
        response = self.tn.read_until(b"\r\n\r\n> ", timeout=.1)
        checkmove = response.decode('ascii').split("\n")[0]
        if "Alas, you cannot" in checkmove:
            success = False
        if success:

            self.tn.write('l\n'.encode('ascii'))
            response = self.tn.read_until(b"\r\n\r\n> ", timeout=.1)
            title = response.decode('ascii').split("\n")[0]
            temp = Tile(title, self.z, self.x, self.y)

            if direction == "n":
                # print("Im trying to move south")
                self.move_south()
            if direction == "e":
                self.move_west()
            if direction == "s":
                self.move_north()
            if direction == "w":
                self.move_east()
            if direction == "u":
                self.move_down()
            if direction == "d":
                self.move_up()
            self.tn.read_until(b"\r\n\r\n> ", timeout=.1)
        return temp

    def check_exits(self):
        exits = {
            "n": None,
            "e": None,
            "s": None,
            "w": None,
            "u": None,
            "d": None
        }
        for k in exits.keys():
            temp = self.get_tile_in_direction(k)
            # print(f"MOVING {k}")
            if temp is not None:
                exits[k] = temp
        self.gm.current.exits = exits
        self.gm.add_tile(self.gm.current, self.z, self.x, self.y)
        self.gm.current = None
Exemple #17
0
 def setUp(self):
     self.m = GameMap()
Exemple #18
0
def initializeGameMap(map_file):
    return GameMap(map_file)
Exemple #19
0
    def set_map(self,
                new_map_name: str,
                one_time_decorations: Optional[List[MapDecoration]] = None,
                respawn_decorations: bool = False,
                init: bool = False) -> None:
        # print('setMap to', new_map_name, flush=True)
        old_map_name = ''
        if not init:
            old_map_name = self.get_map_name()

        # Set light diameter for the new map if there was not an old map or if the new default map
        # diameter is unlimited.  Also update the light diameter for the new map if the default light
        # diameters between the old and new maps are different and either the old map default light
        # diameters was unlimited or the current diameter is less than the default light diameter of the
        # new map.
        new_map_light_diameter = self.game_info.maps[
            new_map_name].light_diameter
        if (not old_map_name or new_map_light_diameter is None or
            (new_map_light_diameter !=
             self.game_info.maps[old_map_name].light_diameter and
             (self.game_info.maps[old_map_name].light_diameter is None or
              (self.hero_party.light_diameter is not None
               and self.hero_party.light_diameter < new_map_light_diameter)))):
            self.hero_party.light_diameter = new_map_light_diameter

        # If changing maps and set to respawn decorations, clear the history of removed decorations
        if respawn_decorations:
            self.removed_decorations_by_map = {}

        map_decorations = self.game_info.maps[
            new_map_name].map_decorations.copy()
        removed_map_decorations: List[MapDecoration] = []
        if one_time_decorations is not None:
            map_decorations += one_time_decorations
        # Prune out decorations where the progress marker conditions are not met
        for decoration in map_decorations[:]:
            if not self.check_progress_markers(
                    decoration.progress_marker,
                    decoration.inverse_progress_marker):
                map_decorations.remove(decoration)
        # Prune out previously removed decorations
        if new_map_name in self.removed_decorations_by_map:
            for decoration in self.removed_decorations_by_map[new_map_name]:
                if decoration in map_decorations:
                    map_decorations.remove(decoration)
                    if decoration.type is not None and decoration.type.removed_image is not None:
                        removed_map_decorations.append(decoration)

        if old_map_name == new_map_name:
            # If loading up the same map, should retain the NPC positions
            npcs = self.game_map.npcs

            # Remove any current NPCs which should be missing
            for npc_char in npcs[:]:
                if not self.check_progress_markers(
                        npc_char.npc_info.progress_marker,
                        npc_char.npc_info.inverse_progress_marker):
                    npcs.remove(npc_char)

            # Add missing NPCs
            for npc in self.game_info.maps[new_map_name].npcs:
                if not self.check_progress_markers(
                        npc.progress_marker, npc.inverse_progress_marker):
                    continue
                is_missing = True
                for npc_char in npcs:
                    if npc_char.npc_info is not None and npc == npc_char.npc_info:
                        is_missing = False
                        break
                if is_missing:
                    npcs.append(NpcState(npc))
        else:
            # On a map change load NPCs from scratch
            npcs = []
            for npc in self.game_info.maps[new_map_name].npcs:
                if self.check_progress_markers(npc.progress_marker,
                                               npc.inverse_progress_marker):
                    npcs.append(NpcState(npc))

        self.game_map = GameMap(self, new_map_name, map_decorations,
                                removed_map_decorations, npcs)
Exemple #20
0
import threading, time, socket
from GameMap import GameMap
from Tools import Tools
adminOnline = False
map = GameMap()
nbPlayers = 4
class Server(threading.Thread):


    ver = threading.RLock()


    def __init__(self, clientsocket):
        threading.Thread.__init__(self)
        self.clientsocket = clientsocket
        self.tool = Tools()

    def run(self):

        global adminOnline
        global map
        global nbPlayers

        nbPlayers = nbPlayers - 1
        while True:
            print(">> ")
            r = self.clientsocket.recv(2048)
            r = r.decode()


            print(nbPlayers)