Esempio n. 1
0
def main():
    pygame.init()
    screen = display.set_mode(DISPLAY, FLAGS, DEPTH)
    display.set_caption("Use arrows to move!")
    timer = time.Clock()

    up = down = left = right = space = False
    bg = Surface((BLOCK_SIZE, BLOCK_SIZE))
    bg.convert()
    bg.fill(Color("#000000"))

    current_level = Level(LEVEL_W, LEVEL_H)
    player = Player(100, 100)
    entities = pygame.sprite.Group()
    entities.add(player)

    while True:
        timer.tick(FPS)
        for e in pygame.event.get():
            if e.type == QUIT: raise SystemExit, "QUIT"
            if e.type == KEYDOWN and e.key == K_ESCAPE:
                raise SystemExit, "ESCAPE"
            if e.type == KEYDOWN and e.key == K_UP:
                up = True
            if e.type == KEYDOWN and e.key == K_DOWN:
                down = True
            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 == KEYDOWN and e.key == K_SPACE:
                space = True

            if e.type == KEYUP and e.key == K_UP:
                up = False
            if e.type == KEYUP and e.key == K_DOWN:
                down = False
            if e.type == KEYUP and e.key == K_LEFT:
                left = False
            if e.type == KEYUP and e.key == K_RIGHT:
                right = False
            if e.type == KEYUP and e.key == K_SPACE:
                space = False

            if e.type == MOUSEBUTTONUP:
                pos = pygame.mouse.get_pos()
                print current_level._identify_img(pos[0]/BLOCK_SIZE, pos[1]/BLOCK_SIZE)

        # draw background
        for y in range(LEVEL_H):
            for x in range(LEVEL_W):
                screen.blit(bg, (x * BLOCK_SIZE, y * BLOCK_SIZE))

        # update player, draw everything else
        player.update(up, down, left, right, space, current_level)
        player.draw(screen)
        #entities.draw(screen)
        current_level.draw(screen)

        pygame.display.flip()
Esempio n. 2
0
    def __init__(self):
        self.map = Map(START_LEVEL)
        # Enforce that a path does exist in the map
        while self.map.findPath() == None:
            self.map = Map(START_LEVEL)
        self.player = Player()
        self.inventory = Inventory()
        self.enemy_factory = EnemyFactory()
        self.user = User()

        self.invuln_turns = 0

        self.swap_weapon_to = None

        self.current_enemy = None
        self.level = START_LEVEL
        self.danger = 5
        self.hide_danger = 5
        self.escape_chance = 3
        self.items_dropped = 0  # a counter so we make sure they get shield, sword and bow chances first
        self.steps_left = MAX_STEPS
        self.escapes_remaining = NUM_ESCAPES
        self.encounter_sdorf = False

        self.dangers = []
        self.escape_chances = []
        self.hide_dangers = []

        self.seerdata = SeerData()
        self.init_dangers()
Esempio n. 3
0
    def update_poses(self):
        if self.pose_input_frame is None:
            return

        datum = self.pose_estimator.grab_pose(self.pose_input_frame)
        self.pose_input_frame = None

        num_poses = len(
            datum.poseKeypoints) if datum.poseKeypoints.ndim > 0 else 0
        self.logger.debug("Number of poses detected: %d", num_poses)
        if num_poses == 0:
            if len(self.players) > 0:
                self.reset_game()
            return

        new_players = set()
        for pose in datum.poseKeypoints:
            player = self.find_nearest_player(pose)
            if not player:
                player = Player(self.space)

            player.update_pose(pose, self.dt)
            new_players.add(player)

        old_players = self.players - new_players
        self.logger.debug("Removing " + str(len(old_players)) + " players")
        for old_player in old_players:
            old_player.destroy()

        self.logger.debug("Keeping/adding " + str(len(new_players)))
        self.players = new_players

        self.output_frame = convert_array_to_pygame_layout(datum.cvOutputData)
Esempio n. 4
0
def players():
    log("SCRIPT", "Booting core server functionality")
    a = Archive()
    handler.load_handlers()
    importer.process_xml()
    log("SCRIPT", "Finished loading core functionality")

    log("SCRIPT", "Retreiving player information from database")
    players = a.list()
    log("SCRIPT", "Loaded %d player%s from database" % (len(players), '' if len(players) == 1 else 's'))
    print

    i = 0
    names = players.keys()
    names.sort()
    for p in names:
        i += 1
        print '%d: %s' % (i, p)
    print

    n = raw_input('Load player index (blank to cancel): ')
    name = None
    try:
        n = int(n)
        if n < 1 or n > len(names):
            print 'Cancelled.'
            sys.exit(0)
        name = names[n - 1]
    except (ValueError, IndexError):
        sys.exit(1)

    player = Player()
    if not a.load(name, player):
        choice = raw_input('Player could not be loaded properly.  Delete? (Y/N): ')
        if choice.upper() == 'Y':
            a.delete(name)
        sys.exit(0)

    print
    print player.name
    print player.gender, player.race
    for stat, value in player.stats.items():
        print ' %s: %d' % (stat, value)
    print
    action = raw_input('Action ([p]assword, [d]elete), [c]ancel): ')
    if action == '':
        sys.exit(0)
    elif 'password'.startswith(action.lower()):
        player.password = encrypt_password(raw_input('New password: '******'Password written.'
    elif 'delete'.startswith(action.lower()):
        confirm = raw_input('Really delete? (Y/N): ')
        if confirm.upper() == 'Y':
            a.delete(name)
            print 'Deletion complete.'
        else:
            print 'Deletion cancelled.'
    else:
        print 'Cancelled.'
Esempio n. 5
0
    def setup(self):
        self.player_list = arcade.SpriteList()
        self.player_bullet_list = arcade.SpriteList()
        self.enemy_list = Enemies.setup(ENEMY_COUNT)
        self.enemy_bullet_list = arcade.SpriteList()

        self.player = Player()
        self.player_list.append(self.player)
Esempio n. 6
0
def two_players():
    drop_all()
    Card(_id='1', name='Bolt', cost=Resources(a=1), effect_id='one_damage').save()
    Card(_id='2', name='Mana', cost=Resources(), effect_id='add_a').save()
    Card(_id='3', name='Counter', cost=Resources(), effect_id='counter').save()
    Deck(_id=1, card_ids=['1', '2'] * 10).save()
    Deck(_id=2, card_ids=['3'] * 20).save()
    Player(_id=1).save()
    Player(_id=2).save()
Esempio n. 7
0
    def __init__(self, **kwargs):
        """
        All arguments are keyword-arguments. All have default values (in
        parenthesis), even if not specified.

        :param azerty: True if keyboard entry is azerty, False for qwerty
            (True).
        :param grid_width: Grid width in tiles (30).
        :param grid_height: Grid height in tiles (20).
        :param screen_mode: Screen size (960, 640).
        :param map_file: .map file describing the map ('level.map').
        :param map_pos: coordinates of the top left corner of the map,
            relative to the top left corner of the screen (128, 64).
        :param play_sound: True to start playing sound, False to start with
            sound muted (False).
        :param base_delay: Minimal delay to wait between each asynchronous
            call of the same function. Useless to give < 1e-4. This should
            not be changed since it affects a lot the way the game behave and
            its performances (1e-3).
        """
        self.azerty = kwargs.get('azerty', True)
        if self.azerty:
            self.key_direction_mapping[pygame.locals.K_z] = 0
            self.key_direction_mapping[pygame.locals.K_q] = 2
        else:
            self.key_direction_mapping[pygame.locals.K_w] = 0
            self.key_direction_mapping[pygame.locals.K_a] = 2

        self.grid_width = kwargs.get('grid_width', 30)
        self.grid_height = kwargs.get('grid_height', 20)

        self.screen = pygame.display.set_mode(kwargs.get('screen_mode',
                                                         (960, 640)))
        self.grid = Grid(kwargs.get('map_file', "level.map"),
                         self.screen,
                         (self.grid_width, self.grid_height),
                         kwargs.get('map_pos', (32*4, 32*2)))
        self.player = Player(self.screen, self.grid, 'male')
        # Create coins
        for p in [(8, 10), (9, 11), (10, 10), (8, 12), (10, 12)]:
            coin = Coin(tuple(numpy.multiply(self.grid.tilesize, 0.75)), 10)
            coin.load_sprites('res/coin.png', 1, 1)
            coin.set_pos(self.grid, p)
            self.grid.add_entity(coin)
        # Array storing arrow key inputs
        self.raw_direction = [0, 0, 0, 0]

        # init button and its hitbox variable, assigned in toggle_sound
        self.sound_button = self.sound_button_box = None
        self.running = False

        self.sound_played = not kwargs.get('play_sound', False)
        # Useless  to go < 1e-4, this controls game tick speed
        # (roughly, not the same as fps)
        # Think of it as "how fast will the game compute things"
        self.base_delay = kwargs.get('base_delay', 1e-3)
Esempio n. 8
0
    def __init__(self, connection):
        asynchat.async_chat.__init__(self, connection)

        # Holds all pending text (awaiting a newline from client).
        self.buffer = ''

        self.set_terminator('\n')

        # Retains the player class tied to this socket.
        self.parent = Player(self)
Esempio n. 9
0
def register_player(number, name, role, teamname, secret_code):
    ''' Stores player in datastore '''
    ''' Process name'''
    name_p = re.sub(r'[^a-zA-z]', '', name)

    ''' Process role'''
    role_p = role.strip().lower()
    try:
        role_p in ROLES
    except:
        raise RegistrationError("invalid role")  # Exception handled by caller

    ''' Process teamname'''
    try:
        team_key = ndb.Key('Team', teamname)
        team = team_key.get()
        if role_p == "sniper":
            if team.sniper:
                team.sniper = number
            else:
                raise RegistrationError("role on your team is already taken.")
        elif role_p == "medic":
            if team.medic:
                team.medic = number
            else:
                raise RegistrationError("role on your team is already taken.")
        else:
            if team.demo:
                team.demo = number
            else:
                raise RegistrationError("role on your team is already taken.")
    except:
        raise RegistrationError("invalid teamname")

    ''' Generate secrete code '''
    if len(secret_code) > 4:
        raise RegistrationError("secret code too long")
    else:
        try:
            secret_code_p = int(secret_code)
            secret_code_query = Player.query()
            used_numbers = secret_code_query.fetch(projection=["secret_code"])
            for number in used_numbers:
                if secret_code_p == number:
                    raise RegistrationError("secret code already taken. \
                                            Please try another one.")
        except:
            raise RegistrationError("secret code must be an integer")

    '''Make and save player object in datastore'''
    player = Player(state="alive", role=role_p, secret_code=secret_code_p)
    player.key = ndb.Key('Player', number, paret=ndb.Key('Team', teamname))
    player.put()
    return name_p, role_p, secret_code, teamname
Esempio n. 10
0
 def level_init(self):
     self.player = Player(20, random.randint(20, game_width - 20),
                          random.randint(20, game_height - 20))
     self.player.game = self.game
     self.enemies = [
         Sphere(random.randint(2, 40), random.randint(40, game_width - 40),
                random.randint(40, game_height - 40)) for x in range(200)
     ]  # spawn random enemies
     for enemy in self.enemies:
         enemy.speed(random.randint(-1, 1), random.randint(
             -1, 1))  # set random speed to reduce impasse
Esempio n. 11
0
 def __init__(self):
     States.__init__(self)
     self.next = 'gameover'
     self.player = Player(self)
     self.platforms = pg.sprite.Group()
     self.all_sprites = pg.sprite.Group()
     self.all_sprites.add(self.player)
     self.PLATFORM_LIST = [Platform(0, HEIGHT - 40, 150, 10), Platform(950, 850, 150, 10), Platform(950, 650, 150, 10), 
              Platform(950, 450, 150, 10), Platform(950, 250, 150, 10), Platform(950, 50, 150, 10)]
     self.create_plat()
     self.score = 0
     self.load_data()
Esempio n. 12
0
 def cleanup(self):
     print('cleaning up Game Level One state stuff')
     States.__init__(self)
     self.next = 'gameover'
     self.player = Player(self)
     self.platforms = pg.sprite.Group()
     self.all_sprites = pg.sprite.Group()
     self.all_sprites.add(self.player)
     self.PLATFORM_LIST = [Platform(0, HEIGHT - 40, 150, 10), Platform(950, 850, 150, 10), Platform(950, 650, 150, 10), 
              Platform(950, 450, 150, 10), Platform(950, 250, 150, 10), Platform(950, 50, 150, 10)]
     self.create_plat()
     self.score = 0
     self.load_data()
Esempio n. 13
0
    def level_init(self):
        self.player = Player(30, random.randint(30, game_width - 30),
                             random.randint(30, game_height - 30))
        self.player.game = self.game

        self.enemies = [
            Sphere(random.randint(2, 20), random.randint(20, game_width - 20),
                   random.randint(20, game_height - 20)) for x in range(100)
        ]
        self.repulsor = Repulsor(30, random.randint(30, game_width - 30),
                                 random.randint(30, game_height - 30))
        for enemy in self.enemies + [self.repulsor]:
            enemy.speed(random.randint(-1, 1) / 1, random.randint(-1, 1) / 1)
Esempio n. 14
0
    def read_player(self, name, create_if_not_found=True):
        cursor = self._exec_sql(
            'SELECT name,rating FROM players WHERE name LIKE ?', (name, ))
        row = cursor.fetchone()
        if row is not None:
            dump('Player %s exists with rating %s' % (name, row[1]))
            return Player(row[0], rating=row[1])

        if not create_if_not_found:
            return None

        dump('Player %s does not exist, creating one' % name)
        return Player(name)
Esempio n. 15
0
    def __init__(self):
        self.middle_rects = self.create_middle_rects(5, 15)

        # Initialize entities
        self.player = Player(20, 20, 100, PLAYER_COLOR)
        self.enemy = Enemy(SCREEN_WIDTH - 20 - 20, 20, 100, ENEMY_COLOR)
        self.ball = Ball(12, 600)

        # Initialize fonts
        self.score_font = pygame.font.Font("8bit.ttf", SCORE_SIZE)
        self.player_score_label = self.score_font.render(
            str(self.player.score), True, SCORE_COLOR)
        self.enemy_score_label = self.score_font.render(
            str(self.enemy.score), True, SCORE_COLOR)
Esempio n. 16
0
class ClientSocket(asynchat.async_chat):
    def __init__(self, connection):
        asynchat.async_chat.__init__(self, connection)

        # Holds all pending text (awaiting a newline from client).
        self.buffer = ''

        self.set_terminator('\n')

        # Retains the player class tied to this socket.
        self.parent = Player(self)

    def collect_incoming_data(self, data):
        for char in data:
            if char == '\b' and len(self.buffer) > 0:
                self.buffer = self.buffer[:-1]
            elif char == '\b' or char == '\r':
                pass
            elif char in string.printable:
                self.buffer += char
                if self.parent.state == STATE_PASSWORD:
                    self.parent.send('\b \b')

    def found_terminator(self):
        data = self.buffer
        self.buffer = ''
        command.accept_command(self.parent, data)

    def handle_close(self):
        # Shunt output to parent (avoids recursion in simultaneous logouts)
        self.parent.send = lambda s: None

        if self.parent.location:
            libsigma.report(libsigma.ROOM, "$actor has left the game.",
                            self.parent)
            self.parent.location.characters.remove(self.parent)

        w = World()
        if self.parent in w.players:
            a = Archive()
            a.save(self.parent)
            w.players.remove(self.parent)

        log("NETWORK", "Client at %s closed connection" % self.addr[0])
        self.parent.socket = None
        self.close()

    def handle_accept(self):
        pass
Esempio n. 17
0
 def __init__(self, width=1000, height=600):
     pygame.init()
     # set the window dimensions
     self.window_width = width
     self.window_height = height
     # create the screen
     self.screen = pygame.display.set_mode((self.window_width, self.window_height))
     pygame.display.set_caption("Dun-Gen")
     # noinspection PyArgumentList
     self.background = pygame.Surface((self.window_width, self.window_height))
     # generate the map
     self.map = TheMap(LAND_WIDTH, LAND_HEIGHT)
     # probability of enemy appearing
     self.enemy_prob = 0
     # creates the clock
     self.clock = pygame.time.Clock()
     self.time = pygame.time.get_ticks()
     # init player
     self.player = Player()
     self.player.rect.left = self.map.player_start_loc[0]
     self.player.rect.top = self.map.player_start_loc[1]
     self.player_sprites = pygame.sprite.RenderPlain(self.player)
     # create the camera
     self.camera = Camera(complex_camera, self.map.width << 5, self.map.height << 5, self.window_width,
                          self.window_height)
     # debugging
     self.debug_mode = False
     self.god_mode = False
     # used for demo
     self.seen_first_key = False
     self.seen_first_stairs = False
Esempio n. 18
0
def on_connect(connection):
    player = Player(connection)
    instance.players.append(player)

    connection.player = player

    logging.info('{} connected', connection.address[0])
Esempio n. 19
0
    def __init__(self):
        self.map = Map(START_LEVEL)
        # Enforce that a path does exist in the map
        while self.map.findPath() == None:
            self.map = Map(START_LEVEL)
        self.player = Player()
        self.inventory = Inventory()
        self.enemy_factory = EnemyFactory()
        self.user = User()

        self.invuln_turns = 0

        self.swap_weapon_to = None

        self.current_enemy = None
        self.level = START_LEVEL
        self.danger = 5
        self.hide_danger = 5
        self.escape_chance = 3
        self.items_dropped = 0 # a counter so we make sure they get shield, sword and bow chances first
        self.steps_left = MAX_STEPS
        self.escapes_remaining = NUM_ESCAPES
        self.encounter_sdorf = False

        self.dangers = []
        self.escape_chances = []
        self.hide_dangers = []

        self.seerdata = SeerData()
        self.init_dangers()
Esempio n. 20
0
class ClientSocket(asynchat.async_chat):
    def __init__(self, connection):
        asynchat.async_chat.__init__(self, connection)

        # Holds all pending text (awaiting a newline from client).
        self.buffer = ''

        self.set_terminator('\n')

        # Retains the player class tied to this socket.
        self.parent = Player(self)

    def collect_incoming_data(self, data):
        for char in data:
            if char == '\b' and len(self.buffer) > 0:
                self.buffer = self.buffer[:-1]
            elif char == '\b' or char == '\r': pass
            elif char in string.printable:
                self.buffer += char
                if self.parent.state == STATE_PASSWORD:
                    self.parent.send('\b \b')

    def found_terminator(self):
        data = self.buffer
        self.buffer = ''
        command.accept_command(self.parent, data)

    def handle_close(self):
        # Shunt output to parent (avoids recursion in simultaneous logouts)
        self.parent.send = lambda s: None

        if self.parent.location:
            libsigma.report(libsigma.ROOM, "$actor has left the game.", self.parent)
            self.parent.location.characters.remove(self.parent)

        w = World()
        if self.parent in w.players:
            a = Archive()
            a.save(self.parent)
            w.players.remove(self.parent)

        log("NETWORK", "Client at %s closed connection" % self.addr[0])
        self.parent.socket = None
        self.close()

    def handle_accept(self):
        pass
Esempio n. 21
0
def load_jsons_to_memory(box_score_directory, end_date):
    players = []
    player_ids = []
    games = []
    for fn in os.listdir(box_score_directory):
        datestring = fn.split('-')[0]
        year = int(datestring[0:4])
        month = int(datestring[4:6])
        day = int(datestring[6:8])
        if datetime.date(year, month, day) <= end_date:
            with open(os.path.join(box_score_directory, fn)) as f:
                t = json.load(f)
                names = [
                    t['resultSets'][i]['name']
                    for i in range(len(t['resultSets']))
                ]
                for player_data in t['resultSets'][names.index(
                        'PlayerStats')]['rowSet']:
                    # can optimize here by keeping sorted list of player_ids but too lazy
                    try:
                        ind = player_ids.index(player_data[4])
                        players[ind].add_game_from_boxscore(
                            player_data, 'normal')
                    # player not in player_ids
                    except ValueError:
                        player_ids.append(player_data[4])
                        temp_player = Player()
                        temp_player.add_game_from_boxscore(
                            player_data, 'normal')
                        players.append(temp_player)
                # add advanced stats. would roll it in with code above but not sure if order is guaranteed
                # to be the same for advanced stats as it is for normal stats
                for player_data in t['resultSets'][names.index(
                        'sqlPlayersAdvanced')]['rowSet']:
                    # can optimize here by keeping sorted list of player_ids but too lazy
                    try:
                        ind = player_ids.index(player_data[4])
                        players[ind].add_game_from_boxscore(
                            player_data, 'advanced')
                    # player not in player_ids
                    except ValueError:
                        player_ids.append(player_data[4])
                        temp_player = Player()
                        temp_player.add_game_from_boxscore(
                            player_data, 'advanced')
                        players.append(temp_player)
                game_summary = t['resultSets'][names.index(
                    'GameSummary')]['rowSet'][0]
                temp_game = Game()
                temp_game.add_data_from_boxscore(
                    t['resultSets'][names.index('LineScore')]['rowSet'],
                    game_summary[6], game_summary[7], 'normal')
                temp_game.add_data_from_boxscore(
                    t['resultSets'][names.index('sqlTeamsAdvanced')]['rowSet'],
                    game_summary[6], game_summary[7], 'advanced')
                games.append(temp_game)
    return players, games
Esempio n. 22
0
    def __init__(self, connection):
        asynchat.async_chat.__init__(self, connection)

        # Holds all pending text (awaiting a newline from client).
        self.buffer = ''

        self.set_terminator('\n')

        # Retains the player class tied to this socket.
        self.parent = Player(self)
Esempio n. 23
0
    def __init__(self):
        # init gui
        self.frame = Frame()
        self.frame.pack()
        self.canvas = Canvas(self.frame,
                             width=WINDOW_WIDTH,
                             height=WINDOW_HEIGHT,
                             bg="black")
        self.canvas.pack()
        self.is_game_over = False
        self.should_quit = False
        self.hud = HUD(0, 0, 0)

        # init entities
        self.creatures = []
        self.player = Player(
            Location(randint(1, TILES_X - 2), randint(1, TILES_Y - 2)))
        self.players_turn = True
        self.hud.update(self.player)

        # initialize the first level
        self.levels = []
        self.levels_discovered = 0
        self.init_level(TILES_X,
                        TILES_Y,
                        SQUARE_SIZE,
                        upstairs=False,
                        fountains=FOUNTAINS_PER_LEVEL)
        self.make_adjacent_tiles_visible(self.player.location)

        # bind keys
        self.canvas.bind('w', self.move_player_north)
        self.canvas.bind('s', self.move_player_south)
        self.canvas.bind('a', self.move_player_west)
        self.canvas.bind('d', self.move_player_east)
        self.canvas.bind('e', self.interact)
        self.canvas.bind('x', self.attack)
        self.canvas.bind('z', self.sleep)
        self.canvas.bind('k', self.kill_player)
        self.canvas.bind('<Escape>', self.quit)
        self.canvas.focus_set()
Esempio n. 24
0
    def gamesetup(self):
        # Setting up the Event Handler.
        self.events = EventHandler()
        self.events.calls["keydown"] = self.key_down
        self.events.calls["keyup"] = self.key_up
        self.events.calls["mouseover"] = self.mouse_over
        self.events.eventsetup()

        # Setting up the Menu controller.
        self.menus = Menus(size=self.size)
        self.menus.menusetup()

        # Setting up the NPCs.
        self.npcs = NPCController()
        self.npcs.controllersetup()

        # Setting up the Player.
        self.player = Player()
        self.player.playersetup(Window.size)
        self.player.place(Window.center[0], Window.center[1])

        # Setting up the Dialogue controller.
        self.dialogue = Dialogue()
        self.dialogue.dialoguesetup()

        # Setting up the world.
        self.world = World()
        self.world.worldcenter = self.center
        self.world.setupworld((768 * 3, 608 * 3))

        # Adding everything to the Widget stack
        self.add_widget(self.events)
        self.world.add_npcs(self.npcs.npcgroup)
        self.world.add_widget(self.player)
        self.add_widget(self.world)
        self.add_widget(self.menus)
        self.add_widget(self.dialogue)

        # Centering Screen on the player
        self.center_screen(0.2)
Esempio n. 25
0
def load_character():
    files = os.listdir('./PlayerSaves')
    print("\nSaved Characters:")
    for counter, file in enumerate(files):
        print(f'  {counter+1}: {file}')
    character_number = option_selector(len(files))
    with open(f'PlayerSaves/{files[character_number-1]}') as f:
        PlayerData = json.load(f)
    player = Player(PlayerData["max_hp"], PlayerData["current_hp"],
                    PlayerData["coins"], PlayerData["xp"],
                    PlayerData["attack_damage"], PlayerData["defense_ablilty"])
    del files, character_number, PlayerData
    return ["menu_request:main_menu", player]
Esempio n. 26
0
def create_player():
    form = PlayerForm()
    if request.method == "POST":
        if not form.validate():
            return render_template("create_player.html", form=form)
        else:
            id = form.id.data
            balance = form.balance.data
            passwrd = form.passwrd.data
            player = Player(player_id=id, balance=balance, passwrd=passwrd)
            database.createPlayer(player)
            return redirect(url_for("players"))
    return render_template("create_player.html", form=form)
Esempio n. 27
0
    def __init__(self, screen, global_config, GS=None):
        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        self.global_config = global_config
        self.GS = GameState()

        self.GS.player = Player()
        self.GS.Camera = Camera(self.GS.player)
        self.GS.entities.add(self.GS.player)

        self.GS.GameMap = None
        self.first_start = True

        self.soundtrack = pygame.mixer.Sound(
            os.path.join(ASSETS_DIRECTORY, SOUNDS_DIRECTORY, "soundtrack.wav"))
Esempio n. 28
0
    def __init__(self, screen, global_config, GS=None):
        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), flags=pygame.RESIZABLE)
        self.global_config = global_config
        self.GS = GameState()

        self.GS.player = Player()
        self.GS.Camera = Camera(self.GS.player)
        self.GS.entities.add(self.GS.player)

        self.goal = (14*16, 18*16)
        self.SPAWN_ENEMY = pygame.USEREVENT + 1
        pygame.time.set_timer(self.SPAWN_ENEMY, 750)

        self.GS.GameMap = GameMap("treasure.json")
        self.first_start = True

        self.soundtrack = pygame.mixer.Sound(os.path.join(ASSETS_DIRECTORY, SOUNDS_DIRECTORY, "soundtrack.wav"))
Esempio n. 29
0
  def __init__(self):
    print "______________________"
    print "Class Main"

    base.disableMouse()
    base.camLens.setNear(0.0001)

    # Setup application
    self.keys()
    self.txt = self.info((-1.32, 0.96), title)

    # Initialize classes
    self.grid = None
    self.free_look_camera = None
    self.avatars = None
    self.camera_type = "free_look"
    self.trees = []

    # Initialize World
    self.root = NodePath("rootMain")
    self.root.reparentTo(base.render)

    # Initialize Picker
    self.picker = picker.Picker(self)

    # Initialize Terrain
    self.terrain = terrain.Terrain(self, 65, 2.0, 20.0, 'advanced', False)

    # Initialize Player
    self.player = Player(Filename("avatars/ralph/ralph.egg.pz"))
    self.player.reparentTo(base.render)
    self.player.setScale(0.05)


    # Initialize Cameras
    self.free_look_camera = FreeLookCamera()
    self.first_person_camera = FirstPersonCamera()

    # Initialize Lights
    self.lights = lighting.Lighting(self)

    # Activate Free Look
    self.free_look_camera.activate()

    return
Esempio n. 30
0
 def load(self, file):
     """
     Carrega o arquivo json com as configurações e níveis
     """
     with open(file) as f:
         data = json.load(f)
     sounds = Sound(data["sounds"])
     sprites = {
         k:(AnimatedSpritesheet(*v) if isinstance(v[2], dict) else Spritesheet(*v))
         for k, v in data["sprites"].items()
     }
     levels = iter(Level(level, sprites) for level in data["levels"])
     self.state = State(levels)
     surface = int(self.resolution[0] / 1.5), int(self.resolution[1] / 1.5)
     camera = Camera(surface, sprites)
     interface = Interface(surface, data["music"]["victory"])
     player = Player(sounds)
     return player, camera, interface
Esempio n. 31
0
    def gamesetup(self):
        # Setting up the Event Handler.
        self.events = EventHandler()
        self.events.calls["keydown"] = self.key_down
        self.events.calls["keyup"] = self.key_up
        self.events.calls["mouseover"] = self.mouse_over
        self.events.eventsetup()

        # Setting up the Menu controller.
        self.menus = Menus(size=self.size)
        self.menus.menusetup()

        # Setting up the NPCs.
        self.npcs = NPCController()
        self.npcs.controllersetup()

        # Setting up the Player.
        self.player = Player()
        self.player.playersetup(Window.size)
        self.player.place(Window.center[0], Window.center[1])

        # Setting up the Dialogue controller.
        self.dialogue = Dialogue()
        self.dialogue.dialoguesetup()

        # Setting up the world.
        self.world = World()
        self.world.worldcenter = self.center
        self.world.setupworld((768*3, 608*3))

        # Adding everything to the Widget stack
        self.add_widget(self.events)
        self.world.add_npcs(self.npcs.npcgroup)
        self.world.add_widget(self.player)
        self.add_widget(self.world)
        self.add_widget(self.menus)
        self.add_widget(self.dialogue)

        # Centering Screen on the player
        self.center_screen(0.2)
Esempio n. 32
0
    def get_by_identifier(identifier):
        """
        Get player data by id (identifier).

        :param identifier: int
        :return: Player
        """
        data = sm.get(PlayersRepository._get_players_endpoint(identifier),
                      PlayersRepository.INCLUDE,
                      paginated=False)

        player = Player(identifier)
        try:
            player.first_name = data['firstname']
            player.last_name = data['lastname']
            player.full_name = data['fullname']
            player.nationality = data['nationality']
            player.team_name = data['team']['data']['name']
            player.position = data['position']['data']['name']
        except KeyError:
            logging.exception("Player data doesn't contain expected fields")

        return player
Esempio n. 33
0
	def __init__(self, name, value, goals, yellow, red, status, team, clean_sheets, games, score):
		Player.__init__(self, name, value, goals, assists, yellow, red, status, team, games, score)		
Esempio n. 34
0
MAP_WIDTH = 0
MAP_HEIGHT = 0
VIEW_SIZE = 16

STATES = ['MOVEMENT', 'OPENING', 'SHOOTING']
STATE_MOVEMENT = 0
STATE_OPENING = 1
STATE_SHOOTING = 2
STATE_TARGETTING = 3
state = STATE_MOVEMENT

testmap = data

pygame.init()

p = Player(3,3,'John')
m = Map(testmap)
cursor = None
MAP_WIDTH = m.w
MAP_HEIGHT = m.h

stage = Stage(m, TILE_WIDTH, TILE_HEIGHT)
stage.add_child(p)

fontsheet = Fontsheet(os.path.join("tiles", "consolas_unicode_16x16.png"), TILE_WIDTH, TILE_HEIGHT)

if __name__ == '__main__':
    screen = pygame.display.set_mode((400,400))
    screen.fill(pygame.Color(255, 255, 255, 0))
    area = get_area_around_entity(p, VIEW_SIZE, VIEW_SIZE, MAP_WIDTH, MAP_HEIGHT)
    stage.render(area, screen, fontsheet)
Esempio n. 35
0
class DunGen:
    """
    This is the main class that initializes everything.
    """

    def __init__(self, width=1000, height=600):
        pygame.init()
        # set the window dimensions
        self.window_width = width
        self.window_height = height
        # create the screen
        self.screen = pygame.display.set_mode((self.window_width, self.window_height))
        pygame.display.set_caption("Dun-Gen")
        # noinspection PyArgumentList
        self.background = pygame.Surface((self.window_width, self.window_height))
        # generate the map
        self.map = TheMap(LAND_WIDTH, LAND_HEIGHT)
        # probability of enemy appearing
        self.enemy_prob = 0
        # creates the clock
        self.clock = pygame.time.Clock()
        self.time = pygame.time.get_ticks()
        # init player
        self.player = Player()
        self.player.rect.left = self.map.player_start_loc[0]
        self.player.rect.top = self.map.player_start_loc[1]
        self.player_sprites = pygame.sprite.RenderPlain(self.player)
        # create the camera
        self.camera = Camera(complex_camera, self.map.width << 5, self.map.height << 5, self.window_width,
                             self.window_height)
        # debugging
        self.debug_mode = False
        self.god_mode = False
        # used for demo
        self.seen_first_key = False
        self.seen_first_stairs = False

    def main_loop(self):
        """
        This initializes everything and starts the main-loop.
        """
        # allows key-strokes to repeat if they're held down
        pygame.key.set_repeat(10, 30)
        # clear the background: black
        self.background = self.background.convert()
        self.background.fill((0, 0, 0))
        while 1:
            self.clock.tick(60)  # displays 60 max-fps
            self.controller()
            self.view()

    def controller(self):
        """
        Handles all of the events-functionality: keys-pressed, etc.
        """
        now = pygame.time.get_ticks()
        for e in pygame.event.get():
            if e.type == KEYDOWN:
                if (e.key == K_RIGHT) or (e.key == K_LEFT) or (e.key == K_UP) or (e.key == K_DOWN):
                    self.player.move(self.map.landscape, self.map.map_objects["other"], e.key)
                elif e.key == K_SPACE:
                    # determine if keys are around; remove the key if found
                    if pygame.sprite.spritecollide(self.player, self.map.map_objects["keys"], True):
                        self.seen_first_key = True
                    # determine if all keys have been collected and player's at a stairwell
                    if len(self.map.map_objects["keys"]) == 0 and pygame.sprite.spritecollide(self.player,
                                                                                              self.map.map_objects[
                                                                                                  "stairs"], False):
                        self.seen_first_stairs = True
                        self.load_new_map()
                elif e.key == K_d and now - self.time > 250:
                    # enter debug-mode
                    self.debug_mode = not self.debug_mode
                    if self.god_mode:
                        self.god_mode = not self.god_mode
                    self.time = now
                elif self.debug_mode and e.key == K_g and now - self.time > 250:
                    # enter god-mode
                    self.god_mode = not self.god_mode
                    self.time = now
                elif e.key == K_ESCAPE:
                    quit()
                # debug mode doesn't allow the map to grow
                # probability of enemies appearing still increases
                if self.debug_mode:
                    if e.key == K_s:
                        self.map.width -= 2
                        self.map.height -= 2
                        self.load_new_map()
            elif e.type == QUIT:
                quit()

        # move the enemies towards the player, if player is near enough
        for enemy_sprite in self.map.enemies_lst:
            if pygame.sprite.collide_circle(enemy_sprite, self.player):  # player-radius: 6, enemy-radius: 4
                enemy_sprite.move_towards_player(self.map.landscape, self.player.rect, self.map.map_objects["other"])

    def view(self):
        """
        Handles all of the display functionality.
        """
        # draw scene and objects
        self.draw_walls_floors_to_screen()
        self.draw_objects_to_screen()
        # draw enemies, if near player or in god-mode
        for sprite in self.map.enemies_lst:
            if pygame.sprite.collide_circle(sprite, self.player) or self.god_mode:
                self.screen.blit(sprite.image, self.camera.apply(sprite))
        # draw player
        for sprite in self.player_sprites:
            self.screen.blit(sprite.image, self.camera.apply(sprite))
        # finally, draw text
        self.keys_remaining_msg()
        self.draw_demo_msg()
        self.draw_debug_msg()
        # present changes to window
        pygame.display.flip()

    def load_new_map(self):
        """
        Loads a new map. Displays a loading message for 6 seconds and generates a new map.
        """
        self.clock.tick()  # initialize a counter
        self.screen.blit(self.background, (0, 0))
        self.display_text_to_screen(LOADING_MSG_FONT_SIZE, "Loading...")
        self.display_text_to_screen(RANDOM_LOADING_MSG_FONT_SIZE, random.choice(RANDOM_LOADING_MSGS),
                                    pos_y=(self.background.get_height() >> 1) + 35,
                                    rgb_color=(255, 25, 25))
        pygame.display.update()  # display loading page
        # generate a new game
        self.map = TheMap(self.map.width + 2, self.map.height + 2)
        self.player.rect.left, self.player.rect.top = self.map.player_start_loc
        # 15 is the boundary; afterwards, the probability of enemy appearing where key is, is 100%
        if self.enemy_prob < 15:
            self.enemy_prob += 1
        self.map.probability_enemy_appears = self.enemy_prob
        # readjust the camera
        self.camera = Camera(complex_camera, self.map.width << 5, self.map.height << 5,
                             self.window_width,
                             self.window_height)
        t1 = self.clock.tick()
        time_to_wait = 6000 - t1  # provide 6 seconds (or more) to read loading msg
        pygame.time.wait(time_to_wait)

    def display_text_to_screen(self, font_size, msg, pos_x=None, pos_y=None, rgb_color=(255, 255, 255)):
        """
        displays some text to the screen
        :param font_size: (int) font size
        :param msg: (str) message to display
        :param pos_x: (int) x-coordinate to display at
        :param pos_y: (int) y-coordinate to display at
        :param rgb_color: (tuple) (r,g,b)
        """
        if pygame.font:
            if not pos_x:
                pos_x = self.window_width >> 1
            if not pos_y:
                pos_y = self.window_height >> 1
            font = pygame.font.Font(None, font_size)
            text = font.render(msg, 1, rgb_color)
            text_pos = text.get_rect(centerx=pos_x, centery=pos_y)
            self.screen.blit(text, text_pos)

    def draw_walls_floors_to_screen(self):
        """
        Draws the walls and the floor if it is some X distance from the player.
        Uses PyGame's circle collision to detect what wall/floor to light up.
        """
        self.camera.update(self.player)
        # clear the background
        self.screen.blit(self.background, (0, 0))
        # shifts all objects and creates camera motion-effect (also, performance booster)
        cam_x1 = -1 * self.camera.state.x >> 5
        cam_y1 = -1 * self.camera.state.y >> 5
        cam_x2 = (-1 * self.camera.state.x + self.window_width + 32) >> 5
        cam_y2 = (-1 * self.camera.state.y + self.window_height + 32) >> 5
        for x in range(cam_x1, cam_x2):
            for y in range(cam_y1, cam_y2):
                sprite = self.map.landscape[y][x]
                if pygame.sprite.collide_circle(sprite, self.player) or self.god_mode:
                    near_viewable = True and not sprite.block_sight
                else:
                    near_viewable = False
                if near_viewable or sprite.visited:  # light sprites nearby and shadow visited sprites
                    if not sprite.block_sight:
                        sprite.visited = True
                        if near_viewable:
                            self.screen.blit(sprite.image, self.camera.apply(sprite))
                        else:
                            self.screen.blit(sprite.drk_image, self.camera.apply(sprite))

    def draw_objects_to_screen(self):
        """
        Draws all map-objects: keys, stairs, and other (objects).
        """
        for object_groups in self.map.map_objects:  # unpacks the lists
            for sprite in self.map.map_objects[object_groups]:  # unpacks the sprites
                if pygame.sprite.collide_circle(sprite, self.player) or self.god_mode:
                    near_viewable = True and not sprite.block_sight
                else:
                    near_viewable = False
                if near_viewable or sprite.visited:  # light sprites nearby and shadows visited but not nearby sprites
                    if not sprite.block_sight:
                        sprite.visited = True
                        if near_viewable:
                            self.screen.blit(sprite.image, self.camera.apply(sprite))
                        else:
                            self.screen.blit(sprite.drk_image, self.camera.apply(sprite))

    def keys_remaining_msg(self):
        """
        Displays a message, indicating how many keys remain to be collected
        """
        remaining_keys = len(self.map.map_objects["keys"])
        pos_y = self.background.get_height() - 30
        if remaining_keys > 0:
            if remaining_keys == 1:
                msg = "Collect the last key"
            else:
                msg = "Collect %s Keys" % remaining_keys
            self.display_text_to_screen(36, msg, pos_y=pos_y)
        else:
            self.display_text_to_screen(36, "Climb the stairs!", rgb_color=(255, 0, 0), pos_y=pos_y)

    def draw_debug_msg(self):
        """
        Displays debug information at the top right of the screen
        """
        text_pos_x = self.window_width - 100  # x-coord to place msg
        text_pos_y = 30  # y-coord to place msg
        text_offset_y = 14  # offset y-coord for next lines
        if self.debug_mode:
            self.display_text_to_screen(16, "Debug mode(d): on", pos_x=text_pos_x, pos_y=text_pos_y)
            if self.god_mode:
                self.display_text_to_screen(16, "God mode(g): on", pos_x=text_pos_x, pos_y=text_pos_y + text_offset_y)
            else:
                self.display_text_to_screen(16, "God mode(g): off", pos_x=text_pos_x, pos_y=text_pos_y + text_offset_y)

            self.display_text_to_screen(16, "Skip level key: s", pos_x=text_pos_x,
                                        pos_y=text_pos_y + (text_offset_y << 1))
        else:
            self.display_text_to_screen(16, "Debug mode(d): off", pos_x=text_pos_x, pos_y=text_pos_y)
        # display msg if enemy is trying to attack
        enemy_lst = pygame.sprite.spritecollide(self.player, self.map.enemies_lst, False)
        if enemy_lst:
            self.display_text_to_screen(16, "This is when he realizes he hasn't been programmed any weapons",
                                        pos_y=(self.window_height >> 1) + 40)

    def draw_demo_msg(self):
        """
        Displays a message the first time the player is on a key or stairway.
        """
        # key
        if not self.seen_first_key:
            color = (255, 255, 0)  # yellow
            key_lst = pygame.sprite.spritecollide(self.player, self.map.map_objects["keys"], False)
            if key_lst:
                self.display_text_to_screen(32, "Press the SPACE BAR to collect the key", rgb_color=color)
        # stair
        if not self.seen_first_stairs:
            color = (255, 255, 0)  # yellow
            stair_lst = pygame.sprite.spritecollide(self.player, self.map.map_objects["stairs"], False)
            if stair_lst:
                if len(self.map.map_objects["keys"]) == 0:
                    self.display_text_to_screen(32, "Press the SPACE BAR to climb the stairs", rgb_color=color)
                else:
                    self.display_text_to_screen(32, "Collect all of the keys and then come back", rgb_color=color)
Esempio n. 36
0
 def __init__(self):
     super().__init__()
     self.entity_manager = EntityManager()
     self.entity_manager.add(Player(100, 100))
     self.add_bawx(-100, -100, 500, 500)
Esempio n. 37
0
import menus
from entities import Player
from functions import clear_screen, save_character, load_character
import json

with open('config.json', 'r') as f:
    config = json.load(f)

clear_screen()
if config["DevMode"] == True:
    player = Player(max_hp=999,
                    current_hp=999,
                    coins=9999,
                    xp=9999,
                    attack_damage=200,
                    defense_ablilty=2000)
else:
    player = Player()
del config
menus.title()

# Start main loop
while True:
    instruction = menus.main_menu()
    while instruction != "main_menu":
        if instruction.startswith("menu_request:"):
            instruction = instruction[len("menu_request:"):len(instruction)]
            if instruction == "fight":
                instruction = menus.fight()
            elif instruction.startswith("battle"):
                instruction = instruction[len("battle "):len(instruction)]
Esempio n. 38
0
def main():
    """ Main Program """
    pygame.init()
    # # Set the height and width of the screen
    size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]
    # # Set display screen
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("Game")
    # # Create world
    world = World()
    sprite_group = pygame.sprite.Group()
    sprite_group_2 = pygame.sprite.Group()
    # # Create the player
    player = Player()
    enemy = Enemy()
    # # Create Walls
    wall = Wall(500, 400, 100, 100)
    wall2 = Wall(100, 100, 50, 50)
    # # Group
    sprite_group.add(wall)
    sprite_group.add(wall2)
    sprite_group_2.add(enemy)
    player.walls = sprite_group
    player.enemies = sprite_group_2
    # Loop until the user clicks the close button.
    done = False
    # # Get keys
    pressed_right = None
    pressed_left = None
    pressed_up = None
    pressed_down = None
    # 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
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    done = True
                elif event.key == pygame.K_RIGHT:
                    pressed_right = True
                elif event.key == pygame.K_LEFT:
                    pressed_left = True
                elif event.key == pygame.K_UP:
                    pressed_up = True
                elif event.key == pygame.K_DOWN:
                    pressed_down = True

            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_RIGHT:
                    pressed_right = False
                elif event.key == pygame.K_LEFT:
                    pressed_left = False
                elif event.key == pygame.K_UP:
                    pressed_up = False
                elif event.key == pygame.K_DOWN:
                    pressed_down = False

        player.update(pressed_right, pressed_left, pressed_up, pressed_down)
        # # Go ahead and update the screen with what we've drawn.
        world.world_shift(player.rect.x, player.rect.y)

        screen.fill(constants.WHITE)
        screen.blit(world.image, world.rect)
        sprite_group.draw(screen)
        screen.blit(player.image, player.rect)
        pygame.draw.rect(screen, constants.GREEN, (10, 10, 60, 10))

        enemy.move_enemy(player.rect.x, player.rect.y)
        # screen.blit(enemy.image, enemy.rect)
        sprite_group_2.draw(screen)
        pygame.display.flip()
        # Limit to 60 frames per second
        clock.tick(60)
    # Be IDLE friendly. If you forget this line, the program will 'hang'
    # on exit.
    pygame.quit()
Esempio n. 39
0
import pygame
from random import randint
from entities import Player, Enemy, Bullet

# game setup
game = {
    "title": "Shoot!",
    "background": (40, 40, 40),
    "width": 700,
    "height": 450
}

player = Player(game["width"] // 2, game["height"])
bullets = []
squadron = []


def rand_x(n, r, dx):
    if dx == 1:
        return randint(r, game["width"] - r * n)
    else:
        return randint(r * 2, game["width"] - r)


def rand_y():
    return randint(0, game["height"] // 3)


def rand_dx():
    rand = randint(0, 1)
    if rand == 0:
Esempio n. 40
0
class Game(object):

    def __init__(self):
        self.map = Map(START_LEVEL)
        # Enforce that a path does exist in the map
        while self.map.findPath() == None:
            self.map = Map(START_LEVEL)
        self.player = Player()
        self.inventory = Inventory()
        self.enemy_factory = EnemyFactory()
        self.user = User()

        self.invuln_turns = 0

        self.swap_weapon_to = None

        self.current_enemy = None
        self.level = START_LEVEL
        self.danger = 5
        self.hide_danger = 5
        self.escape_chance = 3
        self.items_dropped = 0 # a counter so we make sure they get shield, sword and bow chances first
        self.steps_left = MAX_STEPS
        self.escapes_remaining = NUM_ESCAPES
        self.encounter_sdorf = False

        self.dangers = []
        self.escape_chances = []
        self.hide_dangers = []

        self.seerdata = SeerData()
        self.init_dangers()

    def init_dangers(self):
        self.dangers.append(self._update(self.danger, 0, 10, 2))
        self.escape_chances.append(self._update(self.escape_chance, 1, 4, 3))
        self.hide_dangers.append(self._update(self.hide_danger, 0, 10, 2))

        for i in range(8):
            self.dangers.append(self._update(self.dangers[-1], 0, 10, 2))
            self.escape_chances.append(self._update(self.escape_chances[-1], 1, 4, 3))
            self.hide_dangers.append(self._update(self.hide_dangers[-1], 0, 10, 2))

    def levelUp(self):
        self.level += 1
        self.enemy_factory.setLevel(self.level)

    def takeStep(self):
        self.steps_left -= 1
        if self.steps_left <= 0: raise Defeat("You have failed to defeat the Fortress of Dorf.")

    def getDataForAI(self, moveType):
        itemStart = 1
        if self.inventory.get_main_hand():
            itemStart += 1
        if self.inventory.get_offhand():
            itemStart += 1
        if moveType == "ITEM":
            itemStart = 3
        items = self.inventory.get_pack()
        items_dict = {}
        # Map item numbers to weapons in the pack
        for i in range(len(items)):
            items_dict[str(itemStart + i)] = items[i]
        return {
            "situation": moveType,
            "enemy": None if not self.current_enemy else self.current_enemy.description(),
            "player": {
                "health": self.player.health,
                "next_attack": self.inventory.next_attack,
                "swap_weapon_to_hand": self.swap_weapon_to,
            },
            "inventory": {
                "main_hand": self.inventory.get_main_hand().description() if self.inventory.get_main_hand() else None,
                "off_hand": self.inventory.get_offhand().description() if self.inventory.get_offhand() else None,
                "backpack_weapons": items_dict,
                "backpack_has_space": self.inventory.has_inventory_space(),
                "potions": self.inventory.miscitems["Potions"],
                "repels": self.inventory.miscitems["Repel"],
                "fireballs": self.inventory.miscitems["Fireballs"],
                "candles": self.escapes_remaining,
            },
            "level": self.level,
            "map_danger": self.danger,
            "hide_danger": self.hide_danger,
            "escape_chance": self.escape_chance,
            "steps_left": self.steps_left,
            "invuln_steps": self.invuln_turns,
            "future": self.seerdata.get_info(moveType, self.enemy_factory, [self.danger] + self.dangers, [self.hide_danger] + self.hide_dangers, [self.escape_chance] + self.escape_chances),
        }

    def _inventoryData(self):
        # returns a list of 14 strings used to populate the bottom-right corner
        # of the war screen
        data = []
        for i in range(15):
            data.append("")
        data[0] = "Type: {0}".format(self.current_enemy.name)
        #data[1] = "Element: {0}".format(self.current_enemy.element)
        data[1] = "Weapon: {0}".format(self.current_enemy.item.name)
        data[2] = "Weapon Strength: {}".format(self.current_enemy.item.strength)
        data[3] = "Next Attack: {0}".format(
            STRENGTHNAMES[
                self.current_enemy.next_attack])
        data[4] = "- " * 25 + "-"
        data[5] = "EQUIPMENT"

        data[6] = (
            "Main Hand: {0}".format(
                self.inventory.get_main_hand().name \
                if self.inventory.get_main_hand()
                else "Nothing"
                )
        )
        data[7] = (
            "Off-Hand: {0}".format(
                self.inventory.get_offhand().name \
                if self.inventory.get_offhand()
                else "Nothing"
            )
        )
        data[8] = (
            "Player Next Attack: {0}".format(
                STRENGTHNAMES[self.inventory.next_attack]
            )
        )
        data[9] = "- " * 25 + "-"
        data[10] = "INVENTORY"
        data[11] = (
            "Potions: {0}".format(
                self.inventory.miscitems['Potions'])) 
        data[12] =  (
            "Repel: {0}".format(
                self.inventory.miscitems['Repel'])) 
        data[13] = (
            "Fireballs: {0}".format(
                self.inventory.miscitems['Fireballs'])) 
        data[14] = (
            "Candles: {0:<10} Escape Chance: {1:>16}".format(
                self.escapes_remaining, PROBS[self.escape_chance]))
        return data

    def printItems(self):  # TODO: list enemy weapon in case we want it?
        # populate list
        main_hand = self.inventory.get_main_hand()
        offhand = self.inventory.get_offhand()

        main_hand_image = getattr(asciiart, main_hand.image).split('\n') if main_hand else None
        offhand_image = getattr(asciiart, offhand.image).split('\n') if offhand else None

        miscItems = self._inventoryData()
        # fill the next 14 lines

        main_hand_stats = ["Name: " + str(main_hand.name), "Strength: " + str(main_hand.strength), 'Durability: ' + str(main_hand.durability)] if main_hand else None
        offhand_stats = ["Name: " + str(offhand.name), "Strength: " + str(offhand.strength), 'Durability: ' + str(offhand.durability)] if offhand else None
        
        # Gather inventory, including main hand and offhand
        items = []
        item_images = []
        if main_hand:
            items.append(main_hand_stats)
            item_images.append(getattr(asciiart, main_hand.image).split('\n')[1:])
        if offhand:
            items.append(offhand_stats)
            item_images.append(getattr(asciiart, offhand.image).split('\n')[1:])
        # Get weapon data and images
        for item in self.inventory.get_pack():
            items.append(["Name: " + item['name'], "Strength: " + str(item['strength']), 'Durability: ' + str(item['durability'])])
            item_images.append(getattr(asciiart, item['type']).split('\n')[1:]) # Remove the first new line of the items

        lines = []
        offhandText = 'Off-Hand' if offhand else '2.'
        numSpaces = 26 if offhand else 32
        lines.append("| {0:34s}".format('Main Hand' if main_hand else (offhandText if offhand else '1.')) +
                     "| {0:34s}".format(offhandText if main_hand else '2.') +
                     '| {0:34s}'.format('3.') +
                     "| " + "{0:52s}".format(miscItems[0]) + "|")
        lines.append("| " + " " * 22 + '{0:12s}'.format(item_images[0][0] if 0 < len(item_images) else "") +
                     "| " + " " * 22 + '{0:12s}'.format(item_images[1][0] if 1 < len(item_images) else "") +
                     '| ' + ' ' * 22 + '{0:12s}'.format(item_images[2][0] if 2 < len(item_images) else "") +
                     "| " + "{0:52s}".format(miscItems[1]) + "|")

        # print len(item_images), item_images
        for i in range(5):
            lines.append("| " + "{0:22s}".format(items[0][i % 3] if 0 < len(items) and items[0] and i < 3 else "") + '{0:12s}'.format(item_images[0][(i + 1) % 6] if 0 < len(item_images) and item_images[0] else "") +
                         "| " + "{0:22s}".format(items[1][i % 3] if 1 < len(items) and items[1] and i < 3 else "") + '{0:12s}'.format(item_images[1][(i + 1) % 6] if 1 < len(item_images) and item_images[1] else "") +
                         '| ' + "{0:22s}".format(items[2][i % 3] if 2 < len(items) and items[2] and i < 3 else "") + '{0:12s}'.format(item_images[2][(i + 1) % 6] if 2 < len(item_images) and item_images[2] else "") +
                         '| ' + '{0:52s}'.format(miscItems[i+2]) + '|')
        # Index 4 and 5
        lines.append('|' + '-' * 35 + '|' + '-' * 35 + '|' + "-" * 35 + '| ' + '{0:52s}'.format(miscItems[7]) + '|')
        lines.append('| {0:34s}'.format('4.') + '| {0:34s}'.format('5.') + '| {0:34s}'.format('6.') + '| {0:52s}'.format(miscItems[8]) + '|')
        lines.append("| " + " " * 22 + '{0:12s}'.format(item_images[3][0] if 3 < len(item_images) else "") + 
                     "| " + " " * 22 + '{0:12s}'.format(item_images[4][0] if 4 < len(item_images) else "") + 
                     '| ' + ' ' * 22 + '{0:12s}'.format(item_images[5][0] if 5 < len(item_images) else "") + 
                     "| " + "{0:52s}".format(miscItems[9]) + "|")
        for i in range(7, 12):
            lines.append("| " + "{0:22s}".format(items[3][(i-1) % 3] if 3 < len(items) and items[3] and i-1 < 9 else "") + '{0:12s}'.format(item_images[3][i % 6] if 3 < len(item_images) and item_images[3] else "") +
                         "| " + "{0:22s}".format(items[4][(i-1) % 3] if 4 < len(items) and items[4] and i-1 < 9 else "") + '{0:12s}'.format(item_images[4][i % 6] if 4 < len(item_images) and item_images[4] else "") +
                         '| ' + "{0:22s}".format(items[5][(i-1) % 3] if 5 < len(items) and items[5] and i-1 < 9 else "") + '{0:12s}'.format(item_images[5][i % 6] if 5 < len(item_images) and item_images[5] else "") +
                         '| ' + '{0:52s}'.format(miscItems[i+3]) + '|')
        
        lines.append("- " * 82)
        for line in lines:
            print line

    def printScreen(self):
        for i in range(3): print
        # update to remove old messages
        while len(self.messages) > 8:
            self.messages.pop(0)
        message = "\n".join(self.messages)

        print
        # print the message box
        printMessageBox(message)
        # print battlefield
        printBattlefield(
            CHARACTER3,
            getattr(
                asciiart,
                self.current_enemy.image),
            162,
            15)
        # print info bar
        print SCREEN.format(hp=str(self.player.health) + "/" + str(PLAYER_MAX_HEALTH), ehp=str(self.current_enemy.health))
        # print equipment and items
        self.printItems()

    def _getUserMove(self):
        self.messages.append("What will you do?")
        self.printScreen()

        print "What will you do? ('o' for help)",
        decision = self.user.__move__(self.getDataForAI("COMBAT"))
        while decision[0] not in ['x', 'c', 'i', 'e', '1', 'f', '2']:
            # TODO review logic here for bugs
            if decision == 'q':
                print
                raise Quit()
            if decision == 'p':
                printSeerData(self.seerdata.get_info("COMBAT", self.enemy_factory, [self.danger] + self.dangers, [self.hide_danger] + self.hide_dangers, [self.escape_chance] + self.escape_chances))
                while getch() != 'p': print "Press 'p' to return to the game!"
            elif decision == 'o':
                printHelpScreen(self.getDataForAI("COMBAT"))
                while getch() != 'o': print "Press 'o' to return to the game!"
            else:
                self.messages.append("That's not a valid command - what will you do?")
            self.printScreen()
            decision = self.user.__move__(self.getDataForAI("COMBAT"))
        return decision

    def playerTurn(self):
        # set environment variables
        self.printScreen()

        will_escape = self.seerdata.get_escape()
        decisions = [x for x in self._getUserMove()]
        playerDamage = 0
        playerAction = ""

        # SWAPPING
        if decisions[0] == '1' or decisions[0] == '2':
            items = self.inventory.get_pack()
            if len(items) == 0:
                self.messages.append("You have no items to swap between!")
                return False
            
            handChoice = 'Main Hand' if decisions[0] == '1' else 'Off-Hand'
            self.swap_weapon_to = handChoice
            
            # Print the weapons available to swap to
            validSwap = False
            while not validSwap:
                self.messages.append('Which weapon do you want to place in your {}?'.format(handChoice))
                itemIndexOffset = 1
                if self.inventory.get_main_hand():
                    itemIndexOffset += 1
                if self.inventory.get_offhand():
                    itemIndexOffset += 1
                for i in range(len(items)):
                    item = items[i]
                    keyPress = 'Press {} to swap to '.format(i + itemIndexOffset)
                    weaponMssg = '{0} (Type: {1}, Strength: {2}, Durability: {3})'.format(item['name'], item['type'], item['strength'], item['durability'])
                    self.messages.append(keyPress + weaponMssg)
                self.printScreen()
                
                try:
                    itemChoice = self.user.__move__(self.getDataForAI('SWAP'))
                    itemChoice = int(itemChoice[0]) - itemIndexOffset
                    self.messages = []    
                    if not self.inventory.is_valid_item_index(itemChoice):
                        self.messages.append('Invalid command!')
                        return False
                    elif (handChoice == 'Main Hand' and self.inventory.swap_main_hand(itemChoice)) or \
                            (handChoice == 'Off-Hand' and self.inventory.swap_offhand(itemChoice)):
                        self.messages.append('Successfully swapped weapon to {}!'.format(handChoice))
                        validSwap = True
                    else:
                        self.messages.append('You cannot place a {} in your {}!'.format(items[itemChoice]['name'], handChoice))
                        return False
                except ValueError:
                    self.messages.append("Invalid input!")
            if not USE_AI: time.sleep(2)
        
        # ATTACKING
        elif decisions[0] == 'f':
            self.playerStance = "OFFENSIVE"
            result = self.inventory.use_misc("Fireballs")
            if result:
                playerDamage = ITEM_STRENGTHS["Fireballs"]
                self.messages.append("You blast the {0} for {1} damage!".format(self.current_enemy.name, playerDamage))
                self.current_enemy.damage(playerDamage)
            else:
                self.messages.append("You wave your hands around, but nothing happens.")
            return True

        elif decisions[0] == 'x':
            self.playerStance = "OFFENSIVE"
            # are we attacking with a ranged weapon?
            ranged_items = self.inventory.get_equipped_ranged()
            if ranged_items:
                # deal the damage
                playerAction = "shoot"

            # for non-ranged weapons
            else:
                # deal the damage
                playerAction = "hit"

            if self.rangedEncounter and not self.inventory.get_equipped_ranged():
                # Melee weapon is equipped during ranged encounter, therefore cannot do damage
                return True
            playerDamage = self.inventory.get_damage()
            if (self.rangedEncounter):
                playerDamage *= RANGE_COMBAT_FACTOR
                
            # deal the damage and update
            totalDamage = max(1, # Force player to do minimum 1 damage
                              int(playerDamage * (float(self.inventory.next_attack) / 3)))
            self.current_enemy.damage(totalDamage)
            self.messages.append(
                "You {0} the {1} for {2} damage!".format(
                    playerAction,
                    self.current_enemy.name,
                    totalDamage))

            return True

        # ESCAPE
        elif decisions[0] == 'e':
            if not self.escapes_remaining: self.messages.append("You don't have any more Babylon Candles!")
            else:
                self.escapes_remaining -= 1
                if will_escape:
                    self.messages.append("You failed to escape!")
                else:
                    self.messages.append("You escaped using a Babylon Candle!")
                    self.printScreen()
                    if not USE_AI: time.sleep(1.2)
                    raise Escape()

        # ITEMS
        elif decisions[0] == 'i':
            item_type = "Potions"
            result = self.inventory.use_misc(item_type)
            # TODO: Not yet fully implemented for things other than Potions
            if result:
                self.playerStance = "NEUTRAL"
                self.player.health = min(
                    result +
                    self.player.health,
                    PLAYER_MAX_HEALTH)
                self.messages.append(
                    "You drank a potion and recovered {0} health!".format(result))
                self.printScreen()
                return True
            else:
                self.messages.append("You don't have any Potions!")
                return False

        # SHIELDING
        elif decisions[0] == 'c':
            # is there a shield equipped?
            shields = self.inventory.get_equipped_defense()
            if shields:
                self.playerStance = "DEFENSIVE"
                self.messages.append("You raised your shield!")
                return True
            else:
                self.messages.append(
                    "You try to raise your shield, only to discover you're not holding one. The {0} looks confused.".format(
                        self.current_enemy.name))
                return True

        # BAD COMMAND
        else:
            assert(False and "Invalid command specified")

    def enemyTurn(self):
        # enemy will of course hit back
        damage = int((float(self.current_enemy.item.strength) * ENEMY_DAMAGE_CONSTANT) * self.current_enemy.next_attack)
        # player is shielding
        shield_level = 0
        if self.playerStance == "DEFENSIVE":
            # find the shields the player has
            #shield_level = self.inventory.get_equipped_defense().strength
            shield_level = self.inventory.get_defense()
            self.inventory.check_durability()
        if self.playerStance == "DEFENSIVE" and self.seerdata.current_block:
            self.messages.append("You successfully blocked the enemy attack!")
        else:
            self.player.damage(damage)
            damageType = "hit" if not isinstance(
                self.current_enemy.item,
                RangedWeapon) else "shoot"
            self.messages.append(
                "The {0} {2}s you for {1} damage!".format(
                    self.current_enemy.name,
                    damage,
                    damageType))
        return True

        # escape results

    def _isMssgTooLong(self, currentMessage, messageToAppend):
        return len(currentMessage + messageToAppend) > 159


    def runEvent(self):


        from ai import USE_AI

        self.seerdata.generate_encounter(self.inventory.get_defense(), self.escape_chance, self.items_dropped, is_dorf=("DORF" in self.current_enemy.image))
        # Combat loop
        isPlayerTurn = True
        self.messages = []
        if self.player.hiding: self.messages.append("A {0} found your hiding place!".format(self.current_enemy.name))
        else: self.messages.append("A {0} appeared!".format(self.current_enemy.name))
        self.playerStance = "NEUTRAL"
        # Assume player will not make a mistake until he does
        success = True
        # Is player or enemy using a bow?
        self.rangedEncounter = False
        self.current_enemy.next_attack = self.seerdata.get_enemy_attack()
        self.inventory.next_attack = self.seerdata.get_player_attack()
        if self.inventory.get_equipped_ranged() or isinstance(
                self.current_enemy.item,
                RangedWeapon):
            self.rangedEncounter = True

        while not self.current_enemy.isDead() and not self.player.isDead():
            self.printScreen()

            try:
                if self.rangedEncounter:
                    if self.inventory.get_equipped_ranged():
                        while not self.playerTurn():  # Loop on invalid moves
                            self.swap_weapon_to = None # Clear swap hand state
                            self.printScreen()
                        self.seerdata.current_block = self.seerdata.get_block()
                        self.swap_weapon_to = None # Clear swap hand state
                        if self.inventory.get_equipped_ranged():
                            self.inventory.next_attack = self.seerdata.get_player_attack()
                        elif self.playerStance == 'OFFENSIVE':
                            self.messages.append("You swing your weapon wildly, but the {0} isn't close enough. The {0} looks confused...".format(self.current_enemy.name))
                        self.inventory.check_durability()
                    else:
                        self.messages.append(
                            'You run closer to the {0}...'.format(self.current_enemy.name)
                        )
                    if not self.current_enemy.isDead() and isinstance(self.current_enemy.item, RangedWeapon):
                        self.enemyTurn()
                        self.current_enemy.next_attack = self.seerdata.get_enemy_attack()

                # Player's move
                elif isPlayerTurn:
                    while not self.playerTurn():  # Loop on invalid moves
                        self.swap_weapon_to = None # Clear swap hand state
                        self.printScreen()
                    self.seerdata.current_block = self.seerdata.get_block()
                    self.swap_weapon_to = None # Clear swap hand state
                    self.inventory.next_attack = self.seerdata.get_player_attack()
                    self.inventory.check_durability()

                # enemy's move
                else:
                    self.enemyTurn()
                    self.current_enemy.next_attack = self.seerdata.get_enemy_attack()
                # update
                #self.printScreen()

                # Bow is only useful on the first turn
                if self.rangedEncounter:
                    self.rangedEncounter = False
                    if not self.current_enemy.isDead() and not self.player.isDead() and not isinstance(
                            self.current_enemy.item,
                            RangedWeapon):
                        self.messages.append(
                            "The {0} runs closer to you...".format(
                                self.current_enemy.name))
                else:
                    # Change whose turn it is
                    isPlayerTurn = False if isPlayerTurn else True
            except Escape as e:
                self.messages.append("You successfully ran away!")
                self.printScreen()
                return

        # someone died
        if self.current_enemy.isDead():
            self.current_enemy.image = "DEAD_" + self.current_enemy.image
            self.messages.append(
                "You defeated the {0}!".format(
                    self.current_enemy.name))
            self.printScreen()

            if self.seerdata.get_drop_chance():
                self.items_dropped += 1
                self.messages.append(
                    "The {0} dropped a {1}...".format(
                        self.current_enemy.name,
                        self.current_enemy.item.name))
                self.current_enemy.image = "BLANK_ENEMY"

                items = self.inventory.get_pack()
                pickupMssg = '[1: Place in MH] [2: Place in OH]'
                validOptions = ['1', '2',]
                self.messages.append("Would you like to take this with you?")
                toAppend = ''
                for i in range(len(items)):
                    # Add 3 because MH and OH are 1 and 2, so indexing starts at 3
                    validOptions.append(str(i + 3))
                    toAppend = ' [{0}: Replace {1}]'.format(str(i + 3), items[i]['name'])
                    if self._isMssgTooLong(pickupMssg, toAppend):
                        self.messages.append(pickupMssg)
                        pickupMssg = ''
                        toAppend = toAppend[1:]
                    pickupMssg += toAppend
                
                # If Space still in inventory, display "Add to inventory"
                if self.inventory.has_inventory_space():
                    validOptions.append('8')
                    toAppend = ' [8: Add to inventory]'
                    if self._isMssgTooLong(pickupMssg, toAppend):
                        self.messages.append(pickupMssg)
                        pickupMssg = ''
                        toAppend = toAppend[1:]
                    pickupMssg += toAppend
                
                # Always allowed to ignore items
                validOptions.append('9')
                toAppend = ' [9: Ignore]'
                if self._isMssgTooLong(pickupMssg, toAppend):
                    self.messages.append(pickupMssg)
                    pickupMssg = ''
                    toAppend = toAppend[1:]
                pickupMssg += toAppend

                # self.messages.append("[1: Pick up with MH] [2: Pick up with OH] [3: Don't pick up]")
                self.messages.append(pickupMssg)
                self.printScreen()
                y_or_n = self.user.__move__(self.getDataForAI("ITEM"))
                while y_or_n not in validOptions:
                    self.messages.append("Please enter " + '/'.join(validOptions))
                    self.printScreen()
                    y_or_n = self.user.__move__(self.getDataForAI("ITEM"))
                if y_or_n == '1':
                    # pick up item
                    self.inventory.equip_main_hand(self.current_enemy.item)
                    self.printScreen()
                    if not USE_AI: 
                        time.sleep(2)
                elif y_or_n == '2':
                    self.inventory.equip_offhand(self.current_enemy.item)
                    self.printScreen()
                    if not USE_AI: 
                        time.sleep(2)
                elif y_or_n == '8':
                    self.inventory.add_to_pack(self.current_enemy.item)
                elif y_or_n != '9':
                    # Items in inventory are keys 3-7
                    self.inventory.replace_item(int(y_or_n) - 3, self.current_enemy.item)


        elif self.player.isDead():
            self.printScreen()
            if not USE_AI: time.sleep(2)
            raise Defeat("You have been defeated.")

    def checkEvent(self):
        pass
        random.seed()

        event_value = random.uniform(0, 1)
        encounter_chance = 0.03 + BASE_ENEMY_ENCOUNTER_CHANCE * self.danger 
        
        if self.player.hiding: 
            h_event_value = random.uniform(0, 1)
            h_encounter_chance = 0.03 + BASE_HIDE_ENCOUNTER_CHANCE * self.hide_danger 
            if h_event_value <= h_encounter_chance:
                encounter_chance = 1
            else:
                encounter_chance = -1
        
        if STORY_MODE and self.map.stevendorf and not self.map.boss_fight:
            self.map.boss_fight = True
            self.current_enemy = self.enemy_factory.generateEnemy(self.level, boss=self.map.stevendorf or self.encounter_sdorf, dorfweap=14)
            self.runEvent()

        elif event_value <= encounter_chance and not self.invuln_turns:
            # spawn an enemy TODO generator
            self.current_enemy = self.enemy_factory.get_next_enemy()
            self.runEvent()
            self.current_enemy = None

        if self.invuln_turns: self.invuln_turns -= 1
        self.player.hiding = False

    def _update(self, var, start, end, flex):
        temp_danger = var
        danger_change = random.randint(0,flex)
        up_or_down = random.uniform(0,1)
        if up_or_down <= DANGER_MODIFIER: temp_danger += danger_change
        else: temp_danger -= danger_change
        if temp_danger > end: temp_danger = end
        elif temp_danger < start: temp_danger = start
        return temp_danger

    def update_danger(self):
        self.dangers.append(self._update(self.dangers[-1], 0, 10, 2))
        self.danger = self.dangers.pop(0)
        self.escape_chances.append(self._update(self.escape_chances[-1], 1, 4, 3))
        self.escape_chance = self.escape_chances.pop(0)
        self.hide_dangers.append(self._update(self.hide_dangers[-1], 0, 10, 2))
        self.hide_danger = self.hide_dangers.pop(0)

    def move(self, direction):
        if direction == 'HIDE':
            self.player.hiding = True
            self.checkEvent()
            return 1
        # is there something on this square?
        if self.map.canMove(direction):
            if self.map.mapMove(direction):
                return 2
            self.checkEvent()
            return 1
        return 0
Esempio n. 41
0
class Game(object):
    def __init__(self):
        self.map = Map(START_LEVEL)
        # Enforce that a path does exist in the map
        while self.map.findPath() == None:
            self.map = Map(START_LEVEL)
        self.player = Player()
        self.inventory = Inventory()
        self.enemy_factory = EnemyFactory()
        self.user = User()

        self.invuln_turns = 0

        self.swap_weapon_to = None

        self.current_enemy = None
        self.level = START_LEVEL
        self.danger = 5
        self.hide_danger = 5
        self.escape_chance = 3
        self.items_dropped = 0  # a counter so we make sure they get shield, sword and bow chances first
        self.steps_left = MAX_STEPS
        self.escapes_remaining = NUM_ESCAPES
        self.encounter_sdorf = False

        self.dangers = []
        self.escape_chances = []
        self.hide_dangers = []

        self.seerdata = SeerData()
        self.init_dangers()

    def init_dangers(self):
        self.dangers.append(self._update(self.danger, 0, 10, 2))
        self.escape_chances.append(self._update(self.escape_chance, 1, 4, 3))
        self.hide_dangers.append(self._update(self.hide_danger, 0, 10, 2))

        for i in range(8):
            self.dangers.append(self._update(self.dangers[-1], 0, 10, 2))
            self.escape_chances.append(
                self._update(self.escape_chances[-1], 1, 4, 3))
            self.hide_dangers.append(
                self._update(self.hide_dangers[-1], 0, 10, 2))

    def levelUp(self):
        self.level += 1
        self.enemy_factory.setLevel(self.level)

    def takeStep(self):
        self.steps_left -= 1
        if self.steps_left <= 0:
            raise Defeat("You have failed to defeat the Fortress of Dorf.")

    def getDataForAI(self, moveType):
        itemStart = 1
        if self.inventory.get_main_hand():
            itemStart += 1
        if self.inventory.get_offhand():
            itemStart += 1
        if moveType == "ITEM":
            itemStart = 3
        items = self.inventory.get_pack()
        items_dict = {}
        # Map item numbers to weapons in the pack
        for i in range(len(items)):
            items_dict[str(itemStart + i)] = items[i]
        return {
            "situation":
            moveType,
            "enemy":
            None
            if not self.current_enemy else self.current_enemy.description(),
            "player": {
                "health": self.player.health,
                "next_attack": self.inventory.next_attack,
                "swap_weapon_to_hand": self.swap_weapon_to,
            },
            "inventory": {
                "main_hand":
                self.inventory.get_main_hand().description()
                if self.inventory.get_main_hand() else None,
                "off_hand":
                self.inventory.get_offhand().description()
                if self.inventory.get_offhand() else None,
                "backpack_weapons":
                items_dict,
                "backpack_has_space":
                self.inventory.has_inventory_space(),
                "potions":
                self.inventory.miscitems["Potions"],
                "repels":
                self.inventory.miscitems["Repel"],
                "fireballs":
                self.inventory.miscitems["Fireballs"],
                "candles":
                self.escapes_remaining,
            },
            "level":
            self.level,
            "map_danger":
            self.danger,
            "hide_danger":
            self.hide_danger,
            "escape_chance":
            self.escape_chance,
            "steps_left":
            self.steps_left,
            "invuln_steps":
            self.invuln_turns,
            "future":
            self.seerdata.get_info(moveType, self.enemy_factory,
                                   [self.danger] + self.dangers,
                                   [self.hide_danger] + self.hide_dangers,
                                   [self.escape_chance] + self.escape_chances),
        }

    def _inventoryData(self):
        # returns a list of 14 strings used to populate the bottom-right corner
        # of the war screen
        data = []
        for i in range(15):
            data.append("")
        data[0] = "Type: {0}".format(self.current_enemy.name)
        #data[1] = "Element: {0}".format(self.current_enemy.element)
        data[1] = "Weapon: {0}".format(self.current_enemy.item.name)
        data[2] = "Weapon Strength: {}".format(
            self.current_enemy.item.strength)
        data[3] = "Next Attack: {0}".format(
            STRENGTHNAMES[self.current_enemy.next_attack])
        data[4] = "- " * 25 + "-"
        data[5] = "EQUIPMENT"

        data[6] = (
            "Main Hand: {0}".format(
                self.inventory.get_main_hand().name \
                if self.inventory.get_main_hand()
                else "Nothing"
                )
        )
        data[7] = (
            "Off-Hand: {0}".format(
                self.inventory.get_offhand().name \
                if self.inventory.get_offhand()
                else "Nothing"
            )
        )
        data[8] = ("Player Next Attack: {0}".format(
            STRENGTHNAMES[self.inventory.next_attack]))
        data[9] = "- " * 25 + "-"
        data[10] = "INVENTORY"
        data[11] = ("Potions: {0}".format(self.inventory.miscitems['Potions']))
        data[12] = ("Repel: {0}".format(self.inventory.miscitems['Repel']))
        data[13] = ("Fireballs: {0}".format(
            self.inventory.miscitems['Fireballs']))
        data[14] = ("Candles: {0:<10} Escape Chance: {1:>16}".format(
            self.escapes_remaining, PROBS[self.escape_chance]))
        return data

    def printItems(self):  # TODO: list enemy weapon in case we want it?
        # populate list
        main_hand = self.inventory.get_main_hand()
        offhand = self.inventory.get_offhand()

        main_hand_image = getattr(
            asciiart, main_hand.image).split('\n') if main_hand else None
        offhand_image = getattr(asciiart,
                                offhand.image).split('\n') if offhand else None

        miscItems = self._inventoryData()
        # fill the next 14 lines

        main_hand_stats = [
            "Name: " + str(main_hand.name), "Strength: " +
            str(main_hand.strength), 'Durability: ' + str(main_hand.durability)
        ] if main_hand else None
        offhand_stats = [
            "Name: " + str(offhand.name), "Strength: " +
            str(offhand.strength), 'Durability: ' + str(offhand.durability)
        ] if offhand else None

        # Gather inventory, including main hand and offhand
        items = []
        item_images = []
        if main_hand:
            items.append(main_hand_stats)
            item_images.append(
                getattr(asciiart, main_hand.image).split('\n')[1:])
        if offhand:
            items.append(offhand_stats)
            item_images.append(
                getattr(asciiart, offhand.image).split('\n')[1:])
        # Get weapon data and images
        for item in self.inventory.get_pack():
            items.append([
                "Name: " + item['name'], "Strength: " + str(item['strength']),
                'Durability: ' + str(item['durability'])
            ])
            item_images.append(
                getattr(asciiart, item['type']).split('\n')
                [1:])  # Remove the first new line of the items

        lines = []
        offhandText = 'Off-Hand' if offhand else '2.'
        numSpaces = 26 if offhand else 32
        lines.append("| {0:34s}".format('Main Hand' if main_hand else
                                        (offhandText if offhand else '1.')) +
                     "| {0:34s}".format(offhandText if main_hand else '2.') +
                     '| {0:34s}'.format('3.') + "| " +
                     "{0:52s}".format(miscItems[0]) + "|")
        lines.append("| " + " " * 22 + '{0:12s}'.format(
            item_images[0][0] if 0 < len(item_images) else "") + "| " +
                     " " * 22 + '{0:12s}'.format(
                         item_images[1][0] if 1 < len(item_images) else "") +
                     '| ' + ' ' * 22 + '{0:12s}'.format(
                         item_images[2][0] if 2 < len(item_images) else "") +
                     "| " + "{0:52s}".format(miscItems[1]) + "|")

        # print len(item_images), item_images
        for i in range(5):
            lines.append(
                "| " + "{0:22s}".format(items[0][i % 3] if 0 < len(items)
                                        and items[0] and i < 3 else "") +
                '{0:12s}'.format(item_images[0][
                    (i + 1) %
                    6] if 0 < len(item_images) and item_images[0] else "") +
                "| " + "{0:22s}".format(items[1][i % 3] if 1 < len(items)
                                        and items[1] and i < 3 else "") +
                '{0:12s}'.format(item_images[1][
                    (i + 1) %
                    6] if 1 < len(item_images) and item_images[1] else "") +
                '| ' + "{0:22s}".format(items[2][i % 3] if 2 < len(items)
                                        and items[2] and i < 3 else "") +
                '{0:12s}'.format(item_images[2][
                    (i + 1) %
                    6] if 2 < len(item_images) and item_images[2] else "") +
                '| ' + '{0:52s}'.format(miscItems[i + 2]) + '|')
        # Index 4 and 5
        lines.append('|' + '-' * 35 + '|' + '-' * 35 + '|' + "-" * 35 + '| ' +
                     '{0:52s}'.format(miscItems[7]) + '|')
        lines.append('| {0:34s}'.format('4.') + '| {0:34s}'.format('5.') +
                     '| {0:34s}'.format('6.') +
                     '| {0:52s}'.format(miscItems[8]) + '|')
        lines.append("| " + " " * 22 + '{0:12s}'.format(
            item_images[3][0] if 3 < len(item_images) else "") + "| " +
                     " " * 22 + '{0:12s}'.format(
                         item_images[4][0] if 4 < len(item_images) else "") +
                     '| ' + ' ' * 22 + '{0:12s}'.format(
                         item_images[5][0] if 5 < len(item_images) else "") +
                     "| " + "{0:52s}".format(miscItems[9]) + "|")
        for i in range(7, 12):
            lines.append(
                "| " + "{0:22s}".format(items[3][
                    (i - 1) %
                    3] if 3 < len(items) and items[3] and i - 1 < 9 else "") +
                '{0:12s}'.format(item_images[3][i % 6] if 3 < len(item_images)
                                 and item_images[3] else "") + "| " +
                "{0:22s}".format(items[4][
                    (i - 1) %
                    3] if 4 < len(items) and items[4] and i - 1 < 9 else "") +
                '{0:12s}'.format(item_images[4][i % 6] if 4 < len(item_images)
                                 and item_images[4] else "") + '| ' +
                "{0:22s}".format(items[5][
                    (i - 1) %
                    3] if 5 < len(items) and items[5] and i - 1 < 9 else "") +
                '{0:12s}'.format(item_images[5][i % 6] if 5 < len(item_images)
                                 and item_images[5] else "") + '| ' +
                '{0:52s}'.format(miscItems[i + 3]) + '|')

        lines.append("- " * 82)
        for line in lines:
            print line

    def printScreen(self):
        for i in range(3):
            print
        # update to remove old messages
        while len(self.messages) > 8:
            self.messages.pop(0)
        message = "\n".join(self.messages)

        print
        # print the message box
        printMessageBox(message)
        # print battlefield
        printBattlefield(CHARACTER3,
                         getattr(asciiart, self.current_enemy.image), 162, 15)
        # print info bar
        print SCREEN.format(hp=str(self.player.health) + "/" +
                            str(PLAYER_MAX_HEALTH),
                            ehp=str(self.current_enemy.health))
        # print equipment and items
        self.printItems()

    def _getUserMove(self):
        self.messages.append("What will you do?")
        self.printScreen()

        print "What will you do? ('o' for help)",
        decision = self.user.__move__(self.getDataForAI("COMBAT"))
        while decision[0] not in ['x', 'c', 'i', 'e', '1', 'f', '2']:
            # TODO review logic here for bugs
            if decision == 'q':
                print
                raise Quit()
            if decision == 'p':
                printSeerData(
                    self.seerdata.get_info(
                        "COMBAT", self.enemy_factory,
                        [self.danger] + self.dangers,
                        [self.hide_danger] + self.hide_dangers,
                        [self.escape_chance] + self.escape_chances))
                while getch() != 'p':
                    print "Press 'p' to return to the game!"
            elif decision == 'o':
                printHelpScreen(self.getDataForAI("COMBAT"))
                while getch() != 'o':
                    print "Press 'o' to return to the game!"
            else:
                self.messages.append(
                    "That's not a valid command - what will you do?")
            self.printScreen()
            decision = self.user.__move__(self.getDataForAI("COMBAT"))
        return decision

    def playerTurn(self):
        # set environment variables
        self.printScreen()

        self.seerdata.current_block = self.seerdata.get_block()
        will_escape = self.seerdata.get_escape()
        decisions = [x for x in self._getUserMove()]
        playerDamage = 0
        playerAction = ""

        # SWAPPING
        if decisions[0] == '1' or decisions[0] == '2':
            items = self.inventory.get_pack()
            if len(items) == 0:
                self.messages.append("You have no items to swap between!")
                return False

            handChoice = 'Main Hand' if decisions[0] == '1' else 'Off-Hand'
            self.swap_weapon_to = handChoice

            # Print the weapons available to swap to
            validSwap = False
            while not validSwap:
                self.messages.append(
                    'Which weapon do you want to place in your {}?'.format(
                        handChoice))
                itemIndexOffset = 1
                if self.inventory.get_main_hand():
                    itemIndexOffset += 1
                if self.inventory.get_offhand():
                    itemIndexOffset += 1
                for i in range(len(items)):
                    item = items[i]
                    keyPress = 'Press {} to swap to '.format(i +
                                                             itemIndexOffset)
                    weaponMssg = '{0} (Type: {1}, Strength: {2}, Durability: {3})'.format(
                        item['name'], item['type'], item['strength'],
                        item['durability'])
                    self.messages.append(keyPress + weaponMssg)
                self.printScreen()

                try:
                    itemChoice = self.user.__move__(self.getDataForAI('SWAP'))
                    itemChoice = int(itemChoice[0]) - itemIndexOffset
                    self.messages = []
                    if not self.inventory.is_valid_item_index(itemChoice):
                        self.messages.append('Invalid command!')
                        return False
                    elif (handChoice == 'Main Hand' and self.inventory.swap_main_hand(itemChoice)) or \
                            (handChoice == 'Off-Hand' and self.inventory.swap_offhand(itemChoice)):
                        self.messages.append(
                            'Successfully swapped weapon to {}!'.format(
                                handChoice))
                        validSwap = True
                    else:
                        self.messages.append(
                            'You cannot place a {} in your {}!'.format(
                                items[itemChoice]['name'], handChoice))
                        return False
                except ValueError:
                    self.messages.append("Invalid input!")
            if not USE_AI: time.sleep(2)

        # ATTACKING
        elif decisions[0] == 'f':
            self.playerStance = "OFFENSIVE"
            result = self.inventory.use_misc("Fireballs")
            if result:
                playerDamage = ITEM_STRENGTHS["Fireballs"]
                self.messages.append(
                    "You blast the {0} for {1} damage!".format(
                        self.current_enemy.name, playerDamage))
                self.current_enemy.damage(playerDamage)
            else:
                self.messages.append(
                    "You wave your hands around, but nothing happens.")
            return True

        elif decisions[0] == 'x':
            self.playerStance = "OFFENSIVE"
            # are we attacking with a ranged weapon?
            ranged_items = self.inventory.get_equipped_ranged()
            if ranged_items:
                # deal the damage
                playerAction = "shoot"

            # for non-ranged weapons
            else:
                # deal the damage
                playerAction = "hit"

            if self.rangedEncounter and not self.inventory.get_equipped_ranged(
            ):
                # Melee weapon is equipped during ranged encounter, therefore cannot do damage
                return True
            playerDamage = self.inventory.get_damage()
            if (self.rangedEncounter):
                playerDamage *= RANGE_COMBAT_FACTOR

            # deal the damage and update
            totalDamage = max(
                1,  # Force player to do minimum 1 damage
                int(playerDamage * (float(self.inventory.next_attack) / 3)))
            self.current_enemy.damage(totalDamage)
            self.messages.append("You {0} the {1} for {2} damage!".format(
                playerAction, self.current_enemy.name, totalDamage))

            return True

        # ESCAPE
        elif decisions[0] == 'e':
            if not self.escapes_remaining:
                self.messages.append(
                    "You don't have any more Babylon Candles!")
            else:
                self.escapes_remaining -= 1
                if not will_escape:
                    self.messages.append("You failed to escape!")
                else:
                    self.messages.append("You escaped using a Babylon Candle!")
                    self.printScreen()
                    if not USE_AI: time.sleep(1.2)
                    raise Escape()

        # ITEMS
        elif decisions[0] == 'i':
            item_type = "Potions"
            result = self.inventory.use_misc(item_type)
            # TODO: Not yet fully implemented for things other than Potions
            if result:
                self.playerStance = "NEUTRAL"
                self.player.health = min(result + self.player.health,
                                         PLAYER_MAX_HEALTH)
                self.messages.append(
                    "You drank a potion and recovered {0} health!".format(
                        result))
                self.printScreen()
                return True
            else:
                self.messages.append("You don't have any Potions!")
                return False

        # SHIELDING
        elif decisions[0] == 'c':
            # is there a shield equipped?
            shields = self.inventory.get_equipped_defense()
            if shields:
                self.playerStance = "DEFENSIVE"
                self.messages.append("You raised your shield!")
                return True
            else:
                self.messages.append(
                    "You try to raise your shield, only to discover you're not holding one. The {0} looks confused."
                    .format(self.current_enemy.name))
                return True

        # BAD COMMAND
        else:
            assert (False and "Invalid command specified")

    def enemyTurn(self):
        # enemy will of course hit back
        damage = int(
            (float(self.current_enemy.item.strength) * ENEMY_DAMAGE_CONSTANT) *
            self.current_enemy.next_attack)
        # player is shielding
        shield_level = 0
        if self.playerStance == "DEFENSIVE":
            # find the shields the player has
            #shield_level = self.inventory.get_equipped_defense().strength
            shield_level = self.inventory.get_defense()
            self.inventory.check_durability()
        if self.playerStance == "DEFENSIVE" and self.seerdata.current_block:
            self.messages.append("You successfully blocked the enemy attack!")
        else:
            self.player.damage(damage)
            damageType = "hit" if not isinstance(self.current_enemy.item,
                                                 RangedWeapon) else "shoot"
            self.messages.append("The {0} {2}s you for {1} damage!".format(
                self.current_enemy.name, damage, damageType))
        return True

        # escape results

    def _isMssgTooLong(self, currentMessage, messageToAppend):
        return len(currentMessage + messageToAppend) > 159

    def runEvent(self):

        from ai import USE_AI

        self.seerdata.generate_encounter(self.inventory.get_defense(),
                                         self.escape_chance,
                                         self.items_dropped,
                                         is_dorf=("DORF"
                                                  in self.current_enemy.image))
        # Combat loop
        isPlayerTurn = True
        self.messages = []
        if self.player.hiding:
            self.messages.append("A {0} found your hiding place!".format(
                self.current_enemy.name))
        else:
            self.messages.append("A {0} appeared!".format(
                self.current_enemy.name))
        self.playerStance = "NEUTRAL"
        # Assume player will not make a mistake until he does
        success = True
        # Is player or enemy using a bow?
        self.rangedEncounter = False
        self.current_enemy.next_attack = self.seerdata.get_enemy_attack()
        self.inventory.next_attack = self.seerdata.get_player_attack()
        if self.inventory.get_equipped_ranged() or isinstance(
                self.current_enemy.item, RangedWeapon):
            self.rangedEncounter = True

        while not self.current_enemy.isDead() and not self.player.isDead():
            self.printScreen()

            try:
                if self.rangedEncounter:
                    if self.inventory.get_equipped_ranged():
                        while not self.playerTurn():  # Loop on invalid moves
                            self.swap_weapon_to = None  # Clear swap hand state
                            self.printScreen()
                        self.swap_weapon_to = None  # Clear swap hand state
                        if self.inventory.get_equipped_ranged():
                            self.inventory.next_attack = self.seerdata.get_player_attack(
                            )
                        elif self.playerStance == 'OFFENSIVE':
                            self.messages.append(
                                "You swing your weapon wildly, but the {0} isn't close enough. The {0} looks confused..."
                                .format(self.current_enemy.name))
                        self.inventory.check_durability()
                    else:
                        self.messages.append(
                            'You run closer to the {0}...'.format(
                                self.current_enemy.name))
                    if not self.current_enemy.isDead() and isinstance(
                            self.current_enemy.item, RangedWeapon):
                        self.enemyTurn()
                        self.current_enemy.next_attack = self.seerdata.get_enemy_attack(
                        )

                # Player's move
                elif isPlayerTurn:
                    while not self.playerTurn():  # Loop on invalid moves
                        self.swap_weapon_to = None  # Clear swap hand state
                        self.printScreen()
                    self.swap_weapon_to = None  # Clear swap hand state
                    self.inventory.next_attack = self.seerdata.get_player_attack(
                    )
                    self.inventory.check_durability()

                # enemy's move
                else:
                    self.enemyTurn()
                    self.current_enemy.next_attack = self.seerdata.get_enemy_attack(
                    )
                # update
                #self.printScreen()

                # Bow is only useful on the first turn
                if self.rangedEncounter:
                    self.rangedEncounter = False
                    if not self.current_enemy.isDead(
                    ) and not self.player.isDead() and not isinstance(
                            self.current_enemy.item, RangedWeapon):
                        self.messages.append(
                            "The {0} runs closer to you...".format(
                                self.current_enemy.name))
                else:
                    # Change whose turn it is
                    isPlayerTurn = False if isPlayerTurn else True
            except Escape as e:
                self.messages.append("You successfully ran away!")
                self.printScreen()
                return

        # someone died
        if self.current_enemy.isDead():
            self.current_enemy.image = "DEAD_" + self.current_enemy.image
            self.messages.append("You defeated the {0}!".format(
                self.current_enemy.name))
            self.printScreen()

            if self.seerdata.get_drop_chance():
                self.items_dropped += 1
                self.messages.append("The {0} dropped a {1}...".format(
                    self.current_enemy.name, self.current_enemy.item.name))
                self.current_enemy.image = "BLANK_ENEMY"

                items = self.inventory.get_pack()
                pickupMssg = '[1: Place in MH] [2: Place in OH]'
                validOptions = [
                    '1',
                    '2',
                ]
                self.messages.append("Would you like to take this with you?")
                toAppend = ''
                for i in range(len(items)):
                    # Add 3 because MH and OH are 1 and 2, so indexing starts at 3
                    validOptions.append(str(i + 3))
                    toAppend = ' [{0}: Replace {1}]'.format(
                        str(i + 3), items[i]['name'])
                    if self._isMssgTooLong(pickupMssg, toAppend):
                        self.messages.append(pickupMssg)
                        pickupMssg = ''
                        toAppend = toAppend[1:]
                    pickupMssg += toAppend

                # If Space still in inventory, display "Add to inventory"
                if self.inventory.has_inventory_space():
                    validOptions.append('8')
                    toAppend = ' [8: Add to inventory]'
                    if self._isMssgTooLong(pickupMssg, toAppend):
                        self.messages.append(pickupMssg)
                        pickupMssg = ''
                        toAppend = toAppend[1:]
                    pickupMssg += toAppend

                # Always allowed to ignore items
                validOptions.append('9')
                toAppend = ' [9: Ignore]'
                if self._isMssgTooLong(pickupMssg, toAppend):
                    self.messages.append(pickupMssg)
                    pickupMssg = ''
                    toAppend = toAppend[1:]
                pickupMssg += toAppend

                # self.messages.append("[1: Pick up with MH] [2: Pick up with OH] [3: Don't pick up]")
                self.messages.append(pickupMssg)
                self.printScreen()
                y_or_n = self.user.__move__(self.getDataForAI("ITEM"))
                while y_or_n not in validOptions:
                    self.messages.append("Please enter " +
                                         '/'.join(validOptions))
                    self.printScreen()
                    y_or_n = self.user.__move__(self.getDataForAI("ITEM"))
                if y_or_n == '1':
                    # pick up item
                    self.inventory.equip_main_hand(self.current_enemy.item)
                    self.printScreen()
                    if not USE_AI:
                        time.sleep(2)
                elif y_or_n == '2':
                    self.inventory.equip_offhand(self.current_enemy.item)
                    self.printScreen()
                    if not USE_AI:
                        time.sleep(2)
                elif y_or_n == '8':
                    self.inventory.add_to_pack(self.current_enemy.item)
                elif y_or_n != '9':
                    # Items in inventory are keys 3-7
                    self.inventory.replace_item(
                        int(y_or_n) - 3, self.current_enemy.item)

        elif self.player.isDead():
            self.printScreen()
            if not USE_AI: time.sleep(2)
            raise Defeat("You have been defeated.")

    def checkEvent(self):
        pass
        random.seed()

        event_value = random.uniform(0, 1)
        encounter_chance = 0.03 + BASE_ENEMY_ENCOUNTER_CHANCE * self.danger

        if self.player.hiding:
            h_event_value = random.uniform(0, 1)
            h_encounter_chance = 0.03 + BASE_HIDE_ENCOUNTER_CHANCE * self.hide_danger
            if h_event_value <= h_encounter_chance:
                encounter_chance = 1
            else:
                encounter_chance = -1

        if STORY_MODE and self.map.stevendorf and not self.map.boss_fight:
            self.map.boss_fight = True
            self.current_enemy = self.enemy_factory.generateEnemy(
                self.level,
                boss=self.map.stevendorf or self.encounter_sdorf,
                dorfweap=14)
            self.runEvent()

        elif event_value <= encounter_chance and not self.invuln_turns:
            # spawn an enemy TODO generator
            self.current_enemy = self.enemy_factory.get_next_enemy()
            self.runEvent()
            self.current_enemy = None

        if self.invuln_turns: self.invuln_turns -= 1
        self.player.hiding = False

    def _update(self, var, start, end, flex):
        temp_danger = var
        danger_change = random.randint(0, flex)
        up_or_down = random.uniform(0, 1)
        if up_or_down <= DANGER_MODIFIER: temp_danger += danger_change
        else: temp_danger -= danger_change
        if temp_danger > end: temp_danger = end
        elif temp_danger < start: temp_danger = start
        return temp_danger

    def update_danger(self):
        self.dangers.append(self._update(self.dangers[-1], 0, 10, 2))
        self.danger = self.dangers.pop(0)
        self.escape_chances.append(
            self._update(self.escape_chances[-1], 1, 4, 3))
        self.escape_chance = self.escape_chances.pop(0)
        self.hide_dangers.append(self._update(self.hide_dangers[-1], 0, 10, 2))
        self.hide_danger = self.hide_dangers.pop(0)

    def move(self, direction):
        if direction == 'HIDE':
            self.player.hiding = True
            self.checkEvent()
            return 1
        # is there something on this square?
        if self.map.canMove(direction):
            if self.map.mapMove(direction):
                return 2
            self.checkEvent()
            return 1
        return 0
Esempio n. 42
0
class Game(Widget):
    temp_text = StringProperty("")
    temp_textlist = ListProperty(["", "", "", ""])


    def gamesetup(self):
        # Setting up the Event Handler.
        self.events = EventHandler()
        self.events.calls["keydown"] = self.key_down
        self.events.calls["keyup"] = self.key_up
        self.events.calls["mouseover"] = self.mouse_over
        self.events.eventsetup()

        # Setting up the Menu controller.
        self.menus = Menus(size=self.size)
        self.menus.menusetup()

        # Setting up the NPCs.
        self.npcs = NPCController()
        self.npcs.controllersetup()

        # Setting up the Player.
        self.player = Player()
        self.player.playersetup(Window.size)
        self.player.place(Window.center[0], Window.center[1])

        # Setting up the Dialogue controller.
        self.dialogue = Dialogue()
        self.dialogue.dialoguesetup()

        # Setting up the world.
        self.world = World()
        self.world.worldcenter = self.center
        self.world.setupworld((768*3, 608*3))

        # Adding everything to the Widget stack
        self.add_widget(self.events)
        self.world.add_npcs(self.npcs.npcgroup)
        self.world.add_widget(self.player)
        self.add_widget(self.world)
        self.add_widget(self.menus)
        self.add_widget(self.dialogue)

        # Centering Screen on the player
        self.center_screen(0.2)

    def center_screen(self, delay=0.1):
        Clock.schedule_once(self.world.center_screen, delay)

    def update(self, dt):
        self.menus.update(dt)
        self.npcs.update(dt)
        self.player.update(dt)

    def mouse_over(self, pos):
        pass

    def key_down(self, key, mod):
        if key[1] in ("w", "a", "s", "d", "up", "down", "left", "right"):
            self.player.keydown(key[1])
        elif key[1] == "spacebar":
            print(self.player.pos, self.player.center)

    def key_up(self, key):
        if key[1] in ("w", "a", "s", "d", "up", "down", "left", "right"):
            self.player.keyup(key[1])

    def begin_conv(self, npc):
        self.dialogue.npc = npc
        self.dialogue.start_conv()
        self.menus.menu_on = not self.menus.menu_on

    def change_top_text(self, txt):
        """
          Top text area contains only one piece of text at a time.
        """
        self.temp_text = txt
        self.menus.fade_out_top = True

    def change_bottom_text(self, txtlist):
        """
         Bottom Text contains 4 question areas.
        """
        for num, _ in enumerate(self.menus.bottomtext):
            try:
                self.menus.bottomtext[num] = txtlist[num]
            except IndexError:
                self.menus.bottomtext[num] = ""
        self.menus.fade_out_bottom = True
Esempio n. 43
0
def main():
    global SCREEN_WIDTH, SCREEN_HEIGHT, FRAMERATE, BACKGROUND

    # Set win to current window and setup pygame
    win = setup(SCREEN_WIDTH, SCREEN_HEIGHT)

    # Setup pygame clock for framerate
    clock = pygame.time.Clock()

    # Define music
    pygame.mixer.music.load('resources/music.mp3')
    pygame.mixer.music.play(-1)

    # Score counter
    score = 0
    # Wave counter
    wave = 1
    # Deaths counter
    deaths = 0

    # Create an empty list for projectiles
    projectiles = []
    # Create an empty list for enemies
    enemies = []
    # Create an empty list for players
    players = []

    # Setup cooldown for shooting
    shoot_cooldown = 0

    # Create an instance of Player (multiple instances are respawns)
    players.append(Player(x=randint(0, SCREEN_WIDTH - 70), y=410))
    # Create an instance of Enemy
    enemies.append(
        Enemy(x=randint(0, SCREEN_WIDTH - 70),
              y=410,
              start_x=0,
              end_x=SCREEN_WIDTH))

    while True:
        # Framerate
        clock.tick(FRAMERATE)

        if not check_events():
            break

        # Define player as 0th element from array
        try:
            player = players[0]
        except IndexError:
            deaths += 1
            players.append(Player(x=randint(0, SCREEN_WIDTH - 70), y=410))
            player = players[0]

        # Controls
        if player:
            shoot_cooldown = controls(player=player,
                                      projectiles=projectiles,
                                      screen_width=SCREEN_WIDTH - 70,
                                      shoot_cooldown=shoot_cooldown,
                                      max_shoot_cooldown=8 - (wave // 2))

        # Update entities
        enemies, kills = Enemy.update_all(enemies=enemies,
                                          projectiles=projectiles)
        projectiles = Projectile.update_all(projectiles=projectiles,
                                            screen_width=SCREEN_WIDTH)
        players = Player.update_all(players=players, enemies=enemies)

        # Update score
        score += kills

        # Spawn new enemies
        if len(enemies) == 0:
            wave += 1
            for n in range(0, randint(wave, round(wave * 1.5))):
                enemies.append(
                    Enemy(x=randint(0, SCREEN_WIDTH - 70),
                          y=410,
                          start_x=0,
                          end_x=SCREEN_WIDTH))
            # Health increse
            increase = randint(score, score + score * wave // 2)
            player.max_health += increase
            player.health += player.max_health // 2

        # Draw next frame
        redraw_game_window(win=win,
                           background=BACKGROUND,
                           score=score,
                           wave=wave,
                           deaths=deaths,
                           player=player,
                           enemies=enemies,
                           projectiles=projectiles)
Esempio n. 44
0
class Game(DirectObject):
  """initialize"""
  def __init__(self):
    print "______________________"
    print "Class Main"

    base.disableMouse()
    base.camLens.setNear(0.0001)

    # Setup application
    self.keys()
    self.txt = self.info((-1.32, 0.96), title)

    # Initialize classes
    self.grid = None
    self.free_look_camera = None
    self.avatars = None
    self.camera_type = "free_look"
    self.trees = []

    # Initialize World
    self.root = NodePath("rootMain")
    self.root.reparentTo(base.render)

    # Initialize Picker
    self.picker = picker.Picker(self)

    # Initialize Terrain
    self.terrain = terrain.Terrain(self, 65, 2.0, 20.0, 'advanced', False)

    # Initialize Player
    self.player = Player(Filename("avatars/ralph/ralph.egg.pz"))
    self.player.reparentTo(base.render)
    self.player.setScale(0.05)


    # Initialize Cameras
    self.free_look_camera = FreeLookCamera()
    self.first_person_camera = FirstPersonCamera()

    # Initialize Lights
    self.lights = lighting.Lighting(self)

    # Activate Free Look
    self.free_look_camera.activate()

    return

  """info"""
  def info(self, pos, msg):
    self.font = base.loader.loadFont(APP_PATH + 'media/fonts/OCR.otf')
    return OnscreenText(font = self.font, text = msg, style = 1, fg = (1, 1, 1, 1),
                        pos = pos, align = TextNode.ALeft, scale = .035,
                        mayChange = True)


  """keys"""
  def keys(self):
    self.accept('e', self.toggle_wire_frame)
    self.accept('t', self.toggle_texture)
    self.accept('r', self.snapshot)
    self.accept('q', self.switch_camera)
    self.accept('f', self.grow_tree)
    self.accept('escape', sys.exit)
    return

  def collision_traverse(self, task):
    base.cTrav.traverse(base.render)

  def grow_tree(self):
    picked_object, picked_point = self.picker.pick(0.0, 0.0)

    if picked_object is None:
      return
    else:
      tree = SimpleTree(0.01, Vec3(0.05, 0.05, 0.2), picked_point)
      tree.generate()
      self.trees.append(tree)

  def snapshot(self):
    base.screenshot("snapshot")

  def toggle_wire_frame(self):
    base.toggleWireframe()

  def toggle_texture(self):
    base.toggleTexture()

  def switch_camera(self):
    print "Switching Cameras"
    if self.camera_type == "free_look":
      self.free_look_camera.deactivate()

      self.player.activate()
      self.player.setPos(base.camera.getPos())
      self.first_person_camera.activate(False)
      self.first_person_camera.reset_parent(self.player)

      base.taskMgr.add(self.collision_traverse, "ctrav-traverse")
      self.camera_type = "first_person"
    elif self.camera_type == "first_person":
      self.player.deactivate()
      self.first_person_camera.deactivate()
      self.free_look_camera.activate()
      base.taskMgr.remove("ctrav-traverse")
      self.camera_type = "free_look"
    else:
      self.player.deactivate()
      self.first_person_camera.deactivate()
      self.free_look_camera.activate()
      base.taskMgr.remove("ctrav-traverse")
      self.camera_type = "free_look"
Esempio n. 45
0
class OrcInvader(arcade.Window):
    def __init__(self, width, height, title):
        super().__init__(width, height, title)

        self.set_mouse_visible(False)

        arcade.set_background_color(arcade.color.ASH_GREY)

        self.frame_count = 0
        self.player_list = None
        self.player_bullet_list = None
        self.enemy_list = None
        self.enemy_bullet_list = None

        self.player = None
        self.score = 0

        self.current_state = GameState.RUNNING

    def setup(self):
        self.player_list = arcade.SpriteList()
        self.player_bullet_list = arcade.SpriteList()
        self.enemy_list = Enemies.setup(ENEMY_COUNT)
        self.enemy_bullet_list = arcade.SpriteList()

        self.player = Player()
        self.player_list.append(self.player)

    def draw_message(self, text, color):
        arcade.draw_text(text,
                         SCREEN_WIDTH / 2.,
                         SCREEN_HEIGHT / 2.,
                         color,
                         54,
                         align="center",
                         anchor_x="center",
                         anchor_y="center")

    def draw_game(self):
        self.enemy_list.draw()
        self.enemy_bullet_list.draw()
        self.player_list.draw()
        self.player_bullet_list.draw()

        output = f"Score: {self.score}"
        arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)

    def on_draw(self):
        arcade.start_render()
        self.draw_game()

        if self.current_state is GameState.PAUSED:
            self.draw_message("Game Paused", arcade.color.WHITE)
        elif self.current_state is GameState.GAME_OVER:
            self.draw_message("Game Over", arcade.color.RED)
        elif self.current_state is GameState.FINISHED:
            self.draw_message("WON", arcade.color.GREEN)

    def update(self, delta_time):

        if self.current_state is GameState.RUNNING:
            self.player.update()
            self.enemy_list.update()

            hit_list = arcade.check_for_collision_with_list(
                self.player, self.enemy_list)

            if hit_list:
                self.current_state = GameState.GAME_OVER

            self.enemy_bullet_list.update()
            self.player_bullet_list.update()

            if not self.enemy_list:
                self.current_state = GameState.FINISHED

            for enemy in self.enemy_list:
                # use assignment expression once 3.8 is released
                bullet = enemy.shoot()
                if bullet:
                    self.enemy_bullet_list.append(bullet)

                if enemy.top < 0:
                    self.current_state = GameState.GAME_OVER

            for bullet in self.player_bullet_list:

                hit_list = arcade.check_for_collision_with_list(
                    bullet, self.enemy_list)

                if len(hit_list) > 0:
                    bullet.kill()

                for enemy in hit_list:
                    enemy.kill()
                    self.score += 1

                if bullet.bottom > SCREEN_HEIGHT:
                    bullet.kill()

            for bullet in self.enemy_bullet_list:

                hit_list = arcade.check_for_collision_with_list(
                    bullet, self.player_list)

                if hit_list:
                    self.current_state = GameState.GAME_OVER

                if bullet.top < 0:
                    bullet.kill()

    def on_key_press(self, key, modifiers):
        if key == arcade.key.LEFT:
            self.player.change_x = -MOVEMENT_SPEED
        elif key == arcade.key.RIGHT:
            self.player.change_x = MOVEMENT_SPEED
        elif key == arcade.key.SPACE:
            self.player_bullet_list.append(self.player.shoot())
        elif key == arcade.key.P:
            self.toggle_pause()
        elif key == arcade.key.Q:
            sys.exit()

    def on_key_release(self, key, modifiers):
        if key == arcade.key.LEFT or key == arcade.key.RIGHT:
            self.player.change_x = 0

    def toggle_pause(self):
        if self.current_state is GameState.PAUSED:
            arcade.start_render()
            self.current_state = GameState.RUNNING
        else:
            arcade.finish_render()
            self.current_state = GameState.PAUSED