def test_init_exception(self): """ Controller.init() exception test """ Config.params['required_version'] = '4.0' with self.assertRaises(SrcError) as context: Controller().scan_action({}) self.assertTrue(SrcError == context.expected) with self.assertRaises(SrcError) as context: Controller().scan_action({}) self.assertTrue(SrcError == context.expected)
def test_run_exception(self): """ Controller.run() exception test """ controller = Controller.__new__(Controller) with self.assertRaises(SrcError) as context: controller.run() self.assertTrue(SrcError == context.expected)
def test_get_not_divisible(self): tests = [ { 'n': 100, 'p': 7, 'expected_result': 2361 }, { 'n': 1000000000, 'p': 7, 'expected_result': 2129970655314432 }, { 'n': 879799879, 'p': 17, 'expected_result': 6026990181372288 }, { 'n': 879799879, 'p': 19, 'expected_result': 8480245105257600 }, { 'n': 751825096, 'p': 7, 'expected_result': 1268068459033362 }, ] for test in tests: self.assertEqual( test['expected_result'], Controller.get_not_divisible(test['n'], test['p']))
def test_run(self, args): """ Controller.run() test """ Config.params['cfg'] = 'setup.cfg' controller = Controller.__new__(Controller) setattr(controller, 'ioargs', args) controller.run() self.assertTrue(True)
def test_local_version_action_exception(self): """ Controller.local_version() exception test """ Config.params['cfg'] = 'wrong.cfg' controller = Controller.__new__(Controller) with self.assertRaises(SrcError) as context: controller.local_version() self.assertTrue(SrcError == context.expected)
def test_update_action_exception(self): """ Controller.update_action() exception test """ del Config.params['update'] controller = Controller.__new__(Controller) with self.assertRaises(SrcError) as context: controller.update_action() self.assertTrue(SrcError == context.expected)
def main(): r = redis.StrictRedis('localhost', 6379, charset="utf-8", decode_responses=True) view = View.View() c = Controller.Controller(view, r) c.parse_user_input()
def test_scan_action_exception(self): """ Controller.scan_action() exception test """ controller = Controller.__new__(Controller) with self.assertRaises(SrcError) as context: controller.scan_action(params={ 'host': 'http://example.com', 'port': 80 }) self.assertTrue(SrcError == context.expected)
def test_init_exception(self): """ Controller.init() exception test """ self.config['info']['required_versions'] = { 'minor': '4.0', 'major': '4.5' } with self.assertRaises(SrcError) as context: Controller().scan_action({}) self.assertTrue(SrcError == context.expected)
def __init__(self, parent=None): super(Pomodor, self).__init__(parent=parent) self.ui = Ui_PomodorWindow() self.ui.setupUi(self) self.config_file_path = src.utils.get_config_file_path() self.__config_data = src.utils.get_config_data() # Connections self.ui.act_set_times.triggered.connect(self.__show_config) self.ui.reset_btn.clicked.connect(lambda: self.__update_timer(False)) self.ui.stop_btn.clicked.connect(self.stop) self.ui.start_btn.clicked.connect(self.start) self.ui.switch_btn.clicked.connect(self.__switch_session) self.ui.save_schedule_btn.clicked.connect(self.__save_schedule_info) self.ui.save_apply_schedule_btn.clicked.connect( self.__save_apply_schedule) # Stylesheet style_sheet_file = os.path.join(os.path.dirname(self.config_file_path), 'style_sheet.txt') with open(style_sheet_file, 'r') as style_file: style_data = style_file.read() self.setStyleSheet(style_data) # Setting initial values self.__total_slots = int((60 / self.SLOT_INTERVALS) * 24) self.__set_schedule_table() self.__set_quote() self.__focus_time, self.__break_time = self.__get_times() # Create support Classes self.__controller = Controller( self.ui.timer_lcd, self.ui.session_img_lb, focus_time=self.__focus_time, break_time=self.__break_time, ) self.__scheduler_handle = SchedulerHandle(self.SLOT_INTERVALS, self.ui.scheduler_info_lb) self.__scheduler_handle.activate_timer.connect(self.__schedule_cmd) self.__scheduler_handle.show_message.connect(self.msg_dialog)
def __init__(self, keeper_sim): """initialisatie main. Args: keeper_sim: (class) adres van draaiende keeper simulatie om variabelen op te halen. """ if DEBUG_VIDEO: self.file = glob("D:\\Stichting Hogeschool Utrecht\\NLE - Documenten\\Test foto's\\new frame\\1.png") # self.file = glob("C:\\Users\\" + os.getlogin() + "\\Stichting Hogeschool Utrecht\\NLE - Documenten\\Test foto's\\V1.3 cam normal Wide angle + ball\\output_fast.avi") self.camera = ImageCapture(file=self.file[0]) else: self.camera = ImageCapture() self.ks = keeper_sim # print(self.ks.screen) if not self.ks.shoot_bool: self.find_contours = FindContours() self.ball_detection = BallDetection() self.WIDTH_IMG = 640 self.HEIGHT_IMG = 360 self.dql = DQLBase() self.que = Queue(2) try: self.con = Controller() self.met_drivers = True except: self.met_drivers = False # self.hl, = plt.plot([], []) self.points_array = [] self.scored = 0 self.old_ball_positions = [] self.reused_counter = 0
def main(): #Inicializamos la conexión a la base de datos controller = kernel.Controller() controller.initDB() #Mostramos la cabecera de la aplicación y el menú inicial cabecera() menu() #Capturamos la primera opción seleccionada opcion = input() while (opcion != '6'): #Listar todos los contactos if (opcion == '1'): listarContactos(controller) #Buscar contacto if (opcion == '2'): buscarContacto(controller) #Añadir contacto if (opcion == '3'): anyadirContacto(controller) #Modificar contacto if (opcion == '4'): modificarContacto(controller) #Eliminar contacto if (opcion == '5'): eliminarContacto(controller) #Volvemos a mostrar el menú de opciones cabecera() menu() opcion = input() #El usuario ha elegido salir del programa, mostramos mensaje de despedida msgSalir()
class main(): #List conversations app = Controller.Controller() app.getConversationList() conversationList = app.conversationList convos = [] for convo in conversationList: convos.append(convo.title) numList = [] counter = 1 for i in range(len(convos)): numList.append(counter) counter += 1 print("###############################################################") print("##### Facebook Messenger Statistics #####") print("###############################################################") print("------ App by Shreyas Sane -------") print("---------------------------------------------------------------") # time.sleep(1) print( "Enter the number of the chat conversation you'd like to get statistics for." ) # time.sleep(2) for i in range(len(convos)): print(numList[i], ". ", convos[i]) # time.sleep(0.005) #Make a selection and pass convoNum = int(input("Enter your selection: ")) - 1 app.setDirPath(conversationList[convoNum].folderName) app.runStuff()
results = [] for src_dir in dirs: for root, dirs, files in os.walk(src_dir): results.append((root, map(lambda f: root + "/" + f, files))) return results setup( name='opendoor', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html version=Controller.local_version(), description='OWASP WEB Directory Scanner', long_description=LONG_DESCRIPTION, # The project's main homepage. url='https://github.com/stanislav-web/OpenDoor', # Author details author='Stanislav WEB', author_email='*****@*****.**', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(), include_package_data=True,
from src import Controller if __name__ == '__main__': Controller()
# simulation properties simulProp = SimulationParameters() simulProp.FinalTime = 1e7 # the time at which the simulation stops simulProp.outputTimePeriod = 1. # the time after the output is generated (saving or plotting) # simulProp.set_outFileAddress(".\\Data\\leakOff") # the disk address where the files are saved # initializing fracture initTime = 0.5 init_param = ("M", "time", initTime) # creating fracture object Fr = Fracture(Mesh, init_param, Solid, Fluid, Injection, simulProp) # create a Controller controller = Controller(Fr, Solid, Fluid, Injection, simulProp) # run the simulation controller.run() # plotting efficiency Fig_lk, Fig_eff = plot_leakOff(simulProp.get_outFileAddress()) t = 2**np.linspace(np.log2(0.5), np.log2(1e7), 30) # solution taken from matlab code provided by Dontsov EV (2016) eff_analytical = np.asarray([ 0.9923, 0.9904, 0.9880, 0.9850, 0.9812, 0.9765, 0.9708, 0.9636, 0.9547, 0.9438, 0.9305, 0.9142, 0.8944, 0.8706, 0.8423, 0.8089, 0.7700, 0.7256, 0.6757, 0.6209, 0.5622, 0.5011, 0.4393, 0.3789, 0.3215, 0.2688, 0.2218, 0.1809, 0.1461, 0.1171 ]) ax_eff = Fig_eff.get_axes()[0]
def test_get_sierpinski_triangle(self): triangle = Controller.get_sierpinski_triangle(self.n, self.d) self.assertIsInstance(triangle, SierpinskiTriangle) self.assertEqual(self.n, len(triangle.triangle))
def main(): app = QApplication(sys.argv) ui = MainWindow() ui.show() controller = Controller(ui) sys.exit(app.exec_())
def main(): c = Controller() c.readFromFile("data") # c.readFromFile("myLang") c.computeFirstOfGrammar() c.computeFollowOfGrammar() c.computeTable() c.analize()
def test_get_pascal_triangle(self): triangle = Controller.get_pascal_triangle(self.n) self.assertIsInstance(triangle, PascalTriangle) self.assertEqual(self.n, len(triangle.triangle))
class Pomodor(QtWidgets.QMainWindow): SLOT_INTERVALS = 15 BACKGROUND_COLOR = QtGui.QBrush(QtGui.QColor(0, 176, 224)) WHITE_COLOR = QtGui.QBrush(QtGui.QColor("white")) def __init__(self, parent=None): super(Pomodor, self).__init__(parent=parent) self.ui = Ui_PomodorWindow() self.ui.setupUi(self) self.config_file_path = src.utils.get_config_file_path() self.__config_data = src.utils.get_config_data() # Connections self.ui.act_set_times.triggered.connect(self.__show_config) self.ui.reset_btn.clicked.connect(lambda: self.__update_timer(False)) self.ui.stop_btn.clicked.connect(self.stop) self.ui.start_btn.clicked.connect(self.start) self.ui.switch_btn.clicked.connect(self.__switch_session) self.ui.save_schedule_btn.clicked.connect(self.__save_schedule_info) self.ui.save_apply_schedule_btn.clicked.connect( self.__save_apply_schedule) # Stylesheet style_sheet_file = os.path.join(os.path.dirname(self.config_file_path), 'style_sheet.txt') with open(style_sheet_file, 'r') as style_file: style_data = style_file.read() self.setStyleSheet(style_data) # Setting initial values self.__total_slots = int((60 / self.SLOT_INTERVALS) * 24) self.__set_schedule_table() self.__set_quote() self.__focus_time, self.__break_time = self.__get_times() # Create support Classes self.__controller = Controller( self.ui.timer_lcd, self.ui.session_img_lb, focus_time=self.__focus_time, break_time=self.__break_time, ) self.__scheduler_handle = SchedulerHandle(self.SLOT_INTERVALS, self.ui.scheduler_info_lb) self.__scheduler_handle.activate_timer.connect(self.__schedule_cmd) self.__scheduler_handle.show_message.connect(self.msg_dialog) @staticmethod def msg_dialog(msg, title='Pomodor'): msg_box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Information, title, msg) msg_box.setStandardButtons(QtWidgets.QMessageBox.Ok) msg_box.exec() def stop(self): self.__controller.stop_timer() def start(self): self.__controller.start_timer() def is_running(self): return self.__controller.is_running() def __schedule_cmd(self, cmd): msg = None if cmd == 'start' and not self.is_running(): self.start() if self.__controller.is_on_break(): self.__switch_session() else: self.__update_timer(False) msg = { 'title': 'Pomodoro Schedule', 'msg': 'Schedule time starts now!' } elif cmd == 'stop' and self.is_running(): self.stop() if not self.__controller.is_on_break(): self.__switch_session() else: self.__update_timer(False) msg = { 'title': 'Pomodoro Schedule', 'msg': 'No time schedule at this time. Timer has been stopped.' } if msg: self.__controller.notify(custom=msg) def __save_apply_schedule(self): self.__save_schedule_info() self.__scheduler_handle.restart_timer() def __switch_session(self): self.__controller.switch_session() def __set_schedule_table(self): week_days = list(calendar.day_name) hour_list = self.__get_hours() hours = [hour.strftime('%H:%M') for hour in hour_list] self.ui.scheduler_table.setRowCount(len(hours)) self.ui.scheduler_table.setVerticalHeaderLabels(hours) self.ui.scheduler_table.setHorizontalHeaderLabels(week_days) self.__set_table_items() def __set_table_items(self): config_data = src.utils.get_config_data() total_columns = self.ui.scheduler_table.columnCount() total_rows = self.ui.scheduler_table.rowCount() for column in range(total_columns).__reversed__(): for row in range(total_rows).__reversed__(): new_item = QtWidgets.QTableWidgetItem() self.ui.scheduler_table.setItem(row, column, new_item) schedule_times = config_data.get('schedule_times', None) if not schedule_times: continue column_item = self.ui.scheduler_table.horizontalHeaderItem( column) day = column_item.text() day_hours = schedule_times.get(day, None) if not day_hours: continue row_item = self.ui.scheduler_table.verticalHeaderItem(row) hour = row_item.text() if hour not in day_hours: continue new_item.setBackground(self.BACKGROUND_COLOR) def __save_schedule_info(self): config_data = src.utils.get_config_data() times_to_add = defaultdict(list) times_to_remove = defaultdict(list) for item in self.ui.scheduler_table.selectedItems(): row_item = self.ui.scheduler_table.verticalHeaderItem(item.row()) column_item = self.ui.scheduler_table.horizontalHeaderItem( item.column()) hour = row_item.text() day = column_item.text() if item.background() == self.BACKGROUND_COLOR: times_to_remove[day].append(hour) item.setBackground(self.WHITE_COLOR) else: times_to_add[day].append(hour) item.setBackground(self.BACKGROUND_COLOR) for day, hours in times_to_add.items(): if day not in config_data['schedule_times']: config_data['schedule_times'][day] = hours config_data['schedule_times'][day].extend(hours) for day, hours in times_to_remove.items(): for hour in hours: config_data['schedule_times'][day].remove(hour) src.utils.save_config_data(config_data) self.ui.scheduler_table.clearSelection() self.msg_dialog('Schedule has been save.') def __get_hours(self): hours = [] current_time = datetime.now() today = datetime(current_time.year, current_time.month, current_time.day, 9, 0) for slot in range(0, self.__total_slots): sc_time = today + timedelta(minutes=self.SLOT_INTERVALS * slot) if sc_time.hour == 23: break hours.append(sc_time) return hours def __show_config(self): self.config_dialog = QtWidgets.QDialog(parent=self) self.config_ui = Ui_pomodor_config() self.config_ui.setupUi(self.config_dialog) self.config_dialog.show() # Set initial values config_data = src.utils.get_config_data() if config_data: self.config_ui.focus_time_sb.setValue(config_data['focus_time']) self.config_ui.break_time_sb.setValue(config_data['break_time']) self.config_ui.quotes_file_txt.setText(config_data['quotes_file']) self.config_ui.facebook_cbx.setChecked( 'facebook' in config_data['sites']) self.config_ui.twitter_cbx.setChecked( 'twitter' in config_data['sites']) self.config_ui.youtube_cbx.setChecked( 'youtube' in config_data['sites']) # connections self.config_ui.save_btn.clicked.connect(self.__save_config_file) self.config_ui.cancel_btn.clicked.connect(self.config_dialog.close) self.config_ui.quotes_search_btn.clicked.connect(self.__file_search) self.config_ui.save_apply_btn.clicked.connect( lambda: self.__update_timer(True)) def __save_config_file(self): config_data = src.utils.get_config_data() focus_time = self.config_ui.focus_time_sb.value() break_time = self.config_ui.break_time_sb.value() quotes_file = self.config_ui.quotes_file_txt.toPlainText() config_data['sites'] = [] if self.config_ui.youtube_cbx.isChecked(): config_data['sites'].append('youtube') if self.config_ui.twitter_cbx.isChecked(): config_data['sites'].append('twitter') if self.config_ui.facebook_cbx.isChecked(): config_data['sites'].append('facebook') config_data['focus_time'] = focus_time config_data['break_time'] = break_time config_data['quotes_file'] = quotes_file src.utils.save_config_data(config_data) self.config_dialog.close() def __update_timer(self, save): if save: self.__save_config_file() self.__focus_time, self.__break_time = self.__get_times() self.__controller.update_controller(self.__focus_time, self.__break_time) def __file_search(self): file_path = QtWidgets.QFileDialog.getOpenFileName()[0] if file_path: self.config_ui.quotes_file_txt.setText(file_path) def __set_quote(self): config_data = src.utils.get_config_data() if not config_data: self.ui.timer_lb.setText( 'Procrastination only leads to frustration') return quotes_file_path = config_data['quotes_file'] with open(quotes_file_path, 'r', encoding='utf8') as quote_file: quotes = quote_file.readlines() random_num = random.randint(0, len(quotes) - 1) if random_num % 2 != 0: random_num -= 1 quote = f'{quotes[random_num]}\n{quotes[random_num+1]}' if len(quotes[random_num]) > 180: font = self.ui.timer_lb.font() font.setPointSize(8) self.ui.timer_lb.setFont(font) self.ui.timer_lb.setText(quote) def __get_times(self): config_data = src.utils.get_config_data() if not config_data: self.__focus_time = 1 self.__break_time = 2 return self.__focus_time = config_data['focus_time'] self.__break_time = config_data['break_time'] return self.__focus_time, self.__break_time
def test_version_action(self): """ Controller.version_action() test """ Config.params['cfg'] = 'setup.cfg' controller = Controller.__new__(Controller) self.assertIsNone(controller.version_action())
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Development Team: Brain Storm Team """ import sys for _ in ['urllib3', 'json2html', 'tabulate', 'importlib']: try: __import__(_) except ImportError as e: sys.exit( """\t\t[!] Several dependencies wasn't installed! Please run pip3 install -r requirements.txt. Details : %s.""" % (error)) if __name__ == "__main__": from src import Controller, SrcError import sys try: bootstrap = Controller() bootstrap.run() except SrcError: sys.exit()
def main(): main_window = Controller.Controller() main_window.mainLoop()
def main(): controller = Controller.Controller()
class Foostronics: """Klasse van de main applicatie. **Author**: \n Daniël Boon \n Kelvin Sweere \n Chileam Bohnen\n Sipke Vellinga\n **Version**: 1.49 \n **Date**: 23-1-2020 """ def __init__(self, keeper_sim): """initialisatie main. Args: keeper_sim: (class) adres van draaiende keeper simulatie om variabelen op te halen. """ if DEBUG_VIDEO: self.file = glob("D:\\Stichting Hogeschool Utrecht\\NLE - Documenten\\Test foto's\\new frame\\1.png") # self.file = glob("C:\\Users\\" + os.getlogin() + "\\Stichting Hogeschool Utrecht\\NLE - Documenten\\Test foto's\\V1.3 cam normal Wide angle + ball\\output_fast.avi") self.camera = ImageCapture(file=self.file[0]) else: self.camera = ImageCapture() self.ks = keeper_sim # print(self.ks.screen) if not self.ks.shoot_bool: self.find_contours = FindContours() self.ball_detection = BallDetection() self.WIDTH_IMG = 640 self.HEIGHT_IMG = 360 self.dql = DQLBase() self.que = Queue(2) try: self.con = Controller() self.met_drivers = True except: self.met_drivers = False # self.hl, = plt.plot([], []) self.points_array = [] self.scored = 0 self.old_ball_positions = [] self.reused_counter = 0 def calibration(self): print("gebruik 'q' om kalibratie te stoppen, en 'n' om de simulatie te starten.") while True: # get new frame from camera buffer _frame = self.camera.get_frame() # set new frame in find_contours object for image cropping self.find_contours.new_img(_frame) # get cropped image from find_contours _field = self.find_contours.get_cropped_field() cv2.imshow("field", self.find_contours.drawing_img) # set height and width parameters self.HEIGHT_IMG, self.WIDTH_IMG, _ = _field.shape # set new cropped image in ball_detection object self.ball_detection.new_frame(_field) # get new ball position coordinates in image pixel values cor = self.ball_detection.getball_pos() cv2.imshow("ball detection", self.ball_detection.frame) # convert image pixel values to simulation values key = cv2.waitKey(5) if key == ord('q'): cv2.destroyAllWindows() return False elif key == ord('n'): cv2.destroyAllWindows() return True def start_get_ball_thread(self): """Opstarten van een nieuw proces die de functie update_ball_position uitvoert. """ if self.calibration(): ball_thread = Thread(target=self.update_ball_position, args=()) ball_thread.daemon = True ball_thread.start() else: self.camera.camera.release() self.ks.running = False sys.exit() def update_ball_position(self): """Opstarten van bal detectie proces dat een afbeelding uit van de gstreamer of van een bestand haalt. Zie ImageCapture voor het ophalen van afbeeldingen, FindContours om het speelveld te schalen en BallDetect voor de bal detectie. """ while True: if not self.ks.running: self.camera.camera.release() self.con.stop_controller_thread() cv2.destroyAllWindows() break if not self.que.full(): # get new frame from camera buffer _frame = self.camera.get_frame() # set new frame in find_contours object for image cropping self.find_contours.new_img(_frame) # get cropped image from find_contours _field = self.find_contours.get_cropped_field() # set height and width parameters self.HEIGHT_IMG, self.WIDTH_IMG, _ = _field.shape # set new cropped image in ball_detection object self.ball_detection.new_frame(_field) # get new ball position coordinates in image pixel values cor = self.ball_detection.getball_pos() # convert image pixel values to simulation values self.que.put((self._convert2_sim_cor(cor[0], cor[1]), self.ball_detection.reused)) cv2.waitKey(1) def _convert2_sim_cor(self, x_p, y_p): """Zet de pixel positie van de beeldherkenning verhoudingsgewijs om naar pixel positie van de simulatie. Args: x_p: (int) x coördinaat van de pixelpositie. y_p: (int) y coördinaat van de pixelpositie. Returns: (tuple) x & y coördinaten van de simulatie. """ # x_simulatie posite x_s = self.map_function(x_p, 0, self.WIDTH_IMG, self.ks.SIM_LEFT, self.ks.SIM_RIGHT) #-19.35, 19.35 #y_s = self.map_function(y_p, 0, self.HEIGHT_IMG, self.ks.SIM_TOP, self.ks.SIM_BOTTOM) #20, 0 y_s = self.map_function(y_p, 0, self.HEIGHT_IMG, self.ks.SIM_BOTTOM, self.ks.SIM_TOP) return (x_s, y_s) def map_function(self, val, in_min, in_max, out_min, out_max): """Map functie (zoals in de Arduino IDE) die input waarde (in_min & in_max) schaald in verhouding naar de output (out_min & out_max). Args: val: (int) waarde die geschaald moet worden. in_min: (int) minimale waarde die de input kan hebben. in_max: (int) maximale waarde die de input kan hebben. out_min: (int) minimale waarde die de output mag krijgen. out_max: (int) maximale waarde die de output mag krijgen. Returns: (int) geschaalde waarde van de input. """ return (val - in_min) * (out_max - out_min) / (in_max - in_min) + out_min def execute_action(self, action, old_action): """Voer de actie uit, die de AI heeft gekozen, op de stappenmotoren. Args: action: (list) acties die de AI gekozen heeft. old_action: (list) de vorige actie die de AI gekozen heeft. """ if not self.con.que.full(): if np.array_equal(action, self.dql.possible_actions[0]): self.ks.control.y = self.ks.KEEPER_SPEED if(self.met_drivers and (not np.array_equal(action, old_action))): self.con.que.put(0) #self.con.jog_motor(0) #JOG_MIN elif np.array_equal(action, self.dql.possible_actions[1]): self.ks.control.y = -self.ks.KEEPER_SPEED if(self.met_drivers and (not np.array_equal(action, old_action))): self.con.que.put(1) #self.con.jog_motor(1) #JOG_PLUS else: self.ks.control.y = 0 self.ks.body.linearVelocity.y = 0 if np.array_equal(action, self.dql.possible_actions[2]): self.ks.control.y = 0 self.ks.body.linearVelocity.y = 0 if(self.met_drivers): self.con.que.put(2) #self.con.stop_motor() #self.con.shoot() if np.array_equal(action, self.dql.possible_actions[3]): self.ks.control.x = 0 self.ks.control.y = 0 self.ks.body.linearVelocity.x = 0 self.ks.body.linearVelocity.y = 0 if(self.met_drivers): self.con.que.put(3) #self.con.stop_motor() def determine_goal(self, vel_x, vel_x_old): """Bepaal of er een goal is gescoord. Args: vel_x: (int) huidige x coördinaat van de simulatie. vel_x_old: (int) vorige x coördinaat van de simulatie. Returns: (tuple) done, goal - done checkt of ronde klaar is met een bool, goal is een int die aantal goals optelt. """ done = 0 goal = 0 if(len(self.old_ball_positions)<4): self.old_ball_positions.append(self.ks.ball.position) else: self.old_ball_positions.pop(0) self.old_ball_positions.append(self.ks.ball.position) if( ((self.ks.ball.position.x < -18.5) and (self.ks.ball.position.y < (self.ks.SIM_BOTTOM*2/3)) and (self.ks.ball.position.y > (self.ks.SIM_BOTTOM*1/3))) or (self.ks.ball.position.x < self.ks.SIM_LEFT) ): if(not self.scored): self.old_ball_positions = [] goal = 1 done = 1 self.ks.goals += 1 self.points_array.append(0) if (len(self.points_array)>100): self.points_array.pop(0) self.ks.ratio = (100*self.points_array.count(1))/len(self.points_array) self.ks.body.position = (-16.72,(self.ks.SIM_BOTTOM/2)) if(self.ks.shoot_bool): self.ks.world.DestroyBody(self.ks.ball) self.ks._reset_ball() self.scored = 1 elif( ((vel_x_old < 0) and (vel_x > 0) and (self.old_ball_positions[0].x < -7) and (self.old_ball_positions[0].y < (self.ks.SIM_BOTTOM*2/3)) and (self.old_ball_positions[0].y> (self.ks.SIM_BOTTOM*1/3))) or (self.ks.shoot_bool and ((abs(self.ks.ball.linearVelocity.x) < 1) or self.ks.ball.linearVelocity.x > 1)) ): self.old_ball_positions = [] goal = 0 done = 1 self.ks.blocks += 1 self.points_array.append(1) if (len(self.points_array)>100): self.points_array.pop(0) self.ks.ratio = (100*self.points_array.count(1))/len(self.points_array) self.ks.body.position = (-16.72,(self.ks.SIM_BOTTOM/2)) if(self.ks.shoot_bool): self.ks.world.DestroyBody(self.ks.ball) self.ks._reset_ball() self.scored = 0 elif(self.scored): self.scored = 0 return done, goal def run(self): """Deze functie wordt na iedere frame aangeroepen en kan gezien worden als de mainloop. """ if(not self.ks.shoot_bool): #print(self.que.get()) self.ks.ball.position, reused = self.que.get() action, old_action, target, vel_x, vel_x_old = self.dql.get_ai_action() self.ks.action = action self.execute_action(action, old_action) done, goal = self.determine_goal(vel_x, vel_x_old) if done: episode_rewards, total_reward = self.dql.prepare_new_round(goal, self.ks.ball, self.ks.body) # print(np.sum(episode_rewards)) # self.hl.set_xdata(np.append(self.hl.get_xdata(), (len(total_reward)-1))) # self.hl.set_ydata(np.append(self.hl.get_ydata(), np.sum(episode_rewards))) # plt.axis([0, len(total_reward), min(total_reward), max(total_reward)]) # plt.draw() # plt.pause(0.0001) # plt.show if(self.met_drivers): #self.con.stop_motor() if not self.con.que.full(): if(self.ks.body.position.y >=8.71): self.con.que.put(4) #self.con.go_home() else: self.con.que.put(5) #self.con.go_home(1) else: self.dql.update_data(done, self.ks.ball, self.ks.body) if(not self.ks.shoot_bool): if(reused): self.reused_counter += 1 if(self.reused_counter > 5): self.ks.ball.position = (200, 200) elif((not reused) and self.reused_counter): self.reused_counter = 0
def setUp(self): self.controller = Controller.__new__(Controller) self.config = CoreConfig