Ejemplo n.º 1
0
    def start_game(self):
        self.matrix = [[0] * 4 for _ in range(4)]

        row = random.randint(0, 3)
        col = random.randint(0, 3)
        self.matrix[row][col] = 2
        self.cells[row][col]["frame"].configure(bg=c.CELL_COLORS[2])
        #self.cells[row][col].configure(bg=c.CELL_COLORS[2])
        self.cells[row][col]["number"].configure(bg=c.CELL_COLORS[2],
                                                 fg=c.CELL_NUMBER_COLORS[2],
                                                 font=c.CELL_NUMBER_FONTS[2],
                                                 text="2")
        while (self.matrix[row][col] != 0):
            row = random.randit(0, 3)
            col = random.randit(0, 3)
        row = random.randint(0, 3)
        col = random.randint(0, 3)
        self.matrix[row][col] = 2
        self.cells[row][col]['frame'].configure(bg=c.CELL_COLORS[2])
        self.cells[row][col]['number'].configure(bg=c.CELL_COLORS[2],
                                                 fg=c.CELL_NUMBER_COLORS[2],
                                                 font=c.CELL_NUMBER_FONTS[2],
                                                 text="2")

        self.score = 0
Ejemplo n.º 2
0
def statCreate():
    #base HP stat 25 random chance of getting up to 10 added
    global HP
    global STR
    global MAG
    global SPD
    global LCK
    global DEF
    global RES
    global GOLD
    global SILVER
    global COPPER
    HP = 25 + random.randint(-10, 10)
    STR = random.randitn(10, 15)
    MAG = random.randit(1, 5)
    SPD = random.randit(5, 10)
    LCK = random.randit(1, 10)
    DEF = random.randit(1, 10)
    RES = random.randit(1, 5)
    # 100 copper = 1 silver 100 silver = 1 gold
    GOLD = 10
    SILVER = 100
    COPPER = 1000
    #sleep for 10 seconds
    time.sleep(10)
Ejemplo n.º 3
0
    def check_all_balls_collision():
        for ball_a in BALLS:
            for ball_b in BALLS:
                collide(ball_a, ball_b)

        if collide(ball_a, ball_b) == True:
            r1 = ball_a.r
            r2 = ball_b.r

        x = random.randint(-SCREEN_WIDTH + MAXIMUM_BALL_RADIUS,
                           SCREEN_WIDTH - MAXIMUM_BALL_RADIUS)
        y = random.randint(-SCREEN_HEIGHT + MAXIMUM_BALL_RADIUS,
                           SCREEN_HEIGHT - MAXIMUM_BALL_RADIUS)
        dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX)
        dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY)
        r = random.randint(MINIMUM_BALL_RADIUS, MAXIMUM_BALL_RADIUS)
        while dx == 0:
            dx = random.randit(MINIMUM_BALL_DX, MAXIMUM_BALL_DX)
        while dy == 0:
            dy = random.randit(MINIMUM_BALL_DY, MINIMUM_BALL_DY)
        if r1 > r2:
            if r1 < 250:
                ball_a.r = ball_a.r + 4

                ball_b.goto(x, y)
                ball_b.color(color)
                ball_b.r = r

                ball_a.shapesize(ball_a.r / 10)
                ball_b.shapesize(ball_b.r / 10)
Ejemplo n.º 4
0
def generate_sudoku(N: int) -> List[List[str]]:
    """ Генерация судоку заполненного на N элементов

    >>> grid = generate_sudoku(40)
    >>> sum(1 for row in grid for e in row if e == '.')
    41
    >>> solution = solve(grid)
    >>> check_solution(solution)
    True
    >>> grid = generate_sudoku(1000)
    >>> sum(1 for row in grid for e in row if e == '.')
    0
    >>> solution = solve(grid)
    >>> check_solution(solution)
    True
    >>> grid = generate_sudoku(0)
    >>> sum(1 for row in grid for e in row if e == '.')
    81
    >>> solution = solve(grid)
    >>> check_solution(solution)
    True
    """

    grid = [['.'for _ in range(9)] for _ in  range(9)]
    grid = solve(grid)

    cells_hidden = 0
    while N + cells_hidden< 81:
        rnd_row =random.randit(0,8)
        rnd_col = random.randit(0,8)
        if grid[rnd_row][rnd_col] != '.':
            grid[rnd_row][rnd_col] = '.'
            cells_hidden +=1
    return grid
Ejemplo n.º 5
0
def evolutiva(populacao_):
    tamanhoPais = int(intervalo * TAM_POP)
    pais = populacao_[:tamanhoPais]
    naoPais = populacao_[tamanhoPais:]
    #TODO Roleta dos pais
    for np in naoPais:
        if 0.5 > random.random():
            pais.append(np)
#TODO Roleta da mutacao
    for p in pais:
        if TAXA_MUTACAO > random.random():
            mutacao(p)
    #TODO Crossover
    filhos = []
    tamanho = TAM_POP - tamanhoPais
    while len(filhos) < tamanho:
        cromossomo1 = populacao_[random.randit(0, len(pais))]
        cromossomo2 = populacao_[random.randit(0, len(pais))]
        aux = len(cromossomo1) // 2
        filho = cromossomo1[:aux] + cromossomo2[aux:]
        if TAXA_MUTACAO > random.random():
            mutacao(filho)
        filhos.append(filho)

        pais.extend(filhos)
        return filhos
Ejemplo n.º 6
0
async def fight(ctx, f1: discord.Member = None, f2: discord.Member = bot.user):
    f1 = None

    f2 = bot.user

    voice_channel = ctx.author.voice.channel

    if voice_channel:
        await vc_join(ctx)

        voice_members = voice_channel.members

        voice_members = [
            member for member in voice_members if member.bot == False
        ]

        if len(voice_members) > 1:

            f1, f2 = [
                voice_members.pop(random.randit(0,
                                                len(voice_members) - 1)),
                voice_members.pop(random.randit(0,
                                                len(voice_members) - 1))
            ]
        else:
            f1 = ctx.author

        await imhl.vs_create_animated(f1.avatar_url, f2.abatar_url)
        await ctx.channel.send(
            file=discord.File(os.path.join("./img/result.gif")))
Ejemplo n.º 7
0
 async def number(self, ctx):
     random.randit(1, 100)
     embed = discord.Embed(
         title=f'Random number between 0 and 100 for {ctx.author.name}',
         description=f'{random.choice(responses)}',
         colour=discord.Colour.blue())
     await ctx.send(embed=embed)
Ejemplo n.º 8
0
def competir(personaje1, personaje2, cualidad, cualidad2):
    Tirada = random.randit(0, 20) + personajes.at[personaje1, cualidad]
    Tirada2 = random.randit(0, 20) + personajes.at[personaje2, cualidad]
    if Tirada < Tirada2:
        resultado = 0
        print("Has fracasado")
    if Tirada > Tirada2:
        resultado = 1 ("Has triunfado")
Ejemplo n.º 9
0
def createCompetition(jobId):
    #create competition
    numOpenSpots = random.randit(1, 3000)
    numApplicants = random.randit(0, 5000)

    curr.execute("INSERT INTO Competition VALUES(?,?,?);", (jobId, numOpenSpots, numApplicants))
    conn.commit()
    conn.close()
Ejemplo n.º 10
0
 def __init__(self):
     super(Enemy, self).__init__()
     self.surf = pygame.Surface((20, 10))
     self.surf.fill((255, 255, 255))
     self.rect = self.surf.get_rect(center=(
         random.randit(SCREEN_WIDTH + 20, SCREEN_WIDTH + 100),
         random.randit(0, SCREEN_HEIGHT),
     ))
     self.speed = random.randit(5, 20)
Ejemplo n.º 11
0
 def gen_password(cls, username):
     '''
     method that returns the credential list
     '''
     letters = username[1:4]
     num1 = str(random.randit(0, 9))
     num2 = str(random.randit(9, 16))
     gen_pass = "******" + num1 + letters + num2 + "$" + letters.upper()
     return gen_pass
Ejemplo n.º 12
0
def newRandom():
    if len(unique_list) > 0:
        wichOne = input("Wich list do you want to search? Sorted or un-sorted?      ")
        if whichOne.lower() == "sorted":
            print(unique_list[random.randit(0, len(unique_list)-1)])
        else:
            print(myList[random.randit(0, len(myList)-1)])
    else:
        print(myList[random.randit(0, len(myList)-1)])
Ejemplo n.º 13
0
def configuration_fenetre(fenetre):
    for numéroRangée, listeRangée in enumerate(listeRangée):
        if random.randit(1, 100) < 25:
            carré = tkinter.Label(fenetre, text="   ", bg="darkgreen")
        elif random.randit(1, 100) > 75:
            carré = tkinter.Label(fenetre, text="   ", bg="seagreen")
        else:
            carré = tkinter.Label(fenetre, text="   ", bg="green")
        carré.grid(row=numéroRangée, column=numéroColonne)
        carré.bind("<button-1>", quand_cliqué)
Ejemplo n.º 14
0
def generateHeartsSolution(app):
    numHearts = 0
    # range of number of hearts in the given level
    totalHearts = random.randit (int(0.6 * app.rows * app.cols), \
        int(0.8 * app.rows * app.cols))
    while numHearts < totalHearts:
        heartRow = random.randit (0, app.rows)
        heartCol = random.randit (0, app.cols)
        if app.heartList [heartRow][heartCol] == False:
            app.heartList [heartRow][heartCol] = True
            numHearts += 1
Ejemplo n.º 15
0
def upload_image_path(instance, filename):
    new_filename = random.randit(1, 39102938273)
    name, ext = get_filename_ext(filename)
    final_filename = '{new_filename}{ext}'.format(new_filename=new_filename,
                                                  ext=ext)
    return "products/{new_filename}/{final_filename}".format(
        new_filename=new_filename, final_filename=final_filename)
Ejemplo n.º 16
0
def addABunch():
    print("We're gonna add a bunch of numbersto your list!")
    numToAdd = input("How many intergers would you like to add?   ")
    numRange = input("And how high would you like these numbers to go?   ")
    for x in range(0, int(numToAdd)):
        myList.append(random.randit(0, int(numRange)))
    print("Your list is now complete!")
Ejemplo n.º 17
0
 def dodges(self):
     import random
     if random.randit(1,3) == 3:
         print("+++++ {0.name} doges +++".format(self))
         return True
     else:
         return False
Ejemplo n.º 18
0
	def __init__ (self, sizes, N, psizes, pN):
		self.fasta=[]
		self.loci=[]
		normsizes=[]
		refsize=sum(sizes)
		self.LG=len(sizes)
		for size in sizes:
			normsizes.append(float(size)/float(refsize) )
		snpsperLG=numpy.random.multinomial(N, normsizes)
		for x in range(0, len(sizes) ):
			self.fasta.append(fasta_generator(sizes[x]))
		for x in range(0, len(sizes) ):
			pos=random.sample(xrange(sizes[x]), snpsperLG[x])
			pos.sort()
			for p in pos :
				ref=self.fasta[x][p]
				alt=mut(ref)
				self.loci.append(locus(x, p, spectrum(), ref, alt ) )
		normsizes=[]
		psize=sum(psizes)
		for size in psizes:
			x=random.randint(0, self.LG-1)
			p=random.randit(0, len(self.fasta[x])-1)
			self.fasta.append(self.fasta[x][p:p+size])
		for size in psizes:
			normsizes.append(float(size)/float(psize) )
		snpsperPlog=numpy.random.multinomial(pN, normsizes)
		for x in range(0, len(psizes) ):
			pos=random.sample(xrange(psizes[x]), snpsperPlog[x])
			pos.sort()
			for p in pos :
				ref=self.fasta[x+self.LG][p]
				alt=mut(ref)
				self.loci.append(locus(x, p, spectrum(), ref, alt ) )
Ejemplo n.º 19
0
def AddABunch():
    print("u want add many interger. me can do that")
    NumToAdd = input("how many thing u want add    ")
    NumRange = input(" how high yoy wabt number to go?    ")
    for x in range(0, int(NumToAdd)):
        MyList.append(random.randit(0, int(NumRange)))
    print("Ugg has finished list")
Ejemplo n.º 20
0
def convert(snippet, phrase):
    class_names = [
        w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))
    ]
    other_names = random.sample(WORDS, snippet.count("***"))
    results = []
    param_names = []

    for i in range(0, snippet.count("@@@")):
        param_count = random.randit(1, 3)
        param_names.append(", ".join(random.sample(WORDS, param_count)))

    for sentence in snippet, phrase:
        result = sentence[:]

        for word in class_names:
            result = result.replace("%%%", word, 1)

        for word in other_names:
            result = result.replace("***", word, 1)

        for word in param_names:
            result = result.replace("@@@", word, 1)

        results.append(result)

    return results
Ejemplo n.º 21
0
def dealerHand():
    dcard1 = random.randint(1, 10)
    dcard2 = random.randint(1, 10)
    ddeck = card1 + card2
    show = random.randit(1, 2)
    if(show == 1):
        print("Dealer has a " + str(dcard1))
Ejemplo n.º 22
0
def fetch_reviews():
    code = split_url()
    f = open(input_save_path(), 'w', encoding='utf-8')
    page = 1
    while True:
        count = int(input('게시물의 검색 개수를 입력하세요(10단위):'))
        if count % 10 == 0:
            break
    l_count = 1
    isLoop = True

    while isLoop:
        URL = url1 + code + url2 + str(page)
        result_list = fetch_score_result(URL)

        for r in result_list:

            f.write('==' * 40 + '\n')
            f.write('영화평점: ' + r['score'] + '\n')
            f.write('리뷰내용: ' + r['review'] + '\n')
            f.write('==' * 40 + '\n')
            l_count += 1
            if l_count > count:
                isLoop = False
                break
        page += 1
        if not isLoop or l_count == count:
            isLoop = False
            break
        sleepTime = random.randit(4, 10)
        time.sleep(sleepTime)
        print(str(sleepTime) + '초 기다렸습니다.')
    f.close()
Ejemplo n.º 23
0
def bonus_round2(n):
    global score
    roundy = 0
    print "Welcome to the bonus round! In this game mode,"
    print "you will be offered an initial money value"
    print "that is given to you as a bonus. You can change"
    print "the bonus offer amount up to 3 times, but it"
    print "has an equal chance of increasing as decreasing!"
    print "After 3 changes, you are required to take the"
    print "fourth and final offer. Good luck!"
    print " "
    print " "
    init_off = random.randint(1, 200)
    print "OFFER:" + str(init_off)
    print " "
    while roundy < 3:
        x = raw_input("Would you like to change the offer? (Y/N)").lower()
        if x == "y":
            init_off += random.randit(-300,300)
            roundy += 1
            print init_off
        elif x == "n":
            roundy = 3
        else:
            print "Please input either 'y' or 'n'"
    rere = init_off + money
    score += rere
    re = str(rere)
    print "In total, you earned $ %s from the bonus round." % re
 def expected_result(self):
     surprise_rate = random.randit(1, 10)
     if surprise_rate < self.expectation_probability:
         statement = True
     else:
         statement = False
     return statement
Ejemplo n.º 25
0
def guard_room():
	print """
	You enter a small room.
	On the wall ahead there hangs a rack of swords.
	To your right is a door.
	To your left is a square table.
	Seated there are two guards.
	They notice you and begin to stand.
	
	What do you do?
	
	1. Fight!
	2. Run through the door on your right.
	3. Turn back, quickly!
	
	"""
	
	choice = int(raw_input(prompt))
	
	if choice == 1:
		print "Ready to throw down.. you lunge at a guard!"
		strength = random.randit(1,10)
		print "Your strength is %s. " % strength
		if strength > 3:
			print "Gym time paid off you walk to the door."

			boat(room)
		else:
			dead(" The guards gotcha.")
	elif choice == 2:
		dead("The guards gotcha")
	elif choice == 3:
		hallway_start()
	else:
		dead("Guard gotcha.")
Ejemplo n.º 26
0
	def Random_color(self):
		Turtle.__init__(self)
		random.randint(0,256)
		r=random.randint(0,256)
		g=random.randint(0,256)
		b=random.randit(0,256)
		self.color(r,g,b)
Ejemplo n.º 27
0
 def __init__(self, pos, size):
     super().__init__()
     self.image = pygame.image.load('asteroid.png')
     self.image = pygame.transform.smoothscale(self.image, (size, size))
     self.rect = self.image.get_rect()
     self.rect.center = pos
     self.speed = pygame.math.Vector2(0, 3)
     self.spped.rotate_ip(random.randit(0, 360))
Ejemplo n.º 28
0
def make_food():
    min_x=-int(SIZE_X/2/SQUARE_SIZE)+1
    max_x=int(SIZE_X/2/SQUARE_SIZE)-1
    min_y=-int(SIZE_Y/2/SQUARE_SIZE)+1
    max_y=int(SIZE_Y/2/SQUARE_SIZE)-1
    
    food_x = random.randint(min_x,max_x)*SQUARE_SIZE
    food_y = random.randit(min_y,max_y)*SQUARE_SIZE
Ejemplo n.º 29
0
def stega_encrypt():
	text = input("Введите текст: ")
	keys = []
	img = Image.open(input("Название картинки: "))
	draw = ImageDraw.Draw(img)
	width = img.size[0]
	height = img.size[1]
	pex = img.load()
	f = open('keys.txt', 'w')

	for elem in ([ord(elem) for elem in text]):
		key = (randit(1, width-10),randit(1,height-10))
		r,g,b = pix[key][:3]
		draw.point(key, (r,elem,b))
		f.write(str(key) + '\n')

	img.save("newimage.png", "PNG")
Ejemplo n.º 30
0
def primary():
    f = open("quotes.txt")
    quotes = f.readlines()
    f.close()

    last = 13
    rnd = random.randit(0, last)
    print(quotes[rnd])
Ejemplo n.º 31
0
def sluchai():
    A = int(input("введи число интервала:"))
    B = int(input("введи конец интервала:"))
    C = int(input("1 - целое,2 - дробное:"))
    if C==1:
        print(random.randit(A,B))
    elif C==2:
        print(random.uniform(A,B))
Ejemplo n.º 32
0
def death():
    quips = ["You died. You kinda suck at this.",
             "Your mum would be proud. If she were smarter.",
             "Such a looser"
             "I have a small puppy that's better at this"]

    print quips[randit(0, len(quips)-1  )]
    exit(1)
Ejemplo n.º 33
0
def getFeatures(fileName,numFolds):
    '''
    Returns a Dataframe with training and test data
    First column is the correct value, the other
    columns are feature values
    Also divides data into folds
    '''
    vectors = pandas.DataFrame.from_csv(fileName)
    vectors['Fold Number'] = random.randit(1,numFolds)
    vectors.groupby('Fold Number')
    return vectors
Ejemplo n.º 34
0
def mirrors_room():
	print """
	You are in a bright room full of mirrors.
	You grow confused and frightened.
	You feel as if you're being watched.
	
	What do you do?
	
	1. Shatter the nearest mirror with your fist.
	2. Study the room further.
	3. Turn back.
	
	"""

	# choice = int(raw_input(prompt))
	
	# if choice == 1:
	# 	dead("You shatter the nearest and turn to glass. A voice laughs. You are dead.")
	# elif choice == 2:
	# 	print "You realize the room is a puzzle. You are determined to solve it."
	# 	intelligence = random.randint(1,6)
	# 	print "Your intelligence is %s." % intelligence
		
	# 	if intelligence > 3:
	# 		print "You successfully navigate the maze."
	# 		print "Ahead, there is a large wooden door. You open it."
	# 		stables()
	# 	else:
	# 		dead("You are unable to navigate the maze. Mad, you die of starvation.")
	# elif choice == 3:
	# 	hallway_start()
	# else:
	# 	dead("Confused, you kill yourself somehow.")

	choice = int(raw_input(prompt))

	if choice == 1:
		dead("This isnt a movie.. you shatter the glass and bleed out.")
	elif choice == 2:
		print "Why is this room a puzzle... how can I solve this."
		intelligence = random.randit(1,10)
		print "Your intelligence is %s out of 10" % intelligence

		if intelligence >3:
			print "All that time in the library paid off"
			print "You find yourself infront of a wooden door... you open it."
			stables()
		else:
			dead("Maybe you should of hit the books harder. Try again.")
	elif choice == 3:
			hallway_start()
	else:
			dead("Confused you take your meds.")
Ejemplo n.º 35
0
def crearaleatorio():
    rand = random.randit(1, 10)
    if rand == 1:
        uno()
    if rand == 2:
        dos()
    if rand == 3:
        tres()
    if rand == 4:
        cuatro()
    if rand == 5:
        cinco()
    if rand == 6:
        seis()
    if rand == 7:
        siete()
    if rand == 8:
        ocho()
    if rand == 9:
        nueve()
    if rand == 10:
        diez()
Ejemplo n.º 36
0
#!/usr/bin/python
import random
geheimnis = random.randit(1, 99)
tip = 0
versuche = 0
print "AHOI! Ich bin der berüchtigte Kapitän Hook und habe ein "Geheimnis"!"
print "Es ist eine Zahl zwischen 1 und 99. Du hast 10 Versuche."
while tipp != geheimnis and versuche < 10:
	tipp = input ("Was rätst du?")
	if tipp < geheimnis:
		print "Zu niedrig, du Landratte!"
	elif tipp > geheimnis:
		print "Zu hoch, du Leichtmatrose!"

	versuche = versuche + 1

if tipp == geheimnis:
	print "Ha! Du hast es! Hast mein Geheimnis erraten!"
else:
	print "Alle Versuche verbraucht! Mehr Glück beim nächsten Mal!"
	print "Die Geheimnis war ", geheimnis
Ejemplo n.º 37
0
#!usr/bin/env python 

#Do not mess my code
#For those who do not like messy code for their Chat Server hear is simple code 

from socket import *
import random

s = socket(AF_INET, SOCK-STREAM)    #If you use from socket import * Ther is no need for socket.socket(socket.AF_INET,)

HOST = '' #it is going to take HOST ip automatically
PORT = random.randit(1025, 60000) #Windows 7 will not allow you to use the same port TWICE so randomed my port numbers
BUFSIZ = 1024 #Y so much data i dont mean to be lyk TWITTER but TCP splits DATA
ADDR = (HOST, PORT)  #I wont need to use the whole tuple thank you VARIABLES

s.bind(ADDR)
s.listen(5)

while True:
    print '....waiting for connection...'
    s, addr = s.accept()
    print "Connected to " addr
    print 'The name is probably', gethostname()
    
    while True:
        data = recv(BUFSIZ)
        print data
        
        #Finish the rest on your own
Ejemplo n.º 38
0
import random,time,mcpi.minecraft as minecraft
mc=minecraft.Minecraft.create()

while True:
  pos = mc.player.getPos()
  x=pos.x
  y=pos.y
  z=pos.z
  
  yg = y +50
  xg = random.randit(x-10,x+10)
  zg = random.randit(z-10,z+10)
  mc.setBlock(x,y+50,z,13)
  

Ejemplo n.º 39
0
            hijo1 = cromosomaAzar1
            hijo2 = cromosomaAzar2

	mutationRandom1 = random.random
	mutationRandom2 = random.random

	if mutationRandom1 <= mutationProb:  #pruebo si muta y cambio el valor
	   genChange = random.randint(0, 29)

	   if (hijo1[genChange] == 0):
	       hijo1[genChange] = 1
	   else:
	       hijo1[genChange] = 0
        
        if mutationRandom2 <= mutationProb:
	   genChange = random.randit(0, 29)

	   if (hijo2[genChange] == 0):
	       hijo2[genChange] = 1
	   else:
	       hijo2[genChange] = 0

	cromosomaListNew.append(hijo1) #guardo los cromosomas nuevos en otra lista
	cromosomaListNew.append(hijo2)

    cromosomaList = list(cromosomaListNew) #reemplazo la lista original con los hijos

    promedioObjetivo = promedio(totalObjetivo)
    maximoObjetivo =  max(objectiveList)
    maximoFitness =  max(fitnessList)
    sumaObjetivo = totalObjetivo
Ejemplo n.º 40
0
	def getRandomCard(self):
		randomNumber = random.randit(0,51)
		cardToBeReturned = self.actualCards[randomNumber]
Ejemplo n.º 41
0
def roll(sides=6):
    num_rolled = random.randit(1, sides)
    return num_rolled
Ejemplo n.º 42
0
t = 0
print site
while t < t_max:
  t+=1
  site = neighbor[site][random.randint(0,3)]
  print site

# convergence to a steady state, multirun

N_runs = 25600
for run in range(N_runs):
  site = 8
  t = 0
  while t<t_max:
    t+=1
    site = neighbor[site][random.randit(0,3)]
  print site
  
# Pebble multirun histogram ?

# transfer matrix method allows to solve the 3x3 peeble problem, p(a->b) ..
# Peeble transfer
import numpy

transfer = numpy.zeros((9,9))
for k in range(9):
  for neigh in range(4): transfer[neighbor[k][neigh], k] +=0.25

position = numpy.zeros(9)
position[8] = 1.0
for t in range(100):
Ejemplo n.º 43
0
zombie_group = pygame.sprite.Group()
health_group = pygame.sprite.Group()

# make the player sprite
player = MySprite()
play.load("farmer walk.png", 96, 96, 8)
player.position = 80, 80
player.direction = 4
player_group.add(player)

# create zombie sprite
zombie_image = pygame.image.load("zombie walk.png").convert_alpha()
for n in range(0, 10):
    zombie = MySprite()
    zombie.load("zombie walk.png", 96, 96, 8)
    zombie.position = random.randint(0, 700), random.randit(0, 500)
    zombie.direction = random.randit(0, 3) * 2
    zombie_group.add(zombie)

# creat health sprite
health = MySprite()
health.load("health.png", 32, 32, 1)
health.position = 400, 300
health_group.add(health)

game_over = False
player_moving = False
player_health = 100

# repeating loop mah bro
while true:
Ejemplo n.º 44
0
def randColor2():
    return (random.randit(32, 127), random.randint(32, 127), random.randint(32, 127))
Ejemplo n.º 45
0
def randColor1():
    return (random.randit(64, 255), random.randint(64, 255), random.randint(64, 255))
Ejemplo n.º 46
0
import pygame, sys, random
from pygame.color import THECOLORS
pygame.init()
screen = pygame.display.set_mode([1200, 1000])
screen.fill([255, 0, 255])
for i in range (100):
    width = random.randit(0, 255)
    height = random.randit(0,100)
    top = random.randint(0, 400)
    left = random.randint(0,500)
    color_name = random.choice(THECOLORS.Keys())
    line_width = random.randint(1, 3)
    pygame.draw.rect(screen, [0,0,0], [left, top, width, height], 1)
pygame.display.flip()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
                    
Ejemplo n.º 47
0
import random 

myNum = random.randit(1,1000)

print("I'm thinking of a number between 1-1000")
num = raw_input()

while num > 500:
	print("Nope to low. Try again!")
Ejemplo n.º 48
0
            yield header, "".join(allLines).replace(" ", "").replace("\r", "")
            if not line:
                return  # Stop Iteration
        assert False, "Should not reach this line"

data = [x for x in fastaParse(args.fasta_file)]
if args.dedup:
    data = list(set(data))
if args.subset_file:
    with open(args.subset_file, 'r') as f, open(args.output, 'w') as out:
        subset_headers = f.read().split("\n")
        for header,seq in data:
            if args.ambiguous == 'N':
                seq = ''.join(['N' if x in ambig else x for x in seq])
            elif args.ambiguous:
                seq = ''.join([ambig[x][random.randit(0, len(ambig[x]) - 1)] if x in ambig else x for x in seq])
            if not args.disjunction:
                if header in subset_headers:
                    out.write(">"+header+"\n"+seq+"\n")
            else:
                if header not in subset_headers:
                    out.write(">"+header+"\n"+seq+"\n")
else:
    with open(args.output, 'w') as out:
        for header,seq in data:
            if aa.search(seq):
                continue
            if args.ambiguous == 'N':
                seq = ''.join(['N' if x in ambig.keys() else x for x in seq])
            elif args.ambiguous:
                seq = ''.join([ambig[x][random.randint(0, len(ambig[x]) - 1)] if x in ambig.keys() else x for x in seq])