def __init__(self, game_display, game_screen, screen_dims, colour, clock_delay): # Run game - used to exit game loop self.run = True # Load game settings with open('json/settings.JSON') as settings: self.settings = json.load(settings) # Add important game features to self self.game_display = game_display self.game_screen = game_screen self.screen_dims = screen_dims self.colour = colour self.clock_delay = clock_delay # Setup score and level displays self.score = Score(game_screen) self.level = Level(game_screen) # Setup key distances self.spawn_area = (2 * self.player_x, screen_dims[0]) self.map_width = self.game_screen.get_width() self.mid_width = self.map_width // 2 self.mid_height = self.game_screen.get_height() // 2 self.weapon_types = list(WEAPON_TYPES.keys()) # Setup level complete variables self.level_complete = False self.level_complete_text_1 = Text(self.game_screen, (self.mid_width, self.mid_height - 40), 30, 'Level Complete' ) continue_string = f'Press {self.settings["next_level"]} to continue' self.level_complete_text_2 = Text(self.game_screen, (self.mid_width, self.mid_height), 30, continue_string ) # Setup first level self.firstLevel() # Setup god mode capability - used for debugging self.god_mode = False self.cheats = 0 # Play game music self.playMusic() self.projectiles = pygame.sprite.Group()
def refreshTexts(self): ''' Re-loads settings JSON and refreshes the text elements. The texts dictionary contains all text elements to display, while the used_keys dictionary contains the data for all keys that have been assigned by the user. ''' self.loadSettings() texts = {} self.used_keys = [ self.settings_data["left"], self.settings_data["right"], self.settings_data["up"], self.settings_data["attack"], self.settings_data["next_level"] ] screen = self.screen left_str = f'Move Left : {self.settings_data["left"]}' left_text = Text(screen, (self.left, 2 * self.height_unit), 35, left_str) texts['left'] = left_text right_str = f'Move Right : {self.settings_data["right"]}' right_text = Text(screen, (self.left, 3 * self.height_unit), 35, right_str) texts['right'] = right_text jump_str = f'Jump : {self.settings_data["up"]}' jump_text = Text(screen, (self.left, 4 * self.height_unit), 35, jump_str) texts['up'] = jump_text attack_str = f'Attack : {self.settings_data["attack"]}' attack_text = Text(screen, (self.left, 5 * self.height_unit), 35, attack_str) texts['attack'] = attack_text level_str = f'Next Level : {self.settings_data["next_level"]}' level_text = Text(screen, (self.left, 6 * self.height_unit), 35, level_str) texts['next_level'] = level_text self.texts = texts self.changing = (False, None)
def create_database_from_csv(csv_filename, dump_filename, phrase_size, debug_mode=False): start = datetime.datetime.now() print('Criando sql: ', dump_filename) db = DB(debug=debug_mode, path='', filename=dump_filename[:-4], run_on_ram=True) with open(csv_filename, newline='', encoding='utf-8-sig') as csvfile: # lendo o csv reader = csv.reader(csvfile, delimiter=";", quoting=csv.QUOTE_NONE) for row in reader: # para cada linha t = Text(str.split(str.upper(row[1])), row[0]) # cria um Text if t: t.build_phrases(phrase_size) if debug_mode: t.print_phrases() db.insert_text(t, debug_mode) del t else: return -100 end = datetime.datetime.now() print('Começou: ' + start.strftime("%H:%M:%S")) print('Terminou: ' + end.strftime("%H:%M:%S")) print('Delta: ' + str(end - start)) return db
def calc_text_prob(text="", database=None, w_firefly=(1, 1, 1, 1, 1), phrase_size=3, consider_not_found=0): firefly_dimension = len(w_firefly) t = Text(str.split(str.upper(text)), 0) t.build_phrases(phrase_size) phrase_prob = [] for phrase in t.phrases: phrase_prob.append(database.get_phrase_prob(phrase)) [used_clusters, not_found] = get_used_clusters(phrase_prob, firefly_dimension, consider_not_found) used_clusters = normalize(used_clusters) if not len(t.phrases): return [-1, 0, 0] found_ratio = 1 - (not_found / len(t.phrases)) # print("Found: ", len(t.phrases) - not_found, " of ", len(t.phrases), " | ", found_ratio) if found_ratio: return [ calc_prob(used_clusters, w_firefly), len(t.phrases) - not_found, len(t.phrases) ] else: return [-1, 0, len(t.phrases)]
def get_all_phrases_prob(data_validation_source, db: DB, phrase_size): dbh = DbHandler() print("Phrase count: ", db.query("select count(*) from phrases;")) with open(data_validation_source, encoding='utf-8-sig') as csv_file: csv_reader = csv.reader(csv_file, delimiter=';') for row in csv_reader: txt = str.split(str.upper(row[1])) t = Text(txt, row[0]) th = TextHandler() if t: t.build_phrases(phrase_size) phrases_prob = [] for phrase in t.phrases: phrases_prob.append(db.get_phrase_prob(phrase)) if not len( t.phrases): # if text has less words than phrase_size phrases_prob.append(-1) th.append(float(t.probability), phrases_prob) dbh.append(th) del t return dbh
def __init__(self, screen): ''' Initialises a Text object on the screen which can be updated when required ''' self.text_output = Text(screen, (self.position), self.font_size, str(self))
def validation_train(report_dir, source_name): line_count = 0 # inicio do treino =============================== start = datetime.datetime.now() db = DB(report_dir + "/", "database", debug=False, run_on_ram=True) print(report_dir) with open(source_name, newline='', encoding='utf-8-sig') as csvfile: # lendo o csv reader = csv.reader(csvfile, delimiter=";", quoting=csv.QUOTE_NONE) # leitura do arquivo for row in reader: # para cada linha line_count = line_count + 1 print(str(line_count)) t = Text(str.split(str.upper(row[1])), row[0]) # cria um Text if t: t.build_phrases(3) # t.print_phrases() db.insert_text(t, False) del t else: return -100 end = datetime.datetime.now() print('Começou: ' + start.strftime("%H:%M:%S")) print('Terminou: ' + end.strftime("%H:%M:%S")) print('Delta: ' + str(end - start))
def texts_to_sentences(id, texts): """ Converts texts into sentences :type texts: list of texts :return: list of sentences """ sentences = [] sentence = Sentence() distance_from_run_offset = 0 for text in texts: content = '' beginningOfSentenceOffset = text.run_offset chars = text.processed_content() for char in chars: content = content + char distance_from_run_offset += 1 # if content is only bolded or italicized text, it should not be its own sentence contentCopy = copy.deepcopy(content) result = re.search('(BOLD_END.*<BOLD>)|(ITALICS_END.*<ITALICS>)', contentCopy) final = False if result is not None and len(result.group()) > 14: final = True # if reach a period if '.' in char and (('<BOLD>' not in contentCopy[:7] or final) and ('<ITALICS>' not in contentCopy[:10] or final)) or content.count('.') == 2: sentence.add_text( Text(text.run_offset, text.content, beginningOfSentenceOffset - text.run_offset, len(content))) sentences.append(sentence) sentence = Sentence() content = '' beginningOfSentenceOffset = text.run_offset + distance_from_run_offset sentence.add_text( Text(text.run_offset, text.content, beginningOfSentenceOffset - text.run_offset, len(content))) distance_from_run_offset = 0 if content != '': sentences.append(sentence) return sentences
def is_end(): if player1.pos == 18: screen.fill((30, 144, 255)) end = Text('arial', 50, 'Vyhrál MODRÝ hráč!', 'white') end.rect.x = SCREEN_WIDTH / 2 - 240 end.rect.y = SCREEN_HEIGHT / 2 - 25 screen.blit(end.text_r, end.rect) return True elif player2.pos == 18: screen.fill((204, 0, 0)) end = Text('arial', 50, 'Vyhrál ČERVENÝ hráč!', 'white') end.rect.x = SCREEN_WIDTH / 2 - 260 end.rect.y = SCREEN_HEIGHT / 2 - 25 screen.blit(end.text_r, end.rect) return True return False
def makeMenu(self): # Title self.title = Text(self.screen, (self.mid, self.height_unit), 40, 'Settings', 'purple') self.makeNormalButtons() self.makeMusicButton() self.compileMenu()
def train(): default = 'database/treino.csv' a = input('Nome default da tabela de Treino: ' + default + '\n1 - Continuar' '\n2 - Mudar' '\nSelecione uma opção: ') if str.upper(a) in {'S', 'Y', '1'}: print('Continuando com a a tabela: ' + default) else: i = 1 filenames = [] for f in os.listdir(os.path.join( Path().absolute(), "database")): # lendo todos os arquivos .csv em database/ if f.endswith(".csv"): print(str(i) + ' - ' + f) filenames.append('database/' + f) i += 1 while True: a = input('Digite o numero da tabela que deseja usar: ') a = int(a) - 1 if a == -1: exit(0) try: default = filenames[a] break except IndexError: print('Numero inválido. Se deseja sair digite 0.') a = input('Debug? S/N: ') debug_mode = False if str.upper(a) in {'S', 'Y', '1'}: debug_mode = True start = datetime.datetime.now() db = DB(debug=debug_mode, filename='basefull', run_on_ram=True) with open(default, newline='', encoding='utf-8-sig') as csvfile: # lendo o csv reader = csv.reader(csvfile, delimiter=";", quoting=csv.QUOTE_NONE) for row in reader: # para cada linha t = Text(str.split(str.upper(row[1])), row[0]) # cria um Text if t: t.build_phrases(3) if debug_mode: t.print_phrases() db.insert_text(t, debug_mode) del t else: return -100 end = datetime.datetime.now() print('Começou: ' + start.strftime("%H:%M:%S")) print('Terminou: ' + end.strftime("%H:%M:%S")) print('Delta: ' + str(end - start))
def train(file, phrase_size): db = DB(path='', filename=file, run_on_ram=True) with open(file, newline='', encoding='utf-8-sig') as csvfile: # lendo o csv reader = csv.reader(csvfile, delimiter=";", quoting=csv.QUOTE_NONE) for row in reader: # para cada linha t = Text(str.split(str.upper(row[1])), row[0]) # cria um Text if t: t.build_phrases(phrase_size) db.insert_text(t) del t else: return -100
def Brilho(data_validation_source, firefly, DB_V): alfas = AlfaCluster(len(firefly), firefly) positive_error = 0 # erro positivo negative_error = 0 # erro negativo sentence_counter = 0 with open( data_validation_source, encoding='utf-8-sig' ) as csv_file: # conta a quantidade de linhas no arquivo original csv_reader = csv.reader(csv_file, delimiter=';') TP = 0 FP = 0 TN = 0 FN = 0 for row in csv_reader: sentence_counter = sentence_counter + 1 t = Text(str.split(str.upper(row[1])), row[0]) if t: t.build_phrases(3) # construir frases first = 0 prob = 0 for p in t.phrases: p_prob = DB_V.get_phrase_prob(p) temp_alfa = alfas.getalfa(p_prob) if first != 0: prob = prob * ( 1 - p_prob )**temp_alfa # busca a probabilidade associada à frase e calcula probabilidade do texto else: prob = ( 1 - p_prob )**temp_alfa # busca probabilidade da primeira frase first = 1 prob = 1 - prob error = float(t.probability) - prob if (prob >= 0.5 and float(t.probability) >= 0.5) or ( prob <= 0.5 and float(t.probability) <= 0.5): if prob >= 0.5: TP = TP + 1 else: TN = TN + 1 else: if prob >= 0.5: FP = FP + 1 else: FN = FN + 1 if error > 0: positive_error += error else: negative_error += error del t #return (positive_error + abs(negative_error))/sentence_counter #retorna o erro mais 0.000001 para evitar divisão por 0 return (TP + TN) / (sentence_counter)
def initGodMode(self): ''' God Mode This is here to debug the game without dying, and without having to edit the code. ''' self.god_mode = True self.player.max_health = 1000000000000000000000000000 self.player.health = self.player.max_health self.gt = Text(self.game_screen, (110, self.game_screen.get_height() - 20), 20, 'god mode activated') self.player.arms.strength *= 10000
def __init__(self): pygame.init() size = (WIDTH, HEIGHT) if FULLSCREEN: self.displaySurf = pygame.display.set_mode( size, pygame.HWSURFACE | pygame.FULLSCREEN) else: self.displaySurf = pygame.display.set_mode(size, pygame.HWSURFACE) self.population = Population() self.clock = pygame.time.Clock() self.target = Target() self.target.set_center(TARGETPOS) self.text = Text() self.obstacles = [Obstacle()]
def __init__(self, controls): x, y = [50, 50] title = Text("Pokémon Game", fonts.title, colors.black, [x, y]) y += title.height + 50 search = Button("Look for Pokémon", fonts.normal, colors.black, [x, y], True, action="scene_change", value="look") y += search.height + 5 team = Button("My team", fonts.normal, colors.black, [x, y]) y += team.height + 5 exit = Button("Exit", fonts.normal, colors.black, [x, y], action="shutdown") buttons = [search, team, exit] button_manager = ButtonManager(buttons, controls) super().__init__([title, button_manager])
p_list.append(odpoved2.text) elif number == 3: p_list.append(odpoved3.text) elif number == 4: p_list.append(odpoved4.text) pygame.init() clock = pygame.time.Clock() circles_num = [] for idx, circle in enumerate(circles_json['circles']): circles.append(Circle(circle['x'], circle['y'])) circles[idx].colour = okruhy_barva[okruhy[idx]] if idx > 0: circles_num.append(Text('arial', 15, f'{idx}', 'black')) else: circles_num.append(Text('arial', 15, 'START', 'black')) question = Text('arial', 40, 'a', 'black') odpoved1 = Text('arial', 20, 'a', 'black') odpoved2 = Text('arial', 20, 'a', 'black') odpoved3 = Text('arial', 20, 'a', 'black') odpoved4 = Text('arial', 20, 'a', 'black') odpovedi = pygame.sprite.Group(odpoved1, odpoved2, odpoved3, odpoved4) question.rect.y = 200 question.rect.x = 100 odpoved1.rect.y = 365 odpoved1.rect.x = 300 odpoved2.rect.y = 470 odpoved2.rect.x = 300
def makeText(self): ''' Create text object ''' self.text = Text(self.screen, self.position, self.font_size, self.text, self.text_colour)
'text': '' }) # col_analyze.insert({'level': 'step5', 'desc': '', 'text': ''}) # col_analyze.insert({'level': 'step6', 'desc': '', 'text': ''}) # col_analyze.insert({'level': 'step7', 'desc': '', 'text': ''}) # col_analyze.insert({'level': 'step8', 'desc': '', 'text': ''}) # col_analyze.insert({'level': 'step9', 'desc': '', 'text': ''}) init_bigtc() data = col_analyze.find({'level': 'step1'}) news_doc = data[0]['text'] print(news_doc) news_doc = Text.remove_special_chars(news_doc) col_analyze.update({'level': 'step2'}, {'$set': {'text': news_doc}}) print(news_doc) news_doc = Text.make_list_of_words(news_doc) col_analyze.update({'level': 'step3'}, {'$set': {'text': news_doc}}) print(news_doc) news_doc = Text.remove_stop_words_and_stem(news_doc) col_analyze.update({'level': 'step4'}, {'$set': {'text': news_doc}}) print(news_doc) # print(news_sample) # print(len(news_sample)) # news_sample = remove_special_chars(news_sample)
def scoreBoard(screen, delay): ''' Function which creates a screen where a score bored is displayed by using the values from highscores.txt. ''' # establishing a clock for the screen clock = pygame.time.Clock() # Creating width and height variables. width = screen.get_width() height = screen.get_height() # loading a list from game over screen with the newest scores. score_list = loadScoreList() if len(score_list) < 10: n_scores = len(score_list) else: n_scores = 10 # Creating text objects for n highest scores. Header = Text(screen, (width // 2, height // 8), 50, f'TOP {n_scores} SCORES', 'purple') score_objects = [] for k in range(n_scores): index = - 1 * (k + 1) score_objects.append( Text(screen, (width // 2, 120 + (k * 40)), 35, f'{score_list[index][0]} = {score_list[index][1]}') ) # Creating a button for going back to the game over screen. back = Button(screen, 'Back', (400, 585), (lambda: 'go_back'), 25, (126, 64)) menu = Menu(screen, Header, False, back) # Creating a loop for the scoreboard screen. run = True while run: clock.tick(delay) for event in pygame.event.get(): # Send each event to the start menu if event.type == pygame.QUIT: # Detecting user pressing quit button, if X pressed, # break loop and quit screen. quitGame() # Checking if the Back button is being pressed. elif (event.type == pygame.MOUSEBUTTONDOWN) or \ (event.type == pygame.MOUSEBUTTONUP): button_press = menu.do(event) if button_press == 'go_back': run = False # Bliting background image. screen.blit(background, (0, 0)) # Bliting text objects and button to screen. for score_object in score_objects: score_object.display() menu.display() pygame.display.flip()
def __init__(self): font_title = pygame.font.Font("freesansbold.ttf", 54) c_white = (255, 255, 255) x, y = [50, 50] title = Text("Look for Pokémon", font_title, c_white, [x, y]) super().__init__([title])
def validation_text_comparison(data_validation_source, report_flag, training_file, report_name, error_threshold, alfas, database): DB_V = DB(database + "/", "database", debug=False, run_on_ram=database + "/database.sql") print(database) now = datetime.datetime.now() positive_error = 0 #erro positivo negative_error = 0 #erro negativo positive_error_c = 0 #contagem de erro positivo negative_error_c = 0 #contagem de erro negativo sentence_counter = 0 #contagem de frases with open( data_validation_source, encoding='utf-8-sig' ) as csv_file: # conta a quantidade de linhas no arquivo original csv_reader = csv.reader(csv_file, delimiter=';') if report_flag: #caso a flag de relatório esteja ativada with open("../reports/" + report_name + "/report.out", "w") as report: #abre arquivo de relatório orig_stdout = sys.stdout # guarda saida padrão sys.stdout = report # troca saida padrão por relatório print("Data: (DD/MM/AAAA)" + str(now.day) + "/" + str(now.month) + "/" + str(now.year)) print("Hora: (HH:MM:SS)" + str(now.hour) + ":" + str(now.minute) + ":" + str(now.second)) print("Training_File: " + training_file) print("Validation_File: " + data_validation_source) for row in csv_reader: sentence_counter += 1 t = Text(str.split(str.upper(row[1])), row[0]) if t: t.build_phrases(3) #construir frases first = 0 prob = 0 for p in t.phrases: p_prob = DB_V.get_phrase_prob(p) print("Palavra: " + (p.words[0].value.encode('ascii', 'ignore') ).decode('utf-8')) print("Palavra: " + (p.words[1].value.encode('ascii', 'ignore') ).decode('utf-8')) print("Palavra: " + (p.words[2].value.encode('ascii', 'ignore') ).decode('utf-8')) print("Probabilidade: " + str(p_prob)) temp_alfa = alfas.getalfa(p_prob) print("Alfa: " + str(temp_alfa)) if first != 0: prob = prob * ( 1 - p_prob )**temp_alfa # busca a probabilidade associada à frase e calcula probabilidade do texto else: prob = ( 1 - p_prob )**temp_alfa # busca probabilidade da primeira frase first = 1 prob = 1 - prob print(row) #imprime texto print("Probabilidade do texto: " + str( t.probability)) #imprime probabilidade do texto print("Probabilidade calculada: " + str(prob)) #imprime probabilidade calculada error = float(t.probability) - prob if error > 0: positive_error += error if error > error_threshold: positive_error_c += 1 else: negative_error += error if error < error_threshold * -1: negative_error_c += 1 del t print("Numero de frases: " + str(sentence_counter)) print("Erro positivo: " + str(positive_error)) print("Erro negativo: " + str(negative_error)) print("Erro total: " + str(positive_error + abs(negative_error))) print("Contagem de Erros Positivos: " + str(positive_error_c)) print("Contagem de Erros Negativos: " + str(negative_error_c)) sys.stdout = orig_stdout # reseta saída report.close() #fechar arquivo de relatório # caso a flag de relatório esteja desativada else: for row in csv_reader: sentence_counter += 1 t = Text(str.split(str.upper(row[1])), row[0]) if t: t.build_phrases(3) #construir frases first = 0 prob = 0 for p in t.phrases: p_prob = DB_V.get_phrase_prob(p) temp_alfa = alfas.getalfa(p_prob) if first != 0: prob = prob * ( 1 - p_prob )**temp_alfa # busca a probabilidade associada à frase e calcula probabilidade do texto else: prob = ( 1 - p_prob )**temp_alfa # busca probabilidade da primeira frase first = 1 prob = 1 - prob error = float(t.probability) - prob if error > 0: positive_error += error if error > error_threshold: positive_error_c += 1 else: negative_error += error if error < error_threshold * -1: negative_error_c += 1 del t return 1 - ( positive_error + abs(negative_error) ) / sentence_counter #retorna o erro mais 0.000001 para evitar divisão por 0
def get_all_season(url): headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36" } html = requests.get(url, headers=headers) soup = bs(html.content, features="html.parser") player = soup.select('.dataMain > .dataTop > .dataName > h1')[0].text player = f"name:{player}" table = soup.select( '.responsive-table > .grid-view > .items > tbody')[0] profile = soup.select('.dataContent > .dataBottom > .dataDaten') ribbon = soup.select('.dataRibbon > a') if len(ribbon) > 0: ribbon = ribbon[0]['title'] player_bio = [] country = [] for items in profile: for p in items.find_all('p'): for datavalue in p.find_all( True, {"class": re.compile("^(dataValue)$")}): if len(datavalue.find_all('img')) > 0: country.append(datavalue.find_all('img')[0]['title']) bio_data = Text.format_text(p.text) player_bio.append(bio_data) player_bio.append(player) bio = Data.get_bio(player_bio, country) stats = [] try: for cells in table.find_all(True, {"class": re.compile("^(even|odd)$")}): season = cells.find_all('td')[0].text league = cells.find_all( 'td')[1].img['title'] if cells.find_all( 'td')[1].img else '' club = cells.find_all('td')[3].img['alt'] squad = cells.find_all('td')[4].text apps = cells.find_all('td')[5].a.text goals = cells.find_all('td')[7].text assists = cells.find_all('td')[8].text stats_item = { 'season': season, 'league': league, 'club': club, 'squad': squad, 'apps': apps, 'goals': goals, 'assists': assists, } stats.append(stats_item) except IndexError: pass return stats, bio, ribbon
import sys import string from classes.dictionary import Dictionary from classes.text import Text outputfile = "" if len(sys.argv) == 4 : #if all arguments are provided filedict,filetext,outputfile = sys.argv[1],sys.argv[2],sys.argv[3] else: #if o/p filename is not provided filedict,filetext = sys.argv[1],sys.argv[2] d = Dictionary(filedict) if not outputfile: t = Text(filetext) else: t = Text(filetext,outputfile) t.chk_words = d.verify(t.chk_words) t.write()
# Title position title_x = screen_width // 2 title_y = screen_height // 9 # Calculating (x,y) coords of buttons width_unit = screen_width // 6 height_unit = screen_height // 2 major_button_dims = (192, 64) offset = 20 about_position = (screen_width - 64 - offset, 32 + offset) # Creating pygame string objects title_obj = Text(menu_screen, (title_x, title_y), font_size['title'], menu_title, 'purple') play_button = Button(menu_screen, play_text, (1 * width_unit, height_unit), playGame, 35, major_button_dims) settings_button = Button(menu_screen, settings_text,(3 * width_unit, height_unit), runSettings, 30, major_button_dims) about_button = Button(menu_screen, about_text, about_position, loadAbout, 30) quit_button = Button(menu_screen, quit_text, (5 * width_unit, height_unit), quitGame, 35, major_button_dims) # Initialising StartMenu class start_menu = Menu(menu_screen, title_obj, menu_background, play_button,
def draw_sheet(data, sheet_n, stats, bio, ribbon): sheet = Image.new('RGB', (800, 800), color=data['bg_color_2']) draw = ImageDraw.Draw(sheet) draw.rectangle((0, 700, 800, 0), fill=data['bg_color_1']) draw.rectangle((10, 790, 790, 10), fill='#FFF') thumb_size = 800, 800 player_image = Files.open_url(data['photo']) player_image = player_image.convert('RGBA') player_image.thumbnail(thumb_size, Image.ANTIALIAS) player_image_w, player_image_h = player_image.size sheet = Images.apply_image(sheet, player_image, (0, 0), (player_image.size)) # Apply the Data Science logo logo = Files.open_local('./src/images/logo.png') sheet = Images.apply_image(sheet, logo, (10, 10), (75, 75)) if sheet_n == 0: bio_text = Text.write_bio(stats, bio, ribbon) lines = textwrap.wrap(bio_text, 50) medium_font = ImageFont.truetype('./src/fonts/Lato-Bold.ttf', 30) img_width, img_height = sheet.size y_text = player_image_h + 15 for line in lines: draw = ImageDraw.Draw(sheet) width, height = medium_font.getsize(line) draw.text((50, y_text), line, font=medium_font, fill="#222222") y_text += height if sheet_n == 1: stats_text = Text.write_stats(stats, bio, ribbon) lines = textwrap.wrap(stats_text, 50) medium_font = ImageFont.truetype('./src/fonts/Lato-Bold.ttf', 30) img_width, img_height = sheet.size y_text = player_image_h + 50 for line in lines: draw = ImageDraw.Draw(sheet) width, height = medium_font.getsize(line) draw.text((50, y_text), line, font=medium_font, fill="#222222") y_text += height if sheet_n == 2: national_stats_text = Text.write_national_stats(bio) lines = textwrap.wrap(national_stats_text, 50) medium_font = ImageFont.truetype('./src/fonts/Lato-Bold.ttf', 30) img_width, img_height = sheet.size y_text = player_image_h + 50 for line in lines: draw = ImageDraw.Draw(sheet) width, height = medium_font.getsize(line) draw.text((50, y_text), line, font=medium_font, fill="#222222") y_text += height return sheet
def introScreen(screen, controller): ''' Produces the intro cut scene based on star wars Obviously I took inspiration from the famous Star Wars intro, in the layout of this. ''' # Get important screen variables height = screen.get_height() width = screen.get_width() # Make story objects story = open(story_location, 'r') title = [] main_story = [] # Setup screen position x_position = width // 2 title_y = height // 2 - 20 main_y = height // 2 # Extracting relevant text for line in story: if line[0:5] == 'TITLE': title_element = line[6:-1] title.append( Text(screen, (x_position, title_y), 40, title_element, 'turquoise')) title_y += 50 elif line[0:4] == 'MAIN': main_element = line[5:-1] main_story.append( Text(screen, (x_position, main_y), 20, main_element, 'yellow')) main_y += 30 story.close() title_count = 300 move = True # load clock clock = pygame.time.Clock() run_scene = True while run_scene: clock.tick(controller.clock_delay) # Get/action events for event in pygame.event.get(): # Send each event to the start menu if event.type == pygame.QUIT: # Detecting user pressing quit button, if X pressed, # break loop and quit screen. run_scene = False controller.run = False elif (event.type == pygame.KEYDOWN) and \ (event.key == pygame.K_ESCAPE): run_scene = False screen.fill('black') if title_count > 0: for element in title: element.display() title_count -= 1 else: for element in main_story: element.display() if move: element.y -= 1 if move: move = False else: move = True if main_story[-1].y == height // 4: run_scene = False pygame.display.flip()
def gameOver(screen, score, delay): def saveScore(): ''' Function which takes user name and current score and stores it in a text file. ''' saves = open(HIGH_SCORE_LOCATION, 'a') saved_score = f'{player_name.text}/{score.text}\n' saves.write(saved_score) saves.close() # load clock clock = pygame.time.Clock() # Generate useful positions width = screen.get_width() height = screen.get_height() mid = width // 2 left = width // 5 right = 4 * left height_unit = height // 20 # Load previous scores and calculate highscore scores = loadScoreList() if (len(scores) > 0) and (scores[-1][-1] >= score): highscore_string = f'{scores[-1][0]} : {scores[-1][-1]}' else: highscore_string = f'You! : {score}' # Text input is active active = True started = False # Creating text for the main header. menu_title = Text(screen, (mid, 2 * height_unit), 70, 'Game Over', 'Purple') # Creating a header for the score. score_header = Text(screen, (mid, 4 * height_unit), 30, f'HIGHSCORE') # Creating text object for the highest score of the game high_score = Text(screen, (mid, 5 * height_unit), 25, highscore_string) # Creating text object for the current score of the game your_score = Text(screen, (mid, 7 * height_unit), 30, f'YOUR SCORE') # Creating object for the current score. score = Text(screen, (mid, 8 * height_unit), 25, f'{score}') player_name_center = (mid, 9 * height_unit) player_name = Text(screen, player_name_center, 30, '[Enter Name Here]', 'yellow') save_score = Button(screen, 'Save Score', (mid, 11 * height_unit), (lambda: 'save'), 25, (200, 64)) # Creating a button for scoreboard. score_board = Button(screen, 'Scoreboard', (left, 18.5 * height_unit // 1), (lambda: 'scoreboard'), 25, (200, 64)) # Creating a button for main menu. back_to_menu = Button(screen, 'Main menu', (mid, 18.5 * height_unit // 1), (lambda: 'main_menu'), 25, (200, 64)) # Creating a button to exit the game exit_game = Button(screen, 'Quit', (right, 18.5 * height_unit // 1), quitGame, 25, (200, 64)) menu = Menu(screen, menu_title, BACKGROUND_LOCATION, back_to_menu, score_board, exit_game, save_score) saved_menu = Menu(screen, menu_title, BACKGROUND_LOCATION, back_to_menu, score_board, exit_game) # Game over screen loop which checks for inputs of buttons and user text input. run = True while run: clock.tick(delay) # Get/action events for event in pygame.event.get(): # Send each event to the start menu if event.type == pygame.QUIT: # Detecting user pressing quit button, if X pressed, # break loop and quit screen. quitGame() # Check if the text box is pressed on. # If so user can input text in to the box and # save it to the variable user_name. if event.type == pygame.KEYDOWN: if active: if event.key == pygame.K_BACKSPACE: player_name.text = player_name.text[0:-1] player_name.position = player_name.position elif pygame.key.name(event.key) in ALPHABET: if not started: player_name.text = '' started = True player_name.text += event.unicode player_name.position = player_name_center[0], \ player_name_center[1] player_name.makeRect() # Do mouse up/down events elif (event.type == pygame.MOUSEBUTTONDOWN) or \ (event.type == pygame.MOUSEBUTTONUP): button_press = menu.do(event) if button_press == 'main_menu': run = False elif button_press == 'scoreboard': scoreBoard(screen, delay) elif button_press == 'save': saveScore() active = False menu = saved_menu player_name.colour = 'white' # Blit the background image to the screen. screen.fill('black') # Make a rect for the text box #pygame.draw.rect(screen, color, input_rect) # Render the text inputted by the user. #text_surface = base_font.render(user_name, True, (255, 255, 255)) # Blit the text to screen #screen.blit(text_surface, (input_rect.x + 5, input_rect.y + 5)) # Place the text on the rectangle #input_rect.w = max(100, text_surface.get_width() + 10) # Display menu here - this will display all buttons included in # the menu # menu.display() # Text (apart from menu title text) needs to be displayed # separately menu.display() player_name.display() score_header.display() score.display() high_score.display() your_score.display() pygame.display.flip()
col_analyze.insert({'level': 'step2', 'desc': 'Remove special characters', 'text': ''}) col_analyze.insert({'level': 'step3', 'desc': 'Make list of words', 'text': ''}) col_analyze.insert({'level': 'step4', 'desc': 'Remove stop words and stem', 'text': ''}) # col_analyze.insert({'level': 'step5', 'desc': '', 'text': ''}) # col_analyze.insert({'level': 'step6', 'desc': '', 'text': ''}) # col_analyze.insert({'level': 'step7', 'desc': '', 'text': ''}) # col_analyze.insert({'level': 'step8', 'desc': '', 'text': ''}) # col_analyze.insert({'level': 'step9', 'desc': '', 'text': ''}) init_bigtc() data = col_analyze.find({'level': 'step1'}) news_doc = data[0]['text'] print(news_doc) news_doc = Text.remove_special_chars(news_doc) col_analyze.update({'level': 'step2'}, {'$set': {'text': news_doc}}) print(news_doc) news_doc = Text.make_list_of_words(news_doc) col_analyze.update({'level': 'step3'}, {'$set': {'text': news_doc}}) print(news_doc) news_doc = Text.remove_stop_words_and_stem(news_doc) col_analyze.update({'level': 'step4'}, {'$set': {'text': news_doc}}) print(news_doc) # print(news_sample) # print(len(news_sample)) # news_sample = remove_special_chars(news_sample)
def pauseScreen(screen, controller): ''' Pause Screen function Produces the pause screen and allows interaction with buttons. ''' height = screen.get_height() width = screen.get_width() height_unit = height // 3 mid_x, mid_y = width // 2, height // 2 menu_height = 3 * height // 4 width_unit = width // 6 # Setup menu and buttons paused_text = Text(screen, (mid_x, height_unit), 60, 'PAUSED', 'purple') resume_button = Button( screen, 'Resume', (width_unit, 2 * height_unit), (lambda : 'resume'), 20, (192, 64) ) main_menu_button = Button( screen, 'Main Menu', (3 * width_unit, 2 * height_unit), (lambda : 'main_menu'), 18, (192, 64) ) quit_button = Button( screen, 'Quit', (5 * width_unit, 2 * height_unit), quitGame, 20, (192, 64) ) pause_menu = Menu(screen, paused_text, False, resume_button, main_menu_button, quit_button) # load clock clock = pygame.time.Clock() paused = True while paused: clock.tick(controller.clock_delay) # Get/action events for event in pygame.event.get(): # Send each event to the menu if event.type == pygame.QUIT: # Detecting user pressing quit button, if X pressed, # break loop and quit screen. paused = False elif (event.type == pygame.KEYDOWN) and \ (event.key == pygame.K_ESCAPE): paused = False # Here, we check whether the player has clicked the mouse, # if they have, we pass the click into the pause menu and it # processes the click. The button function returns a string # 'resume' for resume game, or 'main_menu' to quit to main # menu. elif (event.type == pygame.MOUSEBUTTONDOWN) or \ (event.type == pygame.MOUSEBUTTONUP): button_press = pause_menu.do(event) #print(button_press) if button_press == 'resume': paused = False elif button_press == 'main_menu': controller.run = False paused = False # Display Pause Menu pause_menu.display() pygame.display.flip()