def pasre_content(self, content: str): if not content.startswith('fen '): manual = Manual() try: manual.callback = lambda fpos, tpos: self.board.setBoard( manual.sit.board, manual.sit.fpos, manual.sit.tpos ) manual.parse(content) except Exception as e: self.toast.message(str(e)) return fen = manual.sit.format_fen() else: fen = content[4:] self.engine.index = 0 self.engine.stack = self.engine.stack[:1] self.engine.sit = self.engine.stack[0] self.updateBoard() self.board.setCheck(None) if self.engine.sit.parse_fen(fen, load=True): moves = self.engine.sit.moves self.engine.sit.moves = [] for fpos, tpos in moves: result = self.engine.move(fpos, tpos) if result == Chess.CHECKMATE: self.game_signal.checkmate.emit() break self.updateBoard() else: self.toast.message("加载棋谱失败")
def __init__(self, address): super().__init__(address) self.about = About(self) self.access = Access(self) self.adjustment = Adjustment(self) self.axis = Axis(self) self.displacement = Displacement(self) self.ecu = Ecu(self) self.functions = Functions(self) self.manual = Manual(self) self.network = Network(self) self.nlc = Nlc(self) self.pilotlaser = Pilotlaser(self) self.realtime = Realtime(self) self.system = System(self) self.system_service = System_service(self) self.update = Update(self) try: self.streaming = Streaming(self) except NameError as e: if "Streaming" in str(e): print("Warning: Streaming is not supported on your platform") else: raise e
def __init__(self, ip, port, coord_inicial): super().__init__() # self.socket = socket.socket() self.port = port self.ip = ip self.begin_pos = coord_inicial self.current_pos = coord_inicial self.manual = True self.map = [] self.flags = [] self._blocked = False self.auto_thread = None # global flags global debug if not debug: try: self.motor = Manual((self.current_pos[0], self.current_pos[1])) print("motor connected") except Exception as e: print("failled to connect motor", e)
def split(dataset, test_size=0.5, random_state=None): if random_state is None: random_state = np.random.randint(0, 999999) nb = dataset.X.shape[0] nb_test = int(nb * test_size) nb_train = nb - nb_test rng = RandomState(random_state) indices = np.arange(0, nb) rng.shuffle(indices) indices_train = indices[0:nb_train] indices_test = indices[nb_train:] X = dataset.X[indices_train] if hasattr(dataset, 'y') and dataset.y is not None: y = dataset.y[indices_train] else: y = None dataset_train = Manual(X, y) if hasattr(dataset, "img_dim"): dataset_train.img_dim = dataset.img_dim if hasattr(dataset, "output_dim"): dataset_train.output_dim = dataset.output_dim X = dataset.X[indices_test] if hasattr(dataset, 'y') and dataset.y is not None: y = dataset.y[indices_test] else: y = None dataset_test = Manual(X, y) if hasattr(dataset, "img_dim"): dataset_test.img_dim = dataset.img_dim if hasattr(dataset, "output_dim"): dataset_test.output_dim = dataset.output_dim return dataset_train, dataset_test
from mover import Mover from shared import SharedObj from manual import Manual global shared_obj shared_obj = SharedObj() # variavel global # Jamal = Mover(0, 0) Jamal = Manual([0, 0]) Jamal.start() while True: user_input = input("> ") if user_input == "w": shared_obj.set(SharedObj.MoverMovimento, Mover.FRENTE) print("Andando para a frente") if user_input == "a": shared_obj.set(SharedObj.MoverMovimento, Mover.ESQUERDA) print('andando para esquerda') if user_input == "d": shared_obj.set(SharedObj.MoverMovimento, Mover.DIREITA) print('andando para a direita') if user_input == "s": shared_obj.set(SharedObj.MoverMovimento, Mover.TRAS) print('andando para tras') if user_input == "q": shared_obj.set(SharedObj.MoverMovimento, Mover.EXIT)
from manual import Manual Manual.xxx()
def _process_data(self, msg): # print(msg) if msg.cmd == Mover.FRENTE: print("frente") try: self.frente() except Exception as e: pass elif msg.cmd == Mover.TRAS: print("tras") try: self.tras() except Exception as e: pass elif msg.cmd == Mover.DIREITA: print("direita") try: self.direita() except Exception as e: pass elif msg.cmd == Mover.ESQUERDA: print("esquerda") try: self.esquerda() except Exception as e: pass elif msg.cmd == Commands.STOP: self.current_pos = self.begin_pos self.flags = None if self.auto_thread: if self.auto_thread.is_alive(): self.auto_thread.join(timeout=10) self.auto_thread = None if not debug: try: self.motor = Manual(self.begin_pos) print("motor connected") except Exception as e: print("[NOVO MANUAL] failled to connect motor: ", e) print("STOP") elif msg == Commands.QUIT: try: self.join() self.socket.close() except: pass elif not msg: time.sleep(1) elif msg.cmd == Commands.UPDATE_MAP: print("mapa: ", msg.data) self.map = msg.data elif msg.cmd == Commands.UPDATE_FLAGS: print("bandeiras: ", msg.data) self.flags = msg.data elif msg.cmd == Commands.MODE: # automatico = False self.manual = msg.data print(msg.data) if not msg.data: print("Modo automatico\n") self.auto_thread = Automatico(self) self.auto_thread.start() else: print("Modo manual\n") if self.auto_thread: if self.auto_thread.is_alive(): self.auto_thread.join(timeout=10) self.auto_thread = None elif msg.cmd == Commands.STATUS_GET_FLAG: self._blocked = False
class Robo(Thread): """essa classe eh para ser executada no robo, a unica coisa que essa classe faz eh mover o robo, e eventualmente ativar o modo automatico""" def __init__(self, ip, port, coord_inicial): super().__init__() # self.socket = socket.socket() self.port = port self.ip = ip self.begin_pos = coord_inicial self.current_pos = coord_inicial self.manual = True self.map = [] self.flags = [] self._blocked = False self.auto_thread = None # global flags global debug if not debug: try: self.motor = Manual((self.current_pos[0], self.current_pos[1])) print("motor connected") except Exception as e: print("failled to connect motor", e) def _process_data(self, msg): # print(msg) if msg.cmd == Mover.FRENTE: print("frente") try: self.frente() except Exception as e: pass elif msg.cmd == Mover.TRAS: print("tras") try: self.tras() except Exception as e: pass elif msg.cmd == Mover.DIREITA: print("direita") try: self.direita() except Exception as e: pass elif msg.cmd == Mover.ESQUERDA: print("esquerda") try: self.esquerda() except Exception as e: pass elif msg.cmd == Commands.STOP: self.current_pos = self.begin_pos self.flags = None if self.auto_thread: if self.auto_thread.is_alive(): self.auto_thread.join(timeout=10) self.auto_thread = None if not debug: try: self.motor = Manual(self.begin_pos) print("motor connected") except Exception as e: print("[NOVO MANUAL] failled to connect motor: ", e) print("STOP") elif msg == Commands.QUIT: try: self.join() self.socket.close() except: pass elif not msg: time.sleep(1) elif msg.cmd == Commands.UPDATE_MAP: print("mapa: ", msg.data) self.map = msg.data elif msg.cmd == Commands.UPDATE_FLAGS: print("bandeiras: ", msg.data) self.flags = msg.data elif msg.cmd == Commands.MODE: # automatico = False self.manual = msg.data print(msg.data) if not msg.data: print("Modo automatico\n") self.auto_thread = Automatico(self) self.auto_thread.start() else: print("Modo manual\n") if self.auto_thread: if self.auto_thread.is_alive(): self.auto_thread.join(timeout=10) self.auto_thread = None elif msg.cmd == Commands.STATUS_GET_FLAG: self._blocked = False def frente(self): try: self.motor.move(Mover.FRENTE) except Exception as e: pass self.current_pos = int(self.current_pos[0]) + 1, int(self.current_pos[1]) print(self.current_pos) if not self.manual: while not self.motor.moveu: pass msg = Message(cmd=Mover.FRENTE) self.connection.send(msg.serialize()) time.sleep(Automatico.SLEEP_TIME) def tras(self): try: self.motor.move(Mover.TRAS) except Exception as e: pass self.current_pos = int(self.current_pos[0]) - 1, int(self.current_pos[1]) print(self.current_pos) if not self.manual: while not self.motor.moveu: pass msg = Message(cmd=Mover.TRAS) self.connection.send(msg.serialize()) time.sleep(Automatico.SLEEP_TIME) def esquerda(self): try: self.motor.move(Mover.ESQUERDA) except Exception as e: pass self.current_pos = int(self.current_pos[0]), int(self.current_pos[1]) - 1 print(self.current_pos) if not self.manual: while not self.motor.moveu: pass msg = Message(cmd=Mover.ESQUERDA) self.connection.send(msg.serialize()) time.sleep(Automatico.SLEEP_TIME) def direita(self): try: self.motor.move(Mover.DIREITA) except Exception as e: pass self.current_pos = int(self.current_pos[0]), int(self.current_pos[1]) + 1 print(self.current_pos) if not self.manual: while not self.motor.moveu: pass msg = Message(cmd=Mover.DIREITA) self.connection.send(msg.serialize()) time.sleep(Automatico.SLEEP_TIME) def _connect(self): """Conecta o robo ao controlador""" self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((self.ip, self.port)) self.socket.listen(1) print("ready to conect") self.connection, self.address = self.socket.accept() print("conectado com, ", self.address) def _send_begin_pos(self): self.connection.send(Message(cmd=Commands.SET_BEGIN_POS, data=self.begin_pos).serialize()) def _handle(self): while True: try: msg = self.connection.recv(2048) print(msg, file=sys.stderr) msg = Message(None, msg) self._process_data(msg) except Exception as e: print(e.with_traceback) def run(self): self._connect() self._handle() def is_blocked(self): return self._blocked def get_flag(self, coord): self.connection.send(Message(cmd=Commands.GET_FLAG, data=coord).serialize()) self._blocked = True def close_socket(self): try: self.connection.close() except Exception as e: print(e) finally: self.socket.close() print("main socket has been closed")
class Assembly(tk.Tk): def __init__(self, title: str, width: int, height: int, load_workspace=True): tk.Tk.__init__(self) self.title(title) self.geometry(f"{width}x{height}+0+0") self.minsize(width, height) self.protocol("WM_DELETE_WINDOW", self.stop) self.menu_bar = MenuWindow(self, font=("", 12)) self.paned_window = tk.PanedWindow(self, orient=tk.HORIZONTAL, sashwidth=5, sashrelief=tk.RAISED) self.paned_window.bind("<Configure>", self.set_panedwindow_size) self.editor = Editor(self, width=int(width * 0.7), load_workspace=load_workspace) self.options = tk.Frame(self, width=int(width * 0.3)) self.build = IconButton(self.options, "build.png", tooltip="Build champion", command=self.build_code) self.template = IconButton(self.options, "template.png", tooltip="Start with template", command=self.editor.start_template) self.help = IconButton(self.options, "help.png", tooltip="Manual for help", command=self.open_manual) self.manual = None self.command_list = CommandList(self.options) self.command_list.button_add.configure(command=self.add_command) self.paned_window.add(self.options) self.paned_window.add(self.editor) self.menu_bar.add_section("Files") self.menu_bar.add_section_command("Files", "New file", self.editor.create_new_file, accelerator="Ctrl+N") self.menu_bar.add_section_command("Files", "Open file", self.editor.open_file, accelerator="Ctrl+O") self.menu_bar.add_section_separator("Files") self.menu_bar.add_section_command("Files", "Save", self.editor.save_in_file, accelerator="Ctrl+S") self.menu_bar.add_section_command("Files", "Save All", self.editor.save_all_files, accelerator="Ctrl+Shift+S") self.menu_bar.add_section_command("Files", "Save As", self.editor.save_file_as, accelerator="Alt+Ctrl+S") self.menu_bar.add_section_separator("Files") self.menu_bar.add_section_command("Files", "Close", self.editor.close_file, accelerator="Ctrl+W") self.menu_bar.add_section_command("Files", "Close All", self.editor.close_all_files, accelerator="Ctrl+Shift+W") self.menu_bar.add_section_separator("Files") self.menu_bar.add_section_command("Files", "Exit", self.stop, accelerator="[Alt+F4 Ctrl+Q]") self.menu_bar.add_section("Edit") self.menu_bar.add_section_command("Edit", "Undo", self.editor.undo_last_modification, accelerator="Ctrl+Z") self.menu_bar.add_section_command("Edit", "Redo", self.editor.redo_last_undo, accelerator="Ctrl+Shift+Z") self.menu_bar.add_section_separator("Edit") self.menu_bar.add_section_command("Edit", "Cut", self.editor.cut_to_clipboard, accelerator="Ctrl+X") self.menu_bar.add_section_command("Edit", "Copy", self.editor.copy_to_clipboard, accelerator="Ctrl+C") self.menu_bar.add_section_command("Edit", "Paste", self.editor.paste_from_clipboard, accelerator="Ctrl+V") self.refresh_functions = list() self.refresh_functions.append(self.editor.update_tab) def run(self, file=None, working_dir=None): if file is not None: self.editor.open_file(file) elif not self.editor.workspace: self.editor.create_new_file() if working_dir is not None and os.path.isdir(working_dir): self.editor.last_opened_folder = working_dir self.all_binds() self.show_widgets() self.refresh() self.mainloop() def stop(self): if self.editor.close_workspace(): self.destroy() def show_widgets(self): self.paned_window.pack(fill=tk.BOTH, expand=True) self.options.grid_columnconfigure(0, weight=1) self.options.grid_columnconfigure(1, weight=1) self.options.grid_columnconfigure(2, weight=1) self.build.grid(row=0, column=0, pady=20) self.template.grid(row=0, column=1, pady=20) self.help.grid(row=0, column=2, pady=20) self.command_list.grid(row=1, column=0, columnspan=3) def refresh(self): for function in self.refresh_functions: function() self.after(10, self.refresh) def all_binds(self): self.bind_key("Control", "n", lambda event: self.editor.create_new_file()) self.bind_key("Control", "o", lambda event: self.editor.open_file()) self.bind_key("Control", "s", lambda event: self.editor.save_in_file()) self.bind_key("Control-Shift", "s", lambda event: self.editor.save_all_files()) self.bind_key("Control-Alt", "s", lambda event: self.editor.save_file_as()) self.bind_key("Control", "w", lambda event: self.editor.close_file()) self.bind_key("Control-Shift", "w", lambda event: self.editor.close_all_files()) self.bind_key("Control", "q", lambda event: self.stop()) def bind_key(self, modifiers: str, key: str, command): self.bind_all(f"<{modifiers}-{key.lower()}>", command) self.bind_all(f"<{modifiers}-{key.upper()}>", command) def set_panedwindow_size(self, event): self.paned_window.paneconfigure(self.options, minsize=0.3 * event.width) self.paned_window.paneconfigure(self.editor, minsize=0.5 * event.width) self.editor.configure(width=int(event.width * 0.7)) self.options.configure(width=int(event.width * 0.3)) def build_code(self): filepath = self.editor.get_file() if len(filepath) == 0: return cmd = [os.path.join(sys.path[0], "asm_compiler"), filepath] try: output_process = subprocess.run(cmd, check=True, capture_output=True) except subprocess.CalledProcessError as e: output = e.stderr.decode() status = e.returncode else: output = output_process.stderr.decode() status = output_process.returncode if len(output) == 0 and status == 0: showinfo("Compilation completed", "The compilation was a succes !") else: output = remove_color_characters(output)[:-1] showerror("An error occurs", output.split(", ")[2]) def add_command(self): command = self.command_list.selected if command is None: return self.editor.insert_command(command.get()) self.command_list.reset() def open_manual(self): if self.manual is None: self.manual = Manual(self) else: self.manual.focus_set()
def open_manual(self): if self.manual is None: self.manual = Manual(self) else: self.manual.focus_set()
print "*" print "*", print " ", print "*" print "****************************************************" mode = raw_input("Would you like to play a round yourself (m) or let the computer run a set number of rounds (a)? ") print "" if mode == 'm': numberOfCards = 0 while numberOfCards != 7 and numberOfCards != 9: numberOfCards = input("7 or 9? ") if numberOfCards != 7 and numberOfCards != 9: print("Holy f*****g smoke, read the question dipshit...") man = Manual(numberOfCards, continueWhenDeckIsEmpty) man.run() if mode == 'a': totalIterations = input("Enter total number of rounds: ") print "" print "Running simulation for 7 cards and %d iterations..." % totalIterations sim = Simulation(7, continueWhenDeckIsEmpty, totalIterations) sim.run() print "" print "Running simulation for 9 cards and %d iterations..." % totalIterations sim = Simulation(9, continueWhenDeckIsEmpty, totalIterations) sim.run()
plt.ylabel('Games Won') plt.title('Tic Tac Toe Results') plt.xticks(x, ('X', 'O', 'Draw')) plt.legend() plt.savefig(filename) a1 = Agent(user.X) a2 = RandomPlayer(user.O) a3 = Agent(user.O) a4 = RandomPlayer(user.X) a5 = Agent(user.O) manual = Manual(user.O) stats = play_games(a1, a2, 100000, figure_name='AgentX_RandY.png') create_bar_graph(stats, 'agent_rand.png') print_stats(stats) a1.set_learn_rate(0) stats = play_games(a4, a3, 100000, figure_name='AgentX_RandY2.png') create_bar_graph(stats, 'agent_rand2.png') print_stats(stats) a3.set_learn_rate(0) stats = play_games(a1, a3, 10000, figure_name='AgentX_RandY3.png') create_bar_graph(stats, 'agent_rand3.png') print_stats(stats)