Example #1
0
def do_credits(screen, clock, audioPlayer, fpsLimit):
    """Main should call this function to initiate the credit scroll."""
    scrRect = screen.get_rect()
    lineW = int(.75*scrRect.w)
    font = pygame.font.Font(FONTS['credits'], scale(30, lineW, 1024))
    lines = pygame.sprite.Group()
    startY = scrRect.h + 1
    spacer = scale(50, lineW, 1024) #Y-space between lines

    startY = _build_multi_lines(lines, font, startY, spacer, lineW, scrRect)
    finalLineBottom = _build_final_lines(lines, font,
                                         startY + scale(100, lineW, 1024),
                                         lineW,scrRect)
    
    numFrames, step, fpsLimit = get_anim_data(33.2, -1*finalLineBottom,
                                              fpsLimit)
    
    pygame.event.clear()
    audioPlayer.play('end')
    _scroll_credits(screen, scrRect, clock, lines, numFrames, step, fpsLimit)

    _blit_thanks(screen, 'Thanks for playing!', font, scrRect, lineW)
    pygame.time.delay(5000)
    pygame.quit()
    exit()
Example #2
0
def _build_rules(scrRect):
    """Return tuple of fully drawn rules surface and its rect."""
    header = '--RULES--'
    offset = scale(50, scrRect.h, 768)
    rect = scrRect.copy()
    rect.inflate_ip(-offset, -offset)
    sfc = pygame.Surface(rect.size)
    font = pygame.font.Font(FONTS['rules'], scale(80, scrRect.h, 768))

    # Draw header
    sfc.fill(JEOP_BLUE)
    headerRect = pygame.Rect((0, int(.05*rect.h)), font.size(header))
    headerRect.centerx = rect.centerx
    draw_textline(sfc, header, font, (255, 255, 255),
                  headerRect, scale(6, scrRect.h, 768))

    # Draw rules
    bounds = tuple(.9*x for x in scrRect.size)
    fsize = restrict_fontsize(FONTS['rules'], scale(50, scrRect.h, 768),
                              RULES, bounds)
    font = pygame.font.Font(FONTS['rules'], fsize)
    draw_centered_textblock(sfc, RULES, font, (255, 255, 255), 0,
                            scale(4, scrRect.h, 768), False)
    sfc.set_alpha(240)

    return sfc, rect
Example #3
0
 def mc_vlb(eta, phi, psi, y_n, N, L):
     T = y_n.shape[0]
     nn_potentials = recognize(y_n, psi)
     samples, stats, global_vlb, local_vlb = run_inference(
         eta_prior, eta, nn_potentials, num_samples=L)
     saved.stats = scale(N, unbox(stats))
     return global_vlb + N * (local_vlb + loglike(y_n, samples, phi))
Example #4
0
    def __init__(self, screen, unit, preferences):
        self.screen = screen
        self.unit = unit
        self.preferences = preferences
        self.running = True

        self.sounds = SoundPlayer((('fall','fall.wav'),('ding','ding.wav'),('eat','eat.wav'),('move','move.wav'),('splat','splat.wav')))
        self.music = MusicPlayer("game.mp3")

        self.clock = pygame.time.Clock()
        self.tick = Constants.FPS

        self.size = Constants.UNITS*self.unit

        self.surface = pygame.Surface((self.size,self.size))
        self.surface_rect = self.surface.get_rect()
        self.surface_rect.centerx = self.screen.get_rect().centerx
        self.surface_rect.centery = self.screen.get_rect().centery

        self.img_background = pygame.image.load(data.filepath("title","background.jpg"))
        self.img_background = pygame.transform.smoothscale(self.img_background,util.scale(self.img_background,width=self.screen.get_rect().width))
        self.img_background.set_alpha(30)
        self.img_background_rect = self.img_background.get_rect()
        self.img_background_rect.centerx = self.screen.get_rect().centerx
        self.img_background_rect.centery = self.screen.get_rect().centery
Example #5
0
def iso_map_static(all_values):
    """
    all_values in list of list format [[VM1cpu,Vm1 mem, vm2cpu, vm2mem],[],..]
    """

    print len(all_values)
   # file =open("VM.classes", 'rb')
   # label = np.array(ast.literal_eval(file.readline()))

    X = numpy.array(all_values)
    print "Actual Values: ",X

    #For all the dimensions normalise the value range between 0 and 1
    #use ceiling function to remove small noise
    X = util.scale(X)

    for i in xrange(12,len(all_values)):

        print len(X[0])

        print X[:i]
        n_neighbors = 10
        #Y = manifold.Isomap(n_neighbors, 2, max_iter= 4000).fit_transform(X)
        Y = manifold.MDS().fit_transform(X[:i])

        #Y = manifold.LocallyLinearEmbedding().fit_transform(X)
        old_values = Y[:-1]
        new_value = Y[-1:]
        plot.animated_plot(old_values, new_value)
Example #6
0
    def __init__(self, parent, config):
        super(Gauge, self).__init__(parent)

        self.config = config
        self.value = config["min"]

        self.font      = QFont()
        self.note_font = QFont()
        self.color     = QColor(config["color"])
        self.red_color = QColor(config["redline_color"])
        self.brush     = QBrush(self.color)
        self.pen       = QPen(self.color)
        self.red_pen   = QPen(self.red_color)

        self.font.setPixelSize(self.config["font_size"])
        self.note_font.setPixelSize(self.config["note_font_size"])
        self.pen.setWidth(3)
        self.red_pen.setWidth(3)

        s = scale(config["min"], config["max"], config["scale_step"])

        self.angles = map_scale(s, 0, 270)
        self.str_scale, self.multiplier = str_scale(s, config["scale_mult"])

        self.red_angle = 270
        if config["redline"] is not None:
            self.red_angle  = map_value(config["redline"], config["min"], config["max"], 0, 270)
Example #7
0
def _draw_winners(sfc, startY, winners):
    """
    Blit the names of the winners, in their respective fonts, onto sfc.
    'startY' is the y-value of the position at which the first name
    will be drawn.
    If there are multiple winners, draw them in order.

    Return pygame.Rect representing area in which names were drawn.
    """
    sfcRect = sfc.get_rect()
    rect = pygame.Rect(0, startY, sfcRect.w, sfcRect.h - startY)
    y = startY 

    for i, name in winners:
        fName = 'team' + str(i + 1)
        font = pygame.font.Font(FONTS[fName], scale(120, sfcRect.h, 768))
        text = font.render(name, 1, (255, 255, 255), JEOP_BLUE)
        tRect = text.get_rect()
        tRect.centerx = rect.centerx
        tRect.y = y

        sfc.blit(text, tRect)
        y += tRect.h + 5

    return rect
Example #8
0
def _animate_congrats(screen, sfc):
    """
    Animate a congratulations message, drawing one character at a time
    and waiting a short time.

    Return y-value, the bottom of the drawn text string.
    """
    word = 'CONGRATULATIONS!'
    sfcRect = sfc.get_rect()
    font = pygame.font.Font(FONTS['congrats'], scale(150, sfcRect.h, 768))
    rect = pygame.Rect((0, 0), font.size(word))
    rect.centerx = sfcRect.centerx
    rect.y = sfcRect.y + int(.20*sfcRect.h)
    x, y = rect.topleft

    for c in word:
        char = font.render(c, 1, (255, 255, 255), JEOP_BLUE)
        sfc.blit(char, (x, y))

        screen.blit(sfc, (0, 0))
        pygame.display.update(rect)
        pygame.time.delay(100)
        x += char.get_size()[0]

    return rect.bottom
Example #9
0
    def _create_line(self, width, font, position, name):
        """Return surface with credit text blitted on it."""
        spacer = pygame.Rect(0, 0, int(0.08*width), 1)
        spacer.centerx = int(width / 2)
        lineH = font.get_linesize()

        position = [(font.render(s, 1, (200, 200, 200)), s)
                    for s in position]
        name = [(font.render(s, 1, (255, 255, 255)), s)
                for s in name]

        position = [(s, s.get_rect(), text) for s, text in position]
        name = [(s, s.get_rect(), text) for s, text in name]

        sfc = pygame.Surface((width, lineH * max((len(position), len(name)))))
        sfc.fill(JEOP_BLUE)

        for i, (s, rect, text) in enumerate(position):
            rect.right = spacer.left
            rect.top = i*lineH
            sfc.blit(s, rect)

        for i, (s, rect, text) in enumerate(name):
            rect.left = spacer.right
            rect.top = i*lineH
            shadow, shadRect = shadow_text(text, rect, font,
                                           scale(3, width, 1024))

            sfc.blit(shadow, shadRect)
            sfc.blit(s, rect)

        return sfc
Example #10
0
    def get_size(self, section, option, default=None):
        """
        Unit specs are case insensitive.

        b  -> 1
        kb -> 1000**1       kib -> 1024
        mb -> 1000**2       mib -> 1024**2
        gb -> 1000**3       gib -> 1024**3
        tb -> 1000**4       tib -> 1024**4
        pb -> 1000**5       pib -> 1024**5
        eb -> 1000**6       eib -> 1024**6
        zb -> 1000**7       zib -> 1024**7
        yb -> 1000**8       yib -> 1024**8
        """
        try:
            spec = self.get(section, option)
            rval = util.scale(spec)
        except ConfigParser.NoOptionError as e:
            if default is not None:
                rval = default
            else:
                e.message += " in %s" % self.filename
                raise
        except ConfigParser.NoSectionError as e:
            if default is not None:
                rval = default
            else:
                e.message += " in %s" % self.filename
                raise

        return rval
Example #11
0
def iso_map_dynamic(current_value_list, label, transition, closest_monitor_range, action_status):

    dynamic_all_values.append(current_value_list)

    write_as_template(dynamic_all_values, violation_position)

    if(len(dynamic_all_values) > 12):

        X = numpy.array(dynamic_all_values)
       # print "Actual Values: ",X

        #For all the dimensions normalise the value range between 0 and 1
        #use ceiling function to remove small noise
        X = util.scale(X)

        util.compute_utilization(util.scale_list(current_value_list))

        #n_neighbors = 10
        #Y = manifold.Isomap(n_neighbors, 2, max_iter= 4000).fit_transform(X)
        Y = manifold.MDS().fit_transform(X)

        #Y = manifold.LocallyLinearEmbedding().fit_transform(X)
        old_values = Y[:-1]
        new_value = Y[-1:]


        plot.animated_plot(old_values, new_value, violation_position, action_status)

    if closest_monitor_range:
        closest_range_position.append(len(dynamic_all_values) -1)

    # If transition, remove all the values until the closest_range_position
    # remove matching violation_position. It is important to do this before violation position is included inorder to feed in the updated (correct)
    # position of dynamic_values to violation_position.
    if transition:
       # print "!!!!!!!!!!Transition detected!!!!!!!!!! "
       # print "Closest Range positions (before): " ,closest_range_position
       # print "Violation positions (before) ", violation_position
       # print "Length All Values (before): ", len(dynamic_all_values)

        # reversed is important. Remove elements at the end first to avoid messing up index in subsequent deletions.
        if len(closest_range_position) >1:
            for position in reversed(xrange(closest_range_position[-2]+1, closest_range_position[-1])):
                print "Deleting element in position: ", position
                del dynamic_all_values[position]
                if position in violation_position:
                    violation_position.remove(position)

            #closest_Range_position[-1] does not anymore hold the right position. update the position by number of elements deleted.
            closest_range_position[-1] = closest_range_position[-1] - abs(closest_range_position[-2]+1 - closest_range_position[-1])

       # print "Length All Values (after): ", len(dynamic_all_values)
       # print "Violation positions (after) ", violation_position
       # print "Closest Range positions (after): " ,closest_range_position

    # Append the position of the violation only after plotting
    # inorder to plot the current value as current point instead of a violation
    if label:
        violation_position.append(len(dynamic_all_values)-1)
Example #12
0
def distance_along_edge_to_point(edge, distance_along_edge):
    edge_start, edge_end = edge
    edge_vector = util.subtract(edge_end, edge_start)
    edge_length = util.norm(edge_vector)    
    scale_factor = distance_along_edge / edge_length
    scaled_vector = util.scale(scale_factor, edge_vector)
    point = util.add(scaled_vector, edge_start)
    return point
Example #13
0
def _blit_thanks(screen, text, font, scrRect, lineW):
    thanks = font.render(text, 1, (255, 255, 255))
    rect = thanks.get_rect()
    rect.center = scrRect.center
    shadow, shadRect = shadow_text(text, rect, font, scale(3, lineW, 1024))
    
    screen.blit(shadow, shadRect)
    screen.blit(thanks, rect)
    pygame.display.update()
Example #14
0
def _build_final_lines(group, font, startY, lineW, scrRect):
    """
    Build final line sprites and adds them to 'group.'
    Return final line's rect.bottom.
    """
    for s in final:
        if isinstance(s, pygame.Surface):
            line = CreditImage(s, group)
        else:
            line = SimpleCreditLine(font, s, (255, 255, 255),
                                      JEOP_BLUE, scale(4, lineW, 1024), group)

        line.rect.y = startY
        line.rect.centerx = scrRect.centerx
        finalLineBottom = line.rect.bottom
        startY = line.rect.bottom + scale(5, lineW, 1024)

    return finalLineBottom
Example #15
0
    def main(self):
        """ Display the screen and a little bit of text at the bottom
            of the screen. """
        self.music_player.once()

        img_logo = pygame.image.load(data.filepath("title","logo_unla.png"))
        img_logo = pygame.transform.smoothscale(img_logo,util.scale(img_logo,width=self.unit*25))
        img_logo_rect = img_logo.get_rect()
        img_logo_rect.centerx = self.screen.get_rect().centerx
        img_logo_rect.centery = self.screen.get_rect().centery

        #settings
        seconds_in = 2
        seconds_still = 1
        seconds_out = 2

        fps = 20
        logo_alpha = 0
        logo_alpha_add = int(255.0/float(fps*seconds_in))
        logo_alpha_sub = -int(255.0/float(fps*seconds_out))
        logo_alpha_sum = logo_alpha_add
        stop_counter = fps*seconds_still

        skip = False

        # LOGO INTRO
        while not skip:
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    skip = True
                elif event.type == pygame.QUIT:
                    self.running = False
                    return

            self.screen.fill((0, 0, 0))
            img_logo.set_alpha(logo_alpha)
            self.screen.blit(img_logo, img_logo_rect)

            if logo_alpha == 255 and stop_counter > 0:
                stop_counter-=1
            else:
                logo_alpha += logo_alpha_sum
                if logo_alpha > 255:
                    logo_alpha = 255
                    logo_alpha_sum = logo_alpha_sub
                elif logo_alpha < 0:
                    break

            pygame.display.update()
            self.clock.tick(fps)

        self.music_player.stop()
 def __init__(self, raw_train_fn, top_dir):
     self.dl = util.DownloadReader(raw_train_fn)
     self.data, self.overs = util.scale(self.dl.data, 0.99)
     #self.data[self.data > 0] = 1
     #self.data = np.hstack((self.data, self.overs.astype(self.data.dtype)))
     #last_col = np.sum(self.overs, axis=1)
     last_col = np.zeros(self.overs.shape[0])
     last_col[np.sum(self.overs, axis=1)>0] = True
     #self.data = np.hstack((self.data, last_col.reshape(last_col.shape[0], -1)))
     self.top_dir = top_dir
     self.base_hyper_params_aa = dict(
         nvis=self.data.shape[1], batch_size=10, nhid=60, save_freq=10,
         tied_weights=False)
     self.aa_yaml=open('autoenc1.yaml', 'r').read()
Example #17
0
def _build_banner(scrRect, color):
    """
    Return 2-tuple containing title banner surface and its Rect, 
    already positioned to be drawn.
    
    Arguments are a pygame.Rect object the size of the screen, and the 
    color of the banner.
    """
    size = (scrRect.w, scale(175, scrRect.h, 768))
    banner = pygame.Surface(size)
    banner.fill(color)
    
    rect = banner.get_rect()
    rect.centery = scrRect.centery

    return (banner, rect)
Example #18
0
    def __init__(self, screen, unit, preferences):
        self.screen = screen
        self.unit = unit
        self.preferences = preferences
        self.running = True
        self.music_player = MusicPlayer(random.choice(listaMenu))
        self.clock = pygame.time.Clock()
        self.choice = 0
        self.size = self.screen.get_size()

        self.img_title = pygame.image.load(data.filepath("title","logo_unla.png"))
        self.img_credits = pygame.image.load(data.filepath("title","logo_unla.png"))
        self.img_background = pygame.image.load(data.filepath("title","background.jpg"))
        self.img_background = pygame.transform.smoothscale(self.img_background,util.scale(self.img_background,width=self.size[0]))
        self.img_background.set_alpha(50)
        self.img_background_rect = self.img_background.get_rect()
        self.img_background_rect.centerx = self.screen.get_rect().centerx
        self.img_background_rect.centery = self.screen.get_rect().centery
Example #19
0
def distance_over_time():
    '''
    Load template and plot the distance over time
    '''
    if os.path.isfile("../template"):
        f_handle = open("../template", 'r')
        dynamic_all_values = ast.literal_eval(f_handle.readline())
        violation_position = ast.literal_eval(f_handle.readline())
        f_handle.close()
    else:
        print "No such file"

    X = numpy.array(dynamic_all_values)
    #  print "Actual Values: ",X

    #For all the dimensions normalise the value range between 0 and 1
    #use ceiling function to remove small noise
    X = util.scale(X)

    #n_neighbors = 10
    #Y = manifold.Isomap(n_neighbors, 2, max_iter= 4000).fit_transform(X)
    Y = manifold.MDS().fit_transform(X)

    old_values = Y[:-1]
    new_value = Y[-1:]

    dist =[]
    for index in xrange(0, len(Y)-1):
        dist.append(distance.calculate_distance(Point(Y[index][0], Y[index][1]), Point(Y[index+1][0], Y[index+1][1])))


    plt.plot(dist,'-', color = 'R',markersize = 10, label = "Distance between points")
    plt.xlabel("Time (Mins)")
    plt.ylabel("distance")
    plt.grid(True)
    plt.minorticks_on()
    plt.legend(loc=2)
    plt.show()

    animated_plot(old_values, new_value, violation_position, 'None')
Example #20
0
 def __rdiv__(self, constant):
     import util
     return util.scale(self, 1 / constant)
Example #21
0
def narrate_time(last_event, event):
    if last_event and last_event['date'].month != event['date'].month:
        narrate_month(event['date'], util.scale(
            last_event['delta'] + event['delta'], -1, 1, 1, 0))
Example #22
0
def narrate_conflict_zoomout(a, b, event, problem_phrase):
    response = get_response(a, b, event)
    problem_statement = tracery.Grammar(
        {
            'origin': "#They# #sometimes# #fought# because #a# felt that #b# #problem#.\n",
            'problem': problem_phrase,
            'pushing': 'pushing',
            'sometimes': util.rank(['occasionally', 'sometimes', 'often', 'frequently', 'always'], util.scale(event['delta'], -1, 0.5, 1, 0)),
            'fought': ['fought', 'argued', 'clashed', 'scuffled'],
            'They': ['They', 'The couple'],
            'a': a['name'],
            'b': b['name'],
        }).flatten('#origin#')
    print(problem_statement)
Example #23
0
    def main(self):
        self.music_player.play()

        img_title = pygame.transform.smoothscale(self.img_title,util.scale(self.img_title,width=self.unit*10))
        img_title_rect = img_title.get_rect()
        img_title_rect.centerx = self.screen.get_rect().centerx
        img_title_rect.y = self.unit*10

        self.choice = 0
        start_game = False

        btn_play = MenuButton("PLAY",self.unit,(self.unit*17, self.unit*3))
        btn_play.rect.centerx = self.screen.get_rect().centerx
        btn_play.rect.y = self.unit*24
        btn_play.set_status(1)

        btn_highscores = MenuButton("HIGH SCORES",self.unit,(self.unit*17, self.unit*3))
        btn_highscores.rect.centerx = self.screen.get_rect().centerx
        btn_highscores.rect.y = self.unit*28

        btn_fullscreen = MenuButton(["FULLSCREEN","WINDOWED"][self.preferences.get('fullscreen')],self.unit,(self.unit*17, self.unit*3))
        btn_fullscreen.rect.centerx = self.screen.get_rect().centerx
        btn_fullscreen.rect.y = self.unit*32

        btn_credits = MenuButton("CREDITS",self.unit,(self.unit*17, self.unit*3))
        btn_credits.rect.centerx = self.screen.get_rect().centerx
        btn_credits.rect.y = self.unit*36

        btn_exit = MenuButton("QUIT",self.unit,(self.unit*17, self.unit*3))
        btn_exit.rect.centerx = self.screen.get_rect().centerx
        btn_exit.rect.y = self.unit*40
        buttons = pygame.sprite.Group()
        buttons.add([btn_play,btn_fullscreen,btn_highscores,btn_credits,btn_exit])

        dbg = util.debugBackground(self.size,self.unit)
        self.draw_background()

        last_choice = -1

        while not start_game:
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_UP or event.key == pygame.K_w:
                        self.choice -= 1
                    elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
                        self.choice += 1
                    elif event.key == pygame.K_RETURN or event.key == pygame.K_SPACE:
                        if self.choice == 0:
                            start_game = True
                        elif self.choice == 1:
                            self.highscores()
                            self.draw_background()
                        elif self.choice == 2:
                            # return to MAIN.PY to save prefs and apply fullscreen mode
                            self.preferences.set('fullscreen',not self.preferences.get('fullscreen'))
                            return
                        elif self.choice == 3:
                            self.credits()
                            self.draw_background()
                        else:
                            self.running = False
                            return
                    elif event.key == pygame.K_ESCAPE:
                        self.running = False
                        return
                    elif event.key == pygame.K_1:
                        pygame.image.save(self.screen, "screenshot.jpg")
                elif event.type == pygame.QUIT:
                    self.running = False
                    return
            if self.choice != last_choice:
                if self.choice < 0: self.choice = 4
                elif self.choice > 4: self.choice = 0
                btn_play.set_status(0)
                btn_highscores.set_status(0)
                btn_fullscreen.set_status(0)
                btn_credits.set_status(0)
                btn_exit.set_status(0)
                if self.choice == 0: btn_play.set_status(1)
                elif self.choice == 1: btn_highscores.set_status(1)
                elif self.choice == 2: btn_fullscreen.set_status(1)
                elif self.choice == 3: btn_credits.set_status(1)
                elif self.choice == 4: btn_exit.set_status(1)
                last_choice = self.choice

            buttons.update()
            self.screen.blit(img_title, img_title_rect)
            buttons.draw(self.screen)
            pygame.display.flip()
            self.clock.tick(30)
        self.music_player.stop()
 def x_scale(self, x):
     return util.scale(x, self.x_domain, self.x_range)
Example #25
0
    def credits(self):
        img_credits = pygame.transform.smoothscale(self.img_credits,util.scale(self.img_credits,height=self.unit*13))
        img_credits_rect = img_credits.get_rect()
        img_credits_rect.centerx = self.screen.get_rect().centerx
        img_credits_rect.y = self.unit*2

        back = False

        btn_back = MenuButton("BACK",self.unit,(self.unit*17, self.unit*3))
        btn_back.rect.centerx = self.screen.get_rect().centerx
        btn_back.rect.y = self.unit*45
        btn_back.set_status(1)

        self.draw_background()

        box = pygame.Surface((self.size[1],self.size[1]))
        box.fill((255,255,255))
        box.set_alpha(150)
        box_rect = box.get_rect()
        box_rect.centerx = self.screen.get_rect().centerx
        box_rect.y = 0
        self.screen.blit(box,box_rect)

        font = pygame.font.Font(data.filepath("font", "abel.ttf"), int(self.unit * 1.5))
        color_text = (30,30,30)
        color_title = (122,30,30)

        credits = Constants.CREDITS.split("\n")
        spooler = []
        for line in credits:
            color = color_text
            if line and line[0] == "*":
                line = line[1:]
                color = color_title
            spooler.append(font.render(line, True, color))

        posy = 16*self.unit
        advance = int(1.6*self.unit)

        self.screen.blit(img_credits, img_credits_rect)
        btn_back.update()
        btn_back.draw(self.screen)

        for el in spooler:
            rect = el.get_rect()
            rect.centerx = self.screen.get_rect().centerx
            rect.y = posy
            self.screen.blit(el, rect)
            posy += advance

        while not back:
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE or event.key == pygame.K_RETURN or event.key == pygame.K_SPACE:
                        return
                    elif event.key == pygame.K_1:
                        pygame.image.save(self.screen, "screenshot.jpg")
                elif event.type == pygame.QUIT:
                    self.running = False
                    return


            pygame.display.flip()
            self.clock.tick(30)
Example #26
0
 def __rmul__(self, constant):
     import util
     return util.scale(self, constant)
 def y_scale(self, y):
     return util.scale(y, self.y_domain, self.y_range)
    def interpret_axis_labels(self, axis_label_indexes):
        x_coords=list()
        x_label_ocr=list()
        y_coords=list()
        y_label_ocr=list()
        for i in axis_label_indexes:
            box = self.bounding_boxes[i]
            x_center = box[2]-box[0]
            y_center = box[3]-box[1]
            """
            If the label lies to the right of the y=x line that passes through
            the bottom left corner of the graph, it is for the x axis.
            Otherwise it is for the y axis.
            We calculate this by decreasing the x center for every y that it is
            below the bottom of the graph.
            """
            x_center_adjusted = x_center-(y_center-self.y_domain[1])
            x_len = len(x_label_ocr)
            y_len = len(y_label_ocr)
            #stop if we have found two labels for both axes
            if x_len>=2 and y_len>=2:
                break
            #util.write_array('temp.txt', self.image)
            pil_image = util.numpy_to_pil(self.image)
            pil_image.save('temp.png')
            if x_center_adjusted>self.x_domain[0]:
                #potential problem: out of order coord_spread. is that dangerous?
                if x_len==0:
                    x_coords.append(x_center)
                    ocr = util.ocr_cropped(pil_image, box)
                    print 'ocr', ocr
                    x_label_ocr.append(float(ocr))
                elif x_len==1:
                    x_coords.append(x_center)
                    ocr = util.ocr_cropped(pil_image, box)
                    print 'ocr', ocr
                    x_label_ocr.append(float(ocr))
                else:
                    #the x labels have already been found
                    pass

            else:
                if y_len==0:
                    y_coords.append(y_center)
                    ocr = util.ocr_cropped(pil_image, box)
                    print 'ocr', ocr
                    y_label_ocr.append(float(ocr))
                elif y_len==1:
                    y_coords.append(y_center)
                    ocr = util.ocr_cropped(pil_image, box)
                    print 'ocr', ocr
                    y_label_ocr.append(float(ocr))
                else:
                    #the y labels have already been found
                    pass

        #Make sure we have the x and y labels and label spreads
        if len(x_coords)>=2 and len(y_coords>=2):
            self.x_range.append(util.scale(x_label_ocr[0], 
                x_coords, self.x_domain))
            self.x_range.append(util.scale(x_label_ocr[1], 
                x_coords, self.x_domain))
            self.y_range.append(util.scale(y_label_ocr[0], 
                y_coords, self.y_domain))
            self.y_range.append(util.scale(y_label_ocr[1], 
                y_coords, self.y_domain))
def narrate_commit(event, events):
    a, b = get_ab(event)
    if event['initiated']:
        enthusiasm = util.scale(event['success_ratio'], 1, 3, 0, 1)
        rules = {
            'courting_phase': ['<p>#dating#</p>'],
            'dating_phase': ['<p>#iloveyou#</p>'],
            'dating': ['#dating_challenge# #dating_result#'],
            'iloveyou': ['#ily_challenge# #ily_result#'],
            'dating_challenge': [
                "#a# asked to start dating.",
                "#a# asked if #b# would be interested in dating.",
            ],
            'dating_result':
            f"#b# agreed {util.enthusiastically(enthusiasm)}. "
            if event['success_ratio'] >= 1 else
            f'#b# said that {b["they"]} needed more time. ',
            'ily_challenge':
            f"#a# said \"I love you,\"",
            'ily_result': [
                'but #b# could not say it back. #a# was #hurt#'
                if event['success_ratio'] < 1 else
                f'and #b# returned the words {util.enthusiastically(enthusiasm)}.'
            ],
            'hurt': util.rank(
                [
                    'hurt, but said #a_they# understood.',
                    'wounded. A tear fell from #a#\'s left eye. ',
                    'devasted. #a_they.capitalize# had hoped #b#\'s response might have been different this time.',
                    'mortified. #a# shouted that #b# was wasting #a#\'s time. #b# shrugged. '
                ],
                util.scale(event.get('prev', 0), 0, 3, 0, 1)
            ),
            'a': a['name'],
            'b': b['name'],
            'a_they': a['they']
        }

    elif event['initiate_ratio'] > 1:
        # Narrate a failed commit event held back by confidence
        rules = {
            'courting_phase': '#origin#',
            'dating_phase': '#origin#',
            'origin': [
                '#a# felt nervous, but excited. ',
                '#a# sighed. #b# seemed so amazing. But would #b_they# return #a#\'s feelings?',
                '#a# smiled quietly to themselves. Perhaps the right time to talk to #b# would come some day. ',
                "#a# had the urge to ask #b# about how they felt about the relationship, but wasn't quite confident enough to ask. ",
            ],
            'a': a['name'],
            'b': b['name'],
            'b_they': b['they'],
        }
    else:
        # Not interested enough.
        rules = {
            'courting_phase': [
                "#a# continued to use dating apps from time to time. ",
                "#a# considered sending #b# a message, but decided not to. ",
                "#a# noticed a message from #b#. #a# ignored it. ",
                "#b# had yet to meet most of #a#'s friends. ",
            ],
            'dating_phase': [
                "#a#'s Facebook relationship status still read 'Single'. ",
                "#a# had yet to mention #b# to their parents. ",
                "#a# told #b# they were busy, but in fact #a# had no concrete plans that day. ",
                "#a# lay awake at night, mulling over exes from previous relationships. ",
            ],
            'a': a['name'],
            'b': b['name'],
            'interest': a['interests'],
        }
    grammar = tracery.Grammar(rules)
    grammar.add_modifiers(base_english)
    if event['phase'] == Phase.COURTING:
        print(grammar.flatten('<p>#courting_phase#</p>'))
    elif event['phase'] == Phase.DATING:
        print(grammar.flatten('<p>#dating_phase#</p>'))
    print('\n')
    narrate_commit_system(event)