Esempio n. 1
0
 def non_showdown(self):
     if len(self.active_players) > 1:
         print('Error in non_showdown, ' + str(len(self.active_players)) + ' active players left')
     elif len(self.active_players) == 0 and len(self.pot.allin_players) != 1:
         print('Error in non_showdown, active players: ' + str(len(self.active_players)) + ', allins: ' + str(
             len(self.pot.allin_players)))
     elif len(self.active_players) == 1 and len(self.pot.allin_players) > 0:
         print('Error in non_showdown, active players: ' + str(len(self.active_players)) + ', allins: ' + str(
             len(self.pot.allin_players)))
     else:
         winner = None
         if self.active_players:
             winner = self.active_players[0]
         elif self.pot.allin_players:
             winner = self.pot.allin_players[0]
         active_bet = winner.street_investment
         previous_bet = 0
         for p in self.players:
             if p is not winner:
                 if p.street_investment > previous_bet:
                     previous_bet = p.street_investment
         self.pot.return_chips(winner, active_bet - previous_bet)
         print(Debug.log_str_win_non_showdown(winner, self.pot))
         self.hand_log.add_str(Debug.log_str_win_non_showdown(winner, self.pot))
         self.pot.return_chips(winner, self.pot.total)
Esempio n. 2
0
 def record_robot(self, robot, function, args):
     """
     Record movements of robot and positions of blocks.
     :param robot: handler of robot
     :type robot: RobotHandler
     :param function: bound function to robot handler object
     :type function: method
     :param args: arguments of function
     :type args: list
     """
 
 
     #New code for the challenge: Update block
     # Update position
     if function == robot.position_new:
         self.__coordinates[0] = args[0]
         self.__coordinates[1] = args[1]
     # Update height
     elif function == robot.height_new:
         self.__coordinates[2] = args[0]
     # Check blocks before putting the pump on
     elif function == robot.pump_on:
         self.__challenge.pump_on(self.__coordinates)
     elif function == robot.pump_off:
         coordinates = self.__coordinates.copy()
         Debug.msg('Der Block wird auf der Koordinate {} abgelegt'.format(coordinates[:]))
         self.__challenge.pump_off(coordinates)
     elif function == robot.drehen:
         Debug.msg('Der Block wird um {} Grad gedreht'.format(args[0]))
         self.__challenge.rotate_man_block(args[0])
Esempio n. 3
0
 def collect_blinds(self, hand_log):
     #self.pot_size()
     print('*** collecting blinds ***')
     if self.players[0].stack_size <= self.table.small_blind:
         hand_log.add_str(
             Debug.log_str_blinds_allin(self.players[0]) + '\n')
         self.total = self.total + self.players[0].stack_size
         self.players[0].move_all_in()
     else:
         hand_log.add_str(
             Debug.log_str_post_sb(self.players[0], self.table.small_blind)
             + '\n')
         self.players[0].invest_chips(self.table.small_blind)
         self.total = self.total + self.table.small_blind
     if self.players[1].stack_size <= self.table.big_blind:
         hand_log.add_str(
             Debug.log_str_blinds_allin(self.players[1]) + '\n')
         self.total = self.total + self.players[1].stack_size
         self.players[1].move_all_in
     else:
         hand_log.add_str(
             Debug.log_str_post_bb(self.players[1], self.table.big_blind) +
             '\n')
         self.players[1].invest_chips(self.table.big_blind)
         self.total = self.total + self.table.big_blind
Esempio n. 4
0
 def deal_community_cards(self):
     new_cards_str = ''
     for c in range(self.community_cards_num[self.street]):
         self.community[self.street].append(self.deck.get_card())
         if c > 0:
             new_cards_str += ', '
         new_cards_str += str(self.community[self.street][c])
     # print(self.streets[self.street] + ': ' + new_cards_str)
     Debug.print_community(self, new_cards_str)
     self.hand_log.add_line(Debug.log_str_community(self))
Esempio n. 5
0
    def run(self):
        """Executes parsing process
		"""

        Debug.printd("Parser -> START")
        try:
            self.__load_source()
            self.__parse_source()
            Debug.pprintd(self._instruction_list)
        except InterpreterError:
            raise
Esempio n. 6
0
    def __add_instructions(self):
        """Loops through instructions in file
		"""

        for instr in self._program_root:
            Debug.printd("Processing instruction '{}'".format(
                instr.get("opcode")))
            try:
                self.__add_instruction(instr)
            except InterpreterError:
                raise
Esempio n. 7
0
    def run(self):
        """Runs the interpreter
		"""

        Debug.printd("Interpreter -> START")

        try:
            self.__parse()
            self.__process()
        except InterpreterError:
            raise
Esempio n. 8
0
 def determine_winners(self, pot):
     winners = []
     hand_ranks = {}
     for p in pot.players:
         hand_ranks[p] = self.rank_hand_py(p)
     for k in hand_ranks.keys():
         if not winners or hand_ranks[k] > hand_ranks[winners[0]]:
             winners = [k]
         elif hand_ranks[k] == hand_ranks[winners[0]]:
             winners.append(k)
     Debug.print_winners(winners)
     return winners
Esempio n. 9
0
 def award_pot(self, pot, winners):
     if len(winners) > 1:
         amount_won = int(pot.total / len(winners))
         leftover = pot.total - (amount_won * len(winners))
         for p in winners:
             pot.return_chips(p, amount_won)
             self.hand_log.add_str(Debug.log_str_win_showdown(p, amount_won))
         r = random.choice(winners)
         pot.return_chips(r, leftover)
         self.hand_log.add_str(Debug.log_str_win_leftover(r, leftover))
     else:
         self.hand_log.add_str(Debug.log_str_win_showdown(winners[0], pot.total))
         pot.return_chips(winners[0], pot.total)
Esempio n. 10
0
 def isBlock(self,coordinates):
     #Checks if there is a block at coordinates
     check = False
     if coordinates[2] >= 0:
         Debug.msg('Is block on coordinate check: {}'.format(coordinates[:]))
         for block in self.blocks:
             if block.is_on_position(coordinates):
                 Debug.msg('Block found on {}'.format(coordinates))
                 check = True
                 break 
         return check
     else:
         return False
Esempio n. 11
0
    def __process(self):
        """Interpreter loop executes parsed instructions
		"""

        Debug.printd("Interpreter -> PROCESSING..")
        instr_count = len(self._instr_order_list)

        while self._instr_index < instr_count:
            try:
                self.__execute_instr()
            except InterpreterError:
                raise

            self._instr_index += 1
Esempio n. 12
0
 def showdown(self):
     print('Got to showdown. Number of sidepots = ' + str(len(self.pot.side_pots)))
     if self.street != 3:
         while self.street + 1 <= 3:
             self.street += 1
             self.deal_community_cards()
     Debug.print_final_board(self.community)
     # handle side pots first
     while len(self.pot.side_pots) > 0:
         side_pot = self.pot.side_pots.pop()
         winners = self.determine_winners(side_pot)
         self.award_pot(side_pot, winners)
     # award main pot
     winners = self.determine_winners(self.pot)
     self.award_pot(self.pot, winners)
Esempio n. 13
0
 def bet(self, player, amount):
     print(Debug.log_str_bet(player, amount))
     if amount == player.stack_size:
         self.pot.move_all_in(player)
         self.active_players.remove(player)
     else:
         self.pot.invest_chips(player, amount)
Esempio n. 14
0
    def __parse(self):
        """Parses and sets up interpreter variables
		"""

        Debug.printd("Interpreter -> PARSING..")
        parser = Parser(self._source_file)

        try:
            parser.run()
        except InterpreterError:
            raise

        self._instr_list = parser.instruction_list
        self._jump_label_list = parser.jump_label_list
        self._instr_order_list = list(self._instr_list.keys())
        self._instr_order_list.sort()
Esempio n. 15
0
 def reraise(self, player, amount):
     print(Debug.log_str_raise(player, amount))
     if amount == player.stack_size + player.street_investment:
         self.pot.move_all_in(player)
         self.active_players.remove(player)
     else:
         self.pot.invest_chips(player, amount - player.street_investment)
Esempio n. 16
0
 def update_coordinates(self):
     #print('origin: {} dim[0]: {}, range(x_b {}'.format(self.pos, self.dimension[0],range(self.dimension[0])))
     if self.dimension:
         self.coordinates = []   
         for x_b in range(self.dimension[0]):
             for y_b in range(self.dimension[1]):
                 x = x_b - (self.dimension[0]-1)/2
                 y = y_b - (self.dimension[1]-1)/2
                 r = math.sqrt(x**2 + y**2)
                 angle = math.atan2(y,x)
                 # Debug.msg('x {},y{},r{},angle{}, rotation {}'.format(x,y,r,angle,self.rotation))
                 angle = math.radians(self.rotation) + angle 
                 self.coordinates.append([int(round(self.pos_center[0]+ r*math.cos(angle),1)),int(round(self.pos_center[1] + r*math.sin(angle),1)),int(self.pos_center[2])])
     else:
         self.coordinates =  [self.pos_center]       
     Debug.msg('Transformed  coordinates: {}'.format(self.coordinates[:]))
Esempio n. 17
0
 def call(self, player, total_bet):
     print(Debug.log_str_call(player, total_bet))
     if player.stack_size <= total_bet - player.street_investment:
         self.pot.move_all_in(player)
         self.active_players.remove(player)
     else:
         self.pot.invest_chips(player, total_bet - player.street_investment)
Esempio n. 18
0
 def postflop(self):
     print('\n*** beginning postflop action ***')
     self.street += 1
     # for loop for postflop
     while self.street <= 3:
         self.deal_community_cards()
         # print('*** beginning ' + self.streets[self.street] + ' action ***')
         Debug.print_remaining_active_players(self.active_players)
         is_hand_finished = self.betting_round(0, 0)
         if is_hand_finished:
             return is_hand_finished
         else:
             self.reset_current_street_investment()
             # print('*** end of ' + self.streets[self.street] + ' action ***')
             self.street += 1
     self.showdown()
     return is_hand_finished
Esempio n. 19
0
 def add_options(self, options):
     # Adds all options of the challenge file to the challenge
     # @options: dict containing the options
     key = 'type'
     if key in options:
         
         if options['type'] == 'test':
             self.success_on = False
             self.load_final_block = False
             Debug.msg('Test on')
         elif options['type'] == 'challenge':
             self.challenge = True
         elif options['type'] == 'other':
             pass
     key = 'info_text'
     if key in options:
         self.info_text = options['info_text']
Esempio n. 20
0
    def __handle(self):
        """Handle passed arguments

		Validates arguments and takes corresponding actions
		"""

        if self.args['help']:
            if len(argv) > 2:
                raise ArgumentsError("invalid combination")
            print(Arguments.helpMessage)
            exit(0)

        if self.args['source'] == "":
            raise ArgumentsError("source file is required")

        if self.args['debug']:
            Debug.active(True)
Esempio n. 21
0
    def __init__(self, class_name):

        if LoggerFactory.log_dir is None:
            cur_path = path.dirname(__file__)
            parent_path = os.path.dirname(cur_path)  # 获得d所在的目录,即d的父级目录
            LoggerFactory.log_dir = parent_path + "/logs"

        self.debug_path = LoggerFactory.log_dir + "/debug.log"
        self.info_path = LoggerFactory.log_dir + "/info.log"
        self.warn_path = LoggerFactory.log_dir + "/warn.log"
        self.error_path = LoggerFactory.log_dir + "/error.log"
        self.critical_path = LoggerFactory.log_dir + "/critical.log"

        self.__debug = Debug(class_name, self.debug_path)
        self.__info = Info(class_name, self.info_path)
        self.__warn = Warn(class_name, self.warn_path)
        self.__error = Error(class_name, self.error_path)
        self.__critical = Critical(class_name, self.critical_path)
Esempio n. 22
0
 def rank_hand_c(self, player):
     print('Player ' + player.name + ' hand: ' + player.hole_cards_str())
     # convert hand and community cards to int keys for SKPokerEval
     cards = [player.hole_cards[0], player.hole_cards[1], self.community[1][0], self.community[1][1],
              self.community[1][2], self.community[2][0], self.community[3][0]]
     card_keys = []
     for card in cards:
         int_value = 4 * (14 - card.rank) + self.deck.suit_key[card.suit]
         card_keys.append(int_value)
     Debug.print_card_list(cards)
     Debug.print_card_keys(card_keys)
     # run hand ranker executable
     shell_cmd = './bin/hand_ranker ' + str(card_keys[0]) + ' ' + str(card_keys[1]) + ' ' + str(card_keys[2]) + ' '
     shell_cmd += str(card_keys[3]) + ' ' + str(card_keys[4]) + ' ' + str(card_keys[5]) + ' ' + str(card_keys[6])
     p = Popen(shell_cmd, shell=True, stdout=PIPE, stdin=PIPE)
     output_str = p.stdout.readline().strip().decode('utf-8')
     rank = int(output_str)
     if Debug.mode == 'debug':
         print('Player  ' + player.name + ' hand rank: ' + output_str)
     return rank
Esempio n. 23
0
    def run_script(self, robot_handler):
        """
        Run script functions on robot.
        :return: True if script was sucessful
        :rtype: bool
        """
        # run functions
        for function_call in self.__function_calls:
            function = function_call["function"]
            argument = function_call["args"]
            # call unbound function
            if len(argument) != 0:
                function(argument)
            else:
                function()
            # update user challenge
            self.__user_challenge.record_robot(robot_handler, function,
                                               argument)

        Debug.msg(
            "All commands executed. Reseting arm and checking challenge victory conditions"
        )
        robot_handler.reset()
        return self.__user_challenge.success()
Esempio n. 24
0
 def getBlock(self,coordinates):
     #CHecks if there is a block at coordinates
     check = False
     
     Debug.msg('Get block at: {}'.format(coordinates[:]))
     if coordinates[2] == 0:
         Debug.msg("There is only the floor there ")
         return False
     for i in range(len(self.blocks)):
         
         if self.blocks[i].is_on_position(coordinates):
             Debug.msg('We got a block!')
             self.block_manipulating = self.blocks[i]
             self.block_manipulating.getBlock(coordinates)
             del self.blocks[i]
             return True
     Debug.msg('We dont got a block!')
     return check 
Esempio n. 25
0
    def load_challenges(self):
        ''' 
        Loads all challenges in the challenge/challenges_init folder with an .ini ending.
        '''

        _,challenge_paths = self.challenge_name_path()
        

        
        for path in challenge_paths:
            parser = configparser.ConfigParser()
            parser.read(path)
            
            # Generate a challenge template
            challenge = Challenge(parser['challenge']['name'])

            
            # Load block types
            block_types = parser['challenge']['block_types']
            block_types = block_types.replace('[','')
            block_types = block_types.replace(']','')
            block_types = block_types.split(",")
            block_types = [i.lower() for i in block_types]
            
            #Load generall options
            options = {}
            keys = ['type','info_text']
            for key in keys:
                if parser.has_option('challenge',key):
                    option = parser['challenge'][key]
                else:
                    option = ''
                options[key] = option
            challenge.add_options(options)
               
            
            
            # Load block dimensions
            for block_type in parser['Block_Dimensions']:
                dim = parser['Block_Dimensions'][block_type]
                dim = dim.replace('[','')
                dim = dim.replace(']','')
                dim = dim.split(',')
                dim = [int(i) for i in dim]
                block_type = block_type.lower()
                if block_type in block_types:
                    challenge.add_block_type(BlockType(block_type,dim))
                    #Debug.msg("Added Dimensions: {} type: {}".format(dim,block_type))
                else:
                    Debug.error("There is no block type {} (see [Block_Dimensions] in {})".format(block_type,path))
            challenge.init[2] = True
                


            
            # Load start positions
            for key in parser['Start_Position']:
                start_pos = parser['Start_Position'][key]
                start_pos= start_pos.replace('[','')
                start_pos = start_pos.replace(']','')
                start_pos = start_pos.split(",")
                # ToDo: Check i
                if len(start_pos) == 4:
                    angle = 0
                elif len(start_pos) == 5:
                    angle = int(start_pos[3])
                else:
                    print("Wrong start_position length. Example name = [x,y,z],rotation,type] or name = [x,y,z], type ")
                if challenge.valid_block_type(start_pos[-1]): 
                    dim = challenge.get_dim(start_pos[-1])
                    #print('dim:' ,dim)
                    challenge.add_start_position(Block([int(i) for i in start_pos[:3]],start_pos[-1].lower(),dim,_rotation=angle))
                    #Debug.msg("Added start positions: {} type: {}".format(start_pos[:3],start_pos[3].lower()))
                else:
                    Debug.error("invalid key of start block: {}".format(start_pos[3] ))
            challenge.reset()
            challenge.init[0] = True
                
                
            # Load final positions
            for key in parser['Final_Position']:
                final_pos = parser['Final_Position'][key]
                final_pos= final_pos.replace('[','')
                final_pos = final_pos.replace(']','')
                final_pos = final_pos.split(",")
                if len(final_pos) == 4:
                    angle = 0
                elif len(final_pos) == 5:
                    angle = int(final_pos[3])
                else:
                    print("Wrong start_position length. Example name = [x,y,z],rotation,type] or name = [x,y,z], type ")
                if challenge.valid_block_type(final_pos[-1]):
                    dim = challenge.get_dim(final_pos[-1])
                    #print('dim:' ,dim)
                    challenge.add_final_position(Block([int(i) for i in final_pos[:3]],final_pos[-1].lower(),dim,_rotation=angle))
                    #Debug.msg("Added final positions: {} type: {}".format(final_pos[:3],final_pos[3].lower()))
                else:
                    Debug.error("invalid key of final block: {}".format(final_pos[3] ))
            challenge.init[1] = True
            
            #challenge.debug_function() #Prints out the current blocks: only for debugging
            #Add the new challenge to the class
            self.__all_challenges.append(challenge)
Esempio n. 26
0
    def challenge_name_path():
        
        ''' Returns the path and other basics of the challenge config file '''
        parent_path = os.path.dirname(os.path.dirname( os.path.abspath(__file__)))
        path = os.path.join(parent_path,"challenges/challenges_init")
        path_challenges = []
        file_ending = 'ini'
        challenge_names_unsorted = [] # names of the challenge
        challenge_names = []
        sample_text_unsorted = [] # text in the challenge textbox
        sample_text = []
        description_unsorted = [] # Info in the challenge description
        description = []
        priorities = [] # Priority of the challenge in the dropdown menu: A low number means that the challenge is higher up.
        for file in os.listdir(path):
            if file.endswith(file_ending):
                path_challenge = os.path.join(path,file)
                path_challenges.append(path_challenge)
                parser = configparser.ConfigParser()
                parser.read(path_challenge)
                if parser['CONFIG']['filetype'] == "challenge":
                    challenge_names_unsorted.append(parser['challenge']['name'])
                    if parser.has_option('challenge','sample_text'):
                        text = parser['challenge']['sample_text']
                        text = text.split('\\n')
                        new_text = ''
                        for line in text:
                            new_text = new_text + line + '\n'
                        sample_text_unsorted.append(new_text)
                    else:
                        sample_text_unsorted.append('')
                    if parser.has_option('challenge','description'):
                        text = parser['challenge']['description']
                        text = text.split('\\n')
                        new_text = ''
                        for line in text:
                            new_text = new_text + line + '\n'
                        description_unsorted.append(new_text)
                    else:
                        description_unsorted.append('')
                    if parser.has_option('challenge','priority'):
                        priorities.append(parser['challenge']['priority'])
                    else:
                        priorities.append(9999)
                   
                    
                        
                else:
                    Debug.error(path_challenge, 'is no valid challenge file. The file is not loaded. Please add challenge to the name in the challenge section.')
        
        
        #Sorting the lists   
        index_of_list = list(range(len(priorities)))  # This will be used as a sorted index list
        range_len = len(priorities)-1
        while range_len > 0:
            for idx in  range(range_len):
                if priorities[idx] > priorities[idx+1]:
                    tmp_priority = priorities[idx]
                    tmp_idx= index_of_list[idx]
                    priorities[idx] = priorities[idx+1]
                    index_of_list[idx] = index_of_list[idx+1]
                    priorities[idx+1] = tmp_priority
                    index_of_list[idx+1] = tmp_idx
            range_len -= 1
                    
        new_list_position = index_of_list # For clarity, we are now sorting the list according to the priorities
        

        for idx in new_list_position:
            challenge_names.append(challenge_names_unsorted[idx])
            description.append(description_unsorted[idx])
            sample_text.append(sample_text_unsorted[idx])
            
            
            
        challenge_infos = {'names':challenge_names,'sample_text' : sample_text, 'description' : description, 'priorities' : priorities}

        
        return [challenge_infos,path_challenges]
Esempio n. 27
0
 def z(self):
      if self.pos_center[2] == None:
          Debug.error("Coordinate x not set yet")
          return False
      else:
          return self.pos_center[2]
Esempio n. 28
0
 def placeBlock(self,coordinates):
     # Checks whether the block can be placed
     check = False
     bottom_coordinates = coordinates.copy()
     bottom_coordinates[2] -= 1
     if self.isBlock(coordinates):
         message = 'There is already a block there'
         Debug.msg(message)
         Debug.error(message)
         raise RobotError(ErrorCode.E0015, message)
         return False
     elif coordinates[2] == 1:
         Debug.msg("The block is placed on the floor")
         self.block_manipulating.placeBlock(coordinates)
         self.blocks.append(self.block_manipulating)
         self.block_manipulating = []
         return True
     elif self.isBlock(bottom_coordinates):
         Debug.msg("The block is placed on another block")
         self.block_manipulating.placeBlock(coordinates)
         self.blocks.append(self.block_manipulating)
         self.block_manipulating = []
         return True 
     else:
         # Implement method for bridge block
         test_block = self.block_manipulating # Used to test whether the block can be placed on two points
         test_block.placeBlock(bottom_coordinates)
         possible_coordinates = test_block.get_positions
         #print('Possible coordinates {}'.format(possible_coordinates))
         blocks_below = 0
         for cord in possible_coordinates:
             #print('Coordinates to check : {}'.format(cord))
             if self.isBlock(cord):
                 blocks_below +=1
                 Debug.msg('There is a block below but not in the center')
         if blocks_below >= 2:
             Debug.msg("The block is placed on multiple other blocks")
             self.block_manipulating.placeBlock(coordinates)
             self.blocks.append(self.block_manipulating)
             self.block_manipulating = []
             return True  
         else:
             message = "Der Block kann nicht in der Luft losgelassen werden. Platziere den Block auf dem Boden oder auf einem anderen Block"
             Debug.error(message)
             raise RobotError(ErrorCode.E0015, message)
     return check 
Esempio n. 29
0
 def action(self, total_bet, raise_amount, big_blind, closing_action):
     action_prompt = Debug.create_action_prompt(self)
     action_str = input(action_prompt)
     return action_str
Esempio n. 30
0
 def deal_cards(self):
     for c in range(2):
         for p in self.players:
             p.get_card(self.deck.get_card())
     Debug.print_cards(self.players)