def display(self): ''' NPC display function. This function examines position of target, makes move based on target, then displays to the screen. ''' # Calling parent display function Character.display(self)
def addTarget(self, target_group): ''' addTarget - Used to lock NPC onto a target to attack ''' Character.addTarget(self, target_group) # Sorry this line is messy! was playing in the debugger and # found it works self.target = target_group.sprites()[0] # TODO: Redo c2c_widtrh and methods which use it # Centre to centre width self.c2c_width = 0.5 * (self.width + self.target.width) self.c2c_height = 0.5 * (self.height + self.target.height)
def update(self): ''' NPC update function This function examines position of target, makes move based on target, then uses parent classes update funciton ''' if self.position[1] > self.max_depth: self.kill() # Deciding on and actioning any moves self.decideMoves() Character.update(self)
def update(self): ''' Update Updates using parent classes update function, then ensures still on screen ''' #print(self.score) Character.update(self) # Preventing from going off edges if self.rect.left < 0: self.rect.left = 0 if self.rect.right > self.screen.get_width(): self.rect.right = self.screen.get_width()
def __init__(self, screen, background, x_position, y_position, arm_type='arms'): # Loading player data json, and converitng to python dictionary with open('json/basic_character.JSON') as player_json: character_data = json.load(player_json) # Initialising Character class Character.__init__(self, character_data, background, screen, x_position, y_position, arm_type)
def attack(self): ''' attack function Checks for any enemies in target group who have collided and attacks them ''' self.attacking = True if self.arms.projectile: boom = self.arms.throw(self.state[1]) self.thrown_projectiles.add(boom) else: collision_enemies = pygame.sprite.spritecollide( self, self.target_group, False) for collision_enemy in collision_enemies: if self.isFacingTarget(collision_enemy): Character.attack(self, collision_enemy)
def __init__(self, characters_set): self.fitness = -1 self.characters_set = list() for character in characters_set: self.characters_set.append( Character(character=character['character'], button_id=character['button_id'])) self._order_fixed_characters()
def load(user_input="none"): global characters df = pd.read_csv("characters.csv") columns = df.columns.tolist() characters_series = df.apply(lambda x: (x[columns[0]], Character(**dict(x))), axis=1) characters = dict(list(characters_series)) print("Ready players: " + ", ".join(list(characters.keys())))
def __init__(self, screen, background, x_position, y_position, npc_type='basic', arm_type='arms', sleep_on_load=True): # Loading player data json, and converitng to python dictionary json_location = f'json/{npc_type}_enemy.JSON' try: with open(json_location) as character_json: character_data = json.load(character_json) except: err_string = "Bad Enemy Name. Please input an enemy which has \ a corresponding JSON" raise Exception(err_string) # Initialising Character class Character.__init__(self, character_data, background, screen, x_position, y_position, arm_type) # Setup sleep variable self.asleep = sleep_on_load self.setAttackDelay() # Kill NPC if falls off map self.max_depth = screen.get_size()[1] # Wake distance (pixels) - used to determine distance target # needs to be after which NPC wakes. # This should go somewhere else, like a JSON perhaps? # TODO: Decide! self.wake_distance = 200
def init_character_data(): dict_enemies[greg_name] = Character( greg_name, 100, [mild_sexism, sell_company, ignore_advice, blame_linda], dict_effects[Effects.NONE]) dict_enemies[pionteks_name] = Character( pionteks_name, 100, [vote_trump, insist_dinner_siblings, pick_on_linda], dict_effects[Effects.NONE]) dict_enemies[tilly_name] = Character( tilly_name, 50, [scarf_and_barf, dead_mouse, alive_mouse, hairball], dict_effects[Effects.NONE]) dict_enemies[noah_name] = Character( noah_name, 100, [toxic_fart, hanger, say_fam, herpdy_derp], dict_effects[Effects.NONE]) dict_enemies[gabe_name] = Character( gabe_name, 100, [sleep_till_3, gabe_out, gabe_stop, obscure_reference], dict_effects[Effects.NONE]) dict_enemies[cookies_name] = Character(cookies_name, 1000, [look_tasty, sit_there], dict_effects[Effects.NONE])
num_turns_in_battle = 1 current_character_enemy_index += 1 character_enemy = dict_enemies[enemy_order[current_character_enemy_index]] set_context('break') character_mom.damage_boost = 1.0 character_mom.active_effect = dict_effects[Effects.NONE] battle_over = True print_delayed('\n\nLinda went to the hooga zone', standard_delay) def print_end_game_text(): print_delayed(congrats, 3) print_delayed( f'You have defeated all bosses! Your total score is {score}!', 3) print_delayed(list_of_rewards, 3) def main(): set_context('attacking.Greg') print_start_of_game_text() start() adventurelib.prompt = prompt adventurelib.no_command_matches = no_command_matches init_game_data() character_mom = Character('Linda', 100, None, dict_effects[Effects.NONE]) character_enemy = dict_enemies['Greg'] if __name__ == '__main__': main()
def setArms(self, new_arms): ''' Sets arms and updates npc delay accordingly ''' Character.setArms(self, new_arms) self.setAttackDelay()
from classes.character import Character from classes.magic import player_spells, enemy_spells from classes.backpack import player_items from classes.bcolors import bcolors from random import randrange # Creating characters player1 = Character('Bezimienny', 2950, 135, 185, 55, player_spells, player_items) player2 = Character('Diego ', 1400, 30, 140, 40, player_spells, player_items) player3 = Character('Milten ', 1250, 300, 45, 25, player_spells, player_items) enemy1 = Character('Priest ', 1500, 200, 20, 30, enemy_spells, []) enemy2 = Character('Śniący ', 6000, 110, 600, 80, enemy_spells, []) enemy3 = Character('Warrior', 1500, 0, 300, 50, enemy_spells, []) players = [player1, player2, player3] dead_players = [player1, player2, player3] enemies = [enemy1, enemy2, enemy3] dead_enemies = [enemy1, enemy2, enemy3] # Let's play play = True print(bcolors.MBOLD + bcolors.MYELLOW + '|' + '-' * 52 + '|' + bcolors.ENDC) print(bcolors.MBOLD + bcolors.MYELLOW + '|' + '=' * 8 + 'You finally found Arch-Demon Sleeper' + '=' * 8 + '|' + bcolors.ENDC) print(bcolors.MBOLD + bcolors.MYELLOW + '|' + '=' * 8 + 'You must defeat him to save Khorinis' + '=' * 8 + '|' + bcolors.ENDC)
def new(input_array): global characters new_char = Character(*input_array[1:]) characters[new_char.name] = new_char print("Huzzah! " + new_char.name + " has joined the game. Welcome to the campaign.")
def main(): character_name = input("What is the name of your character?\n") time.sleep(0.5) while True: try: character_type = input( "Do you want to have a lucky or strong character? Input lucky or strength to indicate your " "choice.\n") new_character = Character(character_name, character_type) break except ValueError: print("That was not a valid character type. Please try again.\n") story = Script.scenario_1 new_game = Game(new_character, story) print("Character History:\n") print( "It is early 1942. You are a junior officer at the rank of Lieutenant in the Imperial Japanese Army who was " "prompted to sign on with the army shortly after graduation from Waseda University due to your strong " "patriotism.\n") time.sleep(4) print("Character Attribute:\n") if new_character.role_type == 'lucky': print( "Furthermore, you have always been sure of your luck as well. Since youth, you have always been saved " "from unfortunate incidents due to sheer luck despite having partaken in them, and you regularly win " "small amounts of money from gambling with your friends as well.\n\nBeing confident of your luck, you " "are sure that you will be able to survive and get out of dangerous situations with luck on your side.\n" ) time.sleep(4) else: print( "Furthermore, you have always been sure of your physical fitness and ability as well. Since youth, you " "have always been first in local athletic events, and have even represented your university in " "Volleyball and Baseball.\n\nYou are sure that even if you are placed in a pinch, your athletic ability " "and toughness will allow you to survive and adapt to most situations.\n" ) time.sleep(4) print("Initial Health:\n") print("Your character has initial health of {}\n".format( new_game.character.getHealth())) time.sleep(2.5) while not new_game.end: new_game.showStory() time.sleep(6.5) new_game.interactiveStory() time.sleep(6.5) if new_game.character.health <= 0: print("Oh no, your health has reached 0. You have died!\n") break else: pass if new_game.script.story_type == 'chapter_end': new_game.showHealth() new_game.script = new_game.script.choice_a else: if new_game.script.choice_a is None and new_game.script.choice_b is None: print("Game has ended.\n") new_game.end = True else: new_game.choiceSelection() time.sleep(1) new_game.showHealth() time.sleep(1) end = input("Thanks for playing! Click Enter to exit the game.") if end is not None: return None return None
def __init__(self, **kwargs): self.name = kwargs.get("name") self.character = Character(name=self.name) self.modules = {} self.commands = {}
#!/usr/local/bin/python3 from classes.character import Character import random characternames = ["Frasier", "Niles", "Roz"] lines = 10 characters = [] for c in characternames: characters.append( Character(c, "transcripts/parsed_by_character/" + c + ".txt", 1)) prevC = c = 0 prevLine = line = None for i in range(0, lines): # Choose a new respondent while c == prevC: c = random.randint(0, len(characternames) - 1) # Generate line while line == None: # First sentence if prevLine == None: line = characters[c].say() # Else, potentially say something new elif random.random() < 0.3: line = characters[c].say() # Else, respond to the previous line else: line = characters[c].respond(prevLine)
def startFight(self): fight = True print("Loading configuration...") dataLoader = JsonLoader() config = Config("./config/", dataLoader) config.loadConfigs() stats = Statistics(self.message) actions = Actions(self.message) actionElements = ["Attack", "Cast spell", "Use item", "Check characters' statistics"] players = [] enemies = [] spells = [] items = [] for spell in config.getSpells(): spells.append( Spell(spell["name"], spell["cost"], spell["value"], spell["school"])) for item in config.getItems(): items.append(Item(item["name"], item["itemType"], item["description"], item["value"])) for player in config.getPlayers(): players.append(Character(player["name"], player["hp"], player["mp"], player["atk"], player["df"], player["spells"], player["items"])) for enemy in config.getEnemies(): enemies.append(Character(enemy["name"], enemy["hp"], enemy["mp"], enemy["atk"], enemy["df"], enemy["spells"], enemy["items"])) alivePlayers = players aliveEnemies = enemies deadPlayers = [] deadEnemies = [] # time.sleep(3) print("Loading done.") # time.sleep(2) print("Starting fight!") # time.sleep(3) while fight: self.message.playerTurn() for player in alivePlayers: stats.getStats(alivePlayers, aliveEnemies) print("Current character: " + player.name) takenAction = False while not takenAction: self.menu.display("Actions", actionElements) actionChoice = self.menu.getChoice( actionElements, "Choose action") attack = False normalAttack = False heal = False elixer = False if actionChoice == 3: self.message.players() stats.getAttrs(alivePlayers) self.message.enemies() stats.getAttrs(aliveEnemies) continue elif actionChoice == 0: value = player.getAtk() attack = True normalAttack = True elif actionChoice == 1: playerSpells = player.getSpells() if not playerSpells: continue spellsName = [] for i in playerSpells: spellsName.append(spells[i].getName() + " (value: " + str(spells[i].getValue()) + ", cost: " + str(spells[i].getCost()) + ")") spellsName.append("Back") self.menu.display("Spells", spellsName) spellChoice = self.menu.getChoice( spellsName, "Choose spell") if spellChoice == len(spellsName) - 1: continue chosenSpell = spells[playerSpells[spellChoice]] casted = actions.castSpell(player, chosenSpell, True) if not casted: continue elif casted: value = chosenSpell.getValue() if chosenSpell.getSchool() == "attack": attack = True elif chosenSpell.getSchool() == "white": heal = True elif actionChoice == 2: playerItems = player.getItems() if not playerItems: continue itemsName = [] for i in playerItems: id = i["id"] quantity = str(i["quantity"]) itemsName.append(items[id].getName() + " - " + items[id].getDescription() + " (" + quantity + "x)") itemsName.append("Back") self.menu.display("Items", itemsName) itemChoice = self.menu.getChoice(itemsName, "Choose item") if itemChoice == len(itemsName) - 1: continue chosenItem = ItemManager(items[playerItems[itemChoice]["id"]], playerItems[itemChoice]["quantity"]) used = actions.useItem( player, chosenItem, itemChoice, True) if not used: continue else: value = chosenItem.getItem().getValue() if chosenItem.getItem().getType() == "potion": heal = True elif chosenItem.getItem().getType() == "attack": attack = True elif chosenItem.getItem().getType() == "elixer": elixer = True if attack == True: enemiesName = [] for enemy in aliveEnemies: enemiesName.append(enemy.getName()) enemiesName.append("Back") self.menu.display("Enemies", enemiesName) enemyChoice = self.menu.getChoice( enemiesName, "Choose enemy") if enemyChoice == len(enemiesName) - 1: continue if normalAttack: defense = round( aliveEnemies[enemyChoice].getDf() / 50) if defense == 0: defense = 1 value = round(value / defense) actions.attack( player, aliveEnemies[enemyChoice], value) elif heal == True: actions.heal(player, value) elif elixer == True: actions.elixer(player) takenAction = True deadEnemies = CheckAlive.getDead( deadEnemies, aliveEnemies, self.message) aliveEnemies = CheckAlive.getAlive(aliveEnemies) if not aliveEnemies: print("Won") fight = False break self.message.enemyTurn() for enemy in aliveEnemies: takenAction = False while not takenAction: attack = False normalAttack = False heal = False elixer = False actionChoice = random.randint(0, 2) if actionChoice == 0: attack = True normalAttack = True elif actionChoice == 1: enemiesSpells = enemy.getSpells() if not enemiesSpells: continue spellChoice = random.randrange(0, len(enemiesSpells)) chosenSpell = spells[enemiesSpells[spellChoice]] if chosenSpell.getSchool() == "white" and enemy.getHp() >= enemy.getMaxHp() * 0.9: continue casted = actions.castSpell(enemy, chosenSpell) if not casted: continue elif casted: value = chosenSpell.getValue() if chosenSpell.getSchool() == "attack": attack = True elif chosenSpell.getSchool() == "white": heal = True elif actionChoice == 2: enemyItems = enemy.getItems() if not enemyItems: continue itemChoice = random.randrange(0, len(enemyItems)) chosenItem = ItemManager(items[enemyItems[itemChoice]["id"]], enemyItems[itemChoice]["quantity"]) if enemy.getHp() >= enemy.getMaxHp() * 0.9: enoughHp = False else: enoughHp = True if enemy.getMp() >= enemy.getMaxMp() * 0.9: enoughMp = False else: enoughMp = True if chosenItem.getItem().getType() == "Potion" and not enoughHp: continue elif chosenItem.getItem().getType() == "Elixer" and (not enoughHp or not enoughMp): continue used = actions.useItem(enemy, chosenItem, itemChoice) if not used: continue else: value = chosenItem.getItem().getValue() if chosenItem.getItem().getType() == "potion": heal = True elif chosenItem.getItem().getType() == "attack": attack = True elif chosenItem.getItem().getType() == "elixer": elixer = True time.sleep(1) if attack == True: target = random.randrange(0, len(alivePlayers)) if normalAttack: defense = round(alivePlayers[target].getDf() / 50) if defense == 0: defense = 1 value = round(value / defense) actions.attack(enemy, alivePlayers[target], value) elif heal == True: actions.heal(enemy, value) elif elixer == True: actions.elixer(enemy) takenAction = True deadPlayers = CheckAlive.getDead( deadPlayers, alivePlayers, self.message) alivePlayers = CheckAlive.getAlive(alivePlayers) if not alivePlayers: print("Lose") fight = False break
def main(): def display_taken_items(): img_path = pygame.image.load("resources/floor-tiles-20x20.png") myfont = pygame.font.SysFont("monospace", 12) item_taken = myfont.render("Item taken :" + str(constants.ITEM), 1, (255, 255, 255)) DISPLAYSURF.blit(img_path, (80, 280), (80, 180, 20, 20)) DISPLAYSURF.blit(item_taken, (0, 290)) def img_items(): """Load 3 images, resize them and put them into a list.""" needle = pygame.image.load("resources/aiguille.png").convert_alpha() needle = pygame.transform.scale(needle, (20, 20)) ether = pygame.image.load("resources/ether.png").convert() ether = pygame.transform.scale(ether, (20, 20)) plastic_tube = pygame.image.load("resources/tube.png").convert() plastic_tube = pygame.transform.scale(plastic_tube, (20, 20)) imgs = [needle, ether, plastic_tube] def random_img(): """Set an image to an item Take a random image in the list then delete it. Then loop in the list, for each loop, set images to items and then put them on the screen. """ while imgs: elem = random.choice(imgs) imgs.remove(elem) return elem for position in map.items: x, y = position.position x, y = x * 20, y * 20 DISPLAYSURF.blit(random_img(), (y, x)) def img_char(): """Display the character Load character image and add it to the screen, on character position. Take character older position, and change it to path image. """ img_path = pygame.image.load("resources/floor-tiles-20x20.png") char = pygame.image.load("resources/MacGyver.png").convert_alpha() char = pygame.transform.scale(char, (20, 20)) x, y = mac.older_position.position x, y = x * 20, y * 20 DISPLAYSURF.blit(img_path, (y, x), (60, 240, 20, 20)) x, y = mac.position.position x, y = x * 20, y * 20 DISPLAYSURF.blit(char, (y, x)) def not_moving_img(): """Load and display differents tiles representing path, wall, and ennemy.""" img_path = pygame.image.load("resources/floor-tiles-20x20.png") img_ennemy = pygame.image.load("resources/Gardien.png") img_ennemy = pygame.transform.scale(img_ennemy, (20, 20)) for position in map.empty: x, y = position.position x, y = x * 20, y * 20 DISPLAYSURF.blit(img_path, (y, x), (60, 240, 20, 20)) for position in map.wall: x, y = position.position x, y = x * 20, y * 20 DISPLAYSURF.blit(img_path, (y, x), (80, 180, 20, 20)) for position in map.end: x, y = position.position x, y = x * 20, y * 20 DISPLAYSURF.blit(img_ennemy, (y, x)) def win_or_lose(char, map): """Win or lose display if the character position is equal to map end position, check if item constant is equat to 3, if it is, the player wins and the victory screen is display, by setting the game constant to 2. If it is not equal to 3, display losing screen by setting game constant to 1. """ if char.position in map.end: if constants.ITEM == 3: constants.GAME += 2 else: constants.GAME += 1 def win_back(): """Load win screen.""" win_img = pygame.image.load("resources/win.png") DISPLAYSURF.blit(win_img, (0, 0)) def lose_back(): """Load lose screen.""" lose_img = pygame.image.load("resources/lose.png") DISPLAYSURF.blit(lose_img, (0, 0)) pygame.init() """Start Pygame.""" DISPLAYSURF = pygame.display.set_mode((300, 300)) """Set size of the screen.""" pygame.display.set_caption("Labyrinth") """Name the Pygame window.""" map = Labyrinth("maps/map1.txt") mac = Character(map) """Create character and labyrinth object from their respectives classes.""" not_moving_img() img_char() img_items() display_taken_items() while constants.GAME == 0: """Start game loop.""" win_or_lose(mac, map) for event in pygame.event.get(): """If we click quit button, quit Pygame and exit system""" if event.type == QUIT: pygame.quit() sys.exit() elif event.type == KEYDOWN: """Events to move character When an arrow key is pressed, call the character method move, that call the position method up, down ,right and left according to the pressed key. Then call the img_char() function to display character image. """ if event.key == K_UP: mac.move("up") img_char() display_taken_items() if event.key == K_DOWN: mac.move("down") img_char() display_taken_items() if event.key == K_LEFT: mac.move("left") img_char() display_taken_items() if event.key == K_RIGHT: mac.move("right") img_char() display_taken_items() pygame.display.update() """Update what is display on the screen""" while constants.GAME == 1: lose_back() for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == KEYDOWN: pygame.quit() sys.exit() pygame.display.update() while constants.GAME == 2: win_back() for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == KEYDOWN: pygame.quit() sys.exit() pygame.display.update() """When the win or lose screen is displayed, quit the game for any key pressed """