def __init__(self, screen, angle, x, y, sizey, team, flags, strength, play=True, defense=False): super().__init__() if team == "green": file1, file2, fileFlag, fileBall = greenCannon elif team == "blue": file1, file2, fileFlag, fileBall = blueCannon coords = np.array([x, y], dtype=float) self.troops = [] for i in range(sizey): """ x displacement from center of Battery based on count shiftx increases with count with a period of sizey, creating a row of soldiers with a length of sizey """ shifty = C_GAPY * ((i % sizey) - sizey // 2) shiftx = 0 self.troops.append(Cannon(screen, angle, shiftx, shifty, strength, file1, file2, fileBall, team, coords, defense)) self.flag = Flag(screen, (x, y), angle, fileFlag, play) flags.append(self.flag) # 0,1=click,release to show buttons, 2,3=click,release to select self.showOrders = 0 # self.bayonetButton = Button(screen, "Bayonets") self.healthDisp = Button(screen, str(self.health)) self.play = play self.team = team self.oldUnits = [] # used to id object for testing, not meant to be seen/used self.id = file1
def display_flags(self): """ Convenience method to handle tabular display of flags set by this user. Presently, flags only refer to Galaxy exports. The absence of flags is noted with a message. Note that a user may have an existence on the iRODS system without ever having exported to it. """ self.generate_related_flags() Flag.display(self.flags, False, True)
def display_flags(self): """ Convenience method to handle tabular display of flags in the workspace. Presently, flags only refer to Galaxy exports. The table always appears but the absence of flags is noted with a message. This listing of flags shows the exporter but no messages in the case of a failed export. That information is available via a user_report parameterized with the exporter's email. """ self.generate_related_flags() Flag.display(self.flags, True, False)
def add_items(): """ Initialize all items to be added to the model""" # create all instances of goombas model.items.append(Goomba(model, 700, 300, -0.1, 0)) model.items.append(Goomba(model, 800, 300, -0.1, 0)) model.items.append(Goomba(model, 1000, 300, -0.1, 0)) model.items.append(Goomba(model, 1300, 300, -0.1, 0)) model.items.append(Goomba(model, 1500, 300, -0.1, 0)) model.items.append(Goomba(model, 1700, 300, -0.1, 0)) model.items.append(Goomba(model, 2800, 300, -0.1, 0)) model.items.append(Goomba(model, 3000, 300, -0.1, 0)) # create all instances of pipes model.items.append(Pipe(model, 800, 425, height=125)) model.items.append(Pipe(model, 2000, 425, height=125)) # create all instances of bricks in the air model.items.append(Air_Bricks(model, 550, 450)) model.items.append(Air_Bricks(model, 1000, 450)) model.items.append(Air_Bricks(model, 1400, 450)) model.items.append(Air_Bricks(model, 2600, 450)) # create the flag and castle model.items.append(Flag(model, length - 275, 250)) model.items.append(Castle(model, length - 200, 350)) # add clouds to display for n in range(1, length, 400): model.items.append(Cloud(x=n, y=random.randint(50, 250)))
def generate_related_flags(self): """ Generates a list of Flag objects, sorted by exported dataset create time, associated with this user. """ flags = self.manager.get_flag_dataobj_names_by_user(self.id) self.flags = [Flag(self.dashboard, flag) for flag in flags] self.flags.sort(key=lambda item: item.exported)
def refresh(self): '''Refetch instance data from the API. ''' response = requests.get('%s/categories/%s' % (API_BASE_URL, self.name)) attributes = response.json() self.ancestors = [Category(name) for name in attributes['ancestors']] self.contents = WikiText(attributes['contents_raw'], attributes['contents_rendered']) self.description = attributes['description'] self.guides = [] for guide in attributes['guides']: self.guides.append(Guide(guide['guideid'])) # Unlike guides, categories return flags as a dict, keyed by flagid. # *Except* when it's empty, in which case we get an empty list due to # PHP's json_encode() not knowing the difference between an empty array # and an empty dict. flags = dict(attributes['flags']).values() self.flags = [Flag.from_id(flag['flagid']) for flag in flags] self.image = Image( attributes['image']['id']) if attributes['image'] else None self.locale = attributes['locale'] #self.parts = attributes['parts'] #self.solutions = attributes['solutions'] self.title = attributes['display_title']
def __init__(self, screen, angle, x, y, sizex, sizey, team, flags, strength, play=True, defense=False): super().__init__() if team == "green": fil1, fil2, fil3, fileFlag = greenImages elif team == "blue": fil1, fil2, fil3, fileFlag = blueImages coords = np.array([x, y], dtype=float) self.troops = [] # self.maxSize = sizex * sizey # add infantry to company for i in range(sizex * sizey): """ x, y displacement from center of Company based on count shiftx increases with count with a period of sizex, creating a row of soldiers with a length of sizex shifty increases when count increases by sizex, starting a new row of soldiers every sizex soldiers """ shifty = I_GAPY * ((i % sizey) - sizey // 2) shiftx = I_GAPX * ((i // sizey) - sizex // 2) self.troops.append( Infantry(screen, angle, shiftx, shifty, strength, team, fil1, fil2, fil3, coords, play, defense)) self.flag = Flag(screen, (x, y), angle, fileFlag, play) flags.append(self.flag) # 0,1=click,release to show buttons, 2,3=click,release to select self.showOrders = 0 self.bayonetButton = Button(screen, "Bayonets") self.carreButton = Button(screen, "Carre") self.lineButton = Button(screen, "Line") self.healthDisp = Button(screen, str(self.health)) self.play = play self.team = team self.formation = "Line" self.oldUnits = [] # used to id object for testing, not meant to be seen/used self.id = fil1
def enter(): global player global objectList global backGround global flag global enemyList global music music = load_music('sound\\stage.mp3') music.set_volume(60) music.repeat_play() backGround = BackGround(1) game_world.add_object(backGround, 0) for i in range(10): for k in range(20): if tile_type[i][k] is 3: crushBlockList.append(CrushBlock((mapFirst + image_sizeW * k, mapTop - i * image_sizeH))) elif tile_type[i][k] is 4: lebberList.append(Lebber((mapFirst + image_sizeW * k, mapTop - i * image_sizeH), tile_type[i][k])) elif tile_type[i][k] is 5: lebberList.append(Lebber((mapFirst + image_sizeW * k, mapTop - i * image_sizeH), tile_type[i][k])) elif tile_type[i][k] is 6: lebberList.append(Lebber((mapFirst + image_sizeW * k, mapTop - i * image_sizeH), tile_type[i][k])) elif tile_type[i][k] is 7: player = Ohdam((mapFirst + image_sizeW * k, mapTop - i * image_sizeH)) elif tile_type[i][k] is 8: enemyList.append(Monster1((mapFirst + image_sizeW * k, mapTop - i * image_sizeH))) elif tile_type[i][k] is 9: flag = Flag((mapFirst + image_sizeW * k, mapTop - i * image_sizeH)) elif tile_type[i][k] is 0: pass else: flourBlockList.append( FlourBlock((mapFirst + image_sizeW * k, mapTop - i * image_sizeH), tile_type[i][k])) game_world.add_object(flag, 5) game_world.add_objects(lebberList, 1); game_world.add_objects(flourBlockList, 3); game_world.add_objects(crushBlockList, 4); game_world.add_objects(enemyList, 2); game_world.add_object(player, 6) for i in range(0, 3): objectList.append(Apple((32 + 64 * 6 + i * 64, 608))) for i in range(0, 3): objectList.append(Apple((32 + 64 * 6 + i * 64, 480))) for i in range(0, 3): objectList.append(Apple((32 + 64 * 6 + i * 64, 352))) for i in range(0, 3): objectList.append(Apple((32 + 64 * 13 + i * 64, 480))) for i in range(0, 3): objectList.append(Apple((32 + 64 * 13 + i * 64, 352))) for i in range(0, 3): objectList.append(Apple((32 + 64 * 14 + i * 64, 608))) for i in range(0, 15): objectList.append(Apple((32 + 64 * 4 + i * 64, 160))) game_world.add_objects(objectList, 7); pass
def parse_flag_chunk(chunk: list, colors_dict: dict, names: dict) -> Flag: name = re.match(r'[A-Z]*_*[A-Z]*', chunk[0])[0] chunk.pop(0) try: name = names[name] except Exception: pass # scan for the background elements background = re.split( r'(colored_emblem|texture_emblem|textured_emblem)\s*=\s*{', ''.join(chunk))[0] background = '\n'.join(background.split('\t')) # parsing pattern pattern = re.findall(r'pattern\s*=\s*"?.*"?', background) pattern = re.findall(r'[A-z0-9]*[.]tga', pattern[0])[0] # parsing background colors colors = re.findall(r'color[0-9]\s*=\s*"?.*"?(?=\t)?', background) colors = [ colors_dict[color.split('=')[-1].replace('"', '').replace(' ', '')] for color in colors ] # make flag object flag = Flag(name, pattern, colors, size=SIZE) # scan for emblems and add them to the flag object defaults = {'colors': colors} emblems = [] chunk = '\n'.join(chunk).replace('\t', '\n').replace(' ', '\n') chunk = re.split( r'(colored_emblem|texture_emblem|textured_emblem)\s*=\s*{', ''.join(chunk))[1:] while not chunk == []: chunk = ''.join(chunk) emblems = parse_emblem( re.split( r'(colored_emblem|texture_emblem|textured_emblem)\s*=\s*{', chunk)[0], colors_dict, defaults) chunk = re.split(r'(colored_emblem|texture_emblem)\s*=\s*{', chunk)[1:] flag.set_emblems(emblems) return flag
def refresh(self): '''Refetch instance data from the API. ''' response = requests.get('%s/guides/%s' % (API_BASE_URL, self.id)) attributes = response.json() self.category = Category(attributes['category']) self.url = attributes['url'] self.title = attributes['title'] if attributes['image']: self.image = Image(attributes['image']['id']) else: self.image = None self.locale = attributes['locale'] self.introduction = WikiText(attributes['introduction_raw'], attributes['introduction_rendered']) self.conclusion = WikiText(attributes['conclusion_raw'], attributes['conclusion_rendered']) if (attributes['tools']): self.tools = attributes['tools'] else: self.tools = None self.parts = attributes['parts'] self.subject = attributes['subject'] self.modifiedDate = datetime.utcfromtimestamp( attributes['modified_date']) self.createdDate = datetime.utcfromtimestamp( attributes['created_date']) self.publishedDate = datetime.utcfromtimestamp( attributes['published_date']) #self.documents = attributes['documents'] author = attributes['author'] #self.author = User(author['userid'], name=author['text']) if (attributes['time_required_min']): self.time_required_min = attributes['time_required_min'] else: self.time_required_min = -1 if (attributes['time_required_max']): self.time_required_max = attributes['time_required_max'] else: self.time_required_max = -1 self.steps = [ Step(step['guideid'], step['stepid'], data=step) for step in attributes['steps'] ] self.type = attributes['type'] self.public = attributes['public'] self.revision = attributes['revisionid'] self.difficulty = attributes['difficulty'] self.prerequisites = [ Guide(guide['guideid']) for guide in attributes['prerequisites'] ] # attributes['prereq_modified_date'] #self.summary = attributes['summary'] self.flags = [ Flag.from_id(flag['flagid']) for flag in attributes['flags'] ]
def __init__(self): pyxel.init(240, 240, caption='Bourne Again', fps=30) pyxel.mouse(True) pyxel.load('stuff.pyxres') self.seemsg = '' self.seemsg_iter = '' self.seemsg_out = '' self.player = Player(30, 120) self.beam_angle = None self.inputed_angle = None self.beam_start_time = 0 #self.wll_index = 0 self.targets = { 'A': Target(200, 120, 'Target A feels lonely'), 'B': Target(1, 20, 'Fortune awaits Target B'), 'C': Target(120, 199, 'Target C is in the mood for shawarma') } self.walls = [Solid(150, 120), Solid(100, 45), Solid(24, 200)] self.flag = Flag(60, 24) self.powerup = Powerup(80, 120) self.upgraded = False self.blocked_functions = ['up', 'down', 'left'] self.locked = False self.has_won = False self.raycast_distance = 0 self.raycast_has_collided = False pyxel.playm(1, loop=True) pyxel.run(self.update, self.draw)
def createExceptionhandler(): global excHandler,excFile,queues errorQueueFileIO = queue.Queue(20) excFile = fileio.FileIO("error_log.txt",errorQueueFileIO,Flag(True)) queues["error"] = queue.Queue(40) excHandler = exceptionhandler.ExceptionHandler(queues["error"],errorQueueFileIO) basicio.BasicIO.setErrorLog(queues["error"]) processing.DataHandler.setErrorLog(queues["error"]) distributor.Distributor.setErrorLog(queues["error"]) dbproxy.DataBaseWorker.setErrorLog(queues["error"]) fileio.FileIO.setErrorLog(queues["error"]) excHandler.start() excFile.start()
def generate_related_flags(self): """ Generates a list of Flag objects, sorted by exported dataset create time, created during the period specified. If no period is specified, all flags are displayed. If only a start date is specified, only those flags created between then and the current time are displayed. If only an end date is specified, only those flags created up to but not including the end date are displayed. Note that any invalid flags are separated out into a separate list for special display. """ flag_dataobj_names = self.manager\ .get_dataobj_names_created_between(paths.FLAGS_PATH, self.start_date, self.end_date) candidate_flags = [Flag(self.dashboard, flag_dataobj_name) for flag_dataobj_name in flag_dataobj_names] self.flags = [item for item in candidate_flags if item.valid] self.invalid_flags = list(set(candidate_flags) - set(self.flags)) self.flags.sort(key=lambda f: f.exported)
def make_level(level_num, max_e, total_e, diff): x = y = 0 global bricks_group, sprite_group, lvl_w, lvl_h, enemies, \ friends, max_enemies, total_enemies, spavned_enemies, enemy_spavner_group,\ camera enemy_spavner_group = [] bullets_group = [] timer.timer = 0 max_enemies = max_e total_enemies = total_e if diff == 1: max_e += 2 total_enemies += 5 if diff == 2: max_e += 4 total_enemies += 10 spavned_enemies = 0 bricks_group = [] sprite_group = [] enemies = friends = 0 lvl_h = len(levels[level_num]) * 40 for row in levels[level_num]: lvl_w = len(row) * 40 for col in row: if col == '0': b1 = Blocks(x, y, 'images/blocks/brick.png', 1) bricks_group.append(b1) sprite_group.append(b1) if col == '1': b1 = Blocks(x, y, 'images/blocks/experimentalbrick.png', 1000000) bricks_group.append(b1) sprite_group.append(b1) if col == 'e': enemy_spavner_group.append([x, y]) if col == 'f': sprite_group.append(Friend(x, y)) friends += 1 if col == 'p': sprite_group = [Player(x, y)] + sprite_group friends += 1 if col == 'b': sprite_group.append(Flag(x, y)) x += 40 y += 40 x = 0 camera = Camera(camera_func, lvl_w, lvl_h)
def choose_flag(self): """Randomly choose which flag to play the game with.""" self.flag = Flag({ 1:"ace", 2:"alt-lesbian", 3:"bi", 4:"intersex", 5:"l-lesbian", 6:"nb", 7:"pan", 8:"poc", 9:"pride", 10:"trans", 11:"gqueer" }[random.randint(1, 10)])
def enter(): global boy, ground, background, spikeList, Hp_Bar, Monster_Bear_List, Monster_Mage_List, ChestList, CHicken,\ GUI, FlatFormList, FLAG background = Background() boy = Boy(background) Hp_Bar = HP_BAR() ground = [Ground(i, background) for i in range(len(Ground.groundList))] Monster_Bear_List = [ Monster_bear(i, background) for i in range(len(Monster_bear.posList)) ] Monster_Mage_List = [ Monster_mage(i) for i in range(len(Monster_mage.posList)) ] spikeList = [Spike(i, background) for i in range(len(Spike.spikeList))] ChestList = [Chest(i, background) for i in range(len(Chest.chestList))] GUI = Gui() FlatFormList = [ Flatform(i, background) for i in range(len(Flatform.flatFormList)) ] FLAG = Flag(background) game_world.add_object(background, 0) for i in range(len(ground)): game_world.add_object(ground[i], 0) game_world.add_object(boy, 2) game_world.add_object(Hp_Bar, 1) for i in range(len(Monster_Bear_List)): game_world.add_object(Monster_Bear_List[i], 1) for i in range(len(Monster_Mage_List)): game_world.add_object(Monster_Mage_List[i], 1) for i in range(len(ChestList)): game_world.add_object(ChestList[i], 1) for i in range(len(spikeList)): game_world.add_object(spikeList[i], 1) game_world.add_object(GUI, 1) for i in range(len(FlatFormList)): game_world.add_object((FlatFormList[i]), 1) game_world.add_object(FLAG, 1) background.set_center_object(boy) boy.set_background(background)
def refresh(self): '''Refetch instance data from the API. ''' response = requests.get('%s/guides/%s' % (API_BASE_URL, self.id)) attributes = response.json() self.category = Category(attributes['category']) self.url = attributes['url'] self.title = attributes['title'] if attributes['image']: self.image = Image(attributes['image']['id']) else: self.image = None self.locale = attributes['locale'] self.introduction = WikiText(attributes['introduction_raw'], attributes['introduction_rendered']) self.conclusion = WikiText(attributes['conclusion_raw'], attributes['conclusion_rendered']) #self.tools = attributes['tools'] #self.parts = attributes['parts'] self.subject = attributes['subject'] self.modifiedDate = datetime.utcfromtimestamp(attributes['modified_date']) self.createdDate = datetime.utcfromtimestamp(attributes['created_date']) self.publishedDate = datetime.utcfromtimestamp(attributes['published_date']) #self.documents = attributes['documents'] author = attributes['author'] #self.author = User(author['userid'], name=author['text']) #self.timeRequired = attributes['timeRequired'] self.steps = [Step(step['guideid'], step['stepid'], data=step) for step in attributes['steps']] self.type = attributes['type'] self.public = attributes['public'] self.revision = attributes['revisionid'] self.difficulty = attributes['difficulty'] self.prerequisites = [Guide(guide['guideid']) for guide in attributes['prerequisites']] # attributes['prereq_modified_date'] #self.summary = attributes['summary'] self.flags = [Flag.from_id(flag['flagid']) for flag in attributes['flags']]
def refresh(self): '''Refetch instance data from the API. ''' response = requests.get('%s/categories/%s' % (API_BASE_URL, self.name)) attributes = response.json() self.ancestors = [Category(name) for name in attributes['ancestors']] self.contents = WikiText(attributes['contents_raw'], attributes['contents_rendered']) self.description = attributes['description'] self.guides = [] for guide in attributes['guides']: self.guides.append(Guide(guide['guideid'])) # Unlike guides, categories return flags as a dict, keyed by flagid. # *Except* when it's empty, in which case we get an empty list due to # PHP's json_encode() not knowing the difference between an empty array # and an empty dict. flags = dict(attributes['flags']).values() self.flags = [Flag.from_id(flag['flagid']) for flag in flags] self.image = Image(attributes['image']['id']) if attributes['image'] else None self.locale = attributes['locale'] #self.parts = attributes['parts'] #self.solutions = attributes['solutions'] self.title = attributes['display_title']
import numpy as np from flag import Flag import forms as formas import matriz as matriz santa_lucia = Flag(1200, 675, (255, 210, 0)) santa_lucia.drawTriangle([(600, 10), (915, 665), (285, 665)], (255, 255, 255)) #PREENCHIMENTO santa_lucia.fillPolygon((380, 511), (255, 255, 255)) santa_lucia.drawTriangle([(600, 100), (865, 665), (335, 665)], (0, 0, 0)) #PREENCHIMENTO santa_lucia.fillPolygon((650, 250), (0, 0, 0)) santa_lucia.drawTriangle([(600, 337), (915, 665), (285, 665)], (0, 210, 255)) #PREENCHIMENTO santa_lucia.fillPolygon((650, 500), (0, 210, 255)) santa_lucia.fillPolygon((325, 645), (0, 210, 255)) santa_lucia.fillPolygon((875, 645), (0, 210, 255)) santa_lucia.scale(1, 2) santa_lucia.translation(20, 20) santa_lucia.rotate(15) santa_lucia.showFlag()
import itertools import os import re import sys import pexpect from retrying import retry from flag import Flag import logging flag = Flag() flag.define_string('--jmp_host', 'jmp_host', None, 'jump server ssh protocol hostname') flag.define_string('--jmp_user', 'jmp_user', None, 'jump server ssh protocol username') flag.define_string('--jmp_pwd', 'jmp_pwd', None, 'jump server ssh protocol password') flag.define_string('--jmp_port', 'jmp_port', 22, 'jump server ssh protocol port number') flag.define_string('--jmp_key_passphrase', 'jmp_key_passphrase', None, 'jump server ssh protocol key passphrase') flag_value = flag.get_flag_value() print(flag_value.jmp_host) print(flag_value.jmp_user) print(flag_value.jmp_pwd) print(flag_value.jmp_port) print(flag_value.jmp_key_passphrase) class ConnectionError(Exception): """Error exception 1lass.""" class PromptError(Exception): """Error exception if prompt not recognized on destination host.""" class SSHConnection: def __init__(self, host, prompt, port=22, user=None, password=None, key=None, jmp_name=None, jmp_user=None, jmp_key=None, jmp_password=None, jmp_port=22, jmp_key_passphrase=None,
import sys from map import Map from flag import Flag from game import Scene from bullet import Bullet from player import Player from enemy_tank import EnemyTank from explosion import Explosion from moveable_object import MoveableObject from bonus import Bonus from game_object import GameObject app = QApplication(sys.argv) map = Map() flag = Flag() scene = Scene() player = Player() bullet = Bullet(player) @pytest.fixture def test_map_init(): assert type(map) == Map def test_map_init_level(): assert len(map.objects) > 0 assert len(map.all_enemys) > 0
import logging import sys import time from retrying import retry from selenium import webdriver from selenium.common.exceptions import WebDriverException as WebDriverException from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from flag import Flag __author__ = 'tianheng' flag = Flag() flag.define_string('--service_plan', 'service_plan', None, 'Customer\'s service plan') flag.define_string('--account_id', 'account_id', None, 'Customer\'s account number') flag.define_string('--action_name', 'action_name', None, 'Action after click update button (Update/Delete)') flag_value = flag.get_flag_value() class WrongRedirectionException(Exception): """Button Check Fail Exception class.""" class Functions: def __init__(self):
def __init__(self, _engine): super(Map, self).__init__() if not Map.tiles: Map.tiles = loadImages('data/gfx/tiles/', alpha=True) self._engine = _engine self._level = self._engine.getLevel() self._above = [] self._workshops = pygame.sprite.Group() self.flags = pygame.sprite.Group() self.tanks = pygame.sprite.Group() self.explosions = pygame.sprite.Group() self.missiles = pygame.sprite.Group() self._holdpos = (False, False) self._pos = [0, 0] self._w, self._h = len(self._level[0]), len(self._level) self._mw, self._mh = self._w * 32, self._h * 32 self._background = pygame.Surface((self._mw, self._mh)) self._debugbackground = pygame.Surface((self._mw, self._mh)) self._debugbackground.fill((1, 5, 4)) self._debugbackground.set_colorkey((1, 5, 4)) self._debugbackground.set_alpha(96) self.debug = pygame.Surface((self._mw, self._mh)) self.debug.fill((1, 5, 4)) self.debug.set_alpha(96) self.debug.set_colorkey((1, 5, 4)) self.screenUpdated() spawn1, spawn2 = None, None for r, row in enumerate(self._level): for c, (cell, mask) in enumerate(row): _, _, x, y = self.tiles[str(cell)].get_rect() self._background.blit(self.tiles[str(cell)], ((c + 1) * 32 - x, (r + 1) * 32 - y)) pygame.draw.rect(self._debugbackground, (0, 0, 0), (c * 32, r * 32, 32, 32), 1) if mask & FIELD_SPAWN1: self._engine.players[0]['spawn'] = spawn1 = (c, r) if mask & FIELD_SPAWN2: self._engine.players[1]['spawn'] = spawn2 = (c, r) if mask & FIELD_FLAG1: self._engine.players[0]['flag'] = flag = Flag( _engine, self, 0, (c * 32 + 16, r * 32 + 16)) self.flags.add(flag) if mask & FIELD_FLAG2: self._engine.players[1]['flag'] = flag = Flag( _engine, self, 1, (c * 32 + 16, r * 32 + 16)) self.flags.add(flag) if mask & FIELD_WORKSHOP1: self._engine.players[0]['workshop'] = workshop = Workshop( (c * 32 + 16, r * 32 + 16)) self._workshops.add(workshop) if mask & FIELD_WORKSHOP2: self._engine.players[1]['workshop'] = workshop = Workshop( (c * 32 + 16, r * 32 + 16)) self._workshops.add(workshop) if str(cell) + 'a' in self.tiles: self._above.append((str(cell) + 'a', ((c + 1) * 32 - x, (r + 1) * 32 - y))) spawn1 = neighbours( spawn1, lambda (x, y): not self.getGridField( (x, y))[1] & FIELD_BLOCKED, TANKS) spawn2 = neighbours( spawn2, lambda (x, y): not self.getGridField( (x, y))[1] & FIELD_BLOCKED, TANKS) random.shuffle(spawn1) random.shuffle(spawn2) for t in xrange(TANKS): x, y = spawn1[t] _engine.players[0]['tanks'].append( Tank(_engine, self, 0, (x * 32 + 16, y * 32 + 16))) for t in xrange(TANKS): x, y = spawn2[t] _engine.players[1]['tanks'].append( Tank(_engine, self, 1, (x * 32 + 16, y * 32 + 16))) self.tanks.add(_engine.players[0]['tanks']) self.tanks.add(_engine.players[1]['tanks']) self.surface = self._background.copy()
def __init__(self, country): self.flag = Flag(country)
class FlagProcessor(): def __init__(self, country): self.flag = Flag(country) def get_flag(self): return self.flag.get_matrix()
#!/usr/bin/env python import re import sys from retrying import retry from SCM.modules import Functions as func from flag import Flag __author__ = 'tianheng' # num_lines = sum(1 for line in open('email')) # print(num_lines) flag = Flag() flag.define_string('--service_plan', 'service_plan', None, "Customer's service plan") flag.define_string('--account_id', 'account_id', None, "Customer's account number") flag.define_string('--button_name', 'button_name', None, "Name of button to be checked") flag.define_string('--action_name', 'action_name', None, 'Action after click update button (Update/Delete)') flag.define_string('--olt_name', 'olt_name', None, 'The OLT will be tested on') flag.define_string('--card_num', 'card_num', None, 'The OLT card number') flag.define_string('--pon_num', 'pon_num', None, 'The Pon number') flag.define_string('--channel', 'channel', None, 'The channel number') flag_value = flag.get_flag_value() class UnexpectedResultException(Exception): """Unexpected Result Exception class.""" class NeedToWaitOrInvalidInputException(Exception): """explicitly wait for result shows up class."""
def createFlags(): global flags for process,processCode in Processes.getAll(): flags[process] = Flag(False)
class Squadron(): """Small unit of several Cavalry controlled by Flag Attributes ---------- coords : float 1-D numpy.ndarray [2], >=0 coords of center of Squadron speed : float, >=0 absolute velocity of Squadron moving : bool whether Squadron is moving, including marching and forming up angle : float angle in radians of Squadron to x-axis. oldAngle : float angle in radians of Squadron to x-axis saved from last forming up troops : list of Cavalry list of sprites representing troops in Squadron flag : Flag sprite that user interacts with to give commands to Squadron target : Squadron or None enemy Squadron which this Squadron is aiming at maxSize : int, >= 0 number of Cavalry that Squadron starts with sizey : int, >= 0 number of rows of Cavalry panicTime : int, >= 0 time in milliseconds when Squadron started panicking showOrders : int stage of selecting orders chargeStart : int when Squadron started charging at target play : bool whether Squadron can be given orders by player team : str team Squadron is on for friend-foe detection defense : bool whether unit will ignore AI move orders allies : list of Battery, Squadron, Squadron list of all units with same team value enemies : list of Battery, Squadron, Squadron list of all units with different team value Properties ---------- size : int, >= 0 number of Cavalry currently contained in Squadron formed : int, >= 0 count of Cavalry in formation idle : bool whether AI can move this Squadron velocity : float 1-D numpy.ndarray [2] velocity of Squadron in vertical and horizontal axes allowShoot : bool whether Squadron will currently aim at targets range : int, >= 0 distance in pixels which Squadrons will set enemies as target aimVars : list of vars variables passed to Cavalry for aim funciton formVars : variables passed to Cavalry for form function morale : int percent chance of Squadron entering panic on losing next Cavalry Methods ------- unitInit set allies and enemies setSpeed set speed to min of default, distance to coords distance measure straight line distance Squadron to coords distanceMany measure straight line distance Squadron to list of coords stop stop Squadron, Cavalry update move Squadron, update Cavalry, panic if necessary follow move Squadron and Cavalry to flag lookAt set rotation to angle from current center to new point findTarget select enemy as target aim turn toward selected target hitBayonets take losses from defended enemies getHit kill own Cavalry when shot getShelled kill own Cavalry hit by cannonball orders give orders other than move for Squadron AIcommand orders company to move to coords AIsupport move to visible allies in combat blitme print elements of Squadron __str__ return string with name of file for id, used in testing """ def __init__(self, screen, angle, x, y, sizex, sizey, team, flags, strength, play=True, defense=False): super().__init__() if team == "green": file1, fileFlag = greenCav elif team == "blue": file1, fileFlag = blueCav coords = np.array([x, y], dtype=float) self.troops = [] # add infantry to company for i in range(sizex * sizey): """ x, y displacement from center of Company based on count shiftx increases with count with a period of sizex, creating a row of soldiers with a length of sizex shifty increases when count increases by sizex, starting a new row of soldiers every sizex soldiers """ shifty = CV_GAPY * ((i % sizey) - sizey // 2) shiftx = CV_GAPX * ((i // sizey) - sizex // 2) self.troops.append( Cavalry(screen, angle, shiftx, shifty, strength, team, file1, coords, play, defense)) self.flag = Flag(screen, (x, y), angle, fileFlag, play) flags.append(self.flag) # 0,1=click,release to show buttons, 2,3=click,release to select self.showOrders = 0 # self.bayonetButton = Button(screen, "Bayonets") self.healthDisp = Button(screen, str(self.health)) # self.bayonets = False self.play = play self.team = team self.oldUnits = [] # used to id object for testing, not meant to be seen/used self.id = file1 def unitInit(self, units): # set allies and enemies if units != self.oldUnits: self.oldUnits = units [unit.unitInit(units) for unit in self.troops] @property def size(self): # number of Cavalry currently contained in Squadron return len(self.troops) @property def flagVars(self): return (self.flag.coords, self.flag.select, self.flag.attackMove, self.flag.angle, self.flag.change) @property def health(self): return sum(inf.size for inf in self.troops) def update(self): # move Squadron, update Cavalry, panic if necessary [unit.panic() for unit in self.troops if unit.panicTime > 0] for unit in self.troops: if unit.size <= 0: self.troops.remove(unit) elif unit.panicTime == -1: unit.update() def follow(self, flags): # move Squadron and Cavalry to flag if self.play: self.flag.checkDrag(flags) [unit.follow(*self.flagVars) for unit in self.troops] self.flag.change = False def aim(self): # turn toward selected target [troop.aim() for troop in self.troops] def orders(self): # give orders other than move for Squadron if not self.play or self.size == 0: return if self.flag.select != 0 or pygame.mouse.get_pressed()[2]: self.showOrders = 0 mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed()[0] touch = any([inf.rect.collidepoint(mouse) for inf in self.troops]) if click and self.showOrders == 0 and touch: self.showOrders = 1 if self.showOrders == 1 and not click: self.showOrders = 2 # self.bayonetButton.draw(self.coords) if self.showOrders == 2 and click: self.showOrders = 3 # if self.bayonetButton.rect.collidepoint(mouse): # self.bayonets = not self.bayonets if self.showOrders == 3 and not click: self.showOrders = 0 def AIcommand(self, coords, attackMove=False): # orders Squadron to move to coords self.flag.coords = coords self.flag.attackMove = attackMove def AIsupport(self): # move to visible allies in combat if self.play or self.size == 0: return unit = self.troops[0] allyDist = unit.distanceMany([grp.coords for grp in unit.allies]) for ally, d in zip(unit.allies, allyDist): cannon = hasattr(ally, 'shot') canSee = d < CV_SIGHT if unit.idle and ally.target is not None and canSee and not cannon: self.AIcommand(ally.target.coords, True) break def blitme(self): # print elements of Squadron [unit.blitme() for unit in self.troops] if self.size > 0: self.flag.blitme() if self.showOrders > 1: coords = self.troops[0].coords healthCoords = (coords[0], coords[1] - FB_SIZE[1]) self.healthDisp.draw(healthCoords, str(self.health)) self.healthDisp.blitme() # self.bayonetButton.blitme() def __str__(self): return self.id
""" menuitem_test.py A simple tester program for menu items. """ from turtle import * from menuitem import MenuItem from flag import Flag INDENT = 30 START_Y = 100 ITEM_SPACE = 30 menuClick = Flag() def changePenColor(c): """Changes the system turtle’s color to c.""" menuClick.value(True) color(c) def createMenu(callback): """Displays 6 menu items to respond to the given callback function.""" x = -(window_width() / 2) + INDENT y = START_Y colors = ("red", "green", "blue", "yellow", "purple", "black") shape = "circle" for color in colors: MenuItem(x, y, shape, color, callback) y -= ITEM_SPACE
from player import Player from flag import Flag from minus import Minus import json screen = pygame.display.set_mode((720, 700)) pygame.display.set_caption("Labyrinthe") bg = pygame.image.load("bg.png") bg = pygame.transform.scale(bg, (1800, 1800)) box = pygame.image.load("black-check-box.png") box = pygame.transform.scale(box, (50, 50)) blank = pygame.image.load("blank.png") blank = pygame.transform.scale(blank, (50, 50)) flag = Flag() affichage = Affichage(screen, box, blank) player = Player() minus = Minus() with open('level.json', 'w') as outfile: json.dump(1, outfile) i = 0 run = True while run: screen.blit(bg, (-250, -350)) minus.start(screen, player) screen.blit(player.image, player.rect)
def run(): # Initialization pygame.init() settings = Settings() state = Game_State() screen = pygame.display.set_mode( (settings.screen_width, settings.screen_height)) pygame.display.set_caption("Super Mario Bros") bg_color = settings.bg_color stats = Game_Stats(screen, settings) clock = pygame.time.Clock() mario = Mario(screen, settings, stats) pygame.mixer.music.load("Sounds/overworld.mp3") pygame.mixer.music.play(-1) # Groups map_group = Group() block_group = Group() floor_group = Group() pipe_group = Group() enemy_group = Group() powerup_group = Group() fireball_group = Group() dead_group = Group() map.generate_map(screen, settings, map_group, floor_group, pipe_group, block_group, enemy_group) f = Flag(screen, settings, 198 * settings.block_width, 13 * settings.block_height) f.add(map_group) pipesprites = pipe_group.sprites() timer = 0 death_counter = 0 # Game Loop while state.running: settings.reset_holders() clock.tick(settings.fps) # handle mario death if mario.is_dead and death_counter <= 240: # draw black screen if death_counter == 60: screen.fill(settings.bg_color) stats.lives -= 1 if stats.lives < 0: stats.init_base_values() #display game over game_over_label = Text(None, settings.TEXT_SIZE, "Game Over", settings.WHITE, 0, 0) game_over_label.rect.center = (settings.screen_width / 2, settings.screen_height / 2) game_over_label.draw(screen) else: # display level lvl_str = "World " + str(stats.world) + "-" + str( stats.level_num) level_label = Text(None, settings.TEXT_SIZE, lvl_str, settings.WHITE, 0, 0) level_label.rect.center = (settings.screen_width / 2, settings.screen_height / 2) level_label.draw(screen) pygame.display.flip() death_counter += 1 print(death_counter) elif mario.is_dead and death_counter > 240: # reset death_counter = 0 mario.kill() mario = Mario(screen, settings, stats) map_group = Group() block_group = Group() floor_group = Group() pipe_group = Group() enemy_group = Group() powerup_group = Group() fireball_group = Group() dead_group = Group() pygame.mixer.music.play(-1) map.generate_map(screen, settings, map_group, floor_group, pipe_group, block_group, enemy_group) f = Flag(screen, settings, 198 * settings.block_width, 13 * settings.block_height) f.add(map_group) stats.new_level() # victory -> change level -> use death_counter to reset if mario.has_won and death_counter <= 300: # draw black screen if death_counter == 100: stats.level_num += 1 screen.fill(settings.bg_color) # display level lvl_str = "World " + str(stats.world) + "-" + str( stats.level_num) level_label = Text(None, settings.TEXT_SIZE, lvl_str, settings.WHITE, 0, 0) level_label.rect.center = (settings.screen_width / 2, settings.screen_height / 2) level_label.draw(screen) coming_soon = Text(None, settings.TEXT_SIZE, "Coming Soon", settings.WHITE, 0, 0) coming_soon.rect.center = (settings.screen_width / 2, (settings.screen_height / 2) + settings.SPACER) coming_soon.draw(screen) pygame.display.flip() death_counter += 1 print(death_counter) elif mario.has_won and death_counter > 300: # reset game death_counter = 0 mario.kill() mario = Mario(screen, settings, stats) map_group = Group() block_group = Group() floor_group = Group() pipe_group = Group() enemy_group = Group() powerup_group = Group() fireball_group = Group() dead_group = Group() pygame.mixer.music.load("Sounds/overworld.mp3") pygame.mixer.music.play(-1) map.generate_map(screen, settings, map_group, floor_group, pipe_group, block_group, enemy_group) f = Flag(screen, settings, 198 * settings.block_width, 13 * settings.block_height) f.add(map_group) stats.new_level() # Game Play gf.check_events(state, mario, screen, settings, fireball_group, map_group) # Update here if not mario.is_dead and not mario.has_won: if timer < settings.fps: timer += 1 else: timer = 0 stats.decrement_time() gf.update(screen, settings, mario, map_group, floor_group, pipe_group, block_group, enemy_group, powerup_group, fireball_group, dead_group, f) if stats.did_time_runout(): mario.dead() if stats.time == 100: pygame.mixer.Sound('Sounds/time_warning.wav').play() # update game values stats.add_score(settings.score_holder) stats.add_coin(settings.coin_holder) if settings.one_up: stats.lives += 1 settings.one_up = False # Display here stats.update() gf.update_screen(screen, settings, stats, mario, map_group, floor_group, pipe_group, block_group, enemy_group, powerup_group, fireball_group, dead_group, f) # stats.draw() pygame.quit() sys.exit()
def register_ntstatus(cls, code, name, descr): if code in cls.ALL_STATUS: return # Use the first def cls.ALL_STATUS[code] = (code, name, descr) return Flag(name, code)
def add_flag(self, x, y, owner): image = self.images[owner] position = (x, y) flag = Flag(position, image, self.game_map.map_corners) self.flags.append(flag)
class Company(): """large unit of several batallions controlled by Flag Attributes ---------- coords : float 1-D numpy.ndarray [2], >=0 coords of center of Company speed : float, >=0 absolute velocity of Company moving : bool whether Company is moving, including marching and forming up angle : float angle in radians of Company to x-axis. oldAngle : float angle in radians of Company to x-axis saved from last forming up troops : list of Infantry list of sprites representing troops in Company flag : Flag sprite that user interacts with to give commands to Company target : Company or None enemy Company which this Company is aiming at maxSize : int, >= 0 number of Infantry that Company starts with sizex : int, >= 0 number of troops in a row of Infantry sizey : int, >= 0 number of rows of Infantry showOrders : int stage of selecting orders bayonetButton : Button button pressed to command Company to charge enemy with bayonets carreButton : Button button pressed to command Company to form carre lineButton : Button button pressed to command Company to form line play : bool whether Company can be given orders by player team : str team Company is on for friend-foe detection formation : String formation of Company defense : bool whether unit will ignore AI move orders allies : list of Battery, Company, Squadron list of all units with same team value enemies : list of Battery, Company, Squadron list of all units with different team value Properties ---------- size : int, >= 0 number of Infantry currently contained in Company formed : int, >= 0 count of Infantry in formation idle : bool whether AI can move this Company velocity : float 1-D numpy.ndarray [2] velocity of Company in vertical and horizontal axes morale : int percent chance of Company entering panic on losing next Infantry Methods ------- unitInit set allies and enemies setSpeed set speed to min of default, distance to coords distanceMany measure straight line distance Company to list of coords stop stop Company, Infantry update move Company, update Infantry, panic if necessary follow move Company and Infantry to flag lookAt set rotation to angle from current center to new point findTarget select enemy as target aim turn toward selected target getHit kill own Infantry when shot getShelled kill own Infantry hit by cannonball orders give orders other than move for Company formCarre Company forms a carre formLine Company forms a line AIcommand orders Company to move to coords AIsupport move to visible allies in combat AIcarre form carre when idle and charged by cavalry blitme print elements of Company __str__ return string with name of file for id, used in testing """ def __init__(self, screen, angle, x, y, sizex, sizey, team, flags, strength, play=True, defense=False): super().__init__() if team == "green": fil1, fil2, fil3, fileFlag = greenImages elif team == "blue": fil1, fil2, fil3, fileFlag = blueImages coords = np.array([x, y], dtype=float) self.troops = [] # self.maxSize = sizex * sizey # add infantry to company for i in range(sizex * sizey): """ x, y displacement from center of Company based on count shiftx increases with count with a period of sizex, creating a row of soldiers with a length of sizex shifty increases when count increases by sizex, starting a new row of soldiers every sizex soldiers """ shifty = I_GAPY * ((i % sizey) - sizey // 2) shiftx = I_GAPX * ((i // sizey) - sizex // 2) self.troops.append( Infantry(screen, angle, shiftx, shifty, strength, team, fil1, fil2, fil3, coords, play, defense)) self.flag = Flag(screen, (x, y), angle, fileFlag, play) flags.append(self.flag) # 0,1=click,release to show buttons, 2,3=click,release to select self.showOrders = 0 self.bayonetButton = Button(screen, "Bayonets") self.carreButton = Button(screen, "Carre") self.lineButton = Button(screen, "Line") self.healthDisp = Button(screen, str(self.health)) self.play = play self.team = team self.formation = "Line" self.oldUnits = [] # used to id object for testing, not meant to be seen/used self.id = fil1 def unitInit(self, units): # set allies and enemies if units != self.oldUnits: self.oldUnits = units.copy() [unit.unitInit(units) for unit in self.troops] @property def size(self): # number of Infantry currently contained in Company return len(self.troops) @property def flagVars(self): return (self.flag.coords, self.flag.select, self.flag.attackMove, self.flag.angle, self.flag.change) @property def health(self): return sum(inf.size for inf in self.troops) def update(self): # move Company, update Infantry, panic if necessary [unit.panic() for unit in self.troops if unit.panicTime > 0] for unit in self.troops: if unit.size <= 0: self.troops.remove(unit) elif unit.panicTime == -1: unit.update() def follow(self, flags): # move Company and Infantry to flag if self.play: self.flag.checkDrag(flags) [unit.follow(*self.flagVars) for unit in self.troops] self.flag.change = False def aim(self): # turn toward selected target [troop.aim() for troop in self.troops] def orders(self): # give orders other than move for Company if not self.play or self.size == 0: return if self.flag.select != 0 or pygame.mouse.get_pressed()[2]: self.showOrders = 0 mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed()[0] touch = any([inf.rect.collidepoint(mouse) for inf in self.troops]) coords = self.troops[0].coords buttonCoords = (coords[0], coords[1] + FB_SIZE[1]) if click and self.showOrders == 0 and touch: self.showOrders = 1 if self.showOrders == 1 and not click: self.showOrders = 2 self.bayonetButton.draw(coords) if self.formation == "Line": self.carreButton.draw(buttonCoords) self.lineButton.draw((-100, -100)) if self.formation == "Carre": self.lineButton.draw(buttonCoords) self.carreButton.draw((-100, -100)) if self.showOrders == 2 and click: self.showOrders = 3 if self.bayonetButton.rect.collidepoint(mouse): for troop in self.troops: troop.bayonets = not troop.bayonets if self.carreButton.rect.collidepoint(mouse): self.formCarre() if self.lineButton.rect.collidepoint(mouse): self.formLine() if self.showOrders == 3 and not click: self.showOrders = 0 def formCarre(self): # Company forms a carre self.formation = "Carre" [inf.formCarre() for inf in self.troops] def formLine(self): # Company forms a line self.formation = "Line" [inf.formLine() for inf in self.troops] def AIcommand(self, coords, attackMove=False): # orders company to move to coords self.flag.coords = coords self.flag.attackMove = attackMove def AIsupport(self): # move to visible allies in combat if self.play or self.size == 0: return unit = self.troops[0] allyDist = unit.distanceMany([grp.coords for grp in unit.allies]) for ally, d in zip(unit.allies, allyDist): cannon = hasattr(ally, 'shot') canSee = d < I_SIGHT if unit.idle and ally.target is not None and canSee and not cannon: self.AIcommand(ally.target.coords, True) break def AIcarre(self): [troop.AIcarre() for troop in self.troops] def blitme(self): # print elements of Company if self.showOrders > 1: self.bayonetButton.blitme() self.carreButton.blitme() self.lineButton.blitme() coords = self.troops[0].coords healthCoords = (coords[0], coords[1] - FB_SIZE[1]) self.healthDisp.draw(healthCoords, str(self.health)) self.healthDisp.blitme() [infantry.blitme() for infantry in self.troops] self.flag.blitme() def __str__(self): return self.id
def __init__(self, level=0): self.objects = [] self.all_enemys = [] self.__init_level__(level) self.__init_borders__(WIDTH, HEIGHT) self.objects.append(Flag())