コード例 #1
0
def kmeans(x, y, ndim=2, ncl=5):
    #init the number of centroids and initialize them to random points.
    centr = zs((ncl, ndim))
    minErr = 0.001
    #list of [x,y] pairs.
    for i in range(ncl):
        centr[i][0] = rn(min(x), max(x))
        centr[i][1] = rn(min(y), max(y))
    #centr now contains ncl item list of [x,y] pairs.
    numUpdates = 1
    passes = 0
    running = True
    while running:
        running = False
        print("The centroids after " + str(passes) + " passes: ")
        print(centr)
        passes += 1
        res = centrPass(x, y, centr)
        for i in range(ncl):
            if (abs(centr[i][0] - res[i][0]) + abs(centr[i][0] - res[i][0]) >
                    minErr):
                running = True
                if (res[i][0] == 0 and res[i][1] == 0):
                    centr[i][0] = rn(min(x), max(x))
                    centr[i][1] = rn(min(y), max(y))
                else:
                    centr[i][0] = res[i][0]
                    centr[i][1] = res[i][1]
    print("The centroids after " + str(passes) + " passes: ")
    print(centr)
    return centr
コード例 #2
0
 def main(self,root,**kwargs):
     root.div('Mixed HTML Elements',margin='10px',
                   font_size='24px',text_align='center',
                   color='#888') 
     #we receive a root and we add a div with a content and
     #some attributes.
     
     mybox=root.div(width='400px',margin='auto',
                      padding='10px',
                      border='1px solid silver',rounded='10',
                      margin_top='50px',shadow='4px 4px 8px #666') 
     #we add now to the root a div that has not a content, 
     #just attributes.
     #this div is in a python variable named 'mybox'
     #we can now put some elements in container
                      
     for j in range(96):
         mybox.div(height='15px',width='15px',shadow='2px 2px 3px #666',
                   background_color='rgb(%i,%i,%i)'%(rn(0,255),rn(0,255),rn(0,255)),
                   rounded='10',margin='5px',display='inline-block')
     
     mytable=root.table(margin='auto',margin_top='50px',
                        border_spacing=0,border_collapse='collapse')
     tbody=mytable.tbody(font_size='10px',color='gray')
     for r in range (10):
         row=tbody.tr()
         for c in range (10):
             cell=row.td(padding='2px')
             cell.div('cell<br/>%i-%i'%(r,c),
                       padding_right='6px',padding_left='6px',
                       rounded=4,border='1px solid gray')
コード例 #3
0
ファイル: matrica.py プロジェクト: TAPAKAHOKOT/Matrica_style
def draw_field(stdscr):
    global key
    global coors

    stdscr.clear()
    stdscr.refresh()
    curses.curs_set(0)

    curses.start_color()
    for k in range(255):
        curses.init_pair(k + 1, k, curses.COLOR_BLACK)

    while True:
        stdscr.clear()

        for y in range(17):
            for x in range(70):
                if x in coors[0]:
                    k = coors[0].index(x)
                    posit = coors[1][k]
                    if posit[1] <= y <= posit[0]:
                        if y == posit[0]: color = 85
                        elif y == posit[0] - 1: color = 84
                        elif y == posit[1]: color = 23
                        elif y == posit[1] + 1: color = 29
                        else: color = coors[3][k]

                        if y == posit[0]: letter = str(coors[2][k])[1]
                        else:
                            if rn(0, 1) == 0:
                                letter = chr(
                                    choice([rn(48, 123),
                                            rn(190, 600)]))
                            else:
                                letter = str(coors[2][k])[1]
                        stdscr.addstr(y, x, letter, curses.color_pair(color))
                    else:
                        stdscr.addstr(y, x, " ")
                else:
                    stdscr.addstr(y, x, " ")
        if coors[1] != []:
            n = 0
            for k in range(len(coors[1])):
                coors[1][k - n][0] += 1
                coors[1][k - n][1] += 1

                if coors[1][k - n][1] >= 17:
                    del (coors[0][k - n])
                    del (coors[1][k - n])
                    del (coors[2][k - n])
                    del (coors[3][k - n])

                    n += 1

        stdscr.refresh()
        time.sleep(0.07)
コード例 #4
0
 def velg_aksjon(self, motspiller):
     if len(Spiller.history[motspiller]) < self.number:
         return Action(rn(0, 2))
     sub_sequence = Spiller.history[motspiller][-self.number:]
     frequency = [0, 0, 0]
     for i in range(
             len(Spiller.history[motspiller]) - self.number - 1, 0, -1):
         if Spiller.history[motspiller][i:i + self.number] == sub_sequence:
             frequency[Action.get_index(
                 Spiller.history[motspiller][i + self.number + 1])] += 1
     if max(frequency) == 0:
         return Action(rn(0, 2))
     else:
         return self.best_move(self.moves[frequency.index(max(frequency))])
コード例 #5
0
 def velg_aksjon(self, motspiller):
     if len(Spiller.history[motspiller]) < self.number:
         return Action(rn(0, 2))
     sub_sequence = Spiller.history[motspiller][-self.number:]
     player_history = self.get_player_history(motspiller)
     frequency = [0, 0, 0]
     for i in range(len(player_history) - self.number - 2, 0, -1):
         if Spiller.history[motspiller][i:i + self.number] == sub_sequence:
             move = player_history[i + self.number]
             frequency[move.get_num()] += 1
     if max(frequency) < 1:
         return Action(rn(0, 2))
     else:
         return self.best_move(frequency.index(max(frequency)))
コード例 #6
0
def get_initial_state(params, tau):
    """ Returns a list describing the state, in the form:
		state = [q1,q2,...,qz] where each q is a necessary parameter for 
			describing the generalized position of a specific subsystem:
			q = [[f1^(0),f2^(0),...,fn^(0)],[f1^(1),f2^(1),...fn^(1)],
				  ...,[f1^(m),f2^(m),...fn^(m)]]
		params = system-specific constants. E.g., mass, length, density, etc.
		
		Assume that the particles, initially stretched random distances out of 
		equilibrium, are starting from rest. 
	"""

    # The spring constant,mass, and network dimensions
    kx, ky, m, r0, xlen, ylen = params

    total = xlen * ylen  # number of subsystems

    rx_list, ry_list = total * [0], total * [0]
    vx_list, vy_list = total * [0], total * [0]  # replace later with derivs()
    ax_list, ay_list = total * [0], total * [0]  # replace later with derivs()

    # Build the part of the state which is projected on x
    state_x = []
    for i in range(0, xlen):  # iterate over the columns
        for j in range(0, ylen):  # iterate over the rows
            rx_list[xlen * i +
                    j] = j * r0 + r0 * (rn() - .5)  # the x coord of mass ij
    state_x.append(rx_list)
    state_x.append(vx_list)
    state_x.append(ax_list)

    state_y = []
    for i in range(0, xlen):  # iterate over the columns
        for j in range(0, ylen):  # iterate over the rows
            ry_list[xlen * i +
                    j] = i * r0 + r0 * (rn() - .5)  # the y coord of mass ij
    state_y.append(ry_list)
    state_y.append(vy_list)
    state_y.append(ay_list)

    state = [state_x, state_y]
    # Replace ax_list and ay_list using derivs()
    deriv_list = derivs(state, tau, params)
    state[0][2] = deriv_list[0][1]
    state[1][2] = deriv_list[1][1]
    # print("state: ", state)

    return state
コード例 #7
0
    def GenRandom_10_pass_list(self):
        print()
        thr_digit = str(input('Enter First 3 digit Sequence: '))
        no_of_p = int(input('How Many Password you Need: '))
        is_con_check = str(input('Print the List in Console "yes" or "no : '))

        for x in range(0, int(no_of_p)):
            if is_con_check == 'yes':
                s = ''.join(["%s" % rn(0, 9) for dig in range(0, 7)])
                res = str(thr_digit) + s
                print(res)
            elif is_con_check == 'no':
                s = ''.join(["%s" % rn(0, 9) for dig in range(0, 7)])
                res = str(thr_digit) + s
                with open('pass.txt', 'a') as writer:
                    writer.write(res + '\n')
コード例 #8
0
 def __init__(self):
     self.race_type = "human"
     self.class_type = None
     self.level = 1
     self.sex = ['f', 'm'][rn(0, 1)]
     self.hand = []
     self.in_play = []
コード例 #9
0
ファイル: matrica.py プロジェクト: TAPAKAHOKOT/Matrica_style
def on_press(key_pressed):
    global key
    global coors
    if key_pressed:
        key = str(key_pressed)

        if len(coors[0]) != 70:
            while True:
                pos = rn(0, 70)
                if pos not in coors[0]: break

            colors = [29, 35, 41, 3, 11]
            coors[0].append(pos)
            coors[1].append([0, -rn(1, 17)])
            coors[2].append(key)
            coors[3].append(colors[rn(0, len(colors) - 1)])
コード例 #10
0
def main(n=50, minVal=0, maxVal=9):
    x = zs(n)
    y = zs(n)
    for i in range(n):
        x[i] = rn(minVal, maxVal)
        y[i] = rn(minVal, maxVal)

    centr = kmeans(
        x,
        y,
    )
    c1 = centr[:, 0]
    c2 = centr[:, 1]

    pp.scatter(x, y)
    pp.scatter(c1, c2, c='r', s=100)
    pp.show()
コード例 #11
0
 def draw(self, cards, card_type):
     drawn_cards = []
     if card_type == "door":
         for c in range(cards):
             doors = list(self.doors.keys())
             draw = doors[rn(0, len(doors) - 1)]
             drawn_cards.append(self.doors[draw])
             del self.doors[draw]
             #cards = list(map(lambda card: self.encode(self.doors[rn(0,len(self.doors)-1)]), [i for i in range(cards)]))
     elif card_type == "treasure":
         for c in range(cards):
             treasures = list(self.treasures.keys())
             draw = treasures[rn(0, len(treasures) - 1)]
             drawn_cards.append(self.treasures[draw])
             del self.treasures[draw]
             #cards = list(map(lambda card: self.encode(self.treasures[rn(0,len(self.treasures)-1)]), [i for i in range(cards)]))
     return drawn_cards
コード例 #12
0
def mutation(children, chance):
    chance = rn() * chance
    random_mutation = np.random.choice(a=[0, 1, -1],
                                       size=children.shape,
                                       p=[1 - chance, chance / 2, chance / 2])
    children = children + random_mutation
    children = np.clip(children, -1, 1)
    return children
コード例 #13
0
ファイル: 10_dataFormula.py プロジェクト: genropy/sandbox
 def colorSlider(self,fb,value=None,lbl=None):
     fb.verticalSlider(value,lbl=lbl[0],height='100px',
                       minimium=0,maximum=255,default_value=rn(0,255),
                       discreteValues=256,
                       lbl_background=lbl,
                       lbl_color='white',
                       lbl_padding='1px',
                       lbl_width='15px',
                       intermediateChanges=True)
コード例 #14
0
def main(n):
    s = n // 100 + 4
    fm = FatMaker()
    files = [fm.cycle(1)]
    while fm.size() < n:
        if rn() < 0.1:
            files.append(fm.cycle(rr(1, s)))
        elif rn() < 0.2 or len(files) < 3:
            files.append(fm.alloc(rr(1, 2 * s)))
        else:
            f = files[rr(0, len(files))]
            nf = fm.alloc(rr(0, s), fm.lookup(f, rr(0, s)))
            files.append(nf)
        # print("fm.size=", fm.size())

    # fm.disp()
    fm.shuffle()
    fm.disp()
    return
コード例 #15
0
 def velg_aksjon(self, motspiller):
     if motspiller not in Spiller.history:
         return Action(rn(0,2))
     else:
         player_history = Spiller.history[motspiller]
         stein = player_history.count(Action(0))
         saks = player_history.count(Action(1))
         papir = player_history.count(Action(2))
         frequence = [stein, saks, papir]
         most_common = frequence.index(max(frequence))
         return Action(self.best_move(most_common))
コード例 #16
0
ファイル: frac.py プロジェクト: samorajp/kompresja_fraktalna
def choose(weights):
    colors = ["red", "green", "blue", "yellow",
			  "purple", "pink"]
    sum_weights = sum(weights)
    normalized = [w / sum_weights for w in weights] 
    rand = rn()
    total_weight = 0
    for i, weight in enumerate(normalized):
        total_weight += weight
        if rand < total_weight:
            turtle.color(colors[i])
            return i
コード例 #17
0
ファイル: testgen.py プロジェクト: skrstv123/CP-ALGO
def tf(files = 2):
    qt = {
        1: lambda : [1, rn(1,30)],       
        2: lambda : [2, rn(1,30)],
        3: lambda : [3, rn(1,30)],
        4: lambda : [4 ,rn(1,30) ,rn(1,30)],
    }
    for tf in range(files):
        sys.stdout = open(f'tf{tf}.txt', 'w') 
        tc = rn(1,1000)
        print(tc)
        for i in range(tc):
            x,q = rn(1, 10**9), rn(1, 10**3)
            print(x, q)
            for j in range(q):
                qtn = rn(1, 4)
                print(qtn)
                print(*(qt[qtn]()[1:]))
コード例 #18
0
 def colorSlider(self, fb, value=None, lbl=None):
     fb.verticalSlider(value,
                       lbl=lbl[0],
                       height='100px',
                       minimium=0,
                       maximum=255,
                       default_value=rn(0, 255),
                       discreteValues=256,
                       lbl_background=lbl,
                       lbl_color='white',
                       lbl_padding='1px',
                       lbl_width='15px',
                       intermediateChanges=True)
コード例 #19
0
 def generate(self, n, p=None, safe = True):
     self.nodes = [] #IT RESETS ALL NODES!
     if p == None:
         p = 2*log(n)/n #If n is large enough it's probablly connected
     self.createNodes(n) 
     #TODO use itertools for cleaner code
     for node1 in self.nodes:
         for node2 in self.nodes:
             if node1 != node2:
                 if rn() <= p:
                     createEdge(node1,node2)
     if safe: #When N is small it's extremly recommended to be safe if you want the graph to be connected
         while not self.isConnected():
             self.generate(n, p, False)
コード例 #20
0
def Arbre(longueur=100, steps=1):
    if longueur < 10: return

    t.color(colors[rn(0, len(colors) - 1)])
    t.width(5 / steps)
    t.fd(longueur)
    t.left(45)
    Arbre(longueur * 0.6)
    t.right(90)
    steps += 1
    Arbre(longueur * 0.6, steps)
    t.left(45)
    t.fd(-longueur)
    return
コード例 #21
0
def main():
    """
    Funcion Principal de nuestra app
    :return: None
    """

    # Soporte para guardar nuestro bot
    try:
        chat = np.load('chat.npy').item()
    except:
        chat = {
            'hola': 'hola',
            'como estas': 'bien muchas gracias',
            'de que color es el cielo': 'El cielo es azul',
            'cual es tu pelicula favorita':
            'Mi pelicula favorita es V de venganza'
        }

    print(
        'Hola, soy un bot que responde a tus preguntas, preguntame algo o di adios'
        ' para salir')

    while True:

        # Preguntamos con una de nuestras frases predeterminadas
        n_pregunta = rn(0, len(preguntas) - 1)
        pregunta = limpiar_cadena(input(preguntas[n_pregunta] + ' '))

        # Validamos que el usuario quiera continuar
        if pregunta == 'adios':
            print('Fue divertido\n')
            # Salvamos nuestro diccionario
            np.save('chat.npy', chat)
            break

        # Si sabemos la respuesta respondemos
        elif pregunta in chat:
            print(chat[pregunta])

        # Si no sabemos preguntamos para aprender
        else:
            respuesta = limpiar_cadena(
                input('No se como responder eso.\n '
                      '¿Que debería decir?\n'))
            agregar_al_chat(pregunta, respuesta, chat)
コード例 #22
0
def kushat():
    global golod
    global shram
    print('В животе неприятно урчит.')
    j = input(
        'За дверью не слышно ни Папы, ни Мамы.\n1. Остаться в детской\n2. Пойти приготовить поесть с шансом быть обнаруженным и наказанным\n3.  вещи\n'
    )
    if j == '1':
        detskaya()
    if j == '2':
        _print('С опаской выхожу из комнаты.')
        _print('Мама оставила еду в сковородке.')
        _print('.')
        _print('.')
        _print('.')
        kitch = rn(1, 40)
        if kitch < 23:
            print(
                'Греть еду в сковородке, не будучи способным различить цифры на электроплите, было глупо.\n'
            )
            shram = 1
            golod = 0
            print('|Вы получили шрам.|')
            _print('|И ощущение сытости!|')
            detskaya()
        else:
            print('Уф, даже без боевых ранений!\n')
            shram = 0
            golod = 0
            detskaya()
    if j == '3':
        inv_Nemo()
        kushat()
    else:
        _print('Не понимаю тебя. Можешь повторить?')
        kushat()
コード例 #23
0
def rand_list(length, offset, scale):
    """Returns a scalar list of len 'length' whose elements are random doubles
		centered around the double 'offset', between +/-'scale'/2.
	"""
    return [scale * (rn() - .5) + offset for i in range(0, length)]
コード例 #24
0
import pygame as pg
from random import randint as rn
pg.init()
fps = 60
width = 500
height = 500
clock = pg.time.Clock()
wind = pg.display.set_mode([width, height])
blue = (0, 191, 255)
black = (0, 0, 0)
x = 1
y = 1
while True:
    # a = 1
    # b = 1
    a = rn(1, 5)
    b = rn(1, 5)
    while True:
        wind.fill(black)
        pg.draw.rect(wind, blue, (x, y, 4, 4))
        pg.display.update()
        clock.tick(fps)
        # если задевает правую или нижнюю стенку
        if x >= width or y >= height:
            if x >= width and y <= height:
                b = rn(-5, 5)
                a = rn(-10, -5)
            elif y >= height and x <= width:
                a = rn(-5, 5)
                b = rn(-10, -5)
            elif x >= width and y >= height:
コード例 #25
0
            tahmin.append("  ")

        else:

            len_finish += 1
            tahmin.append(" _ ")

    return tahmin, len_finish


function_count = 0

kelimeler = [
    "hızlı araba", "güzel ev", "batuhan oğulgaymış", "şevki vurduranoğlu"
]
ana_kelime = kelimeler[rn(0, 3)]
cizgi = len(ana_kelime)
game_finish = 0
tahmin, len_finish = __initGame__(ana_kelime)

print("\033[92m")

while True:

    os.system('cls' if os.name == 'nt' else 'clear')
    print_adam(function_count)
    print("\033[1;34m")
    print("  Kelime :  ", end="")

    for i in tahmin:
コード例 #26
0
# This pulls randint, the function you need, directly from random, simplifying usage. Saying as means you don't have
# to type randint each time, just rn.
from random import randint as rn

# This section gathers the input and makes an answer variable
name = input('Enter Name: ')
question = input('Enter question: ')
answer = ''

# This gets the random number
ANSID = rn(1, 9)

answers = ['Yes, definitely', 'It is decidedly so', 'Without a doubt', 'Reply hazy, try again', 'Ask again later', 'Better if I do not tell you now.', 'Outlook not so good', 'My sources say no', 'very doubtful']
answer = answers[ANSID]
# What this does it create a list. This list specifies all answer possibilities. Putting, for example, list 0, would return the value 0. Python counts 0, 1, 2, etc. In this case, putting answers[0] would give you 'Yes, Definitely.'
# This is faster than individual if statements. I accidentally said that elif was else and if. It is not. Use it after the first if. My bad.

"""if ANSID == 1:
    answer = 'Yes, definitely'
if ANSID == 2:
    answer = 'It is decidedly so'
if ANSID == 3:
    answer = 'Without a doubt'
if ANSID == 4:
    answer = 'Reply hazy, try again'
if ANSID == 5:
    answer = 'Ask again later'
if ANSID == 6:
    answer = 'Better if I do not tell you now.'
if ANSID == 7:
    answer = 'Outlook not so good'
コード例 #27
0
ファイル: bbgsim-cv-hatching.py プロジェクト: lispwriter/rblx
 def random_move_key(self):
     keys = ['w', 's', 'a', 'd']
     draw = rn()
     i = int(math.floor(rn() * 10 / len(keys)))
     return (keys[i])
コード例 #28
0
def map(md):

    global mod  # oyunun açık veya gizli modda başlaması kontrolu için
    global gemiler  # gemileri global yaptım çünki tüm sınıfların erişmesi gerek

    mod = md

    while True:

        kontrol = None

        a = rn(0, 100)  # ilk geminin başlangıç noktası

        b = rn(0, 100)  # ikinci geminin başlangıç noktası

        c = rn(0, 100)  # üçüncü geminin başlangıç noktası

        d = rn(0, 100)  # son geminin baslangıç noktası

        # burada random sayı listeden bir elemen seçecek
        rast = [1, 10, -1, -10]

        # seçtiği elemanlar başlangıç noktasından sonra nasıl ilerleneceği belirlenecek (dikey, yatay)

        b1 = rast[rn(0, 3)]

        c1 = rast[rn(0, 3)]

        d1 = rast[rn(0, 3)]

        gemiler = [
            a, [b, b + 1 * b1, b + 2 * b1],
            [c, c + 1 * c1, c + 2 * c1, c + 3 * c1], [d, d + 1 * d1]
        ]  # tüm gemileri listeye ekledim

        if (str(gemiler[1][0])[0] != str(gemiler[1][1])[0]) or (str(
                gemiler[1][1])[0] != str(gemiler[1][2])[0]) and (b1 == 1
                                                                 or b1 == -1):
            # gemiler yataysa bir alt satıra geçmeme kontrolü(yatay gemilerin birleşik olma kontrolü) * dikey gemiler bu kontrole girmez
            continue

        elif ((str(gemiler[2][0])[0] != str(gemiler[2][1])[0]) or
              (str(gemiler[2][1])[0] != str(gemiler[2][2])[0]) or
              (str(gemiler[2][2])[0] != str(gemiler[2][3])[0])) and (c1 == 1 or
                                                                     c1 == -1):
            # gemiler yataysa bir alt satıra geçmeme kontrolü(yatay gemilerin birleşik olma kontrolü) * dikey gemiler bu kontrole girmez
            continue

        elif (str(gemiler[3][0])[0] != str(gemiler[3][1])[0]) and (d1 == 1 or
                                                                   d1 == -1):
            # gemiler yataysa bir alt satıra geçmeme kontrolü(yatay gemilerin birleşik olma kontrolü) * dikey gemiler bu kontrole girmez
            continue

        elif gemiler[0] >= 100 or gemiler[0] < 0:
            # gemilerin başlangıç noktalarından sonraki gelen blokların 0,100 arasında olma kontrolü
            continue

        elif gemiler[1][2] >= 100 or gemiler[1][0] < 0 or gemiler[1][2] < 0:
            # gemilerin başlangıç noktalarından sonraki gelen blokların 0,100 arasında olma kontrolü

            continue

        elif gemiler[2][3] >= 100 or gemiler[2][0] < 0 or gemiler[2][3] < 0:
            # gemilerin başlangıç noktalarından sonraki gelen blokların 0,100 arasında olma kontrolü

            continue

        elif gemiler[3][1] >= 100 or gemiler[3][0] < 0 or gemiler[3][1] < 0:
            # gemilerin başlangıç noktalarından sonraki gelen blokların 0,100 arasında olma kontrolü

            continue

        # aşağıdaki kontrol blokları gemiler çakışıyormu diye kontrol ediyor.
        elif gemiler[0] in gemiler[1]:
            # ilk gemi ikinci gemiyle çakışıyormu

            kontrol = False

        elif gemiler[0] in gemiler[2]:
            # ilk gemi üçüncü gemiyle çakışıyormu

            kontrol = False

        elif gemiler[0] in gemiler[3]:
            # ilk gemi dördüncü gemiyle çakışıyormu

            kontrol = False

        elif gemiler[1][0] in gemiler[2] or gemiler[1][1] in gemiler[
                2] or gemiler[1][2] in gemiler[2]:
            # ikinci gemi üçüncü gemiyle çakışıyormu

            kontrol = False

        elif gemiler[1][0] in gemiler[3] or gemiler[1][1] in gemiler[
                3] or gemiler[1][2] in gemiler[3]:
            # ikinci gemi dördüncü gemiyle çakışıyormu

            kontrol = False

        elif gemiler[3][0] in gemiler[2] or gemiler[3][1] in gemiler[2]:
            # dördüncü gemi ikinci gemiyle çakışıyormu

            kontrol = False

        # eğer hiçbir sorun yoksa gemiler adlı liste yaratılır.

        elif kontrol == None:

            break  # döngüüden çıkılır
コード例 #29
0
from random import randint as rn
m=int(input())-1
a=[rn(-30,30) for _ in range(30)]
print(*a,'\n')
a[a.index(max(a))], a[m] = a[m], a[a.index(max(a))]
print(*a)
コード例 #30
0
 def velg_aksjon(self, opponent):
     return Action(rn(0, 2))
コード例 #31
0
ファイル: backup3.py プロジェクト: jarmonster/Pandemic
            if i.nr == Person.nr:
                i.insert(Person)
                a.pop(a.index(Person))



#creates families
for i in range(0, fams):
    families.append(tp.Family(i))

#Families sorted in such a way that 10% of the pop is comprised of students
familien = [4, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]

#puts people in families
for i in families:
    c = familien[rn(0, len(familien)-1)]
    for j in range(0, c):
        i.insert(tp.Person(False, i.nr, True, False, False, 1000, False))

#creates students in families
for i in families:
    if len(i.room) == 3:
        i.room[0].Student = True
    if len(i.room) == 4:
        i.room[0].Student = True
        i.room[1].Student = True

#puts buildings in city
for i in range(0, buildings):
    city.append(tp.Building())
コード例 #32
0
def draw_field(stdscr):

    # Clear and refresh the screen for a blank canvas
    stdscr.clear()
    stdscr.refresh()
    curses.curs_set(0)

    play = True
    size = [40, 21]
    ship_cors = [ [1, 1], [2, 1] ]
    bullets = []
    enemy_coors = []
    help_coors = []

    score = 0
    chanse = 15
    bullets_num = 50
    health = 3

    # GRAPHICS ===========
    ship = ["H", ">"]
    bullet_skin = "="
    enemy_skin = ["0"]
    help_skin = ["+"]
    # GRAPHICS ===========

    arr = create_field(size)

    # Start colors in curses
    curses.start_color()
    for k in range(255):
        curses.init_pair(k + 1, k, curses.COLOR_BLACK)

    # Loop where k is the last character pressed
    while health > 0:
        # Initialization
        stdscr.clear()

        key = check_move()
        if key:
            if ship_cors[0][1] + key > 0 and ship_cors[0][1] + key < size[1] - 1:
                ship_cors[0][1] +=  key
                ship_cors[1] = [ ship_cors[0][0] + 1, ship_cors[0][1] ]

        for k, bullet in enumerate(bullets): 
            bullets[k] = move_bullet(bullet)
        for k, enemy in enumerate(enemy_coors):
            if enemy not in bullets:
                enemy_coors[k] = [ enemy[0] - 1, enemy[1] ]

        fire = check_fire(ship_cors)
        if bullets_num > 0:
            if fire: bullets.append(fire); bullets_num -= 1

        for k, hel in enumerate(help_coors):
            help_coors[k] = [ hel[0] - 1, hel[1] ]

        if rn(1, chanse) == 1:
            enemy_coors.append([size[0]-1, rn(1, size[1]-2)])

        if rn(1, 150) == 1:
            help_coors.append([ size[0] - 1, rn(1, size[1] - 2)])

        for k in enemy_coors:
            if k[0] < 0:
                health -= 1
                enemy_coors.remove(k)


        if score > 100: chanse = 2
        elif score > 40: chanse = 5
        elif score > 20: chanse = 10

        for y_ind, k in enumerate(arr):
            for x_ind, i in enumerate(k):
                if [x_ind, y_ind] == ship_cors[0]:
                    stdscr.addstr(y_ind, x_ind * 2, ship[0] + " ", curses.color_pair(220))
                elif [x_ind, y_ind] == ship_cors[1]:
                    stdscr.addstr(y_ind, x_ind * 2, ship[1] + " ", curses.color_pair(202))
                elif [x_ind, y_ind] in bullets and [x_ind, y_ind] in enemy_coors:
                    bullets.remove([x_ind, y_ind])
                    enemy_coors.remove([x_ind, y_ind])
                    bullets_num += 3
                    score += 1
                    stdscr.addstr(y_ind, x_ind * 2, "| ", curses.color_pair(229))
                elif ship_cors[0] in help_coors:
                    help_coors.remove(ship_cors[0])
                    bullets_num += 20
                elif ship_cors[1] in help_coors:
                    help_coors.remove(ship_cors[1])
                    bullets_num += 20
                elif [x_ind, y_ind] in bullets:
                    stdscr.addstr(y_ind, x_ind * 2, bullet_skin + " ", curses.color_pair(215))
                elif [x_ind, y_ind] in enemy_coors:
                    stdscr.addstr(y_ind, x_ind * 2, enemy_skin[0] + " ", curses.color_pair(197))
                elif [x_ind, y_ind] in help_coors:
                    stdscr.addstr(y_ind, x_ind * 2, help_skin[0] + " ", curses.color_pair(83))
                elif y_ind == ship_cors[0][1] and x_ind % 3 == 0 and x_ind != 0:
                    stdscr.addstr(y_ind, x_ind * 2, "- ", curses.color_pair(238))
                else:
                    if i == "#":
                        stdscr.addstr(y_ind, x_ind * 2, i + " ")
                    else:
                        stdscr.addstr(y_ind, x_ind * 2, i + "-", curses.color_pair(235))
        stdscr.addstr(y_ind + 1, 0, "Score: " + str(score) + "   Ammo: " + str(bullets_num) + "   Health: " + str(health))


            # Refresh the screen
        stdscr.refresh()

        time.sleep(0.05)

    with open("data_war.json", 'a') as f: f.close()
    with open('data_war.json', 'r') as file:
        try:
            data = json.loads(file.read())
        except: data = [0]
    file.close()

    if score > data[0]:
        data = [score]
        with open('data_war.json', 'w') as file:
            json.dump(data, file)
        file.close()
        best = str(score)
    else: 
        best = data[0]
    
    print("Your score is {}".format(score))
    print("Best Score is {}".format(best))