def run(self, code, relation=None, peek_answer=False): """ Runs code over the data of a relation instance. If relation argument is given, the relation is assumed to be a Block of type tuple with the first two elements being the from and to Kind instances and possibly more elements. The instances are pushed to the stack by this method. Optionally, an initial stack can be given. It returns the top of the stack after the last code block (or last executed block on error) is run. All possible errors force this to be a Block of type_error. No valid programs can return a type_error. """ core = Core(code) if relation is not None: question, answer, is_test = relation.data core.register['question'] = question if peek_answer or not is_test: core.register['answer'] = answer *_, ret = core return ret
def __init__(self, filename): infantry = unit_w.Unit('data\\units\\infantry.txt') marines = unit_w.Unit('data\\units\\marines.txt') mob_infantry = unit_w.Unit('data\\units\\mobinf.txt') tank = unit_w.Unit('data\\units\\tank.txt') artillery = unit_w.Unit('data\\units\\artillery.txt') filename = ('data\\battle_maps\\' + str(filename)) self.core = Core() self.units_list = [infantry, marines, mob_infantry, tank, artillery] self.hp_last1 = [ infantry.get_abil('xp', 0), marines.get_abil('xp', 0), mob_infantry.get_abil('xp', 0), tank.get_abil('xp', 0), artillery.get_abil('xp', 0) ] self.hp_last2 = copy.copy(self.hp_last1) self.move_last1 = [ infantry.get_abil('move', 0), marines.get_abil('move', 0), mob_infantry.get_abil('move', 0), tank.get_abil('move', 0), artillery.get_abil('move', 0) ] self.move_last2 = copy.copy(self.move_last1) self.cells_list = self.core.load_battle_cells(filename) self.coord_army1 = self.get_army_coords(0) self.coord_army2 = self.get_army_coords(1)
def main(): map = Map() try: map.get_random_map(MAPS_PATH) except MapError as e: print("Map error:", e) exit(FAILURE) # TODO: Handle multiple map loading retries etc... core = Core(map) core.run()
def PTRun(): maxWeight = Core.setMaxWeight() items = parser.loadItems() VpSM = Core.addMatrixVpS(items) sortMatrix = Core.sortMatrix(VpSM) Core.algo(sortMatrix, maxWeight) Log.d(LL.uptime())
def custom(): ''' This is strictly for testing, invoke with -c, --custom''' c = Core() b = Brain(c) print(c.get_data(["AAPL", "GOOG"], "day", limit=20)) rsi = b.RSI("ROKU", timeframe="15Min") print(rsi)
def live_button(self): """ Action triggered when the 'live' button is pressed """ self.dockwidget.liveButton.setEnabled(False) # if no layer do nothing if not self.dockwidget.checkBoxCorrected.isChecked(): if not self.dockwidget.checkBoxDifference.isChecked(): if not self.dockwidget.checkBoxBrut.isChecked(): ErrorWindow("Erreur selection couche", "Veillez selectionner une couche avant de continuer", "critical") #enable live_button self.dockwidget.liveButton.setEnabled(True) return # init core if self.core is None: # Get the current database selection (in the UI selector) selected = self.dockwidget.databaseSelector.currentText() if selected == "": ErrorWindow("Erreur selection base de donnees", "Veillez selectionner une base de donnees avant de valider", "information") # enable live_button self.dockwidget.liveButton.setEnabled(True) return # Construct the @Core class (Main Class) # The Class need the global information of the database # The Class need to manipulate layers so a reference to the interface (iface) is required self.core = Core( self.database_connection.value(selected + '/host'), self.database_connection.value(selected + '/port'), self.database_connection.value(selected + '/username'), self.database_connection.value(selected + '/password'), self.database_connection.value(selected + '/database'), self.iface ) self.core.connect_init() self.update_layer_list() print("live -> stop") # unbind live event self.dockwidget.liveButton.clicked.disconnect(self.live_button) # change text self.dockwidget.liveButton.setText("Stop") # bind stop event self.dockwidget.liveButton.clicked.connect(self.stop_button) # enable liveButton self.dockwidget.liveButton.setEnabled(True) # disable resetButton self.dockwidget.resetButton.setEnabled(False)
def changer_jeu(nom_jeu): global choix global jeu global partie global plateau_graphique global THEME choix.destroy() plateau_graphique.destroy() jeu = importe(nom_jeu) partie = c.Partie(jeu, joueurs) partie.plateau.initialisation() THEME = {} try: for clef, valeur in partie.plateau.Jeu.THEME.items(): photo = PhotoImage(file=dir + valeur) # ImageTk.PhotoImage(image) THEME[clef] = photo except: print("Pas de Thème configuré") print(THEME) plateau_graphique = affichage_init(partie.plateau, THEME) plateau_graphique.grid(row=0, column=0) partie.plateau.afficher() choix = choix_joueurs(saisie) choix.grid(row=4, column=0) texte.set(text="") texte.update()
def multicore_run_all(self, code, ignore_ret_type=False): """ Runs a code item (possibly after many others without clearing). """ stacks = self.multicore_state['stacks'] registers = self.multicore_state['registers'] pic_lists = self.multicore_state['pic_lists'] for stack, register, pic_list in zip(stacks, registers, pic_lists): core = Core(code, stack, register) try: *_, ret = core except Exception: return Block.new_error('Try/catch caught an exception') if ret.type == Block.type_error or not core.all_right: return ret if ret.type == Block.type_picture: pic_list.append(ret) elif not ignore_ret_type: return Block.new_error('Code item does not return a picture') stack = core.stack register = core.register return Block(None, Block.type_no_error)
def generateOutput(self, target_dir, progress_updater, page_index): target_dir = os.path.join(target_dir, self.entity.name) os.mkdir(target_dir) self.__createSubDirs(target_dir) self.__handled_thumbs = 0 self.__current_idx_page = 0 first_child_name = None if len(self.entity.children) > 0: first_child_name = self.entity.children[0].name while len(self.entity.children) - self.__handled_thumbs > 0: self.__current_idx_page += 1 if self.__current_idx_page > 1: self.__reset() self.updateCssRef(2) self.updateStyleDirRefs(2) self.updateDocTitle() menu_id_href_mapping = Core.getInstance().project.getMenuIdHrefMapping(2) if menu_id_href_mapping: self.updateMenuHrefs(menu_id_href_mapping) self.updateTitleCell(self.entity.title, self.entity.subtitle) self.activateMenuItem(self.entity.parent) self.updateMenuItem(self.entity) self.disableNaviControls(True, False, '%s_sls.html' % first_child_name) self._fillMetaDataTag('') self.addIndexTable() idx_file = 'index.html' if self.__current_idx_page > 1: idx_file = 'index%d.html' % self.__current_idx_page self.writeXHTML(self.html_tree, os.path.join(target_dir, idx_file)) for child in self.entity.children: page_index = child.generateOutput(target_dir, progress_updater, page_index) return page_index
def main(jeu, joueurs): """Initialize the interactive window and lauch the games""" partie = c.Partie(jeu, joueurs) partie.plateau.initialisation() partie.plateau.afficher() global num_tour num_tour = 0 root = Tk() THEME = {} try: for clef, valeur in partie.plateau.Jeu.THEME.items(): #image = Image.open(dir+valeur) photo = PhotoImage(file=dir + valeur) #ImageTk.PhotoImage(image) THEME[clef] = photo except: print("Pas de Thème configuré") print(THEME) saisie = Frame(root) texte = StringVar() message = Label(saisie, textvariable=texte) message.grid(column=0, row=2) action = StringVar(saisie) entree = Entry(saisie, textvariable=action, width=30) def agir(): global num_tour if not (partie.plateau.termine()): if partie.plateau.est_valide(action.get(), num_tour): partie.plateau.next(action.get(), num_tour) update(plateau_graphique, partie.plateau, THEME) texte.set(partie.plateau.message(num_tour, partie.joueurs)) partie.plateau.afficher() num_tour += 1 else: texte.set( partie.plateau.message(num_tour, partie.joueurs) + "\nLe coup entré n'est pas valide") else: texte.set(partie.plateau.resultat(partie.plateau)) if partie.plateau.termine(): texte.set(partie.plateau.resultat(partie.plateau)) print(entree.get()) jouer = Button(saisie, text="Jouer", command=agir) #entree.bind("<Return>", agir) plateau_graphique = affichage_init(partie.plateau, THEME) plateau_graphique.grid(row=0, column=0) entree.grid(column=0, row=0) jouer.grid(column=0, row=1) saisie.grid(row=0, column=1) texte.set(partie.plateau.message(num_tour, partie.joueurs)) root.mainloop()
def _get_cores(self): cores = [] i = 0 while True: if exists(f'/sys/devices/system/cpu/cpu{i}'): cores.append(Core(i)) i += 1 else: break return cores
def __init__(self,map_name): pygame.init() self.core = Core() self.mode = Event_Handler() self.file = 'ingame_temp'#заміна self.file в Core.py #self.map_type - треба замінити в Core.py #self.x_coord_start self.x_coord_end - замінити в Core.py self.battle = Battle('1') self.resources = Resources() self.graphical_logic = Graphical_logic() self.w_event = Events() self.minimap_x =0 self.minimap_y =0 self.count = 0 self.days = 0 self.fraction = 1 # першими ходять червоні self.map_name = map_name self.stage = 0 self.save_load_name = '' self.fractions = [[1, 1, 0, 0, 3, 1],[2, 1, 0, 0, 0, 0]]
def generate_random_core(self, cores, upper_time_delay): for i in range(1, cores + 1, 1): sid = self.generate_unique_sid() name = self.generate_random_name(10) start_time = self.generate_start_time() time.sleep(random.randrange(1, upper_time_delay + 1, 1)) end_time = self.generate_end_time() core = Core(sid, name, start_time, end_time) self.core_list.append(core) print(core)
def main(): clock = threading.Event() memory = Memory() bus = Bus(memory) cores = [Core(1, bus), Core(2, bus), Core(3, bus), Core(4, bus)] bus.set_cores(cores) core_threads = [] for core in cores: thread = threading.Thread(target=core.processor.run, args=(clock, )) thread.start() core_threads.append(thread) mem_thread = threading.Thread(target=memory.run, args=(clock, )) mem_thread.start() os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1" QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling) app = QApplication(sys.argv) window = Window(clock, cores, memory) sys.exit(app.exec_())
def main(): # Clear Screen cls() print("+==================================================================+") print("‖ Intelligent S3 Upload ‖") print("+==================================================================+") # Parse Arguments args = parse_args() # Execution Status & Error status = 0 # 0: SUCCESS | 1: INTERRUPTED | 2: ERROR error = None try: # Store the Start Time start_time = time.time() # Load & Validate Credentials credentials = load_credentials() validate_credentials(credentials) # Init Core Class core = Core(credentials, args.path) # Start Uploading Process core.upload() except Exception as e: status = 2 error = str(e) except KeyboardInterrupt as e: status = 1 print("\n- Upload process interrupted.") if len(str(e)) != 0: print("- Total bytes uploaded: {}".format(e)) finally: overall_time = str(timedelta(seconds=time.time() - start_time)) print("- Overall Time: {}".format(overall_time)) if credentials['slack_url']: slack(credentials['slack_url'], overall_time, status, error)
def build_code_base(output_fn, context): """ Outermost method building everything from scratch. """ cd_base = CodeBase() field = Field(Example) solved = Search.solved_problems() for name in solved.keys(): source = solved[name] code = field.compile(source) x_code = Code(code.data + (BopBack.bopback_tests_verify_answer, )) problem = context.get_problem_startswith(name) for example in problem: core = Core(x_code) question, answer, _ = example.data q_copy = question.data.copy() a_copy = answer.data.copy() core.register['question'] = question core.register['answer'] = answer *_, ret = core assert isinstance(ret, Block) assert ret.type == Block.type_integer assert isinstance(ret.data, int) assert ret.data == 1 assert np.array_equal(q_copy, core.register['question'].data) assert np.array_equal(a_copy, core.register['answer'].data) cd_base.add(code, source, name, question) cd_base.save(output_fn)
def main(): # Clear Screen cls() print( "+==================================================================+") print( "‖ Intelligent S3 Upload ‖") print( "+==================================================================+") # Check Python Version if sys.version_info[0] < 3: print("Python 3 required to run this application") sys.exit() # Parse Arguments args = parse_args() try: # Store the Start Time start_time = time() # Load & Validate Credentials credentials = load_credentials() validate_credentials(credentials) # Init Core Class core = Core(credentials, args.path) # Start Uploading Process core.upload() except Exception as e: print(e) except KeyboardInterrupt as e: print("\n- Upload process interrupted.") if len(str(e)) != 0: print("- Total bytes uploaded: {}".format(e)) finally: overall_time = str(timedelta(seconds=time() - start_time)) print("- Overall Time: {}".format(overall_time))
def __init__(self, hilillos_to_run, quantum): self.__pcb = PCBDataStructure() self.threads_barrier = Barrier(2) self.__dead_barrier = False self.__killing_lock = Lock() # Lock used to kill the barrier self.__waiting_lock = Lock() self.__system_main_memory = MainMemory(self.__pcb, hilillos_to_run) self.__simulation_statistics = SimulationStatistics() self.__core0 = Core(0, self) self.__core1 = Core(1, self) self.__core_count = 2 self.running_cores = 2 self.__system_clock = 0 self.__default_quantum = quantum self.__core_finished = False self.__core_finished_counter = 0 # Data buss, instruction buss, cache 0, cache 1 self.__locks = [Lock(), Lock(), Lock(), Lock()] self.__lock_owner = [-1, -1, -1, -1]
def __generateThumbs(self, album_dir): project = Core.getInstance().project thumbnailer = Thumbnailer.getInstance() slide_thumb_size = thumbnailer.slide_thumb_size thumb_path = os.path.join(album_dir, 'thumbs', '%dx%d' % (slide_thumb_size[0], slide_thumb_size[1]), self.entity.pic_file_name) if not os.path.lexists(thumb_path): thumb = thumbnailer.getThumbnail(self.entity.pic_location, 'slide') thumb.save(thumb_path, 'JPEG') album_thumb_size = thumbnailer.album_thumb_size thumb_path = os.path.join(album_dir, 'thumbs', '%dx%d' % (album_thumb_size[0], album_thumb_size[1]), self.entity.pic_file_name) if not os.path.lexists(thumb_path): thumb = thumbnailer.getThumbnail(self.entity.pic_location, 'album') thumb.save(os.path.join(album_dir, 'thumbs', '%dx%d' % (album_thumb_size[0], album_thumb_size[1]), self.entity.pic_file_name), 'JPEG')
def generateOutput(self, target_dir, progress_updater, page_index): self.updateCssRef(0) self.updateDocTitle() menu_id_href_mapping = Core.getInstance().project.getMenuIdHrefMapping(0) if menu_id_href_mapping: self.updateMenuHrefs(menu_id_href_mapping) self.updateTitleCell(self.entity.title, self.entity.subtitle) self.disableNaviControls(False, False, None) self._copyIframeDir(target_dir) self._copyCustomContentHtmlFile(target_dir) self._addIframe() self.writeXHTML(self.html_tree, os.path.join(target_dir, 'index.html')) for child in self.entity.children: page_index = child.generateOutput(target_dir, progress_updater, page_index) return page_index
def test_successful_end_to_end(): ctx = Context('data') prb = ctx.get_problem_startswith('496994bd') code = Code( (Bebop.bebop_get_question, BopForward.bopforward_pic_all_as_pat, BopForward.bopforward_pat_flip_up_down, Bebop.bebop_get_question, BopForward.bopforward_pic_all_as_pat, BopForward.bopforward_2pat_merge_as_pic)) for example in prb: q, a, _ = example.data core = Core(code) core.register['question'] = q *_, last_block = core assert core.all_right assert len(core.stack) == 1 assert isinstance(last_block, Block) assert last_block.type == Block.type_picture assert np.array_equal(last_block.data, a.data)
def test_Bebop(): b = Bebop() assert isinstance(b, Bebop) assert Bebop.__base__ == object with pytest.raises(KeyError): b.use(Bebop) b = Bebop() code = Code((b.opcode['swap_top2'], )) core = Core(code, stack=[Block.new_integer(19), Block.new_integer(21)]) assert core.all_right assert core.stack[-1].data == 21 ret, = core assert core.all_right assert core.stack[-1].data == 19 assert isinstance(ret, Block) assert ret.type == Block.type_integer assert ret.data == 19 core = Core(code) ret, = core assert core.all_right is False assert core.error_msg == 'swap_top2() with less than two' assert isinstance(ret, Block) assert ret.type == Block.type_error assert ret.data == 'swap_top2() with less than two' code = Code((b.opcode['get_answer'], )) core = Core(code) core.register['answer'] = Block.new_integer(37) ret, = core assert core.all_right assert core.stack[-1].data == 37 assert isinstance(ret, Block) assert ret.type == Block.type_integer assert ret.data == 37
def __init__(self, filename): infantry=unit_w.Unit('data\\units\\infantry.txt') marines=unit_w.Unit('data\\units\\marines.txt') mob_infantry=unit_w.Unit('data\\units\\mobinf.txt') tank=unit_w.Unit('data\\units\\tank.txt') artillery=unit_w.Unit('data\\units\\artillery.txt') filename=('data\\battle_maps\\'+str(filename)) self.core=Core() self.units_list=[infantry,marines,mob_infantry,tank,artillery] self.hp_last1=[infantry.get_abil('xp',0),marines.get_abil('xp',0),mob_infantry.get_abil('xp',0),tank.get_abil('xp',0),artillery.get_abil('xp',0)] self.hp_last2=copy.copy(self.hp_last1) self.move_last1=[infantry.get_abil('move',0),marines.get_abil('move',0),mob_infantry.get_abil('move',0),tank.get_abil('move',0),artillery.get_abil('move',0)] self.move_last2=copy.copy(self.move_last1) self.cells_list=self.core.load_battle_cells(filename) self.coord_army1=self.get_army_coords(0) self.coord_army2=self.get_army_coords(1)
def __init__(self, action): core = Core() if (not action): core.sectionMenu() else: params = self.getParameters(action) get = params.get if hasattr(core, get("action")): getattr(core, get("action"))(params) else: core.sectionMenu()
def generateOutput(self, target_dir, progress_updater, page_index): self.updateCssRef(0) self.updateStyleDirRefs(0) self.updateDocTitle() menu_id_href_mapping = Core.getInstance().project.getMenuIdHrefMapping(0) if menu_id_href_mapping: self.updateMenuHrefs(menu_id_href_mapping) self.updateTitleCell(self.entity.title, self.entity.subtitle) # TODO: Hack alert self.disableNaviControls(False, "http://seycek.eu/style/img/back_hr.png", None) self.__updatePrevNavi() self._copyIframeDir(target_dir) self._copyCustomContentHtmlFile(target_dir) self._addIframe() file_name = "%s.html" % self.entity.name self.writeXHTML(self.html_tree, os.path.join(target_dir, file_name)) return page_index
def generateOutput(self, target_dir, progress_updater, page_index): target_dir = os.path.join(target_dir, self.entity.name) os.mkdir(target_dir) self.__createSubDirs(target_dir) self.__generateAlbumThumbs(target_dir) self.updateCssRef(1) self.updateStyleDirRefs(1) self.updateDocTitle() menu_id_href_mapping = Core.getInstance().project.getMenuIdHrefMapping(1) if menu_id_href_mapping: self.updateMenuHrefs(menu_id_href_mapping) self.activateMenuItem() self.updateTitleCell(self.entity.title, self.entity.subtitle) self.disableNaviControls(True, False, None) self._fillMetaDataTag('') self.__addIndexTable() self.writeXHTML(self.html_tree, os.path.join(target_dir, 'index.html')) for child in self.entity.children: page_index = child.generateOutput(target_dir, progress_updater, page_index) return page_index
def generateOutput(self, target_dir, progress_updater, page_index): self.__copyPicture(target_dir) self.__copyHighresPicture(target_dir) self.__generateThumbs(target_dir) self.updateCssRef(2) self.updateStyleDirRefs(2) self.updateDocTitle() menu_id_href_mapping = Core.getInstance().project.getMenuIdHrefMapping(2) if menu_id_href_mapping: self.updateMenuHrefs(menu_id_href_mapping) self.activateMenuItem(self.entity.parent.parent) self.updateMenuItem(self.entity.parent) self.updateTitleCell(self.entity.title, self.entity.subtitle) self.__addPicture() self.__updateThumbStripe() self.__updateNaviControls() self._fillMetaDataTag(self.entity.exif) file_name = '%s.html' % self.entity.name self.writeXHTML(self.html_tree, os.path.join(target_dir, file_name)) self.__createHihgresHTML(target_dir) self.__createSlideshowHTML(target_dir) return page_index
def __createSlideshowHTML(self, album_dir): file_name = '%s_sls.html' % self.entity.name template = HTMLTemplate(Core.getInstance().project.slideshow_xhtml_template) html_tree = template.HTML for elem in html_tree.getiterator(): if 'id' in elem.attrib and elem.attrib['id'] == 'doctitle': tag = elem tag.text = self.entity.name elif 'id' in elem.attrib and elem.attrib['id'] == 'stop-slsh': tag = elem tag.set('href', '%s.html' % self.entity.name) elif 'id' in elem.attrib and elem.attrib['id'] == 'js-globals': tag = elem tag_text = 'slideshow = true; ' prev = self.entity.getPrevious() if prev: tag_text += 'slideshow_prev = "%s_sls.html" ;' % prev.name next = self.entity.getNext() if next: tag_text += 'slideshow_next = "%s_sls.html";' % next.name else: tag_text += 'slideshow_next = "%s.html";' % self.entity.name tag.text = tag_text elif 'id' in elem.attrib and elem.attrib['id'] == 'hauptzelle': tag = elem table = etree.SubElement(tag, 'table') table.set('id', 'picture-table'); tr = etree.SubElement(table, 'tr') td = etree.SubElement(tr, 'td') td.set('align', 'center') td.set('valign', 'middle') img = etree.SubElement(td, 'img') img.set('src', 'pics/%s' % self.entity.pic_file_name) img.set('alt', self.entity.name) elif 'id' in elem.attrib and elem.attrib['id'] == 'title': elem.text = self.entity.name elif 'id' in elem.attrib and elem.attrib['id'] == 'subbtitle': elem.text = self.entity.subtitle self.writeXHTML(html_tree, os.path.join(album_dir, file_name))
def __createHihgresHTML(self, album_dir): if os.path.lexists(self.entity.highres_location): file_name = '%s_hr.html' % self.entity.name template = HTMLTemplate(Core.getInstance().project.highres_xhtml_template) html_tree = template.HTML for elem in html_tree.getiterator(): if 'id' in elem.attrib and elem.attrib['id'] == 'highres_navi_prev': prev = self.__getPrevWithHighres() if prev: prev_file_name = '%s_hr.html' % prev.name elem.set('href', prev_file_name) elif 'id' in elem.attrib and elem.attrib['id'] == 'highres_navi_close': elem.set('href', '%s.html' % self.entity.name) elif 'id' in elem.attrib and elem.attrib['id'] == 'highres_navi_next': next = self.__getNextWithHighres() if next: next_file_name = '%s_hr.html' % next.name elem.set('href', next_file_name) elif 'id' in elem.attrib and elem.attrib['id'] == 'highres_img': elem.set('src', 'pics/highres/%s' % self.entity.pic_file_name) elif 'id' in elem.attrib and elem.attrib['id'] == 'doctitle': elem.text = self.entity.name self.writeXHTML(html_tree, os.path.join(album_dir, file_name))
from Core import Core from Face import Face from Keys import Keys from Interest import Interest from Name import Name from Data import Data import time import pickle import socket faces = Core.get_all_faces() face = Core.get_face(1) key = Keys() private_key = key.get_private_key() public_key = key.get_public_key() name = "name4" interest = Interest(name) interest.set_signature(private_key) transport = face['transport'] ip=transport['ip_address'] port = transport['port'] face_address = (ip, port) client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) client_socket.bind(('127.0.0.1',0)) client_socket.sendto(pickle.dumps(interest),face_address) time.sleep(1) while True:
def __init__(self): self.core = Core() self.graphical_logic = Graphical_logic() self.battle = Battle('1')
class Graphical_logic: def __init__(self): self.core = Core() def get_type_background_textures(self,x,y,local_list): mass_cell_type = [] for k in range(len(local_list)): type_cell = local_list[k][2] if (type_cell !=3) and (type_cell <6): mass_cell_type.append(type_cell) types = [0,0,0,0,0,0] for k in range(0,len(mass_cell_type)): if mass_cell_type[k] == 0: types[0]+=1; elif mass_cell_type[k] == 1: types[1]+=1; elif mass_cell_type[k] == 2: types[2]+=1; elif mass_cell_type[k] == 4: types[3]+=1; elif mass_cell_type[k] == 5: types[4]+=1; elif mass_cell_type[k] == 6: types[5]+=1; max_cells = max(types) for k in range(0,len(types)): if (max_cells == types[k]): if k <3: return k else: return k+1 def get_current_steps(self,id_army,filename): #повертаємо кількість кроків на даний момент в цій армії info_army = self.core.load_army(filename, id_army) info_ar = self.core.load_armies(filename) return info_army[7] def change_current_steps(self,id_army,filename,current_steps,steps): info_army = self.core.load_army(filename, id_army) res_steps = current_steps+steps if (res_steps<=0): res_steps =0 self.core.change_army(filename, id_army, info_army[1], info_army[2], info_army[3], info_army[4], info_army[5], info_army[6], res_steps, info_army[8]) def get_max_steps(self,id_army,filename): info_army = self.core.load_army(filename, id_army) return info_army[6] def get_all_id_armies_for_current_fraction(self,fraction,filename): list_armies = self.core.load_armies(filename) list_id = [] for i in range(len(list_armies)): if (list_armies[i][8]==fraction): list_id.append(list_armies[i][0]) return list_id def change_all_armies_steps_for_fraction(self,fraction,filename): list_id = self.get_all_id_armies_for_current_fraction(fraction, filename) for i in range(len(list_id)): max_step = self.get_max_steps(list_id[i], filename) current_steps = self.get_current_steps(list_id[i], filename) steps = abs(max_step-current_steps) self.change_current_steps(list_id[i], filename, current_steps, steps) #Fraction: id_fraction,base(0 - false, 1 - true),milk, cookies,farms,mines def add_resources_for_current_fraction(self,fraction,filename): fract = self.core.get_fraction_status(filename, fraction) print fract print 'FRACT' self.core.change_fraction_status(filename, fraction, fract[1], fract[2]+fract[4]*20, fract[3]+fract[5]*50, fract[4], fract[5]) fract = self.core.get_fraction_status(filename, fraction) print fract return fract def troops_generator(self,fraction,filename): fract = self.core.get_fraction_status(filename, fraction) costs = [[1,10],[2,25],[4,40],[9,80],[10,140]] current_resources = [fract[2],fract[3]] used_resources = [0,0] army = [] for i in range(5): used_resources = [int(current_resources[0]*0.4),int(current_resources[1]*0.4)] temp_units1 = used_resources[0]//costs[i][0] temp_units2 = used_resources[1]//costs[i][1] if temp_units1 >=temp_units2: used_resources[0]=costs[i][0]*temp_units1 used_resources[1]=costs[i][1]*temp_units1 army.append(temp_units1) else: used_resources[0]=costs[i][0]*temp_units2 used_resources[1]=costs[i][1]*temp_units2 army.append(temp_units2) current_resources[0] = current_resources[0]-used_resources[0] current_resources[1] = current_resources[1]-used_resources[1] base = self.core.load_base(fraction, filename) print str(base[0]+1)+'v v v'+str(base[0]) bottom_coord = self.core.load_cell(base[0]+1, base[1]+1, filename) print 'bottom coord' print bottom_coord id_army = self.core.create_new_army(filename, army[0], army[1], army[2], army[3], army[4], 20, 20, fraction) self.core.change_cell(bottom_coord[0], bottom_coord[1], bottom_coord[2], fraction, id_army, filename) print 'bottom coord final' bottom_coord = self.core.load_cell(bottom_coord[0], bottom_coord[1], filename)
if args.debug: l = logging.DEBUG if args.quiet: l = logging.CRITICAL if args.output: logging.basicConfig(filename=args.output, level=l) else: logging.basicConfig(stream=stderr, level=l) time_period = None minutes = 1 # DEFAULT - USE MINUTE BARS if args.timeframe: try: minutes = int(args.timeframe) except: logging.critical( "Please enter an integer for minutes. Exiting....") exit() if minutes < 1 or minutes > 1440: logging.critical( "Please enter a number of minutes between 1 and 1440. Exiting...." ) exit() core = Core() brain = Brain(core) platform = Platform(core, brain, minutes) platform.run()
class Event_Handler(): def __init__(self): self.core = Core() self.graphical_logic = Graphical_logic() self.battle = Battle('1') #Уровень шаманизма - 90! NE ПbTauTeCb ПОНЯТb БЕЗНОГNМ def stage_0(self,event,fraction,days,action_to_map_coords,action_to_minimap_coords,last_x,last_y,filename,x_start,y_start): if (event[0]=='map_coords'): try: x_start,y_start = action_to_minimap_coords(last_x,last_y)# ВОТ ТЫ ГДЕ, СЦУКА! except AttributeError: print 'lol' x_start,y_start = action_to_minimap_coords(event[2],event[3])# ВОТ ТЫ ГДЕ, СЦУКА! #print 'Coords = '+str(event[2])+' '+str(event[3]) stage, army_coords,id_army = action_to_map_coords(event[2],event[3],x_start,y_start) return stage,last_x,last_y,fraction,days, army_coords,id_army,x_start,y_start elif (event[0]=='minimap_coords'): x_start,y_start = action_to_minimap_coords(event[2],event[3])# ВОТ ТЫ ГДЕ, СЦУКА! stage = event[1] last_x = event[2] last_y = event[3] return stage,last_x,last_y,fraction,days, 0,0,x_start,y_start elif (event[0]=='save_mode'): stage = event[1] return stage,last_x,last_y,fraction,days, 0,0,x_start,y_start elif (event[0]=='load_mode'): stage = event[1] return stage,last_x,last_y,fraction,days, 0,0,x_start,y_start elif (event[0]=='end_of_army_steps'): print 'end_of_army_steps' return stage,last_x,last_y,fraction,days, 0,0,x_start,y_start elif (event[0]=='base_mode'): stage = event[1] return stage,last_x,last_y,fraction,days, 0,0,x_start,y_start elif (event[0]=='end_of_players_steps'): if fraction == 1: self.graphical_logic.add_resources_for_current_fraction(fraction, filename) self.graphical_logic.change_all_armies_steps_for_fraction(fraction, filename) if (days+2)%10 == 0: print ' pivo' self.graphical_logic.troops_generator(fraction, filename) fraction = 2 return 0,last_x,last_y,fraction,days, 0,0,x_start,y_start elif fraction == 2: self.graphical_logic.add_resources_for_current_fraction(fraction, filename) self.graphical_logic.change_all_armies_steps_for_fraction(fraction, filename) if (days+2)%10 == 0: print 'vodka' self.graphical_logic.troops_generator(fraction, filename) fraction = 1 days +=1 return 0,last_x,last_y,fraction,days, 0,0,x_start,y_start def stage_1(self,event,name_for_saving,filename,action_for_save,reload_window,last_x,last_y): action_for_save(name_for_saving) print 'Lol = '+str(len(event)) stage = event[1] if event[3] == 'continue': if len(name_for_saving) <10: name_for_saving += event[2] action_for_save(name_for_saving) if event[3] == 'backspace': if len(name_for_saving)>0: name_for_saving = name_for_saving[:-1] action_for_save(name_for_saving) if event[3] == 'save': if name_for_saving >2: self.core.save_file(name_for_saving,filename) name_for_saving = '' try: reload_window(last_x,last_y) except AttributeError: reload_window(0,0) if event[3] == 'cancel': name_for_saving = '' try: reload_window(last_x,last_y) except AttributeError: reload_window(0,0) return stage, name_for_saving def stage_2(self,event,name_for_loading,filename,action_for_load,reload_window,last_x,last_y): action_for_load(name_for_loading) print 'Lol = '+str(len(event)) stage = event[1] if event[3] == 'continue': if len(name_for_loading) <10: name_for_loading += event[2] action_for_load(name_for_loading) if event[3] == 'backspace': if len(name_for_loading)>0: name_for_loading = name_for_loading[:-1] action_for_load(name_for_loading) if event[3] == 'save': if name_for_loading >2: self.core.load_file(name_for_loading,filename) name_for_loading = '' try: reload_window(last_x,last_y) except AttributeError: reload_window(0,0) if event[3] == 'cancel': name_for_loading = '' try: reload_window(last_x,last_y) except AttributeError: reload_window(0,0) return stage, name_for_loading def stage_3(self,event,stage,moving_army,filename,id_army,last_x,last_y): armies_list = 0 if (event[0] == 'move_army'): current_steps = self.graphical_logic.get_current_steps(id_army, filename) if current_steps > 0: try: move, stage,last_x,last_y,armies_list = moving_army(event[1],event[2],last_x,last_y) except TypeError: move = False if move == True: self.graphical_logic.change_current_steps(id_army, filename, current_steps, -1) elif (event[0] == 'end_of_army_steps'): stage = event[1] armies_list = 0 return stage,last_x,last_y,armies_list def stage_6(self,event,battle_dialog,stage,reload_window,last_x,last_y,armies_lists): print event list = self.battle.auto_battle(armies_lists[0], armies_lists[1]) print list if event[0] == 'battle_mode': stage = event[1] print stage print event return stage else: stage = 6 return stage
class Battle(): def __init__(self, filename): infantry=unit_w.Unit('data\\units\\infantry.txt') marines=unit_w.Unit('data\\units\\marines.txt') mob_infantry=unit_w.Unit('data\\units\\mobinf.txt') tank=unit_w.Unit('data\\units\\tank.txt') artillery=unit_w.Unit('data\\units\\artillery.txt') filename=('data\\battle_maps\\'+str(filename)) self.core=Core() self.units_list=[infantry,marines,mob_infantry,tank,artillery] self.hp_last1=[infantry.get_abil('xp',0),marines.get_abil('xp',0),mob_infantry.get_abil('xp',0),tank.get_abil('xp',0),artillery.get_abil('xp',0)] self.hp_last2=copy.copy(self.hp_last1) self.move_last1=[infantry.get_abil('move',0),marines.get_abil('move',0),mob_infantry.get_abil('move',0),tank.get_abil('move',0),artillery.get_abil('move',0)] self.move_last2=copy.copy(self.move_last1) self.cells_list=self.core.load_battle_cells(filename) self.coord_army1=self.get_army_coords(0) self.coord_army2=self.get_army_coords(1) #остаток здоровья и остаток хода def find_strength(self, army): strength=0 for i in range(5): strength+=army[i+1]*(self.units_list[i].get_abil('xp',0)+self.units_list[i].get_abil('kick',0)+self.units_list[i].get_abil('move',0)) return strength def chanse(self,army_str1, army_str2): chans=army_str1/float(army_str2) if (chans<0.2): str='Однозначное поражение' elif(chans<0.4): str='Тяжелое поражение' elif(chans<0.6): str='Поражение' elif(chans<0.8): str='Незначительное поражение' elif(chans<1): str='Паритет' elif(chans<1.2): str='Пиррова победа' elif(chans<1.4): str='Тяжелая победа' elif(chans<1.6): str='Победа' elif(chans<1.8): str='Блестящая победа' else: str='Легкая разминка' return str def kick(self,army1,army2,type1,type2,fraction): if (fraction==0): self.move_last1[type1-1]=0#no more moving damag=math.ceil((army1[type1]*randint(3,5)*self.units_list[type1-1].get_abil('kick',0)*self.units_list[type1-1].get_abil('bonus',type2))/4.0)#количество*тычка*бонус last_health=math.modf(((army2[type2+1]*self.units_list[type2].get_abil('xp',0))+self.hp_last2[type2]-damag)/self.units_list[type2].get_abil('xp',0)) if(last_health[1]<0):#если убили self.hp_last2[type2]=0 army2[type2+1]=0 else: self.hp_last2[type2]=last_health[0]*self.units_list[type2].get_abil('xp',0) army2[type2+1]= last_health[1] if (fraction==1): self.move_last2[type1-1]=0#no more moving damag=math.ceil((army1[type1]*randint(3,5)*self.units_list[type1-1].get_abil('kick',0)*self.units_list[type1-1].get_abil('bonus',type2))/4.0)#количество*тычка*бонус last_health=math.modf(((army2[type2+1]*self.units_list[type2].get_abil('xp',0))+self.hp_last1[type2]-damag)/self.units_list[type2].get_abil('xp',0)) if(last_health[1]<0):#если убили self.hp_last1[type2]=0 army2[type2+1]=0 else: self.hp_last1[type2]=last_health[0]*self.units_list[type2].get_abil('xp',0) army2[type2+1]= last_health[1] return army2 def is_in_range(self,coord_army1,coord_army2,attacker,victim): distance_x=coord_army1[attacker][0]-coord_army2[victim][0]-self.units_list[attacker].get_abil('range',0) distance_y=coord_army1[attacker][1]-coord_army2[victim][1]-self.units_list[attacker].get_abil('range',0) in_range_by_x=distance_x<=0 in_range_by_y=distance_y<=0 if (in_range_by_x and in_range_by_y): return True return False def get_alive(self,army): alive_list=[] for i in range(1,6): if (army[i]>0): alive_list.append(i-1) return alive_list def get_vunerable(self,atacker,army2): victim=-1 temp=-1 alive_list=self.get_alive(army2) for i in range(len(alive_list)): if (victim<self.units_list[atacker].get_abil('bonus',alive_list[i])): temp=alive_list[i] victim=self.units_list[atacker].get_abil('bonus',alive_list[i]) return temp def bot_moving(self,unit_number, dir_x, dir_y,fraction): if (fraction==0): temp=self.cells_list[self.coord_army1[unit_number][1]*20+self.coord_army1[unit_number][0]] self.cells_list[self.coord_army1[unit_number][1]*20+self.coord_army1[unit_number][0]][3]=0 self.cells_list[(self.coord_army1[unit_number][1]+dir_y)*20+(self.coord_army1[unit_number][0]-dir_x)][3]=temp[3] self.coord_army1[unit_number][0]+=dir_x self.coord_army1[unit_number][1]+=dir_y return self.coord_army1 elif (fraction==1): temp=self.cells_list[self.coord_army2[unit_number][1]*20+self.coord_army2[unit_number][0]] self.cells_list[self.coord_army2[unit_number][1]*20+self.coord_army2[unit_number][0]][3]=0 self.cells_list[(self.coord_army2[unit_number][1]+dir_y)*20+(self.coord_army2[unit_number][0]-dir_x)][3]=temp[3] self.coord_army2[unit_number][0]+=dir_x self.coord_army2[unit_number][1]+=dir_y return self.coord_army2 def get_army_coords(self,fraction): coord_army=[[0,0],[0,0],[0,0],[0,0],[0,0]] for i in range(len(self.cells_list)): if ((self.cells_list[i][3]>(0+fraction*5))and(self.cells_list[i][3]<(6+fraction*5))): coord_army[self.cells_list[i][3]-fraction*5-1][0]=int(self.cells_list[i][0]) coord_army[self.cells_list[i][3]-fraction*5-1][1]=int(self.cells_list[i][1]) return coord_army def bot_1step(self, army1, army2,army1_coord, army2_coord, fraction,attacker): alive_list=self.get_alive(army2) false_army=[-1,0,0,0,0,0] no_in_range=0#если ни одного в пределах досягаемости за ход, это - просто чтобы топал victim=self.get_vunerable(attacker,army2) victim_chosen=False while(victim_chosen == False): distance_x=army1_coord[attacker][0]-army2_coord[victim][0] distance_y=army1_coord[attacker][1]-army2_coord[victim][1] if (abs(distance_x)+abs(distance_y)-(2*self.units_list[attacker].get_abil('range',0))<self.units_list[attacker].get_abil('move',0)):#если дотопает за ход victim_chosen=True break if(sum(false_army)==-1): false_army=copy.copy(army2) false_army[victim+1]=0 if(sum(false_army)>false_army[0]): victim=self.get_vunerable(attacker,false_army) else: victim_chosen=True victim=self.get_vunerable(attacker,army2) for i in range(self.units_list[attacker].get_abil('move',0)): distance_x=army1_coord[attacker][0]-army2_coord[victim][0]#-self.units_list[attacker].get_abil('range',0) distance_y=army1_coord[attacker][1]-army2_coord[victim][1]#-self.units_list[attacker].get_abil('range',0) in_range_by_x=abs(distance_x)-self.units_list[attacker].get_abil('range',0)<=0 in_range_by_y=abs(distance_y)-self.units_list[attacker].get_abil('range',0)<=0 if (in_range_by_x and in_range_by_y):#если кто-то уже в радиусе атаки army2=self.kick(army1,army2,attacker+1,victim,fraction)#то это его проблемы break list_plase=army1_coord[attacker][1]*20+army1_coord[attacker][0] if (abs(distance_x)>self.units_list[attacker].get_abil('range',0)): if (distance_x<0 and (self.cells_list[list_plase-11][3]==0)): army1_coord=self.bot_moving(attacker, 1, 0,fraction) #move left elif( self.cells_list[list_plase-11][3]==0): army1_coord=self.bot_moving(attacker, -1, 0,fraction) #move right else: if (abs(distance_y)>self.units_list[attacker].get_abil('range',0)): if (distance_y<0 and (self.cells_list[list_plase-1][3]==0)): army1_coord=self.bot_moving(attacker, 0, -1,fraction) #move up elif((self.cells_list[list_plase+1][3]==0)): army1_coord=self.bot_moving(attacker, 0, 1,fraction) #move down def who_wins(self,army1,army2): countwarrs1=0 countwarrs2=0 for i in range(5): countwarrs1+=army1[i+1] countwarrs2+=army2[i+1]#считаем кол-во войск if(countwarrs1>0 and countwarrs2>0): return 0 elif(countwarrs2==0): return 1 else: return 2 def auto_battle(self,army1,army2): #coord_army1 = [[1,0],[3,0],[5,0],[7,0],[9,0]] #coord_army2 = [[1,20],[3,20],[5,20],[7,20],[9,20]] alive_list=self.get_alive(army1) while(self.who_wins(army1,army2)==0): for i in range(5): if (army1[i+1]>0): self.bot_1step(army1, army2, self.coord_army1, self.coord_army2,0,i) if(self.who_wins(army1,army2)>0): break if (army2[i+1]>0): self.bot_1step(army2, army1,self.coord_army2, self.coord_army1,1,i) if(self.who_wins(army1,army2)>0): break #print (self.who_wins(army1,army2)) if(self.who_wins(army1,army2)==1): return army1,army2 return army2,army1 #bat=Battle(1) #bat.find_strength([0,10,0,0,0,0]) #bat.auto_battle([0,100,20,0,0,8],[1,50,20,0,0,4])
#!/usr/bin/env python3 import time import sys from Core import Core if __name__ == "__main__": try: Handler = Core( sys.argv[1] ) # Creates Handler object 'dbname' is passed as command-line argument if Handler.status == "Initialized": Handler.startHandle() # Starts handeling of all locks and buttons print("Started " + time.ctime()) while True: # Updates every Xseconds - passed as command-line argument time.sleep(float(sys.argv[2])) Handler.update() # after the time calls 'update' method print("Updated " + time.ctime()) elif Handler.status == "Error": sys.exit() except IndexError: # Occurs when there are not passed all command-line arguments print( "ERROR\nNo database or update time specified\nusage: sudo python3 Main.py <dbname> <seconds>" ) sys.exit() except Exception as err: # Uknown error print(err) print("EXCEPTION") Handler.DB.close() time.sleep(2)
def __init__(self, usr, pwd, name): Core.__init__(self, usr, pwd, name)
class Battle(): def __init__(self, filename): infantry = unit_w.Unit('data\\units\\infantry.txt') marines = unit_w.Unit('data\\units\\marines.txt') mob_infantry = unit_w.Unit('data\\units\\mobinf.txt') tank = unit_w.Unit('data\\units\\tank.txt') artillery = unit_w.Unit('data\\units\\artillery.txt') filename = ('data\\battle_maps\\' + str(filename)) self.core = Core() self.units_list = [infantry, marines, mob_infantry, tank, artillery] self.hp_last1 = [ infantry.get_abil('xp', 0), marines.get_abil('xp', 0), mob_infantry.get_abil('xp', 0), tank.get_abil('xp', 0), artillery.get_abil('xp', 0) ] self.hp_last2 = copy.copy(self.hp_last1) self.move_last1 = [ infantry.get_abil('move', 0), marines.get_abil('move', 0), mob_infantry.get_abil('move', 0), tank.get_abil('move', 0), artillery.get_abil('move', 0) ] self.move_last2 = copy.copy(self.move_last1) self.cells_list = self.core.load_battle_cells(filename) self.coord_army1 = self.get_army_coords(0) self.coord_army2 = self.get_army_coords(1) #остаток здоровья и остаток хода def find_strength(self, army): strength = 0 for i in range(5): strength += army[i + 1] * (self.units_list[i].get_abil('xp', 0) + self.units_list[i].get_abil('kick', 0) + self.units_list[i].get_abil('move', 0)) return strength def chanse(self, army_str1, army_str2): chans = army_str1 / float(army_str2) if (chans < 0.2): str = 'Однозначное поражение' elif (chans < 0.4): str = 'Тяжелое поражение' elif (chans < 0.6): str = 'Поражение' elif (chans < 0.8): str = 'Незначительное поражение' elif (chans < 1): str = 'Паритет' elif (chans < 1.2): str = 'Пиррова победа' elif (chans < 1.4): str = 'Тяжелая победа' elif (chans < 1.6): str = 'Победа' elif (chans < 1.8): str = 'Блестящая победа' else: str = 'Легкая разминка' return str def kick(self, army1, army2, type1, type2, fraction): if (fraction == 0): self.move_last1[type1 - 1] = 0 #no more moving damag = math.ceil( (army1[type1] * randint(3, 5) * self.units_list[type1 - 1].get_abil('kick', 0) * self.units_list[type1 - 1].get_abil('bonus', type2)) / 4.0) #количество*тычка*бонус last_health = math.modf(( (army2[type2 + 1] * self.units_list[type2].get_abil('xp', 0)) + self.hp_last2[type2] - damag) / self.units_list[type2].get_abil('xp', 0)) if (last_health[1] < 0): #если убили self.hp_last2[type2] = 0 army2[type2 + 1] = 0 else: self.hp_last2[ type2] = last_health[0] * self.units_list[type2].get_abil( 'xp', 0) army2[type2 + 1] = last_health[1] if (fraction == 1): self.move_last2[type1 - 1] = 0 #no more moving damag = math.ceil( (army1[type1] * randint(3, 5) * self.units_list[type1 - 1].get_abil('kick', 0) * self.units_list[type1 - 1].get_abil('bonus', type2)) / 4.0) #количество*тычка*бонус last_health = math.modf(( (army2[type2 + 1] * self.units_list[type2].get_abil('xp', 0)) + self.hp_last1[type2] - damag) / self.units_list[type2].get_abil('xp', 0)) if (last_health[1] < 0): #если убили self.hp_last1[type2] = 0 army2[type2 + 1] = 0 else: self.hp_last1[ type2] = last_health[0] * self.units_list[type2].get_abil( 'xp', 0) army2[type2 + 1] = last_health[1] return army2 def is_in_range(self, coord_army1, coord_army2, attacker, victim): distance_x = coord_army1[attacker][0] - coord_army2[victim][ 0] - self.units_list[attacker].get_abil('range', 0) distance_y = coord_army1[attacker][1] - coord_army2[victim][ 1] - self.units_list[attacker].get_abil('range', 0) in_range_by_x = distance_x <= 0 in_range_by_y = distance_y <= 0 if (in_range_by_x and in_range_by_y): return True return False def get_alive(self, army): alive_list = [] for i in range(1, 6): if (army[i] > 0): alive_list.append(i - 1) return alive_list def get_vunerable(self, atacker, army2): victim = -1 temp = -1 alive_list = self.get_alive(army2) for i in range(len(alive_list)): if (victim < self.units_list[atacker].get_abil( 'bonus', alive_list[i])): temp = alive_list[i] victim = self.units_list[atacker].get_abil( 'bonus', alive_list[i]) return temp def bot_moving(self, unit_number, dir_x, dir_y, fraction): if (fraction == 0): temp = self.cells_list[self.coord_army1[unit_number][1] * 20 + self.coord_army1[unit_number][0]] self.cells_list[self.coord_army1[unit_number][1] * 20 + self.coord_army1[unit_number][0]][3] = 0 self.cells_list[(self.coord_army1[unit_number][1] + dir_y) * 20 + (self.coord_army1[unit_number][0] - dir_x)][3] = temp[3] self.coord_army1[unit_number][0] += dir_x self.coord_army1[unit_number][1] += dir_y return self.coord_army1 elif (fraction == 1): temp = self.cells_list[self.coord_army2[unit_number][1] * 20 + self.coord_army2[unit_number][0]] self.cells_list[self.coord_army2[unit_number][1] * 20 + self.coord_army2[unit_number][0]][3] = 0 self.cells_list[(self.coord_army2[unit_number][1] + dir_y) * 20 + (self.coord_army2[unit_number][0] - dir_x)][3] = temp[3] self.coord_army2[unit_number][0] += dir_x self.coord_army2[unit_number][1] += dir_y return self.coord_army2 def get_army_coords(self, fraction): coord_army = [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]] for i in range(len(self.cells_list)): if ((self.cells_list[i][3] > (0 + fraction * 5)) and (self.cells_list[i][3] < (6 + fraction * 5))): coord_army[self.cells_list[i][3] - fraction * 5 - 1][0] = int( self.cells_list[i][0]) coord_army[self.cells_list[i][3] - fraction * 5 - 1][1] = int( self.cells_list[i][1]) return coord_army def bot_1step(self, army1, army2, army1_coord, army2_coord, fraction, attacker): alive_list = self.get_alive(army2) false_army = [-1, 0, 0, 0, 0, 0] no_in_range = 0 #если ни одного в пределах досягаемости за ход, это - просто чтобы топал victim = self.get_vunerable(attacker, army2) victim_chosen = False while (victim_chosen == False): distance_x = army1_coord[attacker][0] - army2_coord[victim][0] distance_y = army1_coord[attacker][1] - army2_coord[victim][1] if (abs(distance_x) + abs(distance_y) - (2 * self.units_list[attacker].get_abil('range', 0)) < self.units_list[attacker].get_abil( 'move', 0)): #если дотопает за ход victim_chosen = True break if (sum(false_army) == -1): false_army = copy.copy(army2) false_army[victim + 1] = 0 if (sum(false_army) > false_army[0]): victim = self.get_vunerable(attacker, false_army) else: victim_chosen = True victim = self.get_vunerable(attacker, army2) for i in range(self.units_list[attacker].get_abil('move', 0)): distance_x = army1_coord[attacker][0] - army2_coord[victim][ 0] #-self.units_list[attacker].get_abil('range',0) distance_y = army1_coord[attacker][1] - army2_coord[victim][ 1] #-self.units_list[attacker].get_abil('range',0) in_range_by_x = abs(distance_x) - self.units_list[ attacker].get_abil('range', 0) <= 0 in_range_by_y = abs(distance_y) - self.units_list[ attacker].get_abil('range', 0) <= 0 if (in_range_by_x and in_range_by_y): #если кто-то уже в радиусе атаки army2 = self.kick(army1, army2, attacker + 1, victim, fraction) #то это его проблемы break list_plase = army1_coord[attacker][1] * 20 + army1_coord[attacker][ 0] if (abs(distance_x) > self.units_list[attacker].get_abil( 'range', 0)): if (distance_x < 0 and (self.cells_list[list_plase - 11][3] == 0)): army1_coord = self.bot_moving(attacker, 1, 0, fraction) #move left elif (self.cells_list[list_plase - 11][3] == 0): army1_coord = self.bot_moving(attacker, -1, 0, fraction) #move right else: if (abs(distance_y) > self.units_list[attacker].get_abil( 'range', 0)): if (distance_y < 0 and (self.cells_list[list_plase - 1][3] == 0)): army1_coord = self.bot_moving(attacker, 0, -1, fraction) #move up elif ((self.cells_list[list_plase + 1][3] == 0)): army1_coord = self.bot_moving(attacker, 0, 1, fraction) #move down def who_wins(self, army1, army2): countwarrs1 = 0 countwarrs2 = 0 for i in range(5): countwarrs1 += army1[i + 1] countwarrs2 += army2[i + 1] #считаем кол-во войск if (countwarrs1 > 0 and countwarrs2 > 0): return 0 elif (countwarrs2 == 0): return 1 else: return 2 def auto_battle(self, army1, army2): #coord_army1 = [[1,0],[3,0],[5,0],[7,0],[9,0]] #coord_army2 = [[1,20],[3,20],[5,20],[7,20],[9,20]] alive_list = self.get_alive(army1) while (self.who_wins(army1, army2) == 0): for i in range(5): if (army1[i + 1] > 0): self.bot_1step(army1, army2, self.coord_army1, self.coord_army2, 0, i) if (self.who_wins(army1, army2) > 0): break if (army2[i + 1] > 0): self.bot_1step(army2, army1, self.coord_army2, self.coord_army1, 1, i) if (self.who_wins(army1, army2) > 0): break #print (self.who_wins(army1,army2)) if (self.who_wins(army1, army2) == 1): return army1, army2 return army2, army1 #bat=Battle(1) #bat.find_strength([0,10,0,0,0,0]) #bat.auto_battle([0,100,20,0,0,8],[1,50,20,0,0,4])
class Window(): def __init__(self,map_name): pygame.init() self.core = Core() self.mode = Event_Handler() self.file = 'ingame_temp'#заміна self.file в Core.py #self.map_type - треба замінити в Core.py #self.x_coord_start self.x_coord_end - замінити в Core.py self.battle = Battle('1') self.resources = Resources() self.graphical_logic = Graphical_logic() self.w_event = Events() self.minimap_x =0 self.minimap_y =0 self.count = 0 self.days = 0 self.fraction = 1 # першими ходять червоні self.map_name = map_name self.stage = 0 self.save_load_name = '' self.fractions = [[1, 1, 0, 0, 3, 1],[2, 1, 0, 0, 0, 0]] def Main_Window(self): self.display = pygame.display.set_mode((1280,720)) manager = ResManager() pygame.display.set_icon(manager.get_image('icon.png')) pygame.display.set_caption("War for cookies") self.map_type = self.core.load_file(self.map_name,self.file) self.display.fill((220,220,250)) pygame.display.flip() i = 0 def Maps_grid(self): self.big_step = 50 self.big_steps =14 pygame.display.flip()# лол, костЫль def Minimaps_grid(self): if self.map_type == 0: self.step_p = 6 self.steps = 50 elif self.map_type == 1: self.step_p = 3 self.steps = 100 elif self.map_type == 2: self.step_p = 2 self.steps = 150 cell = Rect((800,0),(300,300)) pygame.draw.rect(self.display,(0,0,0),cell,2) pygame.display.flip() def load_cells_list(self): self.cells_list = self.core.load_minimap_cells(self.file) def Minimap(self): colour = self.resources.colours() for i in range(self.steps): for j in range(self.steps): cell = Rect((800+self.step_p*i,self.step_p*j),(self.step_p,self.step_p)) cell_type = self.cells_list[i*self.steps+j][2] pygame.draw.rect(self.display,colour[cell_type],cell,0) pygame.display.flip() self.Minimaps_grid() def game_buttons(self): textures = self.resources.textures_for_menu() for i in range(4): first_textures =textures[i].get_rect() first_textures.center=(1215,90+180*i) self.display.blit(textures[i],first_textures) pygame.display.update() def reload_window(self,x,y): self.Maps_grid() self.Minimaps_grid() self.Minimap() self.Load_part_of_map(x,y) self.game_buttons() pygame.display.flip() def status_army(self,id_army): cell = Rect((900,350),(225,400)) pygame.draw.rect(self.display,(220,220,250),cell,0) textures_default = self.resources.textures_for_army() fraction = self.fraction textures = [] list_army = self.core.load_army(self.file, id_army) for i in range(5): textures.append(textures_default[fraction*5+fraction+i+1]) first_texture = textures[i].get_rect() first_texture.center=(932,370+64*i) self.display.blit(textures[i],first_texture) try: font1 = pygame.font.SysFont("Monospace", 40, bold=True, italic=False) item = str(list_army[i+1]) font1 = font1.render(item,0,(20,20,20)) self.display.blit(font1,(964,350+64*i)) except TypeError: pass pygame.display.flip() def res_view(self,fraction): list_1 = self.core.get_fraction_status(self.file, fraction) cell = Rect((750,350),(140,300+100)) pygame.draw.rect(self.display,(220,220,250),cell,0) font1 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False) item = 'Milk' font1_1 = font1.render(item,0,(20,20,20)) self.display.blit(font1_1,(800,350)) item = str(list_1[2]) font2 = font1.render(item,0,(20,20,20)) self.display.blit(font2,(800,350+40)) item = 'cookies' font3 = font1.render(item,0,(20,20,20)) self.display.blit(font3,(800,350+80)) item = str(list_1[3]) font4 = font1.render(item,0,(20,20,20)) self.display.blit(font4,(800,350+120)) item = 'Farms' font5 = font1.render(item,0,(20,20,20)) self.display.blit(font5,(800,350+160)) item = str(list_1[4]) font6 = font1.render(item,0,(20,20,20)) self.display.blit(font6,(800,350+160+40)) item = 'Mines' font7 = font1.render(item,0,(20,20,20)) self.display.blit(font7,(800,350+200+40)) item = str(list_1[5]) font8 = font1.render(item,0,(20,20,20)) self.display.blit(font8,(800,350+240+40)) def Load_part_of_map(self,x,y): textures = self.resources.textures() textures_army = self.resources.textures_for_army() cells_list,x_coord_start,y_coord_start= self.core.load_cells(x,y,self.file) for i in range(self.big_steps): for j in range(self.big_steps): cell_type = cells_list[i*self.big_steps+j][2] fraction = cells_list[i*self.big_steps+j][3] army = cells_list[i*self.big_steps+j][4] if (cell_type >6) and (cell_type<12) or ((fraction!=0) and (army == 0)): x = cells_list[i*self.big_steps+j][0] y = cells_list[i*self.big_steps+j][1] local_list = self.core.load_cells_for_transparent_textures(x, y,self.file) result_type = self.graphical_logic.get_type_background_textures(x, y, local_list) first_texture = textures[result_type].get_rect() first_texture.center=(45+self.big_step*i,25+self.big_step*j) self.display.blit(textures[result_type],first_texture) if (fraction > 0) and (cell_type == 9): first_texture = textures[cell_type+fraction-1].get_rect() first_texture.center=(45+self.big_step*i,25+self.big_step*j) self.display.blit(textures[cell_type+fraction-1],first_texture) elif((cell_type<3) and (army > 0)): first_texture = textures[cell_type].get_rect() first_texture.center=(45+self.big_step*i,25+self.big_step*j) self.display.blit(textures[cell_type],first_texture) first_texture = textures[cell_type].get_rect() first_texture.center=(45+self.big_step*i,25+self.big_step*j) self.display.blit(textures_army[fraction*5+fraction],first_texture) else: first_texture = textures[cell_type].get_rect() first_texture.center=(45+self.big_step*i,25+self.big_step*j) self.display.blit(textures[cell_type],first_texture) cell = Rect((800+x_coord_start*self.step_p,0+y_coord_start*self.step_p),(self.step_p*14,self.step_p*14)) self.Minimap() pygame.draw.rect(self.display,(0,0,0),cell,2) self.Maps_grid() pygame.display.flip() def event_handler(self): event = self.w_event.get_event(self.stage, self.big_step, self.step_p) self.res_view(self.fraction) if (event != None): if self.stage == 0: try: self.stage,self.last_x,self.last_y,self.fraction,self.days,self.army_coords,self.id_army,self.x_start,self.y_start \ = self.mode.stage_0(event, self.fraction, self.days, self.action_to_map_coords, self.action_to_minimap_coords,self.last_x,self.last_y,self.file,self.x_start,self.y_start) except AttributeError: self.status_army(0) self.stage,self.last_x,self.last_y,self.fraction,self.days,self.army_coords,self.id_army,self.x_start,self.y_start \ = self.mode.stage_0(event, self.fraction, self.days, self.action_to_map_coords, self.action_to_minimap_coords,0,0,self.file,0,0) days = 'Day '+str(self.days+1) fraction_out = str(self.fraction) cell = Rect((800,650),(300,50)) pygame.draw.rect(self.display,(220,220,250),cell,0) font1 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False) font2 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False) font1 = font1.render(days,0,(20,20,20)) self.display.blit(font1,(825,675)) font2 = font2.render(fraction_out,0,(20,20,20)) self.display.blit(font2,(975,675)) pygame.display.update() if self.stage == 1: self.action_for_save(self.save_load_name) if len(event) > 2: try: self.stage,self.save_load_name = self.mode.stage_1(event, self.save_load_name, self.file, self.action_for_save, self.reload_window, self.last_x, self.last_y) except AttributeError: self.stage,self.save_load_name = self.mode.stage_1(event, self.save_load_name, self.file, self.action_for_save, self.reload_window, 0,0) print self.save_load_name if self.stage == 2: self.action_for_load(self.save_load_name) if len(event) > 2: try: self.stage,self.save_load_name = self.mode.stage_2(event, self.save_load_name, self.file, self.action_for_load, self.reload_window, self.last_x, self.last_y) except AttributeError: self.stage,self.save_load_name = self.mode.stage_2(event, self.save_load_name, self.file, self.action_for_load, self.reload_window, 0,0) print self.save_load_name if self.stage == 3: self.stage,self.last_x,self.last_y,self.armies_list = self.mode.stage_3(event, self.stage, self.moving_army,self.file,self.id_army,self.last_x,self.last_y) if self.stage == 4: pass if self.stage == 5: pass if self.stage == 6: self.battle_dialog_window() self.stage = self.mode.stage_6(event, self.battle_dialog_window,self.stage,self.reload_window,self.last_x,self.last_y,self.armies_list) if self.stage == 7: pass if self.stage == 8: pass def action_to_map_coords(self,x,y,last_x,last_y): # self.Load_part_of_map(x,y) cell = self.core.load_cell(y+last_y,x+last_x,self.file) if ((cell[3] == self.fraction) and (cell[4]>0)): stage = 3 army_coords = [y+last_y,x+last_x] id_army = cell[4] self.status_army(id_army) return stage, army_coords, id_army else: return 0,0,0 def moving_army(self,x,y,last_x,last_y):## Диагноз - говнокод 90лвл(2:14 ночи) armies_lists = 0 self.status_army(self.id_army) cell = self.core.load_cell(self.army_coords[0],self.army_coords[1],self.file) if cell[4]!=0: self.id_army = cell[4] print 'army '+str(self.id_army) self.core.change_cell(cell[0],cell[1],cell[2],0,0,self.file) if ((self.army_coords[0]+x>-1) and (self.army_coords[1]+y>-1) and (self.army_coords[1]+y<self.steps) and (self.army_coords[0]+x<self.steps)): cell = self.core.load_cell(self.army_coords[0]+x,self.army_coords[1]+y,self.file) if (((cell[2]>=0) and (cell[2]<3)) and (cell[4] == 0)): self.core.change_cell(self.army_coords[0]+x,self.army_coords[1]+y,cell[2],self.fraction,self.id_army,self.file) self.army_coords[0] += x self.army_coords[1] += y print 'last_x '+str(last_x)+'last_y = '+str(last_y) try: if (self.army_coords[1] - self.x_start >6): self.x_start+=5 last_x = self.x_start+7 if (self.x_start>self.steps-1): self.x_start = self.steps - self.big_steps self.reload_window(last_x,last_y) print 'last_x '+str(last_x)+'last_y = '+str(last_y) elif (self.army_coords[0]- self.y_start >6): self.y_start +=5 last_y = self.y_start+7 if (self.y_start>self.steps-1): self.y_start = self.steps - self.big_steps print 'Event!' self.reload_window(last_x,last_y) print 'last_x '+str(last_x)+'last_y = '+str(last_y) elif (self.army_coords[1] - self.last_x <-6): self.x_start-=5 if (self.x_start<0): self.x_start = 0 last_x = self.x_start+7 self.reload_window(last_x,last_y) print 'last_x '+str(last_x)+'last_y = '+str(last_y) elif (self.army_coords[0]- self.last_y <-6): self.y_start -=5 last_y = self.y_start+7 if (self.y_start<0): self.y_start = 0 print 'Event!' self.reload_window(last_x,last_y) print 'last_x '+str(last_x)+'last_y = '+str(last_y) else: self.reload_window(last_x,last_y) except AttributeError: self.reload_window(0,0) print 'last_x '+str(last_x)+'last_y = '+str(last_y) return True,3, last_x,last_y,0 elif ((((cell[2]>=0) and (cell[2]<3)) and(cell[3]!=self.fraction) and (cell[4] != 0))or ((cell[2]==9) and (cell[3]==self.fraction))): armies_lists = [] stage = 6 armies_lists.append(self.core.load_army(self.file, self.id_army)) temp = [] for i in range(6): temp.append(armies_lists[0][i]) armies_lists[0] = temp self.core.change_cell(self.army_coords[0],self.army_coords[1],cell[2],self.fraction,self.id_army,self.file) cell = self.core.load_cell(self.army_coords[0]+x,self.army_coords[1]+y,self.file) armies_lists.append(self.core.load_army(self.file, cell[4])) temp = [] for i in range(6): temp.append(armies_lists[1][i]) armies_lists[1] = temp return False, stage,last_x,last_y,armies_lists elif (((cell[2]>=7) and (cell[2]<9)) and (cell[3] != self.fraction)): stage = 3 lose_fraction = cell[3] print 'Alert' if lose_fraction > 0: if cell[2] == 7: frac = self.core.get_fraction_status(self.file, lose_fraction) self.core.change_fraction_status(self.file, lose_fraction, frac[1], frac[2], frac[3], frac[4]-1, frac[5]) frac = self.core.get_fraction_status(self.file, self.fraction) self.core.change_fraction_status(self.file, self.fraction, frac[1], frac[2], frac[3], frac[4]+1, frac[5]) self.core.change_cell(cell[0], cell[1], 7, self.fraction, 0, self.file) if cell[2] == 8: frac = self.core.get_fraction_status(self.file, lose_fraction) self.core.change_fraction_status(self.file, lose_fraction, frac[1], frac[2], frac[3], frac[4], frac[5]-1) frac = self.core.get_fraction_status(self.file, self.fraction) self.core.change_fraction_status(self.file, self.fraction, frac[1], frac[2], frac[3], frac[4], frac[5]+1) self.core.change_cell(cell[0], cell[1], 8, self.fraction, 0, self.file) else: if cell[2] == 7: frac = self.core.get_fraction_status(self.file, self.fraction) self.core.change_fraction_status(self.file, self.fraction, frac[1], frac[2], frac[3], frac[4]+1, frac[5]) self.core.change_cell(cell[0], cell[1], 7, self.fraction, 0, self.file) if cell[2] == 8: frac = self.core.get_fraction_status(self.file, self.fraction) self.core.change_fraction_status(self.file, self.fraction, frac[1], frac[2], frac[3], frac[4], frac[5]+1) self.core.change_cell(cell[0], cell[1], 8, self.fraction, 0, self.file) return False, stage,last_x,last_y,armies_lists elif ((cell[3]== self.fraction) and (cell[4]!=0)): list_start = self.core.load_army(self.file,self.id_army) list_end = self.core.load_army(self.file, cell[4]) list_resoult = [] for i in range(len(list_start)-3): if i == 0: list_resoult.append(list_end[i]) else: list_resoult.append(list_start[i]+list_end[i]) list_resoult.append(20) list_resoult.append(0) list_resoult.append(self.fraction) self.core.change_army(self.file, list_resoult[0], list_resoult[1], list_resoult[2], list_resoult[3], list_resoult[4], list_resoult[5], list_resoult[6], list_resoult[7], list_resoult[8]) self.core.change_army(self.file, self.id_army,0,0,0,0,0,0,0,0) cell = self.core.load_cell(self.army_coords[0],self.army_coords[1],self.file) self.core.change_cell(self.army_coords[0],self.army_coords[1],cell[2],0,0,self.file) self.reload_window(last_x,last_y) # elif (((cell[2]>=7)) and (cell[4] == 0)): # stage = 5 # return False, stage,last_x,last_y,armies_lists else: return False,3,last_x,self.last_y,armies_lists def battle_dialog_window(self): textures = self.resources.textures_for_battle_gialog_window() first_textures = textures[0].get_rect() first_textures.center=(450,350) self.display.blit(textures[0],first_textures) for i in range(3): first_textures = textures[i+1].get_rect() first_textures.center=(350+100*i,450) self.display.blit(textures[i+1],first_textures) font1 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False) pygame.display.flip() def winrar_window(self,fraction): textures = self.resources.textures_for_battle_gialog_window() first_textures = textures[0].get_rect() first_textures.center=(450,350) font1 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False) item = u'Fraction '+str() font1 = font1.render(item,0,(20,20,20)) self.display.blit(font1,(385,360)) def action_to_minimap_coords(self,x,y): #вернуть стартовые х и у! self.Load_part_of_map(x,y) cells_list,x_coord_start,y_coord_start = self.core.load_cells(x, y, self.file) cell = Rect((800+x_coord_start*self.step_p,0+y_coord_start*self.step_p),(self.step_p*14,self.step_p*14)) self.load_cells_list() self.Minimap() pygame.draw.rect(self.display,(0,0,0),cell,2) self.Maps_grid() return x_coord_start,y_coord_start def action_for_save(self,text): cell = Rect((360,260),(300,200)) pygame.draw.rect(self.display,(204,204,204),cell,0) cell = Rect((385,280),(250,50)) pygame.draw.rect(self.display,(255,255,204),cell,0) pygame.draw.rect(self.display,(0,0,0),cell,2) filename = pygame.font.SysFont("Times New Roman", 20, bold=False, italic=True) font1 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False) font2 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False) item = u'Press enter for save' item2 = u'Press ESC for exit' font1 = font1.render(item,0,(20,20,20)) self.display.blit(font1,(385,360)) font2 = font2.render(item2,0,(20,20,20)) self.display.blit(font2,(385,410)) filename = filename.render(text,0,(20,20,20)) self.display.blit(filename,(455,290)) pygame.display.update() def action_for_load(self,text): cell = Rect((360,260),(300,200)) pygame.draw.rect(self.display,(204,204,204),cell,0) cell = Rect((385,280),(250,50)) pygame.draw.rect(self.display,(255,255,204),cell,0) pygame.draw.rect(self.display,(0,0,0),cell,2) filename = pygame.font.SysFont("Times New Roman", 20, bold=False, italic=True) font1 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False) font2 = pygame.font.SysFont("Monospace", 20, bold=True, italic=False) item = u'Press enter for load' item2 = u'Press ESC for exit' font1 = font1.render(item,0,(20,20,20)) self.display.blit(font1,(385,360)) font2 = font2.render(item2,0,(20,20,20)) self.display.blit(font2,(385,410)) filename = filename.render(text,0,(20,20,20)) self.display.blit(filename,(455,290)) pygame.display.update() #self.Minimap() # 28x28, 25x25 cells def Rewrite_cell(self): self.event_handler() def Run(self): self.Main_Window() self.load_cells_list() self.Maps_grid() self.game_buttons() self.Minimaps_grid() self.Minimap() self.Load_part_of_map(0,0) while True: self.Rewrite_cell()
from SignClassifier import MLPSignClassifier import sys sys.path.insert(0, 'D:/desktop/TLSB/PersonDetector/PersonDetector') from HaarCascadeProcessor import HaarCascadeProcessor haar = HaarCascadeProcessor() classifier_path = "D:/desktop/TLSB/FirstPyNN/FirstPyNN/MLP/results/nuevasSeñas/sigmoidal/una capa/4/40aug/bestModel78.h5" raro = "D://desktop//TLSB//FirstPyNN//FirstPyNN//MLP//results//primer intento/bestModel80.h5" POR_FAVOR = "D:/desktop/DATASET/2/POR_FAVOR/20191018_105014.mp4" CAFE = "D:/desktop/DATASET/2/CAFE/20191018_104918.mp4" HOLA = "D:/desktop/DATASET/2/HOLA/20191018_104850.mp4" QUERER = "D:/desktop/DATASET/2/QUERER/20191018_105443.mp4" CBBA = "D:/desktop/DATASET/CBBA/20190812_160520.mp4" classifier = MLPSignClassifier(classifier_path) proc = ImageProcessor(300, 0, process_type=ImageProcessor.BLURRY_EDGES, kernel_height=3, kernel_width=3) core = Core(Core.FROM_PATH, path=HOLA, image_processor=proc, classifier=classifier, debug=True, duplicate=True) core.start() #core.capture_from_camera(haar)
def main(): """Set the window with parameters and interactions""" global root root = Tk() side = Frame(root) saisie = Frame(side) restart = Button(side, text="Nouvelle Partie", command=recommencer) global mode global nom_du_jeu global jeu global choix mode = IntVar() nom_du_jeu = StringVar() nom_du_jeu.set("dames") jeu = importe(nom_du_jeu.get()) top = Frame(side) def choix_joueurs(root): fond = Frame(root) if jeu.nb_joueurs == 1: vals = [0, 1] etiqs = ['Humain', 'IA'] for i in range(2): b = Radiobutton(fond, variable=mode, text=etiqs[i], value=vals[i]) b.pack(side='left', expand=1) if jeu.nb_joueurs == 2: vals = [0, 1, 2] etiqs = ['Humain vs Humain', 'Humain vs IA', 'IA vs IA'] for i in range(3): b = Radiobutton(fond, variable=mode, text=etiqs[i], value=vals[i]) b.pack(side='left', expand=1) return fond def parametres(root): fond = Frame(root) vals = [ 'dames', 'demineur', '2048', 'puissance_4', 'morpion', 'echecs', 'othello' ] etiqs = [ 'Dames', 'Démineur', '2048', 'Puissance 4', 'Morpion', 'Echecs', 'Othello' ] for i in range(7): b = Radiobutton(fond, variable=nom_du_jeu, text=etiqs[i], value=vals[i], command=lambda: changer_jeu(nom_du_jeu.get())) b.pack(side='left', expand=1) return fond settings = parametres(top) choix = choix_joueurs(saisie) global partie joueurs = ["Alice", "Bob"] partie = c.Partie(jeu, joueurs) settings.grid() choix.grid(row=4, column=0) partie.plateau.initialisation() partie.plateau.afficher() global num_tour num_tour = 0 global THEME THEME = {} try: for clef, valeur in partie.plateau.Jeu.THEME.items(): photo = PhotoImage(file=dir + valeur) #ImageTk.PhotoImage(image) THEME[clef] = photo except: print("Pas de Thème configuré") print(THEME) global texte texte = StringVar() message = Label(saisie, textvariable=texte) message.grid(column=0, row=2) action = StringVar(saisie) entree = Entry(saisie, textvariable=action, width=30) global plateau_graphique plateau_graphique = affichage_init(partie.plateau, THEME) def changer_jeu(nom_jeu): global choix global jeu global partie global plateau_graphique global THEME choix.destroy() plateau_graphique.destroy() jeu = importe(nom_jeu) partie = c.Partie(jeu, joueurs) partie.plateau.initialisation() THEME = {} try: for clef, valeur in partie.plateau.Jeu.THEME.items(): photo = PhotoImage(file=dir + valeur) # ImageTk.PhotoImage(image) THEME[clef] = photo except: print("Pas de Thème configuré") print(THEME) plateau_graphique = affichage_init(partie.plateau, THEME) plateau_graphique.grid(row=0, column=0) partie.plateau.afficher() choix = choix_joueurs(saisie) choix.grid(row=4, column=0) texte.set(text="") texte.update() jouer = Button(saisie, text="Jouer", command=lambda: agir(action.get())) top.grid(row=0, column=0) plateau_graphique.grid(row=0, column=0) entree.grid(column=0, row=0) jouer.grid(column=0, row=1) restart.grid(column=0, row=2) saisie.grid(row=1, column=0) side.grid(row=0, column=1) texte.set(partie.plateau.message(num_tour, partie.joueurs)) root.mainloop()
from TestConfig import BASE_URL, IMPOSSIBLE_URL from Core import Core from CyFailedCIError import CyFailedCIError from requests.status_codes import codes """ Built from http://pyunit.sourceforge.net/pyunit.html """ import unittest resourceErrorRoot = "urn:cytoscape:ci:copycatLayout-app:v1" _copyLayout = CopyLayout( CyRESTInstance(base_url=BASE_URL)) # assumes Cytoscape answers at base_url _bad_copyLayout = CopyLayout(CyRESTInstance( base_url=IMPOSSIBLE_URL)) # # for verifying proper exception thrown _core = Core( CyRESTInstance(base_url=BASE_URL)) # assumes Cytoscape answers at base_url class CopyLayoutTestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def get_network_view_suids(self): viewSUIDs = [] netSUIDs = _core._cy_caller.execute_get('/v1/networks') for suid in netSUIDs: viewSUIDs.extend( _core._cy_caller.execute_get('/v1/networks/%d/views' % suid))
def __init__(self): self.core = Core()
def main(): args = Args().get_args() Core(args).recommend()
''' Check the Schedule configuration and check the file query before calling occured. ''' cbm1 = CBM1(condition1, 'CBM1',CBM["hostname"],CBM["username"],CBM["RootPassword"],CBM["password"],CBM["port"]) #create two thread within a condition lock server = Server(condition1,'Server',"202.38.35.184","bsmbin","Abcde01!",23,fileDirection,0) server.start() #server start first but the thread will set to wait when acquire the lock cbm1.start() #Though start later but the thread will finish its processing first cbm1.join() server.join() #Main thread wait until the thread above finish their tasks ''' Calling happens with the command sent in Core.And then CBM will check the FIlESYS to findout whether the Billing is in the query ''' cbm2 = CBM2(condition2, 'CBM2',"10.178.28.26","nortel","nortel",22) #create two thread within a condition lock core = Core(condition2,'Core',"10.24.16.134","lisa","lisa",23) cbm2.start() #cbm2 start first but the thread will set to wait when acquire the lock core.start() #Though start later but the thread will finish its processing first core.join() cbm2.join() #Main thread wait until the thread above finish their tasks ''' After the process above , Server will double check the Destination of billing to confirm whether the transfering is success. ''' #time.sleep() #suspend the Program for a while server = Server(condition3,'Server',"202.38.35.184","bsmbin","Abcde01!",23,fileDirection,1) server.start() server.join() print "\033[1;34;40m***Testing is finished!***\033[0m"
from Core import Core from trading_api_wrappers import Buda cr = Core() class Order(): orderList = None def new(self, inMkt, inType, inLimit, inAmount): try: buda = Buda.Auth(cr.k, cr.s) res = buda.new_order(inMkt, inType, "limit", inLimit, inAmount) except Exception: pass def cancel(self, orderId): try: buda = Buda.Auth(cr.k, cr.s) buda.cancel_order(orderId) except Exception: pass def myOrders(self, inMkt, inStatus): try: buda = Buda.Auth(cr.k, cr.s) self.orderList = buda.order_pages(inMkt, None, None, inStatus) except Exception: pass
import cv2 as cv2 import asyncio from Core import Core if __name__ == '__main__': imgParser = Core() imgParser.readFile("cactusmic.png") asyncio.run(imgParser.parseImg()) imgParser.showImg() cv2.waitKey()