Пример #1
0
 def spawn(self):
     if self.do_spawn:
         preliminarily_group_coins = pygame.sprite.Group()
         preliminarily_group_nitro = pygame.sprite.Group()
         preliminarily_group_npc = pygame.sprite.Group()
         if self.chance(15):
             coin = Coin(preliminarily_group_coins, random.choice(
                 self.x_places), random.randrange(50, 350), self.road)
             if self.check(coin):
                 self.coin_group.add(coin)
         if self.chance(3):
             nitro = Nitro(preliminarily_group_nitro, self.road, random.choice(
                 self.x_places), random.randrange(50, 350))
             if self.check(nitro):
                 self.nitro_group.add(nitro)
         if self.chance(30):
             x = random.choice(self.x_places)
             if self.x_places[0] <= x <= self.x_places[1]:
                 x -= random.randrange(60, 90)
                 y = random.randrange(-150, -110)
                 npc = Npc(preliminarily_group_npc, x, y, True)
             else:
                 x -= random.randrange(60, 90)
                 y = random.randrange(890, 990)
                 npc = Npc(preliminarily_group_npc, x, y, False)
             if self.check(npc):
                 self.enemy_group.add(npc)
         if self.player.bg_time == 0:
             self.bg_time = time.time()
             self.player.bg_time = 1
Пример #2
0
 def __init__(self, x, y, name, filename, mID):
     if len(mID) == 2:
         Npc.__init__(self, x, y, 'The battle is joined!', filename)
     else: Npc.__init__(self, x, y, mID[2], filename)
     if self.message == '': self.message = 'The battle is joined!'
     self.name = name
     self.turn = False
     self.confused = 0
     self.ID = mID
     self.type = 'enemy'
Пример #3
0
    def handle_event(self):
        if self.story["action"] == "death":
            if self.story["sprite"] == "player":
                self.game.story_manager.display_speech(["GAME OVER"], "bottom")
                self.game.story_manager.set_unblockable(False)
                self.game.perso.kill()
            elif self.story["sprite"]:
                sprite_name = self.story["sprite"]
                sprite = self.game.layer_manager.get_sprite(sprite_name)
                time.sleep(2)
                sprite.kill()
        elif self.story["action"] == "spawn":
            if self.story["spawn_type"] == "npc":
                npc = Npc(self.story["name"],
                          os.path.join(self.game.config.get_sprite_dir(),
                                       self.story["sprite_img"]),
                          self.story["destination"],
                          self.game.layer_manager["npcs"])
                npc.definir_position(self.story["destination"][0],
                                     self.story["destination"][1])
            else:
                monster = Monster(self.story["name"],
                                  os.path.join(self.game.config.get_sprite_dir(),
                                               self.story["sprite_img"]),
                                  self.story["destination"],
                                  self.game.layer_manager["monster"])
                monster.definir_position(self.story["destination"][0],
                                         self.story["destination"][1])
        elif self.story["action"] == "speech":
            self.game.story_manager.display_speech(self.story['text'],
                                                   self.story['position'])
        elif self.story["action"] == "move":
            self.game.story_manager.blocking = True
            self.game.story_manager.set_unblockable(False)
            sprite = self.game.layer_manager.get_sprite(self.story["sprite"])
            dest = self.story["destination"]
            sprite.saveLastPos()
            if sprite.collision_rect.x != dest[0]:
                if sprite.collision_rect.x < dest[0]:
                    sprite.move(sprite.speed * sprite.accel, 0, "right")
                else:
                    sprite.move(-(sprite.speed * sprite.accel), 0, "left")
                self.game.story_manager.events.insert(0, self)
                return
            if sprite.collision_rect.y != dest[1]:
                if sprite.collision_rect.y < dest[1]:
                    sprite.move(0, sprite.speed * sprite.accel, "down")
                else:
                    sprite.move(0, -(sprite.speed * sprite.accel), "up")
                self.game.story_manager.events.insert(0, self)
                return

            if self.game.story_manager.blocking:
                self.game.story_manager.set_unblockable(True)
                self.game.story_manager.blocking = False
Пример #4
0
 def __init__(self, x, y, name, filename, mID):
     if len(mID) == 2:
         Npc.__init__(self, x, y, 'The battle is joined!', filename)
     else:
         Npc.__init__(self, x, y, mID[2], filename)
     if self.message == '': self.message = 'The battle is joined!'
     self.name = name
     self.turn = False
     self.confused = 0
     self.ID = mID
     self.type = 'enemy'
Пример #5
0
    def __init__(self, world, window, renderer, factory):

        self.db = DataBase()

        self.running = False
        self.world = world
        self.window = window
        self.renderer = renderer
        self.factory = factory

        self.background_tiles = []
        self.behind_tiles = []
        self.front_tiles = []
        self.sprites = []

        x = int(WindowSize.WIDTH / 2)
        y = int(WindowSize.HEIGHT / 2)

        self.all_npc = []
        self.init_map("Debug Room")

        # self.map_file = MAPS.get_path("map.tmx")
        # self.map_background_sprite = Map(self.map_file, "background")

        self.npc_sprite_sheet = SpriteSheet("Edelbert")
        self.npc_sprite = self.npc_sprite_sheet.get_sprite()
        self.npc = Npc(self.world, self.npc_sprite, 0, 0)

        self.player_sprite_sheet = SpriteSheet("Player")
        self.player_sprite = self.player_sprite_sheet.get_sprite()
        self.player = Player(self.world, self.player_sprite, x - 64, y - 64)

        self.player_animation = PlayerAnimationSystem("Player")
        self.npc_animation = NpcAnimationSystem("Edelbert")

        self.player_movement = PlayerMovementSystem(x - 128, y - 128, x + 128,
                                                    y + 128)
        self.npc_movement = PlayerMovementSystem(0, 0, WindowSize.WIDTH,
                                                 WindowSize.HEIGHT)

        # self.all_enemies = [Enemy(self.renderer, self.factory, "doombat")]

        self.world.add_system(self.player_animation)
        self.world.add_system(self.player_movement)
        self.world.add_system(self.npc_animation)
        self.world.add_system(self.npc_movement)

        self.world.add_system(self.renderer)
Пример #6
0
def launchGame():
    pygame.init()
    st = Settings()
    mapa = Map(st, './images/maps/temptilesbig.jpg', './maps/map')
    pl = Player(st)
    menu = Menu()
    npcs = [Npc("./images/sprite_scaled/front1.png", 12, 10, NpcType.neutral)]
    screen = pygame.display.set_mode((st.screenX, st.screenY))
    pygame.display.set_caption("2DGame")

    while st.runningFlag:
        if st.menuFlag:
            menu.actionListener(st)
            menu.update(screen, st)
            pygame.display.update()
        elif st.inventoryFlag:
            pl.inventory.actionListener(pl, st)
            pl.inventory.update(screen)
            pygame.display.update()
        else:
            screen.fill(mapa.color)
            actionListener(pl, st, mapa, npcs)
            mapa.update(st, screen, pl)
            for npc in npcs:
                npc.update(mapa, screen, st)
            pl.update(st, screen)
            pygame.display.update()
            time.sleep(0.06)
Пример #7
0
def generate_npc():
    gender = attr.random_gender()
    name = attr.random_name(gender)
    surname = attr.random_surname()
    birth_year = start_year
    max_age = random.randint(50, 120)
    npc = Npc(name, surname, birth_year, gender, max_age)
    return npc
Пример #8
0
    def spawn(self):

        if self.spawn_count < self.spawn_max:
            x = random.randint(self.x, self.x + self.w)
            y = random.randint(self.y, self.y + self.h)

            # Create npc
            Npc(self.name, x, y, self.zone, self.world, self)

            self.spawn_count += 1
Пример #9
0
    def __init__(self, nr_of_bots, player, screen):

        self.player = [Player(player)]
        for i in range(nr_of_bots):
            self.player.append(Npc(random.choice(NAMES)))
        self.deck = Deck(screen)

        self.screen = screen
        self.active_card = Card(1, 1, screen)

        self.player_turn = random.randrange(0, nr_of_bots)
        self.running = True
        self.real_player = 0
Пример #10
0
def enter():
    global character, map1, key
    global npc
    global npc_chat
    map1 = Map()
    game_world.add_object(map1, 0)
    key = Key()
    character = Character()
    npc = Npc()
    npc_chat = load_image('sprite//npc_chat.png')
    game_world.add_object(key, 1)
    game_world.add_object(character, 1)
    game_world.add_object(npc, 1)
    game_world.add_object(npc_chat, 1)
Пример #11
0
def select_npc_by_pk(pk):
    pk = str(pk)
    conn = create_connection()
    cur = conn.cursor()
    cur.execute("SELECT * FROM npc WHERE id=?", (pk, ))
    row = cur.fetchall()[0]
    conn.close()
    npc = Npc(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7],
              row[8], row[9], row[10], row[11], row[12], row[13], row[14],
              row[15], row[16], row[17], row[18], row[19], row[20], row[21],
              row[22], row[23], row[24], row[25], row[26], row[27], row[28],
              row[29], row[30], row[31], row[32], row[33], row[34], row[35],
              row[36], row[37], row[38], row[39], row[40], row[41], row[42],
              row[43], row[44], row[45])
    return npc
Пример #12
0
def select_all_npcs():
    conn = create_connection()
    cur = conn.cursor()
    cur.execute("SELECT * FROM npc")
    query_result = cur.fetchall()
    conn.close()
    npcList = []
    for row in query_result:
        npc = Npc(row[0], row[1], row[2], row[3], row[4], row[5], row[6],
                  row[7], row[8], row[9], row[10], row[11], row[12], row[13],
                  row[14], row[15], row[16], row[17], row[18], row[19],
                  row[20], row[21], row[22], row[23], row[24], row[25],
                  row[26], row[27], row[28], row[29], row[30], row[31],
                  row[32], row[33], row[34], row[35], row[36], row[37],
                  row[38], row[39], row[40], row[41], row[42], row[43],
                  row[44], row[45])
        npcList.append(npc)
    return npcList
Пример #13
0
def main():
    """ Main Program """
    #pygame.init()
    #main_menu()
    # Set the height and width of the screen
    size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)

    pygame.display.set_caption("Danga")

    ### Main score song we pause for debug
    song = pygame.mixer.Sound("sounds/danga.wav")
    song.play(-1)

    score = 0
    # Create the player
    player = Player()
    player_shot = None
    # Create the enemy
    enemy = Enemy()
    enemies  = pygame.sprite.Group()
    npcs  = pygame.sprite.Group()

    #Prepare for enemy_shots
    enemy_shots  = pygame.sprite.Group()

    npc = Npc()

    # Create all the levels
    level_list = []
    level_list.append(levels.Level_01(player))
    level_list.append(levels.Level_02(player))

    # Set the current level
    current_level_no = 0
    current_level = level_list[current_level_no]

    active_sprite_list = pygame.sprite.Group()
    player.level = current_level
    enemy.level = current_level
    npc.level = current_level

    player.rect.x = 340
    player.rect.y = constants.SCREEN_HEIGHT - player.rect.height
    active_sprite_list.add(player)

    enemy.rect.x = constants.SCREEN_WIDTH - enemy.rect.width
    enemy.rect.y = 0 #constants.SCREEN_HEIGHT - enemy.rect.height

    active_sprite_list.add(enemy)
    enemies.add(enemy)

    npc.rect.x = constants.SCREEN_WIDTH - enemy.rect.width
    npc.rect.y = 0 #constants.SCREEN_HEIGHT - enemy.rect.height

    #aggiungiano un NPC ?
    #active_sprite_list.add(npc)
    #npcs.add(npc)

    #Loop until the user clicks the close button.
    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()

    # -------- Main Program Loop -----------
    while not done:
        for event in pygame.event.get(): # User did something
            if event.type == pygame.QUIT: # If user clicked close
                done = True # Flag that we are done so we exit this loop

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    player.go_left()
                if event.key == pygame.K_RIGHT:
                    player.go_right()
                if event.key == pygame.K_UP:
                    player.jump()
                if event.key == pygame.K_SPACE:
                    player.yell()
                if event.key == pygame.K_LCTRL:
                    #shots.append(Shot(player.rect.center, player.direction))
                    player_shot = Shot(player.rect.center, player.direction)
                    active_sprite_list.add(player_shot)
                #if event.key == pygame.K_RCTRL:
                    #shots.append(EnemyShot(enemy.rect.center))
                    #active_sprite_list.add(EnemyShot(enemy.rect.center, player))

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT and player.change_x < 0:
                    player.stop()
                if event.key == pygame.K_RIGHT and player.change_x > 0:
                    player.stop()

        ### ENEMY SHOTS
        time_now = pygame.time.get_ticks()
        #print (str(time_now - enemy.last_shot))
        if time_now - enemy.last_shot > 1500:
            current_shot = EnemyShot(enemy.rect.center, player)
            enemy_shots.add(current_shot)
            active_sprite_list.add(current_shot)
            enemy.last_shot = time_now
            #draw_text('COLLIDE!', font40, constants.WHITE, int( constants.SCREEN_WIDTH / 2 - 100), int( constants.SCREEN_HEIGHT / 2 + 50))

        ### MAIN COLLISION (Player Shot)
        if player_shot:
            if pygame.sprite.collide_rect(player_shot, enemy):
               #print("COLLIDE")
               explosion = Explosion(enemy.rect.centerx, enemy.rect.centery, 4)
               active_sprite_list.add(explosion)
               score += 10

        ### MAIN COLLISION (Enemy Shot)
        if pygame.sprite.collide_rect(current_shot, player):
           #print("COLLIDE")
           explosion = DeathExplosion(player.rect.centerx, player.rect.centery, 4)
           active_sprite_list.add(explosion)
           player.shield = player.shield -3

        ### SHIELD, DEATH, LIVES AND GAME OVER
        if player.shield <= 0: 
            player_die_sound.play()
            death_explosion = DeathExplosion(player.rect.centerx, player.rect.centery, 4)
            active_sprite_list.add(death_explosion)
            # running = False     ## GAME OVER 3:D
            player.hide()
            player.lives -= 1
            player.shield = 100

        ## if player died and the explosion has finished, end game
        if player.lives == 0 and not death_explosion.alive():
            done = True
            #draw_text(screen, "GAME OVER", 30, constants.SCREEN_WIDTH/2, constants.SCREEN_HEIGHT/2)

        ### SPRITE UPDATES
        # Update the player.
        active_sprite_list.update()

        # Update items in the level
        current_level.update()

        ### PLAYER SCREEN LIMITS

        # print ('x:'+str(player.rect.x))
        # print ('y:'+str(player.rect.y))
        # If the player gets near the right side, shift the world left (-x)
        if player.rect.x >= 500:
            diff = player.rect.x - 500
            player.rect.x = 500
            current_level.shift_world(-diff)

        # If the player gets near the left side, shift the world right (+x)
        if player.rect.x <= 120:
            diff = 120 - player.rect.x
            player.rect.x = 120
            current_level.shift_world(diff)

        # If the player gets to the end of the level, go to the next level
        current_position = player.rect.x + current_level.world_shift
        if current_position < current_level.level_limit:
            player.rect.x = 120
            if current_level_no < len(level_list)-1:
                current_level_no += 1
                current_level = level_list[current_level_no]
                player.level = current_level

        ### DRAWS

        # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
        current_level.draw(screen)
        active_sprite_list.draw(screen)

        draw_text(screen, str(score), 18, constants.SCREEN_WIDTH / 2, 10) ## 10px down from the screen
        #draw_shield_bar(screen, 5, 5, 100)
        draw_shield_bar(screen, 5, 5, player.shield)

        # Draw lives
        draw_lives(screen, constants.SCREEN_WIDTH - 100, 5, player.lives, player_mini_img)

        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

        # Limit to 60 frames per second
        clock.tick(60)

        # Go ahead and update the screen with what we've drawn.
        pygame.display.flip()

    game_over()
    main_menu()
Пример #14
0
from npc import Npc, Mob
#________NPCs________
ralph = Npc("Ralph, the Wonder Llama")  # Credits
arthur = Npc("King Arthur")
patsy = Npc(
    'Patsy',
    "Your trusty servant Patsy.  He rides the length and breadth of the land with you, in search of knights who will join you in your court at Camelot."
)  # Arthur's servant
launcelot = Npc("Sir Launcelot")
bedemir = Npc(
    "Sir Bedemir",
    'The wise Sir Bedemir was the first to join King Arthur\'s knights.')
bravesirrobin = Npc("Brave Sir Robin")
galahad = Npc('Sir Galahad')
deadPerson = Npc('Dead Person', 'He feels happy!')
dennis = Npc("Dennis")  # He looks like an old woman, and he's 37
greenKnight = Npc("Green Knight")
tim = Npc("Tim")  # The laden swallow guy

#________MOBS________
niKnight = Mob("A Knight Who Says...  NEE")
blackKnight = Mob(
    "The Black Knight",
    'A knight, clad in black armor, guards the bridge.  "NONE shall pass."  He says, in no uncertain terms.'
)  # Flesh Wound
guard1 = Mob(
    "A guard",
    "This guard seems to know alot about swallows.  Both African AND European."
)
guard2 = Mob(
    "Another guard",
Пример #15
0
cseDoorOut = Door(canvas, 'cseDoorOut', 800, 836, 128, 36, inventory, player,
                  cseRoom, juniorHallway, (118, 220))
stairwellEntrance = Door(canvas, 'stairwellEntrance', 424, 984, 168, 40,
                         inventory, player, outside, stairwell, (180, 614))


def hanasDialogue():
    if stairwellEnter:
        inventory.addItem(flashlight)
        return Writing('playername', 'male').chanas3()
    else:
        return Writing('playername', 'male').chanas2()


mrHanas = Npc(canvas, 64, 96, 150, 300, 1, sprites.chanasAvatars, 'Mr. Hanas',
              sprites.hanasface, hanasDialogue, inventory, player,
              juniorHallway)

metBabbinFirstTime = False
tookFuel = False


def frostingEffect(thisFrosting, thisMsBabbin, clickx, clicky):
    global tookFuel
    if thisMsBabbin.click(clickx, clicky, False):
        thisFrosting._inventory.removeItem(thisFrosting)
        thisFrosting.depopulate
        funkyFrostingFuel.populate()
        tookFuel = True
        info = Dialogue(canvas,
                        Writing("playername", "male").babbin4(), 'Mrs. Babbin',
Пример #16
0
    def load(self, player_name, zone_source, players, monsters, npcs,
             containers, zone_data):

        # unload monsters
        for m in self.monsters.values():
            m.unload()

        for p in self.players.values():
            p.unload()

        for n in self.npcs.values():
            n.unload()

        for s in self.spells:
            s.unload()

        # Load zone and save to cache
        if not self.zones.has_key(zone_source):

            # write zone_data to zone_source
            with open('client_data/zones/' + zone_source, 'w') as tmxfile:
                tmxfile.write(zone_data)

            self.zones[zone_source] = load_pyglet('client_data/zones/' +
                                                  zone_source)
            self.zone = self.zones[zone_source]

            for layer in self.zone.layers:
                if layer.name == 'character' or layer.name == 'blocked' or layer.name == 'block' or layer.name == 'spawns':
                    pass
                else:
                    layer.batch = pyglet.graphics.Batch()
                    layer.sprites = []
                    for x, y, image in layer.tiles():
                        y = self.zone.height - y - 1
                        sprite = pyglet.sprite.Sprite(image,
                                                      x * self.zone.tilewidth,
                                                      y * self.zone.tileheight,
                                                      batch=layer.batch)
                        layer.sprites.append(sprite)
        else:
            # Set zone from cache
            self.zone = self.zones[zone_source]

        self.player_name = player_name
        self.players = {}
        self.monsters = {}
        self.npcs = {}
        self.containers = {}
        self.offset = []

        for name, player in players.items():
            self.players[name] = Player(player['title'], player['gender'],
                                        player['body'], player['hairstyle'],
                                        player['haircolor'], player['armor'],
                                        player['head'], player['weapon'],
                                        player['x'], player['y'])

        for name, npc in npcs.items():
            self.npcs[name] = Npc(npc['title'], npc['gender'], npc['body'],
                                  npc['hairstyle'], npc['haircolor'],
                                  npc['armor'], npc['head'], npc['weapon'],
                                  npc['x'], npc['y'], npc['villan'])

        for name, monster in monsters.items():
            self.monsters[name] = Monster(monster['title'], monster['source'],
                                          monster['x'], monster['y'])

        for name, container in containers.items():
            self.containers[name] = Container(
                container['title'], container['x'], container['y'],
                container['source'], container['source_w'],
                container['source_h'], container['source_x'],
                container['source_y'])

        # Set our label to green :)
        self.players[player_name].label.color = (0, 255, 0, 255)
Пример #17
0
 def __init__(self, x, y, name, filename, roam=5):
     Npc.__init__(self, x, y, name, filename)
     self.home = (x,y)
     self.roam = 5
     self.type = 'animal'
Пример #18
0
#LA BOUCLE PRINCIPALE DEMARRE ICI 
continuer = 1
mon_horloge = pygame.time.Clock()
while continuer:
	for event in pygame.event.get():
		if event.type == QUIT:
			continuer = 0

	keys = pygame.key.get_pressed()

	if keys[K_ESCAPE]:
		menu = Menu(fenetre)
		menu.open_menu()

	fenetre.fill(Color("Black"))
	#Rendu de la map
	tileMap.mapRender(camera)
	camera.update(perso)
	#On gere le Perso Ici (Mouvement et affichage a l ecran)
	perso.event(tileMap, camera)
	
	if Npc.alive == True:
		Npc.event(tileMap, camera)

	#Souris position
	#mouse_pos = pygame.mouse.get_pos()
	#print mouse_pos[1], mouse_pos[1]

	pygame.display.flip()
	mon_horloge.tick(60)
 def add_enemy_patrol(self, race):
     new_enemies = [Npc(race), Npc(race)]
     self.enemy_patrols.append(new_enemies)
Пример #20
0
class Game:
    def __init__(self, world, window, renderer, factory):

        self.db = DataBase()

        self.running = False
        self.world = world
        self.window = window
        self.renderer = renderer
        self.factory = factory

        self.background_tiles = []
        self.behind_tiles = []
        self.front_tiles = []
        self.sprites = []

        x = int(WindowSize.WIDTH / 2)
        y = int(WindowSize.HEIGHT / 2)

        self.all_npc = []
        self.init_map("Debug Room")

        # self.map_file = MAPS.get_path("map.tmx")
        # self.map_background_sprite = Map(self.map_file, "background")

        self.npc_sprite_sheet = SpriteSheet("Edelbert")
        self.npc_sprite = self.npc_sprite_sheet.get_sprite()
        self.npc = Npc(self.world, self.npc_sprite, 0, 0)

        self.player_sprite_sheet = SpriteSheet("Player")
        self.player_sprite = self.player_sprite_sheet.get_sprite()
        self.player = Player(self.world, self.player_sprite, x - 64, y - 64)

        self.player_animation = PlayerAnimationSystem("Player")
        self.npc_animation = NpcAnimationSystem("Edelbert")

        self.player_movement = PlayerMovementSystem(x - 128, y - 128, x + 128,
                                                    y + 128)
        self.npc_movement = PlayerMovementSystem(0, 0, WindowSize.WIDTH,
                                                 WindowSize.HEIGHT)

        # self.all_enemies = [Enemy(self.renderer, self.factory, "doombat")]

        self.world.add_system(self.player_animation)
        self.world.add_system(self.player_movement)
        self.world.add_system(self.npc_animation)
        self.world.add_system(self.npc_movement)

        self.world.add_system(self.renderer)

    def init_map(self, map_name):

        map_data = self.db.get_map_npc(map_name)
        map_npc = []

        for data in map_data:
            map_npc.append(data["npc"])
            print(data)

        # for npc in map_npc:
        #    self.all_npc.append(NPC(self.renderer, self.factory, npc))

    """
    def get_sprites(self):

        self.sprites.append(self.map_background_sprite)
        # self.sprites.append(self.map_behind_sprite)

        # self.sprites.append(self.map_front_sprite)

        for npc in self.all_npc:
            for sprite in npc.get_sprites():
                self.sprites.append(sprite)

        for enemy in self.all_enemies:
            for sprite in enemy.get_sprites():
                self.sprites.append(sprite)

    def update(self, position, motion_type, facing, elapsed_time):

        self.map_background_sprite.position = position
        # self.map_behind_sprite.position = position

        # self.player.update(motion_type, facing, elapsed_time)

        for npc in self.all_npc:
            npc.update(position, elapsed_time)

        for enemy in self.all_enemies:
            enemy.update(position, elapsed_time)
    """

    def run(self):

        game_input = Input()

        speed_x, speed_y = 2, 1
        player_pos = [-100, -100]

        # motion_type = self.player_motion_type
        # facing = self.player_facing

        self.running = True
        last_update_time = SDL_GetTicks()  # units.MS

        while self.running:
            start_time = SDL_GetTicks()  # units.MS

            game_input.begin_new_frame()
            game_events = get_events()

            for event in game_events:
                if event.type == SDL_KEYDOWN:
                    game_input.key_down_event(event)

                elif event.type == SDL_KEYUP:
                    game_input.key_up_event(event)

                elif event.type == SDL_QUIT:
                    self.running = False
                    break

            if not self.running:
                self.clear()
                break

            # Exit
            if game_input.was_key_pressed(SDLK_ESCAPE):
                self.clear()
                self.running = False
                break

            # Player movement
            if game_input.is_key_held(SDLK_RIGHT) and game_input.is_key_held(
                    SDLK_UP):
                player_pos[0] -= speed_x
                player_pos[1] += speed_y
                self.player.velocity.vx = speed_x
                self.player.velocity.vy = -speed_y
                self.player.facing.set("right_up")
                self.player.motiontype.set("walking")
            elif game_input.is_key_held(SDLK_RIGHT) and game_input.is_key_held(
                    SDLK_DOWN):
                player_pos[0] -= speed_x
                player_pos[1] -= speed_y
                self.player.velocity.vx = speed_x
                self.player.velocity.vy = speed_y
                self.player.facing.set("right_down")
                self.player.motiontype.set("walking")
            elif game_input.is_key_held(SDLK_LEFT) and game_input.is_key_held(
                    SDLK_UP):
                player_pos[0] += speed_x
                player_pos[1] += speed_y
                self.player.velocity.vx = -speed_x
                self.player.velocity.vy = -speed_y
                self.player.facing.set("left_up")
                self.player.motiontype.set("walking")
            elif game_input.is_key_held(SDLK_LEFT) and game_input.is_key_held(
                    SDLK_DOWN):
                player_pos[0] += speed_x
                player_pos[1] -= speed_y
                self.player.velocity.vx = -speed_x
                self.player.velocity.vy = speed_y
                self.player.facing.set("left_down")
                self.player.motiontype.set("walking")
            elif game_input.is_key_held(SDLK_LEFT):
                player_pos[0] += speed_x
                self.player.velocity.vx = -speed_x
                self.player.facing.set("left")
                self.player.motiontype.set("walking")
            elif game_input.is_key_held(SDLK_RIGHT):
                player_pos[0] -= speed_x
                self.player.velocity.vx = speed_x
                self.player.facing.set("right")
                self.player.motiontype.set("walking")
            elif game_input.is_key_held(SDLK_UP):
                player_pos[1] += speed_y
                self.player.velocity.vy = -speed_y
                self.player.facing.set("up")
                self.player.motiontype.set("walking")
            elif game_input.is_key_held(SDLK_DOWN):
                player_pos[1] -= speed_y
                self.player.velocity.vy = speed_y
                self.player.facing.set("down")
                self.player.motiontype.set("walking")

            # elif game_input.was_key_pressed(SDLK_i):
            #    self.player.toggle_inventory()

            # Player Attack
            elif game_input.is_key_held(SDLK_SPACE):
                pass
                # motion_type = MotionType.CASTING

            # Nothing
            else:
                self.player.velocity.vx = 0
                self.player.velocity.vy = 0
                self.player.motiontype.set("standing")

            current_time = SDL_GetTicks()  # units.MS
            elapsed_time = current_time - last_update_time  # units.MS

            last_update_time = current_time

            self.world.process()

            # This loop lasts 1/60th of a second, or 1000/60th ms
            ms_per_frame = 1000 // FPS  # units.MS
            elapsed_time = SDL_GetTicks() - start_time  # units.MS
            if elapsed_time < ms_per_frame:
                SDL_Delay(ms_per_frame - elapsed_time)

    def clear(self):
        self.player.delete()
        self.npc.delete()

        self.world.remove_system(self.player_animation)
        self.world.remove_system(self.npc_animation)

        self.world.remove_system(self.player_movement)
        self.world.remove_system(self.npc_movement)
Пример #21
0
                    "you can also specify how many cities you want by passing an "
                    "optional number with the flag",
                    type=int, const=1, nargs='?')
parser.add_argument("--forcename", help="Force the specified name", action="store_true")
parser.add_argument("-v", "--verbose", help="increase output verbosity",
                    action="store_true")
parser.add_argument("-V", "--version", action='version', version="%(prog)s " + VERSION)


args = parser.parse_args()
is_verbose = args.verbose
is_random = args.random
is_overwrite = args.overwrite
is_random_name = not args.forcename

if args.command == "build":
    if args.object == "city" and is_random:
        print("Building " + str(args.random) + " city")
        city = City(args.name)
        city.build_random(overwrite=is_overwrite, verbose=is_verbose, random_name=is_random_name)
    if args.object == "npc" and is_random:
        print("Building " + str(args.random) + " npc")
        npc = Npc(args.name)
        npc.build_random(overwrite=is_overwrite, verbose=is_verbose)

elif args.command == "show":
    if args.object == "city":
        pprint.pprint(City.get_city_by_name(args.name))
    if args.object == "npc":
        pprint.pprint(Npc.get_npc_by_name(args.name))
Пример #22
0
               ((250, 450), (550, 550)), ((850, 450), (1200, 550)),
               ((250, 850), (550, 950)), ((850, 850), (1200, 950)),
               ((450, 950), (550, 1100)), ((850, 950), (950, 1100)))

gameDisplay = pygame.display.set_mode((DisplayWidth, DisplayHeight))
pygame.display.set_caption("stealthy")
clock = pygame.time.Clock()

walls = []
collisionMap = []
for coordinates in mapSegments:
    for i in createRectangleHitbox(coordinates):
        collisionMap.append(i)
    walls.append(createRectangleWall(coordinates, gameDisplay))
print collisionMap
npc = Npc(pygame.image.load("npcSprite.png"), 700, 700, 0, gameDisplay, 10, 5,
          collisionMap)
mob = Mob(pygame.image.load("playerSprite.png"), 1050, 350, 0, gameDisplay, 10,
          5, collisionMap)
world = [mob]
finished = False
counter = 0
xMove = 0
yMove = 0
rotation = 0
while not finished:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            finished = True
            break

        if event.type == pygame.KEYDOWN:
Пример #23
0
    def generate_sentences(self):
        md_writer.print_chapter_sentence(self.state.character_list() +
                                         " made camp.")

        energy = 0

        cs = self.state.get_characters()
        random.shuffle(cs)
        c1 = cs[0]
        c2 = cs[1]
        c3 = cs[2]

        sentences = []

        if random.random() < 0.05:
            md_writer.print_chapter_sentence(
                self.state.get_current_setting().mood_sentence())

        md_writer.print_chapter_sentence(c1.get_name() +
                                         ' searched for dry wood for a fire.')
        if c1.challenge('survival'):
            wood_found = random.choice([
                'dry ash kindling', ' birch twigs', 'large dried mushrooms',
                'grassy dried reeds', 'dessicated cow dung'
            ])
            location = random.choice([
                'in a nearby copse', 'inside a hollow log',
                'beneath a spindly pine', 'along the ' +
                self.state.get_current_setting().get_name() + ' floor'
            ])
            md_writer.print_chapter_sentence(c1.get_pronoun().title() +
                                             ' found ' + wood_found + ' ' +
                                             location + '.')
            fire_sound = random.choice(['roaring', 'crackling', 'hissing'])
            fire_type = random.choice(['campfire', 'blaze', 'bonfire'])
            md_writer.print_chapter_sentence(c2.get_name() + ' started a ' +
                                             fire_sound + ' ' + fire_type +
                                             '.')
            energy += 5
            md_writer.print_chapter_sentence('While ' + c1.get_name() +
                                             ' and ' + c2.get_name() +
                                             ' made a fire, ' + c3.get_name() +
                                             ' scouted around the campsite.')
        else:
            md_writer.print_chapter_sentence(
                c1.get_pronoun().title() +
                ' searched for an hour, but all the wood was wet, and ' +
                c1.get_pronoun() + ' gave up' + '.')
            md_writer.print_chapter_sentence('Meanwhile, ' + c3.get_name() +
                                             ' went scouting.')

        if random.random() < 0.05:
            md_writer.print_chapter_sentence(
                self.state.get_current_setting().mood_sentence())

        if c3.challenge('survival'):
            sense = random.choice(
                ['saw', 'heard', 'spotted', 'noticed', 'observed'])
            grouping = random.choice(['band', 'family', 'patrol'])
            race = random.choice(self.words.fantasy_races)
            critter = copy.copy(race)
            critter = pattern.en.pluralize(critter)
            md_writer.print_chapter_sentence(c3.get_pronoun().title() + ' ' +
                                             sense + ' a ' + grouping +
                                             ' of ' + critter + '.')
            characteristic = Npc(race).characteristic
            md_writer.print_chapter_sentence('One of the ' + critter +
                                             ' had ' +
                                             aOrAn.aOrAn(characteristic) +
                                             " " + characteristic + ".")
            watching_adj = random.choice(
                ['quietly', 'patiently', 'tirelessly'])
            md_writer.print_chapter_sentence(c3.get_pronoun().title() + ' ' +
                                             watching_adj + ' watched the ' +
                                             critter + '.')
            if (len(self.state.get_current_setting().get_known_props()) > 0):
                prop = random.choice(
                    self.state.get_current_setting().get_known_props())
                md_writer.print_chapter_sentence(
                    'The ' + critter + ' took the ' + prop + ' from the ' +
                    self.state.get_current_setting().get_name() + '.')
            md_writer.print_chapter_sentence(
                'But the ' + critter + ' soon left the ' +
                self.state.get_current_setting().get_name() + '.')
            energy += 5
        else:
            critter = random.choice(self.words.fantasy_races)
            self.state.add_enemy_patrol(critter)
            critter_description = c3.get_pronoun().title(
            ) + " thought " + c3.get_pronoun(
            ) + ' saw ' + pattern.en.pluralize(critter) + ' in the distance.'
            md_writer.print_chapter_sentence(critter_description)
            failure = random.choice([
                'fell in a hidden gorge', 'loudly broke a branch',
                'accidentally knocked over a boulder', 'fell asleep',
                'walked into a tree'
            ])
            md_writer.print_chapter_sentence("Suddenly, " + c3.get_pronoun() +
                                             " " + failure + '.')

        night_description = random.choice(
            ['inky', 'black', 'moonlit', 'silent', 'calm'])
        md_writer.print_chapter_sentence(night_description.title() +
                                         ' darkness fell over the camp.')

        c = random.choice(self.state.get_characters())
        if random.random() < 0.5:
            md_writer.print_chapter_sentence(c.get_name() + ' told a story.')
        else:
            md_writer.print_chapter_sentence(c.get_name() +
                                             ' sang a song from ' +
                                             c.get_possessive_pronoun() +
                                             ' childhood.')

        sleep_opening = random.choice([
            'As the fire crackled', 'While the wind gusted',
            'As gentle rain fell', 'As the leaves rustled',
            'As howls were heard in the distance',
            'As the moon shone overhead', 'Although sadness washed over them'
        ])
        md_writer.print_chapter_sentence(sleep_opening + ',' +
                                         ' they all fell asleep.')

        c = random.choice(self.state.get_characters())
        md_writer.print_chapter_sentence(
            c.get_name() + ' dreamt of a ' + self.words.get_fantasy_place() +
            ', ' + self.words.get_fantasy_occupation() + ', and ' +
            self.words.get_living_thing_adj() + ' ' +
            pattern.en.pluralize(self.words.get_living_thing()) + '.')
        energy += 5

        self.state.add_energy(energy)
Пример #24
0
 def __init__(self, x, y, message, filename, name=''):
     Npc.__init__(self, x, y, message, filename, name)
     self.home = (x,y)
     self.roam = 5
     self.type = 'citizen'
Пример #25
0
 def __init__(self, x, y, name, filename):
     Npc.__init__(self, x, y, name, filename)
Пример #26
0
 def __init__(self, x, y, name, filename):
     Npc.__init__(self, x, y, name, filename)
Пример #27
0
    def read(self):
        if self.file is None:
            self.open_file()

        # kills the loop if we've reached the end of the file
        if self.position > self.length:
            return False

        npc = Npc()
        npc.id = self.position

        # name is dynamic, so we need to find the size each time
        name_size = utils.decode_number(self.file.read(1))
        npc.name = self.file.read(name_size).decode("utf-8")

        # eof means end of file. It should be the last "record"
        # and we can safely ignore it.
        if npc.name == "eof":
            return False

        buf = self.file.read(self.data_size)
        npc.graphic = utils.decode_number([buf[0], buf[1]])
        npc.boss = utils.decode_number([buf[3], buf[4]])
        npc.child = utils.decode_number([buf[5], buf[6]])
        npc.type = Type(utils.decode_number([buf[7], buf[8]]))
        npc.vendor_id = utils.decode_number([buf[9], buf[10]])
        npc.hp = utils.decode_number([buf[11], buf[12], buf[13]])
        npc.min_damage = utils.decode_number([buf[16], buf[17]])
        npc.max_damage = utils.decode_number([buf[18], buf[19]])
        npc.accuracy = utils.decode_number([buf[20], buf[21]])
        npc.evade = utils.decode_number([buf[22], buf[23]])
        npc.armor = utils.decode_number([buf[24], buf[25]])
        npc.exp = utils.decode_number([buf[36], buf[37]])

        self._npc = npc
        self.position += 1
        return True