class EventHandler: # global mousePosition, clicked def __init__(self): self.clicked = False self.mousePosition = list(pygame.mouse.get_pos()) self.textInput = TextInput() self.textOutput = TextOutput() self.textOutputRect = None def eventLoop(self): # --- Get all events in a for loop events = pygame.event.get() for event in events: # --- If user clicked close if event.type == pygame.QUIT: closeWindow() # --- If the ESCAPE Key was pressed if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: closeWindow() # --- if user moved the mouse if event.type == pygame.MOUSEMOTION: # get mouse position self.mousePosition = list(event.pos) # --- if user clicked one of the mouse buttons if event.type == pygame.MOUSEBUTTONDOWN: # set clicked flag true self.clicked = True else: self.clicked = False self.textInput.update(events) #self.textOutput.update()
def __init__(self, x, y, width=600, font_size=15): self.input = TextInput(font_family='dpcomic.ttf', antialias=False, max_string_length=width//font_size - 4) self.font_size = font_size self.surf = pg.Surface((width, font_size*3)).convert_alpha() self.surf.fill((88, 88, 88, 88)) self.visible = False self.pos = x, y
def __init__(self, max_length = -1, numbers_only = False, english_only = False, action = "",\ display_text_color = (0, 0, 0), border_size = 1, border_color = (0, 0, 0),\ color = (255, 255, 255), area = ((0, 0), (0, 0)), spacing = 0): self.text_object = TextInput(text_color=display_text_color, max_string_length=max_length, font_size=22) self.max_length = max_length self.action = action self.numbers_only = numbers_only self.english_only = english_only self.border_size = border_size self.border_color = border_color self.color = color self.display_text_color = display_text_color self.area = area self.spacing = spacing self.active = False
class ChatInputWindow: def __init__(self, x, y, width=600, font_size=15): self.input = TextInput(font_family='dpcomic.ttf', antialias=False, max_string_length=width//font_size - 4) self.font_size = font_size self.surf = pg.Surface((width, font_size*3)).convert_alpha() self.surf.fill((88, 88, 88, 88)) self.visible = False self.pos = x, y def update_surf(self): self.surf.fill((88, 88, 88, 88)) self.surf.blit( self.input.font_object.render( '#', False, self.input.text_color), (self.font_size, self.font_size)) self.surf.blit(self.input.get_surface(), (3*self.font_size, self.font_size)) def update(self, events): for event in events: if event.type == pg.KEYDOWN: if event.key == pg.K_t and not self.visible: self.visible = True return if self.visible and self.input.update(events): self.parse(self.input.get_text()) self.input.clear_text() self.visible = False def parse(self, text): if not text.startswith('/'): print(text) # Just print text else: cmd(text[1:]) # Execute command def draw(self, screen): if self.visible: self.update_surf() screen.blit(self.surf, self.pos)
class Textbox: def __init__(self, max_length = -1, numbers_only = False, english_only = False, action = "",\ display_text_color = (0, 0, 0), border_size = 1, border_color = (0, 0, 0),\ color = (255, 255, 255), area = ((0, 0), (0, 0)), spacing = 0): self.text_object = TextInput(text_color=display_text_color, max_string_length=max_length, font_size=22) self.max_length = max_length self.action = action self.numbers_only = numbers_only self.english_only = english_only self.border_size = border_size self.border_color = border_color self.color = color self.display_text_color = display_text_color self.area = area self.spacing = spacing self.active = False def update(self, events): is_enter_pressed = self.text_object.update(events) #temp_text = "" #for char in self.TextInput.input_string: # if char.isdigit() and self.numbers_only: # temp_text += char # elif (char.isalpha() or char == " ") and self.english_only: # temp_text += char ##self.TextInput.input_string == temp_text if self.english_only: pass if self.numbers_only: if self.TextInput.input_string.isdigit(): pass return is_enter_pressed def draw(self, main_surface): pygame.draw.rect(main_surface, self.border_color, self.area) new_area = ((self.area[0][0] + self.border_size, self.area[0][1] + self.border_size),\ (self.area[1][0] - (2*self.border_size), self.area[1][1] - (2*self.border_size))) pygame.draw.rect(main_surface, self.color, new_area) text_surf = self.text_object.get_surface() new_spot = (new_area[0][0] + self.spacing, new_area[0][1] + ((new_area[1][1] - text_surf.get_height()) / 2)) main_surface.blit(text_surf, new_spot)
def __init__(self, question, answer, x, y, part_name) -> None: super().__init__() self.question = question self.answer = answer.lower() self.door_done = image.load(join( "assets", "door done.png")).convert_alpha() self.door_done = transform.scale(self.door_done, (256, 256)) self.image = image.load(join( "assets", "door.png")).convert_alpha() self.image = transform.scale(self.image, (256, 256)) self.rect = self.image.get_rect() self.rect.x = x self.rect.centery = y self.asking = False self.input = TextInput(text_color=WHITE) self.done = False self.part_name = part_name for a in player.acquired: if a['name'] == self.part_name: if self.question in a['question']: self.done = True self.image = self.door_done
def ask_player_for_username(screen, stats): fontsize = 35 inputfield = TextInput( "USERNAME", font_family="Ariel", text_color=pygame.Color("white"), cursor_color=pygame.Color("red"), font_size=fontsize, ) username = None myfont = pygame.font.SysFont("sans serif", fontsize) message = Message( (550, 550), "Type your name & press Enter", font=myfont, color=pygame.Color("green"), ) while True: draw_background_image(screen) draw_saveusername_page(screen) events = pygame.event.get() for event in events: if event.type == pygame.QUIT: stats.close_asteroids_timer() sys.exit() if inputfield.update(events): username = inputfield.get_text() break screen.blit( inputfield.get_surface(), (650, 500), ) message.blitme(screen) pygame.display.update() return username
from Functions import * from pygame_textinput import TextInput from DataBase import * import MUSIC textinput = TextInput() class FinalCutscene(): # всё, что происходит после окончания уровня def __init__(self, screen, clock, level, nick, coins): self.background = screen self.screen = screen self.coins = coins self.nick = nick self.clock = clock self.level = level add(self.nick, self.level, self.coins) # добавление данных в базу данных def start(self): # вывод результатов res = conclusion(self.nick, self.level) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: terminate() elif event.type == pygame.KEYDOWN and ( event.key == pygame.K_KP_ENTER or event.key == pygame.K_RETURN): self.results() return # начинаем игру
def Main(enter, exit): # Run main // (enter, exit) are not used to track exit conditions pygame.init() pygame.display.set_caption("PSI") g_settings = Settings(exit) screen = pygame.display.set_mode((g_settings.screen_width, \ g_settings.screen_height)) font = pygame.font.SysFont(None, 48) g_settings.load_background(screen) stats = Stats(g_settings) ship = Ship(screen, g_settings, stats) reticle = Reticle(g_settings, screen) textbox = TextInput() aliens = Alien(screen, g_settings) scores = Score(g_settings, screen, stats, ship) powerups = Group() twits = Group() # wpns bullets = Group() lazers = Group() bombs = Group() # Our weapons projectiles = [bombs, bullets, lazers] # btns attack_btn = Button(g_settings, screen, [527, 400, 159, 50], 2) login_btn = Button(g_settings, screen, [130, 258, 220, 50], 2) about_btn = Button(g_settings, screen, [820, 260, 245, 50], 2) pass_btn = Button(g_settings, screen, [550, 342, 100, 37], 2) passed_btn = Button(g_settings, screen, [540, 342, 122, 37], 2) # Our buttons buttons = [login_btn, about_btn, attack_btn, pass_btn, passed_btn] clock = pygame.time.Clock() FPS = 22 """ KEYDOWNS occurring outside of gameplay compute within pygame_textinput.py When game is active, textbox.update() ceases, and gf.check_events takes over. """ while True: # Main Game Loop loops clock.tick(FPS) if gf.update_screen(g_settings, screen, font, ship, textbox, aliens, reticle, \ twits, powerups, projectiles, stats, \ scores, buttons) == 'TX_QUIT': # If we receive the quit flag. return True if stats.game_active == True: #enter.send('hello') # As per the DocString if gf.check_events(g_settings, screen, ship, aliens, stats, \ scores, projectiles) == 'CE_QUIT': # if we receive the quit flag return True if stats._current_screen == 3: gf.update_bullets(g_settings, screen, stats, ship, \ scores, projectiles, powerups, \ enter, exit, twits=twits) gf.update_twits(g_settings, screen, stats, ship, powerups,\ twits, scores, projectiles)
class live_display(): _tick = 60 _shop_input = TextInput() _accepted_event1 = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] _accepted_event2 = [K_BACKSPACE, K_DELETE, K_RETURN, K_RIGHT, K_LEFT, K_END, K_HOME, KEYUP] _temp_buttons = None _scroll_y = 0 _black_surface = pygame.Surface((1920,1080), 255) _black_surface.set_alpha(190) def __init__(self, w, h, hive): self._w = w self._h = h self._hive = hive def give_display(self, live, alert, surface, events, buttons, first_call, bees_surfaces, scroll_y, territory, hive_territories): # permet d'appeler la méthode de live_display correspondant à l'affichage en cours, grâce à live if live == "menu": return self.live_menu(surface, alert, buttons) elif live == "management": return self.live_management(surface, events, buttons, alert, bees_surfaces, scroll_y) elif live == "shop": return self.live_shop(surface, events, buttons, alert, first_call, bees_surfaces, scroll_y) elif live == "fight_menu": return self.live_fight_menu(surface, buttons, alert, first_call, territory, hive_territories) elif live == "up": return self.live_up(surface, bees_surfaces, scroll_y, events, buttons, alert, first_call) def live_up(self, surface, bees_surfaces, scroll_y, events, buttons, alert, first_time): max_y = 950 scroll_surface, up_buttons, scroll_y = self.scroll(bees_surfaces, events, scroll_y, max_y) #positionner correctement purchase buttons surface = self.display_ressources(surface) buttons['upgrade_purchase'] = [] buttons['desc'] = [] for but in up_buttons: if but._text == "Description": buttons['desc'].append(but) else: buttons['upgrade_purchase'].append(but) pos_x = 400 pos_y = 200 # valeurs liées aux boutons de display de la bee_surface container_surface = pygame.Surface((1200, 1000), pygame.SRCALPHA) container_surface.blit(scroll_surface, (0, scroll_y)) surface.blit(container_surface, (pos_x, pos_y)) good_up = None font = pygame.font.SysFont('comicsans', 50) #print("DEBUT", alert, first_time) if alert != None: if first_time == True: self._temp_buttons = buttons first_time = False for up in self._hive._upgrades: if up._name == alert[1] and up._lvl == alert[2]: good_up = up surface.blit(self._black_surface, (0,0)) msg = font.render(good_up._description, 1, (255,255,255)) surface.blit(msg, (975-len(good_up._description)*9,550)) buttons = {"ok": button((255,180,255), 900, 600, 150, 80, self._w, self._h, 'Ok', font='comicsans', sizeFont=40)} buttons["ok"].draw_button(surface) elif alert == None and first_time == False: buttons = {} buttons = self._temp_buttons first_time = True return surface, scroll_y, buttons, alert, first_time def live_fight_menu(self, surface, buttons, alert, first_call, sent_territory, hive_territories): # print(sent_territory, alert, first_call) if sent_territory != None and alert == None: if first_call == True: self._temp_buttons = buttons first_call = False for territory in hive_territories: if territory._name == sent_territory: buttons = {} surface.blit(self._black_surface, (0,0)) font = pygame.font.SysFont('comicsans', 50) msg = font.render(territory._display_name, 1, (255,255,255)) surface.blit(msg, (900-len(territory._display_name)*7.5 ,400)) msg = font.render(territory._description, 1, (255,255,255)) surface.blit(msg, (900-len(territory._description)*8,450)) if territory._possession == False: msg = font.render("Force: " + str(territory.strength()), 1, (255,255,255)) surface.blit(msg, (810,500)) msg = font.render("Recompenses:", 1, (255,255,255)) surface.blit(msg, (780,550)) msg = font.render("+1 niveau", 1, (255,255,255)) surface.blit(msg, (820,600)) msg = font.render( str(territory.strength()), 1, (255,255,255)) surface.blit(msg, (900-len(str(territory.strength()))*7,650)) image = pygame.image.load("./Images/pollen.png") surface.blit(pygame.transform.scale(image, (30, 30)), ( 890 + 20*len(str(territory.strength())), 650 )) msg = font.render( str(territory.strength()), 1, (255,255,255)) surface.blit(msg, (900-len(str(territory.strength()))*7,700)) if territory.ressource() == "honey": image = pygame.image.load("./Images/honey.png") surface.blit(pygame.transform.scale(image, (30, 30)), ( 890 + 20*len(str(territory.strength())), 700 )) elif territory.ressource() == "water": image = pygame.image.load("./Images/water.png") surface.blit(pygame.transform.scale(image, (30, 30)), ( 890 + 20*len(str(territory.strength())), 700 )) elif territory.ressource() == "metal": image = pygame.image.load("./Images/metal.png") surface.blit(pygame.transform.scale(image, (30, 30)), ( 890 + 20*len(str(territory.strength())), 700 )) elif territory.ressource() == "uranium": image = pygame.image.load("./Images/uranium.png") surface.blit(pygame.transform.scale(image, (30, 30)), ( 890 + 20*len(str(territory.strength())), 700 )) buttons["back"] = button((255,180,255), 950, 750, 150, 80, self._w, self._h, 'Retour', font='comicsans', sizeFont=40) buttons["back"].draw_button(surface) buttons["attack"] = button((255,180,255), 700, 750, 150, 80, self._w, self._h, 'Attaquer', font='comicsans', sizeFont=40) buttons["attack"].draw_button(surface) else: msg = font.render('Vous possédez déjà ce territoire !', 1, (255,255,255)) surface.blit(msg, (650,600)) buttons["back"] = button((255,180,255), 825, 750, 150, 80, self._w, self._h, 'Retour', font='comicsans', sizeFont=40) buttons["back"].draw_button(surface) elif alert == "Done": buttons = self._temp_buttons alert = None # elif alert == "mine": # font = pygame.font.SysFont('comicsans', 40) # msg = font.render("Vous possédez déjà ce territoire", 1, (255,255,255)) # surface.blit(msg, (700,550)) # buttons = {"confirm" : button((255,180,255), 700, 600, 150, 80, self._w, self._h, 'Retourner sur la carte', font='comicsans', sizeFont=40)} # buttons["confirm"].draw_button(surface) elif alert == "victory": surface.blit(self._black_surface, (0,0)) font = pygame.font.SysFont('comicsans', 40) msg = font.render("Vous avez envahi ce territoire !", 1, (255,255,255)) surface.blit(msg, (700,550)) buttons = {"confirm" : button((255,180,255), 825, 600, 150, 80, self._w, self._h, 'Retour', font='comicsans', sizeFont=40)} buttons["confirm"].draw_button(surface) first_call = True elif alert == "cant_win": surface.blit(self._black_surface, (0,0)) font = pygame.font.SysFont('comicsans', 40) msg = font.render("Votre armée est trop faible pour envahir le territoire", 1, (255,255,255)) surface.blit(msg, (575,550)) buttons = {"confirm" : button((255,180,255), 825, 600, 150, 80, self._w, self._h, 'Retour', font='comicsans', sizeFont=40)} buttons["confirm"].draw_button(surface) elif alert == None and first_call == False: buttons = self._temp_buttons first_call = True elif sent_territory == None and alert == None: self._temp_buttons = buttons return surface, buttons, first_call, alert def live_menu(self, surface, alert, buttons): surface = self.display_ressources(surface) # alert upgrade_choice if alert == "upgrade_choice": surface.blit(self._black_surface, (0,0)) # display_surface = pygame.Surface((600, 150), pygame.SRCALPHA) # surface.blit(display_surface, (760, 480)) buttons = {"fight_upgrades" : button((255,180,255), 730, 450, 200, 80, self._w, self._h, 'Combat', font='comicsans', sizeFont=55), "hive_upgrades" : button((255,180,255), 990, 450, 200, 80, self._w, self._h, 'Ruche', font='comicsans', sizeFont=55), "cancel" : button((212,180,0), 892, 550, 135, 55, self._w, self._h,'Annuler', font='comicsans', sizeFont=33) } buttons["fight_upgrades"].draw_button(surface) buttons["hive_upgrades"].draw_button(surface) buttons["cancel"].draw_button(surface) return surface, buttons def live_management(self, surface, events, buttons, alert, bees_surfaces, scroll_y): max_y = 830 scroll_surface, delete_buttons, scroll_y = self.scroll(bees_surfaces, events, scroll_y, max_y) buttons['delete_bee_button'] = delete_buttons surface = self.display_ressources(surface) pos_x = 150 pos_y = 250 container_surface = pygame.Surface((1500, 850), pygame.SRCALPHA) container_surface.blit(scroll_surface, (0, scroll_y)) surface.blit(container_surface, (pos_x, pos_y)) alert = "" return surface, "", buttons, alert, scroll_y def live_shop(self, surface, events, buttons, alert, first_call, bees_surfaces, scroll_y): max_y = 830 scroll_surface, purchase_buttons, scroll_y = self.scroll(bees_surfaces, events, scroll_y, max_y) #positionner correctement purchase buttons buttons['buy_bee_button'] = purchase_buttons pos_x = 200 pos_y = 250 # valeurs liées aux boutons de display de la bee_surface container_surface = pygame.Surface((1500, 850), pygame.SRCALPHA) container_surface.blit(scroll_surface, (0, scroll_y)) surface.blit(container_surface, (pos_x, pos_y)) surface = self.display_ressources(surface) # print(bees_surfaces[0][1]) delete = False give_event = [] for event in events: if event.type == KEYDOWN: for accepted_tchong in self._accepted_event1: if event.unicode == accepted_tchong: give_event.append(event) #print(event) break for accepted_tchang in self._accepted_event2: if event.key == accepted_tchang: give_event.append(event) if event.key == K_BACKSPACE: delete = True #print(event) break if alert == "Buy": if first_call == True: self._temp_buttons = buttons first_call = False buttons = {} elif first_call == False: surface.blit(self._black_surface, (0,0)) input_surface = pygame.Surface((400, 80)) input_surface.fill(pygame.Color('White')) input_surface.blit(self._shop_input.get_surface(), (180,27)) if len(self._shop_input.get_text()) < 10: self._shop_input.update(give_event) elif delete == True: self._shop_input.update(give_event) surface.blit(input_surface, (760, 480)) buttons = {"cancel_buy" : button((255,180,255), 860, 615, 200, 80, self._w, self._h, 'Annuler Achat', font='comicsans', sizeFont=35)} buttons["cancel_buy"].draw_button(surface) elif alert == "CantBuy": if first_call == True: self._temp_buttons = buttons first_call = False buttons = {} elif first_call == False: surface.blit(self._black_surface, (0,0)) buttons = {"cant_buy_alert" : button((255,50,0,0), 760, 480, 400, 60, self._w, self._h,'Ressource insuffisante', font='comicsans', sizeFont=50)} buttons["cant_buy_alert"].draw_button(surface) elif alert == "GetRideOfThisShit": self._shop_input.clear_text() buttons = self._temp_buttons self._temp_buttons = None alert = None elif alert == "confirm_purchase": surface.blit(self._black_surface, (0,0)) display_surface = pygame.Surface((400, 80)) font = pygame.font.SysFont('comicsans', 50) msg = font.render("Achat effectué !", 1, (0,0,0)) display_surface.fill(pygame.Color('White')) display_surface.blit(msg, (65,25)) surface.blit(display_surface, (760, 480)) buttons = {"purchase_confirmation" : button((255,180,255), 860, 615, 200, 80, self._w, self._h, 'Continuer', font='comicsans', sizeFont=35)} buttons["purchase_confirmation"].draw_button(surface) return surface, self._shop_input.get_text(), buttons, first_call, alert, scroll_y def scroll(self, surface, events, y, max_y): buttons = surface['buttons'] surface = surface['surface'] pixels = 40 for event in events: if event.type == MOUSEBUTTONDOWN and event.button == 5: # vers le haut y -= pixels if y <= 0 and y > -(surface.get_height() - max_y): buttons = self.new_button_pos(buttons, pixels, "-") else: y += pixels if event.type == MOUSEBUTTONDOWN and event.button == 4: # vers le bas y += pixels if y <= 0: buttons = self.new_button_pos(buttons, pixels, "+") else: y -= pixels return surface, buttons, y def new_button_pos(self, buttons, pixels, axe): for i in range (0, len(buttons)): if axe == "+": buttons[i]._y += pixels elif axe == "-": buttons[i]._y -= pixels return buttons def text_rendering(self, font, sizeFont, text): font = pygame.font.SysFont(font, sizeFont) text = font.render(text, 1, (0,0,0)) return text def display_ressources(self, surface): x = 10 for ressource in self._hive._ressource: texte = self.translate_ressources(ressource) disp = texte + ": " + str(math.ceil(self._hive._ressource[ressource])) texte = self.text_rendering("comicsans", 40, disp) surface.blit(texte, (x, 14)) x += 300 text = "Lvl: " + str(self._hive._level) text = self.text_rendering("comicsans", 40, text) surface.blit(text, (x, 14)) return surface def translate_ressources(self, name): if name == "honey": return "Miel" if name == "water": return "Eau" if name == "metal": return "Métal" if name == "uranium": return "Uranium" if name == "pollen": return "Pollen"
def menu_screen(screen, clock): # declaring important variables color_choice = 0 option_flag = 0 prison_choice = 0 random_hint = random.randint(0, 7) # displays random quote high_score, high_time = read_highscore() timer = 0 global mute, friction, first # playing start sound jail pygame.mixer.music.load(os.path.join(assets_directory, "start.wav")) pygame.mixer.music.play(-1) pygame.mixer.music.set_volume(1) # settings and player name settings_manager = Settings_Manager() is_editing_name = False edit_name_start_button = ImgButton(pygame, screen, (34, scr_height - 70, 32, 32), edit_start_img) edit_name_end_button = ImgButton(pygame, screen, (34, scr_height - 70, 32, 32), edit_end_img) name_input = TextInput('', text_color=(255, 255, 255), cursor_color=(255, 255, 255), font_and_size=message_text1) # display start image while timer <= 180 and first: timer += 1 screen.blit(start_img_resized, (0, 0)) draw_walls(screen, wall_brick_width, wall_brick_height) disp_text(screen, "Will You Make It Out... Alive?", (old_div(scr_width, 2), 100), start_horror_text, peace_green) for event in pygame.event.get(): if event.type == pygame.QUIT: os._exit(0) pygame.display.update() clock.tick(FPS) first = 0 pygame.mixer.music.stop() pygame.mixer.music.load(os.path.join(assets_directory, "start_screen.ogg")) pygame.mixer.music.play(-1) pygame.mixer.music.set_volume(2) while True: if not mute: pygame.mixer.music.pause() else: pygame.mixer.music.unpause() # time passed delta_time = old_div(clock.get_time(), 10) mouse_x, mouse_y = pygame.mouse.get_pos() # checking for events events = pygame.event.get() for event in events: if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP or event.key == pygame.K_w: option_flag = (option_flag + 1) % 2 if event.key == pygame.K_DOWN or event.key == pygame.K_s: option_flag = (option_flag - 1) % 2 if event.key == pygame.K_LEFT or event.key == pygame.K_a: color_choice = (color_choice + 3) % 4 if event.key == pygame.K_RIGHT or event.key == pygame.K_d: color_choice = (color_choice + 1) % 4 if event.key == pygame.K_RETURN or event.key == pygame.K_SPACE: return option_flag, color_choice, mute # return index of color in striker_colors if event.key == pygame.K_ESCAPE: os._exit(0) if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed( )[0]: if mouse_x < scr_width - 70 and mouse_x > scr_width - 100 and mouse_y < 100 and mouse_y > 70: mute = not mute mute = mute if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed( )[0]: if mouse_x < scr_width - 70 and mouse_x > scr_width - 100 and mouse_y < 200 and mouse_y > 170: write_highscore(0, 0, 0, 0, 0) high_score, high_time = read_highscore() if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed( )[0]: if mouse_x < 284 and mouse_x > 114 and mouse_y < 336 and mouse_y > 318: prison_choice = 0 friction = 0.01 if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed( )[0]: if mouse_x < 527 and mouse_x > 325 and mouse_y < 336 and mouse_y > 318: prison_choice = 1 friction = 0.018 if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed( )[0]: if mouse_x < 797 and mouse_x > 584 and mouse_y < 336 and mouse_y > 318: prison_choice = 2 friction = 0.025 if event.type == pygame.QUIT: os._exit(0) # checking for button clicks if event.type == pygame.MOUSEBUTTONUP and event.button == LEFT: if is_editing_name: if edit_name_end_button.check_click(event.pos): settings_manager.settings_data[ 'player_name'] = name_input.get_text() settings_manager.save_settings_to_file() is_editing_name = False else: if edit_name_start_button.check_click(event.pos): settings_manager.settings_data['player_name'] = "" name_input.clear_text() is_editing_name = True # fedd name input box with events name_input.update(events) screen.fill(black) # black background, to be changed later draw_walls(screen, wall_brick_width, wall_brick_height) # display moving ball menu_ball.menu_screen_move(delta_time) menu_ball.check_collide_wall() menu_ball.check_collide_palette() menu_ball.draw(screen) # display quote # displaying random hint disp_text(screen, "\"" + hint_message[random_hint % 7] + "\"", (old_div(scr_width, 2), old_div(scr_height, 4) + 20), quote_text, orange) # display title disp_text(screen, "Brk", (old_div(scr_width, 2) - 70, old_div(scr_height, 2) - 240), game_title_text_large, orange) disp_text(screen, "OUT", (old_div(scr_width, 2) + 100, old_div(scr_height, 2) - 240), game_title_text_small, white) disp_text(screen, "YOUR PRISON", (old_div(scr_width, 2), old_div(scr_height, 2) - 80), prison_text_big, blood_red) if prison_choice == 0: disp_text( screen, "HOME", (old_div(scr_width, 2) - 250, old_div(scr_height, 2) - 24), prison_text1, blue) else: disp_text( screen, "HOME", (old_div(scr_width, 2) - 250, old_div(scr_height, 2) - 24), prison_text, yellow) if prison_choice == 1: disp_text( screen, "DUNGEON", (old_div(scr_width, 2) - 25, old_div(scr_height, 2) - 24), prison_text1, blue) else: disp_text( screen, "DUNGEON", (old_div(scr_width, 2) - 25, old_div(scr_height, 2) - 24), prison_text, yellow) if prison_choice == 2: disp_text( screen, "TARTARUS", (old_div(scr_width, 2) + 240, old_div(scr_height, 2) - 24), prison_text1, blue) else: disp_text( screen, "TARTARUS", (old_div(scr_width, 2) + 240, old_div(scr_height, 2) - 24), prison_text, yellow) disp_text(screen, "HIGHSCORE", (130, 65), start_screen_number, white) disp_text(screen, high_score, (130, 105), start_screen_number1, white) disp_text(screen, high_time[:2] + ":" + high_time[2:4], (130, 140), start_screen_number1, white) if mute: screen.blit(unmute_img, (scr_width - 100, 70)) else: screen.blit(mute_img, (scr_width - 100, 70)) screen.blit(help_img, (scr_width - 100, 120)) screen.blit(reset_img, (scr_width - 100, 170)) # display menu # display "Let's Play" if option_flag == 0: disp_text(screen, "Let's Escape", (old_div(scr_width, 2), old_div(scr_height, 2) + 60), menu_item_text_selected, silver) else: disp_text(screen, "Let's Escape", (old_div(scr_width, 2), old_div(scr_height, 2) + 60), menu_item_text, grey) # display white boundary around color palette pygame.draw.rect(screen, white, (old_div(scr_width, 2) - 200, old_div(scr_height, 2) + 100, 400, 100), 3) pygame.draw.rect(screen, white, (old_div(scr_width, 2) - 192, old_div(scr_height, 2) + 108, 384, 84), 2) # display color palette if color_choice == 0: pygame.draw.rect(screen, light_green, (old_div(scr_width, 2) - 190, old_div(scr_height, 2) + 110, 80, 80)) else: pygame.draw.rect(screen, green, (old_div(scr_width, 2) - 185, old_div(scr_height, 2) + 115, 70, 70)) if color_choice == 1: pygame.draw.rect(screen, light_red, (old_div(scr_width, 2) - 90, old_div(scr_height, 2) + 110, 80, 80)) else: pygame.draw.rect(screen, red, (old_div(scr_width, 2) - 85, old_div(scr_height, 2) + 115, 70, 70)) if color_choice == 2: pygame.draw.rect(screen, light_magenta, (old_div(scr_width, 2) + 10, old_div(scr_height, 2) + 110, 80, 80)) else: pygame.draw.rect(screen, magenta, (old_div(scr_width, 2) + 15, old_div(scr_height, 2) + 115, 70, 70)) if color_choice == 3: pygame.draw.rect(screen, light_blue, (old_div(scr_width, 2) + 110, old_div(scr_height, 2) + 110, 80, 80)) else: pygame.draw.rect(screen, blue, (old_div(scr_width, 2) + 115, old_div(scr_height, 2) + 115, 70, 70)) # display "I'm Scared" if option_flag == 1: disp_text(screen, "I'm Scared", (old_div(scr_width, 2), old_div(scr_height, 2) + 240), menu_item_text_selected, silver) else: disp_text(screen, "I'm Scared", (old_div(scr_width, 2), old_div(scr_height, 2) + 240), menu_item_text, grey) # display message if mouse_x < scr_width - 70 and mouse_x > scr_width - 100 and mouse_y < 100 and mouse_y > 70: if mute: disp_text( screen, "Click To Mute", (old_div(scr_width, 2), old_div(scr_height, 2) + 300), message_text, yellow) else: disp_text( screen, "Click To Unmute", (old_div(scr_width, 2), old_div(scr_height, 2) + 300), message_text, yellow) elif mouse_x < scr_width - 70 and mouse_x > scr_width - 100 and mouse_y < 150 and mouse_y > 120: disp_text(screen, "Click For Help", (old_div(scr_width, 2), old_div(scr_height, 2) + 300), message_text, yellow) elif mouse_x < scr_width - 70 and mouse_x > scr_width - 100 and mouse_y < 200 and mouse_y > 170: disp_text(screen, "Click To Reset Highscore", (old_div(scr_width, 2), old_div(scr_height, 2) + 300), message_text, yellow) elif option_flag == 0: disp_text(screen, "Press Enter To Play", (old_div(scr_width, 2), old_div(scr_height, 2) + 300), message_text, yellow) elif option_flag == 1: disp_text(screen, "Press Enter To Quit Game", (old_div(scr_width, 2), old_div(scr_height, 2) + 300), message_text, yellow) # display player name disp_text_origin( screen, settings_manager.settings_data['player_name'], (80, scr_height - 70), message_text1, white, ) if is_editing_name: edit_name_end_button.draw() else: edit_name_start_button.draw() if is_editing_name: screen.blit(name_input.get_surface(), (80, scr_height - 70)) pygame.display.update() clock.tick(FPS)
def __init__(self, settings, screen): """ Initializes basic properties of the prompt screen """ #only one message and title to be displayed at any given time self.title = "Welcome to Up and Down the River!" self.player_name_text = "Enter Player Name:" self.difficulty_levels_text = "Select Difficulty:" self.levels = Group() self.number_of_players_text = "Select Number of Players:" self.players = Group() self.number_of_rounds_text = "Select Number of Rounds:" self.rounds = Group() #basic visual settings self.settings = settings self.screen = screen self.screen_rect = screen.get_rect() self.bg_color = settings.bg_color #title font settings - white for now and just default self.title_text_color = (255, 255, 255) self.title_font = pygame.font.SysFont(None, 48) #Set of title image self.title_image = self.title_font.render(self.title, True, self.title_text_color) #definitions of the title image rect self.title_rect = self.title_image.get_rect() self.title_rect.y = self.settings.screen_height * .05 self.title_rect.center = ((self.settings.screen_width / 2), self.title_rect.y) #player name font settings - white for now and just default self.player_name_text_color = (255, 255, 255) self.player_name_font = pygame.font.SysFont(None, 36) #Set of player name text image self.player_name_image = self.player_name_font.render(self.player_name_text, True, self.player_name_text_color) #definitions of the player name text image rect self.player_name_rect = self.player_name_image.get_rect() self.player_name_rect.y = self.settings.screen_height * .20 self.player_name_rect.x = self.settings.screen_width * .20 #number of players font settings - white for now and just default self.player_number_text_color = (255, 255, 255) self.player_number_font = pygame.font.SysFont(None, 36) #Set of player name text image self.player_number_image = self.player_number_font.render(self.number_of_players_text, True, self.player_number_text_color) #definitions of the player name text image rect self.player_number_rect = self.player_number_image.get_rect() self.player_number_rect.y = self.settings.screen_height * .30 self.player_number_rect.x = self.settings.screen_width * .20 #difficulty levels font settings - white for now and just default self.difficulty_levels_text_color = (255, 255, 255) self.difficulty_levels_font = pygame.font.SysFont(None, 36) #Set of difficulty levels text image self.difficulty_levels_text_image = self.difficulty_levels_font.render(self.difficulty_levels_text, True, self.difficulty_levels_text_color) #definitions of the difficulty levels text image rect self.difficulty_levels_rect = self.difficulty_levels_text_image.get_rect() self.difficulty_levels_rect.y = self.settings.screen_height * .40 self.difficulty_levels_rect.x = self.settings.screen_width * .20 #difficulty levels font settings - white for now and just default self.number_of_rounds_text_color = (255, 255, 255) self.number_of_rounds_text_font = pygame.font.SysFont(None, 36) #Set of difficulty levels text image self.number_of_rounds_text_image = self.number_of_rounds_text_font.render(self.number_of_rounds_text, True, self.number_of_rounds_text_color) #definitions of the difficulty levels text image rect self.number_of_rounds_rect = self.number_of_rounds_text_image.get_rect() self.number_of_rounds_rect.y = self.settings.screen_height * .50 self.number_of_rounds_rect.x = self.settings.screen_width * .20 #Instance of pygame text input module self.text_input = TextInput() self.text_input_rect_x = self.settings.screen_width * .50 self.text_input_rect_y = self.settings.screen_height * .20 #Sprite Group of player options for index in range(0 , len(self.settings.number_of_players_option)): msg = str(self.settings.number_of_players_option[index]) pos_x = self.settings.screen_width * (.50 + (index * .075)) pos_y = self.player_number_rect.y button = PromptScreenButton(self.settings, self.screen, msg, False, pos_x, pos_y) self.players.add(button) self.players.sprites()[0].select() #sets first option as highlight #Sprite Group of difficulties for index in range(0 , len(self.settings.game_difficulty_option)): msg = self.settings.game_difficulty_option[index] pos_x = self.settings.screen_width * (.50 + (index * .15)) pos_y = self.difficulty_levels_rect.y button = PromptScreenButton(self.settings, self.screen, msg, False, pos_x, pos_y) self.levels.add(button) self.levels.sprites()[0].select() #sets first option as highlight #Sprite Group of rounds for index in range(1 , self.settings.max_rounds_available+1): msg = str(index) pos_x = self.settings.screen_width * (.50 + ((index-1) * .05)) pos_y = self.number_of_rounds_rect.y button = PromptScreenButton(self.settings, self.screen, msg, False, pos_x, pos_y) self.rounds.add(button) self.rounds.sprites()[0].select() #sets first option as highlight #Play Button instance to capture all the prompts when selected self.play_button = Button(self.settings, self.screen)
class Game(object): """The game instance.""" def __init__(self): # Create the clock self.clock = pygame.time.Clock() # Create the game window self.window = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) pygame.display.set_caption('Wikipedia Bingo') # Default game options (changed on start screen) self.limit = 5 self.board_size = 5 def run(self): """Run the game until it quits.""" self.running = True while self.running: # Display the start screen self.start_screen() # Start screen quit # Display the main screen self.main_screen() # Main screen quit # Exit self.terminate() def start_screen(self): """Create the start screen.""" self.loop_stage = True # Define buttons self.buttons = {} # Options self.buttons['start'] = Button('START', TEXTCOLOR, TILECOLOR, WINDOWWIDTH / 2 - 125, WINDOWHEIGHT - 100) self.buttons['start'].action = self.next_stage self.buttons['quit'] = Button('QUIT', TEXTCOLOR, TILECOLOR, WINDOWWIDTH / 2 + 25, WINDOWHEIGHT - 100) self.buttons['quit'].action = self.terminate # Difficulty self.buttons['limit3'] = Button('Hard', TEXTCOLOR, TILECOLOR, WINDOWWIDTH / 2 + 100, 500) self.buttons['limit3'].action = self.set_limit_to_3 self.buttons['limit3_sel'] = Button('Hard', TEXTCOLOR, WHITE, WINDOWWIDTH / 2 + 100, 500) self.buttons['limit3_sel'].action = self.set_limit_to_3 self.buttons['limit5'] = Button('Medium', TEXTCOLOR, TILECOLOR, WINDOWWIDTH / 2 - 50, 500) self.buttons['limit5'].action = self.set_limit_to_5 self.buttons['limit5_sel'] = Button('Medium', TEXTCOLOR, WHITE, WINDOWWIDTH / 2 - 50, 500) self.buttons['limit5_sel'].action = self.set_limit_to_5 self.buttons['limit7'] = Button('Easy', TEXTCOLOR, TILECOLOR, WINDOWWIDTH / 2 - 200, 500) self.buttons['limit7'].action = self.set_limit_to_7 self.buttons['limit7_sel'] = Button('Easy', TEXTCOLOR, WHITE, WINDOWWIDTH / 2 - 200, 500) self.buttons['limit7_sel'].action = self.set_limit_to_7 # Board size self.buttons['3x3'] = Button('3x3', TEXTCOLOR, TILECOLOR, WINDOWWIDTH / 2 - 200, 600) self.buttons['3x3'].action = self.set_board_size_to_3x3 self.buttons['3x3_sel'] = Button('3x3', TEXTCOLOR, WHITE, WINDOWWIDTH / 2 - 200, 600) self.buttons['3x3_sel'].action = self.set_board_size_to_3x3 self.buttons['5x5'] = Button('5x5', TEXTCOLOR, TILECOLOR, WINDOWWIDTH / 2 - 50, 600) self.buttons['5x5'].action = self.set_board_size_to_5x5 self.buttons['5x5_sel'] = Button('5x5', TEXTCOLOR, WHITE, WINDOWWIDTH / 2 - 50, 600) self.buttons['5x5_sel'].action = self.set_board_size_to_5x5 self.buttons['7x7'] = Button('7x7', TEXTCOLOR, TILECOLOR, WINDOWWIDTH / 2 + 100, 600) self.buttons['7x7'].action = self.set_board_size_to_7x7 self.buttons['7x7_sel'] = Button('7x7', TEXTCOLOR, WHITE, WINDOWWIDTH / 2 + 100, 600) self.buttons['7x7_sel'].action = self.set_board_size_to_7x7 while self.loop_stage: # Get events events = pygame.event.get() # Check clicks for event in events: if event.type == loc.MOUSEBUTTONUP: # check if the user clicked on an option button for button_name in self.buttons: button = self.buttons[button_name] if button.rect.collidepoint(event.pos): button.action() # Check for exit self.check_for_quit(events) # Draw the board self.draw_start_screen() # Tick the FPS clock self.clock.tick(FPS) def draw_start_screen(self): """Draw the start screen.""" self.window.fill(BGCOLOR) # Draw the name # txt = 'Wikipedia Bingo!' # surf, rect = make_text(txt, MESSAGECOLOR, BGCOLOR, 855, 60) # self.window.blit(surf, rect) # Draw the logo img = pygame.image.load('WIKIPEDIA_BINGO_small.png') rect = img.get_rect() rect.center = (WINDOWWIDTH / 2, 200) self.window.blit(img, rect) # Draw the instructions txt = 'INSTRUCTIONS' surf, rect = make_text(txt, MESSAGECOLOR, BGCOLOR, 100, 200) self.window.blit(surf, rect) with open('instructions.txt') as f: text = f.read().split('\n') for i, line in enumerate(text): textSurf, textRect = make_text(line, MESSAGECOLOR, BGCOLOR, 100, 230 + 20 * i) self.window.blit(textSurf, textRect) # Draw the buttons txt = 'OPTIONS' surf, rect = make_text(txt, MESSAGECOLOR, BGCOLOR, 890, 400) self.window.blit(surf, rect) txt = 'Chose difficulty:' surf, rect = make_text(txt, MESSAGECOLOR, BGCOLOR, 850, 450) self.window.blit(surf, rect) txt = 'Chose board size:' surf, rect = make_text(txt, MESSAGECOLOR, BGCOLOR, 850, 550) self.window.blit(surf, rect) for button_name in self.buttons: button = self.buttons[button_name] # Size pressed if self.board_size == 3 and button_name in [ '3x3', '5x5_sel', '7x7_sel' ]: continue elif self.board_size == 5 and button_name in [ '3x3_sel', '5x5', '7x7_sel' ]: continue elif self.board_size == 7 and button_name in [ '3x3_sel', '5x5_sel', '7x7' ]: continue # Limit button pressed elif self.limit == 3 and button_name in [ 'limit3', 'limit5_sel', 'limit7_sel' ]: continue elif self.limit == 5 and button_name in [ 'limit3_sel', 'limit5', 'limit7_sel' ]: continue elif self.limit == 7 and button_name in [ 'limit3_sel', 'limit5_sel', 'limit7' ]: continue else: self.window.blit(button.surface, button.rect) # Draw the leaderboard txt = 'HIGH SCORES' surf, rect = make_text(txt, MESSAGECOLOR, BGCOLOR, 1500, 200) self.window.blit(surf, rect) scoreboard = pd.read_csv('leaderboard.csv') strings = scoreboard['name'].values scores = scoreboard['score'].values for i, (name, score) in enumerate(zip(strings[:25], scores[:25])): msg = '{: >5.0f}'.format(score) textSurf, textRect = make_text(msg, MESSAGECOLOR, BGCOLOR, 1500, 250 + 20 * i) self.window.blit(textSurf, textRect) msg = '{}'.format(name[:3].upper()) textSurf, textRect = make_text(msg, MESSAGECOLOR, BGCOLOR, 1600, 250 + 20 * i) self.window.blit(textSurf, textRect) # Update the dipslay pygame.display.update() def main_screen(self): """Create the main screen.""" self.loop_stage = True # Default user name self.name = None # Generate a new puzzle self.get_starting_board() # Create list of red tiles self.board_counts = np.zeros((self.board_size, self.board_size)) self.board_new = np.zeros((self.board_size, self.board_size)) # Quit button self.buttons = {} self.buttons['restart'] = Button('RESTART', TEXTCOLOR, TILECOLOR, WINDOWWIDTH - 150, 30) self.buttons['restart'].action = self.next_stage self.buttons['quit'] = Button('QUIT', TEXTCOLOR, TILECOLOR, WINDOWWIDTH - 150, 60) self.buttons['quit'].action = self.terminate # Create TextInput-object self.textinput = TextInput(text_color=TEXTCOLOR, cursor_color=TEXTCOLOR) # Create the message array (starts blank) self.message_array = None # Initial score. self.score = 0 # Draw the initial board self.draw_main_screen() while self.loop_stage: # Get events events = pygame.event.get() # Check clicks for event in events: if event.type == loc.MOUSEBUTTONUP: # check if the user clicked on an option button for button_name in self.buttons: button = self.buttons[button_name] if button.rect.collidepoint(event.pos): button.action() # Send events to the text reader if self.textinput.update(events): # Pressed enter user_input = self.textinput.get_text() self.textinput.clear_text() # Extra commands if user_input and user_input[0] == "\ "[0]: command = user_input[1:].lower() if command in ['q', 'quit']: self.terminate() if command == 'add': self.board_counts += 1 else: # DEBUG print(self.board_words) # Get the article title title = user_input.lower() # Put the title in the top left self.message_array = [title + ':'] if not self.game_won(): # Reset the new word counter self.board_new = np.zeros( (self.board_size, self.board_size)) # Get the wikipedia article validation = Validation(title) try: validation.scrape_wiki() validation.process_wiki() words = validation.token self.score += 1 print(self.score) except Exception: self.message_array.append('Article not found') words = [] self.score += 1 print(self.score) # Remove any words not on the board words = [ word.lower() for word in words if word.lower() in self.board_words.flatten() ] # Count the frequencies counter = Counter(words) # Create the message for the top left if len(words) == 0: self.message_array.append('No valid words') for word in sorted(counter, key=lambda x: counter[x], reverse=True): x, y = tuple( np.argwhere( self.board_words == word.lower())[0]) current_count = self.board_counts[x][y] limit = self.board_limits[x][y] new_count = current_count + counter[word] # Create the message array for the left hand courner message = '{} ({:.0f})+{:.0f} = {:.0f}/{:.0f}'.format( word, current_count, counter[word], new_count, limit) self.message_array.append(message) # Check if the counter has overflowed new_word = None new_range = None if new_count >= limit: new_count = 0 new_word, new_range = self.get_new_word() self.message_array.append( ' OVERFLOW > {}'.format(new_word)) # Save the new count, new word (if needed) and message self.board_counts[x][y] = new_count if new_word: print(new_word) self.board_words[x][y] = new_word self.board_limits[x][y] = new_range self.board_new[x][y] = 1 else: # You win! self.scoring_algorithm() if not self.name and len(user_input) > 0: self.name = user_input # Update the leaderboard. new_win = pd.DataFrame(columns=['score', 'name']) new_win.loc[0] = [self.final_score, self.name] leaderboard = pd.read_csv('leaderboard.csv') new_leaderboard = pd.concat([leaderboard, new_win]) new_leaderboard = new_leaderboard.sort_values( 'score', ascending=False) new_leaderboard.to_csv('leaderboard.csv', index=False) return # Check for exit self.check_for_quit(events) # Draw the board self.draw_main_screen() # Tick the FPS clock self.clock.tick(FPS) def draw_main_screen(self): """Draw the main screen.""" self.window.fill(BGCOLOR) # Draw the board for tilex in range(len(self.board_words)): for tiley in range(len(self.board_words[0])): word = self.board_words[tilex][tiley] # Change the BG colour based on the count count = self.board_counts[tilex][tiley] limit = self.board_limits[tilex][tiley] if 0 < count < limit: bgcolour = (255, 255 - count * 255 / limit, 255 - count * 255 / limit) else: bgcolour = GREEN # Change the text colour if it's new new = self.board_new[tilex][tiley] if new: bgcolour = (60, 185, 100) # Draw the tile self.draw_tile(tilex, tiley, word, count, limit, TEXTCOLOR, bgcolour) left, top = self.get_tile_courner(0, 0) width = self.board_size * TILE_WIDTH height = self.board_size * TILE_HEIGHT pygame.draw.rect(self.window, BORDERCOLOR, (left - 5, top - 5, width + 11, height + 11), 4) # Draw the count msg = 'COUNT: {:.0f}'.format(self.score) surf, rect = make_text(msg, MESSAGECOLOR, BGCOLOR, 5, 5) self.window.blit(surf, rect) # Draw the message if self.message_array: for i, msg in enumerate(self.message_array): textSurf, textRect = make_text(msg, MESSAGECOLOR, BGCOLOR, 5, 35 + 20 * i) self.window.blit(textSurf, textRect) # Draw the winning message if you've won if self.game_won(): # Display winning message textSurf, textRect = make_text('!! WINNER !!', MESSAGECOLOR, BGCOLOR, WINDOWWIDTH / 2 - 75, 5) self.window.blit(textSurf, textRect) # Display score self.scoring_algorithm() textSurf, textRect = make_text( 'FINAL SCORE: {:.0f}'.format(self.final_score), MESSAGECOLOR, BGCOLOR, WINDOWWIDTH / 2 - 120, 25) self.window.blit(textSurf, textRect) # Draw the instructions if not self.game_won(): instruct = 'Enter the name of a Wikipedia article:' color = MESSAGECOLOR else: instruct = 'Enter your name to add to the leaderboard (MAX 3 LETTERS):' color = (255, 50, 50) instructSurf, instructRect = make_text(instruct, color, BGCOLOR, 5, WINDOWHEIGHT - 60) self.window.blit(instructSurf, instructRect) # Draw the text box self.window.blit(self.textinput.get_surface(), (5, WINDOWHEIGHT - 30)) # Draw the buttons for button_name in self.buttons: button = self.buttons[button_name] self.window.blit(button.surface, button.rect) # Update the dipslay pygame.display.update() # # # # # BUTTON FUNCTIONS def next_stage(self): """Go to the next stage.""" self.loop_stage = False def terminate(self): """Quit the game.""" pygame.quit() sys.exit() def set_board_size_to_3x3(self): """Set the board size.""" self.board_size = 3 def set_board_size_to_5x5(self): """Set the board size.""" self.board_size = 5 def set_board_size_to_7x7(self): """Set the board size.""" self.board_size = 7 def set_limit_to_3(self): """Set the tile limits.""" self.limit = 3 def set_limit_to_5(self): """Set the tile limits.""" self.limit = 5 def set_limit_to_7(self): """Set the tile limits.""" self.limit = 7 def check_for_quit(self, events): """Check for quit events.""" for event in events: if event.type == loc.QUIT: # terminate if any QUIT events are present self.terminate() if event.type == loc.KEYUP and event.key == loc.K_ESCAPE: # terminate if the KEYUP event was for the Esc key self.terminate() def get_starting_board(self): """Return a board data structure with tiles in the solved state.""" words = [] ranges = [] for _ in range(self.board_size * self.board_size): word, limit = self.get_new_word() words.append(word) ranges.append(limit) self.board_words = np.array(words, dtype=object).reshape( (self.board_size, self.board_size)) self.board_limits = np.array(ranges).reshape( (self.board_size, self.board_size)) def get_new_word(self): """Get an unused word from the list of all words.""" while True: target = TargetWord(ALL_WORDS) target.word_gen() word = target.word.lower() target.range_gen() limit = self.limit try: if word not in self.board_words.flatten(): break except Exception: break return word, limit def get_tile_courner(self, tilex, tiley): """Get the coordinates of the top left courner of a tile.""" xmargin = int((WINDOWWIDTH - (TILE_WIDTH * self.board_size + (self.board_size - 1))) / 2) ymargin = int((WINDOWHEIGHT - (TILE_HEIGHT * self.board_size + (self.board_size - 1))) / 2) left = xmargin + (tilex * TILE_WIDTH) + (tilex - 1) top = ymargin + (tiley * TILE_HEIGHT) + (tiley - 1) return (left, top) def draw_tile(self, tilex, tiley, word, count, limit, txtcolour=TEXTCOLOR, bgcolour=TILECOLOR): """Draw a tile at board coordinates tilex and tiley.""" left, top = self.get_tile_courner(tilex, tiley) pygame.draw.rect(self.window, bgcolour, (left, top, TILE_WIDTH, TILE_HEIGHT)) surf = BASICFONT.render(str(word), True, txtcolour) rect = surf.get_rect() rect.center = (left + int(TILE_WIDTH / 2), top + int(TILE_HEIGHT / 2)) self.window.blit(surf, rect) txt = '{:.0f}/{:.0f}'.format(count, limit) # txt = '{}{}'.format('-' * int(count), '*' * int(limit - count)) surf = BASICFONT.render(txt, True, txtcolour) rect = surf.get_rect() rect.center = (left + int(TILE_WIDTH / 2) + 75, top + int(TILE_HEIGHT / 2) + 20) self.window.blit(surf, rect) def game_won(self): """Determine if anyone has won the game.""" won = False # check for winning rows for row in self.board_counts: if all(row > 0): won = True # check for winning columns for col in self.board_counts.T: if all(col > 0): won = True return won def scoring_algorithm(self): """ Scores a player's performance Parameters --------- N : int number of wiki articles used to win mode : int Either 3, 5 or 7 for Easy, Medium and Hard grid : int Either 3, 5 or 7 for size of grid 3by3, 5by5 and 7by7 """ self.final_score = 0 if self.board_size == 3: self.final_score += 2000 elif self.board_size == 5: self.final_score += 4000 elif self.board_size == 7: self.final_score += 6000 if self.limit == 3: self.final_score += 4000 elif self.limit == 5: self.final_score += 6000 elif self.limit == 7: self.final_score += 8000 self.final_score = int(self.final_score / (self.score + 1))
def main_screen(self): """Create the main screen.""" self.loop_stage = True # Default user name self.name = None # Generate a new puzzle self.get_starting_board() # Create list of red tiles self.board_counts = np.zeros((self.board_size, self.board_size)) self.board_new = np.zeros((self.board_size, self.board_size)) # Quit button self.buttons = {} self.buttons['restart'] = Button('RESTART', TEXTCOLOR, TILECOLOR, WINDOWWIDTH - 150, 30) self.buttons['restart'].action = self.next_stage self.buttons['quit'] = Button('QUIT', TEXTCOLOR, TILECOLOR, WINDOWWIDTH - 150, 60) self.buttons['quit'].action = self.terminate # Create TextInput-object self.textinput = TextInput(text_color=TEXTCOLOR, cursor_color=TEXTCOLOR) # Create the message array (starts blank) self.message_array = None # Initial score. self.score = 0 # Draw the initial board self.draw_main_screen() while self.loop_stage: # Get events events = pygame.event.get() # Check clicks for event in events: if event.type == loc.MOUSEBUTTONUP: # check if the user clicked on an option button for button_name in self.buttons: button = self.buttons[button_name] if button.rect.collidepoint(event.pos): button.action() # Send events to the text reader if self.textinput.update(events): # Pressed enter user_input = self.textinput.get_text() self.textinput.clear_text() # Extra commands if user_input and user_input[0] == "\ "[0]: command = user_input[1:].lower() if command in ['q', 'quit']: self.terminate() if command == 'add': self.board_counts += 1 else: # DEBUG print(self.board_words) # Get the article title title = user_input.lower() # Put the title in the top left self.message_array = [title + ':'] if not self.game_won(): # Reset the new word counter self.board_new = np.zeros( (self.board_size, self.board_size)) # Get the wikipedia article validation = Validation(title) try: validation.scrape_wiki() validation.process_wiki() words = validation.token self.score += 1 print(self.score) except Exception: self.message_array.append('Article not found') words = [] self.score += 1 print(self.score) # Remove any words not on the board words = [ word.lower() for word in words if word.lower() in self.board_words.flatten() ] # Count the frequencies counter = Counter(words) # Create the message for the top left if len(words) == 0: self.message_array.append('No valid words') for word in sorted(counter, key=lambda x: counter[x], reverse=True): x, y = tuple( np.argwhere( self.board_words == word.lower())[0]) current_count = self.board_counts[x][y] limit = self.board_limits[x][y] new_count = current_count + counter[word] # Create the message array for the left hand courner message = '{} ({:.0f})+{:.0f} = {:.0f}/{:.0f}'.format( word, current_count, counter[word], new_count, limit) self.message_array.append(message) # Check if the counter has overflowed new_word = None new_range = None if new_count >= limit: new_count = 0 new_word, new_range = self.get_new_word() self.message_array.append( ' OVERFLOW > {}'.format(new_word)) # Save the new count, new word (if needed) and message self.board_counts[x][y] = new_count if new_word: print(new_word) self.board_words[x][y] = new_word self.board_limits[x][y] = new_range self.board_new[x][y] = 1 else: # You win! self.scoring_algorithm() if not self.name and len(user_input) > 0: self.name = user_input # Update the leaderboard. new_win = pd.DataFrame(columns=['score', 'name']) new_win.loc[0] = [self.final_score, self.name] leaderboard = pd.read_csv('leaderboard.csv') new_leaderboard = pd.concat([leaderboard, new_win]) new_leaderboard = new_leaderboard.sort_values( 'score', ascending=False) new_leaderboard.to_csv('leaderboard.csv', index=False) return # Check for exit self.check_for_quit(events) # Draw the board self.draw_main_screen() # Tick the FPS clock self.clock.tick(FPS)
class Door(sprite.Sprite): ''' The Door the player needs to open and answer questions ''' def __init__(self, question, answer, x, y, part_name) -> None: super().__init__() self.question = question self.answer = answer.lower() self.door_done = image.load(join( "assets", "door done.png")).convert_alpha() self.door_done = transform.scale(self.door_done, (256, 256)) self.image = image.load(join( "assets", "door.png")).convert_alpha() self.image = transform.scale(self.image, (256, 256)) self.rect = self.image.get_rect() self.rect.x = x self.rect.centery = y self.asking = False self.input = TextInput(text_color=WHITE) self.done = False self.part_name = part_name for a in player.acquired: if a['name'] == self.part_name: if self.question in a['question']: self.done = True self.image = self.door_done def update(self, events) -> None: screen.blit(self.image, self.rect) if not self.done: if self.rect.collidepoint(pygame.mouse.get_pos()) and \ pygame.mouse.get_pressed()[0] and not self.asking: self.asking = True door_open.play() else: if self.asking and not self.rect.collidepoint( pygame.mouse.get_pos()) and \ pygame.mouse.get_pressed()[0]: self.asking = False door_close.play() if self.asking: self.input.update(events) inp = self.input.get_surface() inp_rect = inp.get_rect() inp_rect.centerx = WIDTH // 2 inp_rect.y = self.rect.y - 40 screen.blit(inp, inp_rect) q = question_font.render(self.question, True, BLACK) screen.blit(q, (WIDTH // 2 - q.get_width() // 2, 50)) for event in events: if event.type == KEYDOWN: if event.key == K_RETURN: if fuzz.token_sort_ratio(self.answer, self.input.get_text() ) > 85: self.asking = False self.image = self.door_done self.done = True door_close.play() player.pass_door(self.part_name, self.question) else: wrong_sound.play()
def __init__(self): self.clicked = False self.mousePosition = list(pygame.mouse.get_pos()) self.textInput = TextInput() self.textOutput = TextOutput() self.textOutputRect = None
import pygame import socket import sys import cPickle import constants import utils from pygame_textinput import TextInput from hangword import Hangword textinput = TextInput(True) # create inputbox with one-letter input textbox = pygame.font.SysFont("monospace", constants.FONT) pygame.init() gameExit = False gameDisplay = pygame.display.set_mode( (constants.GAME_WIDTH, constants.GAME_HEIGHT)) clock = pygame.time.Clock() image_cache = utils.load_images() winner = False def play(): global winner gameExit = False