def __init__(self, model, shape, element, lvl, duration, damage): Object.__init__(self, model, shape, element) self.duration = duration self.elapsed = 0.0 self.lvl = lvl self.damage = damage
def __init__(self, sequence, \ id, type, name, \ size, \ posx, posy, posz, \ velx, vely, velz, \ contains, \ order_types, \ order_number, \ modify_time, \ owner, resources): Object.__init__(self, sequence, \ id, type, name, \ size, \ posx, posy, posz, \ velx, vely, velz, \ contains, \ order_types, \ order_number, \ modify_time) self.length += 4 + 4 + 16 * len(resources) self.owner = owner for r in resources: if len(r) != 4: raise TypeError("Resources should be 4 length, <id> <surface> <minable> <inaccess>") self.resources = resources
def tick(self, time_elapsed): Object.tick(self, time_elapsed) self.elapsed += time_elapsed if (self.elapsed >= self.duration): self.lvl.remove_object(self)
def __init__( self, stats, ai, xp, yp, zp=0, ori=0.0, xi=0, yi=0, zi=0, ri=0, thrust=0 ): Object.__init__( self, stats, xp, yp, zp, ori, xi, yi, zi, ri ) self.alive = True self.maxOri = 2*pi self.thrust = thrust self.rg = 0 self.shieldVsMass = self.stats.shieldVsMass self.shieldVsEnergy = self.stats.shieldVsEnergy self.hullVsMass = self.stats.hullVsMass self.hullVsEnergy = self.stats.hullVsEnergy self.ai = ai self.dockedTo = False self.dockedAt = 0 # tick at docking self.hull = stats.maxHull self.shield = stats.maxShield self.inertiaControl = True self.headed = True # differentiate bases from ships self.pulsedUntil = -1000 self.inNebula = False # variable state self.inertiaMod = 1 self.thrustBoost = 0 self.shipyards = [] # list of regulard shipyards self.guestDocked = [] # list of temporary docks
def __init__(self, x, y, char, name, color, blocks=True, ai=None, always_visible=False, equipment=None, character_class=None, creature_type=None, xp=0, screen=None): #call super constructor to create the map object Object.__init__(self, x, y, char, name, color, blocks=blocks, always_visible=always_visible) self.character_class = character_class if self.character_class: # let the fighter component know who owns it self.character_class.owner = self self.screen = screen if self.screen: # set the screen element in the character_class self.character_class.screen = screen self.ai = ai if self.ai: # let the ai component know who owns it self.ai.owner = self self.xp = xp self.dead = False self.inventory = [] #set the default equipment dictionary. self.equipment = {'head': None, 'body':None, 'legs':None, 'hands':None, 'feet':None, 'left hand': None, 'right hand': None} self.player = None
def __init__(self, sequence, \ id, type, name, \ size, \ posx, posy, posz, \ velx, vely, velz, \ contains, \ order_types, \ order_number, \ modify_time, \ owner, ships, damage): Object.__init__(self, sequence, \ id, type, name, \ size, \ posx, posy, posz, \ velx, vely, velz, \ contains, \ order_types, \ order_number, \ modify_time) self.length += 4 + 4 + len(ships) * 8 + 4 self.owner = owner self.ships = ships self.damage = damage
def __init__(self, x, y, char, name, color, slot, power_bonus=0, defense_bonus=0, max_hp_bonus=0): Object.__init__(self, x, y, char, name, color, blocks=False, always_visible=False) self.slot = slot self.is_equipped = False self.power_bonus = power_bonus self.defense_bonus = defense_bonus self.max_hp_bonus = max_hp_bonus
def __init__(self, parent_context, param_list, statements): import proto_functions Object.__init__(self, prototype=proto_functions.function_proto) self.parent_context = parent_context self.param_list = param_list self.statements = statements self.constructing_prototype = Object()
def drawNewBuilding(x, theScore): global buildingList, objectList, scrollSpeed, bomb, walls, pigeonList startX = x startY = random.getrandbits(5) + 30 if startY > 70: startY = 70 wallId = random.getrandbits(3) + 1 if wallId > 3: wallId = 3 buildingLength = ((random.getrandbits(3) + 1) * 3) + 2 if buildingLength < 10: buildingLength = 10 wallId = 0 spacing = random.getrandbits(2) + 1 # Do we need birds if buildingLength > 15 and random.getrandbits(7) > 100: ctr = 4 for bird in pigeonList: bird.reset(startX + ctr + 20 + (spacing * 8), startY - 6) ctr += 7 floorId = random.getrandbits(3) if floorId > 3: floorId = 3 # Create a box or bomb if building is long enough and not the first building if theScore > 100: # Don't do this on first building if x != 0: objType = random.getrandbits(1) if buildingLength > 15: if random.getrandbits(3) > 5: # Crate if objType == 0: objectList.append( Object(blocks, startX + (buildingLength * 8) // 2, startY, objType, 14, 14)) # Bomb else: objectList.append( Object(bomb, startX + ((buildingLength - 3) * 8), startY, objType, 18, 11)) windowId = random.getrandbits(1) if x == 0: spacing = 0 buildingList.append( Building(startX, startY, buildingLength, spacing, floorId, wallId, windowId))
def __init__(self): self.all_sprites = pygame.sprite.Group() self.key_group = pygame.sprite.Group() self.image = Object(MENU_ASSET, 0, 0, self.all_sprites) self.key = Object(KEY_ASSET, 0, 600, self.key_group) self.menu_water = Object(MENU_WATER, 0, 550, self.all_sprites) self.change_scene = False self.tick = 0
def __init__(self, position): Object.__init__(self) self.frame = 0 self._position = position self.frames = self._cls_frames[:] self.frames_count = len(self.frames) self._current_frame_time = 0 self._finished = False self.load_frame()
def __init__(self, source, image, coords): Object.__init__(self, source, image, coords) self.source = source self.wallgroup = self.source.wallgroup self.wall_list = [] for w in self.wallgroup.sprites(): self.wall_list.append(w.rect) self.walls = self.wall_list """ # old settings for sanity self.speed = 2 self.ammo_speed = 3 self.cooldown = 250 self.blast_cool = 2000 self.run_cool = 3000 self.run_time = 750 """ tree = ET.parse("settings.xml") root = tree.getroot().find("player") fps = int(tree.getroot().find("main").find("fps").text) self.speed = int(root.find("speed").text) self.double_speed = self.speed * 2 self.half_speed = int(self.speed) self.velocity = 0.4 self.ammo_speed = float(root.find("ammo_speed").text) * self.speed self.cooldown = int(root.find("cooldown").text) self.blast_cool = int(root.find("blast_cool").text) self.blast_radius = int(root.find("blast_radius").text) self.run_cool = int(root.find("run_cool").text) self.run_time = int(root.find("run_time").text) self.ammo_image = path.join("images", "ammo.png") self.ammogroup = pygame.sprite.Group() self.blastgroup = pygame.sprite.Group() self.bombgroup = pygame.sprite.Group() self.aimx = lambda x: x #* self.speed self.aimy = lambda y: y #* self.speed #self.shoot_start = pygame.time.get_ticks() - self.cooldown #self.blast_start = pygame.time.get_ticks() - self.blast_cool self.run_start = pygame.time.get_ticks() - self.run_cool self.can_blast = True self.can_run = True self.run_speed = self.speed * 2 self.old_dir = (1, 0) self.old_ammo_dir = (0, 0) self.ray_shrink = (-24, -6) self.cast = Cast(self) self.ammo_spawner = Spawner(self, deltaAmmo, self.cooldown, self.ammo_speed, self.ammo_image, 1, self.ammogroup) self.sarja_spawner = Spawner(self, deltaAmmo, self.cooldown, self.ammo_speed, self.ammo_image, 6, self.ammogroup) self.blast_spawner = Spawner(self, Blast, self.blast_cool, 1, self.ammo_image, 1, self.blastgroup) self.bomb_spawner = Spawner(self, Bomb, self.blast_cool, 250, self.ammo_image, 1, self.bombgroup) self.run_spawner = Spawner(self, Run, self.run_cool, self.run_time, None, 1, None)
def change_level(levelnumber, inv = [], coins=0): level = l.levels[levelnumber] news.append("Level " + str(levelnumber + 1) + ", " + l.levels[levelnumber].name + "...") floorplan_file = level.m gobbonum = level.num_gobbos coinum = level.num_gold time = level.time cs = [] objects = level.objects floorplan = read_floorplan(floorplan_file) width = len(floorplan[1]) height = len(floorplan) # x, y, image, color player = creatures.Creature(18, 17, "@", 1, "player") player.coins = coins player.health = 3 cs.append(player) player.inv = inv rawck = Object(0,0,".", 12, "rock") player.inv.append(rawck) gobbo = creatures.Creature(0, 0, "&", 4, "gobbo") spawn_random(1, width - 1, 1, height - 2, gobbo, floorplan, cs, gobbonum) villager = creatures.Creature(0, 0, "v", 17, "villager") spawn_random(1, width - 1, 1, height - 2, villager, floorplan, cs, level.num_villagers) for v in cs: if v.type == "villager" and level.name == "The dwarven village of Brorldown": brorlspeeches = ["Gooday stranger, welcome to our modest little town of Brorldown.", "I see you are loaded with stolen loot! Might I sugest you check out our magic item shops?", "Oh its you, the notorious Namafero, raider of goblins! It is an honor to have you in our town...", "'Sup!", "I hope you enjoy your stay here, adventurer!"] v.speek = choice(brorlspeeches) if v.type == "villager" and level.name == "The Begining": tankspeeches = ["Gooday stranger, welcome to our modest little town of Tankton.", "I hear the town mage wants to converse with you.", "You're going into the goblin base? That's madness! You'll die!", "Hello there!", "I hope you enjoy your stay here, adventurer!"] v.speek = choice(tankspeeches) chest = Object(0,0,"=", 15, "treasure chest") spawn_random(1, width - 1, 1, 5, chest, floorplan, objects, 1) coin = Object(0,0,"$",15,"coin") spawn_random(1, width - 1, 1, height - 2, coin, floorplan, objects, coinum) for i in level.inhabitants: cs.append(i) return (cs, objects, floorplan, time)
def load_kitti(path, mode='train', image_dir=None, label_dir=None): packets = [] with open(path + mode + '.txt', 'rb') as f: file_list = [x.strip() for x in f.readlines()] for file in file_list: image_path = image_dir + file + '.png' label_path = label_dir + file + '.txt' with open(label_path) as f: object_list = [] for line in f: obj_class, truncated, occluded, alpha, bx1, by1, bx2, by2, dz, dy, dx, tx, ty, tz, rot_y = line.split( ) if obj_class == 'Car': #and float(truncated) == 0: #and float(occluded) == 0 : size = [float(x) for x in [dx, dy, dz]] position = [float(x) for x in [tx, ty, tz]] rot_y = float(rot_y) top_left = (int(float(bx1)), int(float(by1))) bottom_right = (int(float(bx2)), int(float(by2))) obj = Object(obj_class, top_left=top_left, bottom_right=bottom_right) obj.size = size obj.position = position object_list.append(obj) if object_list != []: packet = Packet(image_path, objects=object_list) else: continue packets.append(packet) return packets
def __init__(self, model, shape, element, lvl, damage, target_obj, attract_v): Object.__init__(self, model, shape, element) self.lvl = lvl self.damage = damage self.target = target_obj self.velocity = attract_v self.dir = Vector3d(0.,0.,0.)
def world_building(self, object_num): if not self.running and (object_num < 4 or self.draw_goal == False): if self.custom_build or object_num > 3: self.placing_object = True # Centered so cursor is in the middle of the image self.unplaced = Object(0, (self.pos[0] - 200, self.pos[1] - 200)) self.unplaced.load_image("image_resources/" + self.block_images[object_num] + ".png") self.unplaced_goal = (object_num > 3)
def analyze_img(): #print("-------------REQUESTED ANALYZE IMAGE --------------------") # Set image_url to the URL of an image that you want to analyze. # img_url = image name if request.args.get('img_url'): image_url = app.config['IMG_FOLDER'] + request.args.get('img_url') else: return json.dumps({"Error": "Img_url is missing"}) headers = { 'Ocp-Apim-Subscription-Key': subscription_key_cv, 'Content-Type': 'application/octet-stream' } params = {'visualFeatures': 'Objects'} image_data = open(image_url, "rb").read() # data = {'url': image_url} response = requests.post(analyze_url, headers=headers, params=params, data=image_data) response.raise_for_status() # The 'analysis' object contains various fields that describe the image. The most # relevant caption for the image is obtained from the 'description' property. analysis = response.json() object_list = [] for object in analysis['objects']: obj_h = object['rectangle']['h'] desc = object['object'] if desc in OBJECTS_HEIGHT.keys(): real_height = OBJECTS_HEIGHT[desc.lower()] else: real_height = 15 obj = Object(obj_h, real_height, desc, object['rectangle']) obj.calculate_distance() object_list.append(obj) object_list = sorted(object_list, key=lambda k: k.distance) response_json = [] for obj in object_list: #print(str(obj)) d = { 'img_height': obj.img_height, 'real_height': obj.real_height, 'desc': obj.desc, 'distance': obj.distance, 'direction': get_directions(obj, image_url), 'position': obj.position } response_json.append(d) #print(response_json) return json.dumps(response_json)
def __init__(self, model, shape, element, level): Object.__init__(self, model, shape, element) cfg = Config('physics', 'Ship') self.move_force_sz = cfg.get('move_force') self.spin_velocity = cfg.get('spin_velocity') self.strafe_force = cfg.get('strafe_force') self.shape.forces_res.append(cfg.get('vacuum_resistance')) self.breake_rate = cfg.get('breake_rate') self.mouse_sensivity = Config('game', 'Mouse').get('sensivity') self.level = level self.rotation = Quaternion.from_axis_rotations(0., 0., 0.) self.ship_dir = None self.up_dir = None self.spinning = { 'up': False, 'down': False, 'left': False, 'right': False } self.vectors = { 'up': (Vector3d.x_axis(), 1.), 'down': (Vector3d.x_axis(), -1.), 'left': (Vector3d.y_axis(), 1.), 'right': (Vector3d.y_axis(), -1.) } self.strafe = { 'forward': False, 'left': False, 'right': False, 'breake': False } self.strafe_vectors = { 'forward': Vector3d(0., 0., -0.7), 'left': Vector3d(-0.9, 0., 0.), 'right': Vector3d(0.9, 0., 0.), 'breake': Vector3d(0., 0., 1.) } self.angles = [0., 0.] self.mouse_target = [0., 0.] self.collision_set = set() self.keep_colliding = set()
def tick(self, time_elapsed): if (hasattr(self.target, 'destroyed') and self.target.destroyed): self.lvl.remove_object(self) return self.dir = (self.target.shape.position - self.shape.position).normalizing() v = self.dir.scalar(self.velocity) self.shape.velocity = v Object.tick(self, time_elapsed)
def __init__(self, model, shape, element, level): Object.__init__(self, model, shape, element) cfg = Config('physics','Ship') self.move_force_sz = cfg.get('move_force') self.spin_velocity = cfg.get('spin_velocity') self.strafe_force = cfg.get('strafe_force') self.shape.forces_res.append(cfg.get('vacuum_resistance')) self.breake_rate = cfg.get('breake_rate') self.mouse_sensivity = Config('game','Mouse').get('sensivity') self.level = level self.rotation = Quaternion.from_axis_rotations(0.,0.,0.) self.ship_dir = None self.up_dir = None self.spinning = { 'up' : False, 'down' : False, 'left' : False, 'right' : False } self.vectors = { 'up' : (Vector3d.x_axis(), 1.), 'down' : (Vector3d.x_axis(), -1.), 'left' : (Vector3d.y_axis(), 1.), 'right' : (Vector3d.y_axis(), -1.) } self.strafe = { 'forward': False, 'left' : False, 'right' : False, 'breake' : False } self.strafe_vectors = { 'forward':Vector3d(0.,0.,-0.7), 'left' : Vector3d(-0.9,0.,0.), 'right' : Vector3d(0.9,0.,0.), 'breake' : Vector3d(0.,0.,1.) } self.angles = [0.,0.] self.mouse_target = [0.,0.] self.collision_set = set() self.keep_colliding = set()
def tick(self, time_elapsed): Object.tick(self, time_elapsed) self.update_mouse_track(time_elapsed) self.update_spinning(time_elapsed) self.update_strafe(time_elapsed) self.simple_gun.tick(time_elapsed) self.simple_missile.tick(time_elapsed) self.collision_set = self.keep_colliding self.keep_colliding = set()
def __init__(self, x, y, char, name, color, blocks=True, ai=None, always_visible=False, equipment=None, character_class=None, creature_type=None, xp=0, screen=None): #call super constructor to create the map object Object.__init__(self, x, y, char, name, color, blocks=blocks, always_visible=always_visible) self.character_class = character_class if self.character_class: # let the fighter component know who owns it self.character_class.owner = self self.screen = screen if self.screen: # set the screen element in the character_class self.character_class.screen = screen self.ai = ai if self.ai: # let the ai component know who owns it self.ai.owner = self self.xp = xp self.dead = False self.inventory = [] #set the default equipment dictionary. self.equipment = { 'head': None, 'body': None, 'legs': None, 'hands': None, 'feet': None, 'left hand': None, 'right hand': None } self.player = None
def __init__(self): self.sensor_array = [] self.sensor_values = [0, 0] # Has the sensor can seen the target? self.target = False # Forward facing sensory inputs. for i in range(0, 2): self.sensor_array.append(Object(0, (0, 0))) self.sensor_array[i].load_image("image_resources/sensor.png") # Upward facing sensor self.sensor_array.append(Object(0, (0, 0))) self.sensor_array[2].load_image("image_resources/sensor_two.png")
def announce_move_from(self, destination, msg=None, mapping=None, **kwargs): try: Object.announce_move_from(self, destination, msg=None, mapping=None, **kwargs) except NoStorageException: self.ndb.move_override = True
def __init__(self, map, con, x,y, char, color, fighter=None, level=None): Object.__init__(self, None, con, x,y, char, libtcod.namegen_generate('Celtic male'), color, True, fighter=fighter, level=level ) map.player = self self.inventory = Inventory() self.mods = Inventory() class Item: stack_limit = 5 obj = Object(None, con, None,None, 'b', 'boost', color, item=Item()) obj.mod = mods.Boost() self.mods.add_item(obj)
def can_do(self): cant_dig_item = False try: obj = Object.get_object(self.noun) except UnknownObject: cant_dig_item = True else: if not obj.can_apply_action(self.verb): cant_dig_item = True if cant_dig_item: self.cant_do_reason = "You can't dig '{}'.".format(self.noun) return False if self.using: if ( match_word(self.using, 'hands?') or player.has_item(self.using) ): return True else: self.cant_do_reason = "You don't have a {}.".format(self.using) return False else: self.cant_do_reason = "Dig {} using what?".format(self.noun) return False
def generate_world(self): # Reset environment self.blocks = [] self.agents = [] self.agent_num = 0 # Randomly place 3 blocks. while len(self.blocks) < 3: self.unplaced = Object(0, (randint(500, 800), randint(0, 200))) self.unplaced.load_image("image_resources/" + self.block_images[randint(0, 3)] + ".png") self.unplaced.rotate(randint(0, 180)) # Only keep the block if it touches the environment if self.check_environmental_overlap(): self.blocks.append(self.unplaced) # Place goal self.set_goal()
def _create(cls, repo, path, resolve, reference, force): """internal method used to create a new symbolic reference. If resolve is False,, the reference will be taken as is, creating a proper symbolic reference. Otherwise it will be resolved to the corresponding object and a detached symbolic reference will be created instead""" full_ref_path = cls.to_full_path(path) abs_ref_path = os.path.join(repo.git_dir, full_ref_path) # figure out target data target = reference if resolve: target = Object.new(repo, reference) if not force and os.path.isfile(abs_ref_path): target_data = str(target) if isinstance(target, SymbolicReference): target_data = target.path if not resolve: target_data = "ref: " + target_data if open(abs_ref_path, 'rb').read().strip() != target_data: raise OSError("Reference at %s does already exist" % full_ref_path) # END no force handling ref = cls(repo, full_ref_path) ref.reference = target return ref
def doTurn(self, game): (ao, ro, ag) = Object.doTurn(self, game) # detect hit for obj in game.objects.getWithinRadius( self, self.weapon.stats.projectile.explosionTriggerRange): if obj.alive and obj.player != None and obj.player != self.launcher.player: (ao0, ro0, ag0) = explode(self, game, self.weapon.stats.projectile.explosionRange, energyDamage=self.weapon.stats.energyDamage, massDamage=self.weapon.stats.massDamage, sender=self.launcher.player, sound=ids.S_EX_FIRE) (ao, ro, ag) = (ao + ao0, ro + ro0, ag + ag0) if self.alive and self.ttl == 0: (ao0, ro0, ag0) = explode(self, game, self.weapon.stats.projectile.explosionRange, energyDamage=self.weapon.stats.energyDamage, massDamage=self.weapon.stats.massDamage, sender=self.launcher.player, sound=ids.S_EX_FIRE) (ao, ro, ag) = (ao + ao0, ro + ro0, ag + ag0) else: self.ttl = self.ttl - 1 return (ao, ro, ag)
def throw_rock(player, objects, cs, stdscr, m): width = len(m[1]) height = len(m) news.append("Where do you want to throw the rock?") display_news(stdscr, news, width, height) stdscr.addstr(player.y - 1,player.x, "^", curses.color_pair(1)), stdscr.addstr(player.y + 1,player.x, "v", curses.color_pair(1)) stdscr.addstr(player.y,player.x - 1, "<", curses.color_pair(1)) stdscr.addstr(player.y,player.x + 1, ">", curses.color_pair(1)) stdscr.refresh() inp = stdscr.getch() dx = 0 dy = 0 if inp == curses.KEY_DOWN: dy = 5 elif inp == curses.KEY_UP: dy = -5 elif inp == curses.KEY_LEFT: dx = -5 elif inp == curses.KEY_RIGHT: dx = 5 news.append("Yeet!") drop_first(lambda x: x.type == "rock", player.inv) rock = Object(player.x + dx, player.y + dy,".", 12, "rock") objects.append(rock) enemies = filter(lambda c: c.type != "player" and distance(c,rock) <= 10, cs) for e in enemies: e.target = (rock.x, rock.y) e.distracted = 3
def _get_object(self): """ :return: The object our ref currently refers to. Refs can be cached, they will always point to the actual object as it gets re-created on each query""" # have to be dynamic here as we may be a tag which can point to anything # Our path will be resolved to the hexsha which will be used accordingly return Object.new_from_sha(self.repo, hex_to_bin(self.dereference_recursive(self.repo, self.path)))
def animation(self): self.tick += 1 if self.tick <= 45: self.key = Object(KEY_ASSET, 0, 600, self.key_group) else: if self.tick > 90: self.tick = 0 self.key_group.empty()
class ExplodingBullet(Object): def __init__(self, (xp, yp), zp, ori, (xi, yi), target, launcher, weapon): Object.__init__(self, weapon.stats.projectile, xp, yp, zp, ori, xi, yi, 0, 0) self.target = target self.launcher = launcher self.weapon = weapon self.ttl = weapon.stats.projectileTtl
class Mine(Object): def __init__(self, stats, (xp, yp), zp, (xi, yi), weapon, explosionRange, detectionRange): Object.__init__(self, stats, xp, yp, zp, random() * 2 * pi, xi, yi, 0, 0) # random()*0.01 ) self.weapon = weapon self.ttl = 30 * 360 #weapon.stats.projectileTtl self.detectionRange = detectionRange self.explosionRange = explosionRange
def __init__(self, sequence, \ id, type, name, \ size, \ posx, posy, posz, \ velx, vely, velz, \ contains, \ order_types, \ order_number, modify_time): Object.__init__(self, sequence, \ id, type, name, \ size, \ posx, posy, posz, \ velx, vely, velz, \ contains, \ order_types, \ order_number, \ modify_time)
def doTurn(self, game): # ai if self.ai: ( addedObjects0, removedObjects0, addedGfxs0 ) = self.ai.doTurn( self, game ) else: ( addedObjects0, removedObjects0, addedGfxs0 ) = ([],[],[]) if not self.orbiting and self.pulsedUntil < game.tick: # engine thrust self.xi = self.xi + self.thrust * cos( self.ori ) self.yi = self.yi + self.thrust * sin( self.ori ) # gouvernailstats self.ri = self.ri + self.rg # inertia controls self.xi = self.xi * (0.9+0.01*self.stats.mass)*self.inertiaMod #0.9 self.yi = self.yi * (0.9+0.01*self.stats.mass)*self.inertiaMod #0.9 self.zi = self.zi * (0.9+0.01*self.stats.mass)*self.inertiaMod #0.9 if fabs(self.xi) < 0.05 and fabs(self.yi) < 0.05: self.xi = self.yi = 0 if self.inertiaControl: self.ri = self.ri * 0.9 # *self.inertiaMod if fabs(self.ri) < 0.0005: self.ri = 0 if (not self.ai or self.ai.dockingTo) and randint( 0, config.fps*10 ) == 0: # zDiff = -2 + 4*randint( 0, 1 ) nz = randint( -5, 5 ) can = True for obj in game.objects.getWithinArea( self, self.stats.maxRadius+500 ): # print "s ", obj.zp <= max( self.zp, nz ), obj.zp >= min( self.zp, nz ), areOver( self, obj ) if obj != self and obj.zp <= max( self.zp, nz ) and obj.zp >= min( self.zp, nz ) and areOver( self, obj ): can = False break # print "switch", can, nz, obj.zp <= max( self.zp, nz ), obj.zp >= min( self.zp, nz ), areOver( self, obj ) if can: self.zp = nz ( addedObjects1, removedObjects1, addedGfxs1 ) = Object.doTurn( self, game ) # if self.thrust > 0 and self.stats.engines: # if randint( 0, 4 ) == 0: # engine = choice( self.stats.engines ) # (x,y) = (self.xp+engine[0]*cos(self.ori+engine[1]), self.yp+engine[0]*sin(self.ori+engine[1]) ) # addedGfxs1.append( GfxExhaust( (x,y), self.zp, 0, -0.2*self.xi+(0.5-random())*0.4, -0.2*self.yi+(0.5-random())*0.4, random()*pi ) ) if game.tick%(config.fps)==11: self.inNebula = False for obj in game.astres: if isinstance( obj, Nebula ) and distLowerThanObjects( self, obj, self.stats.maxRadius+obj.stats.maxRadius): self.inNebula = True break return ( addedObjects0+addedObjects1, removedObjects0+removedObjects1, addedGfxs0+addedGfxs1 )
def create_final_objects(self, sensor_data): if self.number_of_objects != 0: for obj_number in range(1, self.number_of_objects + 1): items = [] for item in sensor_data: if item[1] == obj_number: items.append(item) created_object = Object("", obj_number, 0) for compare in items: if compare[2] > created_object.percentage: created_object.name = compare[0] created_object.percentage = compare[2] self.objects.append(created_object) return self.objects
def __init__(self, stats, ai, xp, yp, zp=0, ori=0.0, xi=0, yi=0, zi=0, ri=0, thrust=0): Object.__init__(self, stats, xp, yp, zp, ori, xi, yi, zi, ri) self.alive = True self.maxOri = 2 * pi self.thrust = thrust self.rg = 0 self.shieldVsMass = self.stats.shieldVsMass self.shieldVsEnergy = self.stats.shieldVsEnergy self.hullVsMass = self.stats.hullVsMass self.hullVsEnergy = self.stats.hullVsEnergy self.ai = ai self.dockedTo = False self.dockedAt = 0 # tick at docking self.hull = stats.maxHull self.shield = stats.maxShield self.inertiaControl = True self.headed = True # differentiate bases from ships self.pulsedUntil = -1000 self.inNebula = False # variable state self.inertiaMod = 1 self.thrustBoost = 0 self.shipyards = [] # list of regulard shipyards self.guestDocked = [] # list of temporary docks
def draw_object(self,object:objects.Object,value='·',fill = False): if type(object) == objects.Circle: self.draw_circle(object,value,fill) return elif type(object) == objects.Triangle and fill: self.draw_filled_triangle(object,value) return for line in object.get_lines(): self.draw_line(line,value)
def get_objects(): random.seed(time.gmtime) objects = []; for i in range(10): x = random.randint(-10, 10) y = random.randint(-10, 10) if not (x == 2 and y == 2) and not (x == 0 and y == 0): objects.append(Object(i, x, y)) return objects
def tick(self, time_elapsed): Object.tick(self, time_elapsed) self.elapsed += time_elapsed if (self.elapsed >= self.time_interval_shot): self.elapsed = 0. _info = { 'destructible' : False, 'destroys_player' : False, 'target' : False } vec_dir = (self.level.ship.shape.position - self.shape.position - self.gun_pos).normalizing().scalar(70.) bullet_pos = self.shape.position + self.gun_pos shape_bull = Shape(0.01, bullet_pos) shape_bull.velocity = vec_dir # #(self, model, shape, element, lvl, duration, damage) obj_sh = SimpleShootInvasor(self.level.models['InvasorSimpleGun'][0], shape_bull, _info, self.level, 20, 5) self.level.add_object(obj_sh) #
def load_room(self, name, passage=None): name = 'Data/Rooms/' + name with open(name, mode='r') as file: room_map = [line.strip() for line in file] width = len(room_map[0]) height = len(room_map) room_map = [list(row) for row in room_map] if passage is not None: row = None if passage == 1: row = 0 elif passage == 2: row = height - 1 if row is not None: room_map[row][width // 2 - 1] = '|' room_map[row][width // 2] = '|' room_map[row][width // 2 + 1] = '|' for row in range(height): for col in range(width): obj = None if room_map[row][col] == 'W': obj = Object((self.room_sprites, self.wall_sprites), 'wall', col, row, BLOCK_SIZE, offset=self.offset) elif room_map[row][col] == '.': obj = Object((self.room_sprites,), 'empty', col, row, BLOCK_SIZE, offset=self.offset) elif room_map[row][col] == '|': obj = Object((self.room_sprites,), 'empty', col, row, BLOCK_SIZE, offset=self.offset) block_wall = Object((self.block_walls,), 'wall', col, row, BLOCK_SIZE, offset=self.offset) self.block_walls.add(block_wall) elif room_map[row][col] == 'S': obj = Object((self.room_sprites,), 'empty', col, row, BLOCK_SIZE, offset=self.offset) script = Object((self.room_sprites,), 'empty', col, row, BLOCK_SIZE, offset=self.offset) self.scripts.add(script) self.room_sprites.add(script) elif room_map[row][col] == 'P': obj = Object((self.room_sprites,), 'empty', col, row, BLOCK_SIZE, offset=self.offset) self.player = Player(col, row, offset=self.offset) elif room_map[row][col] == 'T': obj = Object((self.room_sprites,), 'empty', col, row, BLOCK_SIZE, offset=self.offset) self.teleport = Object((self.room_sprites,), 'teleport', col - 2, row - 4, BLOCK_SIZE, offset=self.offset) if obj is not None: self.room_sprites.add(obj) return width, height
def __init__(self, sequence, \ id, type, name, \ size, \ startx, starty, startz, \ velx, vely, velz, \ contains, \ order_types, \ order_number, \ modify_time, \ endx, endy, endz): Object.__init__(self, sequence, \ id, type, name, \ size, \ startx, starty, startz, \ velx, vely, velz, \ contains, \ order_types, \ order_number, \ modify_time) self.length += 8*3 self.start = self.pos self.end = (endx, endy, endz)
def doTurn( self, game ): (ao,ro,ag) = Object.doTurn(self, game) # detect hit for obj in game.objects.getWithinRadius( self, self.weapon.stats.projectile.explosionTriggerRange ): if obj.alive and obj.player != None and obj.player != self.launcher.player: (ao0, ro0, ag0) = explode( self, game, self.weapon.stats.projectile.explosionRange, energyDamage=self.weapon.stats.energyDamage, massDamage=self.weapon.stats.massDamage, sender=self.launcher.player, sound=ids.S_EX_FIRE ) (ao, ro, ag) = (ao+ao0, ro+ro0, ag+ag0) if self.alive and self.ttl == 0: (ao0, ro0, ag0) = explode( self, game, self.weapon.stats.projectile.explosionRange, energyDamage=self.weapon.stats.energyDamage, massDamage=self.weapon.stats.massDamage, sender=self.launcher.player, sound=ids.S_EX_FIRE ) (ao, ro, ag) = (ao+ao0, ro+ro0, ag+ag0) else: self.ttl = self.ttl - 1 return (ao,ro,ag)
def _set_reference(self, ref): """ Set ourselves to the given ref. It will stay a symbol if the ref is a Reference. Otherwise we try to get a commit from it using our interface. Strings are allowed but will be checked to be sure we have a commit """ write_value = None if isinstance(ref, SymbolicReference): write_value = "ref: %s" % ref.path elif isinstance(ref, Commit): write_value = ref.sha else: try: write_value = ref.commit.sha except AttributeError: sha = str(ref) try: obj = Object.new(self.repo, sha) if obj.type != "commit": raise TypeError("Invalid object type behind sha: %s" % sha) write_value = obj.sha except Exception: raise ValueError("Could not extract object from %s" % ref) # END end try string # END try commit attribute # if we are writing a ref, use symbolic ref to get the reflog and more # checking # Otherwise we detach it and have to do it manually if write_value.startswith('ref:'): self.repo.git.symbolic_ref(self.path, write_value[5:]) return # END non-detached handling path = self._get_path() directory = os.path.dirname(path) if not os.path.isdir(directory): os.makedirs(directory) fp = open(path, "wb") try: fp.write(write_value) finally: fp.close()
def doTurn( self, game ): (ao,ro,ag) = Object.doTurn(self, game) ## detect hit if not game.tick%20: for obj in game.objects.getWithinRadius( self, self.detectionRange ): if obj.alive and obj.player and not isinstance( obj, Mine ): (ao0,ro0,ag0) = self.explode( game ) (ao,ro,ag) = (ao+ao0,ro+ro0,ag+ag0) break ## detect expiration if self.alive and self.ttl == 0: (ao0,ro0,ag0) = self.explode( game ) (ao,ro,ag) = (ao+ao0,ro+ro0,ag+ag0) else: self.ttl = self.ttl - 1 return (ao,ro,ag)
def doTurn( self, game ): (ao,ro,ag) = Object.doTurn(self, game) # detect hit for obj in game.objects.getWithinRadius( self, self.stats.maxRadius ): if obj.alive and obj.player != None and obj.player != self.launcher.player: # TODO better (ao0, ro0, ag0) = obj.hit( game, utils.angleBetweenObjects( obj, self), self.launcher.player, energy=self.weapon.stats.energyDamage, mass=self.weapon.stats.massDamage ) (ao, ro, ag) = (ao+ao0, ro+ro0, ag+ag0) self.alive = False ro.append( self ) break if self.alive and self.ttl == 0: self.alive = False ro.append( self ) else: self.ttl = self.ttl - 1 return (ao,ro,ag)
def __str__(self): output = Object.__str__(self) output += pack(self.substruct, self.owner, self.ships, self.damage) return output
def __init__(self, prototype): Object.__init__(self, prototype=prototype)
def move(self, dx, dy): result = Object.move(self, dx,dy) return result
def tick(self, time_elapsed): Object.tick(self, time_elapsed) if (self.asteroid_type == 'artificial'): self.shot_tick_counter = (self.shot_tick_counter + 1) % self.shot_tick_interval if (self.shot_tick_counter == 0): self.shot = True
def __init__(self, model, shape, element): Object.__init__(self, model, shape, element) self.asteroid_type = None self.shot_tick_interval = 100 self.shot_tick_counter = 0 self.shot = False