Exemplo n.º 1
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])
Exemplo n.º 2
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()
Exemplo n.º 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()))
Exemplo n.º 4
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)
Exemplo n.º 5
0
def start(args):
    """
    Starts the reporter

    :address:  Aggregator to connect to
    :hostname: Hostname
    """

    # Modules will be completely overwritten but that's as intended
    defaults = {
        'hostname': socket.gethostname(),
        'host'    : '127.0.0.1',
        'port'    : 13337,
        'modules' : {
            'Network': [
                {}
            ]
        }
    }

    # If no config file use dummy data
    if args.configFile:
        config = parseConfig(args.configFile, defaults = defaults)
    else:
        config = defaults

    if args.port:
        config["port"] = args.port
    if args.host:
        config["host"] = args.host
    if args.hostname:
        config['hostname'] = args.hostname

    # Initialize networking client
    client = Client((config["host"], config["port"]))

    # Create target function
    target = functools.partial(send_publish_socket, additional = {
        "host": config['hostname']
    }, client = client)

    # Initialize the publisher
    publisher = Publisher(target)

    # Load modules
    loadModulesFromConfig(config, publisher, moduleFinder)

    # Start client and publisher
    client.connect()
    publisher.start()

    # Wait until client finishes
    try:
        client.finished.wait()
    except KeyboardInterrupt:
        client.disconnect()
        client.finished.wait()
Exemplo n.º 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
Exemplo n.º 7
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
Exemplo n.º 8
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)
Exemplo n.º 9
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)
Exemplo n.º 10
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()
Exemplo n.º 11
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)
Exemplo n.º 12
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_())
Exemplo n.º 13
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_())
Exemplo n.º 14
0
class BaseController(QObject):
    _instance = None

    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()

    def connect_client(self, adr, port):
        if not (self.is_connected or self.is_connecting):
            self.is_connecting = True
            self.c.connect(adr, port)  # will not return any error code
            # if ret == -1:
            #    self.is_connecting = False
            #    print_trace_exception()
            #    raise os.ConnectionError()
            self.is_connected = True
            self.is_connecting = False

    def get_client(self):
        return self.c
Exemplo n.º 15
0
class Password_rec(QDialog):
    """диалоговое окно на случай если юзер забыл пароль"""
    forbidden_chars = "?&="

    def __init__(self, *args):
        super().__init__()

        self.client_path = os.getcwd().rsplit("\\", maxsplit=1)[0]
        self.uic_auth = os.path.join(self.client_path, "ui files",
                                     "pass_rec.ui")
        uic.loadUi(self.uic_auth, self)

        self.network = False

        self.btn_recovery.clicked.connect(self.recovery_pass)

    def my_errors(self, error):
        msg = QMessageBox(self)
        msg.setText(error)
        msg.show()
        return False

    def part_checker(self, login, secret):
        for word, type_ in zip([login, secret], ['Логин', "Секретное слово"]):
            if len(word.replace(' ', '')) == 0:
                return self.my_errors(f"{type_} не может быть пустой!")
            if len(word) == 0:
                return self.my_errors(f"{type_} не может быть пустой!")
            if any(ch in self.forbidden_chars for ch in word):
                return self.my_errors(
                    f"{type_} не может содержать символы '?&='")

        return True

    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)
Exemplo n.º 16
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)
Exemplo n.º 17
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_())
Exemplo n.º 18
0
class NetworkGame(Game):
    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

    def start(self):
        """ wait for server to send start msg, start pygame main loop """

        print('waiting for other player...')
        # Wait for game to start
        while (not self.client.last_message):
            pass

        assigned_team = int(self.client.last_message.split('|')[1])
        self.running_player = self.player1 if assigned_team == 1 else self.player2
        self.opponent = self.player1 if self.running_player == self.player2 else self.player2
        print(f'started! you are player {self.running_player.team}')
        self.running = True
        self.board.setup()
        while self.running:
            if (not self.client.last_message):
                pass
            else:
                cmd = self.client.last_message.split('|')[0]

                # Game started
                if (cmd == 's'):
                    self.client.last_message = None
                    pass

                # Opponent moved
                elif (cmd == 'm'):
                    self.handle_move()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.stop()

                if event.type == pygame.MOUSEBUTTONDOWN:
                    self.handle_mouse_down(event.pos)

                elif event.type == pygame.MOUSEBUTTONUP:
                    if event.button == 1:
                        self.handle_mouse_up(event.pos)

                elif event.type == pygame.MOUSEMOTION:
                    self.handle_mouse_motion(event.pos)
            self.render()
            pygame.display.flip()

    def handle_move(self):
        """ handle move described by client's last_message recieved """
        from_x = int(self.client.last_message.split('|')[1])
        from_y = int(self.client.last_message.split('|')[2])
        to_x = int(self.client.last_message.split('|')[3])
        to_y = int(self.client.last_message.split('|')[4])
        from_tile = self.board.board[from_y][from_x]
        to_tile = self.board.board[to_y][to_x]
        self.opponent.selected_piece = from_tile.piece
        self.opponent.move_piece(to_tile)
        self.going_player = self.running_player
        self.client.last_message = None

    def handle_mouse_down(self, pos):
        """ handle mouse down at pos x, y """
        tile = self.board.get_tile(pos[0], pos[1])
        # Check if is players turn
        if (tile.piece and tile.piece.player.team == self.going_player.team):
            # If network game, make sure going_player is running_player
            if (not self.running_player
                    or (self.running_player == self.going_player)):
                self.going_player.selected_piece = tile.piece
                self.going_player.selected_piece.dragging = True

    def handle_mouse_up(self, pos):
        """ handle mouse up at pos x, y """
        if (not self.going_player.selected_piece):
            return
        self.going_player.selected_piece.dragging = False
        mouse_x, mouse_y = pos
        tile = self.board.get_tile(mouse_x, mouse_y)
        if (self.going_player.selected_piece.check_move(tile)):
            # Send move to server
            msg = f'm|{self.going_player.selected_piece.x}|{self.going_player.selected_piece.y}|{tile.x}|{tile.y}'
            self.client.send(msg)
            self.going_player.move_piece(tile)
            self.going_player = self.player1 if self.going_player.team == 2 else self.player2

        else:
            self.going_player.reset_current_piece()
Exemplo n.º 19
0
 def __init__(self, window):
     self.window = window
     self.client = Client.get_instance()
     self.event_manager = EventManager.get_instance()
Exemplo n.º 20
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)
Exemplo n.º 21
0
#     	myoptions = 'Complaint'
#     elif myoptions == '2':
#     	myoptions = 'Question'
#     elif myoptions == '3': 
#     	myoptions ='Other'
#     else:
#         myoptions = 'no'
#         print 'Invalid input, try again'
# 	
# #while (myoptions != '1' or myoptions != '2' or myoptions != '3'):  
# #	myoptions = raw_input('What brings you here?(choose a number) 1. Complaint, 2. Question, 3. Other ')
# #	print myoptions
# 
# 
# topic = raw_input('What is your topic regarding this prompt?')
client = Client(host, port)
client.do_send({'Conversation Type': 'Type'})
client.do_send({'Topic': 'Test'})
#########################################

#print 'Connecting you with an agent'

thread = Thread(target=asyncore.loop)
thread.daemon = True  # die when the main thread dies 
thread.start()

while 1:
    mytxt = sys.stdin.readline().rstrip()
    #customer console options
    if mytxt == ':q':
        print client
Exemplo n.º 22
0
class App:
    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()

    def _get_raiz(self):
        return self._raiz

    def _messages(self, msg):

        if msg.get():
            '''Añade el nombre del autor'''
            data = msg.get()
            '''Enviando mensaje al servidor...'''
            self._client._send(data)
            '''Borrando contenido de Entry'''
            msg.set('')

    def _update_list_messages(self):
        '''actualizar la lista indefinidamente'''
        while 1:
            msgs_server = self._client._messages
            self._list_messages.set(value=msgs_server)

    def __str__(self):
        return 'Chat hecha con sockets y tkinter'

    def loop(self):
        self._raiz.mainloop()
Exemplo n.º 23
0
 def networking_switcher(self):
     # включение клиентской части
     if self.network is False:
         self.network = Client()
Exemplo n.º 24
0
'''chat agent view'''

from network import Handler, poll, periodic_poll, Client, get_my_ip
import sys
from threading import Thread
from time import sleep
import asyncore


#replace host with ip address
#192.168.1.105
host, port = get_my_ip(), 8888
client = Client(host, port)
                         
thread = Thread(target=asyncore.loop)
thread.daemon = True  # die when the main thread dies 
thread.start()

client.do_send({'speak': 'agent', 'txt': 'Chat agent has connected'})
client.do_send({'Info': 'Model'})
while 1:
    mytxt = sys.stdin.readline().rstrip()
    client.do_send({'speak': 'agent', 'txt': mytxt})
Exemplo n.º 25
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
Exemplo n.º 26
0
class SeeBattle_Auth(QMainWindow):
    """Окно для авторизации"""
    forbidden_chars = "?&="

    def __init__(self, *args):
        self.client_path = os.getcwd().rsplit("\\", maxsplit=1)[0]

        super().__init__()

        self.uic_auth = os.path.join(self.client_path, 'ui files',
                                     'auth_form.ui')
        uic.loadUi(self.uic_auth, self)

        self.network = False

        self.widget_functions()

        with open(os.path.join(self.client_path, 'settings', 'checker_ip.inf'),
                  'r') as f:
            data = [line.split()[1] for line in f.read().split('\n')]
            self.checkers_ip, self.checkers_port = data
        self.checkers_port = int(self.checkers_port)

    def widget_functions(self):
        self.btn_auth.clicked.connect(self.sign_in)
        self.btn_sign_up.clicked.connect(self.sign_up)

    def mousePressEvent(self, event):
        x, y = event.x(), event.y()
        if 40 <= x <= 121 and 210 <= y <= 226:
            self.recovery_pass()

    def my_errors(self, error):
        # Ошибки не свзянанные с ошибками исполнения программы
        msg = QMessageBox(self)
        msg.setText(error)
        msg.show()
        return False

    def login_and_password_checker(self, login, password):
        # Проверка пароля
        for word, type_ in zip([login, password], ['Логин', "Пароль"]):
            if len(word.replace(' ', '')) == 0:
                return self.my_errors(f"{type_} не может быть пустой!")
            if len(word) == 0:
                return self.my_errors(f"{type_} не может быть пустой!")
            if any(ch in self.forbidden_chars for ch in word):
                return self.my_errors(
                    f"{type_} не может содержать символы '?&='")
        return True

    def networking_switcher(self):
        # включение клиентской части
        if self.network is False:
            self.network = Client()

    @errors_handler
    def sign_in(self):
        # авторизация
        login = self.edit_login.text()
        password = self.edit_pass.text()
        if not self.login_and_password_checker(login, password):
            return False
        self.networking_switcher()

        result, data = self.network.command_send(
            f"auth?login={login}&password={password}&ip_port={self.checkers_ip}:{self.checkers_port}"
        ).split('?')
        if result == "False":
            self.my_errors(data)
            return False

        self.close()
        self.main_menu = Game_menu(data, self)
        self.main_menu.show()

        return True

    @errors_handler
    def recovery_pass(self):
        self.pass_rec = Password_rec(self)
        self.pass_rec.show()

    @errors_handler
    def sign_up(self):
        self.sign_up = Sign_up(self)
        self.sign_up.show()
        self.close()
Exemplo n.º 27
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()
Exemplo n.º 28
0
class Drone(Service):
    """Handles communication between the drone and the dispatcher."""
    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

    def start(self):
        """Starts the drone client."""
        self.client.run()
        return

    def stop(self):
        """Stops the drone client."""
        self.client.stop()
        return

    def start_camera(self):
        """Start capturing images."""
        if (self.camera is None) and (not self.camera_factory is None):
            self.camera = self.camera_factory(self.send_image)
            self.camera.frame_rate = self.frame_rate
            self.camera.start()

        return

    def stop_camera(self):
        """Stop capturing images."""
        if self.camera:
            self.camera.stop()
            self.camera = None

        return

    def send(self, message):
        if self.protocol:
            self.protocol.send(message)

        return

    def connected(self, protocol):
        """Handles connection."""
        Service.connected(self, protocol)
        self.protocol = protocol

        self.send(Message(self.name, Message.TYPE_LOGIN))
        return

    def disconnected(self, protocol):
        """Handles disconnection."""
        Service.disconnected(self, protocol)
        self.protocol = None
        self.stop_camera()
        return

    def send_image(self, image_data):
        """Sends JPEG-encoded images."""
        msg = Message(self.name, Message.TYPE_IMAGE, image_data)
        self.send(msg)
        return

    def handle_params(self, protocol, message):
        """Handles param messages."""
        self.log().info("received params from '%s': %s", message.name,
                        message.data)

        params = message.data
        for p in params:
            self.configure_param(p)

        return

    def configure_param(self, param):
        """Processes a parameter."""
        self.log().debug(param)

        if param[0] == 'frame_rate':
            self.frame_rate = param[1]

            if not self.camera is None:
                self.camera.frame_rate = self.frame_rate

        elif param[0] == 'camera':
            if param[1]:
                self.start_camera()

            else:
                self.stop_camera()

        return
Exemplo n.º 29
0
class Sign_up(QMainWindow):
    """"Окно регистрации"""
    forbidden_chars = "?&="

    def __init__(self, *args):
        super().__init__()

        self.network = False

        self.client_path = os.getcwd().rsplit("\\", maxsplit=1)[0]

        self.uic_sign_up = os.path.join(self.client_path, 'ui files',
                                        'sign_up.ui')
        uic.loadUi(self.uic_sign_up, self)

        self.btn_su.clicked.connect(self.sign_up)

    def my_errors(self, error):
        msg = QMessageBox(self)
        msg.setText(error)
        msg.show()
        return False

    def part_checker(self, login, password, secret):
        for word, type_ in zip([login, password, secret],
                               ['Логин', "Пароль", "Секретное слово"]):
            if len(word.replace(' ', '')) == 0:
                return self.my_errors(f"{type_} не может быть пустой!")
            if len(word) == 0:
                return self.my_errors(f"{type_} не может быть пустой!")
            if any(ch in self.forbidden_chars for ch in word):
                return self.my_errors(
                    f"{type_} не может содержать символы '?&='")

        return True

    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])

    def mousePressEvent(self, event):
        x, y = event.x(), event.y()
        if 20 <= x <= 67 and 10 <= y <= 30:
            self.auth_form = SeeBattle_Auth(self)
            self.auth_form.show()
            self.close()
Exemplo n.º 30
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()
Exemplo n.º 31
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()
Exemplo n.º 32
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()
Exemplo n.º 33
0
              'boat': upd_boat,
              # 'buoy': upd_buoy
              }
    while run:
        update = connection.listen()    # update has form [property, value]
        if update is not None:
            switch[update[0]](update[1])
            print(update)
            draw_board()
    pass
    # listen for updates


########################################################
# make connection to server
n = Client()
clientID = n.connect('viewer')
# get initial game values
mapPath, boatList, buoyList, wind = n.send('get', 'initial')
# boats are received as [boatID, pos, heading, spinnaker, colour]
# buoys are received as [buoyID, pos, isFinish]
# create board
boardSize, terrain = create_map(mapPath)
# create flotilla
flotilla = {boat[0]: Boat(boat[1:5]) for boat in boatList}
buoys = {buoy[0]: Buoy(buoy[1:3]) for buoy in buoyList}

# initialise pygame window
pygame.init()
window = pygame.display.set_mode(tuple(i * (blockSize + borderSize) + borderSize for i in boardSize))
pygame.display.set_caption("boardViewer")