Example #1
0
    def main(self):
        """
        ゲーム全体(ポーカー + ダブルアップチャンス)
        """
        can_play_game = True

        while can_play_game:

            # ゲームごとにplayer情報リセット
            player = Player()

            # 山札セット(セット数を決める) = ゲームごとに山札再構築
            deck = stock.Deck()
            poker = Poker(deck, player)
            poker.main_game()

            # 役ありはダブルアップチャンス
            print(player.is_poker_win)
            if player.is_poker_win:
                bonus_game = DoubleUp(player)
                bonus_game.main_game()

            # ゲームリスタート
            restart_msg = "Qでゲーム終了、それ以外でゲームスタート:"
            start_res = input(restart_msg)
            if start_res == 'Q':
                can_play_game = False
Example #2
0
 def __init__(self, near, room_id, ui):
     self.ui = ui
     self.room_id = room_id
     self.near = near
     self.poker = Poker(near, room_id)
     self.player_id = None
     self.cards = []
     self.load()
     super().__init__()
Example #3
0
    def __init__(self, ret):
        from services import ServiceGame
        self.manager = ServiceGame.share()
        self.__flow = ""  # 桌子日志
        self.__tid = ret.tid
        self.__zid = ret.zid
        self.__round_id = ret.roundid
        self.__curr_seat_id = -1
        self.__seats = [None] * TOTAL_SEAT
        self.__round_results = {}
        self.__is_dark = False  # 最后一手下注的明暗状态
        self.__last_bet = 0  # 最后一手下注的数量
        self.__total_bet = 0  # 累积下注
        self.__raise_rate = 0  # 当前的加注倍数
        self.__round_count = 0  # 轮数
        self.__wait_seconds = 0  # 临时等待玩家的时间秒数,用于比牌时播放动画
        self.__game_wait_seconds = 0  # 等待开桌的计时
        self.__button = -1  # 庄家ID
        self.__random_button = True  # 随机庄家
        self.__duel_dict = {0: set(), 1: set(), 2: set(), 3: set(), 4: set()}
        self.__winner = None  # 最后的比牌赢家

        self.__timer = None  # 游戏的定时器
        self.__poker = Poker()  # 初始化扑克信息

        self.__consume = self.manager.zone_consume_chip(self.__zid)  # 消耗金币数
        self.__base_chip = self.manager.zone_base_chip(self.__zid)  # 基数
        self.__limit_chip = self.manager.zone_limit_chip(self.__zid)  # 最低筹码
        self.__total_hands = self.manager.zone_total_hands(self.__zid)  # 最高下注倍数
        self.__status = TABLE_READY
Example #4
0
 def __init__(self):
     self.users = set()
     self.poker = Poker()
     self.in_game = False
     self.pause = False
     self.pause_time = 10
     self.pause_start = 0
     self.play_time = 30
     self.play_start = 0
Example #5
0
def main():
    poker_game = Poker()
    player_one = raw_input('Player one playing? (y/n) ')
    player_two = raw_input('Player two playing? (y/n) ')
    if player_one == 'y' or player_one == 'Y':
        player_one_hand = poker_game.get_hand()
        player_one_rank = poker_game.classify_hand(player_one_hand)
        print('Player one: ', player_one_rank)
    if player_two == 'y' or player_two == 'Y':
        player_two_hand = poker_game.get_hand()
        player_two_rank = poker_game.classify_hand(player_two_hand)
        print('Player 2', player_two_rank)
        poker_game.compare_hands(player_one_hand, player_two_hand)
	def setup_starting_hand(self):
		# Game Title and Welcome
		print("\n *** Harvard Hold'em Poker Bot *** \n")
		print("Welcome. Let's get the game started...")
		self.numplayers = 5
		self.player = Player(input("Enter your name: \n"))
		self.players = [Bot(i) for i in range(1, self.numplayers)]
		self.players.insert(0, self.player)
		self.poker = Poker()
		self.small_blind = 2
		self.big_blind = 1
		self.go_first = 0
		self.setup()
Example #7
0
def main():
    po = Poker()

    hero_pos = input('HERO (BTN or BB):')
    if hero_pos == 'BTN' or hero_pos == 'btn':
        hero_pos = 'BTN'
    else:
        hero_pos = 'BB'
    villan_pos = input('VILLAN (Those who are not heroes):')
    if villan_pos == '':
        if villan_pos == 'BTN':
            villan_pos = 'BB'
        else:
            villan_pos = 'BTN'
    print('BTNopen')
    act_str = input('BB 3bet or call :')
    if act_str == '3bet' or act_str == '3':
        act = 3
        if hero_pos == 'BTN':
            hero = np.where(BTNopen==3, 1, 0)
            villan = np.where(BBvsBTN>=3, 1, 0)
        else:
            villan = np.where(BTNopen==3, 1, 0)
            hero = np.where(BBvsBTN>=3, 1, 0)
    else:
        act = 2
        if hero == 'BTN':
            hero = np.where(BTNopen>=2, 1, 0)
            villan = np.where(BBvsBTN==2, 1, 0)
        else:
            hero = np.where(BTNopen>=2, 1, 0)
            villan = np.where(BBvsBTN==2, 1, 0)

    print('hero')
    print(hero)
    print('villan')
    print(villan)
    hero_prb = po.set_player(hero)
    villan_prb = po.set_player(villan)

    po.set_board(input('flop board(ex: QhJhTh): '))
    hero_df = po.create_df(hero_prb)
    villan_df = po.create_df(villan_prb)
    print('hero_df', hero_pos)
    print(hero_df)
    print('villan_df', villan_pos)
    print(villan_df)

    '''a_hit = np.sum(a_prb*(~pair), axis=0) + np.sum(a_prb*(~pair), axis=1)
Example #8
0
def main():
    #create a poker object
    thePoker = Poker()
    #shuffle this poker
    thePoker.shuffle()
    for cards in thePoker.cards:
        cards.makeShowCase()
    #create a rule object
    #texasHoldem = Rule()
    #create new players
    players = [Player('东邪'), Player('西毒'), Player('南帝'), Player('北丐')]
    #for _ in range(5):
    for i in range(0, 5):
        for player in players:
            player.getCard(thePoker.next())
            print("Cards before arrange: ")
            player.showCardsInHand()
            print("")
    #newArr = sorted(players,reverse=True)

    for player in players:
        #: arrange players' cardsInHand
        player.arrange()
        print("Cards after arrange: ")
        player.showCardsInHand()
        player.findType()
        player.ifFlushStraight()
        print("")

    newArr = sorted(players, reverse=True)

    for i in newArr:
        print(i.name + ': ' + i._cardsType, end=' ' + '\n')
        i.showCardsInHand()

    print('\n' + 'Winner is: ' + newArr[0].name + 'with ' +
          newArr[0]._cardsType)
Example #9
0
	def __init__(self,playerArr):
		# STARTING GAME
		self.pokerRules = Poker()

		# CREATING PLAYERS
		playerFactory = pokerPlayerFactory()
		self.players = []
		for player in playerArr:
			playerName = player[0]
			playerType = player[1]
			newPlayer = playerFactory.newPokerPlayer(playerName,playerType)
			self.players.append(newPlayer)
		random.shuffle(self.players,random.random)


		# PLAYER ORDER
		playerOrder = []
		for player in self.players:
			playerOrder.append(player.name)
Example #10
0
    def rate(player_cardgroup_2, pool):
        poker = Poker(1)

        player_value, _ = TexasHoldem.max_value(player_cardgroup_2, pool)

        win_times = 0
        times = 0
        for li in TexasHoldem.to2(52):
            cardgroup = CardGroup()
            for i, v in enumerate(li):
                if v:
                    cardgroup.append(poker.cards[i])
            if not cardgroup.is_req(pool):
                value, _ = TexasHoldem.max_value(cardgroup, pool)
                if value < player_value:
                    win_times += 1
                times += 1
            #print(win_times, times)
        return win_times, times
Example #11
0
    def game(self, debug=False):
        # print('Game #############')
        poker = Poker(1)
        poker.shuffle()

        pool = CardGroup()
        for player in self.players:
            player.clear()

        for _ in range(2):
            for player in self.players:
                player.append(poker.pop())

        for _ in range(2):
            pool.append(poker.pop())

        scores = {}
        for player in self.players:
            scores[player] = 0

        for _ in range(3):
            pool.append(poker.pop())
            values = {}
            values['min_score'] = 0
            for player in self.players:
                score = player.step(values)

                if score > values['min_score']:
                    scores[player] += score
                    values['min_score'] = score
                elif score == values['min_score']:
                    scores[player] += score

        win_player = None
        win_value = 0
        for player in self.players:
            max_value, _ = self.max_value(player.get_cardgroup(), pool)
            if win_value < max_value:
                win_player = player
                win_value = max_value

        win_player.win(sum(scores.values()))
Example #12
0
Created on 23 okt. 2012

@author: Boris
'''

from poker import Poker

class Bot(object):
    '''
    In order to evaluate poker hand strength, I recommend
    checking out this:
    https://github.com/aliang/pokerhand-eval
    '''
    
    def make_move(self, poker, time_out):
        '''
        Define this function to make your bot work
        '''
        return 'raise %d' % (poker.pot_size()+2*poker.current_bet())

    def __init__(self):
        '''
        Constructor, add stuff if you like
        '''
        pass

if __name__ == '__main__':
    bot = Bot()
    poker = Poker()
    poker.run(bot)
Example #13
0
k = (raw_input("Enter initial money of each players(as least 20 dollars):"))
while (not k.isdigit()):
    print "error,you must input a number,the number of each round must be as least 20 dollars"

    k = raw_input("Enter number of each round: ")
k = int(k)
while (k < 20):
    print ""
    print "error,you must input a number,the number of each round must be as least 20 dollars"
    k = raw_input("Enter number of each round: ")
    if k.isdigit():
        k = int(k)
money_of_each_player = float(k)
#--------------------------------------------------------------
poker = []
poker.append(Poker(number_of_players, money_of_each_player, debug))
#-------input judgement part----------------------------------
k = []
k = (raw_input("Enter round of game:"))
while (not k.isdigit()):
    print "error,you must input a number,the number of players at least be 1"

    k = raw_input("Enter round of game: ")
k = int(k)
while (k < 1):
    print ""
    print "error,you must input a number,the number of players at least be 1"
    k = raw_input("Enter round of game: ")
    if k.isdigit():
        k = int(k)
round_amount = k
Example #14
0
from poker import Poker

"""
def bet_loop(poker):
    stay = poker.players
    fold = set()
    pool = cycle(stay)    
    for p in pool:
"""

if __name__ == "__main__":
    p1 = Player('P1', 1000)
    p2 = Player('P2', 1000)
    p3 = Player('P3', 1000)
    
    poker = Poker()

    while True:
        poker.start_game()
        poker.register_player(p1)
        poker.register_player(p2)
        poker.register_player(p3)
        poker.deliver()
        print(p1)
        print(p2)
        print(p3)
        #bet_loop(poker)
        for i, p in enumerate(poker.players):
            if i == 0:
                poker.get_money(p.bet(50))
            elif i == 1:
Example #15
0
 def test_three_of_a_kind(self):
     result = [6, 1, 6, 2, 6]
     self.assertEqual(4, Poker.CheckScore(result))
Example #16
0
 def setUp(self):
     p1 = Player('P1', 1000)
     p2 = Player('P2', 1000)
     self.poker = Poker([p1, p2])
Example #17
0
 def test_five_of_a_kind_at_3(self):
     result = [3, 3, 3, 3, 3]
     self.assertEqual(6, Poker.CheckScore(result))
Example #18
0
 def test_check_alays_score7_vs_score7_totalp1_is_win(self):
     result1 = [6, 2, 3, 4, 5]
     result2 = [1, 2, 3, 4, 5]
     self.assertEqual(1, Poker.winner(result1, result2))
Example #19
0
 def test_check_p2win_score1_vs_score7(self):
     result1 = [2, 3, 1, 4, 6]
     result2 = [1, 2, 3, 4, 5]
     self.assertEqual(2, Poker.winner(result1, result2))
Example #20
0
 def test_royal_flush(self):
     result = [1, 2, 3, 4, 5]
     self.assertEqual(7, Poker.CheckScore(result))
Example #21
0
 def test_check_p1win_score7_vs_score1(self):
     result1 = [1, 2, 3, 4, 5]
     result2 = [2, 3, 1, 4, 6]
     self.assertEqual(1, Poker.winner(result1, result2))
Example #22
0
 def test_high_card(self):
     result = [2, 3, 1, 4, 6]
     self.assertEqual(1, Poker.CheckScore(result))
Example #23
0
 def test_one_pair(self):
     result = [4, 2, 2, 3, 5]
     self.assertEqual(2, Poker.CheckScore(result))
Example #24
0
 def test_two_pair(self):
     result = [3, 3, 1, 6, 6]
     self.assertEqual(3, Poker.CheckScore(result))
Example #25
0
 def test_full_house1_2(self):
     result = [1, 1, 2, 2, 2]
     self.assertEqual(5, Poker.CheckScore(result))
Example #26
0
class PokerRoomWatcher(threading.Thread):
    def __init__(self, near, room_id, ui):
        self.ui = ui
        self.room_id = room_id
        self.near = near
        self.poker = Poker(near, room_id)
        self.player_id = None
        self.cards = []
        self.load()
        super().__init__()

    def load(self):
        # Load cards
        self.cards = load(self.filename("cards")) or []
        self.ui.cards = self.cards[:]

        # Load secret key
        self.secret_key = load(
            self.filename("secret_key")) or generate_secret_key()
        self.secret_key = int(self.secret_key)
        dump(self.filename("secret_key"), self.secret_key)

    def find_player_id(self):
        players = get(self.poker.deck_state(), 'Ok', 'players')

        if not self.near.account_id in players:
            logging.debug(
                f"{self.near.account_id} is not in game {self.room_id}. Found: {players}"
            )
            return True
        else:
            self.player_id = players.index(self.near.account_id)
            logging.debug(
                f"{self.near.account_id} playing in game {self.room_id}. Found {players}"
            )
            return False

    def update_state(self):
        self._state = self.poker.state()
        self._deck_state = self.poker.deck_state()
        self._poker_state = self.poker.poker_state()
        self._turn = self.poker.get_turn()
        self.ui.update_state(self.room_id, self._state, self._deck_state,
                             self._poker_state, self._turn)

    def is_deck_action(self):
        return get(self._state, 'Ok') == 'DeckAction'

    def check_deck_shuffling(self):
        if not self.is_deck_action():
            return

        index = get(self._deck_state, 'Ok', 'status', 'Shuffling')

        if index is None:
            return
        index = int(index)

        if index != self.player_id:
            return

        partial_shuffle = self.poker.get_partial_shuffle()["Ok"]
        delta = 2 if self.player_id == 0 else 0
        partial_shuffle = [int(value) + delta for value in partial_shuffle]
        partial_shuffle = encrypt_and_shuffle(partial_shuffle, self.secret_key)
        partial_shuffle = [str(value) for value in partial_shuffle]
        self.poker.submit_partial_shuffle(partial_shuffle)

    def filename(self, mode):
        node_env = os.environ.get("NODE_ENV", "")
        chain_enc = f"{self.near.node_url}-{self.near.contract}-{node_env}"
        suffix = hashlib.md5(chain_enc.encode()).hexdigest()[:8]
        return f"{self.near.account_id}-{self.room_id}-{mode}-{suffix}"

    def on_receive_card(self, card):
        if card in self.cards:
            return

        self.cards.append(card)
        dump(self.filename("cards"), self.cards)
        self.ui.update_card(self.room_id, card)

    def check_revealing(self):
        if not self.is_deck_action():
            return

        index = get(self._deck_state, 'Ok', 'status', 'Revealing', 'turn')

        if index is None:
            return

        index = int(index)

        if index != self.player_id:
            return

        progress = int(
            get(self._deck_state, 'Ok', 'status', 'Revealing', 'progress'))

        progress = str(partial_decrypt(progress, self.secret_key))

        if get(self._deck_state, 'Ok', 'status', 'Revealing',
               'receiver') == self.player_id:
            self.on_receive_card(int(progress) - 2)
            self.poker.finish_reveal()
        else:
            self.poker.submit_reveal_part(progress)

    def step(self):
        if self.player_id is None:
            if not self.find_player_id():
                return

        self.update_state()
        self.check_deck_shuffling()
        self.check_revealing()

    def run(self):
        time_to_sleep = 1.

        while True:
            self.step()
            time.sleep(time_to_sleep)
class Pokergame:
	def setup (self):
		self.minimumbet = 2
		self.pot = 0
		self.board_rank = 8
		self.communityCards = 3
		self.rounds = [(1, "Pre-flop"), (2, "Flop"), (3, "Turn"), (4, "The river")]
		self.deal_cards()
		self.round = self.get_next_round()

	def setup_starting_hand(self):
		# Game Title and Welcome
		print("\n *** Harvard Hold'em Poker Bot *** \n")
		print("Welcome. Let's get the game started...")
		self.numplayers = 5
		self.player = Player(input("Enter your name: \n"))
		self.players = [Bot(i) for i in range(1, self.numplayers)]
		self.players.insert(0, self.player)
		self.poker = Poker()
		self.small_blind = 2
		self.big_blind = 1
		self.go_first = 0
		self.setup()

	def setup_next_hand (self, players_still_in):
		print("\n\nYou're still in! You now have ${}".format(str(self.player._money)))
		print("Let's get the next hand started...")
		self.numplayers = len(players_still_in)
		self.players = players_still_in
		self.reset_moves()
		self.reset_bets()
		self.setup()

	def get_next_round(self):
		try:
			self.round = self.rounds.pop(0)
		except IndexError:
			self.round = (0, "end of round")
		self.start_round()

	def deal_cards(self):
		self.hands = self.poker.deal(self.numplayers + 1 + self.communityCards)
		for i in range(0, self.numplayers):
			self.players[i]._cards = self.hands[i]

		self.flopCards = [self.hands[7][0]] + self.hands[6]
		self.turnCards = [self.hands[7][1]]
		self.riverCards = [self.hands[8][0]]
		self.board = self.flopCards

	def announce_round(self):
		round_id, round = self.round
		if (self.small_blind == 0 and self.player._money > 1):
			self.player._money -= 1
			self.player._bet = 1
			print("\n{}!\nYou are the small blind. Your balance is now {}\n".format(
				round, str(self.players[0]._money)))
		elif (self.big_blind == 0 and self.player._money > 2):
			self.player._money -= 2
			self.player._bet = 2
			print("\n{}!\nYou are the big blind. Your balance is now {}\n".format(
				round, str(self.player._money)))
		else:
			print("\n{}!\n".format(round))
		if(self.player._move == "folded" or self.player._money == 0):
			self.bot_turns(2)
		else:
			print("\nthe minimum bet is {}, you have bet\n".format(
				self.minimumbet, self.player._bet))
			self.menu_loop()

	def get_menu (self):
		if (self.minimumbet == self.player.bet):
			return OrderedDict([
				("1", self.player.checked),
				("2", self.player.bet),
				("3", self.player.raised),
				("4", self.player.folded),
			])
		else:
			return OrderedDict([
				("1", self.player.called),
				("2", self.player.bet),
				("3", self.player.raised),
				("4", self.player.folded),
			])

	def menu_loop(self):
		"""show the menu"""
		menu = self.get_menu()
		round_id, round = self.round
		choice = None
		for key, value in menu.items():
			print('{}) {}'.format(key, value.__doc__))
		choice = input("\nWhat would you like to do?\n").strip()
		try:
			action, self.minimumbet, self.pot, out = menu[choice](round_id, self.minimumbet, self.pot)
		except KeyError:
			print("That is not a valid choice. Try again")
			time.sleep(1)
			self.menu_loop()
		if out: self.take_out(player)
		print("Your balance is now $" + str(self.player._money) +".\n")
		time.sleep(1)
		self.bot_turns(action)

	def bot_turns(self, action):
		round_id, round = self.round
		board_rank = self.poker.board_rank(self.board, round_id-1)
		predicted_hand = self.player.classifier.predict(action, round_id, board_rank)
		for bot in self.players:
			rank = self.poker.hole_rank(bot._cards)
			bluff = random.randint(1, 10)
			play_safe = random.randint(1, 10)
			if (bot == self.player or bot._move == "folded" or bot._bet >= self.minimumbet or 
				bot._money+2 < self.minimumbet):
				continue
			else:
				if (rank == predicted_hand and play_safe > 1):
					self.minimumbet, self.pot, out = bot.call(self.minimumbet, self.pot)
				elif (rank > predicted_hand):
					self.minimumbet, self.pot, out = bot.fold(self.minimumbet, self.pot)
				else:
					self.minimumbet, self.pot, out = bot.raised(self.minimumbet, self.pot)
				if out: self.take_out(bot)
		self.end_of_round()
	
	def end_of_round(self):
		winner = self.check_for_winner()
		action = self.player.get_action()
		under_min = len(self.players_under_min())
		if winner:
			if winner == self.player:
				player._money += self.pot
				time.sleep(1)
				print("\nEveryone else is out. You win the round")
				print("{} has been added to your balance.".format(self.pot))
			else:
				winner._money += self.pot
				time.sleep(1)
				print("\nPlayer {} won the round.".format(winner.index))
				print("{} has been added to player {}'s balance.".format(
					self.pot, winner.index))
			self.setup_next_hand(self.players)
		elif (self.player._bet < self.minimumbet and self.player._move != "folded" and
			self.player._money > 0):
			time.sleep(1)
			print("\nThe minumum bet is now {}, you have bet {}".format(
				self.minimumbet, self.player._bet))
			self.menu_loop()
		#elif under_min > 1:
			#self.bot_turns(action)
		else:
			self.reset_bets()
			self.rotate_blinds()

	def take_out(self, player):
		if player == self.player:
			print("You are out. You lost all of your money. Game over.")
		else:
			self.players.remove(player)

	def players_under_min(self):
		under_minbet = []
		for p in self.players:
			if p._bet < self.minimumbet and p._move != "folded":
				under_minbet.append(p)
		return under_minbet

	def check_for_winner(self):
		still_in = []
		for player in self.players:
			if player._move != "folded":
				still_in.append(player)
		if len(still_in) > 1:
			return False
		else: 
			return still_in.pop(0)

	def reset_bets(self):
		self.minimumbet = 2
		for p in self.players:
			p._bet = 0

	def reset_moves(self):
		for p in self.players:
			p._move = ""

	def rotate_blinds(self):
		if self.big_blind == self.numplayers-1 and self.player._move != "folded":
			self.big_blind = 0
		else: 
			self.big_blind += 1
		if self.small_blind == self.numplayers-1 and self.player._move != "folded":
			self.small_blind = 0
		else: 
			self.small_blind += 1
		if self.go_first == self.numplayers-1 and self.player._move != "folded":
			self.go_first = 0
		else:
			self.go_first += 1
		self.round = self.get_next_round()

	def update_hands(self, cards):
		for i in range(0, self.numplayers):
			if (self.players[i]._move != "folded"):
			    self.players[i]._cards += cards
			    self.hands[i] = self.players[i]._cards
	
	def find_best_hands(self):
		for i in range(0, self.numplayers):
		    if self.players[i]._move != "folded":
		        self.hands[i] = list(self.poker.best_hand(self.hands[i]))

	def start_round(self):
		round_id, round = self.round
		if (round_id == 1):
			
			# Places 2 Cards in Each Player's Hand
			for i in range(0, 3):
				sys.stdout.flush()
				time.sleep(.3)
				sys.stdout.write("\rDealing hole cards..")
				time.sleep(.3)
				sys.stdout.write("\rDealing hole cards....")
				time.sleep(.3)
				sys.stdout.write("\rDealing hole cards.....")

			# Displays User's Balance and Hand
			print("\n\nYour balance: ")
			print("$" + str(self.player._money))
			print("Your hand:")
			print(self.player._cards)
			self.announce_round()
		elif(round_id == 2):
			# Reveal Flop Cards
			# Flop - Dealer shows 3 Community Cards
			print("\nThe flops cards are...\n")
			print(self.flopCards)
			time.sleep(2)
			# Update the hands of the players with the flop cards
			self.update_hands(self.flopCards)
			self.announce_round()
		elif(round_id == 3):
			# Reveal Turn Card
			# Turn - Dealer shows 1 More Community Card
			print("\nThe turn card is...")
			print(self.turnCards)
			time.sleep(2)
			# Show all community cards
			print("The 4 community cards so far are...")
			print(self.turnCards + self.flopCards)
			time.sleep(1)
			# Update the hands of the players with the turn cards
			self.update_hands(self.turnCards)
			self.announce_round()
		elif(round_id == 4):
			# Reveal River Card
			# Turn - Dealer shows 1 More Community Card
			print("\nThe river card is...")
			print(self.riverCards)
			time.sleep(2)
			# Show all community cards
			print("The 5 community cards so far are...")
			print(self.riverCards + self.turnCards + self.flopCards)
			time.sleep(1)
			# Update the hands of the players with the turn cards
			self.update_hands(self.riverCards)
			# Show new hand including flop and turn cards
			if self.players[0]._move != "folded":
				print("\nWith the flop, turn, and river cards, your new 7 card hand is now...")
				print(self.hands[0])
				time.sleep(1)
				# Update all then hands with the best combo of 5 cards
			self.find_best_hands()
			self.announce_round()
		else:
		# Reveal The Winner
			print("\nHere comes the reveal of every player's best ranked hand!")
			dealercards = self.hands[5]
			print("\nThese are the dealers cards:" + str(dealercards) + "\n")
			# Call community cards to dealer's hand
			dealercards = dealercards + self.flopCards + self.turnCards + self.riverCards
			self.hands[5] = list(self.poker.best_hand(dealercards))
			time.sleep(1)
			print("The Dealer's best ranked hand is: " + str(self.hands[5]))

			if self.player._move != "folded":
				print("Your hand: " + str(self.hands[0]))
				time.sleep(1)

			for i in range(1, self.numplayers):
				if self.players[i]._move == "folded":
					# If a player folded update their cards in hands[i]
					self.hands[i] = []
				else:
					print("Player " + str(i+1) + ": " + str(self.hands[i]))
			# Before determining winner, make sure there are no null hands going
			# going in as input in poker() func
			winningHands = []
			for i in range(0, self.numplayers + 1): #Plys 1 for the dealers hand
				if self.hands[i] != []:
					winningHands += [self.hands[i]]

			# Need more than 1 value to unpack winner
			count2 = 0
			for i in range(0, self.numplayers):
				if self.players[i]._move == "folded":
					count2 += 1

			# Determine the winner of round
			print("\nThe winning hand is...")
			time.sleep(1)
			if count2 == 5:
				print("\nThe dealer has won!")
				print(str(self.hands[5]))
			else:
				winningPlayer = self.poker.poker(winningHands)
				winner = winningPlayer[0]
				print(str(winner))
				if self.hands[0] == winner:
					print("\nYou have won the round...Congratulations! ")
					self.player._money += self.pot
					print("$" + str(self.pot)+" has been added to your balance!")
				elif self.hands[5] == winner:
					print("\nSorry, the dealer has won!")
				else:
					for i in range(1, self.numplayers):
						if self.hands[i] == winner:
							print("\nPlayer " + str(i+1) + " has won.")
							self.players[i]._money += self.pot
							print("$" + str(self.pot) + " has been added to Player " + str(
								i+1) + "'s balance.")
			players_still_in = []
			for p in self.players:
				if p._money > 0:
					players_still_in.append(p)
				else:
					pass
			if(self.player._money <= 0):
				print("You are out. You lost all of your money. Game over.")
			elif (len(players_still_in) == 1):
				print("You won the Game. You won{}".format(self.player._money))
			else:
				self.setup_next_hand(players_still_in)

	def __init__(self): 
		self.setup_starting_hand()
Example #28
0
import os
from poker import Poker

def test_place(first_deck, second_deck):
  game = poker.Poker(first_deck, second_deck)
  print game.test()


f = open(os.path.expanduser("~/Documents/Development/Python/Project/Euler/input/54.txt"), "r")

first_decks = []
second_decks = []

while True:
    line = f.readline()
    if not line: break

    match = line.strip('\n').split(" ")

    first_decks.append(match[:5])
    second_decks.append(match[5:])


poker_game = Poker(first_decks, second_decks)
print poker_game.play()
Example #29
0
class Referee(object):
    """游戏裁判"""

    def __init__(self, ret):
        from services import ServiceGame
        self.manager = ServiceGame.share()
        self.__flow = ""  # 桌子日志
        self.__tid = ret.tid
        self.__zid = ret.zid
        self.__round_id = ret.roundid
        self.__curr_seat_id = -1
        self.__seats = [None] * TOTAL_SEAT
        self.__round_results = {}
        self.__is_dark = False  # 最后一手下注的明暗状态
        self.__last_bet = 0  # 最后一手下注的数量
        self.__total_bet = 0  # 累积下注
        self.__raise_rate = 0  # 当前的加注倍数
        self.__round_count = 0  # 轮数
        self.__wait_seconds = 0  # 临时等待玩家的时间秒数,用于比牌时播放动画
        self.__game_wait_seconds = 0  # 等待开桌的计时
        self.__button = -1  # 庄家ID
        self.__random_button = True  # 随机庄家
        self.__duel_dict = {0: set(), 1: set(), 2: set(), 3: set(), 4: set()}
        self.__winner = None  # 最后的比牌赢家

        self.__timer = None  # 游戏的定时器
        self.__poker = Poker()  # 初始化扑克信息

        self.__consume = self.manager.zone_consume_chip(self.__zid)  # 消耗金币数
        self.__base_chip = self.manager.zone_base_chip(self.__zid)  # 基数
        self.__limit_chip = self.manager.zone_limit_chip(self.__zid)  # 最低筹码
        self.__total_hands = self.manager.zone_total_hands(self.__zid)  # 最高下注倍数
        self.__status = TABLE_READY

    # 玩家之间的比牌详情
    def duelers_init(self):
        for i in xrange(0, TOTAL_SEAT):
            self.__duel_dict[i].clear()
            self.__duel_dict[i].add(i)

    @property
    def status(self):
        return self.__status

    # 设置桌子状态
    def set_status(self, status):
        self.__status = status
        self.play_log("set status: %d" % (status, ))

    @property
    def zid(self):
        return self.__zid

    @property
    def tid(self):
        return self.__tid

    @property
    def base_chip(self):
        return self.__base_chip

    @property
    def raise_rate(self):  # 当前加注倍率
        return self.__raise_rate

    # 寻找桌子内的空位
    def search_empty_seat(self):
        for seatid in range(0, TOTAL_SEAT):
            if not self.__seats[seatid]:
                return seatid
        return -1

    # 判断玩家是否在桌子内的流程
    def in_table(self, uid):
        if uid <= 0:
            return False
        for seatid in range(0, TOTAL_SEAT):
            if self.__seats[seatid] and self.__seats[seatid].uid == uid:
                return True
        return False

    # 根据玩家uid来获得玩家的坐位ID
    def get_seatid(self, uid):
        for i in range(0, TOTAL_SEAT):
            if self.__seats[i] and self.__seats[i].uid == uid:
                return i
        return -1

    # 扣除玩家税收,返回所扣到的总钱数
    def tax(self, chip):
        if chip <= 0:
            return 0
        tax_chip = 0
        for seatid in range(0, TOTAL_SEAT):
            if not self.__seats[seatid] or self.__seats[seatid].status != player.IN_PLAYING:
                continue
            if 0 < self.__seats[seatid].setChipWithDB(chip, False):
                tax_chip += chip
            self.__seats[seatid].setDark(True)
        return tax_chip

    # 一局开始前下底注
    def base_bet(self, chip):
        if chip <= 0:
            return 0
        base_chip = 0
        for seatid in range(0, TOTAL_SEAT):
            if not self.__seats[seatid] or self.__seats[seatid].status != player.IN_PLAYING:
                continue
            if self.__seats[seatid].bet(chip):
                base_chip += chip
        return base_chip

    # 通知所有的玩家开始游戏
    def notify_game_start(self):
        for i in range(0, TOTAL_SEAT):
            p = self.__seats[i]
            if not p or p.status != player.IN_WAITING:
                continue
            p.onRoundStart()

    # 一位用户进入房间,收集房间信息并返回给客户端
    def sit_down(self, p):
        if self.in_table(p.uid):
            seatid = self.get_seatid(p.uid)
        else:
            seatid = self.search_empty_seat()

        if seatid < 0:
            return ERR_SEAT_FULL
        self.__seats[seatid] = p
        # 玩家响应坐下,保存桌子ID,设置在线,清除手牌,保存坐位ID等操作
        p.on_sit_down(self.__tid, seatid)
        self.manager.update_table_player_num(self.__zid, self.__tid, self.play_num)

        self.on_sit_down_success(p)
        return OK

    # 统计当前在房间的人数
    @property
    def play_num(self):
        count = 0
        for i in range(0, TOTAL_SEAT):
            if self.__seats[i]:
                count += 1
        return count

    # 检查是否已经满足条件可以开始游戏
    def check_start(self):
        if self.status == TABLE_READY and 3 <= self.play_num:  # 可以开局
            self.set_status(TABLE_START)
            DelayCall(1, self.game_start)
        else:
            # print 'CheckStart NOT IN START: ', self.status, self.play_num, self.GameWaitSeconds, self.__seats
            #Manager.debug(self.__zid, self.__tid)
            pass

    # 游戏开局
    def game_start(self):
        self.manager.update_table_player_num(self.__zid, self.__tid, self.play_num)
        self.set_status(TABLE_PLAYING)
        self.clear_duel()
        self.clear_round_result()
        self.__winner = None
        self.__is_dark = True
        self.__last_bet = self.__base_chip
        self.__raise_rate = 0
        self.__curr_seat_id = -1
        self.__round_id += 1
        self.__round_count = 0
        self.__poker.shuffle()  # 洗牌
        self.duelers_init()  # 比牌关系清除
        self.notify_game_start()  # 开局前通知玩家清理
        self.tax(self.__consume)
        self.__total_bet = self.base_bet(self.__base_chip)
        self.__flow = ''  # 清空打牌日志
        self.select_button()  # 选择庄家
        self.play_log('Round %d start, Tax:%d, Button:%d' %
                     (self.__round_id, self.__consume, self.__button))
        self.send_cards()  # 发牌

        for seatid in range(0, TOTAL_SEAT):
            p = self.__seats[seatid]
            if not p or p.status != p.IN_PLAYING:
                continue
            send_data = [CONFIG.game_id, CMD_ROUND_START, self.__zid, self.__tid,
                         self.__consume, self.__base_chip, self.__total_bet, self.__button]
            p.send(send_data)

        DelayCall(ROUND_START_SECONDS, self.turn_to_next, self.__button, True)

    # 选择庄家,第一轮是随机选庄
    def select_button(self):
        if self.__random_button or 0 > self.__button or TOTAL_SEAT <= self.__button:
            self.__random_button = False
            self.__button = 0
            ulist = []  # 集合
            for i in xrange(0, TOTAL_SEAT):
                if self.__seats[i] and self.__seats[i].status == player.IN_PLAYING:
                    ulist.append(i)
            if ulist and len(ulist) > 0:
                random.shuffle(ulist)
                self.__button = ulist[0]
        return self.__button

    # 发牌
    def send_cards(self):
        for i in xrange(0, 3):
            for j in xrange(0, TOTAL_SEAT):
                if not self.__seats[j]:
                    continue
                self.__seats[j].receiveCard(self.__poker.pop())

    # 获得玩家可操作的动作
    def get_play_actions(self, p):
        ret = list()
        ret.append(CMD_USER_LOOK)
        ret.append(CMD_USER_FOLD)
        if not p:
            return ret
        min_chip = self.calc_call_chip(p.is_dark)
        # 跟死自负
        if p.uchip >= min_chip and p.total_bet / self.__base_chip < self.__total_hands:
            ret.append(CMD_USER_CALL)
            if self.__raise_rate < MAX_RAISE_RATE:
                ret.append(CMD_USER_RAISE)
            if self.can_duel:
                ret.append(CMD_USER_DUEL)
        return ret

    # 获得玩家的响应秒数
    def get_user_seconds(self, seatid, is_begginer=False):
        seconds = FIRST_CALL_SECONDS if is_begginer else CALL_SECONDS
        user_seconds = self.__seats[seatid].roundSeconds
        seconds = user_seconds if user_seconds > 0 else seconds
        return seconds

    # 玩家开始接收动作
    def turn_to_player(self, seatid, is_begginer=False):
        self.play_log('Turn to %d.' % (seatid, ))
        if not self.__seats[seatid]:
            self.play_log('user %d gone, turn to next next...' % (seatid, ))
            self.turn_to_next(seatid)
            return
        self.__seats[seatid].onTurnTo(self)
        seconds = self.get_user_seconds(seatid, is_begginer)

        actions = self.get_play_actions(self.__seats[seatid])  # 玩家可操作的动作
        send_data = [CONFIG.game_id, CMD_TURN_TO_PLAYER, self.__zid, self.__tid,
                     seatid, seconds, self.__round_count, actions]
        self.broad_cast(send_data)
        self.__timer = DelayCall(seconds, self.on_user_time_out, seatid)
        self.__curr_seat_id = seatid

    # 处理玩家超时
    def on_user_time_out(self, seatid):
        self.__seats[seatid].incrTimeOutTimes()
        self.user_fold(self.__seats[seatid])
        self.turn_to_next(seatid)

    # 检查是否合法的seatid
    @staticmethod
    def is_seatid(seat_id):
        return TOTAL_SEAT > seat_id >= 0

    # 记录玩家比牌关系
    def save_duel(self, seatid1, seatid2):
        if not self.is_seatid(seatid1) or not self.is_seatid(seatid2):
            return
        self.__duel_dict[seatid1].add(seatid2)
        self.__duel_dict[seatid1].add(seatid1)
        self.__duel_dict[seatid2].add(seatid1)
        self.__duel_dict[seatid2].add(seatid2)

    # 清除比牌关系列表
    def clear_duel(self):
        for i in xrange(0, TOTAL_SEAT):
            self.__duel_dict[i].clear()

    # 随机挑选出一个比牌的玩家
    def pick_enemy_random(self, uid):
        left_player = []
        for i in xrange(0, TOTAL_SEAT):
            if not self.__seats[i]:
                continue
            if self.__seats[i].uid != uid and self.__seats[i].status == player.IN_PLAYING:
                left_player.append(i)
        if not left_player:
            return False
        return random.choice(left_player)

    # 执行玩家的动作
    def do_user_action(self, p, cmd, ret):
        p.reset_time_out_times()  # 玩家请求成功,重置超时次数

        if cmd == CMD_USER_LOOK:  # 看牌不算一个动作,所以返回false以防止转到下一玩家
            self.user_check(p)
            return False
        elif cmd == CMD_USER_CALL:
            return self.user_call(p)
        elif cmd == CMD_USER_RAISE:
            if not ret or len(ret) != 3 or ret[2] < 1:
                self.manager.request_fail(p.uid, cmd, ERR_DATA_BROKEN)
                return False
            rate = ret[2]
            if rate not in RAISE_RATE_LIST:
                self.manager.request_fail(p.uid, cmd, ERR_DATA_BROKEN)
                return False
            if rate <= self.__raise_rate:
                self.manager.request_fail(p.uid, cmd, ERR_DATA_BROKEN)
                return False
            return self.user_raise(p, rate)
        elif cmd == CMD_USER_FOLD:
            return self.user_fold(p)
        elif cmd == CMD_USER_DUEL:
            if not ret or len(ret) != 3:
                self.manager.request_fail(p.uid, cmd, ERR_DATA_BROKEN)
                return False
            seatid = ret[2]
            if seatid < 0 or seatid >= TOTAL_SEAT:
                self.manager.request_fail(p.uid, cmd, ERR_SEAT_NOT_EXIST)
                return False
            p2 = self.__seats[seatid]
            if not p2:
                self.manager.request_fail(p.uid, cmd, ERR_USER_NOT_EXIST)
                return False
            return self.user_duel(p, p2)

        self.manager.request_fail(p.uid, cmd, ERR_ILLEGAL_OPERATION)
        return False

    # 处理玩家的游戏动作,包括看牌,下注/跟注,加注,弃牌,比牌,开牌
    def deal_user_action(self, p, ret):
        cmd = ret[1]
        if self.status != TABLE_PLAYING:  # 非游戏中不响应玩家游戏命令
            return self.manager.request_fail(p.uid, cmd, ERR_NOT_IN_PLAYING)
        if self.__curr_seat_id != p.seatid:  # 未轮到玩家
            return self.manager.request_fail(p.uid, cmd, ERR_NOT_YOUR_TURN)

        if cmd not in self.get_play_actions(p):  # 不允许进行的操作
            return self.manager.request_fail(p.uid, cmd, ERR_ILLEGAL_OPERATION)

        if not self.do_user_action(p, cmd, ret):
            return

        self.turn_to_next(self.__curr_seat_id)  # 下一个玩家继续

    # 处理机器人的游戏动作
    def deal_robot_action(self, robot, cmd, param1):
        if not self.do_user_action(robot, cmd, [CONFIG.game_id, cmd, param1]):
            return
        self.turn_to_next(self.__curr_seat_id)  # 下一个玩家继续

    # 玩家弃牌处理
    def user_fold(self, p):
        if p.seatid == self.__curr_seat_id:  # 只有当前玩家可以清除定时器
            self.cancel()
        chip = p.total_bet  # 玩家总下注
        exp = 0
        self.save_round_result(p.seatid, False, chip, exp)
        p.on_round_over(self, False, chip, exp, player.IN_FOLD)
        if p == self.__winner:
            self.__winner = None

        self.broad_cast([CONFIG.game_id, CMD_USER_FOLD, OK, p.seatid])
        return True

    # 计算跟牌、下注所需要的筹码
    def calc_call_chip(self, is_dark):
        if self.__is_dark == is_dark:
            return self.__last_bet
        if self.__is_dark and not is_dark:
            return self.__last_bet * 2
        return self.__last_bet / 2

    # 玩家下注/跟注
    def user_call(self, p):
        chip = self.calc_call_chip(p.is_dark)
        if not p.bet(chip):
            self.manager.request_fail(p.uid, CMD_USER_CALL, ERR_CHIP_NOT_ENOUGH)
            return False

        self.__total_bet += chip
        self.save_bet(chip, p.is_dark)
        self.cancel()
        send_data = [CONFIG.game_id, CMD_USER_CALL, OK, p.seatid,
                     int(p.is_dark), chip, self.__total_bet]
        self.broad_cast(send_data)
        return True

    # 玩家加注
    def user_raise(self, p, rate):
        minchip = self.calc_call_chip(p.is_dark)
        chip = self.__base_chip * rate

        if not p.is_dark:
            chip *= 2

        if chip < minchip:
            return self.user_call(p)

        if not p.bet(chip):
            self.manager.request_fail(p.uid, CMD_USER_RAISE, ERR_CHIP_NOT_ENOUGH)
            return False

        self.__raise_rate = rate
        self.__total_bet += chip
        self.save_bet(chip, p.is_dark)
        self.cancel()
        send_data = [CONFIG.game_id, CMD_USER_RAISE,
                     OK, p.seatid, int(p.is_dark), chip, rate, self.__total_bet]
        self.broad_cast(send_data)
        return True

    # 返回当前可否进行比牌的操作
    @property
    def can_duel(self):
        return self.__round_count >= 2

    # 玩家比牌
    # 第三轮及之后才可以比牌
    def user_duel(self, p1, p2):
        if not self.can_duel or not p2:
            self.manager.request_fail(
                p1.uid, CMD_USER_DUEL, ERR_ROUND_THREE_NEEDED)
            return False
        return True

    # 玩家看牌动作
    def user_check(self, p):
        p.set_dark(False)
        send_data = [CONFIG.game_id, CMD_USER_LOOK, OK, p.cards]
        p.send(send_data)

        # 广播玩家看牌
        send_data = [CONFIG.game_id, CMD_LOOK_BC, p.seatid]
        self.broad_cast(send_data)
        return True

    # 获得最后剩余的玩家
    def get_last_player(self):
        for i in xrange(0, TOTAL_SEAT):
            if not self.__seats[i]:
                continue
            if self.__seats[i].status == player.IN_PLAYING:
                return self.__seats[i]

    # 获得当局中没有被淘汰的玩家数量
    @property
    def playing_num(self):
        count = 0
        for i in xrange(0, TOTAL_SEAT):
            if self.__seats[i] and self.__seats[i].status == player.IN_PLAYING:
                count += 1
        return count

    # 记录最后一玩家所下注以及是否暗注
    def save_bet(self, chip, is_dark):
        self.__is_dark = is_dark
        self.__last_bet = chip

    # 保存玩家的结算结果,因为有的是弃牌,有的是比牌被K,而这些玩家可能中途就离开
    def save_round_result(self, seatid, is_win, chip, exp):
        self.__round_results[seatid] = [seatid, int(is_win), chip, exp]

    def clear_round_result(self):
        self.__round_results.clear()

    # 获取玩家的手牌
    def get_cards(self, seat_id):
        if not self.__seats[seat_id]:
            return []
        return self.__seats[seat_id].cards

    # 检查是否累加游戏轮数
    def check_round_count(self, seat_id):
        if seat_id == self.__button:
            DelayCall(0.1, self.incr_round_count)

    # 累加游戏轮数
    def incr_round_count(self):
        self.__round_count += 1

    # 获取下家的坐位ID
    def get_next_seatid(self, curr_seatid):

        for i in xrange(curr_seatid + 1, TOTAL_SEAT):
            self.check_round_count(i)
            if not self.__seats[i]:
                continue
            if self.__seats[i] and self.__seats[i].status == player.IN_PLAYING:
                return i

        for i in xrange(0, min(curr_seatid, TOTAL_SEAT)):
            self.check_round_count(i)
            if not self.__seats[i]:
                continue
            if self.__seats[i] and self.__seats[i].status == player.IN_PLAYING:
                return i

        return curr_seatid

    # 通知下一个玩家操作
    def turn_to_next(self, curr_seatid, is_begginer=False):
        if self.status != TABLE_PLAYING:
            return

        if self.__wait_seconds > 0:
            DelayCall(self.__wait_seconds, self.turn_to_next, curr_seatid)
            self.__wait_seconds = 0
            return

        if self.playing_num < 2:  # 玩家数小于2,结算
            self.check_out(self.get_winner())
            return

        self.turn_to_player(self.get_next_seatid(curr_seatid), is_begginer)

    # 获得当前循环用户还剩余的时间,单位为秒
    def left_seconds(self):
        return self.__timer.int_left_seconds

    # 取消定时器的定时操作
    def cancel(self):
        if self.__timer:
            self.__timer.cancel()

    # 获得当前的胜者
    def get_winner(self):
        if not self.__winner:
            return self.get_last_player()
        return self.__winner

    # 游戏结算 输赢加减钱
    def check_out(self, winner):
        if self.status != TABLE_PLAYING:
            self.play_log("checkout error: not in playing. %d" % (self.status, ))
            return
        if not winner:
            self.play_log("checkout error: no winner")
        self.play_log("checkout")

        self.cancel()
        self.__round_count = 0
        self.set_status(TABLE_CHECK_OUT)

        winchip = self.__total_bet
        if winner:
            self.save_round_result(winner.seatid, True, winchip, WIN_EXP)
            winner.on_round_over(
                self, True, winchip, WIN_EXP, player.IN_WAITING)
            self.__button = winner.seatid

        send_data = [CONFIG.game_id, CMD_CHECK_OUT,
                     self.__zid, self.__tid, CHECKOUT_SECONDS]
        for i, data in self.__round_results.items():
            send_data.append(data)

        self.clear_round_result()
        self.broad_cast(send_data)

        for seatid, duelers in self.__duel_dict.items():  # 通知底牌
            if not duelers:
                continue
            p = self.__seats[seatid]
            if not p or p.isQuit or (not p.online):
                continue
            send_data = [
                CONFIG.game_id, CMD_NOTIFY_CARDS, self.__zid, self.__tid]
            for i in duelers:
                ptmp = self.__seats[i]
                if not ptmp:
                    continue
                attr_data = [i]
                attr_data.extend(ptmp.cards)
                send_data.append(attr_data)
            p.send(send_data)

        DelayCall(CHECKOUT_SECONDS, self.check_out_over)

    # 结算结束,修改桌子状态,清理钱不够的玩家,准备开始新一局
    def check_out_over(self):
        if self.status != TABLE_CHECK_OUT:
            return
        self.set_status(TABLE_READY)
        self.quit_robot()  # 退出多余的机器人
        self.__winner = None

        for seat_id in xrange(0, TOTAL_SEAT):  # 清理筹码不够的玩家出房间
            p = self.__seats[seat_id]
            if not p:
                continue
            if p.isQuit:
                self.__seats[seat_id] = None
                continue
            p.setRoundSeconds(0)
            quit_type = 0
            if p.uchip < self.__limit_chip:  # 筹码不足退出
                quit_type = 1
            elif not p.online:  # 离线则退出
                quit_type = 2
            elif p.timeOutTimes >= 2:  # 超时两次则退出
                quit_type = 3
            if quit_type > 0 and seat_id == self.__button:
                self.__random_button = True
            if 0 < quit_type:
                self.manager.do_user_quit(p, self, quit_type)
                self.__seats[seat_id] = None
            else:
                p.setStatus(player.IN_WAITING)

        self.manager.update_table_player_num(self.__zid, self.__tid, self.play_num)
        self.update_game_wait_seconds()
        self.check_start()  # 检查是否再开始游戏

    # 退出房间内多余的机器人,一次只退一个
    def quit_robot(self):
        if self.play_num <= 3:
            return
        for seatid in xrange(0, TOTAL_SEAT):  # 清理多余的机器人出房间
            p = self.__seats[seatid]
            if not p:
                continue
            if not p.isRobot:
                continue

            self.manager.deal_robot_quit(self, p)
            return

    # 发送当前房间内的已进入的玩家至某玩家
    def send_players_in_table(self, to_player):
        for seatid in range(0, TOTAL_SEAT):
            if not self.__seats[seatid]:
                continue
            p = self.__seats[seatid]
            if p.isQuit:
                continue
            if p != to_player:
                data = self.manager.get_user_arrive_data(self.__zid, self.__tid, p)
                to_player.send(data)

    @property
    def game_wait_seconds(self):
        if self.status != TABLE_READY:
            return 0
        return utils.timestamp() - self.__game_wait_seconds

    # 更新游戏桌子等待开始时间
    def update_game_wait_seconds(self):
        self.__game_wait_seconds = utils.timestamp()

    # 玩家进入成功, 收到成功消息并收到其它玩家的数据,
    # 此处并不广播自己成功的消息,广播由manager来做
    def on_sit_down_success(self, p):
        if not p or not self.in_table(p.uid):
            return

        if self.play_num <= 1 and self.status != TABLE_PLAYING:
            self.update_game_wait_seconds()

        send_data = [CONFIG.game_id, CMD_SIT_DOWN,
                     self.__zid, self.__tid, p.uchip, p.seatid, p.status]
        p.send(send_data)
        self.__random_button = True

        self.send_players_in_table(p)

        self.user_re_connect(p)

    # 玩家断线重连
    def user_re_connect(self, p):
        if self.status != TABLE_PLAYING:
            return
        cards = p.cards
        send_data = [CONFIG.game_id, CMD_RE_CONNECT,
                     OK, self.__zid, self.__tid, self.__total_bet]
        actions = self.get_play_actions(self.__seats[self.__curr_seat_id])
        send_data.extend([self.__button, self.__curr_seat_id, actions, self.left_seconds(),
                          self.__base_chip, self.__raise_rate, self.__last_bet, self.__is_dark])
        if p.is_dark:
            send_data.append([])
        else:
            send_data.append(cards)
        for i in xrange(0, TOTAL_SEAT):
            ptmp = self.__seats[i]
            if not ptmp or ptmp.status < player.IN_PLAYING:
                continue
            send_data.append(
                [i, int(ptmp.isDark), ptmp.currBet, ptmp.status, p.total_bet])

        p.send(send_data)
        p.set_online(True)

    # 玩家退出房间
    def user_quit(self, p, reason=0):
        if not p or p.is_quit or not self.in_table(p.uid):
            return False

        self.play_log('user quit %d@%d when %d' %
                     (p.uid, p.seatid, self.status))
        if self.status == TABLE_PLAYING and p.status == player.IN_PLAYING:
            self.user_fold(p)
            if p.seatid == self.__curr_seat_id:
                self.turn_to_next(self.__curr_seat_id)

        self.broad_cast(
            [CONFIG.game_id, CMD_USER_QUIT, OK, p.uid, p.seatid, reason])

        p.set_quit(True)
        self.__seats[p.seatid] = None

        return True

    # 桌子内广播
    def broad_cast(self, data, not_to_uid=0):
        for x in range(0, TOTAL_SEAT):
            if not self.__seats[x]:
                continue
            p = self.__seats[x]
            if p.isQuit:
                continue
            if not p.online:  # 广播时不包括已离线的玩家
                continue
            if p.tid != self.__tid:  # 不包括已进别的房间的玩家
                continue
            if p.uid != not_to_uid:
                p.send(data)

    # 打牌日志
    def play_log(self, log_data):
        self.__flow += log_data + "\n"
        utils.log(log_data, 'table_' + str(self.__tid) + '.log')

    # 返回当前机器人是否大过所有真人
    def is_winner(self, robot):
        flag = True
        if not robot:
            pass
        for i in xrange(0, TOTAL_SEAT):
            p = self.__seats[i]
            if not p or p.status != player.IN_PLAYING or p.isRobot:
                continue

            # [c1, c2, c3] = robot.cards
            # [d1, d2, d3] = p.cards

        return flag
Example #30
0
        print("Invalid number.")
    if players == 0:
        print("No.")
        players == None

while choice != 0:
    print("Select a Game: ")
    print(" 1 - Blackjack")
    print(" 2 - Poker")
    print(" 3 - Yahtzee")
    print(" 0 - Exit")
    try:
        choice = int(input(" > "))
    except ValueError:
        print("That is not a valid input. Please try again.")
        continue

    if choice == 0:
        print("Goodbye.")
    elif choice == 1:
        Blackjack(players)
    elif choice == 2:
        if players < 3:
            print("Two few players.")
            continue
        Poker(players)
    elif choice == 3:
        Yahtzee(players)
    else:
        print("That is not a valid input. Please try again.")
Example #31
0
 def __init__(self, pok=None, dz=False, count=0):
     self.pok = pok if pok else Poker()
     self.dz = dz
     self.count = count
Example #32
0
 def test_royal_flush_no_order(self):
     result = [2, 6, 5, 4, 3]
     self.assertEqual(7, Poker.CheckScore(result))
Example #33
0
 def test_full_house1_6(self):
     result = [6, 1, 6, 1, 6]
     self.assertEqual(5, Poker.CheckScore(result))
Example #34
0
from player import Player
from poker import Poker

if __name__ == "__main__":
    p1 = Player('P1', 1000)
    p2 = Player('P2', 1000)

    poker = Poker()
    poker.register_player(p1)
    poker.register_player(p2)

    poker.start_game()
    poker.deliver()

    poker.reveal_card()
    poker.reveal_card()
    poker.reveal_card()
    poker.reveal_card()
    poker.reveal_card()

    win, score = poker.winner()
    if win.name == 'P1':
        print('{} -> {}'.format(
            [str(c) for c in (win.cards + poker.table_cards)], score))
Example #35
0
class Game:

	def __init__(self,playerArr):
		# STARTING GAME
		self.pokerRules = Poker()

		# CREATING PLAYERS
		playerFactory = pokerPlayerFactory()
		self.players = []
		for player in playerArr:
			playerName = player[0]
			playerType = player[1]
			newPlayer = playerFactory.newPokerPlayer(playerName,playerType)
			self.players.append(newPlayer)
		random.shuffle(self.players,random.random)


		# PLAYER ORDER
		playerOrder = []
		for player in self.players:
			playerOrder.append(player.name)

	def startGame(self):

		# ACTUAL GAMEPLAY
		self.roundNum = 0
		while self.playersLeftForGame():
			startingPlayerIndex = self.roundNum % len(self.players)
			self.playSingleRound(startingPlayerIndex)
			self.roundNum += 1

		# FINDING THE WINNER
		for player in self.players:
			if player.cardsLeft > 0:
				return player.name

	def playersLeftForGame(self):
		playersWithCards = 0
		for player in self.players:
			if player.cardsLeft > 0:
				playersWithCards += 1
		return playersWithCards > 1

	def playSingleRound(self,startingPlayerIndex):

		# ROUND INIT
		self.dealCards()
		for player in self.players:
			player.calibrateStrategy(self)
		self.currentAnnouncedHand=[]
		self.announcingPlayerIndex = startingPlayerIndex
		stillAnnouncing = True

		# ROUND ACTUAL PLAY
		while stillAnnouncing:

			#Get the next player that is still in the game to announce
			while self.players[self.announcingPlayerIndex].cardsLeft == 0:
					self.announcingPlayerIndex += 1
					self.announcingPlayerIndex %= len(self.players)


			#ANNOUNCEMENT
			self.currentAnnouncedHand = self.players[self.announcingPlayerIndex].announce(self)
			self.firstChallenger = True

			for increment in xrange(1,len(self.players)):
				challengingPlayerIndex = (self.announcingPlayerIndex + increment) % len(self.players)

				if self.players[challengingPlayerIndex].cardsLeft == 0:
					#This player is not in the game anymore
					continue

				if self.currentAnnouncedHand == [(14,4)]:
					# Highest available hand
					stillAnnouncing = False
					break

				if self.players[challengingPlayerIndex].challenge(self):
					#Challenge occured
					stillAnnouncing = False
					break

				self.firstChallenger = False

			#Get the index for the next player
			if stillAnnouncing:
				self.announcingPlayerIndex = (self.announcingPlayerIndex + 1) % len(self.players)


		# STANDOFF
		goodChallenge = self.pokerRules.standOff(self.cardsOnTable,self.currentAnnouncedHand)


		# PLAYERS LEARN AND RECALIBERATE
		for player in self.players:
			player.learn(self,goodChallenge)
			player.resetSettings()

		# UPDATE PLAYERS CARD QUOTA AFTER STANDOFF
		if goodChallenge:
			self.players[self.announcingPlayerIndex].cardsLeft -= 1
		else:
			self.players[challengingPlayerIndex].cardsLeft -= 1

	def dealCards(self):
		theDeck = Deck()

		# DEALING CARDS
		counter = 0
		for player in self.players:
			player.cardsInHand = []
			player.playersHand = []
			for i in xrange(player.cardsLeft):
				player.recieveCard(theDeck.dealCard())
				counter += 1

		# INITING TABLE VARIABLES
		cardsOnTable = []
		self.numCardsOnTable = 0
		for player in self.players:
			for cardFromPlayer in player.playersHand:
				self.numCardsOnTable += cardFromPlayer[1]
				existOnTable = False
				for cardOnTable in cardsOnTable:
					if cardFromPlayer[0] == cardOnTable[0]:
						cardOnTable[1] += cardFromPlayer[1]
						existOnTable = True

				if not existOnTable:
					cardsOnTable.append(cardFromPlayer)

		self.cardsOnTable = cardsOnTable

	def getNumCardsOnTable(self):
		return self.numCardsOnTable
Example #36
0
 def test_check_always(self):
     result1 = [6, 2, 3, 4, 5]
     result2 = [6, 2, 3, 4, 5]
     self.assertEqual(0, Poker.winner(result1, result2))
Example #37
0
 def __init__(self, up=None, my=None, down=None, last=None):
     self.up = up if up else Player()
     self.my = my if my else Player()
     self.down = down if down else Player()
     self.last = last if last else Poker()