def is_favourable_trade(self, data): resources_after_trade = copy.deepcopy(self.board.resources) for card in data.offeredResources.cards: resources_after_trade[Resources(card)] += 1 for card in data.wantedResources.cards: resources_after_trade[Resources(card)] -= 1 needed = COSTS[self.calc_next_purchase()] return self.distance_from_cards( needed, resources_after_trade) < self.distance_from_cards( needed, self.board.resources)
def __init__(self): if PLAY_SOUNDS: pygame.mixer.init(44100, -16, 2, 512) pygame.init() self.screen: pygame.Surface = pygame.display.set_mode((WIDTH, HEIGHT)) self.clock = pygame.time.Clock() self.res = Resources() # Скины self.skins = [ self.res.image_car_red, self.res.image_car_cyan, self.res.image_car_yellow, self.res.image_car_purple, self.res.image_car_green, self.res.image_police_car ] # Игровой прогресс self.save_file = os.path.join(Resources.get_application_path(), 'save.bin') self.completed_levels = 0 self.dollars = 0 self.saved_skins = [0] * len(self.skins) self.saved_skins[0] = 1 self.current_skin = 0 self.get_save() self.asm = AppStateManager(self) self.asm.push_first(MenuState(self.asm, self.res)) self.running = True
def __configure_root(self): self.__root = QtGui.QTreeWidgetItem( [os.path.abspath(self.__database.path)]) self.__root.setIcon(0, Resources("icons/Folder")) self.addTopLevelItem(self.__root) self.__root.setFirstColumnSpanned(True) self.__standard_root = QtGui.QTreeWidgetItem(["Standard objects"]) self.__standard_root.setIcon(0, Resources("icons/Folder")) self.__standard_root.setFirstColumnSpanned(True) self.__plugin_root = QtGui.QTreeWidgetItem(["Plugins"]) self.__plugin_root.setIcon(0, Resources("icons/Folder")) self.__plugin_root.setFirstColumnSpanned(True) self.__root.addChildren([self.__standard_root, self.__plugin_root])
def __init__(self, parent, peb, resist): """ :type parent: QtGui.QWidget :type peb: options.PostExposureBake :type resist: options.structures.Resist """ super(TemperatureProfileBox, self).__init__("Post Exposure Bake (PEB) Temperature Profile", parent) self.__resist = None self.__peb = None self.__hlayout_resist = QtGui.QHBoxLayout() self.__resist_icon = QtGui.QLabel() self.__resist_icon.setFixedSize(24, 24) self.__resist_icon.setPixmap( QtGui.QPixmap(Resources(orm.Resist.icon, "path"))) self.__resist_name = QLabel(self) self.__hlayout_resist.addWidget(self.__resist_icon) self.__hlayout_resist.addWidget(self.__resist_name) self.__hlayout_resist.addStretch() self.__diffusion_length = QtGui.QLabel(self) self.__profile_graph = TemperatureProfileGraph(self) self.__layout = QtGui.QVBoxLayout(self) self.__layout.addLayout(self.__hlayout_resist) self.__layout.addWidget(self.__diffusion_length) self.__layout.addWidget(self.__profile_graph) self.__layout.addStretch() self.setPeb(peb) self.setResist(resist)
class Barracks(Building): cost = Resources({Wood: 150}) size = (3, 3) letter_abbreviation = 'B' kind = 'barracks' time_to_build = 50 def units_which_can_be_built(self): """Returns a list of unit kind strings.""" what_can_be_built = [Pikeman.kind] player = self.player if player.age in ('bronze age', 'iron age'): shields = BronzeShields swords = BronzeSwords if all(s.name in player.things_researched for s in (shields, swords)): what_can_be_built.append(Swordsman.kind) return what_can_be_built def build_unit(self, unit_type): player = self.player if unit_type not in self.units_which_can_be_built(): # This should never happen because the function units_which_can_be_built # is called in in the command_handling/insert_commands.py (in the # function insert_build_unit_command) print("Error! unit_type is not in self.units_which_can_be_built()") return if unit_type == Pikeman.kind: Pikeman(self, player) else: Swordsman(self, player)
def paned_window(self): self.panedwindow = ttk.Panedwindow(self.parent, orient = tk.HORIZONTAL) self.panedwindow.pack(expand = True, fill = tk.BOTH) self.left_pane = ttk.Frame(self.panedwindow, height = root.winfo_screenheight() - 140, relief = tk.SUNKEN) self.middle_pane = ttk.Frame(self.panedwindow, height = (root.winfo_screenheight() - 140), relief = tk.SUNKEN) self.right_pane = ttk.Frame(self.panedwindow, height = (root.winfo_screenheight() - 140), relief = tk.SUNKEN) self.panedwindow.add(self.left_pane, weight = 1) self.panedwindow.add(self.middle_pane, weight = 1) self.panedwindow.add(self.right_pane, weight = 10) self.panedwindow_left = ttk.Panedwindow(self.left_pane, orient = tk.VERTICAL) self.panedwindow_left.pack(expand = True, fill = tk.BOTH) self.pane_projects = ttk.Frame(self.panedwindow_left, height = (root.winfo_screenheight() - 140) / 2, relief = tk.SUNKEN) self.pane_actions = ttk.Frame(self.panedwindow_left, height = (root.winfo_screenheight() - 140) / 2, relief = tk.SUNKEN) self.panedwindow_left.add(self.pane_projects, weight = 1) self.panedwindow_left.add(self.pane_actions, weight = 1) self.panewindow_middle = ttk.PanedWindow(self.middle_pane, orient = tk.VERTICAL) self.panewindow_middle.pack(expand = True, fill = tk.BOTH) self.pane_canvas = ttk.Frame(self.panewindow_middle, relief = tk.SUNKEN) self.pane_resources = ttk.Frame(self.panewindow_middle, width = 100, relief = tk.SUNKEN) self.panewindow_middle.add(self.pane_canvas, weight = 5) self.panewindow_middle.add(self.pane_resources, weight = 1) self.menubar = Menubar(self.parent) self.properties = Properties(self.right_pane) self.canvas = Canvas(self.properties) self.toolbar = Toolbar(self.pane_canvas, self.canvas) self.project_explorer = ProjectExplorer(self.pane_projects) self.canvas.create_Ui(self.pane_canvas) self.actions = Actions(self.pane_actions, self.canvas, self.properties) self.resources = Resources(self.pane_resources)
def select_oldest(cloud, args): if cloud and args is not None: resources = Resources(cloud) if isinstance(args.blacklist, str): resources.blacklist.append(args.blacklist) age_resources = SelectAgeRelatedResources(cloud) age_resources.select_old_instances( datetime.timedelta(hours=args.old_active), datetime.timedelta(hours=args.old_inactive), datetime.timedelta(days=args.old_permanent), datetime.timedelta(hours=args.old_inerrror)) old_resources = age_resources.get_selection() new_search_prefix = None oldest = None if 'instances' in old_resources: for instance in old_resources['instances']: rec = old_resources['instances'][instance] if rec is None: continue if oldest is None or oldest > rec['created_on']: oldest = rec['created_on'] new_search_prefix = rec['name'] logging.info( 'Found Old instance [{}] created on [{}] age [{}]'.format( rec['name'], rec['created_on'], str(rec['age']))) if oldest is not None: substring = get_substr_from_name(new_search_prefix) resources.select_resources(substring) return resources return None
def __init__(self, conf_path): self.logger = logging.getLogger(type(self).__name__) # Context initialisation self._rsc = Resources(conf_path) self._event_queue = Queue() self._init_playlist() self._init_soundcard() lcd = self._init_lcd() power_button = PowerButton(self._rsc.power_switch, self._rsc.power_led, None) power_button.callback = self._power_callback station_gpios = self._rsc.station_button self._station_button = RotaryEncoder(station_gpios[0], station_gpios[1], station_gpios[2], callback=self._station_callback) volume_gpios = self._rsc.volume_button self._volume_button = RotaryEncoder(volume_gpios[0], volume_gpios[1], volume_gpios[2], callback=self._volume_callback) self._wifi_thread = WifiThread(self._wifi_callback) self._ctxt = RadioContext(self._rsc, lcd, power_button, self._station_button, self._volume_button, self._wifi_thread, self._event_queue) self._on_state = OnState(self._ctxt, self) self._off_state = OffState(self._ctxt, self) self._bt_state = BluetoothState(self._ctxt, self) self._state = None
def info(user, password, machine, mongo, dt_string): server= machine["name"] owner = machine["owner"] print("working on server " + server) resource = Resources(server, owner, dt_string) conn = Connection(server, user, password) try: pythoncom.CoInitialize() conn.register_physical() except Exception as e: print("connection issues with physical namespace " + server) print(e) mongo.update("systems", {"server": server}, json.loads(str(resource))) return resource.physical_properties = PhysicalProperties(conn.physical_connection, get_login=True) print("got physical info of " + server) try: conn.register_virtual() resource.virtual_properties = VirtualProperties(conn.virtual_connection) for vm in resource.virtual_properties.vms_list: v = VM(conn.virtual_connection, vm) resource.virtual_properties.register_vm(v) print("got virtual info of " + server) resource.physical_properties.virtualization = resource.virtual_properties.virtualization except Exception as e: resource.physical_properties.virtualization = "disabled" print("Did not find virtual namespace on " + server) print(e) #print(resource) mongo.update("systems", {"server": server}, json.loads(str(resource)))
def __init__(self, town_name="", wood=0, oil=0, water=0, discontent=100): ''' Constructor ''' self.__town_name = town_name self.town_resources = Resources(wood, oil, water) self.__discontent = discontent
def check_variable(self, item): index = item.text(InputVariablesTree.INDEX_COLUMN) name = item.text(InputVariablesTree.NAME_COLUMN) item.setIcon(InputVariablesTree.NAME_COLUMN, Resources("icons/Ok")) self.set_selectable(item, False) variable = self.variable_by_indx(index) self.clearSelection() return name, index, variable
def handler_event(event, context): """Handle CloudWatch Event rule.""" resources = Resources() try: resources.apply_tags_from_event(event) except Exception as e: print(e) raise
class BronzeArmorPlates(ResearchObject): num_turns_to_completion = 3 cost = Resources({Bronze: 150, Gold: 60}) name = 'bronze armor plates' def research_completed(self, player): player.messages += 'You researched bronze armor plates.\n' player.things_researched.add(self.name)
class BronzeSwords(ResearchObject): num_turns_to_completion = 3 cost = Resources({Bronze: 140, Gold: 55}) name = 'bronze swords' def research_completed(self, player): player.messages += 'You researched bronze swords.\n' player.things_researched.add(self.name)
class BronzeChainMailArmor(ResearchObject): num_turns_to_completion = 4 cost = Resources({Bronze: 150, Gold: 60}) name = 'bronze chainmail armor' def research_completed(self, player): player.messages += 'You researched bronze chainmail armor.\n' player.things_researched.add(self.name)
class BronzeTippedSpears(ResearchObject): num_turns_to_completion = 3 cost = Resources({Bronze: 100, Gold: 50}) name = 'bronze tipped spears' def research_completed(self, player): player.messages += 'You researched bronze tipped spears.\n' player.things_researched.add(self.name)
class IronShields(ResearchObject): num_turns_to_completion = 3 cost = Resources({Iron: 150, Gold: 60}) name = 'iron shields' def research_completed(self, player): player.messages += 'You researched iron shields.\n' player.things_researched.add(self.name)
def update_vertex(new_vertex_info): print("update_vertex") loc = new_vertex_info.hexCorner vertex_index = BOARD.find_vertex_index_by_coordinates(loc.x, loc.y, loc.z) vertex = BOARD.vertices[vertex_index] if vertex is None: raise ValueError("Given coordinates don't exist on the board.") vertex.owner = new_vertex_info.owner vertex.buildingType = new_vertex_info.buildingType if vertex.owner == PLAYER_COLOR: # Update own building information if vertex.buildingType == 1: BOARD.own_settlements.append(vertex_index) if vertex.buildingType == 2: BOARD.own_settlements.remove(vertex_index) BOARD.own_cities.append(vertex_index) # Update production tiles = BOARD.vertex_tiles[vertex_index] for tile_index in tiles: tile = BOARD.tiles[tile_index] if hasattr(tile, "_diceProbability"): BOARD.own_production[Resources( tile.tileType)] += tile._diceProbability # Update bank trades if vertex.harborType != 0: BOARD.own_harbors.add(vertex.harborType) if vertex.harborType == 1: for resource in Resources: if BOARD.bank_trades[resource] > 3: BOARD.bank_trades[resource] = 3 else: BOARD.bank_trades[Resources(vertex.harborType - 1)] = 2 # Remove neighbour vertices from future settlement placement neighbours = BOARD.adjacency_map[vertex_index] for neighbour in neighbours: print("Restricting neighbour: {0}".format(neighbour["vertex_index"])) BOARD.vertices[ neighbour["vertex_index"]].restrictedStartingPlacement = True
def main(): cfg = Config() fsm = GameFsm(cfg) res = Resources(cfg) res.load_all() fsm.set_state(PacmanGame(cfg, res)) pygame.display.set_caption("Pacman4two") pygame.mouse.set_visible(not cfg.fullscreen) fsm.run()
class IronAge(ResearchObject): num_turns_to_completion = 8 cost = Resources({Food: 600, Wood: 700, Gold: 300, Bronze: 300}) name = 'iron age' def research_completed(self, player): player.age = 'iron age' player.messages += 'You have advanced to the Iron Age!\n' player.things_researched.add(self.name)
class BronzeAge(ResearchObject): num_turns_to_completion = 8 cost = Resources({Wood: 700, Stone: 300}) name = 'bronze age' def research_completed(self, player): player.age = 'bronze age' player.messages += 'You have advanced to the Bronze Age!\n' player.things_researched.add(self.name)
class IronAxes(ResearchObject): num_turns_to_completion = 2 cost = Resources({Iron: 130, Gold: 20}) name = 'iron axes' def research_completed(self, player): player.collecting_capacity[Wood] += 2 player.messages += 'You researched iron axes.\n' player.things_researched.add(self.name)
def read(self): self.debug_log("Reading resources from %s" % self.projectroot) result = Resources() self._read_manifestfile(result) # Find dirs (http://stackoverflow.com/a/142535) for dirname in os.walk(self.resourceroot).next()[1]: self._read_dir(dirname, result) return result
def main(): '''Main function of the script''' parser = argparse.ArgumentParser() parser.add_argument('--all', '-a', action='store_true') parser.add_argument('--interactive', '-i', action='store_true') args = parser.parse_args() logger = CliLogger() screen = Screen() analytics = Analytics(logger) resources = Resources() analytics.ignore = ANALYTICS_IGNORE resources.load(analytics) if args.interactive: handle = wait_league_window(logger, (0, 0, 1024, 768)) screen.d3d.capture(target_fps=10, region=find_rect(handle)) while True: if keyboard.is_pressed('x'): cv2.destroyAllWindows() screen.d3d.stop() break img = screen.d3d.get_latest_frame() if img is None: continue try: img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) objs = tick(logger, analytics, resources, img) draw_objects(img_bgr, objs, wait=False, title='League Vision - Interactive') logger.log('Press and hold x to exit bot.') except NoCharacterInMinimap: pass logger.log('-' * 50) time.sleep(1) return if args.all: files = glob.glob('screenshots/*.png') else: files = glob.glob('screenshots/*.png')[:1] for file in files: img_bgr = cv2.imread(file) img = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) try: objs = tick(logger, analytics, resources, img) logger.log('Press x to exit.') except NoCharacterInMinimap: pass logger.log('-' * 50) if draw_objects(img_bgr, objs, title=f'League Vision - {file}') == 120: break
def __init__(self): self.resources = Resources() self.number_of_tiles = 10 self.tile_size = self.resources.floor_size self.size = self.tile_size * self.number_of_tiles self.tiles = [] self.floors = [] self.walls = [] self.turn_count = 0
def stage(self, stage_name): if stage_name is not None: node = self.__item_by_name(stage_name) node.setIcon(OutputVariableTree.NAME_COLUMN, Resources("icons/Ok")) self.__current_stage = self.__stages[stage_name] elif self.__current_stage is not None: node = self.__item_by_name(self.__current_stage.name) node.setIcon(OutputVariableTree.NAME_COLUMN, QtGui.QIcon()) self.__current_stage = None
def _create_button(self, icon_directory, handler): button = QtGui.QPushButton(str(), self) button.setIcon(Resources(icon_directory)) button.setIconSize(QtCore.QSize(26, 26)) button.setFixedSize(QtCore.QSize(36, 36)) button.setEnabled(False) connect(button.clicked, handler) self.__header_layout.addWidget(button) return button
def __init__(self, login, pwd, driver): BI.bot = self self.AccLogin = login self.AccPassword = pwd self.browser = driver self.name = '???' self.resources = Resources() self.text_output = []
def updateResources(self): bs = BeautifulSoup(bot.browser.page_source, features="html.parser") metal = bs.find('span', {'id': 'resources_metal'}).getText() crystal = bs.find('span', {'id': 'resources_crystal'}).getText() deuter = bs.find('span', {'id': 'resources_deuterium'}).getText() energy = bs.find('span', {'id': 'resources_energy'}).getText() self.resources = Resources(metal, crystal, deuter, energy)
def discovery_apply(): resources = Resources() #resources.apply_tags_instances() resources.apply_tags_volumes() resources.show_report() resources.add_metrics() resources.aws.push_metrics()