def new_peer(message): d = message.data t = TableManager().current() for md5 in d: if t: player = t.find_player(md5) if player is None: t.add_player_by_md5(md5.playerName)
def game_over(message): d = message.data t = TableManager().current() if t: t.update_players(d.players) t.update_table(d.table) t.update_winners_info(d.winners) t.game_over()
def update_board_info(message): d = message.data t = TableManager().current() if t: t.update_table(d.table) t.update_players(d.players) t.update_action(d.action) t.show_action()
def init(self): self.registe_handler(TexasSitTableReq, TexasSitTableResp, self.handle_sit_table) self.registe_handler(TexasUpdatePlayerReq, TexasUpdatePlayerResp, self.handle_update_player) self.room_id = self.serviceId self.table_manager = TableManager(self) self.redis = self.server.redis
def start_of_new_round(message): d = message.data t = TableManager().current() if t: t.update_table(d.table) t.update_players(d.players) t.new_round()
def end_round(message): d = message.data t = TableManager().current() if t: t.update_table(d.table) t.update_players(d.players) t.end_round()
def __init__(self, customer_visiting_period: int): billing_period = 5 cash_desk_num = 1 cooks_num = 3 table_quantity = 20 self.__visiting_period = customer_visiting_period self.__table_manager = TableManager(table_quantity) self.__kitchen = Kitchen(cooks_num) self.__bill_manager = BillManager(billing_period, cash_desk_num) self.__number_of_customers = 0 self.__waiting_customers = [] self.__food_name = {1: "스테이크", 2: "스파게티", 3: "마카로니", 4: "그라탱"} self.__food_eating_time = {1: 30, 2: 20, 3: 15, 4: 10} self.__food_cooking_time = {1: 30, 2: 20, 3: 10, 4: 15}
def deal(message): d = message.data t = TableManager().current() if t: t.update_table(d.table) t.update_players(d.players)
def request_bet(message): d = message.data t = TableManager().current() if t: t.update_table(d.game) t.update_players(d.game.players) player = t.bot() if player: player.update_self(d.self) player.do_actions(t, True)
def new_peer_2(message): d = message.data t = TableManager().current() if t: t.number = d.tableNumber t.status = d.tableStatus logger.info("[__new_peer_2] table number is: %s", t.number) if settings.TRAINING_MODE: logger.info( "[__new_peer_2] http://poker-training.vtr.trendnet.org:3001/game.html?table=%s", t.number) utils.generate_logs(t.number) for pjson in d.players: player = t.find_player(pjson.playerName) if player: player.is_online = pjson.isOnline else: player = Player(pjson.playerName) player.is_online = pjson.isOnline logger.info("[__new_peer_2] player name is: %s, is_online: %s", player.md5[:5], player.is_online)
def test_usability(self, io): io.print('Getting input......') n = io.get('n') b = io.read() io.print('Succefully got input') io.print('Getting table......') path = 'tables/table_manager{:d}.data'.format(n) if os.path.exists(path): tablem = io.load_table(n) else: io.print('table not found, start generating a new table') tablem = TableManager(n) tablem.generate_encode() tablem.generate_decode() io.store_table(tablem) io.print('Successfully got table') encoder = Encoder(b) io.print('Start encoding...') encoder.encode(tablem) io.print(encoder.result, v=1) io.print('Encoding successfully!') decoder = Decoder(encoder.seg_len, encoder.result) io.print('Start decoding...') decoder.decode(tablem) io.print('Decoding successfully!') io.print('Check decoding result') same = (encoder.inp == decoder.result) if same: io.print('Same!') io.print('origin', encoder.inp, v=1) io.print('decoded', decoder.result, v=1) elif encoder.inp == decoder.result[0:-1]: io.print('Same except last byte!') io.print('Input: ', encoder.inp, v=1) io.print('Decoding result:', decoder.result, v=1) else: io.print('Failed!') io.print('Input ', encoder.inp, v=1) io.print('Result', decoder.result, v=1) io.print('Writing decoding result...') io.write(decoder.result) io.print('Done')
def get_table(n, io=None, path=None): global DEFAULT_PATH # init if io is None: io = IO() if path is None: path = DEFAULT_PATH.format(n) if os.path.exists(path): # try to load table from local file system tablem = io.load_table(n) else: io.print('table not found, start generating a new table', v=1) io.print('this might take some time...', v=1) # start calculating encoding and decoding tables tablem = TableManager(n) tablem.generate_encode() tablem.generate_decode() io.store_table(tablem) io.print('got table and stored table for n={:d} successfully'.format(n), v=1) return tablem
class Restaurant: def __init__(self, customer_visiting_period: int): billing_period = 5 cash_desk_num = 1 cooks_num = 3 table_quantity = 20 self.__visiting_period = customer_visiting_period self.__table_manager = TableManager(table_quantity) self.__kitchen = Kitchen(cooks_num) self.__bill_manager = BillManager(billing_period, cash_desk_num) self.__number_of_customers = 0 self.__waiting_customers = [] self.__food_name = {1: "스테이크", 2: "스파게티", 3: "마카로니", 4: "그라탱"} self.__food_eating_time = {1: 30, 2: 20, 3: 15, 4: 10} self.__food_cooking_time = {1: 30, 2: 20, 3: 10, 4: 15} def is_possible_to_wait(self, new_customer: Customer) -> bool: n = 0 lower_time_group = [] higher_time_group = [] for table in self.__table_manager.get_table_queue(): remaining_time = table.get_total_time() - ( table.get_elapsed_waited_time_for_food() + table.get_elapsed_eating_time()) if remaining_time < new_customer.get_maximum_waiting_time(): n += 1 lower_time_group.append(remaining_time) else: higher_time_group.append(remaining_time) if self.__waiting_customers: if len(self.__waiting_customers) < n: new_customer.set_remaining_time_by_new_table( sorted(lower_time_group)[len(self.__waiting_customers)]) return True else: if 1 <= n: new_customer.set_remaining_time_by_new_table( min(lower_time_group)) return True applicable_index = sorted(higher_time_group)[ len(self.__waiting_customers) - n] new_customer.set_remaining_time_by_new_table(applicable_index) return False def customer_visiting(self, elapsed_time: int): self.__number_of_customers += 1 new_customer = Customer(self.__number_of_customers, elapsed_time) print( f"{self.__number_of_customers}번째 손님이 시각 {elapsed_time} 분에 레스토랑에 도착했습니다." ) return new_customer def get_time_until_being_allocated_to_cook(self) -> int: result = 0 q = self.__kitchen.get_order_queue() if q: q = [self.__food_cooking_time[order[0]] for order in q] group = self.__kitchen.get_cooks_current_cooking_time() q.append(0) while q: group.sort() target = group.pop(0) result += target group = [i - target for i in group] group.append(q.pop(0)) return result def customer_entrance(self, customer: Customer): food_num = randrange(1, 5) food_eating_time = self.__food_eating_time[food_num] food_cooking_time = self.__food_cooking_time[food_num] customer.set_attribute((food_num, food_eating_time, food_cooking_time)) table_num = self.__table_manager.set_customer(customer) customer_number = customer.get_customer_number() time_until_being_allocated_to_cook = self.get_time_until_being_allocated_to_cook( ) customer.set_total_time(time_until_being_allocated_to_cook + customer.get_food_cooking_time() + customer.get_food_eating_time()) print(f"{customer_number}번 손님이 {table_num}번 테이블에 앉습니다.") print(f"{customer_number}번 손님이 {food_num}번 요리" f" ({self.__food_name[food_num]})를 주문합니다.") self.__kitchen.get_order_from_new_customer(customer, table_num) def receive_customer(self, customer: Customer): self.__waiting_customers.append(customer) def pop_waiting_queue(self, pop_count: int): if pop_count != 0: for _ in range(pop_count): self.__waiting_customers.pop(0) def waiting_update(self): if self.__waiting_customers: customer_count = 0 for customer in self.__waiting_customers: customer.waiting_update() for customer in self.__waiting_customers: if customer.get_elapsed_waiting_time( ) < customer.get_remaining_time_by_new_table(): break if customer.get_elapsed_waiting_time( ) == customer.get_remaining_time_by_new_table( ) and not self.__table_manager.is_table_full(): self.customer_entrance(customer) customer_count += 1 self.pop_waiting_queue(customer_count) def run(self): elapsed_time = 0 while elapsed_time < 720: elapsed_time += 1 table_target_customer_queue = self.__table_manager.update() for customer in table_target_customer_queue: self.__bill_manager.receive_customer(customer) self.__bill_manager.update() if self.__table_manager.is_exist(): finished_order_queue = self.__kitchen.update() if finished_order_queue: for order in finished_order_queue: self.__table_manager.getting_food(order) self.waiting_update() if elapsed_time % self.__visiting_period == 0: new_customer = self.customer_visiting(elapsed_time) if self.__table_manager.is_table_full(): if self.is_possible_to_wait(new_customer): self.receive_customer(new_customer) else: print( f"손님이 기다릴 수 없어 돌아갑니다.\n현재 대기 시간 {new_customer.get_elapsed_waiting_time()}분 / 대기 가능 시간 " f"{new_customer.get_remaining_time_by_new_table()}분" ) else: self.customer_entrance(new_customer) self.__kitchen.start_cooking_update()
class TexasService(GameService): def setup_route(self): self.registe_command(TexasLeaveTableReq, TexasLeaveTableResp, self.handle_leave_table) self.registe_command(TexasBetActionReq, TexasBetActionResp, self.handle_bet_action) self.registe_command(TexasQueryPlayerReq, TexasQueryPlayerResp, self.handle_query_player) def init(self): self.registe_handler(TexasSitTableReq, TexasSitTableResp, self.handle_sit_table) self.registe_handler(TexasUpdatePlayerReq, TexasUpdatePlayerResp, self.handle_update_player) self.room_id = self.serviceId self.table_manager = TableManager(self) self.redis = self.server.redis def get_table(self, user): return self.table_manager.get_player_table(user) @USE_TRANSACTION def handle_sit_table(self, session, req, resp, event): if event.srcId != 5800: if systemhelper.is_texas_close(req.header.user): resp.header.result = RESULT_FAILED_TEXAS_FIX return table = None self.table_manager.lock.acquire() try: result,table = self.table_manager.sit_table(req.body.table_id, \ req.header.user,event.srcId, req.body.not_tables) if result < 0: resp.header.result = result return table.get_proto_struct(resp.body.table) if table.game != None: if req.header.user in table.game.gamblers: gambler = table.game.gamblers[req.header.user] if len(gambler.pokers) > 0: resp.body.own_pokers.uid = gambler.uid for poker in gambler.pokers: poker.get_proto_struct( resp.body.own_pokers.pokers.add()) else: if table.game.status > TEXAS_START: table.game.new_watch(req.header.user) resp.body.room_id = self.room_id resp.header.result = result except: traceback.print_exc() finally: self.table_manager.lock.release() @USE_TRANSACTION def handle_bet_action(self, session, req, resp, event): table = self.get_table(req.header.user) if table == None: resp.header.result = RESULT_FAILED_INVALID_TABLE return False game = table.game table.lock.acquire() try: if req.body.texas_status != table.game.status: result = RESULT_FAILED_NOT_START else: result = game.bet(req.header.user, req.body.bet_type, req.body.action_gold, req.body.bet_reward_gold) resp.header.result = result except: traceback.print_exc() finally: table.lock.release() @USE_TRANSACTION def handle_leave_table(self, session, req, resp, event): table = self.get_table(req.header.user) if table == None: resp.header.result = RESULT_FAILED_INVALID_TABLE return table.lock.acquire() try: resp.header.result = table.remove_player(req.header.user) if len(table.players) == 0 and table.game != None: table.game.handle_hand(-1) finally: table.lock.release() @USE_TRANSACTION def handle_query_player(self, session, req, resp, event): table = self.get_table(req.body.uid) if table == None: resp.header.result = RESULT_FAILED_INVALID_TABLE return False player = table.players[req.body.uid] player.get_brief_proto_struct(resp.body.player_brief) player_record = session.query(TTexasPlayer).filter( TTexasPlayer.uid == player.uid).first() if player_record: resp.body.play_count = player_record.play_count resp.body.win_rate = int(player_record.win_count / float(player_record.play_count) * 100) resp.body.big_win_gold = player_record.max_win_gold else: resp.body.play_count = 0 resp.body.win_rate = 0 resp.body.big_win_gold = 0 resp.header.result = 0 @USE_TRANSACTION def handle_update_player(self, session, req, resp, event): table = self.get_table(req.header.user) if table == None: return False table.lock.acquire() try: table.update_player_info(req.header.user) finally: table.lock.release() return False
return func return wrapper if __name__ == '__main__': bot_name = "" if len(sys.argv) >= 2: bot_name = str(sys.argv[1]) settings.bot_name = bot_name else: bot_name = settings.bot_name if settings.TRAINING_MODE: client = TexasPokerClient(settings.TRAINING_SERVER_URL) client.start() else: client = TexasPokerClient(settings.BATTLE_SERVER_URL) client.start() try: bot = Bot(client=client, name=bot_name) bot.join() table_mgr = TableManager() table_mgr.create(client).add_player_by_obj(bot) except KeyboardInterrupt: client.on_close()