def ask(self): self.prompt_user() UI.display('Loading ..') self.add_more_questions() ques = None score = 0 while self.question_count > 0: ques = self.manager.get_question(self.current_question) self.current_question += 1 UI.display(ques.question) answer = UI.get_input('Answer: ') try: if ques.answer == int(answer): UI.display('Correct!\n') score += 2 else: UI.display('Wrong!\n') break except ValueError: UI.display('Please enter a valid answer.') self.current_question -= 1 continue if self.question_count == 1: self.add_more_questions() self.question_count -= 1 self.manager.set_score(self.user, score)
def start(self): while True: command = UI.get_input("> ") if command == 'start': self.ask() elif command == 'highscores': UI.display(self.show_highscores()) elif command == 'help': UI.display(self.__HELP_MESSAGE) elif command == 'exit': return
class Level: def __init__(self): # get the display surface self.display_surface = pygame.display.get_surface() self.game_paused = False self.open_game_over = False self.open_game_wins = False self.inimigos = [] # sprite group setup self.visible_sprites = YSortCameraGroup() self.obstacle_sprites = pygame.sprite.Group() # attack sprites self.current_attack = None self.attack_sprites = pygame.sprite.Group() self.attackable_sprites = pygame.sprite.Group() # sprite setup self.create_map() # user interface self.ui = UI() self.upgrade = Upgrade(self.player) # particles self.animation_player = AnimationPlayer() self.magic_player = MagicPlayer(self.animation_player) def setOpenGameWins(self): self.open_game_wins = True def create_map(self): layouts = { 'boundary': import_csv_layout('../map/mapateste_barreira.csv'), 'entities': import_csv_layout('../map/mapateste_inimigos.csv') } for style, layout in layouts.items(): for row_index, row in enumerate(layout): for col_index, col in enumerate(row): if col != '-1': x = col_index * TILESIZE y = row_index * TILESIZE if style == 'boundary': Tile((x, y), [self.obstacle_sprites], 'invisible') if style == 'entities': if col == '394': self.player = Player( (x, y), [self.visible_sprites], self.obstacle_sprites, self.create_attack, self.destroy_attack, self.create_magic) else: if col == '390': monster_name = 'duende' elif col == '389': monster_name = 'boss' else: monster_name = 'esqueleto' self.inimigo = Enemy( monster_name, (x, y), [ self.visible_sprites, self.attackable_sprites ], self.obstacle_sprites, self.damage_player, self.trigger_death_particles, self.add_exp, self.setOpenGameWins) self.inimigos.append(self.inimigo) def kill_all_enemies(self): for inimigo in self.inimigos: inimigo.kill() def create_attack(self): self.current_attack = Weapon( self.player, [self.visible_sprites, self.attack_sprites]) def create_magic(self, style, strength, cost): if style == 'heal': self.magic_player.heal(self.player, strength, cost, [self.visible_sprites]) if style == 'flame': self.magic_player.flame( self.player, cost, [self.visible_sprites, self.attack_sprites]) def destroy_attack(self): if self.current_attack: self.current_attack.kill() self.current_attack = None def player_attack_logic(self): if self.attack_sprites: for attack_sprite in self.attack_sprites: collision_sprites = pygame.sprite.spritecollide( attack_sprite, self.attackable_sprites, False) if collision_sprites: for target_sprite in collision_sprites: if target_sprite.sprite_type == 'grass': pos = target_sprite.rect.center offset = pygame.math.Vector2(0, 75) for leaf in range(randint(3, 6)): self.animation_player.create_grass_particles( pos - offset, [self.visible_sprites]) target_sprite.kill() else: target_sprite.get_damage(self.player, attack_sprite.sprite_type) def damage_player(self, amount, attack_type): if self.player.vulnerable: self.player.health -= amount self.player.vulnerable = False self.player.hurt_time = pygame.time.get_ticks() if self.player.health <= 0: self.open_game_over = True self.kill_all_enemies() #self.animation_player.create_particles(attack_type,self.player.rect.center,[self.visible_sprites]) def trigger_death_particles(self, pos, particle_type): pass # self.animation_player.create_particles(particle_type,pos,self.visible_sprites) def add_exp(self, amount): self.player.exp += amount def toggle_menu(self): self.game_paused = not self.game_paused def run(self): self.visible_sprites.custom_draw(self.player) self.ui.display(self.player) if self.game_paused: self.upgrade.display() else: self.visible_sprites.update() self.visible_sprites.enemy_update(self.player) self.player_attack_logic() if self.open_game_over: return 2 elif self.open_game_wins: return 1 else: return 0
class Game: def __init__(self, db): if (db == "mongo"): self.dbserver = MongoDb() # self.dbserver.load_questions() self.ui = UI() self.categories = pd.DataFrame.from_records( pd.read_json( "https://opentdb.com/api_category.php").trivia_categories) self.categories.set_index("id", inplace=True) self.start_game("normal") def update_db(self, batch): for i in range(len(batch)): self.dbserver.update_db(batch.iloc[i].name, batch.iloc[i].user_name, batch.iloc[i].correct_answer) def user_mode(self): self.user_name = self.ui.input("Please enter your name: ") self.display_categories("Choose a category of questions: \n") # self.ui.display("\n".join(self.categories["name"])) self.user_category = str.title(self.ui.input("\n")) self.user_difficulty = str.lower( self.ui.input("Choose difficulty level (easy, medium, hard): ")) self.user_number_of_questions = self.ui.input( "Please enter number of questions: ") self.session = pd.DataFrame( self.dbserver.get_question(self.user_category, self.user_difficulty, self.user_number_of_questions)) batch = {} while len(self.session): question = self.session.iloc[len(self.session) - 1] self.session = self.session.drop(len(self.session) - 1) self.ui.displayHTMLchars(question["question"]) answers = question["incorrect_answers"] correct_answer = html.unescape(question["correct_answer"]) answers.append(correct_answer) while len(answers): self.ui.displayHTMLchars(answers.pop()) answer = self.ui.input("\nPlease enter your answer: ") is_correct_answer = (answer == correct_answer) if is_correct_answer: self.ui.display("Correct!") else: self.ui.display("Wrong") batch[question["_id"]] = (self.user_name, is_correct_answer) batch = pd.DataFrame.from_dict(batch, orient="index", columns=["user_name", "correct_answer"]) self.ui.display( f"You answered correctly to {batch.correct_answer.sum()} out of {batch.correct_answer.count()} questions!" ) self.update_db(batch) def display_categories(self, intro_text): self.ui.display(intro_text) self.ui.display("\n".join(self.categories["name"])) def add_category(self): self.display_categories("Current categories: ") category = self.ui.input("\nEnter your new category: ") self.categories.loc[self.categories.index.max() + 1, "name"] = category # TODO : categories should be stored in the database def remove_category(self): self.display_categories("Current categories: ") category = self.ui.input("\nEnter category id to be removed: ") self.categories.drop(index=category, inplace=True) def add_question(self): self.display_categories("Choose a category: ") category = str.title(self.ui.input("\n")) qtype = None while (qtype != "boolean" or qtype != "multiple"): qtype = self.ui.input( "What is the type of the question? boolean or multiple choice [boolean/multiple] " ) difficulty = None while (difficulty not in ["easy", "medium", "hard"]): difficulty = str.lower( self.ui.input( "Choose difficulty level (easy, medium, hard): ")) question = self.ui.input("Enter your question:\n") if (qtype == "boolean"): correct_answer = None while (correct_answer != "True" or correct_answer != "False"): correct_answer = str.capitalize( self.ui.input("Enter correct answer (True/False): ")) if (correct_answer) == "True": incorrect_answer = ["False"] else: incorrect_answer = ["True"] else: correct_answer = self.ui.input("Enter correct answer:\n") incorrect_answer = [] for i in range(3): incorrect_answer.append( self.ui.input(f"Enter incorrect answer number {i+1}:\n")) new_question = { "category": category, "type": qtype, "difficulty": difficulty, "question": question, "correct_answer": correct_answer, "incorrect_answers": incorrect_answer } self.dbserver.add_question(new_question) def load_questions(self): amount = self.ui.input( "How many questions would you like to load from online database? ") self.dbserver.load_questions(amount) def admin_menu(self): self.ui.display("1. Add a category") self.ui.display("2. Remove a category") self.ui.display("3. Add a question") self.ui.display("4. Load questions from database") self.ui.display("5. Get game statistics") return self.ui.input("Enter your choice [1-5]: ") def admin_statistics(self): self.ui.display("1. Correct answers by category") self.ui.display("2. Correct answers by difficulty level") self.ui.display("3. Users' statistics") choice = 4 while not (choice >= 1 and choice <= 3): choice = int(self.ui.input("Please enter your choice [1-3]: ")) def admin_mode(self): menu = self.admin_menu() if (menu == 1): self.add_category() elif (menu == 2): self.remove_category() elif (menu == 3): self.add_question() elif (menu == 4): self.load_questions() elif (menu == 5): self.admin_statistics() def start_game(self, mode="normal"): if (mode == "normal"): self.user_mode() if (mode == "admin"): self.admin_mode()
class Game: welcome_message = '\n{} {} {}\nWrite start to play or exit to quit!'.format( '-' * 10, 'Tic Tac Toe!', '-' * 10) winner_message = 'Game Over! Winner is {}' winning_routes = [[(0, 0), (0, 1), (0, 2)], [(0, 0), (1, 0), (2, 0)], [(0, 0), (1, 1), (2, 2)], [(1, 0), (1, 1), (1, 2)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)], [(2, 0), (2, 1), (2, 2)], [(2, 0), (1, 1), (0, 2)]] def __init__(self): self.UI = UI() self.AI = AI(self.UI.BOARD, self.winning_routes) self.player = None self.game_over = False def input_choice(self): x = int(self.UI.get_input('x: ')) y = int(self.UI.get_input('y: ')) if self.are_x_y_valid(x, y) or self.UI.BOARD[x][y] != ' ': raise ValueError return (x, y) def are_x_y_valid(self, x, y): return x >= self.UI.SIZE or y >= self.UI.SIZE or x < 0 or y < 0 def start(self): while self.game_over is False: self.UI.print_map() self.tick() def tick(self): try: choice = self.input_choice() except ValueError: self.UI.display('\nInvalid input! Please reenter.\n') return self.UI.BOARD[choice[0]][choice[1]] = self.UI.X if self.is_board_full(): self.trigger_game_over(None) return self.AI.attack() is_there_a_winner = self.check_for_winner() if is_there_a_winner is not False: self.trigger_game_over(is_there_a_winner) return def check_for_winner(self): for route in self.winning_routes: if all(self.UI.BOARD[coords[0]][coords[1]] == self.UI.X for coords in route): return self.UI.X if all(self.UI.BOARD[coords[0]][coords[1]] == self.UI.O for coords in route): return self.UI.O return False def is_board_full(self): return all(all(block != ' ' for block in line) for line in self.UI.BOARD) def trigger_game_over(self, winner): self.game_over = True self.UI.print_map() self.UI.display(self.winner_message.format('Player' if winner == self.UI.X else ('Enemy' if winner == self.UI.O else winner))) def go(self): self.UI.display(self.welcome_message) if self.UI.get_input('> ') == 'start': self.start()