Example #1
0
def generarNombres():
    silabas = ['pan','chon','je','men','ti','ca','se']
    nombre = ''
    for x in range(0,rnd(2,4)):
        nombre = nombre + silabas[rnd(0,len(silabas)-1)]

    return nombre
Example #2
0
    def __init__(self, sirenSwitch, num=20):
        self.num = num
        self.sirenSwitch = sirenSwitch

        self.fades = Fader(fadein=5, fadeout=30, dur=[35]*num, mul=self.sirenSwitch*.01)
        self.trems = Sine(freq=[rnd(8,16) for i in range(num)], mul=.5, add=.5)
        self.sines = Sine(freq=[rnd(8000, 12000) for i in range(num)], mul=self.fades*self.trems).out()
Example #3
0
	def __init__(self):
		# double_buffer = True, depth_size = 24
		# window flip() is invoked after every on_draw() event
		config = Config(double_buffer=True)
		super(Window, self).__init__(resizable=True, config=config)
		glClearColor(0.1,0.2,0,1)
		glEnable(GL_TEXTURE_2D)
		#glShadeModel(GL_SMOOTH) # TODO: what does this do?

		self.keys = key.KeyStateHandler()
		self.push_handlers(self.keys)
		# some kind of event history
		self.history={}

		#self.label = pyglet.text.Label('Gebrauchswert')

		#self.batch = pyglet.graphics.Batch()
		#self.jaja = pyglet.sprite.Sprite(
			#media.inhabitant('jaja01'), batch=self.batch)

		self.clock = pyglet.clock.ClockDisplay()
		#pyglet.clock.schedule_interval(self.update, 1./24)
		pyglet.clock.set_fps_limit(36)

		#impt = pyglet.image.SolidColorImagePattern((100,180,90,200))
		#self.bg = pyglet.image.create(800,600, impt)

		self.viewport = view.create(self, self.width/2,self.height/2)

		#TODO: get this out of here!
		j = jaja.create(world.surface.width/2,world.surface.height/2)
		self.viewport.goto(map_pos(j))
		self.viewport.zoom = 1.2
		for i in range(25):
			jaja.create(rnd(world.surface.width),rnd(world.surface.height))
Example #4
0
def quickDyn(spread=5, num=10, joints=False, bake=False):
    target = []
    g = py.gravity()

    for i in range(0,num):
        c = py.polyCube()
        target.append(c)
        x = rnd(-spread,spread)
        y = rnd(-spread,spread) + 10
        z = rnd(-spread,spread)
        py.move(x,y,z)
        py.rotate(x,y,z)

    s(target)
    py.rigidBody()

    for i in range(0,len(target)):
        py.connectDynamic(target[i],f=g)

    if(joints==False and bake==True):
        bakeAnimation(target)
        
    if(joints==True):
        target2 = []

        for i in range(0,len(target)):
            s(target[i])
            jnt = py.joint()
            target2.append(jnt)
            
        if(bake==True):
            bakeAnimation(target2)

        for i in range(0,len(target2)):
            unparent(target2[i])
Example #5
0
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

        self.image = image.load_image("particle").convert()
        self.rect = self.image.get_rect()
        self.rect.center = (rnd(0, consts.screen_size[0]), rnd(0, consts.screen_size[1]))
        self.dx, self.dy = (rnd(-2, 2), rnd(-2, 2))
 def __init__(self,canvas):
    self.canvas = canvas
    self.x = rnd(700,1000-100)
    self.y = rnd(100,500)
    self.r = rnd(10,50)
    self.popali=0
    self.id = canvas.create_oval(self.x-self.r,self.y-self.r,self.x+self.r,self.y+self.r, fill='grey')
def click_ball(event):
    global scores, w, h, balls, flag_t
    """ Обработчик событий мышки для игрового холста canvas
    param event: событие с координатами клика
    По клику мышкой нужно удалять тот объект, на который мышка указывает.
    А также засчитываеть его в очки пользователя.
    """
    obj = canv.find_closest(event.x, event.y)
    try:
        x1, y1, x2, y2 = canv.coords(obj)
        radius=math.sqrt((x2-x1)**2+(y2-y1)**2)/2
        # print(radius)
        delta_scores=int(100/radius)
    except:
        x1,y1,x2,y2=0,0,0,0
        
    
    if x1 <= event.x <= x2 and y1 <= event.y <= y2 and flag_t==0: # Блок на возрастание очков при времени =0
        scores+=delta_scores
        # print(scores)
        change_scores_text()
        canv.delete(obj)
        # balls.remove(obj)
        # Создаем новый шарик
        new_ball = ball()
        new_ball.x = rnd(50,w-50)
        new_ball.y = rnd(50,h-50)
        new_ball.r = rnd(10,50)
        new_ball.nap = rnd(1,4)
        new_ball.nx = 1
        new_ball.ny = 1
        new_ball.color = choice(['aqua', 'blue', 'fuchsia', 'green', 'maroon', 'orange',
                  'pink', 'purple', 'red','yellow', 'violet', 'indigo', 'chartreuse', 'lime'])
        balls += [new_ball]
        b.paint()
Example #8
0
def bak_ost(V, K, a):
    #V - изначальное количество вершин
    #K - количество вершин в кластере
    #graph - генерирующийся граф
    #a - притягательность вершины
    graph = dok_matrix((V // K, V // K))
    numbers = [0] * (V // K)
    graph[0, 0] = 1
    vertexs = [0, 0] + (a - 1) * [0]
    for i in range(1, V):
        f = rnd(1, (a + 1) * (i + 1) - 1)
        if f <= a:
            j = i
        else:
            j = vertexs[rnd(0, len(vertexs) - 1)]
        vertexs.append(j)
        vertexs.append(i)
        graph[j // K, i // K] += 1
        graph[i // K, j // K] += 1
        numbers[j // K] += 1
        numbers[i // K] += 1
        vertexs += (a - 1) * [i]
    for i in graph.keys():
        graph[i[0], i[1]] /= numbers[i[0]]
    return graph
 def new_target(self):
     x = self.x = rnd(600,780)
     y = self.y = rnd(300,550)
     r = self.r = rnd(2,50)
     color = self.color = 'red'
     canv.coords(self.id, x-r,y-r,x+r,y+r)
     canv.itemconfig(self.id, fill = color)
Example #10
0
def readSampleXml():
    counterMin = 0;
    counter=int(counterMin);
    counterMax = 200;

    filePath = "/Users/nick/Desktop/"
    fileName = "mocapData1.xml"

    #trackPoint = ["l_foot","l_knee","l_hip","r_foot","r_knee","r_hip","l_hand","l_elbow","l_shoulder","r_hand","r_elbow","r_shoulder","torso","neck","head"]
    trackPoint = ["head"]
    scaler = 1000

    xmlFile = xd.parse(filePath + "/" + fileName)
    print("loaded: " + fileName)

    for t in trackPoint:   
        polyCube()
        scale(0.1,0.1,0.1)

        joint = xmlFile.getElementsByTagName(t)
        for j in joint:

            x = scaler * float(j.getAttribute("x"))
            y = scaler * float(j.getAttribute("y"))
            z = scaler * float(j.getAttribute("z"))
            
            #if(x!=0 and y!=0 and z!=0):
            setFrame(counter)
            counter+=1
            move(x, y, z)
            rotate(rnd(-1 * scaler, scaler),rnd(-1 * scaler, scaler),rnd(-1 * scaler, scaler))
            keyframe()
        
    print("...script complete.")
def add_spiders(event):
    global spiders
    x = int(event.x)
    y = int(event.y)
    r = 100
    for z in range(5):
        spiders += [new_spider(rnd(x-r,x+r),rnd(y-r,y),15, choice(colors))]
def new_game():
    global num_bombs
    global num_bombs_delete
    num_bombs = 0
    num_bombs_delete = 3
    global a
    a = [[cell() for c in range(nc)] for r in range(nr)]
    global bombs_count
    bomb_count = 5 + rnd(25)
    bombs_count = bomb_count
    while bomb_count > 0:
        r = rnd(nr)
        c = rnd(nc) 
        if not a[r][c].bomb:
            a[r][c].bomb = 1
            bomb_count -= 1
    else:
        pass
    
    for r in range(nr):
        for c in range(nc):
            k = 0
            for dr in [-1,0,1]:
                for dc in [-1,0,1]:
                    rr = r + dr
                    cc = c + dc
                    if rr in range(nr) and cc in range(nc):
                        if a[rr][cc].bomb:
                            k += 1
            a[r][c].n = k
    
    paint()
Example #13
0
 def move(self, board_size):
     ''' Let the player make a move
     :param board_size: the size of the board (x,y)
     :return: the new position or none
     If the player is on the board, he goes random in one direction, then returns the new position.
     If the player is not on the board, check his willingness to play and then propose a new position.
     In the latter case, the player do not change his position.
     '''
     if self.is_placed():
         while True:
             direction = rnd(0, 360)
             (new_x, new_y) = self.get_position()
             new_x += sin(direction) * self.step
             new_y += cos(direction) * self.step
             if new_x < 0 or new_x > board_size[0] - 1 \
                     or new_y < 0 or new_y > board_size[1] - 1:
                 # if the coordinates are outside the board size, retry
                 continue
             else:
                 self.place(new_x, new_y)
                 return self.get_position()
     else:
         # if the player is outside the board
         # returns the new random coordinates if the player want to play
         if rnd(1, 10) < self.willing_to_play:
             return rnd(0, board_size[0] - 1), rnd(0, board_size[1] - 1)
Example #14
0
def bogsort(ls):
    count = 0
    while not list_sorted(ls):
        count += 1
        switch = (rnd(0, len(ls)-1), rnd(0, len(ls)-1))
        ls[switch[0]], ls[switch[1]] = ls[switch[1]], ls[switch[0]]
    print count
    return ls
Example #15
0
 def new_target(self):
     """ Инициализация новой цели. """
     x = self.x = rnd(600,780)
     y = self.y = rnd(300,550)
     r = self.r = rnd(2,50)
     color = self.color = 'red'
     canv.coords(self.id, x-r,y-r,x+r,y+r)
     canv.itemconfig(self.id, fill = color)
def inertia_weight(fi1, fi2, vel, pos, best_pos, neigh_best, weight=0.9):

    new_vel = []
    for idx in xrange(len(vel)):
        new_vel.append(weight * vel[idx] + fi1 * rnd() * (best_pos[idx] - pos[idx]) +
                                           fi2 * rnd() * (neigh_best[idx] - pos[idx]))

    return np.array(new_vel)
def inertia_weight(num_particles, part_vel, fi1, fi2, part_pos, part_best_pos, part_gbest, weight=0.9):

    new_vel = []
    for idx in xrange(num_particles):
        new_vel.append(weight * part_vel[idx] + fi1 * rnd() * (part_best_pos[idx] - part_pos[idx]) +
                                                fi2 * rnd() * (part_gbest[idx] - part_pos[idx]))

    return np.array(new_vel)
def pso_vanilla(fi1, fi2, vel, pos, best_pos, neigh_best):

    new_vel = []
    for idx in xrange(len(vel)):
        new_vel.append(vel[idx] + fi1 * rnd() * (best_pos[idx] - pos[idx]) +
                                  fi2 * rnd() * (neigh_best[idx] - pos[idx]))

    return np.array(new_vel)
Example #19
0
def Mate(turmite1, turmite2):
    split = rnd(1, 11)
    s = rnd(0, 1)
    chroms = turmite1.chrom, turmite2.chrom
    new_turmite = Turmite()
    new_turmite.chrom = chroms[s][0:split]+chroms[not[s]][split:12]
    new_turmite.Read()
    new_turmite.Color()
    new_turmite.parents = (turmite1, turmite2)
    return new_turmite
Example #20
0
def RandomPointGrid(noise=1.0,gridSize=8,scale=(1.0,1.0)):
	P=[]
	wd,ht=scale
	psx,psy= Vec2(float(wd),float(ht))/float(gridSize)
	for i in range(gridSize):
		y=(0.5+i)*psy
		for j in range(gridSize):
			x=(0.5+j)*psx
			P.append( Vec2(psx*(rnd()-rnd())*noise/2.0+x,psy*(rnd()-rnd())*noise/2.0+y) )
	return P
Example #21
0
File: 7.py Project: tanya9779/lab11
 def new_target(self):
     """
     Инициализация новой цели
     """
     x = self.x = rnd(600, 780)
     y = self.y = rnd(300, 550)
     r = self.r = rnd(2, 50)
     color = self.color = choice(["blue", "green", "red", "brown"])
     canv.coords(self.id, x - r, y - r, x + r, y + r)
     canv.itemconfig(self.id, fill=color)
 def __init__(self,canvas):
    self.canvas = canvas
    self.x = rnd(700,1000-100)
    self.y = rnd(100,500)
    self.r = choice([10,20,30,40,50])
    slovar={'10':5,'20':4,'30':3,'40':2,'50':1}
    # self.score = self.r//10
    self.score=slovar[str(self.r)]
    self.popali=0
    self.id = canvas.create_oval(self.x-self.r,self.y-self.r,self.x+self.r,self.y+self.r, fill='grey')
    self.score_text = canvas.create_text(self.x,self.y,text=self.score)
Example #23
0
File: 8.py Project: tanya9779/lab11
 def new_target(self):
     """
     Инициализация новой цели
     """
     x = self.x = rnd(600,780)
     y = self.y = rnd(300,550)
     r = self.r = rnd(2,50)
     self.vy=rnd(1,2)
     color = self.color = choice(['blue','green','red','brown'])
     canv.coords(self.id, x-r,y-r,x+r,y+r)
     canv.itemconfig(self.id, fill = color)
def constriction_factor(fi1, fi2, vel, pos, best_pos, neigh_best, K=0.729):

    # phi = fi1 + fi2
    # K   = 2 / np.abs(2 - phi - np.sqrt(phi ** 2 - 4 * phi))

    new_vel = []
    for idx in xrange(len(vel)):
        new_vel.append(K * (vel[idx] + fi1 * rnd() * (best_pos[idx] - pos[idx]) +
                                       fi2 * rnd() * (neigh_best[idx] - pos[idx])))

    return np.array(new_vel)
def constriction_factor(num_particles, part_vel, fi1, fi2, part_pos, part_best_pos, part_gbest, K=0.729):

    phi = fi1 + fi2
    K   = 2 / np.abs(2 - phi - np.sqrt(phi ** 2) - 4 * phi)

    new_vel = []
    for idx in xrange(num_particles):
        new_vel.append(K * (part_vel[idx] + fi1 * rnd() * (part_best_pos[idx] - part_pos[idx]) +
                                            fi2 * rnd() * (part_gbest[idx] - part_pos[idx])))

    return np.array(new_vel)
Example #26
0
 def __init__(self):
     self.alive = True
     self.energy = 50
     self.dirs = [[1, 0], [0, 1], [-1, 0], [0, -1]]
     self.dir = rnd(0, 3)
     self.pos = [rnd(0, 99), rnd(0, 99)]
     self.state = rnd(0, 1)
     self.chrom = bin(rnd(0, 2**12-1))[2:]
     self.chrom = '0'*(12-len(self.chrom))+self.chrom
     c = self.chrom
     self.Read()
     self.Color()
Example #27
0
 def __init__(self, input, ampSwitch, countCloseDisto, num=8):
     self.input = input
     self.ampSwitch = ampSwitch
     self.countCloseDisto = countCloseDisto
     self.amplitudes = DataTable(size=4, init=[1,.35,1,1])
     self.rand = Randi(min=1000, max=2000, freq=[rnd(.02, .05) for i in range(2)])
     self.freq = Randi(min=[.99]*num, max=1.01, mul=self.rand)
     self.varAmp = TableIndex(self.amplitudes, self.countCloseDisto)
     self.varAmpPort = Port(self.varAmp, 10, 10, mul=.3)
     self.amp = Randi(min=0.5, max=1.3, freq=[rnd(.15, .2) for i in range(2)], mul=self.varAmpPort)
     self.wind = Waveguide(self.input, freq=self.freq, dur=60, minfreq=800, mul=self.amp*self.ampSwitch)
     self.mix = self.wind.mix(2)
def random_sample(px, py, r, uniform=False):

    a = rnd()
    b = rnd()

    if uniform and b < a:
        a, b = b, a

    x = b * r * cos(2 * pi * a / b)
    y = b * r * sin(2 * pi * a / b)

    return x + px, y + py
Example #29
0
def addfake(entity):
    name = NAMES[rnd(LN)] + ' ' + (entity if rnd(2) else '')
    my_document = search.Document(
        # Setting the doc_id is optional. If omitted, the search service will create an identifier.
        fields=[
            search.TextField(name='customer', value=name),
            search.HtmlField(name='comment', value='dddf  ' + entity),
        ],
        language='ru'
    )
    search.Index('testing').put(my_document)

    yield op.counters.Increment('fakes')
Example #30
0
	def __init__(self, brick, *args, **kwargs):
		Node.__init__(self, *args, **kwargs)
		self.position = brick.position
		for dx, dy in ((-1, -1), (1, -1), (-1, 1), (1, 1)):
			p = SpriteNode(brick.texture, scale=0.5, parent=self)
			p.position = brick.size.w/4 * dx, brick.size.h/4 * dy
			p.size = brick.size
			d = 0.4
			r = 30
			p.run_action(A.move_to(rnd(-r, r), rnd(-r, r), d))
			p.run_action(A.scale_to(0, d))
			p.run_action(A.rotate_to(rnd(-pi/2, pi/2), d))
		self.run_action(A.sequence(A.wait(d), A.remove()))
Example #31
0
def target_constructor(form):
    global root, canv, colors, target, targets
    this = target.copy()
    if form == "circle":
        x = rnd(100, 700)
        y = rnd(100, 500)
        r = rnd(30, 50)
        create_obj_circle(this, r)
        this["sprite"] = sprite_draw('circle', r, this["color"], x, y)

    elif form == "rect":
        x = rnd(100, 700)
        y = rnd(100, 500)
        a = rnd(30, 50)
        create_obj_rect(this, a)
        this["sprite"] = sprite_draw('rect', a, this["color"], x, y)

    elif form == "star":
        x = rnd(100, 700)
        y = rnd(100, 500)
        r = rnd(30, 50)
        r1 = 6 / 7 * r
        n = 15
        a = pi / 180 * (360 / n / 2)
        poligonList = []
        for c in range(0, n * 2, 2):
            x1 = cos(a * c) * r + x
            x2 = cos(a * (c + 1)) * r1 + x
            y1 = sin(a * c) * r + y
            y2 = sin(a * (c + 1)) * r1 + y
            poligonList.append((x1, y1))
            poligonList.append((x2, y2))
        create_obj_star(this, r)
        this["sprite"] = sprite_draw('star', r, this["color"], 0, 0,
                                     poligonList)
    targets.append(this)
Example #32
0
    def run(self, edit, *arg, **args):
        self.window = self.view.window()
        self.selection = sublime.Selection(self.view.id())
        self.setting = self.view.settings()

        for region in self.view.sel():
            region = self.view.full_line(region)
            # indent = get_indent(self.view.substr(region))
            indent = self.view.indentation_level(region.begin())
            nb = str(rnd(100, 1000))
            code = ' # counter' + nb
            text = ('\t' * indent) + 'counter' + nb + ' = 0\n'
            text += self.view.substr(region)
            text += ('\t' * indent) + '\tcounter' + nb + ' += 1\n'
            text += ('\t' * indent) + '\tif counter' + nb + ' > 100:\n'
            text += ('\t' * indent) + '\t\tprint("end up counter' + nb + '")\n'
            text += ('\t' * indent) + '\t\treturn False' + code + '\n'

            self.view.replace(edit, region, text)
Example #33
0
def crossover(selected, pc, Method='SinglePoint'):
    children = []
    counter = 0
    pop_length = len(selected['Selected_Individuals'])
    number_of_genes = len(selected['Selected_Individuals'][0])
    if Method == 'SinglePoint':
        while counter < pop_length // 2:
            parents = get_pair(selected['Selected_Individuals'])
            r = round(rnd(), 1)
            if r <= pc:
                pos = random.randint(1, number_of_genes - 1)
                temp = copy.deepcopy(parents[0])
                parents[0][pos:number_of_genes] = parents[1][
                    pos:number_of_genes]
                parents[1][pos:number_of_genes] = temp[pos:number_of_genes]
                children.append(parents[0])
                children.append(parents[1])
                counter += 1
    return children
Example #34
0
 def fire2_end(self, event):
     """Выстрел мячом.
     Происходит при отпускании кнопки мыши.
     Начальные значения компонент скорости мяча vx и vy зависят от положения мыши.
     """
     # balls, bullet
     self.bullet += 1
     n = rnd(3, 8)
     if n == 3:
         n = 0
     new_ball = Ball(n)
     new_ball.r += 5
     self.an = math.atan((event.y - new_ball.y) / (event.x - new_ball.x))
     self.an = min(self.an, 0)
     new_ball.vx = self.f2_power * math.cos(self.an)
     new_ball.vy = - self.f2_power * math.sin(self.an)
     self.balls += [new_ball]
     self.f2_on = 0
     self.f2_power = 10
Example #35
0
 def __init__(self, TM, TAPS, start, invAmpSwitch, finalFadeout, num=8):
     self.w1 = [90, 80, 50, 60]
     self.w2 = [60, 70, 90, 80]
     self.w3 = [60, 60, 80, 90]
     self.slowDown = False
     self.start = start
     self.invAmpSwitch = invAmpSwitch
     self.ampSwitch = 1. - self.invAmpSwitch
     self.finalFadeout = finalFadeout
     self.relativeAmp = Sig(self.ampSwitch, mul=.95, add=.05)
     self.feedback = Sig(self.invAmpSwitch, mul=.198, add=.8)
     self.env = ExpTable([(0, 0), (60, 1), (300, .25), (8191, 0)])
     self.mBell = Beat(time=TM,
                       taps=TAPS,
                       w1=self.w1,
                       w2=self.w2,
                       w3=self.w3,
                       poly=1).play()
     self.amp = TrigEnv(self.mBell,
                        self.env,
                        self.mBell['dur'],
                        mul=self.mBell['amp']).stop()
     self.globalAmp = TrigLinseg(self.start, [(0, 0), (.001, 1), (1, 1)],
                                 mul=self.relativeAmp * .25)
     self.noise = Noise(self.amp).stop()
     self.vibrato = Sine(freq=[4.5, 4.87, 5.34, 5.67],
                         mul=[rnd(10, 30) for i in range(4)],
                         add=[
                             midiToHz(101) * random.uniform(.995, 1.005)
                             for i in range(4)
                         ]).stop()
     self.bell = Phaser(self.noise,
                        freq=self.vibrato,
                        spread=[random.uniform(1.4, 1.6) for i in range(4)],
                        q=0.5,
                        feedback=self.feedback,
                        num=num,
                        mul=self.globalAmp).stop()
     self.bellHp = Biquad(self.bell,
                          freq=1000,
                          q=.5,
                          type=1,
                          mul=self.finalFadeout).stop()
Example #36
0
 def __init__(self, x, y):
     global point
     self.delete = 0
     self.delete_point = 0.1  # Нужна, чтобы пули и пулемета удалялись быстрее.
     self.x = x
     self.y = y
     self.r = 5
     self.vx = 0
     self.vy = 0
     self.g = 0.09  # Ускорение свободного падения.
     self.color = 'black'
     self.id = canv.create_oval(self.x - self.r,
                                self.y - self.r,
                                self.x + self.r,
                                self.y + self.r,
                                fill=self.color)
     self.live = rnd(1, 5)
     if point > 0:
         point -= 1
Example #37
0
def main():
    seed(dt.now())
    flg = 0
    slowestPipe = 0
    pipesTiming = [0 for cnt in range(30)]
    pipeTimeArr = [[0 for cnt in range(10)] for cnt in range(2)]
    for i in range(30):
        pipesTiming[i] = rnd(MIN_TIME, MAX_TIME)

    for pipeSize in range(2, 22, 2):
        for i in range(pipeSize):
            if pipesTiming[i] > slowestPipe:
                slowestPipe = pipesTiming[i]

        pipeTimeArr[0][flg] = syncPipeCalc(pipeSize, pipesTiming, slowestPipe)
        pipeTimeArr[1][flg] = asyncPipeCalc(pipeSize, pipesTiming, slowestPipe)
        print(pipeSize, "\t", pipeTimeArr[0][flg], "\t", pipeTimeArr[1][flg])
        flg += 1
    drawGraph(pipeTimeArr)
Example #38
0
 def k_th_inner(A: List[int], k):
     assert k >= 1 and k <= len(A), "Invalid k or array."
     pivot = A[int(rnd() * len(A))]
     equalTo = []
     larger = []
     smaller = []
     for I in A:
         choice = equalTo if I == pivot else (
             larger if I > pivot else smaller)
         choice.append(I)
         counter[0] += 1
     del I, choice
     if len(smaller) == k - 1:
         return pivot
     if len(smaller) < k:
         return pivot if k - len(smaller) < len(equalTo) else \
             k_th_inner(larger, k - len(equalTo) - len(smaller))
     if len(smaller) >= k:
         return k_th_inner(smaller, k)
Example #39
0
    def __init__(self, x=40, y=450):
        """ Конструктор класса ball

        Args:
        x - начальное положение мяча по горизонтали
        y - начальное положение мяча по вертикали
        """
        self.x = x
        self.y = y
        self.r = rnd(1, 200) / 10
        self.vx = 0
        self.vy = 0
        self.color = choice(['#FFCCB6', '#CBAACB', '#FF968A', '#55CBCD'])
        self.id = canvas.create_oval(self.x - self.r,
                                     self.y - self.r,
                                     self.x + self.r,
                                     self.y + self.r,
                                     fill=self.color)
        self.live = 20
Example #40
0
    def move():
        Person.kills = 0
        Person.born = 0
        Person.dead = 0
        for i in range(len(Person.Live)):
            dx, dy = rnd(-1, 2), rnd(-1, 2)
            obj = Person.Live[i]
            if unit[obj].cord[0] == 0:
                dx = rnd(0, 2)
            if unit[obj].cord[0] == cords[0]:
                dx = rnd(-1, 1)
            if unit[obj].cord[1] == 0:
                dy = rnd(0, 2)
            if unit[obj].cord[1] == cords[1]:
                dy = rnd(-1, 1)
            unit[obj].cord[0] += dx
            unit[obj].cord[1] += dy

            unit[obj].age += 1

            if (unit[obj].age > 40 and rnd(30) == 1):
                unit[obj].state = 'dead'
                Person.dead += 1
                Person.show(unit[obj],
                            str(year) + ' dead!', 'family:', unit[obj].family,
                            'experience:', unit[obj].exp)
                print()
            elif (unit[obj].age > 70 and rnd(8) == 1):
                unit[obj].state = 'dead'
                Person.dead += 1
                Person.show(unit[obj],
                            str(year) + ' dead!', 'family:', unit[obj].family,
                            'experience:', unit[obj].exp)
                print()

        if len(Person.Live) == 0:
            print('No one alived at ' + str(year))
        print('\nYear: ' + str(year) + ' People count: ' +
              str(len(Person.Live)),
              end='')
Example #41
0
    def create_balls(self, quantity, max_speed, radius1, radius2):

        global all_balls

        all_balls = []

        for k in range(quantity):

            ball_0 = Ball(rnd(50, 750), rnd(50, 550),
                          rnd(-max_speed, max_speed + 1),
                          rnd(-max_speed, max_speed + 1), 0, 0,
                          rnd(radius1, radius2 + 1) * (rnd(2, 5) // 2), 0)

            all_balls.append(ball_0)
Example #42
0
 def __init__(self):
     self.route_x = rnd(-3, 4)
     self.route_y = rnd(-3, 4)
     self.x = rnd(100, 700)
     self.y = rnd(100, 500)
     self.r = rnd(30, 50)
     self.ball_color = self.painting_ball()
     self.ball = canv.create_oval(self.x - self.r,
                                  self.y - self.r,
                                  self.x + self.r,
                                  self.y + self.r,
                                  fill=self.ball_color[rnd(
                                      0,
                                      len(self.ball_color) - 1)])
Example #43
0
    def __init__(self, x, y, vx, vy):
        """ Конструктор класса ball

        Args:
        x - начальное положение мяча по горизонтали
        y - начальное положение мяча по вертикали
        """

        self.x = x
        self.y = y
        self.r = rnd(15, 20)
        self.vx = vx
        self.vy = vy
        self.color = choice(['blue', 'green', 'red', 'brown'])
        self.id = canv.create_oval(self.x - self.r,
                                   self.y - self.r,
                                   self.x + self.r,
                                   self.y + self.r,
                                   fill=self.color)
        self.live = 30
Example #44
0
    async def thaikick(self, ctx, *, user):
        """Attempt to thai kick a user"""

        author = ctx.message.author
        if user is not None:
            try:
                member = converter.MemberConverter(ctx, user).convert()
                tk = discord.Embed(
                    description="DUN DUN ~ ! {}, THAI KICK ~ !".format(
                        member.mention),
                    color=discord.Color(0xffb6c1))
                tk.set_image(url=rnd(self.tkgifs))
                await self.bot.say(embed=tk)

            except errors.BadArgument:
                await self.bot.say(
                    "{} tried to thai kick something inexistent. Shame!".
                    format(author.mention))
        else:
            await self.bot.send_cmd_help(ctx)
 def playHand(self, oppHistory=History()):
     active_chromosome = 5 * self.history.getHistory() + oppHistory.getHistory()
     totalSum = 0
     for i in range(5):
         totalSum += self.genome[active_chromosome].getGene(i).getValue()
     rockrange = range(0, self.genome[active_chromosome].getGene(1).getValue())
     paperRange = range(self.genome[active_chromosome].getGene(2).getValue()+1, self.genome[active_chromosome].getGene(1).getValue())
     sissorsRange = range(self.genome[active_chromosome].getGene(3).getValue() +1, self.genome[active_chromosome].getGene(2).getValue())
     lizardRange = range(self.genome[active_chromosome].getGene(4).getValue()+1, self.genome[active_chromosome].getGene(3).getValue())
     decision = rnd(0, totalSum)
     if  decision in rockrange:
         return  Game.getHands()['Rock']
     elif decision in paperRange:
         return  Game.getHands()['Paper']
     elif  decision in sissorsRange:
         return Game.getHands()['Sissors']
     elif decision in lizardRange:
         return Game.getHands()['Lizard']
     else:
         return Game.getHands()['Spock']
Example #46
0
    def test_rand(self):
        from random import random, randint as rnd
        for _ in range(100):
            t_side = rnd(0, 100)
            t_vol = t_side**3

            if random() < 0.6:  # make a false test
                t_type = random()
                if t_type < 0.33:
                    t_vol *= -1
                elif t_type < 0.66:
                    t_side *= -1
                else:
                    t_vol = int(t_vol * random() * 2)

            expected = t_vol > 0 and t_vol == t_side**3
            self.assertEqual(
                cube_checker(t_vol, t_side), expected,
                "Testing: volume = %s, side = %s, Expecting: %s" %
                (t_vol, t_side, expected))
Example #47
0
 def test_regression(self):
     from random import random as rnd
     solve = hack_1
     from time import time
     SIZE = 1000 # size of the regression (iterations)
     t1 = time()
     for i in xrange(SIZE):
         # int(rnd() * (upper_bound - lower_bound) + lower_bound) for the parameter
         sequence = sorted([int(rnd() * (1000 - 0)) + 0 for _ in xrange(2*(i + 2))])
         #print sequence
         b = []
         for i in xrange(len(sequence)/2):
             num  = sequence[i]
             b.append(num + sequence[-(i + 1)])
         #print b
         got = solve(b)
         #print got
         self.assertTrue(valid(b, got))
     t2 = time()
     print "regressionOK : "+str(t2 - t1)
Example #48
0
 def hit(self, pointss=1):
     """Попадание шарика в цель.
     Флажок is_hitted в True
     Изменение глбальных start_r, sub_r
     Обновление очков за эту цель
     """
     global start_r, sub_r, points, canv_points, wind
     self.is_hitted = True
     canv.coords(self.id, -10, -10, -10, -10)
     points += pointss
     canv.itemconfig(canv_points, text=points)
     start_r -= 5
     if start_r <= 0:
         start_r = 5
     sub_r += 4
     if sub_r >= 44:
         sub_r = 44
     wind = rnd(-5, 5)
     wind = wind * 0.2
     canv.itemconfig(wind_show, text=('wind = ' + "%.2f" % (wind)))
def move_balls():
    global x, y, r

    for i in balls:
        getxyr(i[0])
        vel = i[1]
        if (vel[0] > 0) and (x + r + vel[0]) > width:
            vel[0] *= -1
        if (vel[0] < 0) and (x - r + vel[0]) < 0:
            vel[0] *= -1

        dy = (-1)**rnd(1, 2)
        if (vel[1] > 0) and (y + r + vel[1]) > height:
            vel[1] *= -1
        if (vel[1] < 0) and (y - r + vel[1]) < 0:
            vel[1] *= -1

        canv.coords(i[0], x - r + vel[0], y - r + vel[1], x + r + vel[0],
                    y + r + vel[1])
    root.after(50, move_balls)
    def measure_collapse(self):
        """Colapses the System into one basis state depending on amplitudes in stateVector
        Works exactly the same as measure(self), but doesn't leave the register intact.
        Built for added realism

        Returns
        -------
        f-string
            the string representation of the selected basis state.
        """
        ## "Uncertainty" is simulated using a Monte-Carlo like approach.
        r = rnd() #random number, uniform probability from 0 to 1
        sum = 0
        for i in range(self.qR.d):  # for i in range (number of states)
            amp = self.stateVector[i] #get the amplitude of the state
            sum += amp.real**2 + amp.imag**2  #find the probability of it occuring and add it to sum
            if r <= sum: #if r is in the interval (sum, sum+prob(state)) then "colapse" system to state
                self.stateVector = np.zeros(self.qR.d)
                self.stateVector[i] = 1
                return (f"{self.qbitVector[i]}")
Example #51
0
    def move(self):
        """
        Randomly moves the ball in dependence of walls
        """
        if self.x > 790 - self.r:
            self.v = -self.v
            self.x -= 10
        if self.x < self.r + 10:
            self.v = -self.v
            self.x += 10
        if self.y > 320 - self.r:
            self.v = -self.v
            self.y -= 10
        if self.y < self.r + 10:
            self.v = -self.v
            self.y += 10

        self.angle += rnd(-15, 15) / 100
        self.x += self.v * math.cos(self.angle)
        self.y += self.v * math.sin(self.angle)
Example #52
0
    def fire2_end(self, event):
        """Выстрел мячом.

        Происходит при отпускании кнопки мыши.
        Начальные значения компонент скорости мяча vx и vy зависят от положения мыши.
        """
        global balls, bullet
        bullet += 1
        coin_flip = rnd(0, 2)
        if coin_flip == 0:
            new_ball = Ball()
        else:
            new_ball = Sting()
        new_ball.r += 5
        self.an = math.atan((event.y - new_ball.y) / (event.x - new_ball.x))
        new_ball.vx = self.f2_power * math.cos(self.an)
        new_ball.vy = -self.f2_power * math.sin(self.an)
        balls += [new_ball]
        self.f2_on = 0
        self.f2_power = 10
Example #53
0
def brain(numb):
    """responsible for calculation an object trajectory"""
    """BE CAREFUL!"""
    """don't use supfunctions and not supfunctions for the same object"""
    if x[numb] > 700 or x[numb] < 100:
        dirx[numb] *= rnd(1, 10) / (-5)

    if y[numb] > 500 or y[numb] < 100:
        diry[numb] *= -1

    x[numb] += V * dT / T * dirx[numb]
    y[numb] += V * dT / T * diry[numb]

    canv.create_oval(x[numb] - r[numb],
                     y[numb] - r[numb],
                     x[numb] + r[numb],
                     y[numb] + r[numb],
                     fill=color[numb],
                     width=0)
    canv.create_text(100, 100, text=i, justify=CENTER, font="Verdana 100")
Example #54
0
    def new_target(self):
        """ Инициализация новой цели. """
        x = self.x = rnd(600, 750)
        y = self.y = rnd(200, 500)
        r = self.r = rnd(5, 50)

        self.v_x = rnd(-3, 2) / 2
        self.v_y = rnd(-3, 2) / 2

        self.live = rnd(1, 5)

        color = self.color = ['green', 'green', 'yellow', 'orange',
                              'red'][self.live]
        canv.coords(self.id, x - r, y - r, x + r, y + r)
        canv.itemconfig(self.id, fill=color)
Example #55
0
def aiChoose(plyChoice):
    sys.stdout.write("\n The AI is choosing, please wait")
    sys.stdout.flush()
    rpsglobals.typewrite("...")
    time.sleep(0.4)
    sys.stdout.flush()

    aiChoice = rnd(rpsglobals.choices, weights=weights, k=1)
    aiChoice = aiChoice[0]

    if plyChoice == aiChoice:
        redoWeights(plyChoice)

        sys.stdout.write("\r The AI chooses " + aiChoice +
                         "! The score remains the same. (" +
                         str(scores["ai"]) + " - " + str(scores["ply"]) + ")")
        sys.stdout.flush()
    elif plyChoice != rpsglobals.opps[aiChoice]:
        redoWeights(plyChoice)

        scores["ai"] += 1
        sys.stdout.write("\r The AI chooses " + aiChoice +
                         "! The AI has gained 1 point. (" + str(scores["ai"]) +
                         " - " + str(scores["ply"]) + ")")
        sys.stdout.flush()
    else:
        redoWeights(plyChoice)

        scores["ply"] += 1
        sys.stdout.write("\r The AI chooses " + aiChoice +
                         "! You have gained 1 point. (" + str(scores["ai"]) +
                         " - " + str(scores["ply"]) + ")")
        sys.stdout.flush()

    print(weights, rpsglobals.choices)

    time.sleep(0.5)
    ans = input("\n \n  > ")
    ans = ans.lower()
    if rpsglobals.processInput(ans):
        aiChoose(ans)
Example #56
0
 def change(self):
     """Замена мишеней"""
     if not self.pause:
         canv.delete(self.list_of_bolls[0].d_boll)
         self.list_of_bolls[0].alive = 0
         for i in range(4):
             self.list_of_bolls[i] = self.list_of_bolls[i+1]
         self.list_of_bolls[4] = boll(rnd(100, 400) / 10, rnd(100, 700), rnd(100, 500), choice(colours), rnd(1000, 7000) / 1000, rnd(0, 1001) / 1000 * 2 * pi)
         canv.delete(self.list_of_not_bolls[0].d_not_boll)
         self.list_of_not_bolls[0].alive = 0
         for i in range(2):
             self.list_of_not_bolls[i] = self.list_of_not_bolls[i+1]
         self.list_of_not_bolls[2] = not_boll(rnd(100, 400)/10, rnd(100, 700), rnd(100, 500), choice(colours), rnd(1000, 7000) / 1000, rnd(0, 1001) / 1000 * 2 * pi)
     if not self.finished:
         root.after(2000, self.change)
Example #57
0
    def move(self):

        global points, id_points

        if self.type == 'bomb':
            self.vx = (g1.x - self.x) / 100
            self.vy = (100 - self.y) / 100
            if abs(self.x - g1.x) < 10 and not self.b:
                self.b = bomb(self.x, self.y)

        if self.b:
            self.b.move()
            if self.b.y > 550:
                self.b = None
            elif self.b.blown:
                print(self.b.x, self.b.y)
                points -= 2
                canv.itemconfig(id_points, text=points)
                self.b = None

        x = self.x = self.x + self.vx
        if self.x > 780:
            self.vx = -self.vx
            x = self.x = 779
        if self.x < 0:
            self.vx = -self.vx
            x = self.x = 1

        y = self.y = self.y + self.vy
        if self.y > 550:
            self.vy = -self.vy
            y = self.y = 549
        if self.y < 0:
            self.vy = -self.vy
            y = self.y = 1
        d = rnd(-2, 2)
        if self.type == 'hor':
            self.vx -= d
        if self.type == 'vert':
            self.vy += d
        canv.coords(self.id, x - self.r, y - self.r, x + self.r, y + self.r)
Example #58
0
    def selectAbasedonQ(self, S, ants):
        directions = ["n", "e","s","w"]
        shuffle(directions)
        action_Qsa = []
        for direction in directions:
            next_S = self.getNextState(S, direction, ants)
            value = self.Q_sa.get((direction, next_S), 0.0) + self.returnValueState(next_S, ants)
            action_Qsa.append((direction, value))

        action_value_pairs = sorted(action_Qsa, key = lambda k: -k[1])
        
        best_action = action_value_pairs[0][0]
        other_actions = [x[0] for x in action_value_pairs[1:]]
        
        random_prob = rnd()

        if random_prob <= 1.0 - self.greedy:
            return best_action
        else:
            shuffle(other_actions)
            return other_actions[0] 
    def __init__(self):
        global H, W
        self.col = colors[random.randint(0, 4)]
        self.x = rnd(100, W - 100)
        self.y = rnd(100, H - 100)
        self.r = rnd(30, 50)
        self.dx = (rnd(-1, 1) * 1)
        self.dy = (rnd(-1, 1) * 1)

        for ball in balls:
            while (2 * (ball.r + self.r)
                   )**2 >= (ball.x - self.x)**2 + (ball.y - self.y)**2:
                self.x = rnd(100, W - 100)
                self.y = rnd(100, H - 100)
        self.obj = canvas.create_oval(self.x - self.r,
                                      self.y - self.r,
                                      self.x + self.r,
                                      self.y + self.r,
                                      fill=self.col)
Example #60
0
 def __init__(self, x=40, y=450):
     """ Конструктор класса ball
     Args:
     x - начальное положение мяча по горизонтали
     y - начальное положение мяча по вертикали
     """
     self.delete = 0
     self.delete_point = 0.7  # Нужна, чтобы пули и пулемета удалялись быстрее.
     self.x = x
     self.y = y
     self.r = 10
     self.vx = 0
     self.vy = 0
     self.g = 0.18  # Ускорение свободного падения.
     self.color = choice(['blue', 'green', 'red', 'brown'])
     self.id = canv.create_oval(self.x - self.r,
                                self.y - self.r,
                                self.x + self.r,
                                self.y + self.r,
                                fill=self.color)
     self.live = rnd(1, 10)