def __init__(self, pos=None): self.__dogpile = [] self.tangle_counter = 0 Monster.__init__(self, pos, 'T', libtcod.red) Tanglable.__init__(self, 0) AI.__init__( self) # so that memory wipes in range of a tangle don't crash it
def setup_game(self, filename: str) -> None: """ Set up a game with walls, player, food, monsters, and powerUp food on the screen """ # open data file to initialize the game screen with open(os.path.join("images", filename)) as f: data = [line.split() for line in f] w = len(data[0]) h = len(data) + 1 self._actors = [] self.stage_width, self.stage_height = w, h - 1 self.size = (w * ICON_SIZE, h * ICON_SIZE) # loop though each line to the file and set up the game for i in range(len(data)): for j in range(len(data[i])): # initialize all objects in the file and add them to the _actors attribute legend = data[i][j] if legend == 'P': # P is player object player = Player("player.png", j, i) self.player = player self._actors.append(player) elif legend == 'X': # X is a wall object self._actors.append(Wall("wall.png", j, i)) elif legend == 'M': # M is a monster object self._actors.append(Monster("monster.png", j, i)) elif legend == 'O': # O is a food object self._actors.append(Food("food.png", j, i)) elif legend == 'U': # U is a powerup object self._actors.append(PowerUp("powerUp.png", j, i))
class Level1: def __init__(self): self.m0 = Monster(0, 80, 16) self.m1 = Monster(1, 112, 112) def draw_level(self): self.draw_map() self.m0.draw_monster() self.m0.walk_monster() self.m1.draw_monster() self.m1.walk_monster() def draw_map(self): x = 0 y = 0 tm = 0 u = 0 v = 0 w = 16 h = 16 pyxel.bltm(x, y, tm, u, v, w, h)
def in_bubble(self, bubble): self.move(bubble.x, bubble.y) Monster.in_bubble(self, bubble) return -1
def __init__(self, lemmings, x, y, dir): Monster.__init__(self, Lemmy, x, y, dir, in_list=lemmings.lemlist) self.lemmings = lemmings
def main(): pygame.init() screen = pygame.display.set_mode(DISPLAY) pygame.display.set_caption("Trump - legend") # Пишем в шапку bg = Surface((WIN_WIDTH, WIN_HEIGHT)) # Создание заднего фона bg.fill(Color(BACKGROUND_COLOR)) # Заливаем фон сплошным цветом hero = Player(70, 70) # создаем героя по (x,y) координатам left = right = False # по умолчанию — стоим up = False is_on_pause = False # проверка на паузу entities = pygame.sprite.Group() # Все объекты obstacles = [] # то, во что мы будем врезаться или опираться coins = [] # список для монет monsters = pygame.sprite.Group() # все монстры entities.add(hero) levels = [load_level(f'level{i + 1}.txt') for i in range(1)] current_level = 0 # уровень на данный момент x = y = 0 # координаты for row in levels[current_level]: # вся строка for col in row: # каждый символ if col == "-": # знак для платформ pf = Platform(x, y) entities.add(pf) obstacles.append(pf) elif col == "*": # для шипов bd = BlockDie(x, y) entities.add(bd) obstacles.append(bd) elif col == "m": # для монет mn = Coin(x, y) entities.add(mn) coins.append(mn) elif col == "e": # для монстров en = Monster(x, y) entities.add(en) obstacles.append(en) monsters.add(en) x += TILE_WIDTH # блоки платформы ставятся на ширине блоков y += TILE_HEIGHT # то же самое и с высотой x = 0 # на каждой новой строчке начинаем с нуля total_level_width = len( levels[current_level] [0]) * TILE_WIDTH # Высчитываем фактическую ширину уровня total_level_height = len(levels[current_level]) * TILE_HEIGHT # высоту camera = Camera(camera_configure, total_level_width, total_level_height) timer = pygame.time.Clock() running = True while running: # Основной цикл программы timer.tick(30) # fps monsters.update(obstacles) for e in pygame.event.get(): # Обрабатываем события if e.type == QUIT: running = False if e.type == KEYDOWN and e.key == K_UP: up = True if e.type == KEYUP and e.key == K_UP: up = False if e.type == KEYDOWN and e.key == K_LEFT: left = True if e.type == KEYDOWN and e.key == K_RIGHT: right = True if e.type == KEYUP and e.key == K_RIGHT: right = False if e.type == KEYUP and e.key == K_LEFT: left = False if e.type == KEYDOWN and e.key == K_ESCAPE: # Esc - управляющая клавиша паузы is_on_pause = 1 - is_on_pause for obj in obstacles: # останавливаем всех монстров в зависимости от состояния if obj.__class__ == Monster: obj.stop(is_on_pause) screen.blit(bg, (0, 0)) # Каждую итерацию необходимо всё перерисовывать if not is_on_pause: hero.update(left, right, up, obstacles, coins, levels[current_level]) # передвижение camera.update(hero) for e in entities: screen.blit(e.image, camera.apply(e)) if is_on_pause: draw_pause(screen) draw_score(screen, str(hero.scores)) pygame.display.update() # обновление и вывод всех изменений на экран pygame.quit()
def setUp(self): self.monster1 = Monster() self.monster2 = Monster(sound='Urk!') self.troll1 = Troll() self.troll2 = Troll(sound="That's just your opinion.") self.horde = [self.monster1, self.monster2, self.troll1, self.troll2]
def test_monster_getitem_bad_key(self): monster = Monster(left_hand="axe") with self.assertRaises(KeyError): monster['left_foot']
def test_monster_getitem(self): monster = Monster(left_hand="axe") self.assertEqual(monster['left_hand'], 'axe')
def spawn(self): monster = Monster(self) self.monsters[monster.name] = monster _log.info("Spawning {}.".format(monster.name)) monster.connect()
def __init__(self): self.m0 = Monster(0, 80, 16) self.m1 = Monster(1, 112, 112)
def init_dungeon(): #Press 1 to being game. 1 is type int. start = int(input('Press 1 to begin: ')) #If anything except 1 is pressed game does not start and player is prompted again. while start != 1: start = int(input('Press 1 to begin: ')) #When Player enters 1 they are asked for their name. #my_player is instantiated with the entered name above. ^ if start == 1: your_name = input('Enter your name: ') #Not all properties of my_player are currently being used. my_player = Player(name=your_name, player_lvl=0, current_exp=0, lvlup_exp=10, HP=10, MP=10, player_atk=1, weapon='One Punch', skills='One Punch', inventory=['One Punch']) #Sets current room number to 1. room_num = 1 #Sets number of enemies required to clear room to 3. #enemy_num = 3 #Tells player current room. print('You are in room number: ', room_num) #This line checks if poring is dead. If False = fight. for i in range(3): # Create instance of class Monster. enemy = Monster('slime', 1, 'Poring', 1, 1, 3, 3, 4, 'feather') #enemy_health = enemy.mob_type #enemy_lvl = enemy.lvl #enemy_name = enemy.name #enemy_atk = enemy.atk_power #enemy_matk = enemy.matk_power enemy_health = enemy.HP #enemy_mana = enemy.MP #enemy_exp = enemy.exp_value #enemy_swag = enemy.loot #Adjust monster instance health for additional use. def enemy_property_adjust(): enemy_health = enemy.HP #This will be full heal later. player_health = my_player.HP player_mana = my_player.HP # Start encounter with poring. print('You encounter a ', enemy.name) #while enemy.is_alive == True: for enemy_counter in range (3): #Prompts player to take an action. action = int(input('Press 1 to attack: ')) #Action with value 1 leads to an attack on poring. if action == 1: #Player attack phase. print('You attack ', enemy.name, 'for ', my_player.player_atk, 'damage.') enemy_health -= my_player.player_atk print(enemy.name, ' has', enemy_health, 'left.') #Enemy attack phase print(enemy.name, 'attacks you for', enemy.atk_power) player_health -= enemy.atk_power print('You have ', player_health, ' left.') #If Poring dies (HP <= 0) do: if enemy_health <= 0: #Congratulate player on their victory over poring1. print('Congratulations! You killed', enemy.name, '!') #Alert player of exp received. print('You receive ', enemy.exp_value, 'experience!') #Calculate exp and update player current_exp. my_player.current_exp = my_player.current_exp + enemy.exp_value print(my_player.current_exp) #Alert player of loot received. print('You recieve ', enemy.loot, '! It has been placed in your inventory!') #Add loot (str) to inventory (list). my_player.inventory.append(enemy.loot) print(my_player.inventory) #Update number of enemies to beat. enemy_counter += 1 #Reset enemy values for new encounter enemy_property_adjust() #Check to see if player leveled up, if True: self.levelup(). if my_player.current_exp >= my_player.lvlup_exp: #Fix this!! Need to full heal on level up and other instances. player_health = my_player.HP player_mana = my_player.MP my_player.level_up() stats = vars(my_player) print(stats)
def get_score(): return Monster.get_count()
def __init__(self,pos=None): self.__dogpile = [] self.tangle_counter = 0 Monster.__init__(self,pos,'T',libtcod.red) Tanglable.__init__(self,0) AI.__init__(self) # so that memory wipes in range of a tangle don't crash it