示例#1
0
    def test_play_match(self):
        server = Server()
        server.start(False)

        client1 = Client('localhost', 8081)
        client2 = Client('localhost', 8081)

        client1_moves = [(1, 1), (2, 2), (3, 3)]
        client2_moves = [(3, 1), (3, 2)]

        client1.on_move_required = lambda ct: (client1_moves
                                               if ct else client2_moves).pop(0)
        client1.on_game_over = lambda winner: self.assertTrue(winner)

        client2.on_move_required = lambda ct: (client1_moves
                                               if ct else client2_moves).pop(0)
        client2.on_game_over = lambda winner: self.assertTrue(winner)

        client1.start(False)
        client2.start(False)

        client1.wait()
        client2.wait()

        server.stop()
示例#2
0
    def sign_up(self):
        login, password, secret = [
            x.text()
            for x in [self.edit_login, self.edit_pass, self.edit_secret]
        ]
        if not self.part_checker(login, password, secret):
            return False

        if self.network is False:
            self.network = Client()
        result = self.network.command_send(
            f"sign_up?login={login}&password={password}&secret={secret}"
        ).split('?')

        if len(result) == 1:
            result = result[0]
            self.auth_form = SeeBattle_Auth(self)
            self.auth_form.show()
            self.close()
            self.network.close()
            msg = QMessageBox(self.auth_form)
            msg.setText("You was success registred")
            msg.show()
            return True
        return self.my_errors(result[1])
示例#3
0
 def __init__(self, ip):
     self.ip = ip
     client = Client(ip)
     self.hostname = client.gethostname()
     self.key = Fernet.generate_key()
     client.send(self.hostname + " connected on " + str(date.today()) +
                 " with key: " + str(self.key.decode()))
示例#4
0
 def __init__(self, service_name):
     QObject.__init__(self)
     self.is_connecting = False
     self.is_connected = False
     self.service_name = service_name
     self.connector = SafeConnector()
     self.c = Client()
示例#5
0
 def alert_patch(self):
     try:
         self.client = Client()
         self.client.alert_patch()
         self.restore_all_game_files()
         self.start_game()
     except Exception as e:
         handle_error(e)
示例#6
0
 def add_client(self, player_class, **kwargs):
     name = player_class.__name__
     client = Client(player_class, manager=self, **kwargs)
     result = client.open()
     if result:
         self.add_polled(client)
         self.log_debug(10, 'Opened a Client for ' + name)
     else:
         self.log_debug(7, 'Failed to open a Client for ' + name)
     return result and client
示例#7
0
def main():
    app = QtWidgets.QApplication([])
    pg.setConfigOptions(antialias=True)

    data_queue = queue.Queue()
    _ = Client("localhost", 10000, data_queue)

    win = MyWidget(data_queue)
    win.show()
    win.resize(800, 600)
    win.raise_()
    sys.exit(app.exec_())
示例#8
0
    def __init__(self, camera_factory=None):
        Service.__init__(self, cfg.CAMERA_NAME)

        self.camera_factory = camera_factory
        self.camera = None

        self.handlers[Message.TYPE_PARAMS] = self.handle_params

        self.client = Client(self, cfg.SERVER_HOST, cfg.SERVER_PORT)
        self.protocol = None

        self.frame_rate = 1.0
        return
示例#9
0
def main():
    """Entry point for our simple vlc player
    """
    app = QtWidgets.QApplication(sys.argv)

    data_queue = queue.Queue()

    player = MiniPlayer(data_queue)
    player.show()
    player.resize(480, 480)

    _ = Client("localhost", 10000, data_queue)
    sys.exit(app.exec_())
示例#10
0
    def recovery_pass(self):
        login, secret = [x.text() for x in [self.edit_login, self.edit_secret]]

        if not self.part_checker(login, secret):
            return False

        if self.network is False:
            self.network = Client()

        command = f"password_reset?login={login}&secret={secret}"
        result, data = self.network.command_send(command).split('?')
        if result != "False":
            self.close()
        return self.my_errors(data)
示例#11
0
def downloadFromProgress(download_progress, interrupt, action_queue, download_queue):
    assert isinstance(download_progress, DownloadProgress)
    assert isinstance(interrupt, Interrupt)
    while True:
        try:
            client = Client(download_progress.serverIP, download_progress.serverPort)
            client.requestFile(download_progress.filename, progress=download_progress, interrupt=interrupt, action_queue=action_queue)
        except ConnectionError:
            if download_queue.kill.qsize() != 0:
                sys.exit(1)
            download_progress.download_speed = 0
            download_queue.update()
            print("Failed to connect, will try again in 10 seconds...")
            eel.sleep(10)
示例#12
0
    def __init__(self):

        #---------All-Messages------------
        self._all_messages = []
        #---------------SOCKET-------------
        addr = ('localhost', 6000)
        self._client = Client(addr)

        #---------------RAIZ---------------
        self._raiz = tk.Tk()
        self._raiz.title('CLIENT')
        self._raiz.resizable(width=False, height=False)

        #--------------VARIABLE------------
        self._var_send = tk.StringVar()

        #---------------FRAME--------------
        self._frame = tk.Frame(self._raiz, width=400, height=400)
        self._frame.pack()

        #-------------MESSAGES------------
        self._list_messages = tk.StringVar(value=self._all_messages)

        #---------LISTBOX-MESSAGES---------
        self._listbox_messages = tk.Listbox(self._frame,
                                            width=42,
                                            listvariable=self._list_messages,
                                            selectmode=tk.EXTENDED,
                                            bg='beige')
        self._listbox_messages.grid(row=0, column=0, columnspan=2)

        #--------------ENTRY---------------
        self._entry_send = tk.Entry(self._frame,
                                    width=25,
                                    textvariable=self._var_send)
        self._entry_send.grid(row=1, column=0)

        #---------------BUTTON-------------
        self._send = tk.Button(self._frame,
                               text='Send',
                               width=10,
                               command=lambda: self._messages(self._var_send))
        self._send.grid(row=1, column=1)
        '''Demonio que actualizar la lista sin blquear el flujo de la aplicacion'''
        self._rc = th.Thread(target=self._update_list_messages, daemon=True)
        self._rc.start()
示例#13
0
def main(stdscr):
    finished = False

    gui = CursesInterface(stdscr)
    inpt = Input(stdscr, 0)

    menu = MenuScreen()
    game = Game()

    gui.initialize()
    inpt.initialize()

    while not menu.finished:
        events = inpt.poll_events()
        gui.clear()
        menu.update(events)
        render_menu(gui, menu)
        gui.refresh()
        time.sleep(0.1)

    if menu.current_idx == 0:
        gamewrapper = LocalVsGameWrapper(inpt, game)
    elif menu.current_idx == 1:
        gamewrapper = LocalAiGameWrapper(inpt, game)
    elif menu.current_idx == 2:
        gamewrapper = NetworkedGameWrapper(inpt, game, Server(), 1, 2)
    else:
        gamewrapper = NetworkedGameWrapper(inpt, game,
                                           Client(menu.get_server_ip_str()), 2,
                                           1)

    gamewrapper.initialize()
    while not game.finished:
        gamewrapper.update()
        gui.clear()
        render_game(gui, game)
        time.sleep(0.05)

    gamewrapper.cleanup()

    while True:
        events = inpt.poll_events()
        if events:
            return
        time.sleep(0.1)
示例#14
0
def connect_to_server(supervisor_obj):
    client = Client()
    data = client.receive_server_data()
    if not data:
        print("Не удалось подключиться к серверу")
        supervisor_obj.raise_error(False, "Не удалось подключиться к серверу.",
                                   "Вы не сможете своевременно получить",
                                   "обновления к переводу.")
    else:
        print(data["patch_alerts"])
        supervisor_obj.set_num_alerts(data["patch_alerts"])

        if data["patch_confirmed"]:
            supervisor_obj.confirm_patch()

        if data["version"] > supervisor_obj.reader.get_parameter("Version"):
            print("Доступна новая версия перевода")
            try:
                if supervisor_obj.reader.get_parameter("Disk") == "Yandex":
                    supervisor_obj.download_file_yandex("trans")
                elif supervisor_obj.reader.get_parameter("Disk") == "Google":
                    supervisor_obj.download_file_google("trans")

                supervisor_obj.reader.set_parameter("Version", data["version"])
                if supervisor_obj.reader.get_parameter("TranslationInstalled"):
                    supervisor_obj.install_translation()
            except Exception as e:
                handle_error(e)
                supervisor_obj.raise_error(
                    False, "Не удалось обновить перевод.",
                    "Ошибка доступна в логах. Измените",
                    "диск и перезапустите программу.")

        if data["prog_ver"] > prog_ver:
            if supervisor_obj.reader.get_parameter("TranslationInstalled"):
                supervisor_obj.restore_all_game_files()

            if supervisor_obj.reader.get_parameter("Disk") == "Yandex":
                supervisor_obj.download_file_yandex("program")
            elif supervisor_obj.reader.get_parameter("Disk") == "Google":
                supervisor_obj.download_file_google("program")
            os.startfile("setup.exe")
            sys.exit(0)
示例#15
0
def main():
    """Entry point to a new window of plots"""
    datagen = DataGen()
    plots = datagen.get_neuron_plots()
    plot_names = datagen.neurons

    data_queue = queue.Queue()

    # Create new plot window
    app = QtWidgets.QApplication(sys.argv)
    pg.setConfigOptions(antialias=True)  # set to True for higher quality plots
    main_window = MainWindow(data_queue,
                             plots,
                             plot_names,
                             beh_intervals=datagen.behavior_intervals)
    main_window.show()
    main_window.resize(800, 600)
    main_window.raise_()
    _ = Client("localhost", 10000, data_queue)
    sys.exit(app.exec_())
示例#16
0
 def networking_switcher(self):
     # включение клиентской части
     if self.network is False:
         self.network = Client()
示例#17
0
                self.screen, self.colors[self.alive.getitem((y, x))],
                ((x - self.base_x) * self.scale + GRID_LINE_WIDTH +
                 CELL_MARGIN,
                 (y - self.base_y) * self.scale + GRID_LINE_WIDTH +
                 CELL_MARGIN, self.scale - GRID_LINE_WIDTH - 2 * CELL_MARGIN,
                 self.scale - GRID_LINE_WIDTH - 2 * CELL_MARGIN))

    def draw_new_round(self):
        # print(scores)
        scoreboard = list(sorted(list(self.scores.items()),
                                 key=lambda x: x[1]))
        lines = [
            ("Round ended.", None),
        ]
        for color_id, score in scoreboard:
            lines.append((f" - {score}", color_id))
        self.new_round_info.display(self.screen, lines, self.colors)

    def main(self):
        while True:
            self.clock.tick(FPS)
            self.update()
            self.draw()


if __name__ == '__main__':
    network = Client()
    # print("Starting game")
    game = Game(network, read_data(network.color)[1][0])
    game.start_game()
示例#18
0
 def __init__(self, screen):
     Game.__init__(self, screen)
     self.client = Client()
     client_thread = Thread(target=self.client.start).start()
     self.running_player = None
     self.opponent = None
示例#19
0
def setup():
    global screen, grid_size
    global client, doGameLoop
    global bothAI

    code = input("Enter game code (or blank to create a new game): ")

    # Connect to the server
    server = "127.0.0.1"
    if len(sys.argv) == 2:
        server = sys.argv[1]
    print(f"Connecting server at to {server}...")

    client = Client(server)
    try:
        joined = client.connect(code)
        if code == "":
            print(f"Created game {joined}")
    except Exception as ex:
        exit(f"Unable to connect to server: {ex}")

    pygame.init()
    pygame.display.set_caption(f"Place your fruit (game {joined})")

    #in game options will have a choice to change the grid size
    grid_size = (c.Drawing.SIZE +
                 c.Drawing.MARGIN) * c.Drawing.SQUARES + c.Drawing.MARGIN

    # Since the unplaced ships are on the right of the board, we need to add room for two columns of ships
    width = grid_size + c.Drawing.SIZE * 2 + 35
    screen = pygame.display.set_mode([width, grid_size])

    # Setup all unplaced ships (carrier, battleship, cruiser 1, cruiser 2, and patrol boat)
    # The first column only has room for two ships - the carrier (5) and the battleship (4)
    margin = c.Drawing.MARGIN + 15
    initial_x = grid_size + margin
    unplaced["carrier"] = [
        initial_x, c.Drawing.MARGIN, c.Drawing.SIZE, c.Drawing.SIZE * 5
    ]
    unplaced["battleship"] = [
        initial_x, unplaced["carrier"][3] + (c.Drawing.MARGIN * 3),
        c.Drawing.SIZE, c.Drawing.SIZE * 4
    ]

    # The second column can fit all of the other ships - the two cruisers (3) and the patrol boat (2)
    margin -= 5
    initial_x += c.Drawing.SIZE + margin
    unplaced["cruiser1"] = [
        initial_x, c.Drawing.MARGIN, c.Drawing.SIZE, c.Drawing.SIZE * 3
    ]
    unplaced["cruiser2"] = [
        initial_x, unplaced["cruiser1"][3] + (c.Drawing.MARGIN * 3),
        c.Drawing.SIZE, c.Drawing.SIZE * 3
    ]
    unplaced["patrol"] = [
        initial_x, unplaced["cruiser2"][3] + unplaced["cruiser2"][1] +
        (c.Drawing.MARGIN * 3), c.Drawing.SIZE, c.Drawing.SIZE * 2
    ]

    displayThread = threading.Thread(target=display)
    displayThread.start()

    # Check for updates from the server
    count = 2
    while doGameLoop:
        client.updateStats(opponentDecreased, weDecreased)

        if client.ready:
            # Count is here to avoid requesting updates before the AI is ready
            if count < 0:
                refreshGrid(True)
            else:
                count -= 1

        time.sleep(0.5)
示例#20
0
    for i in range(len(field)):
        for j in range(len(field)):
            if field[i][j] is None:
                valid.append((j + 1, i + 1))
    print(field, 'field')
    print(valid, 'valid')
    move = random.choice(valid)
    return move


def make_move(crosses_turn):
    global field
    move = get_next_move(field)
    logging.info(move)
    return move


def game_over(crosses_won):
    if crosses_won is None:
        print('Draw')
    else:
        print('Winner:', 'crosses' if crosses_won else 'noughts')


client = Client(args.host, args.port)
client.on_field_received = save_field
client.on_move_required = make_move
client.on_game_over = game_over

client.start()
示例#21
0
                run = False
                pygame.quit()

            if event.type == pygame.MOUSEBUTTONDOWN:
                clickPos = pygame.mouse.get_pos()
                if RadBoats.click(clickPos):
                    print(RadBoats.state)
        pygame.display.update()


########################################################################################################################
pygame.init()
winSize = (300, 520)
window = pygame.display.set_mode(winSize)
pygame.display.set_caption("client")
window.fill(colours['clientBackground'])
running = True
n = Client()
clientID = None
isUmpire = welcome_screen()
print(clientID)
while n.connected:
    if isUmpire:
        print("ump")
        umpire_setup()
        umpire_console()
    else:
        print("play")
        lobby_screen()
        player_console()