示例#1
0
def main(window):
    # shortcuts for callbacks
    jump_callback = lambda event: move(event, frog, window.width, window.height)
    move_callback = lambda event: move(event, frog, window.width, window.height, draw=True)
    turn_callback = lambda event: move(event, frog, window.width, window.height, turnonly=True)

    # create a new frog
    frog = Frog(window)
    frog.shape = 'frog'
    frog.bodycolor = 'green'

    # let the frog jump and turn it, if necessary
    window.listen('<Key-Up>', jump_callback)
    window.listen('<Key-Down>', jump_callback)
    window.listen('<Key-Left>', jump_callback)
    window.listen('<Key-Right>', jump_callback)

    # move the frog and turn it, if necessary
    window.listen('<Shift-Key-Up>', move_callback)
    window.listen('<Shift-Key-Down>', move_callback)
    window.listen('<Shift-Key-Left>', move_callback)
    window.listen('<Shift-Key-Right>', move_callback)

    # turn the frog without moving it
    window.listen('<Control-Key-Up>', turn_callback)
    window.listen('<Control-Key-Down>', turn_callback)
    window.listen('<Control-Key-Left>', turn_callback)
    window.listen('<Control-Key-Right>', turn_callback)

    # "write" a dot with space
    window.listen('<space>', lambda event: frog.dot())

    # you can quit the game by clicking `q` or [Esc]
    window.listen('<Key-Escape>', lambda e: window.quit())
    window.listen('<Key-q>', lambda e: window.quit())
示例#2
0
    def morph_counts_new_version(self, words):
        #Word List to list of all morphisms
        frog = Frog(FrogOptions(tok=True, lemma=True, morph=True, daringmorph=False, mwu=False, chunking=False, ner=False,parser=False))
        words_string = ' '.join(words)
        morphisms = []
        print_counter = 1
        t0 = time.time()
        print("Starting Frog Processing..")
        output = frog.process(words_string)
        print("Process time:")
        process_time = self.format_time(time.time() - t0)
        print(process_time)
        t1 = time.time()
        for i in range(0,len(words)-1):
            morphisms_word = output[i].get("morph")
            morphisms_word_list = morphisms_word.replace('[', '').split(']')
            #Momenteel GEEN GEHELE WOORDEN IN COUNT
            if len(morphisms_word_list) > 2:
                morphisms += morphisms_word_list
            total_length = len(words)
            print(str(print_counter) + " of " + str(total_length))
            print_counter += 1
        print("Process Time:")
        print(process_time)
        print("Getting Morphisms Time:")
        print(self.format_time(time.time() - t1))
        print("Total Time:")
        print(self.format_time(time.time() - t0))



        morphisms = list(filter(None, morphisms))
        morph_counts = Counter(morphisms)
        return morph_counts
示例#3
0
    def __init__(self, width, height, controller, weightIndex=None):
        self.justDied = False
        self.forceUpdate = False
        self.weightIndex = weightIndex
        self.localTrainMode = TRAIN_MODE or GATHER_STATS  # start in train mode if GATHER_STATS
        self.setUpdateIntervals(self.localTrainMode)
        self.width = width
        self.height = height
        self.boardHeight = int(1.5 * height)  # buffers 50% of board
        self.player = Frog(int(width / 2), int(height - 1))
        self.controller = controller
        self.controller.loadWeights()
        self.rowOptions = 2 * ["SAFE"] + 10 * ["ROAD"] + ["RIVER"]

        # open logging file
        if GATHER_STATS:
            self.logfile = open('log.txt', 'w')
            self.logfile.write("TRAINING DATA FOR " +
                               self.controller.id.upper() + " USING " +
                               FEATURE_EXTRACTOR.__name__.upper() + "\n")

        # initialize game
        self.startNewGame()

        # for drawing
        self.surf = pygame.display.set_mode(
            (self.width * BLOCK_SIZE, self.height * BLOCK_SIZE),
            pygame.HWSURFACE)
        pygame.font.init()
        self.score_font = pygame.font.SysFont("monospace", 20)

        # set game to running
        self.running = True
示例#4
0
def play_game(screen):
    frog = Frog(FROG_IMAGE)

    cars = create_cars()
    cars_2 = create_cars()
    cars.extend(cars_2)

    score = Display(color='white', x=-450, y=350)
    game_over = Display('white', 0, 0)

    while True:
        score.display_score(frog.lvl)

        for car in cars:
            car.forward(car.speed)
            frog.move(screen)
            teleport(car)

            if (frog.frog_passed_lvl(LIMIT_UP)):
                random_car = random.choice(cars)
                random_car.speed += 1

                change_car_positions(cars)
            if car.run_over_frog(frog):
                game_over.display_game_over()
                return

        screen.update()
        time.sleep(0.01)
    def morph_counts_old_version(self, words):
        #Word List to list of all morphisms
        print("len words: ")
        print(len(words))
        print("len unique words: ")
        print(len(set(words)))
        frog = Frog(
            FrogOptions(tok=True,
                        lemma=True,
                        morph=True,
                        daringmorph=False,
                        mwu=False,
                        chunking=False,
                        ner=False,
                        parser=False))
        morphisms = []
        print_counter = 1
        t0 = time.time()
        for word in words:
            output = frog.process(word)
            morphisms_word = output[0].get("morph")
            morphisms_word_list = morphisms_word.replace('[', '').split(']')
            #Momenteel GEEN GEHELE WOORDEN IN COUNT
            if len(morphisms_word_list) > 2:
                morphisms += morphisms_word_list
            total_length = len(words)
            print(str(print_counter) + " of " + str(total_length))
            print_counter += 1
        print("Frog Processing Time:")
        print(self.format_time(time.time() - t0))

        morphisms = list(filter(None, morphisms))
        morph_counts = Counter(morphisms)
        return morph_counts
示例#6
0
def prep_nl(df, filename):
    from frog import Frog, FrogOptions

    print("Tokenizing, POS tagging, and lemmatizing the Dutch data...")

    # Create 'frog' instance. Turn off various options to save time.
    frog = Frog(
        FrogOptions(parser=False, morph=False, chunking=False, ner=False))

    # Define set of possible answers
    if not "STAT_C" in str(filename):
        answers = ['Answer']
    elif "STAT_C" in str(filename):
        answers = ['Answer4a', 'Answer2aDec', 'Answer2aCaus']

    # Loop through answers
    for question_type in answers:

        for index in df.index:
            ans = df.loc[index, question_type]

            # Logging
            if index % 20 == 0:
                print(index, "/", df.index[-1], question_type[6:])

            # Remove numbers
            ans = re.sub("\d+", "", ans)

            # Remove tags in spelling-corrected data
            ans = ans.replace("_abbreviation", "")

            # Remove non-Dutch and illegible words
            ans = re.sub("\w+_nonexistent", "", ans)
            ans = re.sub("\w+_nonexisting", "", ans)
            ans = re.sub("\w+_english", "", ans)
            ans = re.sub("\w+_german", "", ans)
            ans = re.sub("\?+_illegible", "", ans)

            # Preprocess the data with Frog
            ans_dict = frog.process(ans)

            tok_answer = []
            lem_answer = []
            pos_tags = []

            # Append outcomes to list
            for word_index in range(len(ans_dict)):
                if ans_dict[word_index][
                        'pos'] != "LET()":  # Exclude punctuation
                    tok_answer.append(ans_dict[word_index]['text'].lower())
                    lem_answer.append(ans_dict[word_index]['lemma'])
                    pos_tags.append(ans_dict[word_index]['pos'])

            # Fill in the dataframe
            df.at[index, 'Tokenized{}'.format(question_type[6:])] = tok_answer
            df.at[index, 'Lemmatized{}'.format(question_type[6:])] = lem_answer
            df.at[index, 'POS{}'.format(question_type[6:])] = pos_tags

    return df
示例#7
0
    def morph_counts_faster_version(self, words):
        #Word List to list of all morphisms

        frog = Frog(FrogOptions(tok=True, lemma=True, morph=True, daringmorph=False, mwu=False, chunking=False, ner=False,parser=False))
        batch_size = 400
        morphisms = []
        print_batch_number = 1
        start_time = time.time()
        total_batch_number = math.ceil(len(words)/batch_size)
        total_process_time = 0
        total_getting_morphisms_time = 0
        for i in range(0, len(words), batch_size):
            t0 = time.time()
            #print_counter = 1
            words_batch = words[i:i + batch_size]
            words_batch_string = ' '.join(words_batch)
            #print("Starting Frog Processing.. for batch = " + str(print_batch_number))
            output = frog.process(words_batch_string)
            #print("Process time:")
            process_time = time.time() - t0
            #print(self.format_time(process_time))
            #print(process_time)
            t1 = time.time()
            for j in range(0,len(words_batch)-1):
                morphisms_word = output[j].get("morph")
                morphisms_word_list = morphisms_word.replace('[', '').split(']')
                #Momenteel GEEN GEHELE WOORDEN IN COUNT
                if len(morphisms_word_list) > 2:
                    morphisms += morphisms_word_list
                total_batch_length = len(words_batch)
                #print(str(print_counter) + " of " + str(total_batch_length) + " -- of batch -- " + str(print_batch_number) + " of " + str(total_batch_number) )
                #print("batch" + " (batch_size: " + str(batch_size) + " words):    " +  str(print_batch_number) + " of " + str(total_batch_number))
                #print_counter += 1
            print_batch_number += 1
            getting_morphisms_time = time.time() - t1
            total_process_time += process_time
            total_getting_morphisms_time += getting_morphisms_time

        print("Total number of words: ")
        print(len(words))
        print("")
        print("Unique number words: ")
        print(len(set(words)))
        print("")
        print("Total Process Time:")
        print(self.format_time(total_process_time))
        print("")
        print("Total Getting Morphisms Time: ")
        print(self.format_time(total_getting_morphisms_time))
        print("")
        print("Total Time:")
        print(self.format_time(time.time() - start_time))
        print("")

        morphisms = list(filter(None, morphisms))
        morph_counts = Counter(morphisms)
        return morph_counts
示例#8
0
 def test_get_range_circle_returns_circle_of_correct_size(self):
     # arrange
     position = Point(2, 2)
     max_jump = 3
     frog = Frog(position, 3, 0)
     # act
     range_circle = frog.get_range_circle()
     # assert
     assert range_circle.radius == max_jump
示例#9
0
 def test_find_possible_lilly_pads_returns_empty_list_when_none_are_available(
         self):
     # arrange
     position = Point(20, 20)
     frog = Frog(position, 1, 0)
     pad = LillyPad(Point(2, 4), 1)
     # act
     possible_pads = frog._find_possible_lilly_pads([pad])
     # assert
     assert len(possible_pads) == 0
示例#10
0
    def __populate(self):
        self.pop = [ Frog(function=self.ff,
                        constraints=self.constraints)
                        for i in range(self.n)]

        for idx, f in enumerate(self.pop):
            while f.current_fit.ret == 0:
                f = Frog(function=self.ff,
                        constraints=self.constraints)
            self.pop[idx] = f
示例#11
0
 def test_find_possible_pads_returns_no_pads_if_nearby_pad_occupied(self):
     # arrange
     position = Point(2, 2)
     frog = Frog(position, 5, 0)
     pad = LillyPad(Point(2, 4), 1)
     pad.currently_occupied = True
     # act
     possible_pads = frog._find_possible_lilly_pads([pad])
     # assert
     assert len(possible_pads) == 0
示例#12
0
 def test_move_to_lilly_pad_updates_frog_current_lilly_pad(self):
     # arrange
     mock_pad = mock.create_autospec(LillyPad)
     mock_pad.circle = Circle(Point(0, 0), 3)
     position = Point(2, 2)
     frog = Frog(position, 1, 0)
     # act
     frog._move_to_lilly_pad(mock_pad)
     # assert
     assert frog.current_lilly_pad == mock_pad
示例#13
0
 def test_find_possible_lilly_pads_returns_list_of_lilly_pads_when_some_are_available(
         self):
     # arrange
     position = Point(2, 2)
     frog = Frog(position, 1, 0)
     pad = LillyPad(Point(2, 4), 1)
     # act
     possible_pads = frog._find_possible_lilly_pads([pad])
     # assert
     assert pad in possible_pads
示例#14
0
 def test_move_to_lilly_pad_calls_lilly_pad_visit_method(self):
     # arrange
     mock_pad = mock.create_autospec(LillyPad)
     mock_pad.circle = Circle(Point(0, 0), 3)
     position = Point(2, 2)
     frog = Frog(position, 1, 0)
     # act
     frog._move_to_lilly_pad(mock_pad)
     # assert
     assert mock_pad.visit.called
示例#15
0
 def test_move_to_lilly_pad_calls_leave_on_current_lilly_pad(self):
     # arrange
     mock_current_pad = mock.create_autospec(LillyPad)
     mock_dest_pad = mock.create_autospec(LillyPad)
     mock_dest_pad.circle = Circle(Point(0, 0), 3)
     position = Point(2, 2)
     frog = Frog(position, 1, 0)
     frog.current_lilly_pad = mock_current_pad
     # act
     frog._move_to_lilly_pad(mock_dest_pad)
     # assert
     assert mock_current_pad.leave.called
示例#16
0
 def test_find_centre_lilly_pad_returns_lilly_pad_where_centre_is_true(
         self):
     # arrange
     frog = Frog(Point(2, 2), 3, 0)
     pad1 = mock.create_autospec(LillyPad)
     pad1.centre_pad = False
     pad2 = mock.create_autospec(LillyPad)
     pad2.centre_pad = True
     # act
     centre_pad = frog._find_centre_lilly_pad([pad1, pad2])
     # assert
     assert centre_pad == pad2
示例#17
0
def change_text_to_morphs(sentences,
                          frog_merge=False,
                          save=False,
                          filename=None):
    # sentence list to sentence list in frog morphism form
    morphSentences = []

    frog = Frog(
        FrogOptions(tok=True,
                    lemma=True,
                    morph=True,
                    daringmorph=False,
                    mwu=False,
                    chunking=False,
                    ner=False,
                    parser=False))

    for sentenceNumber in range(0, len(sentences)):
        print(sentenceNumber)
        print("of")
        print(len(sentences))
        sentenceToBeProcessed = sentences[sentenceNumber]
        sentenceToBeProcessed = sentenceToBeProcessed.replace("\n", " ")
        morphSentence = []
        output = frog.process(sentenceToBeProcessed)
        for i in range(0, len(output)):
            morphisms_word = output[i].get("morph")
            morphisms_word_list = morphisms_word.replace('[', '').split(']')
            if frog_merge:
                morphisms_word_list = list(filter(None, morphisms_word_list))
                morphisms_word_list = intersperse(morphisms_word_list,
                                                  "insertmergetoken")
                #print(morphisms_word_list)
            #print("EVET")
            #print(morphisms_word_list)
            morphSentence += morphisms_word_list
        #print("MORPHSENTENCE")
        #print(morphSentence)
        # Remove the empty strings
        morphSentence = list(filter(None, morphSentence))
        #print("ok")
        #print(morphSentence)
        morphSentence = ' '.join(morphSentence)
        #print("HERE")
        #print(morphSentence)
        morphSentences.append(morphSentence)

    if save is True:
        with open(filename, 'wb') as outputfile:
            pickle.dump(morphSentences, outputfile)
    return morphSentences
def change_text_to_morphs(sentences,
                          frog_merge=False,
                          save=False,
                          filename=None):
    # sentence list to sentence list in frog morphism form
    morphSentences = []

    frog = Frog(
        FrogOptions(tok=True,
                    lemma=True,
                    morph=True,
                    daringmorph=False,
                    mwu=False,
                    chunking=False,
                    ner=False,
                    parser=False))
    j = 0
    for sentenceToBeProcessed in sentences:

        if j % 1000 == 0:
            print(j + 1)
            print("of")
            print(len(sentences))

        j += 1
        sentenceToBeProcessed = sentenceToBeProcessed.rstrip('\n')
        morphSentence = []
        output = frog.process(sentenceToBeProcessed)

        for i in range(0, len(output)):
            morphisms_word = output[i].get("morph")
            morphisms_word_list = morphisms_word.replace('[', '').split(']')
            if frog_merge:
                morphisms_word_list = list(filter(None, morphisms_word_list))
                morphisms_word_list = intersperse(morphisms_word_list,
                                                  "__add_merge__")

            morphSentence += morphisms_word_list

        # Remove the empty strings
        morphSentence = list(filter(None, morphSentence))

        morphSentence = ' '.join(morphSentence)
        morphSentences.append(morphSentence)

    if save is True:
        with open(filename, 'wb') as outputfile:
            pickle.dump(morphSentences, outputfile)
    return morphSentences
示例#19
0
def main():
    app = QApplication(sys.argv)
    frog = Frog(Point(900, 300))
    level = Level(5, Point(100, 100), Point(700, 700))
    game = Game(frog, level)
    a = MainGame(1700, 1000, game)
    sys.exit(app.exec_())
示例#20
0
    def __evolve(self, sub):
        xb = sub[0]
        xw = sub[-1]
        xs = self.pop[0]
        r = np.random.uniform(0, 1)

        # Try to learn from local best
        xt = xb - xw
        xt.p = xw.p + r * (xt.p)
        if (xt.current_fit.ret > xw.current_fit.ret):
            sub[-1] = xt
            return sub

        else:
            # Try to learn from local best
            xt = xs - xw
            xt.p = xw.p + r * (xt.p)
            if (xt.current_fit.ret > xw.current_fit.ret):
                sub[-1] = xt
                return sub
            
            else:
                # Randomize the worst frog in the submemeplex
                sub[-1] = Frog(self.ff, self.constraints)
                return sub
示例#21
0
class FrogTagger(TaggerI):
    def __init__(self, **kwargs):
        # Disable multiword recognition, which is performed by the chunker
        options = FrogOptions(parser=False, mwu=False, xmlIn=True, **kwargs)
        self.__frog = Frog(options)

    def tag(self, sentences):

        if isinstance(sentences, list):
            doc = folia.Document(id='nltk-sentence')
            folia_sent = doc.add(folia.Text)
            for sent in sentences:
                folia_sent.add(folia.Word, sent)
            _input = doc
        else:
            _input = sentences
        self.__output = self.__frog.process(_input)
        return [(token['text'], token['pos'].split('(')[0])
                for token in self.__output]

    def get_tag_probabilities(self):
        if self.__output is None:
            return []
        return [(token['text'], token['posprob']) for token in self.__output]

    def get_lemmas(self):
        if self.__output is None:
            return []
        return [(token['text'], token['lemma']) for token in self.__output]

    def get_morph(self):
        if self.__output is None:
            return []
        return [(token['text'], token['morph']) for token in self.__output]
示例#22
0
class AbstractFrogChunker(ChunkParserI):

    _frog = None

    def __init__(self, **kwargs):
        self._frog = Frog(FrogOptions(parser=False, mwu=False, tok=False, xmlIn=True, **kwargs))

    def __get_folia_doc__(self, tokens):
        doc = folia.Document(id='nltk-sentence')
        folia_sent = doc.add(folia.Text)
        for tok, pos in tokens:
            word = folia_sent.add(folia.Word, tok)
            word.add(folia.PosAnnotation(None, set='custom', cls=pos))
        return doc

    def __create_tree__(self, tokens, key):
        _input = self.__get_folia_doc__(tokens)
        __output = self._frog.process(_input)
        for token in __output:
            token['pos'] = token['pos'].split('(')[0]
            if token['pos'].startswith('SPEC'):
                token['pos'] = 'NNP'
        return conlltags2tree([(token['text'], token['pos'], token[key]) for token in __output ])

    def parse(self, tokens):
        raise NotImplementedError()
示例#23
0
def generate_dataset(
    N=100,
    sigma=0.1,
    mu=0,
    balanced_sample=True,  # equal number of each class
    p=[1. / 5] * 5,  # for multinomial distribution of classes
    datapath="/home/joel/datasets/csi5138-img/dataset1"
):  # do not add trailing /

    for i in range(N):
        if balanced_sample:
            c = i % 5
        else:
            c = np.random.multinomial(1, p)  # choose class from distribution p
            c = np.argmax(c)
        # construct vector of N(mu, sigma**2)
        var = sigma * np.random.randn(5) + mu
        # no switch statement in Python?#yes noswitch statement in python
        if c == 0:
            obj = Dog(*var)
        elif c == 1:
            obj = Truck(*var)
        elif c == 2:
            obj = Airplane(*var)
        elif c == 3:
            obj = Person(*var)
        else:
            obj = Frog(*var)

        obj.generate(datapath, i)
示例#24
0
def main():
    app = QApplication(sys.argv)
    frog = Frog(Point(200, 400))
    level = Level(1, Point(0, 0), Point(700, 700))
    game = Game(frog, level)
    g = Graphics(game, Point(900, 900))
    sys.exit(app.exec_())
示例#25
0
文件: level.py 项目: vnaitis/forggie2
    def load(self, levelConfigPath):
        """Load the level.

        Args:
            levelConfigPath: Absolute path to the level configuration
                             file. String.
        """
        config = configparser.ConfigParser()
        config.read(levelConfigPath)

        cfg = config['general']
        self.name = cfg.get('name', '')

        # Level background image.
        path = cfg.get('background')
        self.background = StaticImage(os.path.join(self.imageDir, path))

        self.frogPosX = cfg.getint('frogPosX')
        self.frogPosY = cfg.getint('frogPosY')
        self.frogCollisionWidth = cfg.getint('frogCollisionWidth')
        self.frogCollisionHeight = cfg.getint('frogCollisionHeight')

        path = cfg.get('frog')
        self.frog = Frog(self.frogPosX, self.frogPosY, self.screenWidth,
                         self.screenHeight, self.configDir, self.imageDir)

        # Load finish image.
        filepath = cfg.get('finishImage')
        posX = cfg.getint('finishImageX')
        posY = cfg.getint('finishImageY')
        centerX = cfg.getint('finishCenterWidth')
        centerY = cfg.getint('finishcenterHeight')

        finish = StaticImage(os.path.join(self.imageDir, filepath),
                             useAlpha=True)
        finish.rect.topleft = (posX, posY)
        width = int((finish.rect.width - centerX) / 2)
        height = int((finish.rect.height - centerY) / 2)
        finish.collisionRect = pygame.Rect(finish.rect.left + width,
                                           finish.rect.top + height, centerX,
                                           centerY)
        self.finishImage = finish

        self.cars, self.shadows = self.loadCars(config,
                                                self.allowedTrackSections)

        riverTracks, floatingObjects = self.loadFloaters(
            config, self.allowedRiverSections)

        if riverTracks:
            riverTrackRects = []
            for track in riverTracks:
                rect = pygame.Rect(0, track['top'], self.screenWidth,
                                   track['bottom'] - track['top'])
                riverTrackRects.append(rect)

        self.riverTracks = riverTracks
        self.floaters = floatingObjects
        self.riverTrackRects = riverTrackRects
示例#26
0
文件: level.py 项目: ikn/latof
 def init(self):
     self._changed = set()
     self._changed_rects = []
     self.overlays = []
     self.ui = {}
     self.dirty = True
     if self.ident != self._last_ident:
         self.game.clear_caches()
     data = conf.LEVELS[self.ident]
     sx, sy = LEVEL_SIZE
     self.objs = objs = [[[] for j in xrange(sx)] for i in xrange(sy)]
     self.road = Road(self)
     self.frog = Frog(self, data['frog pos'], data.get('frog dirn', 1))
     for pos, os in data['objs'].iteritems():
         if isinstance(os, basestring):
             os = (os, )
         objs[pos[0]][pos[1]] = [
             getattr(obj_module, obj)(self, pos) for obj in os
         ]
     self.update_held()
示例#27
0
    def __init__(self, window):
        self.hangman = Hangman()
        self.window = window

        # create a new pen to write the dashes
        self.pen = Frog(self.window)
        self.pen.visible = False
        self.pen.write(' '.join('_' for char in self.hangman.word))

        if SHOW_SOLUTION:
            # show the solution
            solution = Frog(self.window)
            solution.visible = False
            solution.jumpto(0, 50)
            solution.write(' '.join(char for char in self.hangman.word))

        # prepare a pen for writing the gallow
        self.gallow_writer = Frog(self.window)
        self.gallow_writer.visible = False
        self.gallow_writer.jump(-150)
示例#28
0
文件: level.py 项目: ikn/latof
 def init (self):
     self._changed = set()
     self._changed_rects = []
     self.overlays = []
     self.ui = {}
     self.dirty = True
     if self.ident != self._last_ident:
         self.game.clear_caches()
     data = conf.LEVELS[self.ident]
     sx, sy = LEVEL_SIZE
     self.objs = objs = [[[] for j in xrange(sx)] for i in xrange(sy)]
     self.road = Road(self)
     self.frog = Frog(self, data['frog pos'], data.get('frog dirn', 1))
     for pos, os in data['objs'].iteritems():
         if isinstance(os, basestring):
             os = (os,)
         objs[pos[0]][pos[1]] = [getattr(obj_module, obj)(self, pos)
                                 for obj in os]
     self.update_held()
示例#29
0
def game_run():
    pygame.init()
    screen = pygame.display.set_mode((1200, 800))
    frog = Frog(screen)
    pygame.display.set_caption("Firing frog")
    bg_color = (255, 255, 255)
    screen.fill(
        bg_color)  # Using fill method of pygame.display on screen object

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    moving_right = True
                elif event.key == pygame.K_LEFT:
                    moving_left = True
                elif event.key == pygame.K_UP:
                    moving_up = True
                elif event.key == pygame.K_DOWN:
                    moving_down = True

            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_RIGHT:
                    moving_right = False
                elif event.key == pygame.K_LEFT:
                    moving_left = False
                elif event.key == pygame.K_UP:
                    moving_up = False
                elif event.key == pygame.K_DOWN:
                    moving_down = False
        frog.update()
        frog.blitme()
        pygame.display.flip()
示例#30
0
#!/usr/bin/env python3

from __future__ import print_function, unicode_literals

from frog import Frog, FrogOptions
import folia.main as folia

frog = Frog(FrogOptions(parser=True))
output = frog.process_raw("Dit is een test")
print("RAW OUTPUT=", output)

output = frog.process("Dit is nog een test.")
print("PARSED OUTPUT=", output)

frog = Frog(FrogOptions(parser=True, xmlout=True))
output = frog.process("Dit is een FoLiA test.")
assert isinstance(output, folia.Document)
assert isinstance(len(output.data), 1)
assert isinstance(
    next(output.data.select(folia.Sentence)).text(), "Dit is een FoLiA test.")
#output is now no longer a string but an instance of folia.Document, provided by the FoLiA library in PyNLPl (pynlpl.formats.folia)
print("FOLIA OUTPUT=")
print(output.xmlstring())

print("Inspecting FoLiA output (example):")
for word in output.words():
    print(word.text() + " " + word.pos() + " " + word.lemma())
assert len(output.words()) == 5
示例#31
0
class HangmanWidget(object):
    """ The GUI stuff """
    def __init__(self, window):
        self.hangman = Hangman()
        self.window = window

        # create a new pen to write the dashes
        self.pen = Frog(self.window)
        self.pen.visible = False
        self.pen.write(' '.join('_' for char in self.hangman.word))

        if SHOW_SOLUTION:
            # show the solution
            solution = Frog(self.window)
            solution.visible = False
            solution.jumpto(0, 50)
            solution.write(' '.join(char for char in self.hangman.word))

        # prepare a pen for writing the gallow
        self.gallow_writer = Frog(self.window)
        self.gallow_writer.visible = False
        self.gallow_writer.jump(-150)

    def reset(self):
        """ clear the whole window and restart the game """
        # delete the 'frogs'
        self.pen.exit()
        self.gallow_writer.exit()
        self.__init__(self.window)

    def attempt(self, event):
        guessed_char = event['name']

        # lock the pen if it is just writing
        if self.gallow_writer.active:
            return

        self.gallow_writer.speed = 'max'

        # TODO: write a list of all guessed letters

        # right attempt
        if guessed_char.lower() in self.hangman.word:
            self.pen.write(self.hangman.guess(guessed_char))
            if len(self.hangman.right_attempts) == len(set(self.hangman.word)):
                self.gallow_writer.message(
                    'info',
                    'Congratulation! You guessed the word correctly!'
                )
                # start a new game
                self.reset()

        # wrong attempt
        else:
            # the number of mistakes
            num_mistakes = len(self.hangman.wrong_attempts)

            figures = [
                self.hill,
                self.first_beam,
                self.second_beam,
                self.bracket,
                self.rope,
                self.head,
                self.body,
                self.first_leg,
                self.second_leg,
                self.first_arm,
                self.second_arm,
            ]

            # only draw a figure if the guessed
            # letter was not already guessed earlier
            if guessed_char not in self.hangman.attempts:
                figures[num_mistakes]()

            self.hangman.guess(guessed_char)

    def hill(self):
        self.gallow_writer.turnto(90)
        self.gallow_writer.circle(50, 180)

    def first_beam(self):
        self.gallow_writer.circle(50, -90, draw = False)
        self.gallow_writer.turnto(90)
        self.gallow_writer.move(100)

    def second_beam(self):
        self.gallow_writer.turnto(0)
        self.gallow_writer.move(100)

    def bracket(self):
        # move back and build the supporting beam (and yes, the strange
        # number 36 is necessary because the gallow must be hit exactly
        # on the right place)
        self.gallow_writer.jump(-75)
        self.gallow_writer.turnto(225)
        self.gallow_writer.move(36)

        # don't forget to to move to the place where the man will be hung
        self.gallow_writer.jump(-36)
        self.gallow_writer.turnto(0)
        self.gallow_writer.jump(75)

    def rope(self):
        self.gallow_writer.turnto(270)
        self.gallow_writer.move(25)

    def head(self):
        self.gallow_writer.turnto(0)
        self.gallow_writer.circle(-15)

    def body(self):
        self.gallow_writer.turnto(270)
        self.gallow_writer.jump(30)
        self.gallow_writer.move(50)

    def first_leg(self):
        self.gallow_writer.turnto(225)
        self.gallow_writer.move(25)

    def second_leg(self):
        self.gallow_writer.jump(-25)
        self.gallow_writer.turnto(315)
        self.gallow_writer.move(25)

    def first_arm(self):
        self.gallow_writer.jump(-25)
        self.gallow_writer.turnto(90)
        self.gallow_writer.jump(25)
        self.gallow_writer.turnto(135)
        self.gallow_writer.move(25)

    def second_arm(self):
        """ last figure -> user lost! """
        self.gallow_writer.jump(-25)
        self.gallow_writer.turnto(45)
        self.gallow_writer.move(25)
        self.gallow_writer.message(
            'Info',
            'You lost! Shame on you! The word was: ' + self.hangman.word
        )
        # start a new game
        self.reset()
示例#32
0
def main(screen, window_size):
    """
    :param screen: the surface object
    :param window_size: the window size as a tuple
    :return: void
    This is the main game loop
    """
    FPS = 30
    FPS_CLOCK = pygame.time.Clock()

    pygame.mixer.music.load('battle.ogg')
    pygame.mixer.music.play(-1)
    whip = pygame.mixer.Sound('whip.ogg')
    boom = pygame.mixer.Sound('boom.ogg')
    pond = pygame.image.load('pond.png')

    # Draw Frogs
    frog1 = Frog(1, window_size)
    crosshair1 = Crosshair(window_size, 1)

    frog2 = Frog(2, window_size)
    crosshair2 = Crosshair(window_size, 2)

    # Fly Setup
    fly_sprites = pygame.sprite.Group()
    FLY_SPAWN = pygame.USEREVENT + 1
    pygame.time.set_timer(FLY_SPAWN, 1000)

    # Dragonfly Setup
    dfly_sprites = pygame.sprite.Group()
    DFLY_SPAWN = pygame.USEREVENT + 2
    pygame.time.set_timer(DFLY_SPAWN, 5000)

    fireballs1 = pygame.sprite.Group()
    fireballs2 = pygame.sprite.Group()

    # Text
    start_ticks = pygame.time.get_ticks()
    timer = 61
    timer_font = pygame.font.SysFont('berlinsansfb', 50)
    score_font = pygame.font.SysFont('berlinsansfb', 30)

    p1_move_right = False
    p1_move_left = False
    p1_charge = 0
    p1_score = 0
    p1_fire = 0

    p2_move_right = False
    p2_move_left = False
    p2_charge = 0
    p2_score = 0
    p2_fire = 0
    while True:  # <--- main game loop

        seconds = (pygame.time.get_ticks() - start_ticks)/1000

        # render objects
        SCREEN.blit(pond, (0, 0))
        frog1.draw(SCREEN)
        frog2.draw(SCREEN)

        if len(dfly_sprites) > 0:
            dfly_sprites.update()
            dfly_sprites.draw(SCREEN)
        if len(fly_sprites) > 0:
            fly_sprites.update()
            fly_sprites.draw(SCREEN)
        if len(fireballs1) > 0:
            fireballs1.update()
            fireballs1.draw(SCREEN)
            frogs_stunned = pygame.sprite.spritecollide(frog2, fireballs1, True)
            if len(frogs_stunned) > 0:
                frog2.stunned = True
                p2_charge = 0
                crosshair2.charging = 0
                frog2.time_of_stun = timer - seconds
        if len(fireballs2) > 0:
            fireballs2.update()
            fireballs2.draw(SCREEN)
            frogs_stunned = pygame.sprite.spritecollide(frog1, fireballs2, True)
            if len(frogs_stunned) > 0:
                frog1.stunned = True
                p1_charge = 0
                crosshair1.charging = 0
                frog1.time_of_stun = timer - seconds

        # draw targeting line and charge meter for frog 1
        draw_line(screen, frog1.mouth, (crosshair1.x + crosshair1.size[0]/2, crosshair1.y + crosshair1.size[1]/2))
        crosshair1.draw(SCREEN, p1_charge * 5)

        # draw targeting line and charge meter for frog 2
        draw_line(screen, frog2.mouth,  (crosshair2.x + crosshair2.size[0]/2, crosshair2.y + crosshair2.size[1]/2))
        crosshair2.draw(SCREEN, p2_charge * 5)

        for event in pygame.event.get():
            if event.type == QUIT:  # QUIT event to exit the game
                pygame.quit()
                sys.exit()

            # Fly event timer
            if event.type == FLY_SPAWN:
                if len(fly_sprites) < 10:
                    if random.randrange(0, 2) == 0:
                        fly = Fly(0, random.randrange(175, 501), random.randrange(1, 11))
                        fly_sprites.add(fly)
                    else:
                        fly = Fly(700, random.randrange(175, 501), random.randrange(1, 11))
                        fly_sprites.add(fly)

            # Dragonfly event timer
            if event.type == DFLY_SPAWN:
                if len(dfly_sprites) < 1:
                    if random.randrange(0, 2) == 0:
                        dragonfly = Dragonfly(0, random.randrange(175, 450), random.randrange(5, 11), random.randrange(3,11))
                        dfly_sprites.add(dragonfly)
                    else:
                        dragonfly = Dragonfly(700, random.randrange(175, 450), random.randrange(5, 11), random.randrange(3,11))
                        dfly_sprites.add(dragonfly)

            # Input events
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    return 0
                # Player 1
                if event.key == K_LEFT:
                    p1_move_left = True
                if event.key == K_RIGHT:
                    p1_move_right = True
                if event.key == K_DOWN and not frog1.stunned:
                    crosshair1.charging = True

                # Player 2
                if event.key == K_a:
                    p2_move_left = True
                if event.key == K_d:
                    p2_move_right = True
                if event.key == K_s and not frog2.stunned:
                    crosshair2.charging = True

                # Quit
                if event.key == K_ESCAPE:
                    pygame.quit()
                    sys.exit()

            if event.type == KEYUP:
                # Player 1
                if event.key == K_LEFT:
                    p1_move_left = False
                if event.key == K_RIGHT:
                    p1_move_right = False
                if event.key == K_DOWN and not frog1.stunned:
                    whip.play()
                    crosshair1.charging = False
                    xhair1 = (crosshair1.x + crosshair1.size[0]/2,crosshair1.y + crosshair1.size[1]/2)
                    hit_list, is_dragon = frog1.fire_tongue(SCREEN, p1_charge, xhair1[0], xhair1[1], fly_sprites, dfly_sprites)
                    p1_score += len(hit_list)
                    if len(hit_list) > 0 and p1_charge >= 15:
                        p1_score += 2
                    if is_dragon:
                        p1_fire += 1
                        p1_score += 1
                    p1_charge = 0
                if event.key == K_UP and not frog1.stunned:
                    if p1_fire > 0:
                        boom.play()
                        fireball = Fireball(1, frog1.x + 50, frog1.y)
                        fireballs1.add(fireball)
                        p1_fire -= 1

                # Player 2
                if event.key == K_a:
                    p2_move_left = False
                if event.key == K_d:
                    p2_move_right = False
                if event.key == K_s and not frog2.stunned:
                    whip.play()
                    crosshair2.charging = False
                    xhair2 = (crosshair2.x + crosshair2.size[0]/2, crosshair2.y + crosshair2.size[1]/2)
                    hit_list, is_dragon = frog2.fire_tongue(SCREEN, p2_charge, xhair2[0], xhair2[1], fly_sprites, dfly_sprites)
                    p2_score += len(hit_list)
                    if len(hit_list) > 0 and p2_charge >= 15:
                        p2_score += 2
                    if is_dragon:
                        p2_fire += 1
                        p2_score += 1
                    p2_charge = 0
                if event.key == K_w and not frog2.stunned:
                    if p2_fire > 0:
                        boom.play()
                        fireball = Fireball(2, frog2.x + 50, frog2.size[1] - 45)
                        fireballs2.add(fireball)
                        p2_fire -= 1

        # Player 1 crosshair events
        if p1_move_left and not crosshair1.x < 0:
            crosshair1.change_x(-15)
        if p1_move_right and not crosshair1.x > window_size[0] - crosshair1.size[0]:
            crosshair1.change_x(15)
        if crosshair1.charging:
            if p1_charge < 20:
                p1_charge += 0.5

        # Player 2 crosshair events
        if p2_move_left and not crosshair2.x < 0:
            crosshair2.change_x(-15)
        if p2_move_right and not crosshair2.x > window_size[0] - crosshair2.size[0]:
            crosshair2.change_x(15)
        if crosshair2.charging:
            if p2_charge < 20:
                p2_charge += 0.5

        # Calculate, render timers
        if timer - seconds > 0:
            timer_text = str(round(timer - seconds, 2))
        else:
            timer_text = 'GAME OVER'
        if frog1.stunned:
            if (timer - seconds) < frog1.time_of_stun - 2:
                frog1.stunned = False
        if frog2.stunned:
            if (timer - seconds) < frog2.time_of_stun - 2:
                frog2.stunned = False
        SCREEN.blit(timer_font.render(timer_text, False, (255, 0, 0)), (25, 25))
        if (timer - seconds) <= 0:
            if p1_score > p2_score:
                return 1
            elif p2_score > p1_score:
                return 2
            elif p1_score == p2_score:
                return 3

        # render HUD info
        p1_score_text = 'Player 1: ' + str(p1_score)
        p1_fire_text = 'Fireballs: ' + str(p1_fire)

        p2_score_text = 'Player 2: ' + str(p2_score)
        p2_fire_text = 'Fireballs: ' + str(p2_fire)

        SCREEN.blit(score_font.render(p1_score_text, True, (0, 0, 0)),
                    (window_size[0]/2 + frog1.size[0]/2 + 25, window_size[1] - 75))
        SCREEN.blit(score_font.render(p1_fire_text, True, (0, 0, 0)),
                    (window_size[0]/2 + frog1.size[0]/2 + 25, window_size[1] - 50))
        SCREEN.blit(score_font.render(p2_score_text, True, (0, 0, 0)),
                    (window_size[0]/2 + frog1.size[0]/2 + 25, 25))
        SCREEN.blit(score_font.render(p2_fire_text, True, (0, 0, 0)),
                    (window_size[0]/2 + frog1.size[0]/2 + 25, 50))

        pygame.display.update()
        FPS_CLOCK.tick(FPS)
示例#33
0
                    line_txt = re.sub(r'\\-', ' ', line_txt)  # spelling
                    line_txt = re.sub(r'"', '', line_txt)
                    line_txt = re.sub(r'[ ]+(?=[.,:;?!])', "", line_txt)
                    #                    line_txt = re.sub(r'[\.!]*[!]+[\.!]*', '!', line_txt)   # replace combos including at least 1 '!'
                    #                    line_txt = re.sub(r'[\.!?]*[?]+[\.!?]*', '?', line_txt)  # replace combos including at least 1 '?'
                    #                    line_txt = re.sub(r'\.+', '.', line_txt)   # replace clusters of '.' with a single '.'
                    line_txt = re.sub(r'[!.?]+', '!', line_txt)
                    line_txt = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff]',
                                      '', line_txt)
                    line_txt = re.sub(r" 's ", " ''s ", line_txt)
                    line_txt = re.sub(r"^'s ", "''s ", line_txt)
                    #                    if re.search(r'"".+""', line_txt):
                    #                        print(re.search(r'"".+""', line_txt).group())
                    txt_dict[pair][part][spkr] += line_txt + " "

frog = Frog(FrogOptions(mwu=False, ner=False))

for pair in txt_dict:
    for part in txt_dict[pair]:
        with open("{}pos/{}/{}_{}.pos".format(ecsd_path, pair, pair, part),
                  "w",
                  encoding="utf-8") as g:
            for spkr in txt_dict[pair][part]:
                print(pair, part, spkr)
                text = txt_dict[pair][part][spkr]
                word_list = frog.process(text)
                s_counter = 0
                w_counter = 0
                for word in word_list:
                    if word["index"] == "1":
                        s_counter += 1
示例#34
0
                y[-1].append('yes' if fields[-1] == 'animate' else 'no')
    return X, y

X, y = load_data(sys.argv[1], limit=None)
model = Word2Vec.load_word2vec_format(sys.argv[2], binary=True)
full_feature_vectorizer = FeatureStacker(('windower', Windower(window_size=3)),
                                         ('embeddings', WordEmbeddings(model)))
backoff_feature_vectorizer = FeatureStacker(('windower', Windower(window_size=3)))

X_full = full_feature_vectorizer.fit_transform([[word for word in doc] for doc in X])
X_backoff = backoff_feature_vectorizer.fit_transform([[word for word in doc] for doc in X])
y = LabelEncoder().fit_transform([l for labels in y for l in labels])

clf_full = LogisticRegression().fit(X_full, y)
clf_backoff = LogisticRegression().fit(X_backoff, y)
frogger = Frog(int(sys.argv[3]))

for filename in glob.glob(os.path.join(sys.argv[4], "*")):
    print filename
    characters = Counter()
    with codecs.open(filename, encoding='utf-8') as infile:
        doc = infile.read()
        document = frogger.tag(doc)
        document = [[f.decode('utf-8') for f in w[:-1]]
                    for sentence in document for w in sentence]
        words = [word[0] for word in document]
    X_test_full = full_feature_vectorizer.transform([document])
    X_test_backoff = backoff_feature_vectorizer.transform([document])
    for i, word in enumerate(X_test_full):
        if words[i].lower() not in model:
            pred = clf_backoff.predict(X_test_backoff[i])[0]
示例#35
0
文件: level.py 项目: ikn/latof
class Level (object):
    def __init__ (self, game, event_handler, ident = 0):
        self.game = game
        event_handler.add_event_handlers({
            pg.MOUSEBUTTONDOWN: self._click,
            pg.MOUSEMOTION: self._move_mouse
        })
        event_handler.add_key_handlers([
            (conf.KEYS_BACK, self.end, eh.MODE_ONDOWN)
        ])
        self._held_sfc = pg.Surface(TILE_SIZE).convert_alpha()
        self._held_sfc.fill(conf.UI_BG)
        self._last_ident = self.ident = ident
        self._locked = False
        self.drop_input()
        self.game.linear_fade(*conf.INIT_FADE)
        self.init()

    def init (self):
        self._changed = set()
        self._changed_rects = []
        self.overlays = []
        self.ui = {}
        self.dirty = True
        if self.ident != self._last_ident:
            self.game.clear_caches()
        data = conf.LEVELS[self.ident]
        sx, sy = LEVEL_SIZE
        self.objs = objs = [[[] for j in xrange(sx)] for i in xrange(sy)]
        self.road = Road(self)
        self.frog = Frog(self, data['frog pos'], data.get('frog dirn', 1))
        for pos, os in data['objs'].iteritems():
            if isinstance(os, basestring):
                os = (os,)
            objs[pos[0]][pos[1]] = [getattr(obj_module, obj)(self, pos)
                                    for obj in os]
        self.update_held()

    def restart (self):
        self.cutscene(self.init, *conf.RESTART)

    def end (self, *args):
        self.cutscene(self.game.quit_backend, *conf.END, persist = True)

    def _progress (self):
        if hasattr(self, '_cleanup'):
            self._cleanup()
        self.game.switch_backend(level_backends[self.ident], self.ident)

    def progress (self):
        self.ident += 1
        if self.ident >= len(conf.LEVELS):
            self.end()
        else:
            self.cutscene(self._progress, *conf.PROGRESS)

    def _end_cutscene (self):
        self._locked = False

    def cutscene (self, evt_f, evt_t, fade, ctrl_t = None, persist = False):
        self._locked = True
        self.frog.stop()
        self.game.linear_fade(*fade, persist = persist)
        self.game.scheduler.add_timeout(evt_f, seconds = evt_t)
        if ctrl_t is None:
            ctrl_t = evt_t
        self.game.scheduler.add_timeout(self._end_cutscene, seconds = ctrl_t)

    def _click (self, evt):
        if self._locked:
            return
        if self._grab_click(evt) and evt.button in conf.ACTION_SETS:
            self._rm_ui('msg')
            pos = tuple(x / s for x, s in zip(evt.pos, TILE_SIZE))
            self.frog.action(conf.ACTION_SETS[evt.button],
                             self.objs[pos[0]][pos[1]], pos)

    def _move_mouse (self, evt):
        if self._grab_move(evt):
            orig_x, orig_y = evt.pos
            x = orig_x / TILE_SIZE[0]
            y = orig_y / TILE_SIZE[1]
            obj = self.top_obj(self.objs[x][y])
            if obj is None:
                self._rm_ui('label')
                return
            label = obj_module.name(obj)
            sfc = self.game.render_text(
                'label', label, conf.FONT_COLOUR, bg = conf.UI_BG,
                pad = conf.LABEL_PADDING, cache = ('label', label)
            )[0]
            o = conf.LABEL_OFFSET
            ws, hs = sfc.get_size()
            x, y = orig_x + o[0], orig_y - hs + o[1]
            w, h = conf.RES
            x = min(max(x, 0), w - ws)
            y = min(max(y, 0), h - hs)
            self._add_ui('label', sfc, (x, y))

    def _native_click (self, evt):
        return True

    def _native_move (self, evt):
        return True

    def grab_input (self, click, move):
        self._grab_click = click
        self._grab_move = move

    def drop_input (self):
        self._grab_click = self._native_click
        self._grab_move = self._native_move

    def change_tile (self, tile):
        self._changed.add(tuple(tile))

    def rect_tiles (self, rect):
        sx, sy = TILE_SIZE
        x, y, w, h = rect
        x0 = int(x / sx)
        y0 = int(y / sy)
        x1 = int(ceil(float(x + w) / sx))
        y1 = int(ceil(float(y + h) / sy))
        w, h = LEVEL_SIZE
        tiles = []
        for i in xrange(x0, x1):
            if 0 <= i < w:
                for j in xrange(y0, y1):
                    if 0 <= j < h:
                        tiles.append((i, j))
        return tiles

    def change_rect (self, rect, tiles = None):
        if tiles is None:
            tiles = self.rect_tiles(rect)
        self._changed.update(tiles)
        self._changed_rects.append(rect)
        return tiles

    def add_obj (self, obj, pos):
        self.objs[pos[0]][pos[1]].append(obj)
        if isinstance(obj, obj_module.OneTileObj):
            self.change_tile(pos)
        road = self.road
        if road.tile_rect.collidepoint(pos) and hasattr(obj, 'on_crash') and \
           road.lane_moving(pos[1]):
            obj.on_crash(self.frog, road)
            assert not (obj.holdable and obj.solid)

    def rm_obj (self, obj, pos = None):
        if pos is None:
            pos = obj.pos
        self.objs[pos[0]][pos[1]].remove(obj)
        if isinstance(obj, obj_module.OneTileObj):
            self.change_tile(pos)
        if self.road.tile_rect.collidepoint(pos) and \
           hasattr(obj, 'on_uncrash'):
            obj.on_uncrash(self.frog, self.road)

    def top_obj (self, objs):
        # select uppermost (last) obj
        return objs[-1] if objs else None

    def solid_objs (self, *ignore):
        # return set of tiles of containing solid objects
        objs = set()
        for x, col in enumerate(self.objs):
            for y, os in enumerate(col):
                for o in os:
                    if o.solid and o not in ignore:
                        objs.add((x, y))
                        break
        return objs

    def _add_ui (self, ident, sfc, pos = None):
        if pos is None:
            pos = conf.UI_POS[ident]
        ui = self.ui
        if ident in ui:
            ui[ident].hide()
        ui[ident] = Overlay(self, sfc, pos).show()

    def _rm_ui (self, ident):
        ui = self.ui
        if ident in ui:
            overlay = ui[ident]
            del ui[ident]
            overlay.hide()

    def update_held (self):
        sfc = self._held_sfc
        if self.frog.item is not None:
            sfc = sfc.copy()
            self.frog.item.draw(sfc, (0, 0))
        self._add_ui('held', sfc)

    def say (self, msg):
        sfc = self.game.render_text(
            'msg', msg, conf.FONT_COLOUR, width = conf.MSG_WIDTH,
            bg = conf.UI_BG, pad = conf.MSG_PADDING, cache = ('msg', msg)
        )[0]
        self._add_ui('msg', sfc)

    def update (self):
        self.frog.update()
        self.road.update()
        self._changed.update(self.road.tiles)

    def _draw_objs (self, screen, objs):
        last = None
        # draw non-solid
        for o in objs:
            if isinstance(o, obj_module.OneTileObj):
                if o.solid:
                    last = o
                else:
                    o.draw(screen)
        # draw solid
        if last is not None:
            last.draw(screen)

    def _draw_cars (self, screen):
        for dirn, cars in self.road.cars:
            for car in cars:
                car.draw(screen)

    def draw (self, screen):
        bg = self.game.img('bg.png')
        draw_objs = self._draw_objs
        overlays = self.overlays
        road = self.road
        if self.dirty:
            self.dirty = False
            # background
            screen.blit(bg, (0, 0))
            # objects
            for col in self.objs:
                for objs in col:
                    if objs:
                        draw_objs(screen, objs)
            # moving cars
            self._draw_cars(screen)
            # overlays
            for overlay in overlays:
                overlay.draw(screen)
            rtn = True
        else:
            # draw changed tiles
            rects = self._changed_rects
            in_road_rect = road.tile_rect.collidepoint
            objs = self.objs
            sx, sy = TILE_SIZE
            todo_os = set()
            # draw bg and objs
            screen.blit(bg, road.rect, road.rect)
            for x, y in road.tiles:
                draw_objs(screen, objs[x][y])
                for overlay in overlays:
                    if (x, y) in overlay.tiles:
                        todo_os.add(overlay)
            for tile in self._changed:
                if in_road_rect(tile):
                    continue
                x, y = tile
                this_objs = objs[x][y]
                x *= sx
                y *= sy
                r = (x, y, sx, sy)
                screen.blit(bg, (x, y), r)
                draw_objs(screen, this_objs)
                # add to changed rects
                rects.append(r)
                # add overlays
                for overlay in overlays:
                    if tile in overlay.tiles:
                        todo_os.add(overlay)
            self._draw_cars(screen)
            rects.append(road.rect)
            # draw overlays
            for overlay in todo_os:
                overlay.draw(screen)
            rtn = rects
        self._changed = set()
        self._changed_rects = []
        return rtn
示例#36
0
                                  line_txt)  # deal with d'rbij
                line_txt = re.sub(r'^\.', '', line_txt)
                line_txt = re.sub(
                    r'[!?\.,:;]', lambda m: " " + m.group(),
                    line_txt)  # prevent from being interpreted as SPEC(afk)
                #                    if re.search(r'"".+""', line_txt):
                #                        print(re.search(r'"".+""', line_txt).group())
                #                if len(line_txt) > 0:
                #                    if line_txt[-1] not in [".", ",", "!", "?", ":", ";"]:  # add . if chunk does not end in punctuation
                #                            if re.search(r' [A-Za-z]$', line_txt):  # prevent from being interpreted as SPEC(afk)
                #                                line_txt += "!"
                #                            else:
                #                        line_txt += " ."
                txt_dict[file_n][speakers[file_n][spkr]] += line_txt + " "

frog = Frog(FrogOptions(parser=True))


def tag_files(files):
    for fl in files:
        with open(tens_path + "Annotations/pos/" + fl + ".pos", "w") as g:
            for spkr in txt_dict[fl]:
                print(fl, spkr)
                text = txt_dict[fl][spkr]
                #                print(text)
                word_list = frog.process(text)
                print("BLA")
                s_counter = 0
                for word in word_list:
                    if word["index"] == "1":
                        s_counter += 1
示例#37
0
from storypy import Story
import glob
import codecs
import os
import sys

from frog import Frog, Word

frogger = Frog(int(sys.argv[1]))

def token_boundaries(tokens, original_text):
    curr_pos = 0
    for tok in tokens:
        start_pos = original_text.index(tok, curr_pos)
        # TODO: Check if we fail to find the token!
        end_pos = start_pos + len(tok)
        yield (start_pos, end_pos)
        curr_pos = end_pos

for filename in glob.glob(os.path.join(sys.argv[2], "SINVS*.ann")):
    if 'anomalies' in filename:
        continue
    story = Story.load(filename)
    if sys.argv[3] == 'chars':
        characters = {(start, end): (id, name)
                      for character in story.characters
                      for id, name, start, end in character.chain}
    else:
        characters = {(start, end): (id, name)
                      for location in story.locations
                      for id, name, start, end in location.chain}