def check_colisions(box): collided = False # 1 # # # # 2 # # # # # # # # # # 3 # # # # 4 x = box[0] * X y = box[1] * Y w = box[2] * X h = box[3] * Y center_x = int(x + (w / 2)) center_y = int(y + (h / 2)) pt1 = Vector(center_x - w, center_y - h) pt2 = Vector(center_x - w, center_y + h) pt3 = Vector(center_x + w, center_y - h) pt4 = Vector(center_x + w, center_y + h) box_poly = Poly(Vector(center_x, center_y), [pt1, pt2, pt3, pt4]) #print(box, box_poly, end="\n") if collide(box_poly, LEFT_LINE_POLY) or collide(box_poly, RIGHT_LINE_POLY): collided = True return collided
def main(argv): arg_dict = {} switches = {'li': list, 'di': dict, 'tu': tuple} singles = ''.join([x[0] + ':' for x in switches]) long_form = [x + '=' for x in switches] d = {x[0] + ':': '--' + x for x in switches} try: opts, args = getopt.getopt(argv, singles, long_form) except getopt.GetoptError: print "bad arg" sys.exit(2) for opt, arg in opts: if opt[1] + ':' in d: o = d[opt[1] + ':'][2:] elif opt in d.values(): o = opt[2:] else: o = '' if o and arg: arg_dict[o] = ast.literal_eval(arg) if not o or not isinstance(arg_dict[o], switches[o]): print opt, arg, " Error: bad arg" sys.exit(2) for e in arg_dict: print collision.collide(arg_dict[e]) return collision.collide(arg_dict[e])
def main(argv): arg_dict = {} switches = {"li": list, "di": dict, "tu": tuple} singles = "".join([x[0] + ":" for x in switches]) long_form = [x + "=" for x in switches] d = {x[0] + ":": "--" + x for x in switches} try: opts, args = getopt.getopt(argv, singles, long_form) except getopt.GetoptError: print "bad arg" sys.exit(2) for opt, arg in opts: if opt[1] + ":" in d: o = d[opt[1] + ":"][2:] elif opt in d.values(): o = opt[2:] else: o = "" if o and arg: arg_dict[o] = ast.literal_eval(arg) if not o or not isinstance(arg_dict[o], switches[o]): print opt, arg, " Error: bad arg" sys.exit(2) for e in arg_dict: print collision.collide(arg_dict[e]) return collision.collide(arg_dict[e])
def test_char_with_many_skills(self): self.p1.rect.midright = (100, 100) self.p1.action = "move_right" self.p2.rect.midleft = (100, 100) self.p2.action = "special_2" skill1 = Skill(self.p2) skill1.rect.midleft = (95, 100) self.p2.action = "throw" skill2 = Skill(self.p2) skill2.rect.midleft = (95, 100) self.p2.action = "special_1" skill3 = Skill(self.p2) skill3.rect.midleft = (95, 100) skills = SkillManager(skill2, skill3, skill1) collide(self.p1, skills) self.assertTrue(pygame.mixer.get_busy()) self.assertEqual(self.p1.action, "take_damage") self.assertEqual(self.p1.hud.get_health(), self.p1.hud.health.capacity - skill2.damage) self.assertTrue(skill2.cooldown) self.assertTrue(skill1.cooldown) self.assertTrue(skill3.cooldown)
def move(self): ''' Defines enemy movement ''' movement = sample(['up', 'down', 'left', 'right'], 1).pop() self.load_direction_image(movement) d_x, d_y = 0, 0 if movement == 'up': d_y = -1 if movement == 'down': d_y = 1 if movement == 'left': d_x = -1 if movement == 'right': d_x = 1 if not collide(self, self.game.walls_sprites, d_x, d_y) and not collide( self, self.game.all_sprites, d_x, d_y, self.enemy_touches_hero) and not collide( self, self.game.enemy_sprites, d_x, d_y): self.x_pos += d_x self.y_pos += d_y
def update(): print(field.field_draw_x) jones.update(get_frame_time_jones()) stone1.update(get_frame_time_stone()) for rock in rocks: rock.update() if jones.y < -10 or jones.dead: #게임오버 조건 jones.dead_sound.play() game_framework.change_state(gameover_state) if (collision.collide(jones, door1)): jones.ondoor = True else: jones.ondoor = False #for ledder in ledders: # if(collision.collide(jones,ledder)): # jones.onledder=True for rock in rocks: if (collision.collide(jones, rock)): print("collision") for spear in spears: if (collision.collide(jones, spear)): print("collision") #jones.dead=True #for ml in mls: # ml.update() for bow in bows: if (collision.collide(jones, bow)): print("collision") jones.dead = True if field.field_draw_x < 3000: for bow in bows: bow.bow_trigger = True #bow.sound_fire.play() if field.field_draw_x < 2300: for stone in stones: stone1.Stone_trigger = True if field.field_draw_x < 3400: for rock in rocks: rock.Rock_trigger = True for bow in bows: if bow.bow_trigger: bow.sound_fire.play() bow.x -= 1 bow.sound_wind.play() for land in lands: if (collision.collide(jones, land)): return if jones.state == Jones.UPDOWN_RUN: return if jones.state == Jones.UPDOWN_STAND: return if jones.jump: return jones.y -= 2
def test_no_collision_char_with_char(self): self.p1.rect.right = 0 self.p2.rect.left = self.p1.rect.w result = collide(self.p1, self.p2) self.assertFalse(result) result = collide(self.p2, self.p1) self.assertFalse(result)
def move(self, d_x=0, d_y=0): ''' Defines hero movement ''' if not collide(self, self.game.walls_sprites, d_x, d_y, bump_sound) and not collide( self, self.game.enemy_sprites, d_x, d_y, self.hero_touches_enemy): self.x_pos += d_x self.y_pos += d_y
def collision_step(self, timestep, scene, audio_sampler) -> None: PhysicsCircle.collision_step(self, timestep, scene, audio_sampler) in_spawn_zone = collision.collide( self.collision_shape, self._spawn_collision_shape, ) if not in_spawn_zone: in_alive_zone = collision.collide(self.collision_shape, self._alive_collision_shape) if not in_alive_zone: self.respawn()
def test_no_collision_char_with_skill(self): self.p1.rect.midright = (100, 100) self.p2.action = "throw" self.p2.rect.midleft = (200 + self.p2.rect.w, 100) skill = Skill(self.p2) result = collide(self.p1, skill) self.assertFalse(result) result = collide(skill, self.p1) self.assertFalse(result)
def test_jump(self): self.p1.rect.midright = (100, 100) self.p1.action = "jump" self.p1.movements["jump"].current_frame = self.p1.movements["jump"].\ max_frame self.p2.rect.midleft = (80, 100) collide(self.p1, self.p2) self.assertTrue(self.p1.rect.left, self.p2.rect.right)
def test_char_with_char_normal_attack_block(self): self.p1.rect.midright = (100, 100) self.p1.action = "normal_attack" self.p2.rect.midleft = (90, 100) self.p2.action = "move_right" collide(self.p1, self.p2) self.assertEqual(self.p2.action, "block") self.assertTrue("block" in self.p2.skills) self.assertTrue(pygame.mixer.get_busy()) self.assertTrue(self.p2.hud.get_health(), self.p2.hud.health.capacity) self.assertTrue(self.p1.hud.get_mana(), self.p2.hud.mana.capacity)
def test_char_with_char_normal_attack_take_damage(self): self.p1.rect.midright = (100, 100) self.p1.action = "normal_attack" self.p2.rect.midleft = (90, 100) self.p2.action = "stance" collide(self.p1, self.p2) self.assertEqual(self.p2.action, "take_damage") self.assertTrue("take_damage" in self.p2.skills) self.assertTrue(pygame.mixer.get_busy()) self.assertTrue(self.p2.hud.get_health(), self.p2.hud.health.capacity - self.p1.damage) self.assertTrue(self.p1.hud.get_mana(), self.p2.hud.mana.capacity)
def test_char_with_skill_block(self): self.p1.rect.midright = (100, 100) self.p1.action = "move_left" self.p2.rect.midleft = (100, 100) self.p2.action = "special_2" skill = Skill(self.p2) skill.rect.midleft = (95, 100) collide(self.p1, skill) self.assertTrue(pygame.mixer.get_busy()) self.assertTrue(skill.cooldown) self.assertEqual(self.p1.action, "block") self.assertEqual(self.p1.hud.get_health(), self.p1.hud.health.capacity)
def test_char_with_char_stance(self): self.p1.action = "stance" self.p1.rect.midright = (100, 100) self.p2.action = "stance" self.p2.rect.midleft = (90, 100) result = collide(self.p1, self.p2) self.assertTrue(result) self.assertEqual(self.p1.rect.right, 100) self.assertEqual(self.p2.rect.left, 90) result = collide(self.p2, self.p1) self.assertTrue(result) self.assertEqual(self.p1.rect.right, 100) self.assertEqual(self.p2.rect.left, 90)
def getFileList(areaPoly): """ returns a list of the files that contains the data for the positions. fileformat varies between .tab, .asc and .tif, as does the folders but the names are the same. areaPoly should be given in sweref99 2D coordinates. """ fileList=['67250_5950_25','67250_5975_25', '67275_5950_25', '67275_5975_25'] cornerList=[(595000, 6725000),(597500, 6725000), (595000,6727500),(597500,6727500) ] w=2500 #m width of cell file is representing h=2500 pol=fun.Polygon(areaPoly[0], areaPoly) files=[] #the files we should return. for i in range(len(cornerList)): pos=cornerList[i] nodes=[pos] square=[pos, (pos[0]+w, pos[1]), (pos[0]+w, pos[1]+w), (pos[0], pos[1]+w)] sq=fun.Polygon((pos[0]+w*0.5, pos[1]+h*0.5), square) if col.collide(pol, sq): files.append(fileList[i]) if len(files)==0: raise Exception('could not find matching terrain files') return files
def laser_obstacle_collision(): #TODO: move? """removes lasers that collide with obstacles""" for laser in Laser_Manager.laser_list: for obstacle in Obstacle_Manager.obstacle_list: if coll.collide(laser.coll_laser, obstacle.coll_obstacle): Laser_Manager.laser_list.remove(laser) break
def grab(self): x, _ = self.draw_pos p_l, p_b, p_r, p_t = self.get_bb() for obj in gfw.world.objects_at(gfw.layer.object): crash = collision.collide(self, obj) if crash == True: self.grab_item = obj self.grab_sound.play() return True
def is_colliding(self, other): """ Returns a collision response if the two objects are colliding, else returns None. """ if isinstance(other, Collidable): resp = Response() if self.collider: if other.collider: result = collide(self.collider, other.collider, resp) else: result = collide(self.collider, other.rel_vector, resp) else: if other.collider: result = collide(self.rel_vector, other.collider, resp) else: result = collide(self.rel_vector, other.rel_vector, resp) else: return NotImplemented return resp if result else None
def move(self): ''' Defines boss movement ''' movement = sample(['up', 'down', 'left', 'right'], 1).pop() d_x, d_y = 0, 0 if movement == 'up': d_y = -1 elif movement == 'down': d_y = 1 elif movement == 'left': d_x = -1 else: d_x = 1 if not collide(self, self.game.walls_sprites, d_x, d_y) and not collide(self, self.game.all_sprites, d_x, d_y, self.boss_touches_hero): self.x_pos += d_x self.y_pos += d_y
def active(self): crash = False for t in gfw.world.objects_at(gfw.layer.tile): if t.name in ['exit', 'entrance', 'cant_break']: continue crash = collide(t, self) if crash == True: t.remove() for obj in gfw.world.objects_at(gfw.layer.object): if obj == self: continue crash = collide(obj, self) if crash == True: obj.collide_bomb() for m in gfw.world.objects_at(gfw.layer.monster): if m == self: continue crash = collide(m, self) if crash == True: m.collide_whip((0, 0)) for p in gfw.world.objects_at(gfw.layer.player): p_crash = collide(p, self) if p_crash == True: p.dameged_to_die()
def update(self, frame_time): distance = Stone.RUN_SPEED_PPS * frame_time self.total_frames += 1.0 self.rotateangle -= 0.01 if (self.y < 0): self.sound.set_volume(1) if (self.Stone_trigger): self.sound.play() for land in lands: if collision.collide(self, land) and self.x < 4300: self.x += distance return self.y -= 2
def pick_object(obj_name: str, me: int): pos = _WORLD.component_for_entity(me, Position) claw = _WORLD.component_for_entity(me, Claw) success: bool = False msg: str = f'Object {obj_name} not found.' # Create boundaries, if necessary if claw.boundaries is None: span = Ellipse(pos.center, claw.max_range, claw.max_range) col = Collidable(shape=helpers.collision_from_points(span, pos.center)) claw.boundaries = col # For every pickable component, see if it's within range for _, (pick, col) in _WORLD.get_components(Pickable, Collidable): if pick.name == obj_name: # This is the object we want. Let's see if it's in range and under limit weight for s1 in col.shapes: if collide(claw.boundaries.shapes[0], s1): if pick.weight <= claw.max_weight: # Take the object reply_channel = Store(_ENV) payload = ObjectManager.GrabPayload( obj_name, ObjectManager.ObjectManagerOps.REMOVE, reply_channel) event = EVENT(ObjectManager.ManagerTag, payload) _EVENT_STORE.put(event) # Wait for reply response = yield reply_channel.get() if response.get('success', False): success = True # Add removed component to my inventory if not _WORLD.has_component(me, Inventory): _WORLD.add_component(me, Inventory()) inventory = _WORLD.component_for_entity( me, Inventory) inventory.objects[obj_name] = pick.skeleton msg = f'Picked {obj_name}. My inventory: {inventory.objects}' else: success = False msg = response.get('msg', '') else: msg = f'Pickable {obj_name} too heavy. Max weight:{claw.max_weight}. Object weight: {pick.weight}' success = False else: msg = f'Pickable {obj_name} not within claw range!' success = False response = RESPONSE_ClawPayload(op=ClawOps.GRAB, ent=me, success=success, msg=msg) event_to_put = EVENT(ClawDoneTag, response) _EVENT_STORE.put(event_to_put) return success, msg
def collide(self, humans): shortest_colliding_axis = None overlap_v = None response = collision.Response() collide = False for other_human in humans: # check if this is another human if other_human.id == self.id: continue if (collision.collide(self.collision_circle(), other_human.collision_circle(), response)): shortest_colliding_axis, overlap_v = self.update_axis_and_overlap(shortest_colliding_axis, overlap_v, response.overlap_n, response.overlap_v) # Not sure if people who have recovered can pass it on? if (other_human.infectious() and self.status == Status.Healthy): self.status = Status.Sick if (self.infectious() and other_human.status == Status.Healthy): other_human.status = Status.Sick collide = True # Also check any barriers barrier_collide = False for barrier in self.barriers: if (collision.collide(self.collision_circle(), barrier, response)): shortest_colliding_axis, overlap_v = self.update_axis_and_overlap(shortest_colliding_axis, overlap_v, response.overlap_n, response.overlap_v) collide = True barrier_collide = True if (collide): self.position -= overlap_v self.bounce(shortest_colliding_axis.reverse())
def check_collision(self, other)->Tuple[bool, Optional[collision.Response]]: collided = False response = None if other is not self: if self._needs_collision_response: response = collision.Response() if self.collision_shape is not None and other.collision_shape is not None: # module function to check collision btwn shapes collided = collision.collide( self.collision_shape, other.collision_shape, response=response ) return collided, response
def handle_event(self, event): if (event.type, event.key) == (SDL_KEYDOWN, SDLK_LEFT): if self.state in (self.RIGHT_STAND, self.LEFT_STAND, self.RIGHT_RUN, self.UPDOWN_RUN, self.UPDOWN_STAND): self.state = self.LEFT_RUN elif (event.type, event.key) == (SDL_KEYDOWN, SDLK_RIGHT): if self.state in (self.RIGHT_STAND, self.LEFT_STAND, self.LEFT_RUN, self.UPDOWN_RUN, self.UPDOWN_STAND): self.state = self.RIGHT_RUN elif (event.type, event.key) == (SDL_KEYUP, SDLK_LEFT): if self.state in (self.LEFT_RUN, ): self.state = self.LEFT_STAND elif (event.type, event.key) == (SDL_KEYUP, SDLK_RIGHT): if self.state in (self.RIGHT_RUN, ): self.state = self.RIGHT_STAND elif (event.type, event.key) == (SDL_KEYDOWN, SDLK_SPACE): #로프기능 self.fst_y = self.y self.jump = True self.jump_sound.play() for ledder in ledders: if (event.type, event.key) == (SDL_KEYDOWN, SDLK_UP) and collision.collide( jones, ledder): self.state = self.UPDOWN_RUN if (event.type, event.key) == (SDL_KEYUP, SDLK_UP) and collision.collide( jones, ledder): self.state = self.UPDOWN_STAND if (event.type, event.key) == (SDL_KEYUP, SDLK_UP) and not collision.collide( jones, ledder): self.state = self.RIGHT_STAND if (event.type, event.key) == (SDL_KEYDOWN, SDLK_UP): if self.ondoor: self.door_open_sound.play() game_framework.change_state(jwerly_state)
def run(self): tic=time.clock() rN=self.G.roadNet for e in rN.edges_iter(data=True): r=e[2]['r'] direction=r.direction tList=self.G.terrain.GetTrees(r.pos, self.reach+r.radius, onlyNonHarvested=True) ray=np.array(r.endPoints) for t in tList: p1, tval=col.closestLinePoint(t.pos, ray, additionalInfo=True) #tval will be used later, if col.collide(t, r): self.chop(t, p1, tval, r) #could get into problems if t is on ray... hmm.. elif t.marked and fn.getDistance(p1, t.pos)<=self.reach: #marked foo thinning self.chop(t, p1, tval, r) print "harvester routine took %.4f seconds"%(time.clock()-tic)
def player_obstacle_collision(): """changes the horizonal or vertical velocity of the ship to 0 """ #print("hi") for obstacle in Obstacle_Manager.obstacle_list: if coll.collide(player.coll_ship, obstacle.coll_obstacle, response): print(response.overlap_n) print(response.overlap) if response.overlap_n.x: player.update_pos( -abs(response.overlap_n.x) * player.vel[0], 0) if response.overlap_n.y: player.update_pos( 0, -abs(response.overlap_n.y) * player.vel[1]) response.reset()
def handle_events(frame_time): global unit_attack events = get_events() for event in events: if event.type == SDL_QUIT: game_framework.quit() else: if (event.type, event.key) == (SDL_KEYDOWN, SDLK_ESCAPE): game_framework.quit() elif (event.type, event.key) == (SDL_KEYDOWN, SDLK_i) and unit.state == Unit.DEAD: unit.hp = mini_map.stage*45000 unit.atk = mini_map.stage*5+5 unit.first_hp = unit.hp unit.state = unit.STAND unit.dead_frame = 0 elif (event.type, event.key) == (SDL_KEYDOWN, SDLK_q): mini_map.stage = 4 else: unit.handle_event(event) mini_map.handle_event(event,unit) if not collide(enemy_knight,unit) and not collide(enemy_archur,unit): background.handle_event(event) enemy_knight.handle_event(event) enemy_archur.handle_event(event)
def update(self): self.color_transition.update() self.spawner.update(self.deltatime) trapezoids = self.spawner.draw_trapezoids() self.big_hexagon.draw_lines_from_origin_to_vertex( self.color_transition.color) self.player.left = self.left self.player.right = self.right self.player.update() self.screen.blit(self.player.image, self.player.rect) self.big_hexagon.update_vertex(self.rotation, 0) self.small_hexagon.update_vertex(self.rotation, self.expand) self.small_hexagon.draw_hexagon(self.color_transition.color) self.small_hexagon.draw_hexagon_filled() for i in trapezoids: if collide(i, self.player.circle): self.game_over = True
def process(kwargs: SystemArgs): logger = logging.getLogger(__name__) env = kwargs.get('ENV', None) world = kwargs.get('WORLD', None) if env is None: raise Exception("Can't find env") # Local ref most used variables get_components = world.get_components sleep = env.timeout total = timedelta() runs = 0 while True: start = datetime.now() for ent, (pos, vel, sensor) in get_components(Position, Velocity, sensor_type): # logger.debug(f'Analysing ent {ent}') center_x, center_y = pos.center sensor_range = sensor.range points = [ (center_x - sensor_range, center_y - sensor_range), (center_x + sensor_range, center_y - sensor_range), (center_x + sensor_range, center_y + sensor_range), (center_x - sensor_range, center_y + sensor_range) ] col = Collidable([(pos.center, points)]) closeEntities = [] for otherEnt, (otherCol, otherPos) in get_components(Collidable, Position): if ent == otherEnt: continue for s1 in otherCol.shapes: if collide(col.shapes[0], s1): closeEntities.append(CloseEntity(otherEnt, otherPos)) break if closeEntities: event = EVENT('SensorEvent', SensorPayload(ent, pos, vel, closeEntities)) sensor.reply_channel.put(event) yield sleep(frequency) end = datetime.now() runs += 1 total += end - start if runs % 50 == 0: logger.debug(f'runs: {runs}; total: {total}; avg = {total / runs}')
def _is_valid_proposal(o1_x, o1_y, object1_index, bounding_boxes, placements): o1_x += bounding_boxes[object1_index, 0, 0] o1_y += bounding_boxes[object1_index, 0, 1] # Check if object collides with any of already placed objects. We use half-sizes, # but collision uses full-sizes. That's why we multiply by 2x here. o1_w, o1_h, _ = bounding_boxes[object1_index, 1] object1 = Poly.from_box(Vector(o1_x, o1_y), o1_w * 2.0, o1_h * 2.0) for object2_index in range(len(placements)): # Don't care about z placement o2_x, o2_y, _ = placements[object2_index] o2_x += bounding_boxes[object2_index, 0, 0] o2_y += bounding_boxes[object2_index, 0, 1] # Don't care about object depth. o2_w, o2_h, _ = bounding_boxes[object2_index, 1] object2 = Poly.from_box(Vector(o2_x, o2_y), o2_w * 2.0, o2_h * 2.0) if collide(object1, object2): return False return True
def update(frame_time): if collide(enemy_knight,unit): if unit.state == unit.RUN: unit.state = unit.STAND if enemy_knight.state == enemy_knight.RUN: enemy_knight.state = enemy_knight.STAND if enemy_archur.state in (enemy_archur.STAND,enemy_archur.ATTACK1,enemy_archur.ATTACK2): enemy_archur.speed=0 if mini_map.state == mini_map.RUN: mini_map.state = mini_map.STAND background.speed = 0 unit.attack_damage(enemy_knight) enemy_knight.speed=0 if enemy_knight.state == enemy_knight.ATTACK: enemy_knight.attack_damage(unit) if collide(enemy_archur,unit): if unit.state == unit.RUN: unit.state = unit.STAND if enemy_archur.state == enemy_archur.RUN: enemy_archur.state = enemy_archur.STAND if mini_map.state == mini_map.RUN: mini_map.state = mini_map.STAND background.speed = 0 unit.attack_damage(enemy_archur) enemy_archur.speed=0 elif enemy_archur.x <= 500 and enemy_archur.state == enemy_archur.RUN: enemy_archur.state = enemy_archur.STAND enemy_archur.speed -= Enemy_Archur.TIME_PER_ACTION if enemy_knight.update(frame_time,mini_map.stage): count_killed.count() if enemy_archur.update(frame_time,mini_map.stage): count_killed.count() background.update(frame_time) unit.update(frame_time,mini_map.stage) arrow1.update(frame_time) if enemy_archur.state == Enemy_Archur.ATTACK1: arrow1.state = Arrow.ATTACK arrow1.x=enemy_archur.x arrow1.y=enemy_archur.y arrow1.draw_frame = 0 arrow1.arrow_up = True if collide(arrow1,unit): arrow1.state = arrow1.REST arrow1.y=0 enemy_archur.attack_damage(unit) arrow2.update(frame_time) if enemy_archur.state == Enemy_Archur.ATTACK2: arrow2.state = Arrow.ATTACK arrow2.x=enemy_archur.x arrow2.y=enemy_archur.y arrow2.draw_frame = 0 arrow2.arrow_up = True if collide(arrow2,unit): arrow2.state = arrow2.REST arrow2.y=0 enemy_archur.attack_damage(unit) ingame_time.update(frame_time,morale) mini_map.update(frame_time,morale,ingame_time) if (morale.state == morale.FAIL) and (morale.image != morale.SUCCESS): morale.morale_fail(unit) if (morale.state == morale.SUCCESS) and (morale.image != morale.FAIL): morale.morale_success(unit) if unit.state == Unit.DEAD : ingame_time.stop() if mini_map.position_x>=680 and mini_map.stage<4: mini_map.stage += 1 enemy_knight.atk = mini_map.stage*1 enemy_knight.hp = (mini_map.stage-1)*5000+3000 enemy_archur.atk = mini_map.stage*1 enemy_archur.hp = (mini_map.stage-1)*5000+3000 morale.image = 0 unit.atk = mini_map.stage * 5+ 5 unit.hp = mini_map.stage * 35000 unit.first_hp = unit.hp mini_map.position_x = 120 mini_map.position_y = 320 mini_map.state = Mini_Map.STAND mini_map.speed = 0 mini_map.total_frames = 0.0 enemy_knight.x, enemy_knight.y = 700, 70 enemy_archur.x, enemy_archur.y = 700, 60 stage_view.total_frame = 0.0 ingame_time.start_time = -1.0 ingame_time.total_frames = 0.0 if mini_map.stage == 2: ingame_time.stage = Ingame_Time.STAGE2 background.bgm1.stop() background.bgm2.set_volume(64) background.bgm2.repeat_play() if mini_map.stage == 3: ingame_time.stage = Ingame_Time.STAGE3 background.bgm2.stop() background.bgm3.set_volume(64) background.bgm3.repeat_play() if mini_map.stage == 4: ingame_time.stage = Ingame_Time.STAGE4 background.bgm3.stop() background.bgm4.set_volume(64) background.bgm4.repeat_play() ingame_time.run_time = True background.speed = 0 background.left = 0 background.screen_width = 800 background.screen_height = 400 enemy_knight.first_hp = enemy_knight.hp enemy_archur.first_hp = enemy_archur.hp if mini_map.position_x>=680 and mini_map.stage==4: game_framework.push_state(ending_state)
''' Takes multi-user schedule info (tokens) and returns open times for users to meetup when they don't have class Blame iPage for this being done in py v2.5 Here is what a token looks like, there is one for each user: "******" TESTS, enter these commands in the cmd line in the WatWhenWhere/python_modules path: python2.5 run.py "MWF830AM-920AM&F930AM-1020AM&TTh1000AM-1120AM&TTh230PM-350PM&MW1130AM-1220PM&F130PM-220PM&MWF230PM-320PM&W530PM-620PM" "F1030AM-1120AM&TTh830AM-950AM&MWThF230PM-320PM&MWF930AM-1020AM&Th1030AM-1120AM&MW100PM-220PM&F330PM-450PM&TTh1230PM-220PM" "F930AM-1020AM&TTh100PM-220PM&TTh1000AM-1120AM&MWF1130AM-1220PM&MWF1030AM-1120AM&W530PM-620PM&MW1230PM-220PM" "F930AM-1020AM&MWF1130AM-1220PM&TTh1130AM-1250PM&TTh100PM-220PM&F130PM-220PM&MWF830AM-920AM&MWF1030AM-1120AM&Th1030AM-1120AM" python2.5 run.py "M1000AM-1100AM&M1200PM-200PM" "M1100AM-1200PM" python2.5 run.py "TTh14301550&W10301120&MW16001720&MWF08300920&W09301020&MWF12301320&Th12301320&TTh10001120&F15301650&" Sarth, Nat(23), Ed(20) test: python2.5 run.py "TTh1000AM-1120AM&Th130PM-220PM&WF930AM-1020AM&T230PM-420PM&M130PM-420PM&MW830AM-920AM&W130PM-220PM&F130PM-420PM&MWF1030AM-1120AM&Th230PM-420PM&MTWF1230PM-120PM&T1130AM-1220PM" "W1630-1720&TTh1600-1720&TTh1000-1150&MWF1130-1220&MWF1430-1520" "TTh1130AM-1250PM&W130PM-220PM&TTh230PM-350PM&MWF1130AM-1220PM" python2.5 run.py "TTh1000AM-1130AM&Th130PM-230PM&WF930AM-1030AM&T230PM-430PM&M130PM-430PM&MW830AM-930AM&W130PM-230PM&F130PM-430PM&MWF1030AM-1130AM&Th230PM-430PM&MTWF1230PM-130PM&T1130AM-1230PM" "W1630-1730&TTh1600-1730&TTh1000-1200&MWF1130-1230&MWF1430-1530" "TTh1130AM-100PM&W130PM-230PM&TTh230PM-400PM&MWF1130AM-1230PM" ''' import cmdparser #Import the locally cloned argparse module (iPage doesn't have argparse so we needed to keep the argparse code locally) import collision #Import the collision module created to do this processing parser = cmdparser.ArgumentParser() #Create a parser object parser.add_argument("tokens", nargs="+", help="enter apostrophe contained tokens deliminated by spaces") #Add a schedule tokens argument to the parser args = parser.parse_args() #Parse argument strings to produce an args object containing the tokens in a list print collision.collide(args.tokens) #Apply collision processing to the token list and print the result for the backend to read
if (point_inside_polygon(cxo, cyo, list(pts))): if int(pt[0, 3]) == mode: cv2.circle(frame, (int(cx), int(cy)), 8, (0, 0, 255), 15) cx = (max(pt[:, 1]) - min(pt[:, 1])) / 2 + min(pt[:, 1]) cy = (max(pt[:, 2]) - min(pt[:, 2])) / 2 + min(pt[:, 2]) cv2.putText(frame, str(int(l)), (int(cx), int(cy)), font, 0.6, (255, 255, 255), 2) object_list = road_object.keys() objects_combinations = list(itertools.combinations(object_list, 2)) for i in objects_combinations: if ((not (road_object[i[0]][0] == 2 and road_object[i[1]][0] == 2)) and collision.collide(road_object[i[0]][1], road_object[i[1]][1])): # Check if collisions are already reported or not if (i[0] not in incident_arrays or i[1] not in incident_arrays): incident_arrays.append(i[0]) incident_arrays.append(i[1]) cv2.putText(frame, 'Warning Collision Detected!', (road_object[i[0]][1].pos.x, road_object[i[0]][1].pos.y), font, 0.6, (0, 0, 255), 2) print('Collision Detected!') print(frame_count_total) # Send alert to Web send_alert(address[address_index], road_object[i[0]][0], road_object[i[1]][0]) address_index += 1
def game_loop(): run = True FPS = 60 clock = pygame.time.Clock() lost = False # flag lost_count = 0 # the count of seconds we render the "you lost" message enemies = [] # list of the enemies ships wave_length = 5 # the count of the enemy ships in each wave level = 0 # the current level lives = 5 # the number of lives the player has main_font = pygame.font.SysFont("comicsans", 50) lost_font = pygame.font.SysFont("comicsans", 60) # create a player player = Player(300, 550) """ The function draw the window """ def redraw_window(): WIN.blit(BG, (0, 0)) # draw the text lives_label = main_font.render(f"Lives: {lives}", 1, (255, 255, 255)) level_label = main_font.render(f"Level: {level}", 1, (255, 255, 255)) WIN.blit(lives_label, (10, 10)) WIN.blit(level_label, (WIDTH - level_label.get_width() - 10, 10)) # draw the enemy ships for enemy in enemies: enemy.draw(WIN) # draw the player player.draw(WIN) if lost: lost_label = lost_font.render("You Lost!", 1, (255, 255, 255)) WIN.blit(lost_label, (WIDTH // 2 - lost_label.get_width() // 2, 275)) pygame.display.update() while run: clock.tick(FPS) redraw_window() # check if the player lose if lives <= 0 or player.health <= 0: lost = True lost_count += 1 # render the "you lost" message for 3 seconds if lost: if lost_count > FPS * 3: quit() else: continue # check if we complete the level if len(enemies) == 0: level += 1 wave_length += 5 for i in range(wave_length): # spawn the enemy ships enemy = Enemy(random.randrange(50, WIDTH - 100), random.randrange(-1500 * level, -100), random.choice(["red", "green", "blue"])) enemies.append(enemy) for event in pygame.event.get(): # quit the game if you click the quit button if event.type == pygame.QUIT: quit() # in order to move diagonaly - meaning pressing two keys in the same time keys = pygame.key.get_pressed() # move the ship to the left if keys[pygame.K_a] and player.x - PLAYER_VEL > 0: player.x -= PLAYER_VEL # move the ship to the right if keys[pygame. K_d] and player.x + PLAYER_VEL + player.get_width() < WIDTH: player.x += PLAYER_VEL # move the ship to the up if keys[pygame.K_w] and player.y - PLAYER_VEL > 0: player.y -= PLAYER_VEL # move the ship to the down if keys[pygame.K_s] and player.y + PLAYER_VEL + player.get_height( ) + 15 < HEIGHT: player.y += PLAYER_VEL # create laser when clicking the space bar if keys[pygame.K_SPACE]: player.shoot() # move the enemy ships for enemy in enemies: enemy.move(ENEMY_VEL) enemy.move_lasers(LASER_VEL, player) # make the enemy shoot at the player # 50% to shoot every second if random.randrange(0, 3 * 60) == 1: enemy.shoot() # check for collision if collide(enemy, player): player.health -= 10 enemies.remove(enemy) # check if the enemy passed us elif enemy.y + enemy.get_height() > HEIGHT: lives -= 1 # remove the specified enemy enemies.remove(enemy) player.move_lasers(-LASER_VEL, enemies)
def collision(self, obj): return collide(obj, self)
def checkCollide(shapes1, shapes2): for s1 in shapes1: for s2 in shapes2: if collide(s1, s2): return True return False
def update(self, time, input_list): """Consecutively update player1, player2, skill projectiles and check for collision after each update. Update enemy_position and direction attributes of each character, the background and the timer. Increase both players' mana points by a fixed rate(50 per second). PlayMenu.update(time, input_list): return None clock -- should be a pygame.time.Clock object """ self.player1.update(input_list) collide(self.player1, self.player2) collide(self.player1, self.player2.skills) self.player2.update(input_list) collide(self.player2, self.player1) collide(self.player2, self.player1.skills) self._update_enemy_positions() self.skills = SkillManager(self.player1.skills, self.player2.skills) self.skills.update(pygame.time.get_ticks()) collide(self.player2.skills, self.player1) collide(self.player1.skills, self.player2) self._boost_mana() self.utils.update(time)