def maxSlices(pizza):
    matrix = pizza.grid
    print "matrix:"
    print matrix
    # Output Data Type
    slices = []

    iMax = pizza.R
    jMax = pizza.C
    i = 0
    while (i < (iMax - 1)):
        j = 0
        while (j < (jMax - 1)):
            startVal = matrix[i][j]
            endVal = matrix[i][j + 1]
            if (isValidSlice(startVal, endVal)):
                startCoord = Coord(i, j)
                endCoord = Coord(i, j + 1)
                currSlice = Slice(startCoord, endCoord)
                slices.append(currSlice)
                j += 2
            else:
                j += 1
        i += 1

    # print matrix
    for currSlice in slices:
        currSlice.printSlice()
    visitSlices(matrix, slices)
def get_row_set_from_cache(access_list):
    cache_offset = cache.get_offset()
    cache_index_size = cache.get_index_size()
    for entry in access_list:
        split = entry.split(',')
        sliced_address = Slice(split[0], cache_offset, cache_index_size)
        cache_row_set = cache.read_cache(int(split[1]), util.bin_to_dec(sliced_address.get_offset()),
                                         sliced_address.get_index())
        access_the_cache(cache_row_set, util.bin_to_hex(sliced_address.get_tag()))
Exemple #3
0
    def reset(self):
        self.y_offset = 0
        self.player = Player(self)
        self.walls = Walls(self)
        self.slice = Slice(self)
        self.enemies = [
            TutorialEnemy(self, y=c.WINDOW_HEIGHT / 2, x=c.MIDDLE_X)
        ]
        self.enemies[0].angle = 0
        self.update_enemies(0, [])
        self.particles = []
        self.text_particles = []
        self.background = Background(self)
        self.player.velocity = (100, 600)
        self.aiming = False
        self.aimingness = 0

        self.score_yoff = 50
        self.score_size = 40
        self.target_score_size = 40
        self.score_bumped = True

        self.shade = pygame.Surface(c.WINDOW_SIZE)
        self.shade.fill(c.BLACK)
        self.shade.set_alpha(0)

        self.shade_2 = pygame.Surface(c.WINDOW_SIZE)
        self.shade.fill(c.BLACK)
        self.shade_2.set_alpha(0)

        self.shade_3 = pygame.Surface(c.WINDOW_SIZE)
        self.shade.fill(c.BLACK)
        self.shade_3.set_alpha(255)

        self.flare = pygame.Surface(c.WINDOW_SIZE)
        self.flare.fill((255, 226, 140))
        self.flare.set_alpha(0)
        self.flare_alpha = 0

        self.multiplier = 1

        self.queue_reset = False

        self.game_end = False

        self.retry_button.visible = False
        self.submit_button.visible = False
        self.closing = False
        self.freeze_surf = None

        for button in self.buttons:
            button.disabled = False

        self.error_message = ""
        self.tutorial = True
        self.tutorial_offset = 0
def stitch(tiles, slice_shape=(2044, 2048), IMG_WIDTH=256, IMG_HEIGHT=256):
    slice = np.zeros(slice_shape)
    # M, N = np.shape(tiles[0].detach().numpy()[0,0,:,:])
    n = 0
    for x in range(0, slice.shape[0], IMG_WIDTH):
        for y in range(0, slice.shape[1], IMG_HEIGHT):
            this_tile = Slice(tiles[n].detach().numpy()[0, 0, :, :])
            M, N = np.shape(slice[x:x + IMG_WIDTH, y:y + IMG_HEIGHT])
            slice[x:x + IMG_WIDTH,
                  y:y + IMG_HEIGHT] = this_tile.norm_max().reshape(M, N).slice
            n += 1
    return Slice(slice)
Exemple #5
0
    def setUp(self):
        """setUp test.

        :return:
        """

        super(SliceTestCase, self).setUp()

        self.cell0 = Cell(X0, Y0)
        self.cell1 = Cell(X1, Y1)
        self.slice = Slice()
Exemple #6
0
    def setUp(self):
        """setUp test.

        :return:
        """

        super(PizzaSliceTestCase, self).setUp()

        pizza_cell = PizzaCell(Ingredient.MUSHROOM.value)

        self.cell0 = Cell(X0, Y0)
        self.cell1 = Cell(X1, Y1)

        self.slice0 = Slice()
        pizza_cell.cell = self.slice0
        self.slice0 += pizza_cell

        self.slice1 = Slice()
        pizza_cell.cell = self.slice1
        self.slice1 += pizza_cell

        self.pizza_slice = PizzaSlice()
Exemple #7
0
    def generate_children(self):
        if self.mushrooms == 0 or self.tomatoes == 0:
            return []
        L = constants.L
        pizza = constants.pizza
        C = constants.C
        R = constants.R
        H = constants.H
        nodes = []
        starty = 0
        startx = 0
        for i in range(starty, R):
            for j in range(startx, C):
                for size in range(2 * L, H + 1):
                    for rows in range(1, size + 1):
                        if len(nodes) > 100:
                            return nodes
                        if (size % rows == 0):
                            newcoord = (i + rows - 1, j + (size / rows) - 1)
                            if (newcoord[0] < R and newcoord[1] < C):
                                newSlice = Slice(int(i), int(j),
                                                 int(newcoord[0]),
                                                 int(newcoord[1]))
                                if (newSlice.isValid(self.node_slices)):
                                    newnode = Node(self.node_slices,
                                                   self.score, self.estimate,
                                                   newSlice, self.mushrooms,
                                                   self.tomatoes)
                                    if (newnode.mushrooms >= constants.L and
                                            newnode.tomatoes >= constants.L):
                                        percentage = float(
                                            newnode.mushrooms) / (
                                                newnode.mushrooms +
                                                newnode.tomatoes)
                                        diff = abs(0.5 - percentage)
                                        heappush(nodes, (-newnode.score -
                                                         (1 - diff), newnode))

        return nodes
    def get_new_slice(self, pizza_cell: PizzaCell) -> Slice:
        """Return new slice with this cell.

        :param pizza_cell: add this cell into new slice
        :type pizza_cell: PizzaCell
        :return: last slice
        :rtype: Slice
        """

        slice = Slice(pizza_cell)

        self.__add__(slice)

        return slice
    def __init__(self,
                 slice_size=SLICE_SIZE_DEFAULT,
                 slice_offset=SLICE_OFFSET_DEFAULT,
                 max_dist_mult=MAX_DIST_MULT_DEFAULT,
                 publish_rate=PUBLISH_RATE_DEFAULT,
                 publish_pc=PUBLISH_PC_DEFAULT,
                 scan_topic=SCAN_TOPIC_DEFAULT,
                 contour_topic=CONTOUR_TOPIC_DEFAULT,
                 centroid_topic=CENTROID_TOPIC_DEFAULT,
                 pc_topic=PC_TOPIC_DEFAULT):
        self.__slice_size = slice_size
        self.__slice_offset = slice_offset
        self.__max_dist_mult = max_dist_mult
        self.__publish_point_cloud = publish_pc

        self.__rate = rospy.Rate(publish_rate)
        self.__laser_projector = LaserProjection()
        self.__vals_lock = Lock()
        self.__curr_msg = None
        self.__data_available = False
        self.__stopped = False

        # Create Slices once and reset them on each iteration
        self.__slices = [
            Slice(v, v + self.__slice_size)
            for v in range(0, 180, self.__slice_size)
        ]

        rospy.loginfo(
            "Publishing Contour vals to topic {}".format(contour_topic))
        self.__contour_pub = rospy.Publisher(contour_topic,
                                             Contour,
                                             queue_size=5)

        rospy.loginfo(
            "Publishing Point vals to topic {}".format(centroid_topic))
        self.__centroid_pub = rospy.Publisher(centroid_topic,
                                              Point,
                                              queue_size=5)

        if self.__publish_point_cloud:
            rospy.loginfo(
                "Publishing PointCloud2 vals to topic {}".format(pc_topic))
            self.__pc_pub = rospy.Publisher(pc_topic,
                                            PointCloud2,
                                            queue_size=5)

        rospy.loginfo("Subscribing to LaserScan topic {}".format(scan_topic))
        self.__scan_sub = rospy.Subscriber(scan_topic, LaserScan, self.on_msg)
    def create_copy(cls,
                    reconstruction,
                    parent=None,
                    logger=None,
                    slide_score_api=None,
                    slide_score_user=None):
        '''
        Create make a copy of the reconstruction, while reloading all objects
        :param reconstruction: the reconstruction object from which a copy is made
        :param parent: the parent
        :param logger: the logger
        :param slide_score_api:  the slide score api
        :param slide_score_user: the slide score user
        :return: the newly created object
        '''
        if reconstruction is None:
            return None
        # first create an empty reconstruction
        obj = cls(parent=parent,
                  logger=logger,
                  slide_score_api=slide_score_api,
                  slide_score_user=slide_score_user)
        # set the study and case id
        obj.set_slide_score_study_and_case_id(
            slide_score_study_id=reconstruction.slide_score_study_id,
            slide_score_case_id=reconstruction.slide_score_case_id)
        # reload the coupes
        import coupe
        obj.logger.warning("Reloading Coupes")
        importlib.reload(coupe)
        from coupe import Coupe
        for miro_photo_id in reconstruction.coupes:
            obj.coupes[miro_photo_id] = Coupe.create_copy(
                coupe=reconstruction.coupes[miro_photo_id],
                parent=parent,
                logger=logger)
        obj.active_coupe = reconstruction.active_coupe
        # same for the slices
        import slice
        obj.logger.warning("Reloading Slices")
        importlib.reload(slice)
        from slice import Slice
        for slice in reconstruction.slices:
            obj.slices.append(Slice.create_copy(slice=slice, logger=logger))

        # and finally the ruler
        obj.ruler_points = reconstruction.ruler_points
        return obj
Exemple #11
0
    def _setSlices(self, path, codes):

        # prepare empty dictionary
        slice_dict = {}

        # iterate over the expected slice spec files
        for slice_name in codes:

            # construct a path to slice file
            slice_path = f'{path}/{slice_name}.json'

            # add slice to the dictionary under the appropriate key
            slice_dict[slice_name] = Slice(slice_path)

        # return the dictionary of slices
        return slice_dict
    def add_slice_from_rect(self, rect):
        '''
        Create a new slice from bounding box (rect) based on self.macro_photo
        The newly createad slice is returned, but also added to the list of slices (self.slices)

        :param rect: The rectangle (using QRect) with the bounding box within the macro photo
        :return: the newly created slice
        '''

        try:
            new_slice = Slice.create_from_photo(macro_photo=self.macro_photo,
                                                rect=rect,
                                                id=len(self.slices),
                                                logger=self.logger)
            self.slices.append(new_slice)
            self.logger.info(f"Adding slice with rect {rect}")
            return new_slice
        except:
            self.logger.error(sys.exc_info()[0])
            self.logger.error(traceback.format_exc())
            return None
Exemple #13
0
    def reset(self):
        """
        reset the env and return the obs

        Returns
        -------
            all slice adj_matrix and flow features
        """
        self.num_flow_to_route = 0
        # self.edge_set = self.topology.edge_set()
        self.slices = [Slice(self.topology) for _ in range(self.num_slices)]
        for s in self.slices:
            s.init_band(self.num_slices)
            s.gen_edge_features()
        flow_generator = self.topology.gen_flows()
        self.flows = [Flow(i, *next(flow_generator)) for i in range(300)]
        for f in self.flows:
            f.gen_bfs_edges(self.topology.graph)
        return dict(
            {'flow': self.flows[self.num_flow_to_route].edge_bfs_features}, **{
                'slice' + str(i): self.slices[i].edge_features
                for i in range(self.num_slices)
            })
    def create_from_dict(cls,
                         data,
                         slide_score_api,
                         slide_score_user,
                         parent=None,
                         logger=None):
        '''
        :param data: input dictionary
        :param slide_score_api: the slide_score api
        :param slide_score_user: the slide socre user
        :param parent: parent object
        :param logger: logger
        :return: the reconstruction as created from the dict
        '''
        obj = cls(parent=parent,
                  logger=logger,
                  slide_score_api=slide_score_api,
                  slide_score_user=slide_score_user)
        obj.set_macro_photo(data['macro_photo_path'])
        obj.set_slide_score_study_and_case_id(
            slide_score_study_id=data['slide_score_study_id'],
            slide_score_case_id=data['slide_score_case_id'])
        for coupe_id in data['coupe_ids']:
            obj.coupes[coupe_id] = Coupe.create_from_slide_score(
                slide_score_api=slide_score_api,
                slide_score_study_id=obj.slide_score_study_id,
                slide_score_case_id=obj.slide_score_case_id,
                slide_score_image_id=coupe_id,
                parent=parent,
                logger=logger)

        for slice_data in data['slices']:
            obj.slices.append(
                Slice.create_from_dict(data=slice_data,
                                       macro_photo=obj.macro_photo,
                                       logger=logger))
        return obj
Exemple #15
0
        neng = english_syll

    return neng, hindi_syll


incorrect_pairings = []

with open(RESOURCE_FOLDER+'/Output/all-words-pairs.txt') as infile:
    with open('diff.txt', 'w') as outfile:
        for line in infile:
            line = line.strip()
            e, h = line.split('\t')
            e = e.decode('utf-8')
            h = h.decode('utf-8')
            word_dict[h].add(e)
            el = [u for u in Slice(e, len(e)).morphemes]
            hl = [u for u in Slice(h, len(h), True).morphemes]
            el, hl = update_on(el, hl)

            total_length += 1
            if len(el) == len(hl):
                for i in xrange(len(el)):
                    hsyllable_representations[hl[i]][el[i]] += 1
                    if i + 1 < len(el) and i > 0:
                        hsyllable_prev_combination_count[hl[i]][hl[i - 1]] += 1
                    hsyllable_count[hl[i]] += 1
                    esyllable_count[el[i]] += 1
            else:
                diff_length += 1
                incorrect_pairings.append((el, hl))
Exemple #16
0
    def _set_slice_mode(self, slice_mode):
        if slice_mode not in ["axial", "coronal", "sagittal", "multiplanar"]:
            raise medipy.base.Exception("Unknown slice mode : %s" %
                                        (slice_mode, ))

        old_cursor_position = (numpy.copy(self.cursor_index_position)
                               if self.cursor_index_position is not None else
                               None)

        old_slice_mode = self._slice_mode
        self._slice_mode = slice_mode

        for slice in self._slices:
            self._rwi.GetRenderWindow().RemoveRenderer(slice.renderer)
            slice.unset_rwi(self._rwi)

        if old_slice_mode == "multiplanar" and slice_mode != "multiplanar":
            self._rwi.GetRenderWindow().RemoveRenderer(
                self._informations_renderer)

        self._slices = []
        self._slices_names = []

        names = (["axial", "coronal", "sagittal"]
                 if slice_mode == "multiplanar" else [slice_mode])

        # Build and configure the Slice objects
        for name in names:
            if self._display_coordinates == "index":
                # Do not use radiological or neurological slices
                convention = "index"
            else:
                convention = self._convention

            world_to_slice = medipy.base.coordinate_system.slices[convention][
                name]
            slice = Slice(world_to_slice, self._layers, self._annotations,
                          self._interpolation, self._display_coordinates,
                          self._scalar_bar_visibility,
                          self._orientation_visibility,
                          slice_mode != "multiplanar", self.crosshair)

            if slice_mode == "multiplanar":
                slice.renderer.SetViewport(*self._viewport[name])
            else:
                slice.renderer.SetViewport(0., 0., 1., 1.)
            self._rwi.GetRenderWindow().AddRenderer(slice.renderer)
            slice.setup_rwi(self._rwi)
            self._slices.append(slice)
            self._slices_names.append(name)

        for index, slice in enumerate(self._slices):
            for event in slice.allowed_events:
                if event in [
                        "any", "cursor_position", "image_position", "center",
                        "corner_annotations_visibility", "world_to_slice",
                        "layer_visibility"
                ]:
                    continue
                slice.add_observer(event, self._on_slice_event)

            slice.add_observer("cursor_position", self._on_cursor_position)
            slice.add_observer("center", self._on_center)
            slice.add_observer("layer_visibility", self._on_layer_visibility)

            # Synchronize the Slices' colormaps
            # Do not use PropertySynchronized API for better event handling
            # and thus better performances
            if len(self._slices) > 1:
                next_slice = self._slices[(index + 1) % len(self._slices)]

                for layer_index, layer in enumerate(slice.layers):
                    for event in [
                            "data", "display_range", "cut_low", "cut_high",
                            "zero_transparency"
                    ]:
                        layer.colormap.add_observer(event,
                                                    self._on_colormap_event)
                    next_slice_layer = next_slice.layers[layer_index]
                    layer.colormap.append_child(next_slice_layer.colormap)

        # Add a 4th renderer with image info in multiplanar mode, otherwise
        # display the corner annotations
        if slice_mode == "multiplanar":
            self._rwi.GetRenderWindow().AddRenderer(
                self._informations_renderer)
            self._informations_corner_annotation.SetVisibility(
                self.corner_annotations_visibility)
        else:
            self._slices[
                0].corner_annotations_visibility = self.corner_annotations_visibility

        for button, (class_, args, kwargs) in self._mouse_tools.items():
            self.set_mouse_button_tool(button, class_, *args, **kwargs)
        for key, (class_, args, kwargs) in self._keyboard_tools.items():
            self.set_keyboard_tool(key, class_, *args, **kwargs)

        # Keep the same pixel under the cursor and centered in the view
        self._locked = True
        if old_cursor_position is not None:
            self._set_cursor_index_position(old_cursor_position)
        self._locked = False

        self._update_informations()
def infer(PATH_IMG_INFER, PATH_MODEL_PARAMS, PATH_INFER_SAVE, DEPTH,
          NUM_CHANNELS, MULT_CHAN, NUM_CLASSES, Z_RANGE, IMG_WIDTH,
          IMG_HEIGHT):

    ### instantiate model and load the model parameters
    my_model = MyModel(n_in_channels=NUM_CHANNELS,
                       mult_chan=MULT_CHAN,
                       depth=DEPTH)
    my_model.load_state_dict(
        torch.load(PATH_MODEL_PARAMS, map_location=torch.device('cpu')))
    my_model.eval()

    ### read in the tiff and place into a ZStack object
    stack = ZStack(path=PATH_IMG_INFER, zrange=Z_RANGE)

    # separate zslices; assign each to its own Slice object, and hold them all in a list
    slices = [Slice(x) for x in stack.images]

    # split each slice into tiles
    tiles = np.array(
        [slices[z].tile(IMG_WIDTH, IMG_HEIGHT) for z in range(len(slices))])

    # normalize (z-score) the tiles before passing to model
    [[tiles[y][x].normalize() for x in range(0, tiles.shape[1])]
     for y in range(0, tiles.shape[0])]

    # reshape data; h=z_slices, w=numtiles for each z-slice
    h, w = np.shape(tiles)
    flat_tiles = np.zeros((h * w, 1, IMG_WIDTH, IMG_HEIGHT), dtype=np.float32)
    for i in range(h * w):
        flat_tiles[i] = tiles.flatten(order='C')[i].reshape(
            IMG_WIDTH, IMG_HEIGHT).slice

    # load data into pytorch data structs
    dataset = FormsDataset(flat_tiles, num_classes=NUM_CLASSES)
    hold = []
    data_loader = DataLoader(dataset, batch_size=1, shuffle=False)
    for i, images in enumerate(data_loader, 1):
        images = images.type(torch.FloatTensor)
        hold.append(images)

    # now lets perform inference on the tiles, store them in 'predictions'
    predictions = []
    for tile in hold:
        predictions.append(my_model(tile))

    # and lets time ourselves
    print("--- Inference: {} seconds ---".format(time.time() - start_time))

    ### now we have to stitch our images back together!
    unflat_predictions = np.array(predictions).reshape((h, w))
    stack_infer = []
    for z in unflat_predictions:
        stack_infer.append(
            stitch(z, IMG_WIDTH=IMG_WIDTH, IMG_HEIGHT=IMG_HEIGHT).toimage())

    stack_infer[0].save(PATH_INFER_SAVE,
                        save_all=True,
                        append_images=stack_infer[1:])

    print("--- Finish: {} seconds ---".format(time.time() - start_time))
Exemple #18
0
def uiRun(userIn):
    if (db.__contains__(userIn)):
        word = userIn

        # break into syllables
        # read from CSV and check if begins with or ends with
        toPrint = None
        fixWord = word
        with open('../database/fixes.csv') as file:
            reader = csv.reader(file, delimiter=',')
            split = ""
            for col in reader:
                fix = col[0]
                # PREFIX
                if fix.endswith("-"):
                    fix = fix.replace("-", "")
                    # print(word + " " + fix)
                    if word.startswith(fix):
                        split = fix + " - "
                        print(fix + " - ", end="")
                        fixWord = re.sub(fix, "", word, 1)
                # SUFFIX
                else:
                    fix.replace("-", "")
                    if word.endswith(fix):
                        toPrint = fix
                        fixWord = re.sub(fix, "", word)
        slicer = Slice(fixWord, 3)
        slicer.slice()
        count = 0
        for morphs in slicer.morphemes:
            if count < len(slicer.morphemes) / 2 and count != len(
                    slicer.morphemes) / 2 - 1:
                split = split + morphs + " - "
                print(morphs + " - ", end="")
            elif count < len(slicer.morphemes) / 2:
                split = split + morphs
                print(morphs)
            count += 1
        # SUFFIX ADDITION
        if not toPrint == None:
            split = split + " - " + toPrint
            print(" - " + toPrint)

        popup = Tk()
        popup.geometry("300x300")
        popup.title("Syllables")
        frame5 = Frame(popup)
        frame5.pack()
        label = Label(frame5, text=split)
        label.pack(pady=10)
        # scroll = Scrollbar(popup)
        # scroll.pack(side = RIGHT, fill = Y)
        # scroll.config(command = popup.yview)

        try:
            frame6 = Frame(popup)
            frame6.pack()

            replay = Button(frame6,
                            text="Replay",
                            command=lambda: playback(word, True))
            replay.pack(side="left", padx=5, pady=10)
            attempt = Button(
                frame6,
                text="Attempt",
                command=lambda: listen(recording, word, popup, frame7))
            attempt.pack(side="left", padx=5, pady=10)
            cancel = Button(frame6,
                            text="Cancel",
                            command=lambda: close(popup))
            cancel.pack(side="left", padx=5, pady=10)
            frame7 = Frame(popup)
            frame7.pack()
            recording = playback(word, True)

        except Exception as e:
            print(e)
            print("Audio recording does not exist for this word.")
            if not "Audio recording does not exist for this word." in split:
                split = split + " - " + "Audio recording does not exist for this word."
Exemple #19
0
 def generate_slices(self):
     s1 = Slice(self.pizza)
     s1.expand_to_valid(self.L, self.H)
     s1.expand_more(self.H)
     # s1.shrink(self.H)
     self.insert_slice(s1)
     print(s1)
     s2 = Slice(self.pizza, sr=0, sc=s1.ec + 1)
     s2.expand_to_valid(self.L, self.H)
     s2.expand_more(self.H)
     # s2.shrink(self.H)
     self.insert_slice(s2)
     s3 = Slice(self.pizza, sr=0, sc=s2.ec + 1)
     s3.expand_to_valid(self.L, self.H)
     s3.expand_more(self.H)
     # s3.shrink(self.H)
     self.insert_slice(s3)
     s4 = Slice(self.pizza, sr=0, sc=s3.ec + 1)
     s4.expand_to_valid(self.L, self.H)
     s4.expand_more(self.H)
     # s4.shrink(self.H)
     self.insert_slice(s4)
     s5 = Slice(self.pizza, sr=0, sc=s4.ec + 1)
     s5.expand_to_valid(self.L, self.H)
     s5.expand_more(self.H)
     # s5.shrink(self.H)
     self.insert_slice(s5)
     s6 = Slice(self.pizza, sr=0, sc=s5.ec + 1)
     s6.expand_to_valid(self.L, self.H)
     s6.expand_more(self.H)
     # s6.shrink(self.H)
     self.insert_slice(s6)
Exemple #20
0
def run():
    readDB()

    while (running):
        userIn = input(
            "Type the word you'd like to hear, 'filter' to filter results or 'exit' to leave the program.\n"
        )
        if (userIn == "exit"):
            sys.exit()
        elif userIn == "filter":
            filter = None
            while filter == None:
                filter = input("AZ or ZA or section ordering? ")
            if filter == "AZ":
                displayDB(1, None)
            elif filter == "ZA":
                displayDB(2, None)
            else:
                displayDB(3, filter)

        elif (db.__contains__(userIn)):
            word = userIn

            # break into syllables
            # read from CSV and check if begins with or ends with
            toPrint = None
            fixWord = word
            with open('../database/fixes.csv') as file:
                reader = csv.reader(file, delimiter=',')
                for col in reader:
                    fix = col[0]
                    if fix.endswith("-"):
                        fix = fix.replace("-", "")
                        # print(word + " " + fix)
                        if word.startswith(fix):
                            print(fix + " - ", end="")
                            fixWord = re.sub(fix, "", word, 1)
                    else:
                        fix.replace("-", "")
                        if word.endswith(fix):
                            toPrint = fix
                            fixWord = re.sub(fix, "", word)
            slicer = Slice(fixWord, 3)
            slicer.slice()
            count = 0
            for morphs in slicer.morphemes:
                if count < len(slicer.morphemes) / 2 and count != len(
                        slicer.morphemes) / 2 - 1:
                    print(morphs + " - ", end="")
                elif count < len(slicer.morphemes) / 2:
                    print(morphs)
                count += 1
            if not toPrint == None:
                print(" - " + toPrint)

            # https://pythonbasics.org/python-play-sound/
            try:
                recording = playback(word, True)
                userIn = input(
                    "Would you like to attempt the word? Y/N or would you like a repeat? R "
                )
                while (userIn == 'r'):
                    recording = playback(word, True)
                    userIn = input(
                        "Would you like to attempt the word? Y/N or would you like a repeat? R "
                    )
                if (userIn == 'y'):
                    listen1(recording, word)
                    # listen2(recording, word)
            except Exception as e:
                print(e)
                print("Audio recording does not exist for this word.")
        else:
            continue
    return
Exemple #21
0
class Game:
    def __init__(self):
        pygame.mixer.pre_init(22050, -16, 2, 1024)
        pygame.init()
        self.music = pygame.mixer.Sound(
            os.path.join(c.ASSETS_PATH, "luminary.wav"))
        self.screen = pygame.display.set_mode(c.WINDOW_SIZE)
        pygame.display.set_caption(c.GAME_NAME)
        self.clock = pygame.time.Clock()
        self.name = "WWWW"
        self.max_score = None

        self.port_on_load = get_server_port()
        self.error_message = ""

        self.slowdown = 1.0
        self.effect_slow = 1.0
        self.since_effect = 1000
        self.since_shake = 1000
        self.shake_amp = 0
        self.shake_frequency = 9
        self.shake_offset = 0
        self.score_background = pygame.image.load(
            os.path.join(c.ASSETS_PATH, "score_background.png"))
        self.title_background = pygame.image.load(
            os.path.join(c.ASSETS_PATH, "title.png"))

        self.tear_sounds = [
            pygame.mixer.Sound(os.path.join(c.ASSETS_PATH, "tear1.wav")),
            pygame.mixer.Sound(os.path.join(c.ASSETS_PATH, "tear2.wav")),
            pygame.mixer.Sound(os.path.join(c.ASSETS_PATH, "tear3.wav")),
            pygame.mixer.Sound(os.path.join(c.ASSETS_PATH, "tear4.wav"))
        ]
        self.bad_tear_sounds = [
            pygame.mixer.Sound(os.path.join(c.ASSETS_PATH, "bad_tear1.wav")),
            pygame.mixer.Sound(os.path.join(c.ASSETS_PATH, "bad_tear2.wav"))
        ]
        self.explosion = pygame.mixer.Sound(
            os.path.join(c.ASSETS_PATH, "explosion.wav"))
        self.explosion.set_volume(0.8)
        self.dash = pygame.mixer.Sound(
            os.path.join(c.ASSETS_PATH, "dashing.wav"))
        self.dash.set_volume(0.4)
        for sound in self.tear_sounds + self.bad_tear_sounds:
            sound.set_volume(0.16)
        self.nope = pygame.mixer.Sound(os.path.join(c.ASSETS_PATH, "nope.wav"))
        self.nope.set_volume(0.3)
        self.fifths = pygame.mixer.Sound(
            os.path.join(c.ASSETS_PATH, "fifths.wav"))
        self.typing = pygame.mixer.Sound(
            os.path.join(c.ASSETS_PATH, "type.wav"))
        self.bounce = pygame.mixer.Sound(
            os.path.join(c.ASSETS_PATH, "bounce_wall.wav"))
        self.bounce.set_volume(0.13)
        self.reset_sound = pygame.mixer.Sound(
            os.path.join(c.ASSETS_PATH, "reset.wav"))
        self.reset_sound.set_volume(1.5)
        self.typing.set_volume(0.7)
        self.wings_charged = pygame.mixer.Sound(
            os.path.join(c.ASSETS_PATH, "wings_charged.wav"))
        self.wings_used = pygame.mixer.Sound(
            os.path.join(c.ASSETS_PATH, "wings_used.wav"))
        self.sus = pygame.mixer.Sound(os.path.join(c.ASSETS_PATH, "sus.wav"))
        self.retry_button = Button((c.MIDDLE_X, c.MIDDLE_Y + 50),
                                   "Retry",
                                   visible=False)
        self.submit_button = Button((c.MIDDLE_X, c.MIDDLE_Y + 100),
                                    "Submit",
                                    visible=False)
        self.buttons = [self.retry_button, self.submit_button]

        self.name_input()
        self.screen.fill(c.BLACK)
        pygame.display.flip()
        start = time.time()
        while time.time() < start + 2:
            self.update_globals(0.01)
        self.music.play(-1)
        while True:
            self.title_sequence()
            result = 1
            while result == 1:
                result = self.main()

    def launch_factor_multiplier(self):
        if self.score() < 1000:
            return 1
        else:
            return min(10, (self.score() - 1000) / 4000 + 1)

    def title_sequence(self):
        self.error_message = ""
        now = time.time()
        time.sleep(0.001)
        self.phase = c.TITLE
        play = Button((c.MIDDLE_X, c.MIDDLE_Y + 100), "Play", (1, 1))
        scoreboard = Button((c.MIDDLE_X, c.MIDDLE_Y + 155), "High scores",
                            (1, 1))
        while True:
            dt = self.clock.tick(60) / 1000
            dt, events = self.update_globals(dt)
            play.update(dt, events)
            scoreboard.update(dt, events)
            self.screen.blit(self.title_background, (0, 0))
            play.draw(self.screen)
            scoreboard.draw(self.screen)
            self.draw_error_text(self.screen)
            pygame.display.flip()
            if scoreboard.clicked:
                container = []
                self.get_sprocket(container)
                if len(container):
                    self.error_message = ""
                    self.score_phase(container[0])
                    scoreboard.font_size = 40
                    scoreboard.target_font_size = 40
                    scoreboard.scale = 1.0
                else:
                    self.error_message = "No internet connection"
            if play.clicked:
                break
        black = pygame.Surface(c.WINDOW_SIZE)
        black.fill(c.BLACK)
        black.set_alpha(0)
        start = time.time()
        while True:
            dt = self.clock.tick(60) / 1000
            diff = time.time() - start
            dt, events = self.update_globals(dt)
            self.screen.blit(self.title_background, (0, 0))
            play.draw(self.screen)
            scoreboard.draw(self.screen)
            self.screen.blit(black, (0, 0))
            pygame.display.flip()

            black.set_alpha(min(255 * diff * 6, 255))
            if (255 * diff * 6) > 255:
                break

    def name_input(self):
        now = time.time()
        time.sleep(0.001)

        name_font = pygame.font.Font(
            os.path.join(c.ASSETS_PATH, "great_answer.ttf"), 70)
        prompt_font = pygame.font.Font(
            os.path.join(c.ASSETS_PATH, "great_answer.ttf"), 30)

        self.name = ""
        self.phase = c.NAME_PHASE
        continue_button = Button((c.WINDOW_WIDTH // 2, c.WINDOW_HEIGHT - 60),
                                 "continue", (5, 5),
                                 visible=False,
                                 true_scale=0.65)
        while True:
            dt = self.clock.tick(60) / 1000
            dt, events = self.update_globals(dt)
            continue_button.disabled = not len(self.name) > 0
            if self.name:
                continue_button.visible = True
            for word in c.PROFANITY:
                if word.upper() in self.name:
                    continue_button.disabled = True
            continue_button.update(dt, events)
            for event in events:
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RETURN and not continue_button.disabled:
                        continue_button.clicked = True

            self.screen.fill(c.BLACK)

            surf = prompt_font.render("Type your name", 1, (150, 150, 150))
            self.screen.blit(
                surf, (c.MIDDLE_X - surf.get_width() // 2, c.MIDDLE_Y - 85))

            name_render = name_font.render(self.name, 1, c.WHITE)
            self.screen.blit(
                name_render,
                (c.WINDOW_WIDTH // 2 - name_render.get_width() // 2,
                 c.WINDOW_HEIGHT // 2 - name_render.get_height() // 2))
            continue_button.draw(self.screen)

            if self.name and continue_button.clicked:
                break

            for event in events:
                if event.type == pygame.KEYDOWN:
                    k = pygame.key.name(event.key)
                    if k in "abcdefghijklmnopqrstuvwxyz1234567890":
                        self.name += k.capitalize()
                        if len(self.name) < 6:
                            self.typing.play()
                    if k.lower() == "backspace":
                        self.name = self.name[:-1]
            self.name = self.name[:5]
            pygame.display.flip()
        self.fifths.play()

    def tear_sound(self):
        random.choice(self.tear_sounds).play()
        self.explosion.play()

    def bad_tear_sound(self):
        random.choice(self.tear_sounds).play()

    def update_enemies(self, dt, events, n=10):
        while len(self.enemies) < n:
            if len(self.enemies) == 1:
                spacing = int(c.WINDOW_HEIGHT * 0.85)
            else:
                spacing = (c.WINDOW_HEIGHT//4) * (self.enemies[-1].y + 20000)/20000 \
                          + random.random() * c.WINDOW_HEIGHT//3 \
                          - c.WINDOW_HEIGHT//8
            if spacing > c.WINDOW_HEIGHT * 0.8:
                spacing = c.WINDOW_HEIGHT * 0.8
            padding = 60
            x = random.random()*(self.walls.width - 2 * padding) \
                       + c.MIDDLE_X \
                       - (self.walls.width - 2 * padding)/2
            y = self.enemies[-1].y + spacing
            seed = random.random()
            if self.y_offset < 2000:
                if seed < 0.3:
                    new_enemy = Enemy
                elif seed < 0.7:
                    new_enemy = BigEnemy
                else:
                    new_enemy = SmallEnemy
            elif self.y_offset < 5000:
                if seed < 0.5:
                    new_enemy = Enemy
                elif seed < 0.7:
                    new_enemy = BigEnemy
                else:
                    new_enemy = SmallEnemy
            else:
                if seed < 0.7:
                    new_enemy = Enemy
                elif seed < 0.8:
                    new_enemy = BigEnemy
                else:
                    new_enemy = SmallEnemy
            self.enemies.append(new_enemy(self, x=x, y=y))

    def loading_text(self):
        dots = int(time.time() * 2) % 3 + 1
        return f"Connecting{'.' * dots}"

    def draw_tutorial(self, surface):
        if self.y_offset > c.WINDOW_HEIGHT or self.tutorial_offset > c.WINDOW_HEIGHT:
            return
        surf = tutorial_clicked if time.time(
        ) % 1 < 0.5 else tutorial_unclicked
        surf = surf.copy().convert()
        surf.set_colorkey((255, 0, 255))
        surface.blit(surf, (c.MIDDLE_X - surf.get_width() // 2 - 30,
                            c.WINDOW_HEIGHT - surf.get_height() - 60 +
                            self.y_offset // 2 + self.tutorial_offset))

    def draw_loading_text(self, surface):
        self.loading_font = pygame.font.Font(
            os.path.join(c.ASSETS_PATH, "gothland.ttf"), 20)
        w = self.loading_font.render("Connecting.", 1, c.WHITE).get_width()
        surf = self.loading_font.render(self.loading_text(), 1, c.WHITE)
        surface.blit(surf, (c.MIDDLE_X - w // 2, c.WINDOW_HEIGHT - 30))

    def draw_error_text(self, surface):
        self.loading_font = pygame.font.Font(
            os.path.join(c.ASSETS_PATH, "gothland.ttf"), 20)
        surf = self.loading_font.render(self.error_message, 0, c.WHITE)
        if self.phase == c.GAME_PHASE:
            surf = surf.convert()
            surf.set_colorkey(c.BLACK)
            surf.set_alpha(255 - 155 * self.aimingness)
        surface.blit(
            surf, (c.MIDDLE_X - surf.get_width() // 2, c.WINDOW_HEIGHT - 30))

    def reset(self):
        self.y_offset = 0
        self.player = Player(self)
        self.walls = Walls(self)
        self.slice = Slice(self)
        self.enemies = [
            TutorialEnemy(self, y=c.WINDOW_HEIGHT / 2, x=c.MIDDLE_X)
        ]
        self.enemies[0].angle = 0
        self.update_enemies(0, [])
        self.particles = []
        self.text_particles = []
        self.background = Background(self)
        self.player.velocity = (100, 600)
        self.aiming = False
        self.aimingness = 0

        self.score_yoff = 50
        self.score_size = 40
        self.target_score_size = 40
        self.score_bumped = True

        self.shade = pygame.Surface(c.WINDOW_SIZE)
        self.shade.fill(c.BLACK)
        self.shade.set_alpha(0)

        self.shade_2 = pygame.Surface(c.WINDOW_SIZE)
        self.shade.fill(c.BLACK)
        self.shade_2.set_alpha(0)

        self.shade_3 = pygame.Surface(c.WINDOW_SIZE)
        self.shade.fill(c.BLACK)
        self.shade_3.set_alpha(255)

        self.flare = pygame.Surface(c.WINDOW_SIZE)
        self.flare.fill((255, 226, 140))
        self.flare.set_alpha(0)
        self.flare_alpha = 0

        self.multiplier = 1

        self.queue_reset = False

        self.game_end = False

        self.retry_button.visible = False
        self.submit_button.visible = False
        self.closing = False
        self.freeze_surf = None

        for button in self.buttons:
            button.disabled = False

        self.error_message = ""
        self.tutorial = True
        self.tutorial_offset = 0

    def update_tutorial(self, dt, events):
        if not self.tutorial:
            return
        if self.player.y > 150 and self.player.velocity[
                1] >= 0 or self.player.y > 60 and self.player.velocity[1] <= 0:
            self.aiming = True
            self.tutorial = False

    def update_effects(self, dt, events):
        if self.max_score is not None and self.score() > self.max_score:
            self.error_message = "NEW HIGH SCORE"
        self.music.set_volume(0.8 - 0.6 * self.aimingness)

        if self.player_is_dead():
            self.aiming = False
            self.tutorial_offset += dt * 750

        if self.queue_reset and self.player_is_dead():
            self.retry_button.visible = True
            self.submit_button.visible = True

        self.since_effect += dt
        if self.since_effect > 0:
            self.effect_slow = 1.0
        else:
            self.effect_slow = 0.01

        self.since_shake += dt
        self.shake_offset = self.shake_amp * math.cos(
            self.since_shake * self.shake_frequency * 2 * math.pi)
        self.shake_amp *= 0.2**dt
        self.shake_amp = max(self.shake_amp - 200 * dt, 0)

        self.flare_alpha *= 0.7**dt
        self.flare_alpha -= 300 * dt
        self.flare_alpha = max(0, self.flare_alpha)
        self.flare.set_alpha(self.flare_alpha)

        if not self.queue_reset:
            if self.score() % 1000 < 500 and not self.score_bumped:
                self.score_bumped = True
                self.score_size = 120
                self.sus.play()
            if self.score() % 1000 > 500 and self.score_bumped:
                self.score_bumped = False

        ds = self.target_score_size - self.score_size
        if ds > 0:
            self.score_size = min(self.score_size + ds * 5 * dt,
                                  self.target_score_size)
        else:
            self.score_size = max(self.score_size + ds * 5 * dt,
                                  self.target_score_size)

        if self.queue_reset:
            self.target_score_size = 80
            dy = c.MIDDLE_Y - self.score_yoff
            self.score_yoff = min(self.score_yoff + dy * 5 * dt,
                                  c.MIDDLE_Y - 100)

    def score(self):
        if not self.phase == c.GAME_PHASE:
            return -1
        return int(self.y_offset // 10)

    def draw_score(self):
        text = f"{self.score()}"
        self.score_font = pygame.font.Font(
            os.path.join(c.ASSETS_PATH, "no_continue.ttf"),
            int(self.score_size))
        surf = self.score_font.render(text, 0, c.WHITE)
        surf2 = self.score_font.render(text, 0, c.BLACK)
        x = c.MIDDLE_X - surf.get_width() // 2
        y = self.score_yoff

        mpos = pygame.mouse.get_pos()
        padding = 35
        inner_padding = 12
        dx = max(x - mpos[0], mpos[0] - x - surf.get_width())
        dy = max(y - mpos[1], mpos[1] - y - surf.get_height())
        small_alpha = 80
        if dx < inner_padding and dy < inner_padding:
            if self.aiming:
                surf.set_alpha(small_alpha)
                surf2.set_alpha(small_alpha)
        elif dx < padding + inner_padding and dy < padding + inner_padding:
            diff = padding - (max(dx, dy) - inner_padding)
            if self.aiming:
                small_alpha = 255 - (255 - small_alpha) * (diff / padding)
                surf.set_alpha(small_alpha)
                surf2.set_alpha(small_alpha)

        self.screen.blit(surf2, (x, y + self.score_size // 10))
        self.screen.blit(surf, (x, y))

    def slowdown_effect(self, duration=0.4):
        self.since_effect = -duration

    def shake_effect(self, amplitude=20):
        if amplitude < self.shake_amp:
            return
        self.since_shake = 0
        self.shake_amp = max(amplitude, self.shake_amp)

    def update_offset(self, dt, events):
        max_off = c.WINDOW_HEIGHT * 0.7
        if self.player.y > self.y_offset + max_off and type(
                self.enemies[0]) is not TutorialEnemy:
            self.y_offset = self.player.y - max_off

    def update_aim(self, dt, events):
        speed = 7
        da = self.aiming - self.aimingness
        self.aimingness += h.sign(da) * dt * speed
        if self.aimingness > 1:
            self.aimingness = 1
        elif self.aimingness < 0:
            self.aimingness = 0

        self.shade.set_alpha(128 * self.aimingness)
        self.slowdown = 1 - 0.95 * self.aimingness

    def draw_shade(self):
        self.screen.blit(self.shade, (0, 0))

    def flare_up(self, amt):
        self.flare_alpha = amt

    def game_to_screen_y(self, y):
        return c.WINDOW_HEIGHT - y + self.y_offset

    def game_position_to_screen_position(self, pos):
        x = pos[0] + self.shake_offset
        y = self.game_to_screen_y(pos[1]) + self.shake_offset
        return x, y

    def screen_position_to_game_position(self, pos):
        x = pos[0]
        y = c.WINDOW_HEIGHT - pos[1] + self.y_offset
        return x, y

    def mouse_position(self):
        mpos = pygame.mouse.get_pos()
        return self.screen_position_to_game_position(mpos)

    def main(self):
        self.reset()
        self.phase = c.GAME_PHASE

        then = time.time()
        self.clock.tick(c.MAX_FPS)
        time.sleep(0.001)
        since_print = 0
        fpss = []

        while True:
            now = time.time()
            rdt = now - then
            if rdt > 1 / 30: rdt = 1 / 30
            then = now
            since_print += rdt
            fpss.insert(0, 1 / rdt)
            fpss = fpss[:100]
            # if since_print > 1.0:
            #     since_print = 0
            #     print(f"FPS: {sum(fpss)/len(fpss)}")

            # Do things
            dt, events = self.update_globals(rdt)
            self.update_tutorial(dt, events)
            if self.queue_reset:
                new_alpha = self.shade_2.get_alpha() + 500 * dt
                self.shade_2.set_alpha(min(new_alpha, 160))
            for button in self.buttons:
                button.update(rdt, events)
            self.slice.update(rdt, events)
            self.update_effects(rdt, events)
            self.player.update(dt, events)
            self.walls.update(dt, events)
            self.background.update(dt, events)
            self.update_aim(dt, events)
            self.update_offset(dt, events)
            self.update_enemies(dt, events)
            for enemy in self.enemies[::-1]:
                enemy.update(dt, events)
            for particle in self.particles[::-1]:
                particle.update(dt, events)
            for particle in self.text_particles[::-1]:
                particle.update(rdt, events)

            # Draw things
            # self.screen.fill((150, 150, 150))
            self.background.draw(self.screen)
            for particle in self.particles:
                particle.draw(self.screen)
            if self.shade.get_alpha() > 0:
                self.draw_shade()
            for enemy in self.enemies:
                enemy.draw(self.screen)
            self.walls.draw(self.screen)
            for particle in self.text_particles:
                particle.draw(self.screen)
            if self.flare_alpha > 0:
                self.screen.blit(self.flare, (0, 0))
            if self.aiming:
                self.slice.draw(self.screen)
            self.player.draw(self.screen)
            if self.queue_reset:
                self.screen.blit(self.shade_2, (0, 0))
            if self.submit_button.clicked:
                self.freeze_surf = self.screen.copy()
            self.draw_score()
            for button in self.buttons:
                button.draw(self.screen)
            self.draw_error_text(self.screen)
            self.draw_tutorial(self.screen)
            if self.shade_3.get_alpha() > 0:
                self.screen.blit(self.shade_3, (0, 0))
            self.update_screen()

            # Other things?
            if self.submit_button.clicked:
                self.error_message = ""
                status = self.submit_score()
                for button in self.buttons:
                    button.disabled = False
                if status == c.SCORE_RECEIVED:
                    return 0
                elif status == c.NO_CONNECT:
                    self.submit_button.clicked = False
                    self.error_message = "No Internet connection"
                elif status == c.TIMEOUT:
                    self.submit_button.clicked = False
                    self.error_message = "Server timed out"
            if self.retry_button.clicked:
                self.retry_button.clicked = False
                self.closing = True
                self.reset_sound.play()
            if self.closing:
                new_alpha = self.shade_3.get_alpha() + 1000 * dt
                self.shade_3.set_alpha(min(new_alpha, 255))
                if self.shade_3.get_alpha() == 255:
                    return 1
            else:
                new_alpha = self.shade_3.get_alpha() - 1000 * dt
                self.shade_3.set_alpha(max(new_alpha, 0))

            self.clock.tick(c.MAX_FPS)

    def update_globals(self, dt):
        events = pygame.event.get()
        if self.phase == c.GAME_PHASE and self.player.y < self.y_offset - 100:
            self.player.test_wings()
        if self.phase == c.GAME_PHASE and self.player_is_dead():
            self.queue_reset = True
        for event in events:
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit(0)
            if event.type == pygame.MOUSEBUTTONUP and self.phase == c.GAME_PHASE:
                if event.button == 1:  # 1 is left click
                    self.player.dash_toward(self.mouse_position(), 300)
                    self.aiming = False
                    self.aimingness = 0
            if event.type == pygame.MOUSEBUTTONDOWN and self.phase == c.GAME_PHASE and not self.player.cutting and not self.queue_reset:
                if event.button == 1:
                    self.shade_target_alpha = 100
                    self.aiming = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r and self.phase == c.GAME_PHASE:
                    self.queue_reset = True
        return dt * min(self.slowdown, self.effect_slow), events

    def update_screen(self):
        pygame.display.flip()

    def player_is_dead(self):
        return self.player.y < self.y_offset - 50 and not self.player.flying and not self.player.has_wings

    def get_sprocket(self, container):
        try:
            port = get_server_port()
            if not port:
                return
            sprocket = Sprocket(c.SERVER_ADDR, port)
            container.append(sprocket)
        except Exception as e:
            print(e)

    def submit_score(self):
        name = self.name
        container = []
        threading.Thread(target=self.get_sprocket,
                         args=(container, ),
                         daemon=True).start()
        age = 0
        while not container:
            dt = self.clock.tick(60) / 1000
            age += dt
            if age > c.TIMEOUT_TIME:
                return c.TIMEOUT
            if threading.active_count() == 1 and not container:
                return c.NO_CONNECT
            self.screen.blit(self.freeze_surf, (0, 0))
            self.draw_score()
            for button in self.buttons:
                button.disabled = True
                button.update(dt, [])
                button.draw(self.screen)
            self.draw_loading_text(self.screen)
            self.update_globals(dt)
            pygame.display.flip()
        sprocket = container[0]
        sprocket.send(type="push", score=self.score(), name=name)
        result = []
        age = 0
        do_break = False
        while not do_break:
            dt = self.clock.tick(60) / 1000
            age += dt
            self.update_globals(dt)
            if age > c.TIMEOUT_TIME:
                return c.TIMEOUT
            result += sprocket.get()
            for packet in result:
                if packet.has("success") and packet.success:
                    do_break = True
        return self.score_phase(sprocket)

    def draw_scoreboard(self, surface, scoreboard):
        size = 30
        font = pygame.font.Font(os.path.join(c.ASSETS_PATH, "no_continue.ttf"),
                                size)
        scores = scoreboard.data
        spacing = int(1.25 * size)
        x = int(c.WINDOW_WIDTH * 0.55)
        y = int(c.WINDOW_HEIGHT - (size * 10 + (spacing - size) * 9)) // 2 + 50
        green = (60, 210, 100)
        shadow_offset = 3
        self.max_score = scores[9].score
        for item in scores[:10]:
            if item.name == self.name and item.score == self.score():
                color = green
                green = c.WHITE
            else:
                color = c.WHITE
            name = item.name[:5]
            space = ""
            width = 225
            text = f"{name}:"
            surfb = font.render(text, 1, c.BLACK)
            surf = font.render(text, 1, color)
            surface.blit(surfb, (x, y + shadow_offset))
            surface.blit(surf, (x, y))
            surf2 = font.render(f"{item.score}", 1, color)
            surf2b = font.render(f"{item.score}", 1, c.BLACK)
            surface.blit(surf2b,
                         (x + width - surf2.get_width(), y + shadow_offset))
            surface.blit(surf2, (x + width - surf2.get_width(), y))

            y += spacing

    def score_phase(self, sprocket):
        age = 0
        alpha = 255
        self.freeze_surf = self.screen.copy().convert()
        sprocket.send(type="print")
        result = []
        has_result = False
        while alpha > 0 or not has_result:
            dt = self.clock.tick(60) / 1000
            age += dt
            self.screen.fill(c.BLACK)
            alpha = max(0, 255 - age * 900)
            self.freeze_surf.set_alpha(alpha)
            self.screen.blit(self.freeze_surf, (0, 0))
            self.update_globals(dt)

            pygame.display.flip()

            result += sprocket.get()
            for packet in result:
                if packet.has("scores"):
                    scoreboard = packet.scores
                    has_result = True
        shade = pygame.Surface(c.WINDOW_SIZE)
        shade.fill(c.BLACK)
        shade.set_alpha(255)
        age = 0
        back_button = Button((140, c.WINDOW_HEIGHT - 100),
                             "back", (50, 50),
                             visible=True)
        buttons = [back_button]
        while True:
            dt = self.clock.tick(60) / 1000
            age += dt
            _, events = self.update_globals(dt)
            for button in buttons:
                button.update(dt, events)

            shade.set_alpha(255 - min(255, age * 900))
            self.screen.blit(self.score_background, (0, 0))
            self.draw_scoreboard(self.screen, scoreboard)
            for button in buttons:
                button.draw(self.screen)
            self.screen.blit(shade, (0, 0))
            pygame.display.flip()

            if back_button.clicked:
                return c.SCORE_RECEIVED
Exemple #22
0
def fill_runner(af):
    """Produces slices from airfoils. Used for parallell computation."""
    return Slice.from_airfoil(af)
    def generate_image(self):
        while not self.__stopped:
            if not self.__data_available:
                time.sleep(0.1)
                continue

            with self.__curr_vals_lock:
                contour_msg = self.__curr_msg
                self.__data_available = False

            max_dist = contour_msg.max_dist
            slice_size = contour_msg.slice_size
            centroid = Point2D(contour_msg.centroid.x, contour_msg.centroid.y)
            all_points = [Point2D(p.x, p.y) for p in contour_msg.all_points]
            nearest_points = [Point2D(p.x, p.y) for p in contour_msg.nearest_points]

            # Initialize plot
            plt.figure(figsize=(8, 8), dpi=80)
            plt.grid(True)

            # Plot robot center
            plt.plot([0], [0], 'r^', markersize=8.0)

            # Plot centroid and write heading
            if self.__plot_centroid or self.__plot_all:
                c = Point2D(centroid.x, centroid.y)
                plt.title("Heading: {} Distance: {}".format(c.heading, round(c.origin_dist, 2)))
                plt.plot([centroid.x], [centroid.y], 'g^', markersize=8.0)

            # Plot point cloud
            if self.__plot_points or self.__plot_all:
                plt.plot([p.x for p in all_points], [p.y for p in all_points], 'ro', markersize=2.0)

            # Plot contour
            if self.__plot_contour or self.__plot_all:
                nearest_with_origin = [Origin] + nearest_points + [Origin]
                icx = [p.x for p in nearest_with_origin]
                icy = [p.y for p in nearest_with_origin]
                plt.plot(icx, icy, 'b-')
                plt.plot(icx, icy, 'go', markersize=4.0)

            # Plot slices
            if self.__plot_slices or self.__plot_all:
                slices = [Slice(v, v + slice_size) for v in range(0, 180, slice_size)]
                linestyle = 'r:'
                for s in slices:
                    plt.plot([s.begin_point(max_dist).x, 0], [s.begin_point(max_dist).y, 0], linestyle)
                plt.plot([slices[-1].end_point(max_dist).x, 0], [slices[-1].end_point(max_dist).y, 0], linestyle)

            # Plot axis
            dist = max_dist * self.__max_axis_mult
            plt.axis([-1 * dist, dist, - 0.05, dist])

            if self.__image_server is not None:
                sio = cStringIO.StringIO()
                plt.savefig(sio, format="jpg")
                self.__image_server.image = sio.getvalue()
                sio.close()
            else:
                plt.show()

            # Close resources
            plt.close()
Exemple #24
0
def gen_slices(net_top, num_slice=3):
    Slice.set_num_slice(num_slice)
    slices = {}
    for i in tqdm(range(num_slice), desc='Generating ' + str(num_slice) + ' slices'):
        slices[i] = Slice(net_top)
    return slices