class TestEnemy(utest.TestCase): RUNS = 10 def setUp(self): self.dmap = DungeonMap(10) self.enemy = Enemy(self.dmap) def test_move_randomly_moves_one_tile_only(self): def single_run(): start_pos = self.enemy.position self.enemy.move_randomly() diff = tuple_diff(self.enemy.position, start_pos) valid_diffs = { -1, 1, 0 } assert diff[0] in valid_diffs and diff[1] in valid_diffs repeat(single_run, self.RUNS) def test_move_randomly_moves_in_bounds(self): def single_run(): self.enemy.position = (0, 0) self.enemy.move_randomly() self.assertTrue(self.dmap.in_bounds(self.enemy.position))
def spawn_one_enemy(self): """ Spawn one enemy with random type and random position """ import random from common import Util if self.last_group_end_time is not None and \ time.time() - self.last_group_end_time < self.scene_conf['time_between_enemy_group']: return if self.already_spawn_count >= self.scene_conf['enemy_group_num'][self.spawn_group_id]: return self.already_spawn_count += 1 # random prefab enemy_prefabs = self.enemy_conf['enemy_prefab'] enemy_prefab_idx = Util.get_random_index_with_distribution(self.scene_conf['enemy_spawn_distribution']) # random spawn transform spawn_transforms = self.scene_conf['enemy_spawn_transforms'] spawn_transform_idx = random.randint(0, len(spawn_transforms) - 1) spawn_transform = deepcopy(spawn_transforms[spawn_transform_idx]) # create enemy ep = enemy_prefabs[enemy_prefab_idx] eid = self.generate_enemy_id() enemy = Enemy(eid, spawn_transform[0:3], spawn_transform[3:6], deepcopy(self.scene_conf['target_position']), ep) self.enemies[eid] = enemy # send spawn message spawn_msg = enemy.generate_spawn_msg() self.broadcast(spawn_msg)
def move(self, amountX, amountY): self.px += amountX self.py += amountY for en in enemyList: Enemy.rawmove(en, amountX, amountY) rows = len(self.gridList) # When the left-most-grid falls off the screen if self.px % GRID_PIXEL_SIZE == 0: for row in range(rows): del self.gridList[row][0] # When the right-most-grid needs to be generated if (self.px + SCREEN_WIDTH) % GRID_PIXEL_SIZE == 0: if DebugDefines.WHOOPS_ON_GRID_CREATION: print("Whoop") for row in range(rows): leftGrid = self.gridList[row][-1] upGrid = self.gridList[row - 1][-1] if rows - 1 >= 0 else None self.gridList[row].append( generateNewGrid(self, leftGrid, upGrid, ((SCREEN_WIDTH // GRID_PIXEL_SIZE) + 1) * GRID_PIXEL_SIZE - 2 * SPRITE_SIZE + EXCESS_GRIDS * GRID_PIXEL_SIZE, row * GRID_PIXEL_SIZE)) for row in range(rows): for col in range(len(self.gridList[row])): self.gridList[row][col].move(amountX, amountY)
def __init__(self, debug_mode=False): self.debug_mode = debug_mode # to calcurate frame per second self._time = time.time() self.fps = 30 pyxel.init(width=250, height=200, caption="STG", scale=3, fps=30) pyxel.load("../asset.pyxres") self.player = Player(sx=100, sy=150, width=10, height=10, speed=2, debug_mode=self.debug_mode) self.player.activate() self.enemies = [] for i in range(20): e = Enemy(sx=100, sy=0, height=10, width=10, speed=0.5, max_hp=10, idx=i, debug_mode=self.debug_mode) e.activate() self.enemies.append(e) self.particles = [] self.back_ground = BackGround() pyxel.run(self.update, self.draw)
def attack( self, toHit ): #ac, profBonus, abilityBonus, advantage, damDiceNum, damDiceSize, critMult #d20=d.Dice.rolls(1,20,e.Enemy.getProfBonus(self)+e.Enemy.getAbilityMod(self)) d20 = d.rolls(1, 20) self.profBonus = str(e.getProfBonus(self)) print("Proficiency Bonus: " + self.profBonus) self.abilityMod = str(e.getAbilityMod(self)) print("Ability Modifier: " + self.abilityMod) #print("Ability Modifier: {}".format(e.getAbilityMod(self))) print("D20: {}".format(d20)) total = 0 if d20 == 1: total = "critical miss!" elif d20 == 20: total = "critical hit!" else: total = d20 + e.getProfBonus(self) + e.getAbilityMod(self) if total < toHit: print("Miss!") else: print("Hit!") print("Total: {}".format(total))
def main(self): enemy = Enemy() helper = Helper() self.print_board(helper) position = raw_input('Enter position (row # column #) : ') while position != 'q': position_to_move = tuple(position.replace(' ', '')) if helper.check_basic_validations(position_to_move): helper.board[int(position_to_move[0]), int(position_to_move[1])] = "X" self.print_board(helper) if self.check_win_condition('X', helper): print 'You win!' position = 'q' break if len(helper.get_current_positions('X')) + len( helper.get_current_positions('O')) == 9: print "It's a tie!" break print '\n... Computer is thinking ...\n' time.sleep(1) enemy.ai(helper) self.print_board(helper) if self.check_win_condition('O', helper): print 'Computer Wins!' break position = raw_input('Enter position : ')
def __init__(self, xlocation, ylocation, level, fps=1): # unique attributes parent class doesn't have self.enemy_ID = 2 # icecream ID self.image = PI.load("FPGraphics/burger/burgerFront.png") \ .convert_alpha() self.front_image = self.image self.bound_factor = 2 # attributes to be passed to parent for parent function use self.health = self.set_health(level) self.speed = self.set_speed(level) self.rect = self.image.get_rect() self.rect.x = xlocation self.rect.y = ylocation self.xboundl = xlocation - self.rect.width * self.bound_factor self.yboundt = ylocation - self.rect.width * self.bound_factor self.xboundr = xlocation + self.rect.width * self.bound_factor self.yboundb = ylocation + self.rect.width * self.bound_factor self.detect_distance = 250 self.IMAGES_RIGHT = [] self.IMAGES_LEFT = [] self.IMAGES_FRONT = [] self.IMAGES_BACK = [] self.load_images() Enemy.__init__(self, self.rect, self.IMAGES_RIGHT, self.IMAGES_LEFT, self.IMAGES_FRONT, self.IMAGES_BACK, self.health) self.drop_num = 3
class LocationCombatInstance(LocationBase): def __init__(self, instance, character): super(LocationCombatInstance, self).__init__(instance, character) self.enemy = Enemy(instance.getParentInstance()) # location should be changed to allow for enemy creation self.character = character self.instance = instance self.entryMessages.append("You encountered a lvl." + str(self.enemy.level) + " " + str(self.enemy.name) + ".") self.inputMessage = 'you can attack, run or examine the enemy with scan\n' self.name = "combat" attackLambda = lambda : self.enemy.attack(self.character, self.instance) self.actions.append( LocationBase.Action("Attack", LocationBase.Action.attack, [], [attackLambda], [])) self.actions.append( LocationBase.Action("Run", LocationBase.Action.run, [], [self.run], []) ) self.actions.append( LocationBase.Action("Examine", LocationBase.Action.examine, [], [self.enemy.checkLife], []) ) def run(self): if RNG_under_ten() <= 5: print("you failed to escape from the " + self.enemy.name) self.character.attack(self.enemy.getDamage()) else: print("As fast as you can you leave the " + self.enemy.name + " behind...") self.instance.leaveInstance() def attemptAttack(self, argument): if RNG_under_ten() >= 3: # determines whether i hit the enemy self.enemy.attack(self.character, self.instance)
def run_game(self): ''' This method implements a single game frame. It will work depends on ''' if self.__current_game_state is GAME_MENU: try: if self.__game_start_mode is LOAD_GAME: player_position, dungeon_map = DungeonGameSaveLoad.load_game() self.__dungeon_map.init_from_load(player_position, dungeon_map) else: map_size = int(input('Map size (>= 5): ')) self.__dungeon_map.generate_new_map(map_size) except NoSavedDataFileError as error: logging.error(f'User have chosen to load the game but we can\'t find game save data on address:\ {error}.') logging.info('Sorry, but there is no game save data. Please, save the game firstly or find the\ save data file.') self.process_game_start() else: self.__character = Character('User', DungeonGameConfig.PLAYER_HP, self.__dungeon_map) self.__enemy = Enemy('Enemy', self.__character, self.__dungeon_map) self.__current_game_state = GAMEPLAY self.__update_list.add_children(self.__dungeon_map, self.__character) self.__enemy.start_moving() elif self.__current_game_state is GAMEPLAY: logging.info(f'Current character stats: hp - {self.__character.get_hp()}, num of treasures - \ {self.__character.get_treasures_number()}') self.__update_list.update()
def __init__(self): # initialize game window, etc pg.init() pg.mixer.init() # dimension of window self.winWidth = 500 self.winLength = 281 # window set-up self.screen = pg.display.set_mode(size=(self.winWidth, self.winLength)) pg.display.set_caption("Shinobi Warrior") self.keys = pg.key.get_pressed() self.clock = pg.time.Clock() self.background_no = 1 self.last_update = 0 self.playing = False self.running = True self.score = 0 self.font2 = pg.font.Font('../fonts/Bank_Gothic_Medium_BT.ttf', 15) self.font = pg.font.Font('../fonts/Bank_Gothic_Medium_BT.ttf', 20) self.red = Enemy(420, 188) self.health_bar = pg.sprite.Group() self.enemies = pg.sprite.Group() self.kunais = pg.sprite.Group() self.red = Enemy(420, 188) self.health_bar.add(Health(30, 10)) self.health_bar.add(Health(60, 10)) self.health_bar.add(Health(90, 10)) self.enemies.add(self.red) self.kunais.add(Kunai())
def placeEnemies(BombermanBoard): # Place enemies on the board for i in range(0, MAX_ENEMY): block = Enemy(BombermanBoard.height, BombermanBoard.width) while not BombermanBoard.placeObject(block.x_pos, block.y_pos, EM): block = Enemy(BombermanBoard.height, BombermanBoard.width) # Append the enemies to the alive enemy list EnemyList.append(block)
def move_hero(self, direction): direction = direction.lower() x = self.hero_position_X y = self.hero_position_Y if direction == 'up': x -= 1 if direction == 'down': x += 1 if direction == 'left': y -= 1 if direction == 'right': y += 1 if x in range(0, self.X) and y in range(0, self.Y): enemy = Enemy(self.level * 15, self.level * 10) fight = Fight(self.hero, enemy, self.tmp_map, self.X, self.Y) if self.tmp_map[x][y] != '#': self.hero.take_mana() if self.tmp_map[x][y] == 'T': self.treasure_found() if self.tmp_map[x][y] == 'E': enemy = Enemy(self.level * 15, self.level * 10) fight.fight() self._update_tmp_map(x, y) if self.hero.can_cast(): fight.remote_battle(x, y) return True else: print('Invalid. Your move was out of the map!') return False
def createEnemy(self): for i in range(self.EnemyCount): direction = random.choice([1, -1]) if 4 - i > 1: enemy = Enemy(4 - i, direction, 1) else: enemy = Enemy(2, direction, 1) self.EnemyList.append(enemy) for j in range(self.EnemyPieceCount): if direction == -1: if j == 0: self.EnemyList[i].pieces.append(EnemyPiece(self.screenwidth + (j - 1) * 25, (i + 2) * 25, "Head", 0, direction, 1)) else: self.EnemyList[i].pieces.append(EnemyPiece(self.screenwidth + (j - 1) * 25, (i + 2) * 25, "Tail", 0, direction, 1)) elif direction == 1: if j == 0: self.EnemyList[i].pieces.append(EnemyPiece((-j) * 25, (i + 2) * 25, "Head", 180, direction, 1)) else: self.EnemyList[i].pieces.append(EnemyPiece((-j) * 25, (i + 2) * 25, "Tail", 180, direction, 1)) self.EnemyFeetSprites.add(self.EnemyList[i].pieces[-1].feet) self.levelSprites.add(self.EnemyList[i].pieces[-1].feet) self.EnemyPieces.add(enemy.pieces) self.levelSprites.add(enemy.pieces)
class Game(object): def __init__(self): pygame.init() # Config self.max_fps = 40 self.screen_length = int(GetSystemMetrics(1) * 0.75) self.screen_with = int(GetSystemMetrics(1) * 0.5) self.screen = pygame.display.set_mode( (self.screen_with, self.screen_length)) self.clock = pygame.time.Clock() self.delta = 0.0 pygame.display.set_caption("303 Polish Fighter Squadron") self.title_icon = pygame.image.load("title_icon.png") pygame.display.set_icon(self.title_icon) # Initialization self.player = Rocket(self) self.bullet = Bullets(self, self.player) self.enemy = Enemy(self, self.player, self.bullet) self.background = Background(self) print(self.screen_with, self.screen_length) while True: self.update() self.screen.fill((0, 0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: sys.exit(0) if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: self.bullet.shoot() # Ticking self.delta += self.clock.tick() / 1000.0 while self.delta > 1 / self.max_fps: self.tick() self.delta -= 1 / self.max_fps # Drawing self.draw() pygame.display.flip() def update(self): self.screen_length = int(GetSystemMetrics(1) * 0.75) self.screen_with = int(GetSystemMetrics(1) * 0.5) def tick(self): self.background.tick() self.bullet.tick() self.player.tick() self.enemy.tick() def draw(self): self.background.draw() self.bullet.draw() self.player.draw() self.enemy.draw()
def __init__(self, x, y, player, director): Enemy.__init__(self, x, y, "page.png", -1, "coordLarryPage.txt", [3, 3, 3, 3], player, (0, 10, 6, 10, 2, 4, 6, 11), director) self.setWeapon( WpnBlade("lightsaber.png", -1, Rect(128, 209, 42, 42), "sthswng1.wav", 0.2)) self.hp = 300
def main(): entity_table = [ Player(100, 0, "player.dat"), Enemy("Knight", 15, 0, "boss.dat"), Enemy("Guard", 15, 0, "boss2.dat") ] game = GameGui(entity_table) game.run()
def __init__(self, x, y, player, director): Enemy.__init__(self, x, y, "mr_h.png", -1, "coordMr_h.txt", [3, 3, 3, 3], player, (0, 10, 6, 10, 6, 4, 6, 8), director) # Maybe another kind of weapon? self.setWeapon(WpnRifle()) self.hp = 200
def __init__(self, x, y, player, director): Enemy.__init__(self, x, y, "FutureSoldier.png", -1, "coordFutureSoldier.txt", [3, 3, 3, 3], player, (0, 10, 6, 10, 6, 4, 6, 8), director) self.controller = RangeController(self, player, director) self.setWeapon(WpnLaser()) self.hp = 200 self.atk_delay_reset = 2.5
def __init__(self, x, y, player, director): Enemy.__init__(self, x, y, "nazist.png", -1, "coordNazist.txt", [3, 3, 3, 3], player, (0, 10, 6, 10, 6, 4, 6, 8), director) self.controller = RangeController(self, player, director) self.setWeapon(WpnRifle()) self.atk_delay_reset = 3.0 #Otherwise you don't have a chance self.hp = 50
def __init__(self): self.Stage = Stage(screen, 1, '1-1') self.Player = Player(screen, self.Stage) self.Enemy = Enemy(screen) remain_show() Sound.play_BGM('titerman') self.main()
def start(): global running while running: if player.data['name'] is None: print( 'Type one of the following commands: save, load, create, exit') cmd = str(input()) if cmd == 'load': player.data = PlayerData.load() print(player.data) if cmd == 'create': create_account() if cmd == 'exit': running = False else: if player.data['current_room'] == 'shop': print( 'Type one of the following commands: inspect item_name, heal, battle, shop, save, exit' ) else: print( 'Type one of the following commands: heal, battle, shop, save, exit' ) cmd = str(input()) if cmd == 'save': PlayerData.save(player) if cmd == 'exit': running = False if cmd == 'heal': player.restore_hp(1000) if cmd == 'battle': enemy = Enemy() enemy.data['current_hp'] = enemy.data['max_hp'] enemy.data['name'] = 'Skeleton' print(enemy.data) Battle.render_battle(player, enemy) # del enemy # print('test') if cmd == 'shop': player.data['current_room'] = 'shop' shop.get_items() if 'inspect' in cmd: cmds = cmd.split() item = cmds[1] shop_items = [item.name for item in shop.items] if item in shop_items: print(item) player.clamp_hp() render(player) if player.data['current_xp'] >= player.data['req_xp']: player.level_up() print('You leveled up!')
def test(self, move, B, P): if self.name == "Start": if move == "start game": self.body[0] = True print("You see two marauding goblins approaching! \n") print("Type '(a)ttack' to fight them, before they get you!") B.enemies = [ Enemy("Goblin1", "Goblin"), Enemy("Goblin2", "Goblin") ] B.Done = False if self.name == "Forest": if P.pos == "forest": self.body[0] = True print("A large figure approaches you.") print("Goblin King: I am the king of these lands.") print( "Goblin King: If you wish to stay alive, you must complete my quests." ) print("Type '(t)alk' to talk whoever is in your location. \n") if self.name == "Goblin King": if B.King.hp <= 0: print("You have defeated the Goblin King!") time.sleep(5) print("Epilogue:") time.sleep(3) print("The goblin village has gotten a bit better.") time.sleep(3) print("But it is slightly melancholic.") time.sleep(3) print("You have killed the king, but for what.") time.sleep(3) print("All he ever wanted was a friend.") time.sleep(3) print("He had started to think that maybe you were a friend.") time.sleep(3) print("You think that he needed you to go on those quests?") time.sleep(3) print("No.") time.sleep(3) print("He just wanted to build a friendship.") time.sleep(3) print("And you killed him.") time.sleep(3) print("I hope you're happy with you 'decision'.") time.sleep(3) exit()
class Stage_1: def __init__(self): self.Stage = Stage(screen, 1, '1-1') self.Player = Player(screen, self.Stage) self.Enemy = Enemy(screen) remain_show() Sound.play_BGM('titerman') self.main() def main(self): while 1: screen.fill((160, 180, 250)) # 強制アニメーション if self.Player.goal_animation(): global REMAIN REMAIN += 1 state_change(2) return if self.Player.dokan_animation() or self.Player.death_animation(): return self.Player.update() self.Enemy.update() self.Player.item_animation() self.Stage.update() Text.update() # スペースキーで2倍速 variable_FPS = FPS * (2 if pygame.key.get_pressed()[K_SPACE] else 1) clock.tick(variable_FPS) pygame.display.update(Rect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT)) for event in pygame.event.get(): # 「×」ボタンが押されたら終了 if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: # ESCキーが押されたら終了 if event.key == K_ESCAPE: pygame.quit() sys.exit() # F1キーが押されたらタイトルに戻る if event.key == K_F1: state_change(0) return # oキーが押されたら自殺 if event.key == K_o: Stage.player_object.isDeath = True
def __init__(self, pos): Enemy.__init__(self, Constants.PlayerImage(), pos) self.circlespeed = 0.01 self.offsetspeed = 0.3 self.dir = 0, 1 self.speed = 3 self.bulletrate = 0.05 timer = Timer(self.bulletrate, self.shoot_bullet) self.timers.append(timer)
def update(self): Enemy.update(self) tick = self.clock.tick() self.check_spell_action(tick) distance = distance_between_points(self.get_centered_pos(), self.player_pos) self.check_sword_action(distance, tick) if not self.sword.swinging: self.move(distance)
def create_enemy( log, number_of_enemies, ): log.info('Inicializando enemy {}'.format(number_of_enemies)) enemy = Enemy(number_of_enemies, MIN_POSX + (random.randint(20, 50)), MAX_POSY - random.randint(20, 50)) enemy.daemon = True enemy.start() return enemy
def create_enemy(self, name, w, h, index): if random() < 0.5: # to move left dir_moving = -1 else: # to move right dir_moving = 1 e = Enemy(w, h, self.movement_rate_w[name], self.movement_rate_h[name], self.images[name], self.size_w[name], self.size_h[name], index) e.dir_moving = dir_moving return e
def __init__(self, surface): self.surface = surface self.bullets = Bullets(surface, 5, 0.2) self.enemy = Enemy(3, surface) self.player_img = Utils.load_image("shooter", "gauntlet.png") self.player_img = pygame.transform.scale( self.player_img, (Constants.player_width, Constants.player_height)) self.position = ((surface.get_width() / 2) - (Constants.player_width / 2), surface.get_height() - (Constants.player_height + 10))
def __init__(self, x, y, player, director): Enemy.__init__(self, x, y, "legionnaire.png", -1, "coordLegion.txt", [3, 3, 3, 3], player, (5, 25, 15, 25, 10, 25, 0, 30), director) self.setWeapon( WpnBlade("wpns2.png", -1, Rect(344, 342, 28, 28), "blade_swing.wav", 0.5)) self.alive = True self.hp = 30
def gameLoop(): for event in pygame.event.get(): if event.type == pygame.QUIT: return True if event.type == pygame.KEYDOWN: pressMap = { pygame.K_DOWN: (0, -1), pygame.K_UP: (0, 1), pygame.K_LEFT: (-1, 0), pygame.K_RIGHT: (1, 0), } if event.key in pressMap: Snek.moveSnek(*pressMap[event.key]) #init enemies when they are almost on screen for enemy in Renderer.enemiesToInit: if (enemy.px < Renderer.SCREEN_WIDTH + 2 * Renderer.SPRITE_SIZE): Enemy.finish_init(enemy) #remove inited enemies Renderer.enemiesToInit = [ x for x in Renderer.enemiesToInit if not Enemy.isinit(x) ] #actual enemy logic for enemy in Renderer.enemyList: if (Enemy.isinit(enemy)): Enemy.update(enemy) if (enemy.px < -Renderer.SPRITE_SIZE * 2): Enemy.on_survived_board(enemy) #remove enemies that cleared the board Renderer.enemyList = [ x for x in Renderer.enemyList if not Enemy.needsremoving(x) ] return False