Exemple #1
0
    def __init__(self, screenSize, eventHandler):
        if type(screenSize) != tuple:
            raise TypeError

        if len(screenSize) != 2:
            raise IndexError

        if type(eventHandler) != EventHandler:
            raise TypeError

        self.screenSize = screenSize
        self.eventHandler = eventHandler

        self.timeUpdated = 0

        self.active = False

        # UI
        self.textGameOver = Text(pygame.Vector2(0, 0), "Game Over", 48)
        self.textNewHighScore = Text(pygame.Vector2(0, 0),
                                     "New Highscore Entry!", 48)
        self.textScoreNumber = Text(pygame.Vector2(0, 0), "0", 48)
        self.textPressAnyKey = Text(pygame.Vector2(0, 0),
                                    "Press any Key to continue...", 20)

        self.textGameOver.pos = pygame.Vector2(
            self.screenSize[0] / 2 - self.textGameOver.width() / 2,
            self.screenSize[1] / 2 - self.textGameOver.height() / 2)

        self.textPressAnyKey.pos = pygame.Vector2(
            self.screenSize[0] / 2 - self.textPressAnyKey.width() / 2,
            self.screenSize[1] - self.textPressAnyKey.height() -
            GameOver.textSpacing)

        self.ui = [self.textGameOver]
 def __init__(self, dialect, word_id, title, definition, pos, category, phrase, phrase_def, user, contributor,
              cultural_note, pronunciation, reference, image_id, audio_id, video_id, children_archive, status, literal_translation, change):
     Text.__init__(self, dialect, word_id, title, definition, user, contributor, cultural_note, reference, image_id,
                   audio_id, video_id, children_archive, status, literal_translation, change)
     self.category = category
     self.pos = pos
     self.pronunciation = pronunciation
     self.phrase = phrase
     self.phrase_def = phrase_def
Exemple #3
0
 def __init__(self, dialect, entry_id, title, definition, user, translation,
              book_id, cultural_note, image_id, audio_id, video_id, change,
              order):
     self.order = order
     for book in dialect.legacy_books:
         if book.id == book_id:
             self.book = book
             self.status = book.status
             self.children_archive = book.children_archive
     Text.__init__(self, dialect, entry_id, title, definition, user, None,
                   cultural_note, None, image_id, audio_id, video_id,
                   self.children_archive, self.status, translation, change)
Exemple #4
0
 def __init__(self, dialect, book_id, title, definition, user, contributor,
              cultural_note, reference, image_id, audio_id, video_id,
              children_archive, status, intro, intro_def, author,
              author_ref, contributor_ref, translation, sstype, change,
              order):
     Text.__init__(self, dialect, book_id, title, definition, user,
                   contributor, cultural_note, reference, image_id,
                   audio_id, video_id, children_archive, status,
                   translation, change)
     self.intro = intro
     self.intro_def = intro_def
     self.author = author
     self.author_ref = author_ref  ##
     self.contributor_ref = contributor_ref  ##
     self.sstype = sstype
     self.order = order
Exemple #5
0
    def __init__(self, window):
        State.__init__(self, State.MENU_STATE, window)
        center_x = self.window.width / 2
        self.title_text_surf, self.title_text_rect = Text.text_objects(
            "Penguino.ai", Text.large_font)
        self.title_text_rect.center = (center_x, (self.window.height / 6))

        self.instructions_text_surf, self.instructions_text_rect = Text.text_objects(
            "Type the letter in () to select an option", Text.tiny_font)
        self.instructions_text_rect.center = (center_x,
                                              (self.window.height * 2 / 6))

        self.play_text_surf, self.play_text_rect = Text.text_objects(
            "(P)lay", Text.small_font)
        self.play_text_rect.center = (center_x, (self.window.height * 3 / 6))

        self.ai_text_surf, self.ai_text_rect = Text.text_objects(
            "(A)I Model", Text.small_font)
        self.ai_text_rect.center = (center_x, (self.window.height * 4 / 6))
 def __init__(self, dialect, phrase_id, title, definition, phrase_book,
              user, contributor, cultural_note, reference, image_id,
              audio_id, video_id, children_archive, status, change):
     Text.__init__(self,
                   dialect,
                   phrase_id,
                   title,
                   definition,
                   user,
                   contributor,
                   cultural_note,
                   reference,
                   image_id,
                   audio_id,
                   video_id,
                   children_archive,
                   status,
                   change=change)
     self.category = phrase_book
Exemple #7
0
 def init_game_finished(self):
     """
     If game is finished show relevant message
     :return:
     """
     self.game_objects.reset()
     self.game_objects.texts.append(
         Text(self.ui, "You win!\nCongratulations!", (450, 200)))
     self.game_objects.buttons.append(
         Button(self.ui, "New game", "new", (450, 300)))
Exemple #8
0
 def show_rules_page(self):
     """
     Init rules page
     :return: None
     """
     self.game_objects.reset()
     self.game_objects.texts.append(
         Text(
             self.ui, """
         You play as a red box!
         Your goal is to push green boxes to circles.
         When they will be on circles the game is finished.""", (450, 200)))
     self.game_objects.buttons.append(
         Button(self.ui, "Back", "back", (600, 300)))
Exemple #9
0
	def __init__(self, highscoreFile):
		if type(highscoreFile) != str:
			raise TypeError

		self.highscoreFile = highscoreFile

		self.active = False

		self.data = []
		self.ui = []

		try:
			# Datei oeffnen
			with open(self.highscoreFile, 'r') as handle:
				# Highscores auslesen
				self.data = handle.readlines()
		except OSError:
			# Datei nicht vorhanden
			with open(self.highscoreFile, 'w') as handle:
				# Datei mit Nullen fuellen
				for i in range(0, 10):
					self.data.append("0\n")

				handle.writelines(self.data)

		# Highscore auslesen (Datei ist sortiert, also ersten Score)
		self.highscore = int(self.data[0][:-1])

		# UI
		textSpacing = 20
		upperLeft = pygame.Vector2(textSpacing, textSpacing)

		textHighscores = Text(upperLeft, "Highscores")
		self.ui.append(textHighscores)

		for (idx, d) in enumerate(self.data):
			self.ui.append(Text(pygame.Vector2(upperLeft.x,	self.ui[idx].pos.y + self.ui[idx].height() + textSpacing), d[:-1]))
Exemple #10
0
    def __init__(self, text):

        self.text = Text(text)
        # x is 1 since we scale it later anyway - less memory
        self.dimensions = (1, (len(self.text.colours)) * (self.rec_height + 1))

        # scaling started
        # if len(self.text.colours) * self.rec_height > dimensions[1]:
        #     self.scaled_colours = self.scaled_colours
        # else:
        #     self.scaled_colours = self.text.colours
        self.scaled_colours = self.text.colours

        self.image = Image.new(self.colour_space, self.dimensions,
                               self.background)
        self.drawer = ImageDraw.Draw(self.image)
Exemple #11
0
    def __init__(self, rect, text, color=Color.WHITE):
        if type(rect) != pygame.Rect:
            raise TypeError

        if type(text) != str:
            raise TypeError

        # Hitbox des Buttons
        self.rect = rect

        # Text des Buttons
        self.text = Text(pygame.Vector2(0, 0), text)

        # Text im Button zentrieren
        self.text.pos = pygame.Vector2(
            self.rect.x + self.rect.width / 2 - self.text.width() / 2,
            self.rect.y + self.rect.height / 2 - self.text.height() / 2,
        )

        # Button und Textfarbe
        self.color = color
Exemple #12
0
    def __init__(self, window, state=State.GAME_STATE):
        State.__init__(self, state, window)
        self.substate = state
        self.penguin = Penguin(window.width / 3, window.height / 2)
        self.entities = []
        ice_boundary = IceBoundary(window.width, window.height)
        self.entities = self.entities + ice_boundary.floor + ice_boundary.ceiling
        self.game_count = 0

        # AI needs this info
        self.closest_gap_range = (0,window.height)
        self.closest_x_distance_to_penguin = window.width - self.penguin.x
        self.old_state = None
        self.environment_state = None
        self.reward = 0

        # Score message
        self.score = 0
        self.score_text_surf, self.score_text_rect = Text.text_objects(str(self.score), Text.small_font)
        self.score_text_rect.center = ((self.window.width * 4 / 5), (self.window.height / 6))

        # Game start screen
        self.game_started = False
        self.spacebar_text_surf, self.spacebar_text_rect = Text.text_objects("To begin and to flap, hit the (Spacebar)", Text.tiny_font)
        self.spacebar_text_rect.center = ((self.window.width / 2), (self.window.height / 3))

        self.p_to_pause_text_surf, self.p_to_pause_text_rect = Text.text_objects("(P) to pause", Text.tiny_font)
        self.p_to_pause_text_rect.center = ((self.window.width / 2), (self.window.height * 2 / 3))

        # Quit text
        self.quit_text_surf , self.quit_text_rect = Text.text_objects("(Q)uit to menu", Text.tiny_font)
        self.quit_text_rect.center = ((self.window.width / 2), (self.window.height * 2 / 3))

        # Unpause text
        self.unpause_text_surf, self.unpause_text_rect = Text.text_objects("(U)npause", Text.small_font)
        self.unpause_text_rect.center = ((self.window.width / 2), (self.window.height / 3))

        # Restart text
        self.restart_text_surf, self.restart_text_rect = Text.text_objects("(P)lay Again", Text.small_font)
        self.restart_text_rect.center = ((self.window.width / 2), (self.window.height / 3))

        self.update_score()

        if self.substate == State.AI_GAME_STATE:
            self.game_started = True
Exemple #13
0
    default=None,
    type=float,
    help=
    'threshold (TF-IDF value) below which concepts will not be included to the graph'
)
args = arg_parser.parse_args()

current_dir = os.path.dirname(os.path.abspath(__file__))
df_filename = os.path.normpath(
    os.path.join(current_dir, 'datasets/bbc-news.json'))
texts_path = os.path.normpath(os.path.join(current_dir, 'input'))

print('Loading DF metrics from ')
corpus = TextCorpus(df_filename)

print('Creating English semantic network...')
net = Network(english, args.threshold)
print('Reading texts from ' + texts_path)
for filename in glob.iglob(os.path.join(texts_path, '**/*.*'), recursive=True):
    text = Text(corpus,
                open(filename, mode='r', encoding='utf-8').read(),
                name=re.search('[^\\\/]+$', filename).group(0))
    print('Text of ' + str(len(text.terms)) + ' terms with average score of ' +
          str(text.avg_score))
    net.merge(text)

net.save_graph('output/output')
net.log_to_html()
print('Graph saved to ' + current_dir +
      '/output/output-edges.xlsx (output-nodes.xlsx)!')
 def __init__(self, dialect, phrase_id, title, definition, user,
              contributor, children_archive, status):
     Text.__init__(self, dialect, phrase_id, title, definition, user,
                   contributor, None, None, None, None, None,
                   children_archive, status)
     self.dialect.unentered_phrases += 1
Exemple #15
0
 def update_score(self):
     self.score_text_surf, self.score_text_rect = Text.text_objects(str(self.score), Text.small_font)
     self.score_text_rect.center = ((self.window.width * 4 / 5), (self.window.height / 6))
Exemple #16
0
    def play(variables, constructors, superficies):
        print('Iniciando Juego')
        # Cargamos las variables
        screen_size = variables.get('screen_size')
        screen_filled_color = variables.get('colors').get('screen_filled')
        movex = variables.get('movex')
        movey = variables.get('movey')
        zoomv = variables.get('zoomv')
        images = variables.get('images')
        zoom_list_refs = variables.get('zoom_list_refs')
        map_sizex = variables.get('map_sizex')
        map_sizey = variables.get('map_sizey')
        images_dir = variables.get('images_dir')
        eje_coordenadas = variables.get('eje_coordenadas')
        vel_mov_mapa = variables.get('vel_mov_mapa')
        zoom_base = variables.get('zoom_base')

        map_size = (map_sizex[1], map_sizey[1])
        variables['map_size'] = map_size
        zoom_list = list(map(lambda x: zoomv * x, zoom_list_refs))
        zoom_list.append(2)

        minimapa = False

        display = constructors['display']
        menu_creator = constructors['menu_creator']
        clock = constructors['clock']

        #Cargamos las imagenes en memoria
        images, imagesString = utils.charge_images(images, zoom_list,
                                                   images_dir)
        variables['images'] = imagesString
        superficies['images'] = images

        # Creamos los mapas de la pantalla

        display.images = images
        #display.image()
        display.maps(map_size)
        pantallita = display.pantallita
        maps = display.returnMaps()
        variables['maps'] = maps
        variables['supmapa'] = maps[0]
        supmapa = maps[0]

        # Creamos el mapa
        map_generator = GenMap()
        constructors['map_generator'] = map_generator
        chunk = Chunks(images)
        constructors['chunk'] = chunk
        map_generator.chunk(map_size, map_sizex, map_sizey, zoomv, chunk)
        map_generator.gen_map(map_size, images, chunk)

        #map_tile = Tiles.tiles(map_size, map_sizex, map_sizey, zoomv, map_generator.map_list)
        mapaActual = MapaString(zoomv)
        constructors['mapaActual'] = mapaActual

        mapaActual.create(map_generator.map_list, images, movex, movey, zoomv,
                          map_size)

        #Creamos menus
        '''
        menu_creator = MenuCreators(screen_size)
        menu_creator.create_menus(pantallita, menusObj, menu_creator)
        '''

        menu_creator.main_menus()

        text = Text(pantallita, {
            'x': 200,
            'y': 200,
            'width': 200,
            'height': 40
        }, 20, (255, 255, 255))

        #Creamos Unidades
        unitsCreator = UnitsCreators(variables)
        variables['unitsCreator'] = unitsCreator

        run = True
        text_active = False
        click_map = False
        clicking = {1: False}
        selected = []
        clicked_map_origin = [0, 0]

        test = Test()

        #screenProcess = multiprocessing.Process(target=test.printear, args=('10'))
        #screenProcess.start()

        #Creamos el mapa en si
        variables['supmapa'] = display.displayCreate(
            constructors['mapaActual'], constructors['map_generator'],
            variables['movex'], variables['movey'], variables['zoomv'],
            pygame.image.tostring(variables['supmapa'],
                                  'RGB'), variables['map_size'])

        while run:

            #Pintamos la pantalla

            #screenProcess = multiprocessing.Process(target=display.display, args=(constructors['mapaActual'], constructors['map_generator'], variables['movex'], variables['movey'], variables['zoomv'], pygame.image.tostring(variables['supmapa'], 'RGB'), variables['map_size']))
            display.display(constructors['mapaActual'],
                            constructors['map_generator'], variables['movex'],
                            variables['movey'], variables['zoomv'],
                            pygame.image.tostring(variables['supmapa'], 'RGB'),
                            variables['map_size'])
            '''
            pantallita.fill(screen_filled_color)
            pantallita.blit(supmapa, (0 + movex, 0 + movey))
            supmapa.fill(screen_filled_color)
            mapaactual.create(map_generator.map_list, images, supmapa, movex, movey, zoomv, screen_size)
            '''
            if text_active == True:
                text.textUpdate()

            #Pintamos unidades

            #Pintamos menus
            menu_creator.Menus.menu_draw()
            menu_creator.Buttons.button_draw()

            #Actualizacion de variables
            variables['eje_coordenadas'] = [
                int(screen_size[0] / 2) - variables['movex'],
                int(screen_size[1] / 2) - variables['movey']
            ]

            if click_map and clicking[1]:
                draw_select_multi(clicked_map_origin, pantallita, movex, movey,
                                  map_size)

            #Vemos si el raton esta en algun borde para mover el mapa
            variables['movex'], variables['movey'] = Border.check(
                pygame.mouse.get_pos(), variables['eje_coordenadas'],
                variables['movex'], variables['movey'], variables['map_size'],
                variables['zoomv'], variables['screen_size'],
                variables['vel_mov_mapa'])

            #Miramos que eventos ocurren
            for event in pygame.event.get():

                #Miramos si se pulsa la X, de ser asi cerramos el juego
                if event.type == pygame.QUIT:

                    run = False

                #Miramos si se pulsa la un boton del raton
                if event.type == pygame.KEYDOWN:
                    pressed = pygame.key.get_pressed()
                    if pressed[pygame.K_m] and minimapa == False:
                        minimapa = True
                        oldVar = (supmapa, movex, movey, zoomv, map_size)
                        supmapa, movex, movey, zoomv, map_size = Zooms.minimap(
                            event, zoomv, supmapa, movex, movey, map_size,
                            mapaActual, zoom_base, eje_coordenadas,
                            screen_filled_color, map_generator, images,
                            screen_size)
                    elif pressed[pygame.K_m]:
                        supmapa = oldVar[0]
                        movex = oldVar[1]
                        movey = oldVar[2]
                        zoomv = oldVar[3]
                        map_size = oldVar[4]
                        supmapa, movex, movey, zoomv, map_size = Zooms.zoom(
                            -1, zoomv, supmapa, movex, movey, map_size,
                            mapaActual, zoom_base, eje_coordenadas,
                            screen_filled_color, map_generator, images,
                            screen_size, clicked_map)
                        minimapa = False

                if event.type == pygame.MOUSEBUTTONDOWN:

                    MouseInput.clickInput(event, variables, constructors)

                if event.type == pygame.MOUSEBUTTONUP:

                    clicking[event.button] = False
                    click_map = False
                    if click_map:
                        pass
                    else:
                        pass
                    unclicked = pygame.mouse.get_pos()

                    #selected2 = click.click(movex, movey, map_size, map_sizex, map_sizey, zoomv)
                    '''
                    if selected == selected2:
                        if selected[0] == -1:
                            pass
                        else:
                            if event.button == 3:
                                genMap.editMap(selected[0],selected[1],0)
                            else:
                                genMap.editMap(selected[0],selected[1],1)
                    
                    else:
                        selectedM = {}
                        casilla = 0
                        for i in range (selected[0], selected2[0]+1):
                            for j in range (selected[1], selected2[1]+1):
                                casilla = casilla + 1
                                selectedM[casilla] = [i,j]
                        # print (selectedM) 
                    '''

                if event.type == pygame.MOUSEWHEEL:

                    MouseInput.wheelInput(event, variables, constructors)

                if text_active == True:
                    texto = text.textEdit(event)
                    text.textUpdate()
                    if texto != None:
                        textoSaved = texto
                        print(textoSaved)

            clock.tick(30)
            pygame.display.flip()

        pygame.quit()
        return True
Exemple #17
0
	def __init__(self, screenSize, eventHandler, highscore):
		if type(screenSize) != tuple:
			raise TypeError

		if len(screenSize) != 2:
			raise IndexError

		if type(eventHandler) != EventHandler:
			raise TypeError

		if type(highscore) != int:
			raise TypeError

		# Zufallszahlen initialisieren
		random.seed()

		self.screenSize = screenSize
		self.eventHandler = eventHandler
		self.highscore = highscore

		self.state = Game.GameStates.inactive

		self.projectiles = []
		self.asteroids = []
		self.explosions = []
		self.ui = []
		self.collectablePowerUps = []

		self.lastPowerUpSpawnTime = pygame.time.get_ticks()

		self.player = Player(pygame.Vector2(self.screenSize[0] / 2, self.screenSize[1] / 2))

		pygame.display.set_caption("Asteroids")

		# Sounddateien
		laser_wav = r'./resources/laser.wav'  			# Sound Laser
		asteroid_wav = r'./resources/asteroid3.wav'  	# Sound Explosion
		powerup_wav = r'./resources/powerUp1.wav'  		# Sound PowerUp

		Sound.init()  # Initialisieren von pygame.mixer

		# Sounds laden
		self.soundLaser = Sound(laser_wav, 0.03)
		self.soundExplosion = Sound(asteroid_wav, 0.1)
		self.soundPowerUp = Sound(powerup_wav, 0.1)
		# Hintergrundmusik ist Tetris-Theme in pygame.music (keine Klasse da nur eine Hintergrundmusik)
		pygame.mixer.music.load('./resources/Tetris.wav')
		pygame.mixer.music.set_volume(0.03)
		pygame.mixer.music.play(-1)		# Spiele Tetris-Theme als Loop (-1) ab

		# UI-Einstellungen
		textSpacing = 20
		textUpperLeft = pygame.Vector2(textSpacing, textSpacing)
		textUpperRight = pygame.Vector2(self.screenSize[0] - textSpacing, textSpacing)

		# UI (links oben)
		textScore = Text(pygame.Vector2(textUpperLeft), "Score:")
		self.textScoreNumber = Text(pygame.Vector2(textUpperLeft.x + textScore.width() + textSpacing, textUpperLeft.y), "0")
		textLives = Text(pygame.Vector2(textUpperLeft.x, textUpperLeft.y + textScore.height() + textSpacing), "Lives:")
		self.textLivesNumber = Text(pygame.Vector2(textUpperLeft.x + textLives.width() + textSpacing, textUpperLeft.y + textScore.height() + textSpacing), "5")

		# UI (rechts oben)
		textHighscore = Text(pygame.Vector2(0, 0), "Highscore:")
		textHighscoreNumber = Text(pygame.Vector2(0, 0), str(self.highscore))
		textHighscore.pos = pygame.Vector2(textUpperRight.x - textHighscoreNumber.width() - textSpacing - textHighscore.width(), textUpperRight.y)
		textHighscoreNumber.pos = pygame.Vector2(textUpperRight.x - textHighscoreNumber.width(), textUpperRight.y)

		self.ui.append(textScore)
		self.ui.append(self.textScoreNumber)
		self.ui.append(textLives)
		self.ui.append(self.textLivesNumber)
		self.ui.append(textHighscore)
		self.ui.append(textHighscoreNumber)
Exemple #18
0
#!/usr/bin/env python3

from src.TextCorpus import TextCorpus
from src.Text import Text
from src.Network import Network
from src.rule_set import english
import os

current_dir = os.path.dirname(os.path.abspath(__file__))
text_filename = os.path.join(
    current_dir,
    'datasets/bbc-news/news/tech/call-for-action-on-internet-scam.txt')

print('Analyzing ' + text_filename)
corpus = TextCorpus(os.path.join(current_dir, 'datasets/bbc-news.json'))
text = Text(corpus, open(text_filename, mode='r', encoding='utf-8').read())
print('Text of ' + str(len(text.terms)) + ' terms with average score of ' +
      str(text.avg_score))

net = Network(english)
net.merge(text)
net.save_graph('output/test')
net.log_to_html()
print('Graph saved to test-edges.xlsx!')