def config_from_file(self, a_path): """ Configure the Brewer instantiates elements and populates the Tank as described by the selected config file :param a_path: path and name of the config file :type a_path: String """ print "using path:"+a_path with open(a_path) as f: content = f.read() f.close() print "content"+content y = BeautifulSoup(content,"xml") self.__name = y.brewer['name'] self.__receipe=Receipe("Fill me !") self.__receipe.config_from_file(y.brewer.receipe.contents[0]) thermo_tank=Thermometer(y.brewer.tank.equipments.thermometer['name'], y.brewer.tank.equipments.thermometer.path.contents[0]) if(y.brewer.tank['drivetype']=="BOOLEAN"): self.__tank=Tank(y.brewer.tank['name'],int(y.brewer.tank['diameter']),thermo_tank, BOOLEAN) elif(y.brewer.tank['drivetype']=="PID"): self.__tank=Tank(y.brewer.tank['name'],int(y.brewer.tank['diameter']),thermo_tank, PID) elif(y.brewer.tank['drivetype']=="PREDICTIVE"): self.__tank=Tank(y.brewer.tank['name'],int(y.brewer.tank['diameter']),thermo_tank, PREDICTIVE) elif(y.brewer.tank['drivetype']=="STEP_INERTIA"): self.__tank=Tank(y.brewer.tank['name'],int(y.brewer.tank['diameter']),thermo_tank, STEP_INERTIA) for a_heater in y.find_all('heater'): self.__tank.add_heater(Heater(a_heater.get('name'),int(a_heater.get('power')),int(a_heater.get('GPIOpin')))) for an_ingredient in y.find_all('ingredient'): if(an_ingredient.get('type')=="Grain"): self.__tank.add_ingredient(Ingredient(an_ingredient.get('name'),GRAIN,float(an_ingredient.get('quantity')))) elif(an_ingredient.get('type')=="Water"): self.__tank.add_ingredient(Ingredient(an_ingredient.get('name'),WATER,float(an_ingredient.get('quantity')))) self.__outside_thermometer = Thermometer(y.brewer.outsidethermometer['name'],y.brewer.outsidethermometer.path.contents[0]) return self.__name
def __init__(self): Tank.__init__(self) self.sensors = [Sensor(-45, 90, 75, False), Sensor(45, 90, 75, False), Sensor(0, 10, 50, True)] self.clockwise = random.random() < 0.5 self.tread_accel = 120 self.tread_max = 120
def __init__(self): Tank.__init__(self) self.sensors = [Sensor(0, 45, 90, True)] #speed = int((0.5 - random.random())*500) self.speed = 500 print(self.speed) self.set_speed('l', self.speed) self.set_speed('r', self.speed)
def __init__(self, coords, direction, phoenix, image=None, enemy=None): self.player = pygame.image.load(image).convert_alpha() self.player = pygame.transform.scale( self.player, (PART_SIZE, PART_SIZE)) self.direction = direction self.screen = pygame.display.set_mode(SCREEN_SIZE) self.phoenix = phoenix self.enemy = enemy Tank.__init__(self, coords, self.direction, self.phoenix, self.enemy)
def __init__(self): Tank.__init__(self) self.sensors = [Sensor(0, 90, 75, False), Sensor(180, 90, 75, False)] self.clockwise = True self.forward = 1 r = 200 g = 50 b = 50 self.primary_color = '#{:02X}{:02X}{:02X}'.format(r, g, b) r = 10 g = 10 b = 10 self.secondary_color = '#{:02X}{:02X}{:02X}'.format(r, g, b)
def transfer(): sID = input("Enter source ID: ") if Tank.isIDValid(sID) == False: print("Invalid ID entered. \n Back to Menu.") return dID = input("Enter Destination ID: ") if Tank.isIDValid(dID) == False: print("Invalid ID entered. \n Back to Menu.") return transferAMT = 0 while(transferAMT <= 0): transferAMT = int(input("Enter positive amount to transfer: ")) if tank_manager.transfer(sID, dID, transferAMT) == True: print("Tank ID: %s transfered %d to Tank ID: %s" % (sID, transferAMT, dID)) else: print("Did not transfer.")
def delete(): id = input("Enter the id of the tank you want to remove: ") if Tank.isIDValid(id) == False: print("Invalid ID entered. \n Back to Menu.") return if tank_manager.delete(id) == True: print("Tank with ID: %s terminated." % id) else: print("Tank Not terminated.")
def main(): game = Game() render = Render(game) timer = pygame.time.Clock() players = [] # add player tank = Tank() tank.pos = Vec2d(200, 200) p1 = HumanPlayer('Ray', tank) p1.Mapping = HumanPlayer.MappingSet1 tank2 = Tank() tank2.pos = Vec2d(400, 200) p2 = HumanPlayer('Pest', tank2) p2.Mapping = HumanPlayer.MappingSet2 players += [p1, p2] for p in players: game.add_player(p) # add obstacle for pos, col in zip([(100, 400), (500, 400)], ['blue', 'red']): obs = ObstacleBlock((100, 100), pos, Color(col)) game.obstacles.append(obs) timer.tick() FPS = config.FPS dt = 1.0/FPS while 1: for e in pygame.event.get(): if e.type == QUIT: return elif e.type == KEYDOWN: for p in players: p.on_keydown(e.key) if e.key == K_b or (e.mod & KMOD_LCTRL) and e.key == K_q: return elif e.type == KEYUP: for p in players: p.on_keyup(e.key) game.loop(dt) render.draw() game.fps = timer.tick(FPS)
def display(tanks): ## Implement the Tank class appropriately, so this code ## works as intended. ## DO NOT MODIFY this function ## print(Tank.getHeader()) for tank in tanks: print(tank.formatted_str())
class TestTankLogic(unittest.TestCase): def setUp(self): self.tank1 = Tank() self.tank2 = Tank() def test_moving(self): self.assertEqual(self.tank1.pos, 0) self.assertEqual(self.tank2.pos, 0) self.tank1.pos = 100 self.assertEqual(self.tank1.pos, 100) self.assertEqual(self.tank2.pos, 0) def test_fire(self): self.tank1.pos = 100 self.tank2.fire(self.tank1) self.assertEqual(self.tank1.pos, 0)
def add(): id = input("Enter new Tank ID: ") if Tank.isIDValid(id) == False: print("Invalid ID entered.\n Tank Not Added.") return pNumber = input("Enter Part Number: ") amtLeft = input("Enter Amount Left: ") capacity = input("Enter Capacity: ") date = input("Enter the date (Y-M-D): ") newTank = id +"," + pNumber + "," + amtLeft + "," + capacity + "," + date addedTank = Tank(newTank) if tank_manager.add(addedTank) == True: print("Tank with ID: %s Added." % id) else: print("Tank Not Added.")
def get_rand_spawn_space(self): (x,y) = (0,0) new_tank = None new_pixels = None for i in range(100): should_break = True (x,y) = random.choice(self.available_spawn_locs) new_pixels = Tank.three_by_three((x,y)) for t in self.tanks: if len(filter(lambda x: x in new_pixels, t.get_pixel_pos())) > 0: should_break = False break if should_break: break return (x,y)
def makeTank(self): self.tank = Tank(world=self)
def setup_scene(file_path=''): # RESOLUTION try: cmds.setAttr("defaultResolution.width", Tank().data['project']['resolution'][0]) cmds.setAttr("defaultResolution.height", Tank().data['project']['resolution'][1]) cmds.setAttr('defaultResolution.deviceAspectRatio', ((Tank().data['project']['resolution'][0]) / (Tank().data['project']['resolution'][1]))) except: LOG.error('FAILED load resolution.', exc_info=True) # IMG FORMAT # try: # cmds.setAttr("defaultRenderGlobals.imageFormat", 8) # except: LOG.error('FAILED load img format.', exc_info=True) # FPS try: fps = software_data['SETTINGS']['FPS'][Tank().data['project']['fps']] cmds.currentUnit(time=fps) cmds.optionVar(sv=("workingUnitTime", fps)) cmds.optionVar(sv=("workingUnitTimeDefault", fps)) except: LOG.error('FAILED load fps.', exc_info=True) # UNIT try: cmds.currentUnit(linear=software_data['SETTINGS']['unit']) except: LOG.error('FAILED load unit.', exc_info=True) # RENDERER try: renderer = software_data['renderer'] cmds.optionVar(sv=("preferredRenderer", software_data['renderer'])) cmds.optionVar(sv=("preferredRendererHold", software_data['renderer'])) except: LOG.error('FAILED load renderer.', exc_info=True) # ANIMATION extension try: cmds.setAttr('defaultRenderGlobals.animation', 1) cmds.setAttr('defaultRenderGlobals.putFrameBeforeExt', 1) cmds.setAttr('defaultRenderGlobals.extensionPadding', 4) except: LOG.error('FAILED set extension.', exc_info=True) if file_path: try: render_path = os.path.dirname(os.path.dirname(file_path)) render_path += "/" + Tank( ).data['rules']["STATUS"]["render"] + "/<Scene>/<Scene>" cmds.setAttr('defaultRenderGlobals.imageFilePrefix', render_path, type='string') except: LOG.error('FAILED set image path.', exc_info=True) try: import pymel.core as pm pm.mel.setProject(os.path.dirname(file_path)) except: LOG.error('FAILED set project path.', exc_info=True)
def spawn_tank(): tank = Tank(objects_to_add) tank.bag['tankx'] = 100 tank.bag['tanky'] = 100 tank.bag['barrelx'] = 100 tank.bag['barrely'] = 100
def __init__(self): Tank.__init__(self) self.sensors = [Sensor(0, 90, 50, False), Sensor(0, 5, 400, True)] self.clockwise = random.random() < 0.5
def __init__(self): Tank.__init__(self) self.sensors = [Sensor(30, 60, 150, True), Sensor(-30, 60, 150, True), Sensor(0, 10, 50, True)] self.clockwise = True # random.random() < 0.5
from tank import Tank tanks = {"a":Tank("Alpha"), "b":Tank("Blabo"), "c":Tank("Chary")} alivetanks = len(tanks) while alivetanks > 1: print for tankname in sorted( tanks.keys()): print (tankname, tanks[tankname]) first = str(input("who fires??").lower()) second= str(input("who at??").lower()) try: firsttank = tanks[first] secondtank = tanks[second] except KeyError: print ("NO such Tank") continue if not firsttank.alive or not secondtank.alive: print("already dead") continue print ("*" *30) firsttank.fire_at(secondtank) if not secondtank.alive:
class Game: def __init__(self): self.r = random.Random() self.scene = GameObject() # field -- self.field = Field() self.field.load_from_file('data/level1.txt') self.scene.add_child(self.field) self.field_protector = FieldProtector(self.field) self.my_base = MyBase() self.my_base.position = self.field.map.coord_by_col_and_row(12, 24) self.scene.add_child(self.my_base) # tanks -- self.tanks = GameObject() self.scene.add_child(self.tanks) self.make_my_tank() self.ai = EnemyFractionAI(self.field, self.tanks) # projectiles -- self.projectiles = GameObject() self.scene.add_child(self.projectiles) # bonuses -- self.bonues = GameObject() self.scene.add_child(self.bonues) self.score = 0 self.score_layer = ScoreLayer() self.scene.add_child(self.score_layer) self.freeze_timer = Timer(10) self.freeze_timer.done = True # else -- self.font_debug = pygame.font.Font(None, 18) # to test bonus self.make_bonus(*self.field.map.coord_by_col_and_row(13, 22), BonusType.TOP_TANK) def respawn_tank(self, t: Tank): is_friend = self.is_friend(t) pos = random.choice(self.field.respawn_points(not is_friend)) t.place(self.field.get_center_of_cell(*pos)) if is_friend: t.tank_type = t.Type.LEVEL_1 def make_my_tank(self): self.my_tank = Tank(Tank.FRIEND, Tank.Color.YELLOW, Tank.Type.LEVEL_1) self.respawn_tank(self.my_tank) self.my_tank.activate_shield() self.tanks.add_child(self.my_tank) self.my_tank_move_to_direction = None @property def frozen_enemy_time(self): return not self.freeze_timer.done def _on_destroyed_tank(self, t: Tank): if t.is_bonus: self.make_bonus(*t.center_point) if t.fraction == t.ENEMY: if t.tank_type == t.Type.ENEMY_SIMPLE: ds = 100 elif t.tank_type == t.Type.ENEMY_FAST: ds = 200 elif t.tank_type == t.Type.ENEMY_MIDDLE: ds = 300 elif t.tank_type == t.Type.ENEMY_HEAVY: ds = 400 else: ds = 0 self.score += ds self.score_layer.add(*t.center_point, ds) def make_bonus(self, x, y, t=None): bonus = Bonus(BonusType.random() if t is None else t, x, y) self.bonues.add_child(bonus) def switch_my_tank(self): tank = self.my_tank t, d, p = tank.tank_type, tank.direction, tank.position tank.remove_from_parent() types = list(Tank.Type) current_index = types.index(t) next_type = types[(current_index + 1) % len(types)] tank = Tank(Tank.Color.PLAIN, next_type) tank.position = tank.old_position = p tank.direction = d tank.shielded = True tank.activate_shield() self.tanks.add_child(tank) self.my_tank = tank def make_explosion(self, x, y, expl_type): self.scene.add_child(Explosion(x, y, expl_type)) def is_friend(self, tank): return tank.fraction == tank.FRIEND def fire(self, tank=None): tank = self.my_tank if tank is None else tank tank.want_to_fire = False if self.is_game_over and self.is_friend(tank): return if tank.try_fire(): power = Projectile.POWER_HIGH if tank.tank_type.can_crash_concrete else Projectile.POWER_NORMAL projectile = Projectile(*tank.gun_point, tank.direction, sender=tank, power=power) self.projectiles.add_child(projectile) def move_tank(self, direction: Direction, tank=None): tank = self.my_tank if tank is None else tank tank.remember_position() tank.move_tank(direction) def apply_bonus(self, t: Tank, bonus: BonusType): if bonus == bonus.DESTRUCTION: for t in self.tanks: if not t.is_spawning and t.fraction == Tank.ENEMY: self.kill_tank(t) elif bonus == bonus.CASK: t.shielded = True elif bonus == bonus.UPGRADE: t.upgrade() elif bonus == bonus.TIMER: self.freeze_timer.start() elif bonus == bonus.STIFF_BASE: self.field_protector.activate() elif bonus == bonus.TOP_TANK: t.upgrade(maximum=True) else: print(f'Bonus {bonus} not implemented yet.') def update_bonuses(self): for b in self.bonues: # type: Bonus if b.intersects_rect(self.my_tank.bounding_rect): b.remove_from_parent() self.apply_bonus(self.my_tank, b.type) @property def all_mature_tanks(self): return (t for t in self.tanks if not t.is_spawning) @property def is_game_over(self): return self.my_base.broken def update_tanks(self): for tank in self.all_mature_tanks: self.field.oc_map.fill_rect(tank.bounding_rect, tank, only_if_empty=True) if not self.is_game_over: if self.my_tank_move_to_direction is None: self.my_tank.stop() self.my_tank.align() else: self.move_tank(self.my_tank_move_to_direction, self.my_tank) self.freeze_timer.tick() if self.frozen_enemy_time: self.ai.stop_all_moving() else: self.ai.update() for tank in self.all_mature_tanks: if tank.want_to_fire: self.fire(tank) if tank.to_destroy: tank.remove_from_parent() bb = tank.bounding_rect if not self.field.oc_map.test_rect(bb, good_values=(None, tank)): push_back = True else: push_back = self.field.intersect_rect(bb) if push_back: tank.undo_move() def is_player_tank(self, t: Tank): return t is self.my_tank def hit_tank(self, t: Tank): destroy = False if self.is_friend(t): destroy = True self.respawn_tank(t) else: t.hit = True self.ai.update_one_tank(t) if t.to_destroy: destroy = True t.remove_from_parent() self._on_destroyed_tank(t) if destroy: self.make_explosion(*t.center_point, Explosion.TYPE_FULL) def kill_tank(self, t: Tank): self.make_explosion(*t.center_point, Explosion.TYPE_FULL) if self.is_friend(t): self.respawn_tank(t) else: self.ai.update_one_tank(t) t.remove_from_parent() def make_game_over(self): self.my_base.broken = True go = GameOverLabel() go.place_at_center(self.field) self.scene.add_child(go) def update_projectiles(self): for p in self.projectiles: # type: Projectile r = extend_rect((*p.position, 0, 0), 2) self.field.oc_map.fill_rect(r, p) remove_projectiles_waitlist = set() for p in self.projectiles: # type: Projectile p.update() something = self.field.oc_map.get_cell_by_coords(*p.position) if something and something is not p and isinstance( something, Projectile): remove_projectiles_waitlist.add(p) remove_projectiles_waitlist.add(something) was_stricken_object = False x, y = p.position if self.field.check_hit(p): was_stricken_object = True self.make_explosion(*p.position, Explosion.TYPE_SUPER_SHORT) elif self.my_base.check_hit(x, y): self.make_game_over() was_stricken_object = True self.make_explosion(*self.my_base.center_point, Explosion.TYPE_FULL) else: for t in self.all_mature_tanks: # type : Tank if t is not p.sender and t.check_hit(x, y): was_stricken_object = True if not t.shielded and p.sender.fraction != t.fraction: self.make_explosion(*p.position, Explosion.TYPE_SHORT) self.hit_tank(t) break if was_stricken_object: remove_projectiles_waitlist.add(p) for p in remove_projectiles_waitlist: p.remove_from_parent() def update(self): self.field.oc_map.clear() self.field.oc_map.fill_rect(self.my_base.bounding_rect, self.my_base) self.field_protector.update() self.score_layer.update() self.update_tanks() self.update_bonuses() self.update_projectiles() # ---- render ---- def render(self, screen): self.scene.visit(screen) score_label = self.font_debug.render(str(self.score), 1, (255, 255, 255)) screen.blit(score_label, (GAME_WIDTH - 50, 5)) # - 1 because the scene is not literally an object dbg_text = f'Objects: {self.scene.total_children - 1}' if self.is_game_over: dbg_text = 'Press R to restart! ' + dbg_text dbg_label = self.font_debug.render(dbg_text, 1, (255, 255, 255)) screen.blit(dbg_label, (5, 5)) # --- test --- def testus(self): self.respawn_tank(self.my_tank)
# Colour constants SKY_COLOR = (165, 182, 209) SKY_COLOR = (165, 182, 209) GROUND_COLOR = (9, 84, 5) # Different tank colors for player 1 and player 2 # These colors must be unique as well as the GROUND_COLOR TANK_COLOR_P1 = (216, 216, 153) TANK_COLOR_P2 = (219, 163, 82) SHELL_COLOR = (255, 255, 255) TEXT_COLOR = (255, 255, 255) # Timer used to create delays before action (prevent accidental button press) game_timer = 0 # Tank 1 = Left tank1 = Tank("left", TANK_COLOR_P1) # Tank 2 = Right tank2 = Tank("right", TANK_COLOR_P2) # Only fire one shell at a time, a single shell object can be used for both player 1 and player 2 shell = Shell(SHELL_COLOR) ground = Land(GROUND_COLOR, (WIDTH, HEIGHT)) # Get positions of tanks from ground generator tank1.set_position(ground.get_tank1_position()) tank2.set_position(ground.get_tank2_position()) def draw(): global game_state
screen.blit(settings.t2Icon, (650, 150)) for i in range(25, tank2.hp * 25 + 1, 25): screen.blit(settings.heartImg, (650 + i, 150)) textsurface = myfont.render(str(round(tank2.reload, 2)), False, WHITE) screen.blit(textsurface,(650,200)) pygame.display.update(pygame.Rect(675, 50, 75, 200)) pygame.init() clock = pygame.time.Clock() pygame.font.init() myfont = pygame.font.SysFont('Comic Sans MS', 30) tank1 = Tank(0, 0, settings.t1Img, 3, -1) tank2 = Tank(settings.width - settings.block, settings.height - settings.block, settings.t2Img, 3, 1) boxes = createBoxes() screen = pygame.display.set_mode((settings.width + 200, settings.height)) play = True while (play): circB = pygame.draw.rect(screen, BLACK, (tank1.X, tank1.Y, settings.block, settings.block)) circB = pygame.draw.rect(screen, BLACK, (tank2.X, tank2.Y, settings.block, settings.block)) grid.draw(screen) for i in pygame.event.get(): if i.type == QUIT or (i.type == KEYDOWN and i.key == K_ESCAPE):
def make_my_tank(self): self.my_tank = Tank(Tank.FRIEND, Tank.Color.YELLOW, Tank.Type.LEVEL_1) self.respawn_tank(self.my_tank) self.my_tank.activate_shield() self.tanks.add_child(self.my_tank) self.my_tank_move_to_direction = None
from tank import Tank tanks = {"a": Tank("Alice"), "b": Tank("Bob"), "c": Tank("Carol")} alive_tanks = len(tanks) while alive_tanks > 1: print for tank_name in sorted(tanks.keys()): print tank_name, tanks[tank_name] first = raw_input("Who fires? ").lower() second = raw_input("Who at? ").lower() try: first_tank = tanks[first] second_tank = tanks[second] except KeyError: print "No such tank!" continue if not first_tank.alive or not second_tank.alive: print "One of those tanks is dead!" continue print print "*" * 30 first_tank.fire_at(second_tank) if not second_tank.alive: alive_tanks -= 1
def __init__(self): Tank.__init__(self) self.sensors = [Sensor(0, 180, 75, False), Sensor(0, 180, 50, False), Sensor(0, 180, 25, False)] #, Sensor(0, 10, 50, True)] self.clockwise = random.random() < 0.5
def setUp(self): self.tank1 = Tank() self.tank2 = Tank()
import sys, pygame from bullet import Bullet from tank import Tank from chat import Chat from config import * import client tank = Tank(width/2, height - 20) enemy = Tank(width/2, 20, rotate = False) # estabilish connect, have to receive # 'conn' to be in the game client = client.Client(sys.argv[1], int(sys.argv[2])) print 'Conectando ao servidor...' if client.connected(): print 'OK!' else: print 'Nao ha espaco livre no servidor' sys.exit() # initialize chat chat = Chat(client) print 'Sincronizando...' if client.synced(): client.listen(tank, enemy, chat) # init and show screen
def __init__(self): print 'Initiated main window' # Define the colors we will use in RGB format black = [ 0, 0, 0] white = [255,255,255] self.dx = 0 # x travel self.dy = 0 # y travel self.dz = 0 # shot firing self.dzTime = 0 # shot last fired self.speed = 3 # tank speed pygame.init() screen = pygame.display.set_mode(SCREEN_SIZE) pygame.display.set_caption("Tanks Title") #FIXME working title # Initialize timer for MainWindow clock = pygame.time.Clock() font = pygame.font.Font(None, 25) # Render the text. "True" means anti-aliased text. # Black is the color. This creates an image of the # letters, but does not put it on the screen text = font.render("Tanks - hello world", True, black) tankPosition = [100, 100] self.localTank = Tank(tankPosition, "red") testDummy = Tank([400,400], "blue") self.tanks.add(testDummy) # self.sprites.add(testDummy) testSabot = Sabot(200,200, math.pi) mainExit=False while mainExit==False: # This limits the while loop to a max of 45 times per second. # Leave this out and we will use all CPU we can. clock.tick(45) for event in pygame.event.get(): # User did something # If user clicked close or hit escape key if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): mainExit = True # Flag that we are done so we exit this loop # FIXME Add menu system here self.userInput(event, tankPosition) # Put the image of the text on the screen at 250x250 screen.fill(white) screen.blit(text, [250,250]) # update the tank position # tankPosition = [tankPosition[0] + (self.dx * self.speed), tankPosition[1] + (self.dy * self.speed)] # self.localTank.moveTo(tankPosition) if self.dy > 0: self.localTank.moveForward() elif self.dy < 0: self.localTank.moveReverse() if self.dx > 0: self.localTank.rotateLeft() elif self.dx < 0: self.localTank.rotateRight() # paint the tank screen.blit(self.localTank.image, self.localTank.rect) testSabot.draw(screen) self.userAttack() for shot in self.sprites.sprites(): shot.draw(screen) for t in self.tanks.sprites(): t.draw(screen) #screen.blit(testDummy.image, testDummy.rect) #self.sprites. if pygame.sprite.spritecollideany(testDummy, self.sprites): print 'Collide' self.sprites.remove(testDummy) collidedSabots = pygame.sprite.spritecollide(testDummy, self.sprites, True) if collidedSabots.__sizeof__() > 0: testDummy.killTank() print 'Kill Tank' # Go ahead and update the screen with what we've drawn. # This MUST happen after all the other drawing commands. pygame.display.flip()
def create_folder_structure(self): # CHECK inputs for inputs in self.inputs: if not inputs.currentText(): if self.scene_steps < 5 and self.wgSaveAs.cbxSet == inputs: continue self.set_status('Missing input: {}'.format( inputs.objectName().replace('cbx', '')), msg_type=2) return False self.update_file() # CHECK FILE if os.path.exists(self.save_file): self.set_status('PATH already exists: {}'.format(self.save_file), msg_type=2) return False save_list = [] if self.all_task in self.save_file: for task in Tank().data_project['TASK'][ self.wgSaveAs.cbxScene.currentText()]: new_path = self.save_file.replace(self.all_task, task) save_list.append(new_path) else: save_list.append(self.save_file) LOG.debug('Folder list {}'.format(save_list)) for folder in save_list: pipefunc.create_folder(folder) if self.new_file: Tank().software.scene_save_as(self.save_file, setup_scene=True) snapshot.create_any_screenshot(self.wgSaveAs) tmp_img_path = snapshot.save_snapshot(self.save_file) tmp_title = os.path.basename(self.save_file).split('.')[0] tmp_func = 'SAVE AS' self.set_meta_data(self.save_file) else: try: self.set_open_folder(save_list[0]) except: LOG.error('CANT set folder: {}'.format(save_list)) self.set_status('Created new {}'.format( self.wgSaveAs.cbxScene.currentText()), msg_type=1) tmp_img_path = 'lbl/lbl_create' tmp_title = self.wgSaveAs.cbxScene.currentText() tmp_func = 'CREATE' note = arNotice.Notice(title=tmp_title, msg='CREATED a new {} with folders'.format( self.wgSaveAs.cbxScene.currentText()), func=tmp_func, img=tmp_img_path, img_link=os.path.dirname(self.save_file)) arNotice.ArNotice(note) return True
import os import errno import nuke import libLog import libFunc from tank import Tank TITLE = os.path.splitext(os.path.basename(__file__))[0] LOG = libLog.init(script=TITLE) #************************ # PIPELINE all_data = Tank().data project_data = all_data['project'] software_data = all_data['software'] RESOLUTION = (' ').join([ str(project_data['resolution'][0]), str(project_data['resolution'][1]), project_data['name'].replace(' ', '') ]) #************************ # FOLDER CREATION def createWriteDir(): file_name = nuke.filename(nuke.thisNode()) file_path = os.path.dirname(file_name) os_path = nuke.callbacks.filenameFilter(file_path)
def __init__(self): Tank.__init__(self) self.sensors = [Sensor(0, 90, 75, False), Sensor(90, 90, 75, False),Sensor(180, 90, 75, False),Sensor(270, 90, 75, False)] self.clockwise = random.random() < 0.5
def create_tank(self): """Create A Tank Object and Fill it With Creatures""" self.__tank = Tank() self.__tank.fill_tank(self.__screen)
def __call__(self): from tank import Tank TITLE = os.path.splitext(os.path.basename(__file__))[0] LOG = Tank().log.init(script=TITLE) LOG.debug('____________________________________________________________') LOG.debug('PIPELINE: {} [{}, {}, {}] {}'.format(self.pipeline_data['PIPELINE']['name'], self.pipeline_data['PIPELINE']['version'], os.environ['PIPELINE_STATUS'], 'user overwrite' if os.environ['DATA_USER_PATH'] else 'NO user overwrite', self.data_pipeline_path)) LOG.debug('PROJECT: {} [{}, {}] [{}{}]'.format(self.project_data['name'], '{} x {}'.format(Tank().data_project['resolution'][0], Tank().data_project['resolution'][1]), Tank().data_project['fps'], '' if os.path.exists(self.project_data['path']) else 'NOT existing: ', os.path.normpath(self.project_data['path']))) LOG.debug('------------------------------------------------------------') LOG.debug('SYS_PATH: {}'.format('[%s]' % ', '.join(map(str, sys.path)))) LOG.debug('ADD_ENV: {}'.format(self.pipeline_env))
def respawn_tank(self, t: Tank): is_friend = self.is_friend(t) pos = random.choice(self.field.respawn_points(not is_friend)) t.place(self.field.get_center_of_cell(*pos)) if is_friend: t.tank_type = t.Type.LEVEL_1
class Brewer: """ A brewer uses the thermometers and heaters in order to follow the receipe. Each brewer has a single tank who knows its own composition in order to perform kick-ass calculations' """ def __init__(self): """ Constructor """ self.__name = None self.__outside_thermometer = None self.__tank = None self.__receipe = None self.__brewing_started = False def config_from_file(self, a_path): """ Configure the Brewer instantiates elements and populates the Tank as described by the selected config file :param a_path: path and name of the config file :type a_path: String """ print "using path:"+a_path with open(a_path) as f: content = f.read() f.close() print "content"+content y = BeautifulSoup(content,"xml") self.__name = y.brewer['name'] self.__receipe=Receipe("Fill me !") self.__receipe.config_from_file(y.brewer.receipe.contents[0]) thermo_tank=Thermometer(y.brewer.tank.equipments.thermometer['name'], y.brewer.tank.equipments.thermometer.path.contents[0]) if(y.brewer.tank['drivetype']=="BOOLEAN"): self.__tank=Tank(y.brewer.tank['name'],int(y.brewer.tank['diameter']),thermo_tank, BOOLEAN) elif(y.brewer.tank['drivetype']=="PID"): self.__tank=Tank(y.brewer.tank['name'],int(y.brewer.tank['diameter']),thermo_tank, PID) elif(y.brewer.tank['drivetype']=="PREDICTIVE"): self.__tank=Tank(y.brewer.tank['name'],int(y.brewer.tank['diameter']),thermo_tank, PREDICTIVE) elif(y.brewer.tank['drivetype']=="STEP_INERTIA"): self.__tank=Tank(y.brewer.tank['name'],int(y.brewer.tank['diameter']),thermo_tank, STEP_INERTIA) for a_heater in y.find_all('heater'): self.__tank.add_heater(Heater(a_heater.get('name'),int(a_heater.get('power')),int(a_heater.get('GPIOpin')))) for an_ingredient in y.find_all('ingredient'): if(an_ingredient.get('type')=="Grain"): self.__tank.add_ingredient(Ingredient(an_ingredient.get('name'),GRAIN,float(an_ingredient.get('quantity')))) elif(an_ingredient.get('type')=="Water"): self.__tank.add_ingredient(Ingredient(an_ingredient.get('name'),WATER,float(an_ingredient.get('quantity')))) self.__outside_thermometer = Thermometer(y.brewer.outsidethermometer['name'],y.brewer.outsidethermometer.path.contents[0]) return self.__name def get_name(self): """ Returns the name of the Brewer :return: Name of the Brewer :rtype: Sting """ return self.__name def print_self(self): """ Returns the Brewer as a human readable String ended with a new line :return: A String detailling the caracteristics of the Brewer :rtype: String """ to_print="Name : "+self.__name to_print+="Outside thermometer : "+self.__outside_thermometer.print_self() to_print+="Tank : "+self.__tank.print_self() to_print+="Receipe : "+self.__receipe.print_self()+"\n" return to_print def init_brewing(self): """ Checks that everything is ready for brewing and starts the receipe :return: A Boolean True = started OK, False for any anomaly :rtype: Boolean """ if(self.__name == None or self.__tank == None or self.__receipe == None or self.__brewing_started == True):return False self.__brewing_started = True self.__receipe.start(self.__tank.get_current_temperature()) print "***************************************************" print "Updated receipe "+self.__receipe.print_self() return True def log_temperatures(self,a_file): """ This function logs in the desired output file the temperature state of the system. :param a_file: path and name of the file where all temperature will be reccorded :type a_file: String """ f=open(a_file, "a") try: f.write(str(datetime.datetime.now().strftime('%H:%M:%S'))+"\t"+unicodedata.normalize('NFKD',self.__receipe.get_current_step().get_name()).encode('ascii','ignore')+"\t"+str(self.__receipe.get_current_temperature_instruction())+"\t"+str(self.__tank.get_current_temperature())+"\t"+str(self.__tank.get_heating_status())+"\n") except: print "Unexpected log write error" f.close() def brew(self,a_outputfile): """ This function is the main brewing function : ajusting the temperature according to the receipe. Function to be called regularily (every 5 seconds for instance). :param a_outputfile: path and name of the file where all temperature will be reccorded :type a_outputfile: String """ while 1==1 : self.__receipe.update_step() if(self.__receipe.get_current_step().get_type()==TRANSITION): if(self.__tank.get_current_temperature()>=self.__receipe.get_next_temperature_instruction()): #Only works as long as transitions go from lower to higher temperatures... self.__receipe.transition_complete() if(self.__receipe.get_current_step()==None): print "Receipe completed" return True #self.__tank.temperature_hysteresis_drive(self.__receipe.get_current_temperature_instruction()) #self.__tank.temperature_inertia_drive(self.__receipe.get_current_temperature_instruction(), self.__receipe.get_next_temperature_instruction()) #self.__tank.temperature_model_drive(self.__receipe.get_current_temperature_instruction(), self.__receipe.get_next_temperature_instruction(),self.__outside_thermometer.read_temperature()) self.__tank.temperature_step_inertia_drive(self.__receipe.get_current_temperature_instruction(), self.__receipe.get_next_temperature_instruction(),self.__receipe.get_current_step().get_inertia()) print "Current step : "+self.__receipe.get_current_step().print_self() print "Temperature instuction : "+str(self.__receipe.get_current_temperature_instruction()) print "Next Temperature instuction : "+str(self.__receipe.get_next_temperature_instruction()) print "Current temperature : "+str(self.__tank.get_current_temperature()) self.log_temperatures(a_outputfile) print 'Type "N" if you want to skip the current step', rlist, _, _ = select([sys.stdin], [], [], UPDATE_PERIOD) if rlist: s = sys.stdin.readline() if(s == "N\n"): print "Skip order received" self.__receipe.user_force_next_step() else: print "No input. Moving on..."
# date = 2019-12-01 # # license = MIT <https://github.com/alexanderrichtertd> # author = Alexander Richter <alexanderrichtertd.com> #********************************************************************* import os import nuke import webbrowser from tank import Tank #********************************************************************* # VARIABLE TITLE = os.path.splitext(os.path.basename(__file__))[0] LOG = Tank().log.init(script=TITLE) #********************************************************************* # FUNCTIONS def add_gizmo_menu(menu): for paths in os.getenv('SOFTWARE_SUB_PATH').split(';'): for file in os.listdir(paths): if file.endswith('.gizmo'): gizmo = file.replace('.gizmo', '') menu.addCommand('Gizmos/' + gizmo, 'nuke.tcl("{}")'.format(gizmo)) def add_write_node(): import write_node
def __init__(self, perma_board = []): """ if we want walls/hospital we give them in perma_board perma_board should be formatted as a 64x64 2D list of pixel values """ # the set of things on the board which never change # currently includes HOSPITAL and WALL # formatted as a 64x64 2D list of pixel values self.perma_board = perma_board if len(self.perma_board) == 0: for i in range(64): self.perma_board += [[EMPTY]*64] # the set of locations on the board where tanks can spawn # excludes HOSPITAL and WALL and anything adjacent to either # formatted as a 64x64 2D list of pixel values self.available_spawn_locs = [space for space in np.nindex(64,64)] self.available_spawn_locs = filter(lambda x: true_for_each(lambda y: self.perma_board[y[0],y[1]] == EMPTY, Tank.three_by_three(x)), self.available_spawn_locs) # purely aesthetic features which never interact # includes EYE for instance # formatted as a 64x64 2D list of pixel values self.ghost_board = [] for i in range(64): self.ghost_board += [[EMPTY]*64] self.scores = {} self.load_colors() self.tanks = {} self.board = copy.deepcopy(self.perma_board) self.bullets = [] self.t_minus = TURN_RATE self.last_time_stamp = time.time() self.fast_forward = False self.pending_tank_ids = [] self.scomm = ServerCommunicator()
class TankGame: """Class for the Tank Game""" def __init__(self): """Initializes the game""" pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("A Tank Game") self.tank = Tank(self) self.bullet = pygame.sprite.Group() def run_game(self): """Runs the game""" while True: self._check_event() self.tank.update() self._update_bullet() self._update_screen() def _check_event(self): """Checks for events""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_events_keydown(event) elif event.type == pygame.KEYUP: self._check_events_keyup(event) def _check_events_keydown(self, event): """Checks for keydown events""" if event.key == pygame.K_RIGHT: self.tank.moving_right = True elif event.key == pygame.K_LEFT: self.tank.moving_left = True elif event.key == pygame.K_UP: self.tank.moving_up = True elif event.key == pygame.K_DOWN: self.tank.moving_down = True elif event.key == pygame.K_q: sys.exit() elif event.key == pygame.K_SPACE: self._fire_bullet() def _check_events_keyup(self, event): """Checks for keyup events""" if event.key == pygame.K_RIGHT: self.tank.moving_right = False elif event.key == pygame.K_LEFT: self.tank.moving_left = False elif event.key == pygame.K_UP: self.tank.moving_up = False elif event.key == pygame.K_DOWN: self.tank.moving_down = False def _fire_bullet(self): """Produces a new bullet object and adds it to the 'bullet' list""" new_bullet = Bullet(self) self.bullet.add(new_bullet) def _update_bullet(self): """Updates the bullet and removes bullets that reaches out of screen""" self.bullet.update() for bullet in self.bullet.copy(): if bullet.rect.bottom < 0: self.bullet.remove(bullet) def _update_screen(self): """Updates the screen """ self.screen.fill(self.settings.bg_color) self.tank.blitme() for bullet in self.bullet.sprites(): bullet.draw_bullet() pygame.display.flip()
def __init__(self): path_ui = ("/").join([os.path.dirname(__file__), "ui", TITLE + ".ui"]) self.wgHeader = QtCompat.loadUi(path_ui) # VAR # self.monitor_res = QtGui.QDesktopWidget().screenGeometry() # self.monitor_size = QtCore.QSize(self.monitor_res.width(), self.monitor_res.height()) self.open_path = "" self.preview_img_path = '' Tank().user.create() self.wgHeader.setWindowIcon( QtGui.QPixmap(QtGui.QImage( Tank().get_img_path("btn/btn_project")))) # BUTTONS ICONS self.wgHeader.btnReport.setIcon( QtGui.QPixmap(QtGui.QImage(Tank().get_img_path("btn/btn_report")))) self.wgHeader.btnHelp.setIcon( QtGui.QPixmap(QtGui.QImage(Tank().get_img_path("btn/default")))) self.wgHeader.btnOpenFolder.setIcon( QtGui.QPixmap(QtGui.QImage(Tank().get_img_path("btn/btn_folder")))) self.wgHeader.btnUser.setIcon( QtGui.QPixmap(QtGui.QImage( Tank().get_img_path("user/default")))) # current user self.wgHeader.btnUser.setToolTip(("").join([ '<html><head/><body><p><span style=" font-weight:600;">', Tank().user.name, '</span><br>', Tank().user.rights, '<br>[open user folder]</p></body></html>' ])) self.wgHeader.btnProject.setIcon( QtGui.QPixmap(QtGui.QImage( Tank().get_img_path('btn/btn_project')))) # current user self.wgHeader.btnProject.setToolTip(os.environ['PROJECT_NAME'] + '\n[open project folder]') # SIGNAL self.wgHeader.btnAccept.clicked.connect(self.press_btnAccept) self.wgHeader.btnAccept.setAttribute( QtCore.Qt.WA_TranslucentBackground) self.wgHeader.btnOption.clicked.connect(self.press_btnOption) self.wgHeader.btnOpenFolder.clicked.connect(self.press_btnOpenFolder) self.wgHeader.btnUser.clicked.connect(self.press_btnUser) self.wgHeader.btnProject.clicked.connect(self.press_btnProject) self.wgHeader.btnReport.clicked.connect(self.press_btnReport) self.wgHeader.btnHelp.clicked.connect(self.press_btnHelp) # SETUP self.refresh_data() self.set_status() self.set_open_folder() self.wgHeader.edtComment.setText('') self.wgHeader.setWindowIcon( QtGui.QIcon(Tank().get_img_path("btn/program"))) #self.add_preview(self.wgHeader.layMain) #self.add_menu() self.wgHeader.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) # self.wgHeader.setWindowFlags(QtCore.Qt.CustomizeWindowHint | QtCore.Qt.FramelessWindowHint) # | QtCore.Qt.Tool | QtCore.Qt.WindowStaysOnTopHint) self.wgHeader.show()
tank1_sprite = pygame.image.load("tank1_sprite.png").convert() tank1_sprite = pygame.transform.scale(tank1_sprite, (35, 35)) tank1_sprite.set_colorkey((255, 255, 255)) tank2_sprite = pygame.image.load("tank2_sprite.png").convert() tank2_sprite = pygame.transform.scale(tank2_sprite, (35, 35)) tank2_sprite.set_colorkey((255, 255, 255)) bullet1_sprite = pygame.image.load("bullet1_sprite.png").convert() bullet1_sprite = pygame.transform.scale(bullet1_sprite, (15, 5)) bullet1_sprite.set_colorkey((255, 255, 255)) bullet2_sprite = pygame.image.load("bullet2_sprite.png").convert() bullet2_sprite = pygame.transform.scale(bullet2_sprite, (15, 5)) bullet2_sprite.set_colorkey((255, 255, 255)) run = True tank_1 = Tank(300, 300, 200, tank1_sprite, bullet1_sprite) tank_2 = Tank(100, 100, 200, tank2_sprite, bullet2_sprite, pygame.K_d, pygame.K_a, pygame.K_w, pygame.K_s, pygame.K_SPACE) tanks = [tank_1, tank_2] bullets = [] def hit_check(bullet, which_bullet): global tanks shadow_x1 = [] shadow_x2 = [] shadow_y1 = [] shadow_y2 = [] i = 0
def create_node(this_node=''): if not this_node: this_node = nuke.thisNode() if this_node["customRange"].getValue(): this_node["frameStart"].setValue(int(nuke.Root()['first_frame'].getValue())) this_node["frameEnd"].setValue(int(nuke.Root()['last_frame'].getValue())) this_node["resolutionX"].setValue(this_node.width()) this_node["resolutionY"].setValue(this_node.height()) fileName = os.path.basename(nuke.root().name()).split(".")[0] renderPath = os.path.dirname(os.path.dirname(nuke.root().name())) + "/{render}/{file}/exr/{file}.%04d.exr".format(render=Tank().data_project['STATUS']['render'], file=fileName) renderPath = renderPath.replace('\\','/') # this_node["rootPath"].setValue(renderPath) this_node["exrPath"].setValue(renderPath) this_node["jpgPath"].setValue(renderPath.replace("exr","jpg")) this_node["tifPath"].setValue(renderPath.replace("exr","tif"))
from threading import Thread from Qt import QtWidgets, QtGui, QtCore, QtCompat import pipefunc import arNotice import snapshot from tank import Tank from users import User from arUtil import ArUtil #********************************************************************* # VARIABLE TITLE = os.path.splitext(os.path.basename(__file__))[0] LOG = Tank().log.init(script=TITLE) #********************************************************************* # CLASS class ArSaveAs(ArUtil): def __init__(self, new_file=True): super(ArSaveAs, self).__init__() path_ui = ("/").join([os.path.dirname(__file__), "ui", TITLE + ".ui"]) self.wgSaveAs = QtCompat.loadUi(path_ui) self.all_task = '<all tasks>' self.new_file = new_file self.save_file = ''
def openRV(path): if not os.path.exists(os.path.dirname(path)) or not os.listdir(os.path.dirname(path)): LOG.warning("FOLDER : NOT EXISTS : " + path) else: os.system('start "" "' + Tank().data_software['RV']['path'] + '" ' + path)
def set_meta_data(self, save_path=''): meta_path = os.path.dirname( save_path) + Tank().data_project['META']['file'] comment_dict = {'user': User().id, 'comment': 'new scene'} Tank().set_data(meta_path, os.path.basename(save_path), comment_dict)
class GameWindow(arcade.Window): def __init__(self, width, height, title, key_mappings): super().__init__(width, height, title) self.window_size = (width, height) self.key_mappings = key_mappings self.key_state = {key: None for key in self.key_mappings.keys()} self.mouse_position = (0, 0) self.view_left = 0 self.view_bottom = 0 def setup_level(self, map_source="res/level.tmx"): self.tank_list = arcade.SpriteList() self.tank = Tank(self.tank_list) self.tank.set_position(100, 100) self.bullet_list = arcade.SpriteList() level_map = arcade.tilemap.read_tmx(map_source) self.level_boundary = ((0, 0), (level_map.map_size.width * level_map.tile_size.width, level_map.map_size.height * level_map.tile_size.height)) enemies_position = self.get_enemies_position(level_map) self.layers = { key: None for key in ("boundary", "background", "terrain", "box") } if level_map.background_color: arcade.set_background_color(level_map.background_color) for layer_name in self.layers.keys(): self.layers[layer_name] = arcade.tilemap.process_layer( map_object=level_map, layer_name=layer_name) for sprite in self.layers["box"]: sprite.health = 20 self.physics_engines = [] self.physics_engines.append( arcade.PhysicsEngineSimple(self.tank.wheel_sprite, self.layers["boundary"])) self.physics_engines.append( arcade.PhysicsEngineSimple(self.tank.wheel_sprite, self.layers["box"])) self.ai_sprite_list = arcade.SpriteList() self.ai_objects = [] for position in enemies_position: ai_obj = Tank(self.ai_sprite_list, "res/ai.png") ai_obj.set_position(*position) self.ai_objects.append(ai_obj) self.physics_engines.append( arcade.PhysicsEngineSimple(ai_obj.wheel_sprite, self.tank_list)) self.physics_engines.append( arcade.PhysicsEngineSimple(self.tank.wheel_sprite, self.ai_sprite_list)) self.physics_engines.append( arcade.PhysicsEngineSimple(ai_obj.wheel_sprite, self.layers["boundary"])) self.physics_engines.append( arcade.PhysicsEngineSimple(ai_obj.wheel_sprite, self.layers["box"])) self.path = None self.create_barriers() def create_barriers(self): grid_size = 64 playing_field_left_boundary = self.level_boundary[0][0] + 64 playing_field_right_boundary = self.level_boundary[1][0] - 64 playing_field_top_boundary = self.level_boundary[1][1] - 64 playing_field_bottom_boundary = self.level_boundary[0][1] + 64 self.ai_barriers = [] sp_list = arcade.SpriteList() sp_list.extend(self.layers["box"]) sp_list.extend(self.layers["boundary"]) barrier_list = CustomAStarBarrierList(None, sp_list, grid_size, playing_field_left_boundary, playing_field_right_boundary, playing_field_bottom_boundary, playing_field_top_boundary) for ai in self.ai_objects: barrier_list.moving_sprite = ai.wheel_sprite self.ai_barriers.append(barrier_list) def get_enemies_position(self, level_map): object_layers = filter( lambda x: isinstance(x, pytiled_parser.objects.ObjectLayer), level_map.layers) location = [] for layer in object_layers: if layer.name == "enemies": for obj in layer.tiled_objects: location.append( (obj.location.x, self.level_boundary[1][1] - obj.location.y)) return location def on_key_press(self, key, modifiers): for key_k in self.key_state.keys(): if self.key_mappings[key_k] == key: self.key_state[key_k] = True def on_key_release(self, key, modifiers): for key_k in self.key_state.keys(): if self.key_mappings[key_k] == key: self.key_state[key_k] = False def on_mouse_press(self, x, y, button, modifiers): #print(x, y) self.bullet_list.append(self.tank.fire()) def on_mouse_motion(self, x, y, dx, dy): self.mouse_position = (x + dx, y + dy) self.tank.rotate_turret(self.mouse_position, (self.view_left, self.view_bottom)) def on_update(self, delta_time): """ Movement and game logic """ self.tank.movement(self.key_state, delta_time) for engine in self.physics_engines: engine.update() self.bullet_list.update() for bullet in self.bullet_list: hit_list = arcade.check_for_collision_with_list( bullet, self.layers["boundary"]) hit_list.extend( arcade.check_for_collision_with_list(bullet, self.layers["box"])) items = arcade.check_for_collision_with_list( bullet, self.layers["box"]) removed = False for item in items: if hasattr(item, "health"): item.health -= bullet.damage if item.health <= 0: item.remove_from_sprite_lists() removed = True if removed: self.create_barriers() if len(hit_list) > 0: bullet.remove_from_sprite_lists() self.tank.update() self.tank.rotate_turret(self.mouse_position, (self.view_left, self.view_bottom)) for self.ai_object in self.ai_objects: self.ai_object.update() enemy = self.ai_object.wheel_sprite enemy_x, enemy_y = enemy.position tank_x, tank_y = self.tank.wheel_sprite.position distance_between_ai_and_tank = ((tank_x - enemy_x)**2 + (tank_y - enemy_y)**2)**(0.5) if distance_between_ai_and_tank < 1000 and distance_between_ai_and_tank > 100: self.path = arcade.astar_calculate_path( enemy.position, self.tank_list[0].position, self.ai_barriers[0], diagonal_movement=True) if self.path and len( self.path) > 1 and distance_between_ai_and_tank > 100: x1, y1 = self.path[1] x2, y2 = self.ai_object.wheel_sprite.position direction = (x1 - x2), (y1 - y2) x, y = direction magnitude = (x**2 + y**2)**0.5 unit_vector = x / magnitude, y / magnitude velocity = self.ai_object.movement_speed req_vector = unit_vector[0] * velocity, unit_vector[ 1] * velocity delta_position = req_vector[0] * \ delta_time, req_vector[1] * delta_time angle = math.atan2( *unit_vector[::-1]) - self.ai_object.rotation self.ai_object.rotate_body(angle) #ai turret roatation x, y = self.tank.body_sprite.position turret_x, turret_y = self.ai_object.turret_sprite.position if (turret_y - y) != 0: rad = math.atan2((turret_x - x), (y - turret_y)) self.ai_object.turret_sprite.radians = rad #ai bullet firing self.ai_object.change_position(*delta_position) self.ai_object.ai_fire_dt += delta_time if (self.ai_object.ai_fire_dt > (1 / self.ai_object.ai_fire_rate)): self.bullet_list.append(self.ai_object.fire()) self.ai_object.ai_fire_dt -= ( 1 / self.ai_object.ai_fire_rate) self.scroll(self.tank.body_sprite) def draw_health(self): height_offset = 15 healthbar_width = 70 healthbar_height = 10 if hasattr(self.tank, "health"): sprite = self.tank.body_sprite if self.tank.health != 100: arcade.draw_rectangle_filled( sprite.center_x, sprite.center_y + sprite.height + height_offset, healthbar_width, healthbar_height, arcade.csscolor.WHITE) width = healthbar_width * self.tank.health / 100 width_reduced = healthbar_width - width arcade.draw_rectangle_filled( sprite.center_x - width_reduced / 2, sprite.center_y + sprite.height + height_offset, width, healthbar_height, arcade.csscolor.GREEN) def scroll(self, follow_sprite): left_viewport_margin = 250 right_viewport_margin = 250 bottom_viewport_margin = 250 top_viewport_margin = 250 changed = False # Scroll left left_boundary = self.view_left + left_viewport_margin if self.tank.body_sprite.left < left_boundary and self.view_left > self.level_boundary[ 0][0]: self.view_left -= left_boundary - self.tank.body_sprite.left changed = True # Scroll right right_boundary = self.view_left + \ self.window_size[0] - right_viewport_margin if self.tank.body_sprite.right > right_boundary and self.view_left + self.window_size[ 0] < self.level_boundary[1][0]: self.view_left += self.tank.body_sprite.right - right_boundary changed = True # Scroll up top_boundary = self.view_bottom + \ self.window_size[1] - top_viewport_margin if self.tank.body_sprite.top > top_boundary and self.view_bottom + self.window_size[ 1] < self.level_boundary[1][1]: self.view_bottom += self.tank.body_sprite.top - top_boundary changed = True # Scroll down bottom_boundary = self.view_bottom + bottom_viewport_margin if self.tank.body_sprite.bottom < bottom_boundary and self.view_bottom > self.level_boundary[ 0][1]: self.view_bottom -= bottom_boundary - self.tank.body_sprite.bottom changed = True if changed: # Only scroll to integers. Otherwise we end up with pixels that # don't line up on the screen self.view_bottom = int(self.view_bottom) self.view_left = int(self.view_left) arcade.set_viewport(self.view_left, int(self.window_size[0] + self.view_left), self.view_bottom, self.window_size[1] + self.view_bottom) def on_draw(self): arcade.start_render() for value in self.layers.values(): value.draw() self.bullet_list.draw() self.ai_sprite_list.draw() self.tank_list.draw() self.draw_health() if self.path: arcade.draw_line_strip(self.path, arcade.color.BLUE, 2)
value = os.path.normpath(value) if self.has_key(key): self[key].append(value) else: self[key] = [value] def __missing__(self, key): return key #********************************************************************* # START import argparse parser = argparse.ArgumentParser(description='Setup your pipeline and start scripts.') parser.add_argument('-so','--software', help='add software: nuke') parser.add_argument('-p', '--proxy', action='store_true') args = parser.parse_args() if args.software: Setup() from tank import Tank if args.software == 'desktop': # Tank().start_software(args.software) import arDesktop arDesktop.start() else: Tank().start_software(args.software)
from stream import Stream from tank import Tank from system import System for steps in [10, 50, 100, 200, 500]: tank_system = System() tank1 = Tank('Tank A') tank2 = Tank('Tank B', start_salt=20, line_color="-b") streams1_in = [Stream(6, 0.2), Stream(1, tank2)] streams1_out = [Stream(3, tank1), Stream(4, tank1)] for stream in streams1_in: tank1.add_stream_in(stream) for stream in streams1_out: tank1.add_stream_out(stream) streams2_in = [Stream(3, tank1)] streams2_out = [Stream(1, tank2), Stream(2, tank2)] for stream in streams2_in: tank2.add_stream_in(stream) for stream in streams2_out: tank2.add_stream_out(stream) tank_system.add_tank(tank1) tank_system.add_tank(tank2)
def set_pipeline_env(self): # SET STATUS os.environ['PIPELINE_STATUS'] = self.pipeline_status # ADD sub ENV for eachPath in self.data_pipeline_path: self.pipeline_env.add('PIPELINE_PATH', eachPath) if os.path.exists(eachPath + '/img'): self.pipeline_env.add('IMG_PATH', eachPath + '/img') if os.path.exists(eachPath + '/software'): self.pipeline_env.add('SOFTWARE_PATH', eachPath + '/software') if os.path.exists(eachPath + '/lib'): self.pipeline_env.add('LIB_PATH', eachPath + '/lib') if os.path.exists(eachPath + '/lib/apps'): self.pipeline_env.add('APPS_PATH', eachPath + '/lib/apps') if os.path.exists(eachPath + '/lib/extern'): self.pipeline_env.add('EXTERN_PATH', eachPath + '/lib/extern') if os.path.exists(eachPath + '/lib/dcc'): self.pipeline_env.add('DCC_PATH', eachPath + '/lib/dcc') os.environ['DATA_PATH'] = self.data_pipeline_path[0] + '/data' os.environ['DATA_PROJECT_PATH'] = self.data_pipeline_path[0] + '/data/project/' + self.pipeline_data['project'] # ADD all pipeline env self.add_env('PIPELINE_PATH', (';').join(self.pipeline_env['PIPELINE_PATH'])) try: self.add_env('IMG_PATH', (';').join(self.pipeline_env['IMG_PATH'])) self.add_env('LIB_PATH', (';').join(self.pipeline_env['LIB_PATH'])) self.add_env('APPS_PATH', (';').join(self.pipeline_env['APPS_PATH'])) self.add_env('EXTERN_PATH', (';').join(self.pipeline_env['EXTERN_PATH'])) self.add_env('DCC_PATH', (';').join(self.pipeline_env['DCC_PATH'])) self.add_env('SOFTWARE_PATH', (';').join(self.pipeline_env['SOFTWARE_PATH'])) self.add_env('SOFTWARE_SRC_PATH', (';').join(self.pipeline_env['SOFTWARE_PATH'])) except: raise OSError ('STOP PROCESS', 'PATH doesnt exist in data/pipeline.yml', self.this_pipeline) sys.path.append(os.environ['PIPELINE_PATH']) sys.path.append(os.environ['IMG_PATH'] ) sys.path.append(os.environ['LIB_PATH']) sys.path.append(os.environ['APPS_PATH']) sys.path.append(os.environ['DCC_PATH']) sys.path.append(os.environ['SOFTWARE_PATH'] ) sys.path.append(os.environ['DATA_PATH']) sys.path.append(os.environ['DATA_PROJECT_PATH']) self.add_env('PYTHONPATH', os.environ['IMG_PATH']) self.add_env('PYTHONPATH', os.environ['LIB_PATH']) self.add_env('PYTHONPATH', os.environ['APPS_PATH']) self.add_env('PYTHONPATH', os.environ['EXTERN_PATH']) self.add_env('PYTHONPATH', os.environ['DCC_PATH']) # DATA ENV os.environ['DATA_USER_PATH'] = self.data_pipeline_path[0] + '/data/user/' + getpass.getuser() os.environ['DATA_USER_OVERWRITE'] = str(self.pipeline_data['user_data']) sys.path.append(os.environ['DATA_USER_PATH']) # SET project Data from tank import Tank self.project_data = Tank().data_project os.environ['PROJECT_NAME'] = self.project_data['name'] # ADD project path if os.path.exists(self.project_data['path']): os.environ['PROJECT_PATH'] = os.path.normpath(self.project_data['path']) else: os.environ['PROJECT_PATH'] = '' # OS & PYTHON_VERSION os.environ['OS'] = sys.platform os.environ['PYTHON_VERSION'] = sys.version[:3]
class PyTanksIO: """ Main class that contains most of the code for the game """ def __init__(self, width, height, title): # Window initializing code self.win_size = width, height self.win = pygame.display.set_mode((width, height)) pygame.display.set_caption(title) self.running = True self.background = (0, 0, 0) # Pymunk initializing code pymunk.pygame_util.positive_y_is_up = False self.space = pymunk.Space() self.space.gravity = 0, 700 # Create game objects self.ground = Ground(self.win_size[0], 150, self.win_size) self.player1 = Tank("red") self.player2 = Tank("blue") self.bullets = [] # Setup code self.current_player = self.player1 self.other_player = self.player2 self.moves_left = 100 self.shoot_wait = 380 self.shooting = False self.player1.body._set_position((100, 250)) self.player2.body._set_position((width-136, 250)) # Add game objects to space self.ground.add_to_space(self.space) self.player1.add_to_space(self.space) self.player2.add_to_space(self.space) def input(self, keys): current_p = self.current_player body = self.current_player.body speed = Tank("ehhh").vertices[2][0] * 2.3333333333 rot_speed = 0.7 power_speed = 1 if not self.shooting: # Tank Movement if body.velocity[1] < 1 and self.moves_left > 0: if keys[pygame.K_d] or keys[pygame.K_RIGHT]: body.velocity = speed, body.velocity[1] self.moves_left -= 1 if keys[pygame.K_a] or keys[pygame.K_LEFT]: body.velocity = -speed, body.velocity[1] self.moves_left -= 1 # Turret Rotation if keys[pygame.K_q] or keys[pygame.K_COMMA]: current_p.turn_turret(rot_speed) if keys[pygame.K_e] or keys[pygame.K_PERIOD]: current_p.turn_turret(-rot_speed) # Power Adjusting if keys[pygame.K_w] or keys[pygame.K_UP]: current_p.fire_power += power_speed if keys[pygame.K_s] or keys[pygame.K_DOWN]: current_p.fire_power -= power_speed # Firing if keys[pygame.K_SPACE] and current_p.fire_timer >= 100: self.shooting = True current_p.fire_timer = 0 bullet = current_p.shoot() bullet.add_to_space(self.space) self.bullets.append(bullet) elif self.shooting: self.shoot_wait -= 1 self.moves_left = 100 def logic(self): # Update Rects for rendering self.player1.update() self.player2.update() current_p = self.current_player other_p = self.other_player for bullet in self.bullets: # Collision with ground if self.ground.rect.colliderect(bullet.rect): bullet.body.velocity *= 0, 1 bullet.update() # Collision with tanks if bullet.rect.colliderect(current_p.rect): current_p.score -= randint(5, 10) self.bullets.remove(bullet) self.shoot_wait = 35 elif bullet.rect.colliderect(other_p.rect): current_p.score += randint(10, 15) self.bullets.remove(bullet) self.shoot_wait = 35 # Reset self.shooting if self.shoot_wait <= 0: self.bullets.clear() self.shooting = False self.shoot_wait = 380 self.current_player, self.other_player = self.other_player, self.current_player def render(self): self.win.fill(self.background) # Render Game Objects self.ground.render(self.win) self.player1.render(self.win) self.player2.render(self.win) for bullet in self.bullets: bullet.render(self.win) # Render UI Elements text( self.win, "Player 1: " + str(self.player1.score), 35, (255, 255, 255), (80, 30) ) text( self.win, "Player 2: " + str(self.player2.score), 35, (255, 255, 255), (self.win_size[0] - 80, 30) ) if self.current_player == self.player1: turn_display = "Player 1's Turn" elif self.current_player == self.player2: turn_display = "Player 2's Turn" if not self.shooting: text( self.win, turn_display, 40, (255, 255, 255), (self.win_size[0] / 2, self.win_size[1] - 70) ) pygame.display.flip()
import os import maya.mel as mel import maya.cmds as cmds import maya.OpenMaya as api import libLog from tank import Tank import libLog TITLE = os.path.splitext(os.path.basename(__file__))[0] LOG = libLog.init(script=TITLE) software_data = Tank().software.data def setup_scene(file_path=''): # RESOLUTION try: cmds.setAttr("defaultResolution.width", Tank().data['project']['resolution'][0]) cmds.setAttr("defaultResolution.height", Tank().data['project']['resolution'][1]) cmds.setAttr('defaultResolution.deviceAspectRatio', ((Tank().data['project']['resolution'][0]) / (Tank().data['project']['resolution'][1]))) except: LOG.error('FAILED load resolution.', exc_info=True)
def __init__(self, grid: Grid): self.grid = grid self.shots = Shots(self.grid) self.greenTank = Tank(CellType.GreenTankBody, self.grid.green_start) self.blueTank = Tank(CellType.BlueTankBody, self.grid.blue_start)
# date = 2019-12-01 # # license = MIT <https://github.com/alexanderrichtertd> # author = Alexander Richter <alexanderrichtertd.com> #********************************************************************* import os import sys import maya.cmds as cmds import maya_utils from tank import Tank #********************************************************************* # VARIABLE TITLE = 'userSetup' # os.path.splitext(os.path.basename(__file__))[0] LOG = Tank().log.init(script=TITLE) #********************************************************************* # INIT AND PRINT CONSOLE Tank().init_software(os.getenv('SOFTWARE')) Tank().software.print_checked_header( 'menu', func=cmds.evalDeferred("maya_utils.load_menus()")) Tank().software.print_checked_header('shelf') Tank().software.print_checked_header('scene setup') Tank().software.print_checked_header('render setup') print("")
def __init__(self): Tank.__init__(self) self.sensors = [Sensor(0, 10, 60, True), Sensor(0, 120, 100, False), Sensor(120, 120, 100, False), Sensor(240, 120, 100, False)]
class World(object): ''' Inits ==================================''' def __init__(self, width, height): self.width = width self.height = height self.center = Vector2D(width/2, height/2) self.obstacles = [] self._clock = 0 self.scale = 10 self.gravity = Vector2D(0, -900) self.makeTank() self.makeFish() self.makeDebug() self.makeFood() self.makeObstacles() self.makeHunters() ''' Setup methods ==================================''' def makeFish(self): self.fishes = [] def makeFood(self): self.food = [] self.foodDistance = 30 self.autoFeed = True self.autoFeedAboveInterval = 2 # seconds self.autoFeedBelowInterval = 1 # seconds self.sicknessEnabled = True self.sicknessInterval = 0.1 clock.schedule_interval(self.autoAddFoodAbove, self.autoFeedAboveInterval) clock.schedule_interval(self.autoAddFoodBelow, self.autoFeedBelowInterval) clock.schedule_interval(self.makeFishSicker, self.sicknessInterval) def makeTank(self): self.tank = Tank(world=self) def makeObstacles(self): self.obstacles = [] self.addRocks(10) def makeHunters(self): self.hunters = [] self.addHunters() ''' 'Add' methods ==================================''' def addFood(self, x, y=None, num = 1): # If no y was given then use the standard food distance above the tank if(y is None): y = self.height - self.foodDistance else: y = Util.clamp(self.tank.box.bottom, y, self.height) # Make sure the food will go in the tank x = Util.clamp(self.tank.box.left, x, self.tank.box.right) # Add the foods for _ in range(num): newFood = Food(world=self) newFood.pos = Vector2D(x, y) self.food.append(newFood) def obstacleOverlapsOtherObstacles(self, obstacle): breathingSpace = 20 for o in self.obstacles: if(o.pos.distance(obstacle.pos) - obstacle.boundingRadius - o.boundingRadius < breathingSpace): return True return False def addRocks(self, num=10): for i in range(num): newRock = Rock(world=self) newRock.vel = Vector2D.random(newRock.maxSpeed) newRock.vel.y = 0 newRock.pos = self.tank.randomPosition() while(self.obstacleOverlapsOtherObstacles(newRock)): newRock.pos = self.tank.randomPosition() self.obstacles.append(newRock) def autoAddFoodAbove(self, dt=0): self.autoAddFood(above=True) def autoAddFoodBelow(self, dt=0): self.autoAddFood(above=False) self.autoAddFood(above=False) def autoAddFood(self, above = True): # Make sure auto food is enabled if(not self.autoFeed): return position = self.tank.randomPosition() # Add the food if(above): self.addFood(x = position.x) else: self.addFood(x = position.x, y = position.y) def addHunters(self, num=1): # Add the foods for _ in range(num): newHunter = Hunter(world=self) newHunter.pos = self.tank.randomPosition() self.hunters.append(newHunter) ''' Updating ==================================''' def update(self, delta, forced=False): self.lastDelta = delta if not self.paused or forced: self._clock += delta # Debug fish if(len(self.fishes)): self.fishes[0].chosenOne = True if(len(self.hunters)): self.hunters[0].chosenOne = True # Keep list of living fish for food calculatinons self.livingFishes = [f for f in self.fishes if not f.dead] # TODO: Calculate fish times/distances from foods for everything so it isn't # recalculated by every fish * food # self.calculateFoodData() # Updates [f.update(delta) for f in self.fishes] [f.update(delta) for f in self.food if not f.eaten] [o.update(delta) for o in self.obstacles] [h.update(delta) for h in self.hunters] # Kill dead fishes self.fishes = [f for f in self.fishes if not (f.dead and f.pos.y < self.tank.box.bottom - 50)] # Remove food that's off the screen self.food = [f for f in self.food if not f.eaten] def makeFishSicker(self, dt=0): # Make sure sickness is enabled if(not self.sicknessEnabled): return [f.sicker() for f in self.fishes] ''' Rendering ==================================''' def render(self): # Draw tank first self.tank.render() # Then fish [f.render() for f in self.fishes] # Food [f.render() for f in self.food if not f.eaten] # Rocks [o.render() for o in self.obstacles] # Hunters [h.render() for h in self.hunters] ''' World logic ==================================''' def resize(self, width, height): self.width = width self.height = height self.center = Vector2D(width/2, height/2) self.tank.resize() def addFish(self, num=1): if(num < 1): return newFishes = [] for _ in xrange(num): newFish = Guppy(world=self, scale=10) self.fishes.append(newFish) newFishes.append(newFish) # if(num == 1) # return newFishes[0] return newFishes def randomizePath(self): self.path.create_random_path(8, self.width/6, self.height/6, self.width*2/3 + self.width/6, self.height*2/3 + self.height/6) for agent in self.fishes: agent.path = self.path def getNeighbours(self, agent, distance=100): distanceSq = distance**2 return [a for a in self.fishes if a != agent and a.pos.distanceSq(agent.pos) < distanceSq] def getFood(self, agent, distance=10000): return [f for f in self.food if not f.eaten and self.tank.contains(f.pos)] # Enables/disables the circle of life properties @property def lionKing(self): return self.autoFeed # same value for both, so just pick this one @lionKing.setter def lionKing(self, value): self.autoFeed = value self.sicknessEnabled = value ''' Util ==================================''' def wrap_around(self, pos): ''' Treat world as a toroidal space. Updates parameter object pos ''' max_x, max_y = self.width, self.height if pos.x > max_x: pos.x = pos.x - max_x elif pos.x < 0: pos.x = max_x - pos.x if pos.y > max_y: pos.y = pos.y - max_y elif pos.y < 0: pos.y = max_y - pos.y def transform_points(self, points, pos, forward, side, scale=Vector2D(1, 1)): ''' Transform the given list of points, using the provided position, direction and scale, to object world space. ''' # make a copy of original points (so we don't trash them) wld_pts = Util.copyPoints(points) # create a transformation matrix to perform the operations mat = Matrix33() # scale, mat.scale_update(scale.x, scale.y) # rotate mat.rotate_by_vectors_update(forward, side) # and translate mat.translate_update(pos.x, pos.y) # now transform all the points (vertices) mat.transform_vector2d_list(wld_pts) # done return wld_pts def transform_point(self, point, pos, forward, side): ''' Transform the given single point, using the provided position, and direction (forward and side unit vectors), to object world space. ''' # make a copy of the original point (so we don't trash it) wld_pt = point.copy() # create a transformation matrix to perform the operations mat = Matrix33() # rotate mat.rotate_by_vectors_update(forward, side) # and translate mat.translate_update(pos.x, pos.y) # now transform the point (in place) mat.transform_vector2d(wld_pt) # done return wld_pt ''' Debug variables ==================================''' def makeDebug(self): self.paused = False self.drawDebug = False, self.drawComponentForces = False self.drawHidingSpots = False self.awokenHunter = True
def create_basic_enemy(position): return Tank(position, [ controllers.BounceMoveController(), controllers.BasicTargetingController(), controllers.EnemyDieController() ])
from tank import Tank brewer = None tank = None print('Listening to Slack...') try: while True: for notification in Chat.getNotifications(): Chat.processNotification(notification) while True: action = Chat.getNextAction() if action is None: break if brewer and brewer.isAlive(): Chat.talk('Oh I\'m kind of busy now! Please wait a bit and I\'ll take your order @{0}.' .format(action['user']['name']), channel=action['notification']['channel']) continue # Spam a brewing process. brewer = Brewer(action['isShort'], action['notification']['channel'], action['user']) brewer.start() if not tank or not tank.isAlive() and not Chat.isDisabled(): # Spam a tank check process. tank = Tank() tank.start() time.sleep(0.5) finally: Senseo.disablePump() Senseo.close()
time.sleep(0.1) # 软件延时 except KeyboardInterrupt: pass ser.close() return result_str fruit_list = ['fruit', 'apple', 'banana', 'orange'] meat_list = ['meat', 'beef', 'pork', 'fish'] drinking_list = ['drinking', 'milk', 'yogurt', 'coke'] food_database = [fruit_list, meat_list, drinking_list] for list in food_database: if detection_result in list: detection_attribute = list[0] new_food = Food(detection_result, detection_attribute) break fridge = [] for i in range(6): tank = Tank() fridge.append(tank) new_food_2 = Food('orange', 'fruit') fridge[0].add_food(new_food) fridge[0].add_food(new_food_2) for tank in fridge: tank.print_content()