def bug_vector_y(percept, dist, scale, theta, p): r = percept.getRadius() / 2 return ( Math.sin(deg2pi(180 + self.towards(percept.getX() + r, percept.getY() + r))) * theta / Math.pow((dist / scale), p) )
def tick(self): if self.t == 0: if self.player.hasPotionEffect(PotionEffectType.INVISIBILITY): self.castSpell('ASSASSIN', 5) if self.clone: self.sound(Sound.ENTITY_EVOKER_CAST_SPELL, .5, 1.6) self.sound(Sound.ENTITY_BLAZE_AMBIENT, .2, 1.5) l = self.player.getEyeLocation().clone().add( Math.sin(self.t * -22.5 * DEG2RAD) * 5, 0, Math.cos(self.t * -22.5 * DEG2RAD) * 5) for e in self.nearbyMobs(l, 3, 3, 3): if e in self.hit: continue self.hit.add(e) self.damage(e, False, 1.5, .7, 0, .3, 0, 0, 0) PySpell.knockback(e, VectorUP, .5) e.addPotionEffect(PotionEffect(PotionEffectType.BLINDNESS, 100, 1)) e.addPotionEffect(PotionEffect(PotionEffectType.SLOW, 20, 8)) self.particle(l.clone().subtract(0, .5, 0), Particle.SWEEP_ATTACK, 4, .5, .5, .5, 0) self.particle(l, Particle.CLOUD if self.clone else Particle.SQUID_INK, 5, .5, .5, .5, .1) self.particle( l, Particle.SPELL_WITCH if self.clone else Particle.CRIT_MAGIC, 10, .5, .5, .5, .2) self.sound(l, Sound.ENTITY_PLAYER_ATTACK_SWEEP, 1, 1.2) self.sound(l, Sound.ITEM_FLINTANDSTEEL_USE, 1, 1.3)
def processEnv(): if my._direction_ttl: my._direction_ttl -= 1 percepts = self.getPercepts() best = None rocket = None for p in percepts: if p.getTeam() != my.getTeam(): if p.getPerceptType( ) == 'RocketLauncher': # or i.getPerceptType() == 'Explorer': if not best or distance(p.getX(), p.getY()) < distance( best.getX(), best.getY()): best = p elif p.getPerceptType() == 'Home': my.setHome(p.getX(), p.getY()) if p.getPerceptType() == 'Rocket' or p.getTeam() != my.getTeam(): if not rocket or distance(p.getX(), p.getY()) < distance( rocket.getX(), rocket.getY()) and Math.abs( self.towards(p.getX(), p.getY())) - Math.abs( self.getHeading()) < 20: rocket = p if not best: return my.setTarget(p.getX(), p.getY()) # évitement des rockets et des mechants ! if rocket and not my._direction_ttl: self.setHeading(self.towards(rocket.getX(), rocket.getY()) + 120) my._direction_ttl = 30
def entropy(domain): sume = 0 chars = Counter(domain) N = len(domain) for n in chars.values(): sume += -n / N * Math.log(n / N) / Math.log(2) return sume
def move(this): if not this._first_time and this._explore_ttl: this._explore_ttl -=1 if not this._explore_ttl % 50: d('explore: '+str(this._explore_ttl)) if not this._explore_ttl: this.me.setBehavior(exploring) return if this._join_ttl: this._join_ttl -= 1 if this._join_ttl: return else: sumx = sumy = 0 for p in this._join_points: sumx += p[0] sumy += p[1] this._join_direction = self.towards(sumx/len(this._join_points), sumy/len(this._join_points)) this._first_time = 0 if not this._cached and len(this.me._killers) > 0: if this._first_time: for pos in this.resolve(this.me._killers, this.getCircle(len(this.me._killers), security_radius)): k = this.me.getKillerByName(pos[0].getName()) k.setPosition(pos[1][0], pos[1][1]) this._cached = 1 else: x = Math.cos(this._join_direction*Math.PI/180) * security_radius y = Math.sin(this._join_direction*Math.PI/180) * security_radius for pos in this.resolve(this.me._killers, this.getHalfCircle(len(this.me._killers), security_radius, x, y)): k = this.me.getKillerByName(pos[0].getName()) k.setPosition(pos[1][0], pos[1][1]) this._cached = 1 this.sendCache()
def create(self): w = Gdx.graphics.getWidth() h = Gdx.graphics.getHeight() self.camera = OrthographicCamera() self.camera.setToOrtho(False, (w / h) * 320, 320) self.camera.update() self.cameraController = OrthoCamController(self.camera) Gdx.input.setInputProcessor(self.cameraController) self.font = BitmapFont() self.batch = SpriteBatch() self.tiles = Texture( Gdx.files.internal('../../data/maps/tiled/tiles.png')) splitTiles = TextureRegion.split(self.tiles, 32, 32) self.map = TiledMap() layers = self.map.getLayers() for l in range(20): layer = TiledMapTileLayer(150, 100, 32, 32) for x in range(150): for y in range(100): ty = int(Math.random() * len(splitTiles)) tx = int(Math.random() * len(splitTiles[ty])) cell = Cell() cell.setTile(StaticTiledMapTile(splitTiles[ty][tx])) layer.setCell(x, y, cell) layers.add(layer) self.renderer = OrthogonalTiledMapRenderer(self.map)
def entropy(domain): sume = 0 chars = Counter(domain) N = len(domain) for n in chars.values(): sume += - n / N * Math.log(n / N) / Math.log(2) return sume
def update_distances(): covered=self.getCoveredDistance() last_angle=mvt_mem.last_heading - deg_val(mvt_mem.direction) toterm("la"+str(last_angle)+"lh"+str(mvt_mem.last_heading)+"di"+str(deg_val(mvt_mem.direction))) ortho_increment=covered*Math.sin(last_angle) dist_increment=covered*Math.cos(last_angle) mvt_mem.valuable_distance += dist_increment mvt_mem.orthogonal_error += ortho_increment
def process(input, position): size = len(input) output = copy.deepcopy(input) fft = DoubleFFT_1D(size) fft.realForward(output) for j in range(size/2): output[j]= Math.sqrt(Math.pow(output[2*j],2)+Math.pow(output[2*j+1],2)); return output[:len(input)/2]
def update_distances(): covered = self.getCoveredDistance() last_angle = mvt_mem.last_heading - deg_val(mvt_mem.direction) toterm("la" + str(last_angle) + "lh" + str(mvt_mem.last_heading) + "di" + str(deg_val(mvt_mem.direction))) ortho_increment = covered * Math.sin(last_angle) dist_increment = covered * Math.cos(last_angle) mvt_mem.valuable_distance += dist_increment mvt_mem.orthogonal_error += ortho_increment
def miseAJourMouvement(): # Mouvement normal et mise a jour des coordonnees alpha = self.getHeading() * Math.PI / 180 depl_x = 2*Math.cos(alpha) depl_y = 2*Math.sin(alpha) if not self.isMoving(): self.randomHeading() else: coordonnees.setCoord(coordonnees.getX() + depl_x, coordonnees.getY() + depl_y)
def tick(self): if self.t == 0: if not self.player.getWorld().getBlockAt( self.player.getLocation().clone().subtract( 0, 1, 0)).isEmpty() or not self.player.getWorld().getBlockAt( self.player.getLocation().clone().subtract( 0, 2, 0)).isEmpty(): #self.player.addScoreboardTag('escape') eye_dir = self.player.getEyeLocation().getDirection() self.player.setVelocity( eye_dir.setY(Math.min(-.4 * Math.abs(eye_dir.getY()), -.4)).multiply(-4)) self.sound(self.player.getLocation(), Sound.ENTITY_BLAZE_SHOOT, 1, 1.2) self.particle( self.player.getLocation().clone().add(0, 1, 0), Particle.VILLAGER_HAPPY if self.clone else Particle.SQUID_INK, 10 if self.clone else 5, .3, 2, .3, .2) if self.clone: self.particle( self.player.getLocation().clone().add(0, 1, 0), Particle.CLOUD, 5, .3, 2, .3, .1) else: self.cancel() return if not self.player.isOnGround(): self.delay() if self.player.isSneaking(): self.player.setVelocity( self.player.getVelocity().clone().subtract(Vector(0, 1, 0))) elif self.player.getVelocity().getY() <= -.5: self.player.getVelocity().setY(-.5) else: if self.player.isSneaking(): for i in range(0, 360, 60): for j in range(9): l = self.player.getLocation().clone().add( Math.sin(i * DEG2RAD) * j, 0, Math.cos(i * DEG2RAD) * j) self.particle(l, Particle.SQUID_INK, 2, 0, 0, 0, .2) self.particle(l, Particle.CLOUD, 2, 0, 0, 0, .2) self.particle(l, Particle.CRIT, 2, 0, 0, 0, .3) self.sound(Sound.ENTITY_GENERIC_EXPLODE, .5, 1.2) self.sound(Sound.ENTITY_IRON_GOLEM_DEATH, 1, 1) for e in self.nearbyMobs(8, 10, 8): self.damage(e, 4) self.player.addPotionEffect( PotionEffect(PotionEffectType.SPEED, 3600, 2, True, False, True))
def gemm(self, n): import time #from no.uib.cipr.matrix.nni import BLAS,LAPACK; from jarray import array, zeros from java.lang import Math, System import no.uib.cipr.matrix as matrix if n < 100: r = 100 else: r = 10 t = time.time() #A = zeros(n*n,'d') #B = zeros(n*n,'d') #C = zeros(n*n,'d') pin = range(n*n) #for i in pin: # A[i] = Math.random(); # B[i] = Math.random(); # C[i] = Math.random(); A = matrix.Matrices.random(n,n); B = matrix.Matrices.random(n,n); C = matrix.Matrices.random(n,n); alpha = Math.random() beta = Math.random() print "Random numbers time: "+str((time.time() - t)) for i in range(10): #BLAS.gemm(BLAS.ColMajor, BLAS.NoTrans, BLAS.NoTrans, n, n, n, alpha, A, n, B, n, beta, C, n) A.multAdd(alpha,B, C) C.scale(beta); #E=D.mult(C, C.copy()) t = time.time() for i in range(r): #BLAS.gemm(BLAS.ColMajor, BLAS.NoTrans, BLAS.NoTrans, n, n, n, alpha, A, n, B, n, beta, C, n) #D=A.mult(B, B.copy()); E=D.mult(C, C.copy()); A.multAdd(alpha,B, C) C.scale(beta); s = (time.time() - t) print s f = 2 * (n + 1) * n * n mfs = (f / (s * 1000000.0)) * r print str(mfs)
def miseAJourMouvement(): # Mouvement normal et mise a jour des coordonnees alpha = self.getHeading() * Math.PI / 180 depl_x = 2 * Math.cos(alpha) depl_y = 2 * Math.sin(alpha) if not self.isMoving(): self.randomHeading() else: coordonnees.setCoord(coordonnees.getX() + depl_x, coordonnees.getY() + depl_y)
def arcTo(self, cx, cy, p2x, p2y): """Adds a segment from the current position to p2x, p2y by drawing part of a circle centered on 'cx,cy'""" p1x, p1y = self.nodes[-1].position2() angle1 = Math.atan2(-(p1y-cy), p1x-cx) angle2 = Math.atan2(-(p2y-cy), p2x-cx) if (angle2-angle1>Math.PI): angle2-=Math.PI*2 if (angle2-angle1<-Math.PI): angle2+=Math.PI*2 self.arc(Math.sqrt( (p1x-cx)*(p1x-cx)+(p1y-cy)*(p1y-cy)), cx,cy, angle1, angle2, join=1) return self
def longJumps(t, mindist): for nd in t.getRoot().getSubtreeNodes(): if nd.parent is None: continue d = Math.sqrt(Math.pow(nd.x - nd.parent.x, 2) + Math.pow(nd.y - nd.parent.y, 2)) if d > mindist: print nd.x, nd.y p = array([nd.x, nd.y], 'f') aff = t.affineTransform aff.transform(p, 0, p, 0, 1) cal = t.layerSet.getCalibration() print "Off:", p[0] * cal.pixelWidth, p[1] * cal.pixelHeight, (nd.layer.getParent().indexOf(nd.layer) + 1)
def getHalfCircle(this, num, radius, x, y): if num == 1: return [[x,y]] axe = self.towards(x, y) rayon = radius * (1 - Math.exp(-num/3)) offset = Math.PI / (num-1) points = [] for i in range(num): X = rayon*Math.cos(i*offset+Math.PI/2+axe*Math.PI/180)+x Y = rayon*Math.sin(i*offset+Math.PI/2+axe*Math.PI/180)+y points.append([X,Y]) return points
def getCircle(this, num, radius): if num == 0: return None if num == 1: return [[50, 50]] rayon = radius * (1 - Math.exp(-num / 3)) offset = 2 * Math.PI / num points = [] for i in range(num): X = rayon * Math.cos(i * offset) Y = rayon * Math.sin(i * offset) points.append([X, Y]) return points
def getCircle(this, num, radius): if num == 0: return None if num == 1: return [[50,50]] rayon = radius * (1 - Math.exp(-num/3)) offset = 2*Math.PI / num points = [] for i in range(num): X = rayon*Math.cos(i*offset) Y = rayon*Math.sin(i*offset) points.append([X,Y]) return points
def tick(self): if self.t == 0: # Find totem totem = None totem_id = PersistentDataAPI.getInt(PersistentDataAPI.getData(self.player), 'totem', None) for e in self.player.getWorld().getEntities(): if e.getEntityId() == totem_id: totem = e if totem is None: PlayerAPI.sendWynnMessage(self.player, 'messages.totem_out') self.cancel() return vector = totem.getLocation().clone().subtract(self.player.getLocation()).add(0, 2, 0).toVector() vector = Vector(Math.max(Math.min(vector.getX(), 6), -6), Math.max(Math.min(vector.getY(), 2), -2), Math.max(Math.min(vector.getZ(), 6), -6)) self.player.setVelocity(vector.clone().multiply(0.5).setY(vector.getY()).multiply(0.5)); self.particle(self.player.getLocation(), Particle.CLOUD, 6, 1, 1, 1, 0.1) self.particle(self.player.getLocation(), Particle.SQUID_INK, 6, 1, 1, 1, 0.1) self.sound(Sound.ENTITY_PLAYER_ATTACK_KNOCKBACK, .4, .8) self.sound(Sound.ENTITY_BLAZE_SHOOT, 1, 1) self.sound(Sound.ENTITY_IRON_GOLEM_HURT, .8, .8) if self.clone: self.sound(Sound.ENTITY_BLAZE_AMBIENT, .1, .9) elif self.t > 10: if self.player.isOnGround(): self.particle(self.player.getLocation().clone().add(0, 1, 0), Particle.FIREWORKS_SPARK if self.clone else Particle.TOTEM, 5, 1, 2, 1, .2) self.particle(self.player.getLocation(), Particle.CLOUD, 6, 1, .2, 1, .1) self.particle(self.player.getLocation(), Particle.SQUID_INK, 6, 1, .2, 1, .1) if self.clone: self.particle(self.player.getLocation(), Particle.SPELL_MOB, 0, 1, 1, 1, 1) self.sound(Sound.BLOCK_STONE_STEP, 1, .9) self.sound(Sound.BLOCK_STONE_FALL, 1, .9) self.player.setVelocity(Vector(0, .5, 0)) self.cancel() else: for e in self.nearbyMobs(1, 1, 1): if e in self.hit: continue self.hit.add(e) self.damage(e, False, 1, .8, 0, .2, 0, 0, 0) PySpell.knockback(e, VectorUP, 2) e.addPotionEffect(PotionEffect(PotionEffectType.BLINDNESS, 100, 0, True, False))
def getHalfCircle(this, num, radius, x, y): if num == 1: return [[x, y]] axe = self.towards(x, y) rayon = radius * (1 - Math.exp(-num / 3)) offset = Math.PI / (num - 1) points = [] for i in range(num): X = rayon * Math.cos(i * offset + Math.PI / 2 + axe * Math.PI / 180) + x Y = rayon * Math.sin(i * offset + Math.PI / 2 + axe * Math.PI / 180) + y points.append([X, Y]) return points
def move(this): if this._retreat_ttl: this._retreat_ttl -= 1 if not this._retreat_ttl: this.me.setBehavior(defensing) return if len(this.me._killers) == 0 or not this._enemyX: return x = Math.cos(self.towards(this._enemyX, this._enemyY)*Math.PI/180) * security_radius y = Math.sin(self.towards(this._enemyX, this._enemyY)*Math.PI/180) * security_radius for pos in this.resolve(this.me._killers, this.getHalfCircle(len(this.me._killers), security_radius, x, y)): k = this.me.getKillerByName(pos[0].getName()) #k.setPosition(pos[1][0], pos[1][1]) self.send(k.getAddress(), 'move', str(pos[1][0]), str(pos[1][1]))
def Perpendicular_line(imp, line_info): ## Calculates the parameters for a line that is ## perpendicular to an ROI line. This is the line ## that acts as the depth reference. angle, xbase, ybase, width, height, xend, yend, slope = line_info width, height, nChannels, nSlices, nFrames = imp.getDimensions() b = ybase - (slope*xbase) perp_angle = math.toRadians(angle - 90) slope_new_line = math.tan(perp_angle) return(slope_new_line, b)
def skitter(_field): _maxangle = 2 * Math.PI _ordering = sortBy(_field) _increment = _maxangle / len(_ordering) _curangle = 0 g.nodes[0].outdegree _maxdeg = outdegree.max + 1.0 for _n in _ordering: _radius = 1 - Math.log((_n.outdegree + 1.0) / _maxdeg) _radius = _radius * 500.0 _x = 500.0 + _radius * Math.cos(_curangle) _y = 500.0 + _radius * Math.sin(_curangle) _n.setX(_x) _n.setY(_y) _curangle += _increment
def gene(cible, p): taille = 12 if p.getPerceptType() == "Home": taille = 20 # Distance par rapport au tir angle = self.towards(cible.getX(), cible.getY()) angle = Math.PI * angle / 180 t = Math.tan(angle) s = Math.sin(angle) c = Math.cos(angle) dist_x = ( p.getX() + t* p.getY()) / (c + s * t) dist_y = -p.getY()/c + t * dist_x #print self.getAddress().getName() + " --> " + str(dist_x) + " --- " + str(dist_y) return abs(dist_y) < taille and dist_x > 0 and dist_x< cible.distanceTo(Point())
def damageAndPull(self, l): for e in self.nearbyMobs(l, .5, 2, .5): pull_dir = self.totem.getLocation().clone().subtract( e.getLocation()).toVector() pull_dir = Vector(Math.max(Math.min(pull_dir.getX() / 5, 1), -1), 0.2, Math.max(Math.min(pull_dir.getZ() / 5, 1), -1)) e.setVelocity(pull_dir) if e in self.hit: continue self.hit.add(e) self.damage(e, False, 2, .7, 0, 0, .3, 0, 0)
def localContrast(im, block = 127, histobins = 256, maxslope = 3): ipMaskCLAHE = ByteProcessor(im.getWidth(),im.getHeight()) ipMaskCLAHE.threshold(-1) bitDepth = im.getBitDepth() if bitDepth == 8: maxDisp = Math.pow(2,8) - 1 else: maxDisp = Math.pow(2,12) - 1 ip = im.getProcessor() ip.setMinAndMax(0,maxDisp) if bitDepth == 8: ip.applyLut() Flat.getFastInstance().run(im, block, histobins, maxslope, ipMaskCLAHE, False) del ipMaskCLAHE return im
def generateData(self, channel, numofpoints): if self.useGaussian: for i in range(numofpoints): self.resetGaussian(i) baseValue = self.gaussian.yAtX(i + 1) # print channel, baseValue, i self.data.append( self.round( (baseValue + channel) * (1.0 + self.noiseLevel * (2.0 * Math.random() - 1.0)))) else: for i in range(numofpoints): self.data.append( self.round(int(Math.random() * 10.0) * (i + 1))) # print channel, self.data return self.data
def render_shape_to_graphics(self, shape): r = shape.getShapeRenderer() # Find the size that the shape will be rendered to at the specified scale and resolution. shapeSizeInPixels = r.getSizeInPixels(1.0, 96.0) # Rotating the shape may result in clipping as the image canvas is too small. Find the longest side # and make sure that the graphics canvas is large enough to compensate for this. maxSide = Math.max(shapeSizeInPixels.width, shapeSizeInPixels.height) image = BufferedImage(int(maxSide * 1.25), int(maxSide * 1.25), BufferedImage.TYPE_INT_ARGB) # Rendering to a graphics object means we can specify settings and transformations to be applied to # the shape that is rendered. In our case we will rotate the rendered shape. gr = image.getGraphics() # Clear the shape with the background color of the document. gr.setBackground(shape.getDocument().getPageColor()) gr.clearRect(0, 0, image.getWidth(), image.getHeight()) # Center the rotation using translation method below gr.translate(image.getWidth() / 8, image.getHeight() / 2) # Rotate the image by 45 degrees. gr.rotate(45 * Math.PI / 180) # Undo the translation. gr.translate(-image.getWidth() / 8, -image.getHeight() / 2) # Render the shape onto the graphics object. r.renderToSize(gr, 0, 0, shapeSizeInPixels.width, shapeSizeInPixels.height) ImageIO.write(image, "png", File(self.dataDir + "TestFile.RenderToGraphics.png")) gr.dispose() print "Shape rendered to Graphics successfully."
def gene(cible, p): taille = 12 if p.getPerceptType() == "Home": taille = 20 # Distance par rapport au tir angle = self.towards(cible.getX(), cible.getY()) angle = Math.PI * angle / 180 t = Math.tan(angle) s = Math.sin(angle) c = Math.cos(angle) dist_x = (p.getX() + t * p.getY()) / (c + s * t) dist_y = -p.getY() / c + t * dist_x #print self.getAddress().getName() + " --> " + str(dist_x) + " --- " + str(dist_y) return abs(dist_y) < taille and dist_x > 0 and dist_x < cible.distanceTo( Point())
def eviteObstacles(percepts): dist1 = dist2 = 500 taille_robot = 20 liste_obstacles = [] for p in percepts: centre = Point() centre.setCoord(p.getX(), p.getY()) liste_obstacles.append(centre) # on dessine 2 droite paralleles a la direction # qui partent des bords du robot -> d1 : y = 12 et d2 : y = -12 # Dans nouveau repere : origine = self # rotation du repere de l'angle de direction courant direction = self.getHeading() angle = Math.PI * direction / 180 t = Math.tan(angle) s = Math.sin(angle) c = Math.cos(angle) for p in liste_obstacles: # centre_x, centre_y : centre de l'obstacle dans le repere centre_x = (p.getX() + t * p.getY()) / (c + s * t) centre_y = -p.getY() / c + t * centre_x # savoir quelle droite prendre if centre_x > 0: if centre_y >= 0 and centre_y <= 2 * taille_robot: y = centre_y - taille_robot dist1 = min( dist1, -Math.sqrt(taille_robot * taille_robot - y * y) + centre_x) elif centre_y < 0 and centre_y >= -(2 * taille_robot): y = centre_y + taille_robot dist2 = min( dist2, -Math.sqrt(taille_robot * taille_robot - y * y) + centre_x) if min(dist1, dist2) <= 100 and abs(dist1 - dist2) > 2: if dist1 < dist2: direction += 100 / dist1 else: direction -= 100 / dist2 self.setHeading(direction)
def doInBackground(self, params): w, h, self.position = params bitmap = self.getSpriteBitmap() width = bitmap.getWidth() height = bitmap.getHeight() xscale = w / float(width) yscale = h / float(height) scale = Math.min(xscale, yscale) if 0 < scale < 1: sw = Math.max(1, scale * width) sh = Math.max(1, scale * height) bitmap = Bitmap.createScaledBitmap(bitmap, sw, sh, True) elif scale >= 2: s = Math.min(int(Math.floor(scale)), 3) sw = Math.max(1, s * width) sh = Math.max(1, s * height) bitmap = Bitmap.createScaledBitmap(bitmap, sw, sh, False) preview = self.emptyBitmap(w, h, True) canvas = Canvas(preview) canvas.drawBitmap(bitmap, (w - bitmap.getWidth()) / 2, (h - bitmap.getHeight()) / 2, self.paint) return preview
def in_cone (a1, a2, d2, radius): # bug madkit ;-) parfois on est DANS l'objet... if d2 <= radius: d2 = radius + 1 delta = Math.asin (radius / d2) + 15 cone_sup = add_angles (a2, delta) cone_inf = add_angles (a2, -delta) rule = angle_in_range (a1, cone_inf, cone_sup) return rule
def singleCS(self, vs, into, node, angle): angle += 0.5 * Math.PI angle %= 2.0 * Math.PI wi, h = vs.size.width, vs.size.height a, b = wi / 2.3, h / 2.3 x0, y0 = wi / 2.0, h / 2.0 bx, by = 1, 1 e = Math.sqrt(1 - b**2 / a**2) r = a * Math.sqrt((1 - e**2) / (1 - e**2 * Math.cos(angle)**2)) x = r * Math.cos(angle) + x0 y = -r * Math.sin(angle) + y0 cs = vs.orthoBoxCS(into, node + "_FILLET", -100, x - bx / 2, y - by / 2, 1, 1, bx, by) return cs
def newElement(self): theta = Math.toRadians(self.angle) element = Element(self, complex(R0 * math.cos(theta), R0 * math.sin(theta))) self.angle = self.angle + self.forcedDivergence if self.angle > 360.0: self.angle = self.angle - 360.0 return element
def in_cone(a1, a2, d2, radius): # bug madkit ;-) parfois on est DANS l'objet... if d2 <= radius: d2 = radius + 1 delta = Math.asin(radius / d2) + 15 cone_sup = add_angles(a2, delta) cone_inf = add_angles(a2, -delta) rule = angle_in_range(a1, cone_inf, cone_sup) return rule
def toBut(self, but): if but.x == 'abs': return but.y a = but.x - self.origin.x b = but.y - self.origin.y if a == 0 and b == 0: return rnd.nextDouble() * 360; if b < 0: return 180*Math.asin(a / Math.sqrt(Math.pow(a,2)+Math.pow(b,2)))/Math.PI+270 else: return 180*Math.acos(a / Math.sqrt(Math.pow(a,2)+Math.pow(b,2)))/Math.PI
def move(this): if this._retreat_ttl: this._retreat_ttl -= 1 if not this._retreat_ttl: this.me.setBehavior(defensing) return if len(this.me._killers) == 0 or not this._enemyX: return x = Math.cos(self.towards(this._enemyX, this._enemyY) * Math.PI / 180) * security_radius y = Math.sin(self.towards(this._enemyX, this._enemyY) * Math.PI / 180) * security_radius for pos in this.resolve( this.me._killers, this.getHalfCircle(len(this.me._killers), security_radius, x, y)): k = this.me.getKillerByName(pos[0].getName()) #k.setPosition(pos[1][0], pos[1][1]) self.send(k.getAddress(), 'move', str(pos[1][0]), str(pos[1][1]))
def p_addition(p): '''addition : term | term addOP addition''' from java.lang import Math import Addition if len(p) == 4 and isinstance( p[1], int ) and isinstance( p[3], int ): print "Calling java Math: ", Math.max(p[1], p[3]) print "Calling java Addition.add: ", Addition.add(p[1], p[3]) if len(p) == 4: p[0] = str(p[1]) + str(p[2]) + str(p[3]) else : p[0] = p[1]
def compute_heading(target, mode): # composantes X et Y du vecteur direction final X = Y = 0 for it, dist in percepts.friends.items(): # percept, dist, scale, theta, p X = X + vector_x(it, dist, 50, 60, 2) Y = Y + vector_y(it, dist, 50, 60, 2) for it, dist in percepts.bases.items(): # Les bases sont boguées : repère sur le coin # supérieur gauche X = X + bug_vector_x(it, dist, 60, 70, 2) Y = Y + bug_vector_y(it, dist, 60, 70, 2) for it, dist in percepts.attackers.items(): # devrait être négligeable... X = X + vector_x(it, dist, 30, 70, 2) Y = Y + vector_y(it, dist, 30, 70, 2) for it, dist in percepts.explorers.items(): X = X + vector_x(it, dist, 20, 60, 1) Y = Y + vector_y(it, dist, 20, 60, 1) for it, dist in percepts.homes.items(): X = X + bug_vector_x(it, dist, 60, 70, 2) Y = Y + bug_vector_y(it, dist, 60, 70, 2) for it, dist in percepts.obstacles.items(): radius = it.getRadius() X = X + vector_x(it, dist, 50 + radius, 60, 2) Y = Y + vector_y(it, dist, 50 + radius, 60, 2) # pour la cible if mode == 'flee': offset = 180 u = 12 # on s'arrache viiiiite !! else: offset = 0 u = 8 X = X + Math.cos( deg2pi(offset + self.towards(target.getX(), target.getY())) ) * u * target.getDistance() Y = Y + Math.sin( deg2pi(offset + self.towards(target.getX(), target.getY())) ) * u * target.getDistance() if immobile(): toterm("immobile") self.setHeading(self.towards(X, Y))
def message(self, m): x = float(m.getArg1()) + m.getFromX() y = float(m.getArg2()) + m.getFromY() d = Math.sqrt(x*x+y*y) a = m.getAct() if a=='Me': return 1/(d + 1) elif a=='RocketLauncher': if d>200 and d<400 and mem.trouille < mem.t: mem.trouille = mem.t
def eviteAmis(percepts): dist1 = dist2 = 500 taille_robot = 20 liste_obstacles = [] for p in percepts: centre = Point() centre.setCoord(p.getX(), p.getY()) liste_obstacles.append(centre) # on dessine 2 droite paralleles a la direction # qui partent des bords du robot -> d1 : y = 12 et d2 : y = -12 # Dans nouveau repere : origine = self # rotation du repere de l"angle de direction courant direction = self.getHeading() angle = Math.PI * direction / 180 t = Math.tan(angle) s = Math.sin(angle) c = Math.cos(angle) for p in liste_obstacles: # centre_x, centre_y : centre de l"obstacle dans le repere centre_x = ( p.getX() + t* p.getY()) / (c + s * t) centre_y = -p.getY()/c + t * centre_x # savoir quelle droite prendre if centre_x > 0: if centre_y >= 0 and centre_y <= 2*taille_robot: y = centre_y - taille_robot dist1 = min(dist1,-Math.sqrt(taille_robot*taille_robot - y*y) + centre_x) elif centre_y < 0 and centre_y >= -(2*taille_robot): y = centre_y + taille_robot dist2 = min(dist2,-Math.sqrt(taille_robot*taille_robot - y*y) + centre_x) if min(dist1, dist2) <= 100 and abs(dist1 - dist2) > 2: if dist1 < dist2: direction += 100/dist1 else: direction -= 100/dist2 self.setHeading(direction)
def message(self, m): x = float(m.getArg1()) + m.getFromX() y = float(m.getArg2()) + m.getFromY() d = Math.sqrt(x * x + y * y) a = m.getAct() if a == 'Me': return 1 / (d + 1) elif a == 'RocketLauncher': if d > 200 and d < 400 and mem.trouille < mem.t: mem.trouille = mem.t
def move(this): if not this._first_time and this._explore_ttl: this._explore_ttl -= 1 if not this._explore_ttl % 50: d('explore: ' + str(this._explore_ttl)) if not this._explore_ttl: this.me.setBehavior(exploring) return if this._join_ttl: this._join_ttl -= 1 if this._join_ttl: return else: sumx = sumy = 0 for p in this._join_points: sumx += p[0] sumy += p[1] this._join_direction = self.towards( sumx / len(this._join_points), sumy / len(this._join_points)) this._first_time = 0 if not this._cached and len(this.me._killers) > 0: if this._first_time: for pos in this.resolve( this.me._killers, this.getCircle(len(this.me._killers), security_radius)): k = this.me.getKillerByName(pos[0].getName()) k.setPosition(pos[1][0], pos[1][1]) this._cached = 1 else: x = Math.cos( this._join_direction * Math.PI / 180) * security_radius y = Math.sin( this._join_direction * Math.PI / 180) * security_radius for pos in this.resolve( this.me._killers, this.getHalfCircle(len(this.me._killers), security_radius, x, y)): k = this.me.getKillerByName(pos[0].getName()) k.setPosition(pos[1][0], pos[1][1]) this._cached = 1 this.sendCache()
def compute_heading (): if (mvt_mem.direction=="EAST"): x_modifier=2000 y_modifier=0 elif (mvt_mem.direction=="WEST"): x_modifier=-2000 y_modifier=0 elif (mvt_mem.direction=="SOUTH"): x_modifier=0 y_modifier=+2000 elif (mvt_mem.direction=="NORTH"): x_modifier=0 y_modifier=-1000 # on construit une liste de TOUS les objets répulsifs repulsives = percepts.attackers.items () + \ percepts.explorers.items () + \ percepts.homes.items () + \ percepts.friends.items () + \ percepts.obstacles.items () # valeurs magiques theta = 140 scale = 25 p = 2 u = 30 # composantes X et Y du vecteur direction final X = 0 Y = 0 if repulsives: for it, dist in repulsives: X = X + Math.cos (deg2pi (180 + self.towards (it.getX(), it.getY()))) * theta / Math.pow (dist/scale, p) Y = Y + Math.sin (deg2pi (180 + self.towards (it.getX(), it.getY()))) * theta / Math.pow (dist/scale, p) toterm ("AFTER REPULSION:"+str(X) +" "+ str(Y)) X = X + Math.cos (deg2pi ( self.getHeading() ))*u Y = Y + Math.sin (deg2pi ( self.getHeading() ))*u toterm ("AFTER ATTRACTION:"+str(X) +" "+ str(Y)) X+=x_modifier Y+=y_modifier toterm ("NEW HEADING : "+str(self.towards (X, Y))) self.setHeading (self.towards (X, Y))
def toBut(self, but): if but.x == 'abs': return but.y a = but.x - self.origin.x b = but.y - self.origin.y if a == 0 and b == 0: return rnd.nextDouble() * 360 if b < 0: return 180 * Math.asin( a / Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2))) / Math.PI + 270 else: return 180 * Math.acos( a / Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2))) / Math.PI
def __init__(self, extender): self._extender = extender self.setModel(extender) self.addMouseListener(mouseclick(self._extender)) self.getColumnModel().getColumn(0).setPreferredWidth( Math.round(10 / 10 * 1)) self.getColumnModel().getColumn(1).setPreferredWidth(250) self.getColumnModel().getColumn(2).setPreferredWidth(250) self.getColumnModel().getColumn(3).setPreferredWidth(250) self.setRowSelectionAllowed(True) return
def build_exceedance_array(ref1, ref2, end_of_sept=True, tw=None): from java.lang import Math x1=sort(ref1, end_of_sept, tw) x2=sort(ref2, end_of_sept, tw) darray=[] i=0 n=int(Math.min(len(x1),len(x2))) while i < n: darray.append((100.0-100.0*float(i)/(n+1),x1[i],x2[i])) i=i+1 return darray
def floatingBuffer(self, vs, into, buffer): map = java.util.HashMap() if len(buffer) == 0: return map d = 360.0 / len(buffer) for i in range(len(buffer)): if self.structLink.isLinked(buffer[i]): path = java.util.ArrayList(1) path.add(buffer[i]) cs = self.singleCS(vs, into, buffer[i], Math.toRadians(i * d)) cs = vs.coords.translate(cs, 0, 0, 100) vs.matcher.add(cs, "Floating_" + buffer[i]) map.put(buffer[i], self.floatingView.geometry.buildMindNet(vs, cs, path)) else: map.put( buffer[i], self.singleCS(vs, into, buffer[i], Math.toRadians(i * d))) return map
def tick(self): if self.t % 20 > 0: return self.particle(self.player.getLocation().clone().add(0, .5, 0), Particle.PORTAL, 144, 4, 0, 4, .1) self.particle(self.player.getLocation().clone().add(0, .3, 0), Particle.CRIT_MAGIC, 144, 4, 0, 4, .1) self.particle(self.player.getLocation().clone().add(0, 1, 0), Particle.FIREWORKS_SPARK, 16, .3, 1, .3, .05) self.sound(Sound.ENTITY_EVOKER_CAST_SPELL, .5, 1.5) self.sound(Sound.BLOCK_LAVA_EXTINGUISH, 1, 1) self.player.setHealth(Math.min(self.player.getHealth() + 50, self.player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue())) for p in self.player.getNearbyEntities(4, 4, 4): if not isinstance(p, Player): continue p.setHealth(Math.min(p.getHealth() + 50, p.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue())) Bukkit.getPluginManager().callEvent(EntityRegainHealthEvent(p, 50, EntityRegainHealthEvent.RegainReason.CUSTOM)) self.particle(p.getLocation().clone().add(0, 1, 0), Particle.FIREWORKS_SPARK, 16, .3, 1, .3, .05)
def ftest(self, name, value, expected, ulps_err=1): if expected != 0. : # Tolerate small deviation in proportion to expected ulp_unit = Math.ulp(expected) else : # On zero, allow 2**-52. Maybe allow different slack based on name ulp_unit = Math.ulp(1.) # Complex expressions accumulate errors if name in ('cosh(2)-2*cosh(1)**2', 'sinh(1)**2-cosh(1)**2') : # ... quite steeply in these cases ulps_err *= 5 err = value-expected if abs(err) > ulps_err * ulp_unit: # Use %r to display full precision. message = '%s returned %r, expected %r (%r ulps)' % \ (name, value, expected, round(err/ulp_unit, 1)) self.fail(message)
def initTabs(self): # ## init autorize tabs # self.logTable = Table(self) self.logTable.setAutoCreateRowSorter(True) tableWidth = self.logTable.getPreferredSize().width self.logTable.getColumn("ID").setPreferredWidth(Math.round(tableWidth / 50 * 2)) self.logTable.getColumn("URL").setPreferredWidth(Math.round(tableWidth / 50 * 24)) self.logTable.getColumn("Orig. Length").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self.logTable.getColumn("Modif. Length").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self.logTable.getColumn("Unauth. Length").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self.logTable.getColumn("Authorization Enforcement Status").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self.logTable.getColumn("Authorization Unauth. Status").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) self._splitpane.setResizeWeight(1) self.scrollPane = JScrollPane(self.logTable) self._splitpane.setLeftComponent(self.scrollPane) self.scrollPane.getVerticalScrollBar().addAdjustmentListener(autoScrollListener(self)) self.menuES0 = JCheckBoxMenuItem(self._enfocementStatuses[0],True) self.menuES1 = JCheckBoxMenuItem(self._enfocementStatuses[1],True) self.menuES2 = JCheckBoxMenuItem(self._enfocementStatuses[2],True) self.menuES0.addItemListener(menuTableFilter(self)) self.menuES1.addItemListener(menuTableFilter(self)) self.menuES2.addItemListener(menuTableFilter(self)) copyURLitem = JMenuItem("Copy URL"); copyURLitem.addActionListener(copySelectedURL(self)) self.menu = JPopupMenu("Popup") self.menu.add(copyURLitem) self.menu.add(self.menuES0) self.menu.add(self.menuES1) self.menu.add(self.menuES2) self.tabs = JTabbedPane() self._requestViewer = self._callbacks.createMessageEditor(self, False) self._responseViewer = self._callbacks.createMessageEditor(self, False) self._originalrequestViewer = self._callbacks.createMessageEditor(self, False) self._originalresponseViewer = self._callbacks.createMessageEditor(self, False) self._unauthorizedrequestViewer = self._callbacks.createMessageEditor(self, False) self._unauthorizedresponseViewer = self._callbacks.createMessageEditor(self, False) self.tabs.addTab("Modified Request", self._requestViewer.getComponent()) self.tabs.addTab("Modified Response", self._responseViewer.getComponent()) self.tabs.addTab("Original Request", self._originalrequestViewer.getComponent()) self.tabs.addTab("Original Response", self._originalresponseViewer.getComponent()) self.tabs.addTab("Unauthenticated Request", self._unauthorizedrequestViewer.getComponent()) self.tabs.addTab("Unauthenticated Response", self._unauthorizedresponseViewer.getComponent()) self.tabs.addTab("Configuration", self.pnl) self.tabs.setSelectedIndex(6) self._splitpane.setRightComponent(self.tabs)
def NeighborChecker(xar, yar, zar, switch): """ Check the distance to neighbors, and count the number of neighbors below thdist. """ global thdist neighborA = zeros('d', len(xar)) if switch: for i in range(len(xar)): cx = xar[i] cy = yar[i] cz = zar[i] for j in range(len(xar)): if j != i : dist = Math.sqrt( Math.pow((cx - xar[j]), 2) + Math.pow((cy - yar[j]), 2)) if dist < thdist: if Math.abs(cz - zar[j]) < 2: logstr = ".... Dot%d - Dot%d too close: dist = %d" % (i, j, dist) IJ.log(logstr) print logstr neighborA[i] += 1 if neighborA[i] > 0: IJ.log("---> Dot%d rejected" % (i)) print "---> Dot", i, " rejected" return neighborA
def compute_heading (target, mode): # composantes X et Y du vecteur direction final X = Y = 0 for it, dist in percepts.friends.items (): # percept, dist, scale, theta, p X = X + vector_x (it, dist, 50, 60, 2) Y = Y + vector_y (it, dist, 50, 60, 2) for it, dist in percepts.bases.items (): # Les bases sont boguées : repère sur le coin # supérieur gauche X = X + bug_vector_x (it, dist, 60, 70, 2) Y = Y + bug_vector_y (it, dist, 60, 70, 2) for it, dist in percepts.attackers.items (): # devrait être négligeable... X = X + vector_x (it, dist, 30, 70, 2) Y = Y + vector_y (it, dist, 30, 70, 2) for it, dist in percepts.explorers.items (): X = X + vector_x (it, dist, 20, 60, 1) Y = Y + vector_y (it, dist, 20, 60, 1) for it, dist in percepts.homes.items (): X = X + bug_vector_x (it, dist, 60, 70, 2) Y = Y + bug_vector_y (it, dist, 60, 70, 2) for it, dist in percepts.obstacles.items (): radius = it.getRadius () X = X + vector_x (it, dist, 50+radius, 60, 2) Y = Y + vector_y (it, dist, 50+radius, 60, 2) # pour la cible if mode == 'flee': offset = 180 u = 12 # on s'arrache viiiiite !! else: offset = 0 u = 8 X = X + Math.cos (deg2pi (offset + self.towards (target.getX(), target.getY()))) * u * target.getDistance () Y = Y + Math.sin (deg2pi (offset + self.towards (target.getX(), target.getY()))) * u * target.getDistance () if immobile (): toterm ("immobile") self.setHeading (self.towards (X, Y))
def isMasqued(x, y): # on ne tire pas si un #@! de copain se trouve devant (verification des percepts seulement ?) for p in self.getPercepts(): if p.getTeam() == self.getTeam() and p.getPerceptType() != 'Rocket': if distance(p.getX(), p.getY()) > distance(x, y): continue a = self.towards(p.getX(), p.getY())*Math.PI/180 b = self.towards(x, y) r = p.getRadius() + security_distance cos = Math.cos(a - Math.PI/2) sin = Math.sin(a - Math.PI/2) inf = self.towards(p.getX() + r*cos, p.getY() + r*sin) sup = self.towards(p.getX() - r*cos, p.getY() - r*sin) #~ d('ene: x: '+str(x)+' y: '+str(y)+' A: '+str(b)+' a: '+str(b*Math.PI/180)) #~ d(' s: '+str(p.getX() + r*cos)+':'+str(p.getY() + r*sin)+' t: '+str(p.getX() - r*cos)+':'+str(p.getY() - r*sin)) #~ d('ami: x: '+str(p.getX())+' y: '+str(p.getY())+' A: '+str(a*180/Math.PI)+' a: '+str(a)+' r: '+str(r)) #~ d('ne pas tirer ene(A) entre '+str(inf)+' et '+str(sup)) #~ d('angles relatifs: ami: '+str((sup - inf) % 360)+' enemy: '+str((b - inf) % 360 )) if ((b - inf) % 360 ) > ((sup - inf) % 360): #~ d('boom!') continue #~ d('un ami me cache la cible!') return 1 return 0
def setTrajectoire(this): if this._explore: if not self.isMoving() or self.getHeading() == 0: self.randomHeading() return decalx = decaly = 0 for p in self.getPercepts(): type = p.getPerceptType() dist = p.getDistance() if dist < redirect_distance and p.getTeam() == self.getTeam() and (type == 'Home' or type == 'RocketLauncher' or type == 'Explorer'): decalx += p.getX() / dist * (70-dist) / 120 decaly += p.getY() / dist * (70-dist) / 120 #~ d('distance: '+str(dist)) #~ d('direction originelle: '+str(self.towards(this._destX, this._destY))) #~ d('direction modifiee: '+str(self.towards(Math.cos(self.towards(this._destX, this._destY))-decalx, Math.sin(self.towards(this._destX, this._destY))-decaly))) self.setHeading(self.towards(Math.cos(self.towards(this._destX, this._destY)*Math.PI/180)-decalx, Math.sin(self.towards(this._destX, this._destY)*Math.PI/180)-decaly))
def addElement(self): event = GrowthEvent(self) self.notifyBeforeAddingElement(event) element = self.newElement() self.elts.append(element) angle = Math.toDegrees(math.atan2(element.z.imag, element.z.real)) if (angle < 0.0): angle = angle + 360.0 self.angles.append(angle) if (len(self.angles) > 1): divergence = angle - self.angles[-2] if divergence < 0.0: divergence = divergence + 360.0 self.divergences.append(divergence) self.notifyAfterAddingElement(event)