def murder(self, player, list_of_players):
        if len(list_of_players) == 1:
            print("SORRY there are no other players with influences to murder")
            return 0

        player.coins = -3
        choose_person = []
        counter = 0
        for person in (list_of_players):
            if person.status != "Playing":
                choose_person.append(person)
                print(
                    "You can MURDER an INFLUENCE of {} by pressing {}".format(
                        person, counter))
                counter += 1

        print(
            "Enter the number of the person's influence you want to murder: ")
        murder_person = Console.cast(0, counter)

        print("PASS the computer to {}".format(
            choose_person[murder_person].name))
        input("PRESS ANY KEY to continue")
        Console.clear()
        choose_person[murder_person].resign_card()
        print("Player {} now has {} coins".format(player.name, player.coins))
Beispiel #2
0
 def __set_players(cls):
     for i in range(1, cls.NUMBER_OF_PLAYERS + 1):
         name = Console.get_str_input_with_args(
             '\nWrite player\'s {} name: ', [i])
         cls.__players.append(Player(name, i))
     cls.__actual_player = cls.__players[0]
     Console.clear()
Beispiel #3
0
    def __ask_players_to_challenge(cls):

        challenge = [False,0]  

        if cls.__actual_player.choosen_action in [
                'Tax', 'Exchange', 'Steal', 'Assassinate'
        ]:
            Console.print_str('    * CHALLENGING PHASE * ')
            for i in range(len(cls.__players)):

                if cls.__players[i] != cls.__actual_player and challenge[
                        0] == False:

                    while True:
                        answer = Console.get_str_input_with_args(
                            '\n* {}, you wanna challenge player {}  * [ Yes / No ] \n',
                            [cls.__players[i].name, cls.__actual_player.name])

                        if answer == 'Yes' or answer == 'No':
                            if answer == 'Yes':
                                challenge[0] = True
                                challenge[1] = i
                            break
                        else:
                            Console.print_str(
        
                                '\n * You answer isn´t valid * \n')
        Console.clear()                       
        return challenge
    def play(cls):
        cls.__set_players()
        cls.__set_deck()
        for player in cls.__players:
            cls.__table_deck.assign_cards_player(player, 2,
                                                 cls.__table_deck.deck)
        cls.__number_of_players = len(cls.__players)

        #We let everybody see their cards by turns
        print(
            "\nOn this first round every player will get to SEE THEIR CARDS.")
        for player in cls.__players:
            player.status = "Playing"
            print("PASS computer to {}".format(player))
            input("PLAYER {} PRESS ANY KEY to see your cards".format(player))
            player.see_cards()
            input("PRESS ANY KEY to continue")
            Console.clear()
            player.status = None

        #To not begin first round inmediately:
        print("Pass the computer to {}".format(cls.__players[0]))
        input("NOW THE GAME BEGINS: press enter ")

        while len(cls.__players) > 1:
            for player in cls.__players:
                if (player == cls.__current_player):
                    continue
                cls.__current_player = player
                cls.__player_play()
                cls.__remove_player()

        print("{} there are NO MORE PLAYERS left, YOU WON!!".format(
            cls.__players[0]))
Beispiel #5
0
class Walk(object):
  KeyMap = {
    "h": Coord(-1,  0), "j": Coord(0,  1), "k": Coord(0, -1), "l": Coord(1, 0),
    "y": Coord(-1, -1), "u": Coord(1, -1), "b": Coord(-1, 1), "n": Coord(1, 1)
  }

  def __init__(self):
    self._coord = Coord(1, 1)
    self._console = Console().colorOn().nonBlocking()

  def run(self):
    self.render()
    interval = int(1000/30)
    while True:
      self.update()
      self._console.sleep(interval)

  def update(self):
    key = self._console.getKey()
    self._coord += Walk.KeyMap.get(key, Coord(0, 0))
    self.render()

  def render(self):
    self._console.clear()
    self._console.move(Coord(1, 2)).write("+", Color.LIGHT_YELLOW)
    self._console.move(Coord(3, 4)).write("T", Color.GREEN, Color.BLUE)
    self._console.move(Coord(5, 6)).write("*", Color.LIGHT_YELLOW, Color.GREEN)
    self._console.move(Coord(7, 8)).write("&", random.choice(list(Color.LIST)))
    self._console.move(self._coord).write("@", Color.LIGHT_YELLOW).move(self._coord)
Beispiel #6
0
 def resign_card(self):
     print("{} you ought to resign a card".format(self.__name))
     self.status = "Playing"
     self.see_cards()
     print("Press the NUMBER of the card you want to resign: ")
     card_resigned = Console.cast(0, len(self.cards))
     self.cards[card_resigned - 1].out_of_game = True
     self.status = None
     Console.clear()
Beispiel #7
0
 def see_cards_option(self):
     print("=======================")
     print("PRESS 1 if you wish to SEE YOUR CARDS AGAIN. 0 if you don't.")
     print("You get this choice ONCE before choosing your action!")
     print("=======================")
     number = Console.cast(0, 1)
     if number == 1:
         self.see_cards()
         input("To continue: press enter")
         Console.clear()
     else:
         return
Beispiel #8
0
 def money_to_play(self, choice):
     if (self.__coins >= 10 and choice != 3):
         print("You have 10 COINS. You MUST CHOOSE HIT")
         return 0
     if (self.__coins < 7 and choice == 3):
         Console.clear()
         print("\n==== NOT ENOUGH COINS for Hit. Try again. =====")
         return 0
     if (self.__coins < 3 and choice == 5):
         Console.clear()
         print("\n==== NOT ENOUGH COINS for Murder. Try again. =====")
         return 0
     return 1
    def __challenge(cls, player, action):
        print("• Does anybody want to DEFY this action? •")
        challengers = []
        for other_player in cls.__players:
            if other_player.status != "Playing":
                add = input(
                    "-> {} press 1 if you want to CHALLENGE, press enter otherwise "
                    .format(other_player))
                if add == "1":
                    challengers.append(other_player)
        if len(challengers) == 0:
            print("\n– NOBODY CHALLENGED YOU! –\n")
            return 0
        shuffle(challengers)
        challenger = challengers[0]
        action.activity_log.append("{} CHALLENGED {}".format(
            challenger, player))
        print("• {} you have been CHALLENGED by {} •".format(
            player, challenger))
        win = False
        influence = cls.__dic_of_influences[action.action_status]

        #when winning a challenge your card gets inmediatly replaced wit one on the deck
        for card in player.cards:
            if (card.out_of_game == False):
                if card.influence == influence:
                    win = True
                    cls.__table_deck.deck.append(card)
                    player.cards.remove(card)
                    cls.__table_deck.assign_cards_player(
                        player, 1, cls.__table_deck.deck)

        if win == True:
            print("!! {} you have WON the challenge !!".format(player))
            input("press ANY KEY to see your new card")
            player.see_cards()
            input("press ANY KEY to continue AND PASS computer to {}".format(
                challenger))
            Console.clear()
            challenger.resign_card()
            action.activity_log.append(
                "{} lost the challenge".format(challenger))
            action.action_succes = True
        else:
            print("• {} you have LOST the challenge •".format(player))
            action.action_succes = False
            action.activity_log.append("{} lost the challenge".format(player))
            input("press ANY KEY to CONTINUE")
            Console.clear()
            player.resign_card()
Beispiel #10
0
    def __ask_actual_player_to_challenge(cls):

        Console.print_str('    * CHALLENGING PHASE * \n ')
        challenge = False
        while True:
            answer = Console.get_str_input_with_args(
                '\n* {}, want you to challenge?* [ Yes / No ] \n',
                [cls.__actual_player.name])

            if answer == 'Yes' or answer == 'No':
                if answer == 'Yes':
                    challenge = True

                break
            else:
                Console.print_str('\n * You answer isn´t valid * \n')
        return challenge
        Console.clear()
Beispiel #11
0
 def __player_play(cls):
     Console.clear()
     Console.print_str_with_args('Turn of player {}\n\n',
                                 [cls.__current_player.name])
     Console.print_str(str(cls.__board))
     Console.print_str('\n\nPoints:')
     Console.print_str_with_args('{}: {} | {}: {}\n', [
         cls.__players[0].name, cls.__players[0].score,
         cls.__players[1].name, cls.__players[1].score
     ])
     if len(cls.__current_player.selected_coords) < 2:
         cls.__current_player.selected_coords.append([
             int(number) for number in Console.get_str_input(
                 'Select a card entering the '
                 'coords separeted by comma: ').split(',')
         ])
         cls.__board.show_card(cls.__current_player.selected_coords[-1])
     else:
         Console.get_str_input('Press any key to continue...')
Beispiel #12
0
class FovDemo(object):
    KeyMap = {
        "h": direction.W,
        "j": direction.S,
        "k": direction.N,
        "l": direction.E,
        "y": direction.NW,
        "u": direction.NE,
        "b": direction.SW,
        "n": direction.SE
    }

    def __init__(self):
        self._hero = (1, 1)
        self._console = Console()
        self._map = Map()
        self._fov = Fov(self._map.isFloor, 5)

    def run(self):
        while True:
            self.update()

    def update(self):
        self.render()
        key = self._console.getKey()
        self.moveHero(self.KeyMap.get(key, (0, 0)))

    def moveHero(self, dir):
        nextCoord = coord.sum(self._hero, dir)
        if self._map.isWall(nextCoord): return
        self._hero = nextCoord

    def render(self):
        self._console.clear()
        self._map.render(self._console)
        self.renderFov()
        self._console.move(self._hero).write("@").move(self._hero)

    def renderFov(self):
        for c in self._fov.compute(self._hero):
            if self._map.isFloor(c) and self._map.isInBound(c):
                self._console.move(c).write('.')
    def hit(self, player, list_of_players):
        if len(list_of_players) == 1:
            print("SORRY there are no other players to HIT")
            return 0

        player.coins = -7
        choose_person = []
        counter = 0
        for person in (list_of_players):
            if person.status != "Playing":
                choose_person.append(person)
                print("You can take a HIT on {} by pressing {}".format(
                    person, counter))
                counter += 1
        print("Enter the NUMBER of the person you want to hit: ")
        hit_person = Console.cast(0, counter)

        print("PASS the computer to {}".format(choose_person[hit_person].name))
        input("PRESS ANY KEY to continue")
        Console.clear()
        choose_person[hit_person].resign_card()
Beispiel #14
0
class AStarDemo(object):
  KeyMap = {
    "h": direction.W, "j": direction.S, "k": direction.N, "l": direction.E,
    "y": direction.NW, "u": direction.NE, "b": direction.SW, "n": direction.SE
  }

  def __init__(self):
    self._cursor = (1, 1)
    self._start = (1, 1)
    self._goal = (33, 8)
    self._console = Console()
    self._map = Map()
    self._astar = AStar(self._map.cost)

  def run(self):
    while True:
      self.update()

  def update(self):
    self.render()
    key = self._console.getKey()
    if key in self.KeyMap:
      self._cursor = coord.sum(self._cursor, self.KeyMap.get(key))
    else:
      self.putTerrain(key)

  def putTerrain(self, key):
    if key not in (' ', '"', '=', '#') : return
    self._map.put(self._cursor, key)

  def render(self):
    self._console.clear()
    self._map.render(self._console)
    self._renderRoute()
    self._console.move(self._cursor)

  def _renderRoute(self):
    for c in self._astar.compute(self._start, self._goal):
      self._console.move(c).write('*')
Beispiel #15
0
    def __check_actual_player(cls):
        NUMBER = 0
        Elimination_list = []
        for i in range(cls.NUMBER_OF_PLAYERS):
            if len(cls.__players[i].hand_of_cards) == 0:
                Console.clear()
                Console.print_str_with_args("{}, has been eliminated",[cls.__players[i]])
                Elimination_list.append(i)
                Console.clear()  
                
            if cls.__players[i].number == cls.__actual_player.number:
                NUMBER = i

        if NUMBER == (cls.NUMBER_OF_PLAYERS - 1):
            cls.__actual_player = cls.__players[0]
        else:
            cls.__actual_player = cls.__players[NUMBER + 1]

        if len(Elimination_list) > 0:
            for number in Elimination_list:
                cls.__players.remove(cls.__players[number])
                cls.NUMBER_OF_PLAYERS -= 1
Beispiel #16
0
    def __choose_the_action(cls):

        Console.print_str_with_args(
            '* TURN OF PLAYER {} *\n\n\n* Your influences are: *\n     ',
            [cls.__actual_player.name])
        Console.print_list(cls.__actual_player.hand_of_cards)     
 
        all_actions = ['Income', 'Foreign Aid', 'Tax', 'Exchange', 'Steal']

        if cls.__actual_player.coins >= 10: 
            cls.__actual_player.choosen_action = 'Coup'

        else:
            if cls.__actual_player.coins >= 7: 
                all_actions.append('Coup')

            if cls.__actual_player.coins >= 3:
                all_actions.append('Assassinate')

            Console.print_str('\n* Take one action: * \n ')
            Console.print_list(all_actions)  

            while True:
                action = Console.get_str_input('\n* Select your action *\n')
                if action in all_actions:

                    break
                else:
                    Console.print_str(
                        '* Wrong action, please choose again * \n')

            Console.print_str_with_args('\n* {} took the action: {} *\n',
                                        [cls.__actual_player.name, action])

            cls.__actual_player.choosen_action = action

        Console.clear()
Beispiel #17
0
    def __counter_action(cls):

        counteratackking = [False, 0]
        counter_actions = [
            'Block-Foreign Aid', 'Block-Stealing', 'Block-Assassination'
        ]
        Console.clear()
        Console.print_str("     *  COUNTERING PHASE  * \n")
        for i in range(len(cls.__players)):
            if cls.__players[i] != cls.__actual_player:
                while True:
                    answer = Console.get_str_input_with_args(
                        '\n* {}, do you want to counter {}  * [ Yes / No ] \n',
                        [cls.__players[i].name, cls.__actual_player.name])
                    if answer == 'Yes' or answer == 'No':
                        if answer == 'Yes':
                            while True:
                                Console.print_str('\n * SELECT YOU COUNTER *\n  ')
                                Console.print_list(counter_actions)
                                counteraction = Console.get_str_input('')
                                if counteraction in counter_actions:
                                    cls.__players[
                                        i].choosen_action = counteraction
                                    counteratackking[0] = True
                                    counteratackking[1] = i
                                    break
                                else:
                                    Console.print_str(
                                        '* Wrong counter, please choose again * \n'
                                    )
                            break
                        elif answer == 'No':
                            break
                    else:
                        Console.print_str('\n * You answer isn´t valid * \n')
        return counteratackking
Beispiel #18
0
class LineDemo(object):
    KeyMap = {
        "h": direction.W,
        "j": direction.S,
        "k": direction.N,
        "l": direction.E,
        "y": direction.NW,
        "u": direction.NE,
        "b": direction.SW,
        "n": direction.SE
    }

    def __init__(self):
        self._target = (1, 1)
        self._center = (10, 10)
        self._console = Console()

    def run(self):
        while True:
            self.update()

    def update(self):
        self.render()
        key = self._console.getKey()
        self.moveTarget(self.KeyMap.get(key, (0, 0)))

    def moveTarget(self, dir):
        self._target = coord.sum(self._target, dir)

    def render(self):
        self._console.clear()
        self._console.move(self._center).write('@')
        self._console.move(self._target).write('X')
        for c in coord.line(self._center, self._target):
            self._console.move(c).write('.')
        self._console.move(self._target)
    def defy_counterattack(self,list_of_players,player,action,table_deck):
        print("\nDoes anybody want to DEFY this COUNTERATTACK?")
        challengers=[]
        for other_player in list_of_players:
            if other_player.status!="Challenging":
                add=input("{} PRESS 1 if you want to CHALLENGE, press any other key otherwise ".format(other_player))
                if add=="1":
                    challengers.append(other_player)
        if len(challengers)==0:
            action.action_succes=False
            print("Nobody challenged you")
            self.master_of_counterattack(player,self.__adversary,action.action_status)
            return 0
        shuffle(challengers)
        challenger=challengers[0]
        action.activity_log.append("{} challenged {}'s counterattack".format(challenger,self.__adversary))
        print("{} you have been CHALLENGED by {}".format(self.__adversary,challenger))
        win=False
        for card in self.adversary.cards:
            if (card.out_of_game==False and card.influence==self.__character):
                win=True
                print("{} you have WON the CHALLENGE and get to complete the counterattack".format(self.__adversary))
                action.activity_log.append("{} won challenge and got to complete counterattack".format(self.__adversary))
                table_deck.deck.append(card)
                self.__adversary.cards.remove(card)
                table_deck.assign_cards_player(self.__adversary,1,table_deck.deck)
                input("{} press ANY KEY to see your new card".format(self.__adversary))
                self.__adversary.see_cards()
                input("PASS computer to {} AND PRESS ANY KEY to continue".format(challenger))
                Console.clear()
                challenger.resign_card()
                Console.clear()
                action.action_succes=False
                self.master_of_counterattack(player,self.__adversary,action.action_status)
        
        if win==False:
            print("{} you have LOST the CHALLENGE".format(self.__adversary))
            action.activity_log.append("{} won the challenge and got to stop the counterattack".format(challenger))
            input("PASS computer to {} AND PRESS ANY KEY to continue".format(self.__adversary))
            Console.clear()
            self.__adversary.resign_card()
            Console.clear()

        self.__adversary.status=None
    def __player_play(cls):
        Console.clear()
        print("It's {}'s turn!".format(cls.__current_player))
        cls.__current_player.status = "Playing"
        cls.__current_player.see_cards_option()
        flag = 0
        while (flag == 0):
            cls.__see_coins_and_cards()
            choice = Console.player_menu(cls.__current_player.name)
            flag = cls.__current_player.money_to_play(choice)

        action = Action()
        action.action_status = cls.__list_of_actions[choice - 1]
        action.action_succes = True
        action.activity_log = []
        input("PRESS ANY KEY and PASS the computer to the other players")
        Console.clear()
        Console.show_last_action(cls.__current_player.name,
                                 action.action_status)
        action.activity_log.append("{} chose the action {}".format(
            cls.__current_player, action.action_status))

        if (choice != 1 and choice != 2 and choice != 3):
            cls.__challenge(cls.__current_player, action)
        cls.__remove_player()
        if action.action_succes == True:
            if (choice == 2 or choice == 5 or choice == 6):
                result = cls.__counterattack(cls.__current_player,
                                             action.action_status)
                if result != 0:
                    action.activity_log.append("{} counterattacked {}".format(
                        result[0], cls.__current_player))
                    new_counterattack = Counterattack(result[0], result[1])
                    new_counterattack.defy_counterattack(
                        cls.__players, cls.__current_player, action,
                        cls.__table_deck)

        cls.__remove_player()
        if (action.action_succes == True):
            print(". : Now {} gets to complete their action : .".format(
                cls.__current_player))
            action.activity_log.append(
                "{} got to complete the action {}".format(
                    cls.__current_player, action.action_status))
            action.master_of_actions(choice, cls.__current_player,
                                     cls.__players, cls.__table_deck.deck)
        cls.__current_player.status = None
        input("Press ENTER to continue")
        Console.clear()
        Console.show_log(cls.__current_player, action.activity_log)
        input("END OF TURN, PRESS ENTER to continue")
Beispiel #21
0
    def take_pictures(self):
        Console.clear()
        print('Preparing ...')
        sleep(2)
        # flushes input buffer to prevent user input concatenation with previously pressed keys
        stdout.flush()
        tcflush(stdin, TCIOFLUSH)
        Console.clear()

        # Q1
        email = input("What's email address?\n")

        # password loop to make sure user is entering the correct one.
        while True:
            password1 = getpass.getpass(
                "Set up your password (min 6 chars).\n")
            password2 = getpass.getpass("Repeat your password.\n")
            if password1 == password2:
                break

        # create firebase credentials
        self._fb.create_user(email, password1)

        # time countdown before take the picture (5s)
        ct = 5
        Console.clear()
        while ct > 0:
            print(
                'Please look at the camera now. We will take a few pictures in: %s'
                % ct)
            sleep(1)
            ct = ct - 1
            os.system('clear')

        # check if folder already exists
        if os.path.exists('user') is False:
            os.mkdir('user')

        # get random id and if exists re-randomize again
        user_id = random.SystemRandom().randint(10000, 99999)
        while True:
            if os.path.exists('user/%s' % user_id) is False:
                os.mkdir('user/%s' % user_id)
                self._fb.update_data({"users/%s" % user_id: email})
                break
            else:
                user_id = random.SystemRandom().randint(10000, 99999)

        counter = 0  # will count pictures which were taken

        # taking user's pictures
        while True:
            ret, frame = self._video.read(
            )  # ret - bool, frame - current camera frame
            gray = self._convert_to_grey(frame)  # convert picture to greyscale
            faces = self._cascade.detectMultiScale(gray, 1.3,
                                                   5)  # detect faces

            # iterate through detected
            for (x, y, w, h) in faces:
                cv2.imwrite("user/%s/%s.jpg" % (user_id, counter),
                            gray[y:y + h, x:x + w])

                counter = counter + 1
            if counter == 10:  # at the 10th picture stop
                self.train_faces()  # run train algorithm

                # print successful message
                Console.clear()
                print('Your profile was created! Thanks!')
                sleep(3)

                # update broker and system with the information on registration
                self._fb.update_data({"registration_on_progress": False})
                self.is_registration_on = False
                # show a regular message on the display
                Console.show_reg_msg()
                break
Beispiel #22
0
class ConsoleOutput:
    PENDING = 0
    INPROGRESS = 1
    COMPLETE = 2

    start = None
    fp = None
    console = None
    pos = 0
    tier = None
    dirs = None
    export_counts = None
    libs_counts = None
    failed = False
    lines = []
    throbber = ['-', '\\', '|', '/']
    throbpos = 0

    def __init__(self, fp):
        self.console = Console(fp)
        self.fp = fp
        # Reset the display
        self.console.clear_title()
        self.console.reset_color()
        self.console.clear()
        # Clear the screen and go to the top left
        self.start = datetime.now()
        self.fp.write("Build started at %s\n" %
                      self.start.strftime("%H:%M:%S"))
        self.console.go_right(79)

    def destroy(self):
        now = datetime.now()
        delta = (now - self.start).seconds
        delta, seconds = divmod(delta, 60)
        hours, minutes = divmod(delta, 60)
        if not self.failed:
            self._go_to_end()
            self.console.clear_title()
            self.console.reset_color()
            self.fp.write("\nBuild completed at %s taking %d:%02d:%02d\n\n" %
                          (now.strftime("%H:%M:%S"), hours, minutes, seconds))
        else:
            self.fp.write("\nBuild failed at %s taking %d:%02d:%02d\n\n" %
                          (now.strftime("%H:%M:%S"), hours, minutes, seconds))

    def _go_to_pos(self, pos):
        self._clear_throbber()
        self.console.go_to_pos(pos)
        self.console.go_linehome()

    def _go_to_end(self):
        self._go_to_pos(0)

    def _color_for_state(self, state, count=0):
        if state == self.COMPLETE:
            return self.console.GREEN
        if state == self.INPROGRESS or count > 0:
            return self.console.YELLOW
        return self.console.RED

    def _print_tier_line(self, export_state, export_count, libs_state,
                         libs_count, name):
        self.console.set_color(
            self._color_for_state(export_state, export_count))
        self.fp.write("  export ")
        if export_count > 0:
            self.fp.write("[%2s]      " % export_count)
        else:
            self.fp.write("          ")
        self.console.set_color(self._color_for_state(libs_state, libs_count))
        self.fp.write("libs ")
        if libs_count > 0:
            self.fp.write("[%2s]      " % libs_count)
        else:
            self.fp.write("          ")
        self.console.reset_color()
        self.fp.write("%-45s" % name)
        self._draw_throbber()

    def _print_tools_line(self, state, count, name):
        self.console.set_color(self._color_for_state(state, count))
        self.fp.write("  %s " % name)
        if count > 0:
            self.fp.write("[%2s]" % count)
        else:
            self.fp.write("    ")
        self.console.reset_color()
        self.console.go_right(79 - (7 + len(name)))
        self._draw_throbber()

    def _draw_throbber(self):
        self.console.go_left(1)
        self.fp.write(self.throbber[self.throbpos])
        self.throbpos = (self.throbpos + 1) % len(self.throbber)

    def _clear_throbber(self):
        self.console.go_left(1)
        self.fp.write(" ")

    def start_prebuild(self):
        self._go_to_end()
        self.console.reset_color()
        self.fp.write("\nprebuild:\n")

    def start_configure(self, name):
        self._go_to_end()
        self.console.set_title("prebuild %s" % name)
        self.console.set_color(self._color_for_state(self.INPROGRESS, 0))
        self.fp.write("  %s\n" % name)
        self.console.reset_color()
        self.console.go_up(1)
        self.console.go_right(79)
        self._draw_throbber()

    def finish_configure(self, name):
        self.console.go_linehome()
        self.console.set_color(self._color_for_state(self.COMPLETE))
        self.fp.write("  %-77s" % name)
        self.console.reset_color()
        self._draw_throbber()

    def start_tier(self, name, dirs):
        self._go_to_end()
        self.console.reset_color()
        self.fp.write("\ntier %s - %s dirs:\n" % (name, len(dirs)))
        self.tier = name
        self.dirs = dirs
        self.export_counts = dict()
        self.libs_counts = dict()
        for dir in dirs:
            self.export_counts[dir] = 0
            self.libs_counts[dir] = 0
            self._print_tier_line(self.PENDING, 0, self.PENDING, 0, dir)
            self._clear_throbber()
            self.fp.write("\n")
        self.console.go_up(len(dirs))
        self.console.go_right(79)

    def start_exports(self, dir):
        pos = self.dirs.index(dir)
        self._go_to_pos(pos - len(self.dirs))
        self.console.set_title("%s export [%d/%d] %s" %
                               (self.tier, pos + 1, len(self.dirs), dir))
        self._print_tier_line(self.INPROGRESS, self.export_counts[dir],
                              self.PENDING, self.libs_counts[dir], dir)

    def start_export_subdir(self, dir):
        pos = self.dirs.index(dir)
        self._go_to_pos(pos - len(self.dirs))
        self.export_counts[dir] += 1
        self._print_tier_line(self.INPROGRESS, self.export_counts[dir],
                              self.PENDING, self.libs_counts[dir], dir)

    def finish_exports(self, dir):
        pos = self.dirs.index(dir)
        self._go_to_pos(pos - len(self.dirs))
        self._print_tier_line(self.COMPLETE, self.export_counts[dir],
                              self.PENDING, self.libs_counts[dir], dir)

    def start_libs(self, dir):
        pos = self.dirs.index(dir)
        self._go_to_pos(pos - len(self.dirs))
        self.console.set_title("%s libs [%d/%d] %s" %
                               (self.tier, pos + 1, len(self.dirs), dir))
        self._print_tier_line(self.COMPLETE, self.export_counts[dir],
                              self.INPROGRESS, self.libs_counts[dir], dir)

    def start_libs_subdir(self, dir):
        pos = self.dirs.index(dir)
        self._go_to_pos(pos - len(self.dirs))
        self.libs_counts[dir] += 1
        self._print_tier_line(self.COMPLETE, self.export_counts[dir],
                              self.INPROGRESS, self.libs_counts[dir], dir)

    def finish_libs(self, dir):
        pos = self.dirs.index(dir)
        self._go_to_pos(pos - len(self.dirs))
        self._print_tier_line(self.COMPLETE, self.export_counts[dir],
                              self.COMPLETE, self.libs_counts[dir], dir)

    def start_tools(self, name, dirs):
        self._go_to_end()
        self.console.reset_color()
        self.fp.write("\ntools tier %s - %s dirs:\n" % (name, len(dirs)))
        self.tier = name
        self.dirs = dirs
        self.libs_counts = dict()
        for dir in dirs:
            self.libs_counts[dir] = 0
            self._print_tools_line(self.PENDING, 0, dir)
            self._clear_throbber()
            self.fp.write("\n")
        self.console.go_up(len(dirs))
        self.console.go_right(79)
        self._draw_throbber()

    def start_tools_dir(self, dir):
        pos = self.dirs.index(dir)
        self._go_to_pos(pos - len(self.dirs))
        self.console.set_title("%s tools [%d/%d] %s" %
                               (self.tier, pos + 1, len(self.dirs), dir))
        self._print_tools_line(self.INPROGRESS, self.libs_counts[dir], dir)

    def start_tools_subdir(self, dir):
        pos = self.dirs.index(dir)
        self._go_to_pos(pos - len(self.dirs))
        self.libs_counts[dir] += 1
        self._print_tools_line(self.INPROGRESS, self.libs_counts[dir], dir)

    def finish_tools_dir(self, dir):
        pos = self.dirs.index(dir)
        self._go_to_pos(pos - len(self.dirs))
        self._print_tools_line(self.COMPLETE, self.libs_counts[dir], dir)

    def error(self):
        if self.failed:
            return
        self.failed = True
        self._go_to_end()
        self.console.clear_title()
        self.console.reset_color()
        self.fp.write("\n")
        for line in self.lines:
            self.fp.write(line)

    def build_log(self, line):
        self.fp.flush()
        #time.sleep(0.005)
        if self.failed:
            self.fp.write(line)
        else:
            self._draw_throbber()
            if len(self.lines) == 5:
                self.lines.pop(0)
            self.lines.append(line)
Beispiel #23
0
    def __execute_action(cls): 
        if cls.__actual_player.choosen_action != '':
            Console.print_str_with_args('    *{} Effect* \n ',
                [cls.__actual_player.choosen_action])

            if cls.__actual_player.choosen_action == 'Income':  # INCOME
                cls.__Income(cls.__actual_player)
                Console.print_str_with_args(
                    '\n*{} has {} coins now *\n',
                    [cls.__actual_player, cls.__actual_player.coins])

            elif cls.__actual_player.choosen_action == 'Foreign Aid':  # FOREIGN AID
                counter = cls.__counter_action()
                if counter[0] == True:
                    Console.print_str_with_args(
                        '\n*{} counter-atack with {} *\n', [
                            cls.__players[counter[1]],
                            cls.__players[counter[1]].choosen_action
                        ])

                    challenge = cls.__ask_actual_player_to_challenge()
                    if challenge == True:
                        cls.__challenge(cls.__players[counter[1]],
                                        cls.__actual_player)
                    else:
                        cls.__Foreign_aid(cls.__actual_player)
                        Console.print_str_with_args(
                            '\n*{} has {} coins now *\n',
                            [cls.__actual_player, cls.__actual_player.coins])
                else:
                    cls.__Foreign_aid(cls.__actual_player)
                    Console.print_str_with_args(
                        '\n*{} has {} coins now *\n',
                        [cls.__actual_player, cls.__actual_player.coins])

            elif cls.__actual_player.choosen_action == 'Coup':  ### COUP
                Target_number = cls.__choosen_player_to_attack()
                cls.__Coup(cls.__actual_player, cls.__players[Target_number], cls.__deck)
                Console.print_str_with_args(
                    '\n*{} made a Coup, he has {} coins now *\n',
                    [cls.__actual_player.name, cls.__actual_player.coins])

            elif cls.__actual_player.choosen_action == 'Tax':  ### TAX
                cls.__Duke_act(cls.__actual_player)
                Console.print_str_with_args(
                    '\n*{} has {} coins now *\n',
                    [cls.__actual_player, cls.__actual_player.coins])

            elif cls.__actual_player.choosen_action == 'Assassinate':  ### ASSASSINATE
                Target_number = cls.__choosen_player_to_attack()
                counter = cls.__counter_action()
                if counter[0] == True:
                    Console.print_str_with_args(
                        '\n*{} counter-atack with {} *\n', [
                            cls.__players[counter[1]],
                            cls.__players[counter[1]].choosen_action
                        ])

                    challenge = cls.__ask_actual_player_to_challenge()
                    if challenge == True:
                        cls.__challenge(cls.__players[counter[1]],
                                        cls.__actual_player)
                    else:
                        cls.__Assassin_act(cls.__actual_player,
                                        cls.__players[Target_number], cls.__deck)
                        Console.print_str_with_args(
                            '\n*{} has murder a influence of  {} *\n',
                            [cls.__actual_player, cls.__players[Target_number]])
                else:
                    cls.__Assassin_act(cls.__actual_player,
                                    cls.__players[Target_number], cls.__deck)
                    Console.print_str_with_args(
                        '\n*{} has murder a influence of  {} *\n',
                        [cls.__actual_player, cls.__players[Target_number]])

            elif cls.__actual_player.choosen_action == 'Exchange':  ### EXCHANGE
                cls.__Ambassador_act(cls.__actual_player, cls.__deck)
                Console.print_str_with_args(
                    '\n*{} hand of card:  *\n',
                    [cls.__actual_player])
                Console.print_list(cls.__actual_player.hand_of_cards)

            elif cls.__actual_player.choosen_action == 'Steal':  ## STEAL
                Target_number = cls.__choosen_player_to_attack()
                counter = cls.__counter_action()
                if counter[0] == True:
                    Console.print_str_with_args(
                        '\n*{} counter-atack with {} *\n', [
                            cls.__players[counter[1]],
                            cls.__players[counter[1]].choosen_action
                        ])

                    challenge = cls.__ask_actual_player_to_challenge()
                    if challenge == True:
                        cls.__challenge(cls.__players[counter[1]],
                                        cls.__actual_player)
                    else:
                        cls.__Captain_act(cls.__actual_player, cls.__players[Target_number])
                        Console.print_str_with_args(
                            '\n*{} steal some coins, he has {} coins now *\n',
                            [cls.__actual_player, cls.__actual_player.coins])
                else:
                    cls.__Captain_act(cls.__actual_player,cls.__players[Target_number])
                    Console.print_str_with_args(
                        '\n*{} steal some coins, he has {} coins now *\n',
                        [cls.__actual_player, cls.__actual_player.coins])

            Console.clear()
Beispiel #24
0
    def __challenge(cls, player_challenged,challenger):  

        possible_actions = ['Income', 'Foreign Aid']
        for card in player_challenged.hand_of_cards:
            if card == 'Duke':
                possible_actions.append('Tax')
                possible_actions.append('Block-Foreign Aid')
            elif card == 'Ambassador':
                possible_actions.append('Exchange')
                possible_actions.append('Block-Stealing')
            elif card == 'Captain':
                possible_actions.append('Steal')
                possible_actions.append('Block-Stealing')
            elif card == 'Assassin' and player_challenged.coins >= 3:
                possible_actions.append('Assasinate')
            elif card == 'Contessa':
                possible_actions.append('Block-Assassination')

        if player_challenged.choosen_action in possible_actions:  

            if player_challenged.choosen_action == 'Tax':
                cls.__deck.return_to_deck('Duke')
                player_challenged.hand_of_cards.remove('Duke')
            elif player_challenged.choosen_action == 'Exchange':
                cls.__deck.return_to_deck('Ambassador')
                player_challenged.hand_of_cards.remove('Ambassador')
            elif player_challenged.choosen_action == 'Steal':
                cls.__deck.return_to_deck('Captain')
                player_challenged.hand_of_cards.remove('Captain')
            elif player_challenged.choosen_action == 'Assassinate':
                cls.__deck.return_to_deck('Assassin')
                player_challenged.hand_of_cards.remove('Assassin')
            elif player_challenged.choosen_action == 'Block-Assasinate':
                cls.__deck.return_to_deck('Contessa')
                player_challenged.hand_of_cards.remove('Contessa')

            player_challenged.hand_of_cards.append(
                cls.__deck.pick_card_and_remove())

            Console.print_str_with_args(
                '\n* {} loosed the challenge. {} can use {} *\n', [
                    challenger, player_challenged,
                    player_challenged.choosen_action
                ])

            challenger_cards = []
            for card in challenger.hand_of_cards:
                challenger_cards.append(card)

            Console.print_list(challenger_cards)
            if len(challenger_cards) == 2:
                while True:
                    discard = Console.get_str_input_with_args(
                        ' * {}: Select the card that do you want to discard *\n',[challenger.name])
                    if discard in challenger_cards:
                        break
                    else:
                        Console.print_str(
                            '* Wrong selection, please choose again * \n')
            else:
                discard = challenger_cards[0]

            
            challenger.hand_of_cards.remove(discard)
            cls.__Table.append(discard)
            Console.print_str_with_args('* {}, your cards left are: *',[challenger.name])
            Console.print_list(challenger.hand_of_cards)

        else:

            Console.print_str_with_args(
                '\n* {} loosed the challenge. He can´t use {} *\n',
                [player_challenged, player_challenged.choosen_action])

            challenged_cards = []
            for card in player_challenged.hand_of_cards:
                challenged_cards.append(card)

            Console.print_list(challenged_cards)

            if len(challenged_cards) == 2:
                while True:
                    discard = Console.get_str_input_with_args(
                        '* {} : Select the card that do you want to discard *\n\n',
                        [player_challenged])
                    if discard in challenged_cards:
                        break
                    else:
                        Console.print_str(
                            '* Wrong selection, please choose again * \n')
            else:
                discard = challenged_cards[0]

            cls.__Table.append(discard)
            player_challenged.hand_of_cards.remove(discard)

            Console.print_str_with_args('\n* {}, your cards left are: *\n',[player_challenged.name])
            Console.print_list(player_challenged.hand_of_cards)
            player_challenged.choosen_action = ''

        Console.clear()
Beispiel #25
0
class Game:
    def __init__(self):
        self.rng = RNG()
        self.entities = []
        self.active_entities = []
        self.dungeon = None
        self.message_log = None
        self.menu = None
        self.overlay = None

        self.tile_types = {}
        self.materials = {}
        self.words = {}
        self.status_effects = {}
        self.traits = {}
        self.abilities = {}
        self.breeds = {}
        self.prefabs = {}
        self.active_region = []
        self.player = None
        self.fps=0

        self.map_con = Console("Dungeon Map",MAP_X,MAP_Y,MAP_W,MAP_H)
        self.panel_con = Console("Side Panel",PANEL_X,PANEL_Y,PANEL_W,PANEL_H)
        self.log_con = Console("Message Log",LOG_X,LOG_Y,LOG_W,LOG_H)

        self.state = STATE_PLAYING
        self.input_state = INPUT_NORMAL

        self.key = libtcod.Key()
        self.mouse = libtcod.Mouse()

    @property
    def depth(self):
        return self.player.depth
    @property
    def cur_level(self):
        return self.player.level

    @property
    def living_entities(self):
        return filter(lambda entity: entity.creature and entity.creature.alive, self.entities)

    def add_entity(self,entity):
        self.entities.append(entity)

    def next_id(self):
        next_id = 0
        id_list = [entity.entity_id for entity in self.entities]
        while True:
            if next_id not in id_list:
                return next_id
            else:
                next_id += 1

    def load_yaml(self):
        load_file = open('data/load.yaml')
        load_data = yaml.load(load_file)
        load_file.close()

        load_order = [('tiles',self.load_tile_types),
                      ('materials',self.load_materials),
                      ('words',self.load_words),
                      ('statuseffects',self.load_status_effects),
                      ('traits',self.load_traits),
                      ('abilities',self.load_abilities),
                      ('breeds',self.load_breeds),
                      ('prefabs',self.load_prefabs),
                      ('player',self.load_player)]

        for category in load_order:
            files = []
            if 'directories' in load_data[category[0]]:
                for directory in load_data[category[0]]['directories']:
                    for file_name in os.listdir(directory):
                        if file_name.endswith('.yaml'):
                            files.append(directory.strip('/')+'/'+file_name)
            if 'files' in load_data[category[0]]:
                for file_name in load_data[category[0]]['files']:
                    files.append(file_name)
            category[1](files)

    def load_tile_types(self,files):
        for file_name in files:
            f = open(file_name)
            data = yaml.load(f)
            f.close()
            yamlhelp.merge(data,self.tile_types)

        for tile_type_id in self.tile_types:
            tile_type = self.tile_types[tile_type_id]
            tile_type = TileType(tile_type_id,**tile_type)
            self.tile_types[tile_type_id] = tile_type

            if type(tile_type.color)==list:
                tile_type.color = [yamlhelp.load_color(c)
                                   for c in tile_type.color]
            else:
                tile_type.color = yamlhelp.load_color(tile_type.color)
            tile_type.color_not_visible = yamlhelp.load_color(tile_type.color_not_visible)

    def load_materials(self,files):
        for file_name in files:
            f = open(file_name)
            data = yaml.load(f)
            f.close()
            yamlhelp.merge(data,self.materials)

        for material_id in self.materials:
            material = self.materials[material_id]
            material = Material(material_id, **material)
            self.materials[material_id] = material

            material.color = yamlhelp.load_color(material.color)

    def load_status_effects(self,files):
        for file_name in files:
            f = open(file_name)
            data = yaml.load(f)
            f.close()
            yamlhelp.merge(data,self.status_effects)
        for status_effect_id in self.status_effects:
            status_effect = self.status_effects[status_effect_id]
            status_effect = StatusEffect(status_effect_id, **status_effect)
            self.status_effects[status_effect_id] = status_effect

    def load_traits(self,files):
        for file_name in files:
            f = open(file_name)
            data = yaml.load(f)
            f.close()
            yamlhelp.merge(data,self.traits)

        for trait_id in self.traits:
            trait = self.traits[trait_id]
            trait = Trait(trait_id,**self.traits[trait_id])
            self.traits[trait_id] = trait

        for trait_id in self.traits:
            #second pass needed since traits defs include other traits
            trait = self.traits[trait_id]
            if trait.replaces:
                trait.replaces = self.traits[trait.replaces]
            if not trait.cancels: trait.cancels=[]
            for i in range(len(trait.cancels)):
                trait.cancels[i] = self.traits[trait.cancels[i]]

            trait.effect = StatusEffect(trait_id,**trait.effect)

            if trait.cost:
                yamlhelp.convert_keys(trait.cost,self.materials)

            if trait.removal_cost:
                yamlhelp.convert_keys(trait.removal_cost,self.materials)

    def load_words(self,files):
        for file_name in files:
            f = open(file_name)
            data = yaml.load(f)
            f.close()
            yamlhelp.merge(data,self.words)

        for word_id in self.words:
            word = self.words[word_id]
            word = Word(word_id, **word)
            self.words[word_id] = word

            word.color = yamlhelp.load_color(word.color)

    def load_abilities(self,files):
        for file_name in files:
            f = open(file_name)
            data = yaml.load(f)
            f.close()
            yamlhelp.merge(data,self.abilities)

        for ability_id in self.abilities:
            ability = self.abilities[ability_id]
            ability = Ability(self, ability_id, **ability)
            self.abilities[ability_id] = ability
            ability.trigger = eval('abilityfunctions.%s'%ability.trigger)
            ability.effect  = eval('abilityfunctions.%s'%ability.effect)
            if ability.color:
                ability.color = yamlhelp.load_color(ability.color)

    def load_breeds(self,files):
        for file_name in files:
            f = open(file_name)
            data = yaml.load(f)
            f.close()
            yamlhelp.merge(data,self.breeds)

        for breed_id in self.breeds:
            breed = self.breeds[breed_id]
            breed = Breed(self, breed_id, **breed)
            self.breeds[breed_id] = breed

            breed.color = yamlhelp.load_color(breed.color)
            yamlhelp.convert_keys(breed.materials,self.materials)
            if breed.death_func:
                breed.death_func = eval('deathfunctions.%s' % \
                                        breed.death_func)

    def load_prefabs(self,files):
        for file_name in files:
            f = open(file_name)
            data = yaml.load(f)
            f.close()
            yamlhelp.merge(data,self.prefabs)

        for prefab_id in self.prefabs:
            prefab = self.prefabs[prefab_id]
            prefab = Prefab(prefab_id,**prefab)
            self.prefabs[prefab_id] = prefab

            for char in prefab.char_to_tile:
                if type(prefab.char_to_tile[char])==list:
                    prefab.char_to_tile[char] = [self.tile_types[t] for t in prefab.char_to_tile[char]]
                else:
                    prefab.char_to_tile[char] = self.tile_types[prefab.char_to_tile[char]]

    def load_player(self,files):
        player_data = {}
        for file_name in files:
            f = open(file_name)
            data = yaml.load(f)
            f.close()
            yamlhelp.merge(data,player_data)
        player_name = player_data.keys()[0]
        player_data = player_data[player_name]
        if 'abilities' in player_data:
            starting_abilities = player_data['abilities']
            del player_data['abilities']
        else:
            starting_abilities = []
        player_creature = Golem(self,player_name,**player_data)
        player_creature.raw_color = yamlhelp.load_color(player_creature.raw_color)
        for ability in starting_abilities:
            player_creature.add_ability(ability)
        for bp_name in player_creature.body_parts:
            bp = player_creature.body_parts[bp_name]
            bp = BodyPart(player_creature,bp_name,**bp)
            player_creature.body_parts[bp_name] = bp
            starting_trait_ids = bp.traits
            bp.traits = []
            for trait_id in starting_trait_ids:
                bp.add_trait(self.traits[trait_id],force=True)

        self.player = Player(self, self.next_id(),
                             0, 0, 0, False, True,
                             input_handler = InputHandler(),
                             creature = player_creature)
        self.add_entity(self.player)

        for name in self.materials:
            self.player.materials[self.materials[name]] = 0
        for ability in self.abilities.values():
            self.player.add_observer(ability)
            ability.add_observer(self.player.input_handler)
        for word_id in self.words:
            self.player.words.append(self.words[word_id])

    def clear_all(self):
        for entity in self.entities:
            entity.clear(self.player.x,
                        self.player.y,
                        self.map_con)

    def get_entity(self,entity_id):
        for entity in self.entities:
            if entity.entity_id == entity_id:
                return entity

    def get_creature_at(self,x,y):
        return self.cur_level.get_tile(x,y).creature
    def get_item_at(self,x,y):
        return self.cur_level.get_tile(x,y).item

    def render_panel(self):
        self.panel_con.clear()
        self.panel_con.draw_border(True,C_BORDER,C_BORDER_BKGND)

        y = 2
        if SHOW_FPS:
            x=2
            self.panel_con.set_default_foreground(C_MENU)
            self.panel_con.print_string(x,y,'FPS: %i'%self.fps)
            y += 1

        y += 1
        for part_name in ['Head','Torso','L Arm','R Arm','L Leg','R Leg']:
            part = self.player.creature.body_parts[part_name]
            part_name = '%s:'%part.name
            part_health = '%i/%i'%(part.health,part.max_health)
            x = 2
            self.panel_con.set_default_foreground(C_MENU)
            self.panel_con.print_string(x,y,part_name)
            x = 9
            self.panel_con.set_default_foreground(libtcod.light_red)
            self.panel_con.print_string(x,y,part_health)
            y += 1

        status_effects = []
        for bp in self.player.creature.body_parts.values():
            status_effects += bp.status_effects
        if status_effects:
            y += 1
            for se in status_effects:
                if se.name:
                    x = 2
                    self.panel_con.set_default_foreground(C_MENU)
                    self.panel_con.print_string(x,y,se.name)
                    y += 1

        y += 1
        for material in sorted(self.player.materials):
            x = 2
            s = '%s: %i'%(material,self.player.materials[material])
            self.panel_con.set_default_foreground(material.color)
            self.panel_con.print_string(x,y,s)
            y += 1

        """y += 1
        for word in sorted(self.player.words):
            color = word.color
            x = 2
            self.panel_con.set_default_foreground(word.color)
            self.panel_con.print_string(x,y,word.name)
            y += 1"""

        y += 1
        self.panel_con.set_default_foreground(C_MENU)
        for stat in (('Size',self.player.creature.size),
                     ('Agility',self.player.creature.agility),
                     ('Perception',self.player.creature.perception),
                     ('Strength',self.player.creature.strength),
                     ('Speed',self.player.creature.speed)):
            x = 2
            self.panel_con.print_string(x,y,'%s: %i'%stat)
            y += 1

    def render_all(self):
        player_x = self.player.x
        player_y = self.player.y
        if FOCUS == FOCUS_PLAYER:
            focus_x = player_x
            focus_y = player_y
        elif FOCUS == FOCUS_FIXED:
            focus_x = LEVEL_W//2
            focus_y = LEVEL_H//2

        self.dungeon.render(focus_x, focus_y, self.map_con,
                            overlay=self.overlay)
        for entity in self.entities:
            if entity != self.player:
                entity.render(focus_x, focus_y, self.map_con)
        for entity in self.living_entities: #draw living creatures on top
            if entity != self.player:
                entity.render(focus_x, focus_y, self.map_con)
        self.player.render(focus_x, focus_y, self.map_con)
        self.map_con.draw_border(True,C_BORDER,C_BORDER_BKGND)

        if self.menu:
            self.menu.render(self.map_con)
        self.map_con.blit()

        self.message_log.render(self.log_con)
        self.log_con.blit()

        self.render_panel()
        self.panel_con.blit()

    def play(self):
        self.dungeon.update()
        self.render_all()
        libtcod.console_flush()
        t = time.time()
        while not libtcod.console_is_window_closed():
            #libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS|libtcod.EVENT_MOUSE, self.key, self.mouse)

            #self.state = self.player.input_handler(key,mouse,
            #                                       self.input_state,
            #                                       self.menu)
            #if self.menu and self.state != STATE_MENU:
            #    self.menu = None

            #if self.state == STATE_PLAYING:
            #    self.player.creature.energy -= ENERGY_THRESHOLD
            #while self.state == STATE_PLAYING:
            player_room = self.cur_level.get_room_at(*self.player.pos)
            if player_room:
                active_rooms = [player_room]
                self.active_region = []
                for room in player_room.connections:
                    if room not in active_rooms:
                        active_rooms.append(room)
                        for r in room.connections:
                            if r not in active_rooms:
                                active_rooms.append(room)
                for room in active_rooms:
                    self.active_region += room.tile_positions
            else:
                self.active_region = [self.player.pos]
            self.active_entities=[]
            for entity in self.entities:
                if entity.pos in self.active_region:
                    self.active_entities.append(entity)

            self.clear_all()
            for entity in self.active_entities:
                entity.update()
                    
                #self.player.creature.energy += self.player.creature.speed
                #print self.player.creature.energy
                #if self.player.creature.energy >= ENERGY_THRESHOLD:
                    #self.state = STATE_PAUSED

            self.dungeon.update()
            self.render_all()
            libtcod.console_flush()
            self.fps = 1.0/(time.time()-t)
            t=time.time()
Beispiel #26
0
# Ryan Dawkins
# October 9th, 2014
# Programming Assignment 1

from storage import Storage
from console import Console
from structconsole import StructConsole
from arrayconsole import ArrayConsole

if __name__ == "__main__":
    Console.clear()
    Console.greet()

    # We give storage the None object because we want
    # to abstract what kind of class it is later
    storage = None
    arraysOrStructs = raw_input(
        "Would you rather use structs or arrays? (enter s or a)\n> ")
    if arraysOrStructs == "a":
        storage = ArrayConsole()
    elif arraysOrStructs == "s":
        storage = StructConsole()
    else:
        print "Incorrect input you must enter s or a"
        sys.exit()

    while True:
        command = raw_input("user:<storage>$ ")
        storage.execute(command)
Beispiel #27
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        #icon = QIcon("logo.png")
        #self.setWindowIcon(icon)
        self.setWindowTitle("LiveHack by nAkoustix v0.1")

        #pal = self.palette()
        #pal.setColor(QPalette.Base, Qt.black)
        #pal.setColor(QPalette.Text, Qt.green)
        #self.setPalette(pal)
        #self.setAutoFillBackground(True)

        self.console = Console(self)
        self.lay = QGridLayout()
        self.lay.addWidget(self.console, 0, 0)

        cw = QWidget(self)
        cw.setLayout(self.lay)
        self.setCentralWidget(cw)

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.setblocking(0)
        self.localAddr = ("localhost", 9001)
        self.socket.bind(self.localAddr)

        self.socksend = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.remoteAddr = ("localhost", 9000)

        self.buffer = []
        self.indentation = 0

        self.readTimer = QTimer(self)
        self.readTimer.timeout.connect(self.readData)

        self.console.newLine.connect(self.interpretLine)
        self.console.indentationPlus.connect(self.indentPlus)
        self.console.indentationMinus.connect(self.indentMinus)

        self.readTimer.start(50)

        self.console.makePrompt()

    def indentPlus(self):
        print("indent +")
        self.indentation += 1

    def indentMinus(self):
        print("indent -")
        self.indentation -= 1

    def interpretLine(self, line):
        if line[:3] != ">>>" and line[:3] != "...":
            self.console.putData("\n")
            self.console.makePrompt()
            return
        line = line[4:]
        if line[:1] == "!":
            line = line[1:]
            #-- Escape chars ----------------------
            print("Escape char!")
            if line == "knock":
                print("knock, knock, knocking on Liiives door...")
                self.console.putData(
                    "\n\\0/ - Client says:\t\"Knock knock.. Hi Live! may I come in?\""
                )
                self.socksend.sendto("!knock".encode("utf-8"), self.remoteAddr)
            elif line == "clear":
                self.socksend.sendto("!clear".encode("utf-8"), self.remoteAddr)
                self.clear()
                self.console.clear()
            elif line == "exit":
                print("Bye!!")
                self.exitTimer = QTimer(self)
                self.console.putData("\nBye!!")
                #self.exitTimer.timeout.connect(QCoreApplication.instance.quit)
                self.exitTimer.timeout.connect(self.close)
                self.exitTimer.start(800)
                #QCoreApplication.instance().quit()
            else:
                self.console.putData("\nUnknown escape sequence!")
                self.makePrompt()
            self.clear()
            return
        self.buffer += [line]
        #self.console.addToCmdHistory(line)
        #-- Editor behaviour ------------------
        if line[-1:] == ":":
            self.console.putData("\n")
            self.indentation += 1
            self.console.makeExtendedPrompt(self.indentation)
            print(": found")
            print("line")
            #debug("1");
        else:
            self.console.putData("\n")
            if self.indentation == 0:
                self.execute()
                self.console.makePrompt()
                #debug("2");
            else:
                #self.indentation = 0
                stripped = line.replace(" ", "")
                if len(stripped) == 0:
                    self.indentation = 0
                    self.execute()
                    self.console.makePrompt()
                    #debug("3");
                else:
                    #debug("4");
                    self.console.makeExtendedPrompt(self.indentation)

    def clear(self):
        self.indentation = 0
        self.buffer = []

    def execute(self):
        print("execute")
        print(self.indentation)
        s = ""
        for line in self.buffer:
            s += line + "\n"
        # check if there is anything
        if len(s.replace("\n", "")) == 0:
            print("execution aborted")
        else:
            print(s)
            self.socksend.sendto(bytes(s, "utf-8"), self.remoteAddr)
            self.socksend.sendto("!execute".encode("utf-8"), self.remoteAddr)
        self.clear()

    def readData(self):
        try:
            while 1:
                self.data, self.addr = self.socket.recvfrom(65536)
                decoded = self.data.decode()
                #print(decoded)
                if decoded != "" and decoded != "\n":
                    self.console.putData("\n")
                    self.console.putData(decoded)

        except Exception as e:
            pass
Beispiel #28
0
class MainWindow(QMainWindow):
    
	def __init__(self, parent=None):
		super(MainWindow, self).__init__(parent)
		#icon = QIcon("logo.png")
		#self.setWindowIcon(icon)
		self.setWindowTitle("LiveHack by nAkoustix v0.1")
		
		#pal = self.palette()
		#pal.setColor(QPalette.Base, Qt.black)
		#pal.setColor(QPalette.Text, Qt.green)
		#self.setPalette(pal)
		#self.setAutoFillBackground(True)
		
		self.console = Console(self)
		self.lay = QGridLayout()
		self.lay.addWidget(self.console, 0,0)
        
		cw = QWidget(self)
		cw.setLayout(self.lay)
		self.setCentralWidget(cw)
		
		self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		self.socket.setblocking(0)
		self.localAddr = ("localhost", 9001)
		self.socket.bind(self.localAddr)
		
		self.socksend = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		self.remoteAddr = ("localhost", 9000)
		
		self.buffer = []
		self.indentation = 0
		
		self.readTimer = QTimer(self)
		self.readTimer.timeout.connect(self.readData)
		
		self.console.newLine.connect(self.interpretLine)
		self.console.indentationPlus.connect(self.indentPlus)
		self.console.indentationMinus.connect(self.indentMinus)
		
		self.readTimer.start(50)
		
		self.console.makePrompt()
		
	def indentPlus(self):
		print("indent +")
		self.indentation += 1
		
	def indentMinus(self):
		print("indent -")
		self.indentation -= 1
		
	def interpretLine(self, line):
		if line[:3] != ">>>" and line[:3] != "...":
			self.console.putData("\n")
			self.console.makePrompt()
			return
		line = line[4:]
		if line[:1] == "!":
			line = line[1:]
#-- Escape chars ----------------------
			print("Escape char!")
			if line == "knock":
				print("knock, knock, knocking on Liiives door...")
				self.console.putData("\n\\0/ - Client says:\t\"Knock knock.. Hi Live! may I come in?\"")
				self.socksend.sendto("!knock".encode("utf-8"), self.remoteAddr)
			elif line == "clear":
				self.socksend.sendto("!clear".encode("utf-8"), self.remoteAddr)
				self.clear()
				self.console.clear()
			elif line == "exit":
				print("Bye!!")
				self.exitTimer = QTimer(self)
				self.console.putData("\nBye!!")
				#self.exitTimer.timeout.connect(QCoreApplication.instance.quit)
				self.exitTimer.timeout.connect(self.close)
				self.exitTimer.start(800)
				#QCoreApplication.instance().quit()
			else:
				self.console.putData("\nUnknown escape sequence!")
				self.makePrompt()
			self.clear()
			return
		self.buffer += [line]
		#self.console.addToCmdHistory(line)
#-- Editor behaviour ------------------
		if line[-1:] == ":":
			self.console.putData("\n")
			self.indentation += 1
			self.console.makeExtendedPrompt(self.indentation)
			print(": found")
			print("line")
			#debug("1");
		else:
			self.console.putData("\n")
			if self.indentation == 0:
				self.execute()
				self.console.makePrompt()
				#debug("2");
			else:
				#self.indentation = 0
				stripped = line.replace(" ", "")
				if len(stripped) == 0:
					self.indentation = 0
					self.execute()
					self.console.makePrompt()
					#debug("3");
				else:
					#debug("4");
					self.console.makeExtendedPrompt(self.indentation)
	def clear(self):
		self.indentation = 0;
		self.buffer = []
				
	def execute(self):
		print("execute")
		print(self.indentation)
		s = ""
		for line in self.buffer:
			s += line + "\n"
		# check if there is anything
		if len(s.replace("\n", "")) == 0:
			print("execution aborted")
		else:
			print(s)
			self.socksend.sendto(bytes(s, "utf-8"), self.remoteAddr)
			self.socksend.sendto("!execute".encode("utf-8"), self.remoteAddr)
		self.clear()
		
	def readData(self):
		try:
			while 1:
				self.data, self.addr = self.socket.recvfrom(65536)
				decoded = self.data.decode()
				#print(decoded)
				if decoded != "" and decoded != "\n":
					self.console.putData("\n")
					self.console.putData(decoded)

		except Exception as e:
			pass