示例#1
0
 def __init__(self, index = -1, alive = True, loc = (1,1,1)):
     self.id = index # represent the color of the player
     self.alive = alive
     self.loc = Player_location(loc)  # (row, column, endpoint), (0, 0) is top left, endpoint (0..7)
     self.hand = Hand()
     self.player = None
     self.cheated = False
示例#2
0
def recenter(IP, PORT, CK, Left_H, Right_H, x, y, LH, LS, LV, UH, US, UV, tts,
             proxy):
    if CK == 1:
        Hand.choose(IP, PORT, Left_H, Right_H, proxy)
        pick_flag = True
        again_flag = False
    else:
        #nx,ny=getcenter(IP,PORT,LH,LS,LV,UH,US,UV)
        nx, ny = getcenter(IP,
                           PORT,
                           LH,
                           LS,
                           LV,
                           UH,
                           US,
                           UV,
                           tts,
                           showingimage=True)
        if nx <= x + 25 and nx >= x - 25 and ny <= y + 25 and ny >= y - 25:
            Hand.choose(IP, PORT, Left_H, Right_H, proxy)
            pick_flag = True
            again_flag = False
            print("step")
        else:
            pick_flag = False
            again_flag = True
            print("step2")

    return pick_flag, again_flag
示例#3
0
def gameRound():
	deck = Deck.Deck()
	deck.shuffle()

	hands =[]
	# adding 5 player or hands of player in hand
	for i in range(5):
		hands.append([])

	# distributing cards to player
	for i in range(3):
		for hand in hands:
			hand.append(deck.drawCard())

	for i,hand in enumerate(hands):
		print "Player{}'s hand is:".format(i+1)
		for card in hand:
			card.show()
		print

	for i,hand in enumerate(hands):
		print 'Player{} has a {}'.format(i+1, Hand.getRank(hand)[1])
	print

	winningHand = Hand.compare(hands)
	iWinningPlayer = hands.index(winningHand)
	print "Player{} wins!!!".format(iWinningPlayer+1)
示例#4
0
 def updateState(self):
     while (not self.ctrlLeapmotion.frame().is_valid):
         pass
     if (self.actFrame.id == self.ctrlLeapmotion.frame().id):
         return
     self.actFrame = self.ctrlLeapmotion.frame()
     print("\nFrame ID: " + str(self.actFrame.id) + "\n")
     handlist = self.actFrame.hands
     handDetector = 0
     for hand in handlist:
         id = hand.is_right
         handDetector += id + 1
         for finger in hand.fingers:
             previousState = self.hands[id].getFingerState(finger.type)
             eventDetected = self.detectEvent(finger)
             fingerState = self.getNewState(previousState, eventDetected)
             self.hands[id].setFingerState(finger.type, fingerState)
             self.hands[id].height = self.getHandHeight(hand)
         self.hands[id].printHandStatus()
     if handDetector == 0:
         self.hands[0] = Hand.Hand(0, 0.0)
         self.hands[1] = Hand.Hand(1, 0.0)
     elif handDetector == 1:
         self.hands[1] = Hand.Hand(1, 0.0)
     elif handDetector == 2:
         self.hands[0] = Hand.Hand(0, 0.0)
示例#5
0
文件: RulesTest.py 项目: eruns/GUI-1
 def test_function_book_check_fullbook(self):
     rules = Rules()
     hand = Hand()
     for s in Suit:
         hand.add_card(Card(rank=Rank.THREE, suit=s))
     self.assertEqual(rules.book_check(Rank.THREE, hand), 4,
                      "book check not finding book")
示例#6
0
def start():
    while True:
        blackjack_functions.clear()
        print 'Your balance is {}$'.format(balance.total)
        while True:
            try:
                bet = int(input('The game begins!\nPlease take a bet '))
                if bet > balance.total or bet < 0:
                    raise ValueError
            except:
                print 'Bad betting, try again: '
                continue
            else:
                break

        blackjack_functions.clear()
        player = Hand.Hand()
        dealer = Hand.Hand()
        deck = Deck.Deck()
        deck.shuffle()
        dealer.add_card(deck.deal())
        dealer.add_card(deck.deal())
        player.add_card(deck.deal())
        player.add_card(deck.deal())
        blackjack_functions.show_some(player, dealer)
        game = game_on(player, dealer, deck, bet)
        if game == False:
            return True
        if game == 'repeat?':
            return 'repeat'
def dealSomeHands():
    # Generate the initial deck and shuffle it.
    d = Deck()
    d.shuffle()

    # Find out from the user how many hands to generate.
    while True:
        # Run this while loop until we get a legal (positive
        # integer) answer from the user.
        nStr = input("How many hands should I deal? ")
        if not nStr.isdigit():
            print (" Positive number required. Try again!")
        else:
            n = int( nStr ); break
            
        # Generate n hands.
    for i in range( n ):
        # If there are not enough cards left in the deck
        # to deal a hand, generate and shuffle a new deck.
        if ( len(d) < 5 ):
            print("\nDealing a new deck.")
            d = Deck()
            d.shuffle()
            
        # Generate a new hand, print it, and evaluate it.
        h = Hand(d)
        print("\n\tHand drawn (", i + 1, "): ", sep="")
        print(h)
        print( "\t   -", h.evaluateHand())
示例#8
0
    def __init__(self, expert):

        self.expert_mode = expert  #Booléen indiquant si la partie se déroule en mode expert ou non
        self.frontiers_visual, self.frontiers_p0_rect, self.frontiers_p1_rect, self.frontiers_p2_rect = self.initializeFrontiers(
        )  #Visuels des frontières
        self.cards_visual = self.initializeCards()  #Visuels des cartes
        self.frontiers = []  #Liste des objets "Frontier"
        for i in range(0, 9):  #On initialise les objets "Frontier"
            self.frontiers.append(Frontier(i))
        self.ClanCardDraw = Card_Draw(
            "Clan")  #On initialise la pioche de cartes de clan
        if expert:  #Si la partie se déroule en mode expert
            self.TacticCardDraw = Card_Draw(
                "Tactic")  #On initialise la pioche de cartes tactiques
            self.nTacticCardPlayed = [
                0, 0
            ]  #Nombre de cartes tactiques jouées par les deux joueurs
            self.DiscardPile = []  #Liste de cartes défaussées
        self.hands = [Hand(expert), Hand(expert)
                      ]  #On initialise les objets "Hand" des deux joueurs
        self.hands[0].fillHand(
            self.ClanCardDraw)  #On remplit la main du premier joueur
        self.hands[1].fillHand(
            self.ClanCardDraw)  #On remplit la main du second joueur
        self.player1_cards_rect, self.player2_cards_rect = self.initializeHandCardsRect(
        )  #Positions des cartes des mains des joueurs
        self.frontiers_sides_cards_rect = self.initializeSideCardsRect(
        )  #Positions des cartes jouées
        self.winner = 0
示例#9
0
 def initState(self):
     while (not self.ctrlLeapmotion.is_connected):
         pass
     while (not self.ctrlLeapmotion.frame().is_valid):
         pass
     self.actFrame = self.ctrlLeapmotion.frame()
     self.hands[0] = Hand.Hand(0, 0.0)
     self.hands[1] = Hand.Hand(1, 0.0)
示例#10
0
    def test_is2Pair(self):
        hstr = '8C TS KC 9H 4S'.split(' ')
        hand = hd.Hand(hstr)
        hv = hand.hand_type()
        self.assertNotEqual(hv, hd.Hand.HAND_TYPE_VALS['2_PAIR'])

        hstr = '7C 7S 8C 8H 6D'.split(' ')
        hand = hd.Hand(hstr)
        hv = hand.hand_type()
        self.assertEqual(hv, hd.Hand.HAND_TYPE_VALS['2_PAIR'])
示例#11
0
    def test_is3Kind(self):
        hstr = '8C TS KC 9H 4S'.split(' ')
        hand = hd.Hand(hstr)
        hv = hand.hand_type()
        self.assertNotEqual(hv, hd.Hand.HAND_TYPE_VALS['3_KIND'])

        hstr = '7C 7S 7H 8H 2D'.split(' ')
        hand = hd.Hand(hstr)
        hv = hand.hand_type()
        self.assertEqual(hv, hd.Hand.HAND_TYPE_VALS['3_KIND'])
示例#12
0
    def test_isStraightFlush(self):
        hstr = '8C TS KC 9H 4S'.split(' ')
        hand = hd.Hand(hstr)
        hv = hand.hand_type()
        self.assertNotEqual(hv, hd.Hand.HAND_TYPE_VALS['STRAIGHT_FLUSH'])

        hstr = '7C 6C 5C 8C 4C'.split(' ')
        hand = hd.Hand(hstr)
        hv = hand.hand_type()
        self.assertEqual(hv, hd.Hand.HAND_TYPE_VALS['STRAIGHT_FLUSH'])
示例#13
0
    def test_is1Pair(self):
        hstr = '8C TS KC 9H 4S'.split(' ')
        hand = hd.Hand(hstr)
        hv = hand.hand_type()
        self.assertNotEqual(hv, hd.Hand.HAND_TYPE_VALS['1_PAIR'])

        hstr = '5C 4S 7H 3H 7D'.split(' ')
        hand = hd.Hand(hstr)
        hv = hand.hand_type()
        self.assertEqual(hv, hd.Hand.HAND_TYPE_VALS['1_PAIR'])
示例#14
0
def wentFirst(truth):
    global turnOffset
    if truth:
        logging.info("You are going first")
        Hand.hand = [Hand.card('Mulliganned') for _ in range(4)] + [Hand.card('The Coin')]
        turnOffset = 1
    else:
        logging.info("You are going second")
        Hand.hand = [Hand.card('Mulliganned') for _ in range(3)]
        turnOffset = 0
示例#15
0
文件: GUI-Game.py 项目: eruns/GUI-1
    def __init__(self, hand_size=0, hand_count=0, max_hand_size=0, ace_rank=None, discard_type=None, sort=None):
        """Initializes the game object"""
        self._init_hand_size = 0
        self._hand_count = 0
        self._max_hand_size = 52
        self._acerank = Rank.ACELOW
        self._discard_type = Visibility.INVISIBLE
        self._hands = []
        self._deck = []
        self._empty_hands = 0
        self._active = None
        self._sort = Sort.SUITTHENRANKD
        self._log_file = Error.log_error("Game initalized", "Game.__init__")

        """Instantiating properties"""
        if hand_size != 0 and type(hand_size) == int:
            self._init_hand_size = hand_size

        if hand_count != 0 and type(hand_count) == int:
            self._hand_count = hand_count

        if max_hand_size != 0 and type(max_hand_size) == int:
            self._max_hand_size = max_hand_size

        if ace_rank != None and type(ace_rank) == Rank:
            self._acerank = ace_rank

        if discard_type != None and type(discard_type) == Visibility:
            self._discard_type = discard_type

        if sort != None and type(sort) == Sort:
            self._sort = sort

        """Building the deck"""
        deck = Deck(ace_rank=self.ace_rank)
        self._deck = deck
        deck.shuffle()
        temp_hands = {}

        """Dealing the hands"""
        if self._hand_count != 0 and self._hands == []:
            for i in range(self.hand_count):
                hand = Hand(visibility=self.discard_type, sort=self.sort_method)
                for j in range(self.init_hand_size):
                    card = deck.deal()
                    hand.add_card(card)
                name = "hands%s" % i
                score = 0
                temp_hands[name] = [hand, score]
            self._hands = temp_hands

        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Hello, world")
        label.pack()
        label.bind("<1>", self.quit)
示例#16
0
 def test_function_add_card_array_addTest(self):
     hand = Hand()
     card1 = Card(suit=Suit.SPADES, rank=Rank.TEN)
     card2 = Card(suit=Suit.DIAMONDS, rank=Rank.FIVE)
     card3 = Card(suit=Suit.SPADES, rank=Rank.THREE)
     card4 = Card(suit=Suit.DIAMONDS, rank=Rank.KING)
     card5 = Card(suit=Suit.CLUBS, rank=Rank.ACEHIGH)
     new_cards = [card1, card2, card3, card4, card5]
     hand.add_card(new_cards)
     self.assertEqual(hand.card_count, 5,
                      "Add card not properly adding array")
示例#17
0
 def __init__(self, order):
     """
     Generates a player object
     """
     self.starting_pos = order
     self.name = 'Player' + str(order + 1)
     self.position = order
     self.stack = self.STARTING_STACK
     self.hand = Hand()
     self.current_bet = 0
     self.is_folded = False
     self.is_busted = False
示例#18
0
    def processHand(self, handText):
        if self.isPartial(handText):
            raise FpdbHandPartial(
                _("Could not identify as a %s hand") % self.sitename)
        if self.copyGameHeader:
            gametype = self.parseHeader(
                handText,
                self.whole_file.replace('\r\n', '\n').replace(u'\xa0', u' '))
        else:
            gametype = self.determineGameType(handText)
        hand = None
        l = None
        if gametype is None:
            gametype = "unmatched"
            # TODO: not ideal, just trying to not error. Throw ParseException?
            self.numErrors += 1
        else:
            if gametype['category'] in self.import_parameters['importFilters']:
                raise FpdbHandSkipped("Skipped %s hand" % gametype['type'])
            # See if gametype is supported.
            if 'mix' not in gametype: gametype['mix'] = 'none'
            if 'ante' not in gametype: gametype['ante'] = 0
            if 'buyinType' not in gametype: gametype['buyinType'] = 'regular'
            if 'fast' not in gametype: gametype['fast'] = False
            if 'newToGame' not in gametype: gametype['newToGame'] = False
            if 'homeGame' not in gametype: gametype['homeGame'] = False
            if 'split' not in gametype: gametype['split'] = False
            type = gametype['type']
            base = gametype['base']
            limit = gametype['limitType']
            l = [type] + [base] + [limit]

        if l in self.readSupportedGames():
            if gametype['base'] == 'hold':
                hand = Hand.HoldemOmahaHand(self.config, self, self.sitename,
                                            gametype, handText)
            elif gametype['base'] == 'stud':
                hand = Hand.StudHand(self.config, self, self.sitename,
                                     gametype, handText)
            elif gametype['base'] == 'draw':
                hand = Hand.DrawHand(self.config, self, self.sitename,
                                     gametype, handText)
        else:
            log.error(
                _("%s Unsupported game type: %s") % (self.sitename, gametype))
            raise FpdbParseError

        if hand:
            #hand.writeHand(self.out_fh)
            return hand
        else:
            log.error(
                _("%s Unsupported game type: %s") % (self.sitename, gametype))
示例#19
0
 def __init__(self):
     super().__init__()
     self.__hand = Hand()
     self.__players = []
     self.__chipsPile = 0
     self.__dealerHole = 0
     self.__newDeck = d.Deck()
     self.__roundCount = 0
     self.__maxBet = 0
     self.__winnerCount = 0
     self.__winningPlayers = []
     self.__foldedPlayers = []
示例#20
0
 def resource_distributions(self, dice_sum: int) -> Dict[Player.Player, Hand.Hand]:
     dist = {}
     for hex_tile in self.hexes():
         if hex_tile.token() == dice_sum and not hex_tile.has_robber():  # hex that distributes
             adj_nodes = hexgrid.nodes_touching_tile(hex_tile.id() + 1)  # he uses 1 indexing
             for node in adj_nodes:
                 if self.nodes().get(node):  # node has buildable on it
                     player = self.nodes().get(node).player()  # belongs to player_id
                     if player not in dist:
                         dist[player] = Hand.Hand()
                     dist[player].insert(Hand.Hand(hex_tile.resource()))  # add hex's resource to distributed hand
     return dist
示例#21
0
    def frame(self):
        global backCount, handState
        dt = self.getDt()

        super(mySim,self).frame()
        self.teapot.zeroBean(Hand)
        #self.teapot.hand = handState
        self.teapot.draw(theta)
        if self.teapot.hand :
            self.teapot.rotateT(theta, self.teapot.axis)
            
        newCurTime = time.time()

        maxCollision = 4

        for p in self.steam :
            p.simulate(dt)
            if p.loc[1] >= 6 :
                ll = self.teapot.lid
                vv = np.array([myRand(-2, 2), myRand(2,11), myRand(-2, 2)])
                p.loc = ll
                p.vel = vv
        for p in self.particle :
            p.simulate(dt)
            if self.teapot.hand == False:
                p.loc = self.teapot.lid
            if p.loc[1] < 0.04 :
                ll = self.teapot.lid
                vv = np.array([myRand(-2, 2), myRand(2,11), myRand(-2, 2)])
                p.loc = ll
                p.vel = vv

        for p in self.particle :
            p.cdraw([0.0,0.0,1.0,1.0])
        for p in self.steam :
            p.cdraw([1.0, 1.0, 1.0, 1.0])


        global upCnt,downCnt,leftCnt,rightCnt
        glPushMatrix()
        for i in range(upCnt):
            glTranslatef(0,1,0)
        for i in range(downCnt):
            glTranslatef(0,-1,0)
        for i in range(leftCnt):
            glTranslatef(0,0,-1)
        for i in range(rightCnt):
            glTranslatef(0,0,1)
        Hand.doAnimation(ani.KeyInputState)
        glPopMatrix()
        print(Hand.rootJoint.getCurAnimatedLocationCOG() , ' is COG of RottJoint')
        print(self.KeyInputState)
        super(mySim,self).afterFrame()
示例#22
0
 def test_function_add_card_array_sortTest(self):
     hand = Hand(sort=Sort.RANKTHENSUITA)
     card1 = Card(suit=Suit.SPADES, rank=Rank.TEN)
     card2 = Card(suit=Suit.DIAMONDS, rank=Rank.FIVE)
     card3 = Card(suit=Suit.SPADES, rank=Rank.THREE)
     card4 = Card(suit=Suit.DIAMONDS, rank=Rank.KING)
     card5 = Card(suit=Suit.CLUBS, rank=Rank.ACELOW)
     new_cards = [card1, card2, card3, card4, card5]
     hand.add_card(new_cards)
     self.assertEqual(hand.cards[0].rank.value, 1,
                      "Sort card not properly sorting hand")
     self.assertEqual(hand.cards[4].rank.value, 13,
                      "Sort card not properly sorting hand")
示例#23
0
 def testHighCard(self):
 	hand1 = Hand.Hand([Card.Card(Card.Rank.JACK, Card.Suit.SPADES), \
         Card.Card(Card.Rank.KING, Card.Suit.SPADES), \
         Card.Card(Card.Rank.FIVE, Card.Suit.SPADES), \
         Card.Card(Card.Rank.QUEEN, Card.Suit.HEARTS), \
         Card.Card(Card.Rank.FOUR, Card.Suit.SPADES)])
 	hand2 = Hand.Hand([Card.Card(Card.Rank.JACK, Card.Suit.SPADES), \
         Card.Card(Card.Rank.ACE, Card.Suit.SPADES), \
         Card.Card(Card.Rank.FIVE, Card.Suit.SPADES), \
         Card.Card(Card.Rank.QUEEN, Card.Suit.SPADES), \
         Card.Card(Card.Rank.FOUR, Card.Suit.DIAMONDS)])
 	self.assertTrue(hand1.value == Hand.Value.HIGH_CARD)
 	self.assertTrue(hand1.compareTo(hand2) < 0)
    def processHand(self, handText, showKnown, fastFold,
                    separateTablesByMaxSeats):
        if not self.isPartial(handText):
            gametype = self.determineGameType(handText)
            hand = None
            l = None
            if gametype is None:
                gametype = "unmatched"
            else:
                if 'mix' not in gametype: gametype['mix'] = 'none'
                if 'ante' not in gametype: gametype['ante'] = 0
                if 'buyinType' not in gametype:
                    gametype['buyinType'] = 'regular'
                if 'fast' not in gametype: gametype['fast'] = False
                if 'newToGame' not in gametype: gametype['newToGame'] = False
                if 'homeGame' not in gametype: gametype['homeGame'] = False
                type = gametype['type']
                base = gametype['base']
                limit = gametype['limitType']
                l = [type] + [base] + [limit]

            if l in self.readSupportedGames():
                if gametype['base'] == 'hold':
                    if gametype['fast'] == True:
                        hand = Hand.HoldemOmahaHand(None, self, self.sitename,
                                                    gametype, handText,
                                                    showKnown, fastFold,
                                                    separateTablesByMaxSeats)
                    else:
                        hand = Hand.HoldemOmahaHand(None, self, self.sitename,
                                                    gametype, handText,
                                                    showKnown, False,
                                                    separateTablesByMaxSeats)

                elif gametype['base'] == 'stud':
                    hand = Hand.StudHand(None, self, self.sitename, gametype,
                                         handText)
                elif gametype['base'] == 'draw':
                    hand = Hand.DrawHand(None, self, self.sitename, gametype,
                                         handText)
            else:
                print(("%s Unsupported game type: %s") %
                      (self.sitename, gametype))
                #raise FpdbParseError
                return

            if hand:
                return hand
            else:
                print(("%s Unsupported game type: %s") %
                      (self.sitename, gametype))
示例#25
0
 def __init__(self, agent: Agent.Agent, name: str = None):
     self.__agent = agent
     self.__id = self.__gen_id()
     self.__name = self.__gen_name(name)
     self.__resources_hand = Hand.Hand()
     self.__devs_hand = Hand.Hand()
     self.__used_devs = Hand.Hand()
     self.__settlement_nodes = []
     self.__city_nodes = []
     self.__road_edges = []
     self.__has_longest_road = False
     self.__has_largest_army = False
     self.__longest_road_len = 0
     self.__harbors = set()
示例#26
0
class Player:
    def __init__(self, is_dealer):
        self.hand = Hand()
        self.hands = [self.hand]
        #is_dealer is a bool
        self.money = (1 - is_dealer) * 100
        self.name = ""

    def deal_hand(self, deck):
        self.hand.add_card(deck)
        self.hand.add_card(deck)

    def reset(self):
        self.hand = Hand()
        self.hands = [self.hand]
示例#27
0
    def hand_evaluate_preflop(self, card_holding, name):
        he = Hand.HandEvaluation(card_holding, name,
                                 event='Preflop')  #Unique to player instance
        evaluation, rc, score_desc, event = he.get_evaluation()

        self.take_action_flop(he, evaluation, rc, score_desc)
        return he, evaluation, rc, score_desc, event
示例#28
0
    def test_enumerate_tiles(self):
        hand_1 = Hand()
        tile_1 = init_tile_1()
        tile_2 = init_tile_3()
        hand_1.add_tile(tile_1)
        hand_1.add_tile(tile_2)

        res = hand_1.enumerate_tiles(tile_1)
        self.assertEqual(len(res),7)
        for i in range(7):
            if i < 3:
                self.assertEqual(res[i].get_rotation(), i+1)
                self.assertEqual(res[i].paths, tile_1.paths)
            else:
                self.assertEqual(res[i].get_rotation(), i-3)
                self.assertEqual(res[i].paths, tile_2.paths)
示例#29
0
文件: RulesTest.py 项目: eruns/GUI-1
 def test_function_player_answer_yes(self):
     rules = Rules()
     hand = Hand()
     card = Card(rank=Rank.ACEHIGH, suit=Suit.DIAMONDS)
     hand += card
     self.assertEqual(rules.player_answer(Rank.ACEHIGH, hand), "YES",
                      "player answer Not returning YES when it should")
示例#30
0
	def __init__(self, dataSet):
		self.dataSet = dataSet
		
		self.cardType = CardType.createType(self.generateList('type'), self.model)
		self.cardTypes = CardTypes.createTypes(self.generateList('types'), self.model)
		self.cmc = Cmc.createCmc(self.generateList('cmc'), self.model)
		self.colorIdentity = ColorIdentity.createColorIdentity(self.generateList('colorIdentity'), self.model)
		self.colors = Colors.createColors(self.generateList('colors'), self.model)
		self.hand = Hand.createHand(self.generateList('hand'), self.model)
		self.imageName = ImageName.createImageName(self.generateList('imageName'), self.model)
		self.layouts = Layouts.createLayouts(self.generateList('layout'), self.model)
		self.legalities = Legalities.createLegalities(self.generateList('legalities'), self.model)
		self.life = Life.createLife(self.generateList('life'), self.model)
		self.loyalty = Loyalty.createLoyalty(self.generateList('loyalty'), self.model)
		self.manaCost = ManaCost.createManaCost(self.generateList('manaCost'), self.model)
		self.name = Name.createName(self.generateList('name'), self.model)
		self.names = Names.createNames(self.generateList('names'), self.model)
		self.power = Power.createPower(self.generateList('power'), self.model)
		self.printings = Printings.createPrintings(self.generateList('printings'), self.model)
		self.rulings = Rulings.createRulings(self.generateList('rulings'), self.model)
		self.source = Source.createSource(self.generateList('source'), self.model)
		self.starter = Starter.createStarter(self.generateList('starter'), self.model)
		self.cardSubTypes = CardSubTypes.createSubTypes(self.generateList('subtypes'), self.model)
		self.cardSuperTypes = CardSuperTypes.createSuperTypes(self.generateList('supertypes'), self.model)
		self.text = Text.createText(self.generateList('text'), self.model)
		self.toughness = Toughness.createToughness(self.generateList('toughness'), self.model)
示例#31
0
 def __init__(self, name = "Player"):
     """Initializes Player instance object with data attributes."""
     self.name = name
     self.is_playing = False
     self.score = 0
     self._books = []
     self._player_hand = Hand_library.Hand()
示例#32
0
class scoreTest(unittest.TestCase):
    x = Card('Eight', 'H', 8)
    y = Card('Eight', 'S', 8)
    z = Card('Seven', 'S', 7)
    a = Card('Nine', 'C', 9)
    b = Card('Ten', 'H', 10)

    hand = Hand()
    hand.addCard(x)
    hand.addCard(y)
    hand.addCard(z)
    hand.addCard(a)
    hand.addCard(b)
    subsets = genSubsets(hand)

    def testGenSubsets(self):
        subsets = genSubsets(scoreTest.hand)
        self.assertEqual(len(subsets), 32)

    def testFifteens(self):
        self.assertEqual(fifteens(scoreTest.subsets), 4)

    def testPair(self):
        couples = [set for set in scoreTest.subsets if len(set) == 2]
        self.assertEqual(pairs(couples), 2)

    def testRun(self):
        runSets = [set for set in scoreTest.subsets if len(set) >= 3]
        self.assertEqual(runs(runSets), 8)

    def testScore(self):
        self.assertEqual(score(scoreTest.hand), 14)
示例#33
0
    def importhand(self, handid=1):
        # Fetch hand info
        # We need at least sitename, gametype, handid
        # for the Hand.__init__

        h = Hand.hand_factory(handid, self.config, self.db)

        # Set the hero for this hand using the filter for the sitename of this hand
        h.hero = self.filters.getHeroes()[h.sitename]
        return h
示例#34
0
def build_body():
    pymelLogger.debug('Starting: build_body()...') 
    
    
    Torso.build()
    
    # legs
    CanidaeLeg.build(side = Names.prefixes['left'])
    CanidaeLeg.build(side = Names.prefixes['right'])
    # arms
    Arm.build(side = Names.prefixes['left'])
    Arm.build(side = Names.prefixes['right'])
    
   

    # Hands and fingers
    Hand.build( side = Names.prefixes['left'] )
    Hand.build( side = Names.prefixes['right'] )
    
    
    # main ctrl
    main_cnt_name =  Names.joints_torso[0] + '_' + Names.suffixes['control']
    main_cnt = Control.create( name=main_cnt_name, offsets=0, shape='circle_4_arrow', 
                size=1, color='yellow', 
                pos=None, parent=None, typ='body' )
    pm.parent(main_cnt, 'controls')
    ######################
    ######################
    # hard coded! fix!
    consGrp = [Names.torso_module, Names.legs_module]
    for grp in consGrp:
        try: pm.parentConstraint( main_cnt, grp, mo=1 )
        except: print 'Could not constraint: ' + main_cnt + ' to ' + grp
    # constraint main to reference_jnt
    pm.parentConstraint(main_cnt, Names.joints_torso[0], mo=1)
    ######################
    ######################
   
    
    
  
    pymelLogger.debug('End: build_body()...')
示例#35
0
def trigger(entity):
    if entity['player'] == Utilities.them:
        if entity['name'] == "Alarm-o-Bot":
            Hand.draw(entity, note="Alarm-o-Bot")
        elif entity['name'] == "Archmage Antonidas":
            Hand.draw(entity, note='Fireball')
        elif entity['name'] == "Emperor Thaurissan":
            for card in Hand.hand:
                card.cost -= 1
        elif entity['name'] == "Kabal Trafficker":
            Hand.draw(entity, source='random', kind='demon minion')
        elif entity['name'] == "Ysera":
            Hand.draw(entity, kind='dream')
示例#36
0
    def resetGame(self):
        self.matchID = None
        # dummy entries, overridden on first newGame packet
        self.leftOpp = Participant()
        self.rightOpp = Participant()
        self.numHands = None
        self.stackSize = None
        self.bigB = None
        self.smallB = None
        self.timebank = None

        self.numArrivalsAtStreet = [0,0,0,0]
        self.hand = Hand()
示例#37
0
文件: Hud.py 项目: Fulvio75/fpdb
    def create(self, hand, config, stat_dict):
        # update this hud, to the stats and players as of "hand"
        # hand is the hand id of the most recent hand played at this table

        self.stat_dict = stat_dict # stat_dict from HUD_main.read_stdin is mapped here
        # the db_connection created in HUD_Main is NOT available to the
        #  hud.py and aux handlers, so create a fresh connection in this class
        # if the db connection is made in __init__, then the sqlite db threading will fail
        #  so the db connection is made here instead.
        self.db_hud_connection = Database.Database(self.config)
        # Load a hand instance (factory will load correct type for this hand)
        self.hand_instance = Hand.hand_factory(hand, config, self.db_hud_connection)
        self.db_hud_connection.connection.rollback()
        log.info(_('Creating hud from hand ')+str(hand))
示例#38
0
文件: Hud.py 项目: Tuxik/fpdb
    def create(self, hand, config, stat_dict):
#    update this hud, to the stats and players as of "hand"
#    hand is the hand id of the most recent hand played at this table

        self.creation_attrs = hand, config, stat_dict

        #create new database connection for this table - must create a fresh one
        # here because the one used in HUD_Main is not available in this thread
        self.db_hud_connection = Database.Database(self.config)
        # Load a hand instance (factory will load correct type for this hand)
        self.hand_instance = Hand.hand_factory(hand, config, self.db_hud_connection)

        self.hand = hand            #fixme - not sure what this is doing here?
        self.stat_dict = stat_dict  #fixme - not sure what this is doing here?
        self.db_hud_connection.connection.rollback()
        log.info(_('Creating hud from hand ')+str(hand))
示例#39
0
def deal():
    """Generates a new round. Deals a hand to the dealer and player.
    Checks if either hand is a BlackJack"""
    global outcome, in_play, dealer, player, deck, score, total_games
    if total_games != 0:
        outcome = ""
    if in_play:
        outcome = "Player dealed again, lost a point. "
        score -= 1
        in_play = False
    dealer = Hand()
    player = Hand()
    deck = Deck()
    deck.shuffle()
    dealer.add_card(deck.deal_card())
    dealer.add_card(deck.deal_card())
    player.add_card(deck.deal_card())
    player.add_card(deck.deal_card())
    in_play = True
    outcome += "New Game! Hit or Stand?"
    if in_play and player.get_value() == 21:
        stand()
    if in_play and dealer.get_value() == 21:
        stand()
示例#40
0
    def importhand(self, handid=1):

        h = Hand.hand_factory(handid, self.conf, self.db)
        
        return h
示例#41
0
class GameState:
    def __init__(self):
        self.state = None
        self.me = Participant()
        self.resetGame()
        self.resetHand()

    def resetGame(self):
        self.matchID = None
        # dummy entries, overridden on first newGame packet
        self.leftOpp = Participant()
        self.rightOpp = Participant()
        self.numHands = None
        self.stackSize = None
        self.bigB = None
        self.smallB = None
        self.timebank = None

        self.numArrivalsAtStreet = [0,0,0,0]
        self.hand = Hand()
        #self.trackedHands = [CHECK,BET,RAISE,CALL, POST]

    def resetHand(self):
        self.handID = None
        self.me.newHand()
        self.leftOpp.newHand()
        self.rightOpp.newHand()
        self.holeCard1 = None
        self.holeCard2 = None

        self.potSize = None
        self.pot = 0
        self.numBoardCards = None

        self.boardCards = "__,__,__,__,__"#["__","__","__","__","__"]
        self.numLastActions = None
        self.lastActions = None
        self.numLegalActions = None
        self.legalActions = None

        self.hand.clearHand()

        self.lastBet = 0
        self.street = PREFLOP
        self.activePlayers = 3
        self.lastActor = None


    def parseInput(self, input):
        numOptArgs = 0
        packet = input.split(" ")
        self.state = packet[0]
        if self.state == NEWGAME:
            self.resetGame()

            self.matchID = int(packet[1])
            self.leftOpp = Participant(packet[2])
            self.rightOpp = Participant(packet[3])
            self.numHands = int(packet[4])
            self.stackSize = int(packet[5])
            self.bigB = int(packet[6])
            self.smallB = int(packet[7])
            self.timebank = float(packet[8])

        elif self.state == NEWHAND:
            self.resetHand()

            self.handID = int(packet[1])
            self.me.position = int(packet[2])
            self.rightOpp.position = (self.me.position - 1)%3
            self.leftOpp.position = (self.me.position + 1)%3
            self.holeCard1 = Card(packet[3])
            self.holeCard2 = Card(packet[4])
            self.me.holeCard1 = packet[3]
            self.me.holeCard2 = packet[4]
            self.me.bankroll = int(packet[5])
            self.leftOpp.bankroll = int(packet[6])
            self.rightOpp.bankroll  = int(packet[7])
            self.timeBank = float(packet[8])
            self.numArrivalsAtStreet[self.street] += 1

        elif self.state == GETACTION:
            self.potSize = int(packet[1])
            self.numBoardCards = int(packet[2])
            if self.numBoardCards>0:
                numOptArgs += 1
                self.boardCards = packet[3]    #Card(packet[3+i])
            #parse action
            self.numLastActions = int(packet[3+numOptArgs])
            if self.numLastActions>0:
                numOptArgs += 1
                self.lastActions = packet[3+numOptArgs]
            self.numLegalActions = int(packet[4+numOptArgs])
            if self.numLegalActions > 0:
                self.legalActions = packet[5+numOptArgs]

            self.timebank = float(packet[-1])

            self.parseBoardCards()
            self.parseLastActions()
            self.parseLegalActions()
            print self.potSize, "=?", self.pot

        elif self.state == HANDOVER:
            self.me.bankroll = int(packet[1])
            self.leftOpp.bankroll = int(packet[2])
            self.rightOpp.bankroll = int(packet[3])
            self.numLastActions = int(packet[4])
            #parse actions
            if self.numLastActions>0:
                numOptArgs += 1
                self.lastActions = packet[5]
            self.numBoardCards = int(packet[5+numOptArgs])
            if self.numBoardCards>0:
                numOptArgs += 1
                self.boardCards = packet[5+numOptArgs]
            self.timebank = float(packet[-1])

            self.parseBoardCards()
            self.parseLastActions()
            self.hand.splitActionsList()
            #self.calculatePlayerStats()
            self.leftOpp.archive.update(self)
            self.rightOpp.archive.update(self)

            print "my bankroll:", self.me.bankroll
            print self.leftOpp.name, " bank:", self.leftOpp.bankroll
            print self.rightOpp.name, " bank:", self.rightOpp.bankroll

    def parseLastActions(self):
        if self.lastActions:
            self.lastActions = self.lastActions.split(",")
            for i in range(self.numLastActions):
                self.lastActions[i] = self.lastActions[i].split(":")
                #add each action into structure, Hand

                c1 = None
                c2 = None

                sla = self.lastActions[i][0]
                actor = self.lastActions[i][1]
                if actor == self.leftOpp.name:
                    player = self.leftOpp
                elif actor == self.rightOpp.name:
                    player = self.rightOpp
                else:
                    player = self.me

                player.totalPot = self.pot + self.me.pip + self.leftOpp.pip + self.rightOpp.pip
                potamt = 0
                betamt = 0
                amt = self.lastBet
                if len(self.lastActions[i]) == 3:
                    amt = float(self.lastActions[i][2])

                if sla == "RAISE":
                    betamt = amt/float(self.lastBet)
                    potamt = amt/float(player.totalPot)
                    self.lastBet = amt
                    player.stack -= amt - player.pip

                    if not player.aggFreqChanged:
                        player.numBets[self.street] += 1
                        player.aggFreqChanged = True
                    player.amountContributed[self.street] += amt - player.pip
                    player.amountBetRaise[self.street] += amt - player.pip
                    player.pip = amt
                elif sla == "CALL":
                    betamt = 1.0
                    potamt = amt/float(player.totalPot)
                    player.stack -= self.lastBet - player.pip

                    player.amountContributed[self.street] += amt - player.pip
                    player.pip = self.lastBet
                elif sla == "CHECK":
                    if self.street != PREFLOP:
                        amt = 0
                elif sla == "BET":
                    betamt = amt/float(self.lastBet)
                    potamt = amt/float(player.totalPot)
                    self.lastBet = float(self.lastActions[i][2])
                    player.stack -= self.lastBet
                    player.pip = self.lastBet

                    if not player.aggFreqChanged:
                        player.numBets[self.street] += 1
                        player.aggFreqChanged = True
                    player.amountContributed[self.street] += amt
                    player.amountBetRaise[self.street] += amt
                elif sla == "DEAL":
                    amt = 0
                    self.pot += self.me.pip + self.leftOpp.pip + self.rightOpp.pip
                    self.me.pip = 0
                    self.leftOpp.pip = 0
                    self.rightOpp.pip = 0
                    self.street += 1
                    self.numArrivalsAtStreet[self.street] += 1
                    for pl in [self.me, self.leftOpp, self.rightOpp]:
                        pl.aggFreqChanged = False
                        if pl.active==1 and pl.stack>0:
                            pl.numArrivalsAtStreet[self.street] += 1
                        print pl.name, "active:", pl.active, "stack size:", pl.stack, "arrivals:", pl.numArrivalsAtStreet
                elif sla == "POST":
                    self.lastBet = float(self.lastActions[i][2])
                    player.stack -= self.lastBet
                    player.pip = self.lastBet

                    player.amountContributed[self.street] += self.lastBet
                elif sla == "SHOWS":
                    c1 = self.lastActions[i][2]
                    c2 = self.lastActions[i][3]
                    amt = 0
                elif sla == "FOLD":
                    player.active = 0
                    self.activePlayers -= 1
                #elif sla == "REFUND":
                #elif sla == "TIE":
                #elif sla == "WIN":
                if sla in ["POST","BET", "RAISE"]:
                    self.lastActor = player
                    print "lastactor:",self.lastActor.name

                a = Action(ACTION_TYPES.index(sla), self.lastActions[i][1], self.street, c1,
                           c2, potamt, betamt, amt)
                self.hand.actions.append(a)
                player.lastActions.append(a)

#                print "processed action: " + str(a)
#                print "resulting in: stacks",self.me.stack, self.leftOpp.stack, self.rightOpp.stack, "and pips", self.me.pip, self.leftOpp.pip, self.rightOpp.pip
#        print "lastActions", self.lastActions

    def parseLegalActions(self):
        if self.legalActions:
            self.legalActions = self.legalActions.split(",")
            for i in range(self.numLegalActions):
                self.legalActions[i] = self.legalActions[i].split(":")

    def parseBoardCards(self):
        if(type(self.boardCards) == type("STRING")):
            self.boardCards = self.boardCards.split(",")
        for i in range(5-len(self.boardCards)):
            self.boardCards += ["__"]

    def calculatePlayerStats(self):
        for p in [self.leftOpp, self.rightOpp]:
            for s in [0,1,2,3]:
                rounds = p.numArrivalsAtStreet[s]
                if s==0:
                    rounds = self.handID
                if rounds == 0:
                    p.aggFreq[s] = 0
                    p.avgChips[s] = 0
                else:
                    p.avgChips[s] = float(p.amountContributed[s])/rounds
                    p.aggFreq[s] = float(p.numBets[s])/rounds
                if p.numBets[s] >0:
                    p.avgRaiseAmt[s] = float(p.amountBetRaise[s])/p.numBets[s]
                if self.handID !=0:
                    p.percentArrivals[s] = float(rounds)/self.handID
示例#42
0
def play2(entity):
    if entity['player'] == Utilities.them:
        logging.info('Opponent plays %s' % entity['name'])
        if entity['name'] in ["Crackle", "Fireguard Destroyer", "Lightning Bolt", "Stormcrack", "Stormforged Axe", "Totem Golem", "Dunemaul Shaman", "Siltfin Spiritwalker"]:
            Utilities.overload += 1
        elif entity['name'] in ["Ancestral Knowledge", "Dust Devil", "Flamewreathed Faceless", "Forked Lightning", "Feral Spirit", "Lava Burst", "Lightning Storm", "Doomhammer"]:
            Utilities.overload += 2
        elif entity['name'] in ["Earth Elemental", "Neptulon"]:
            Utilities.overload += 3
        elif entity['name'] in ["Elemental Destruction"]:
            Utilities.overload += 5
        elif entity['name'] in ["Lava Shock", "Eternal Sentinel"]:
            Utilities.overload = 0

        elif entity['name'] == "Varian Wrynn":
            Legendaries.varianWrynn = True

        elif entity['name'] == "A Light in the Darkness":
            Hand.draw(entity, source='random', kind='minion', buff=+1)
        elif entity['name'] == "Arch-Thief Rafaam":
            Hand.draw(entity, note='A powerful artifact')
        elif entity['name'] == "Babbling Book":
            Hand.draw(entity, source='random', hero='mage', kind='spell')
        elif entity['name'] == "Burgle":
            Hand.draw(entity, source='random', hero='your class') # FIXME
            Hand.draw(entity, source='random', hero='your class') # FIXME
        elif entity['name'] == "Cabalist's Tomb":
            Hand.draw(entity, source='random', hero='mage', kind='spell')
            Hand.draw(entity, source='random', hero='mage', kind='spell')
            Hand.draw(entity, source='random', hero='mage', kind='spell')
        elif entity['name'] == "Dark Peddler":
            Hand.draw(entity, note='A 1-cost card')
        elif entity['name'] == "Ethereal Conjurer":
            Hand.draw(entity, source='discovered', hero='mage', kind='spell')
        elif entity['name'] == "Finders Keepers":
            Hand.draw(entity, hero='shaman', note='A card with overload')
        elif entity['name'] == "Gorillabot A-3":
            Hand.draw(entity, kind='mech minion')
        elif entity['name'] == "Grand Crusader":
            Hand.draw(entity, source='random', hero='paladin')
        elif entity['name'] == "Grimestreet Informant":
            Hand.draw(entity, hero='hunter, paladin, or warrior')
        elif entity['name'] == "I Know a Guy":
            Hand.draw(entity, kind='taunt minion')
        elif entity['name'] == "Jeweled Scarab":
            Hand.draw(entity, note='A 3-cost card')
        elif entity['name'] == "Journey Below":
            Hand.draw(entity, note='A deathrattle card')
        elif entity['name'] == "Kabal Chemist":
            Hand.draw(entity, kind='potion spell')
        elif entity['name'] == "Lotus Agents":
            Hand.draw(entity, hero='druid, rogue, or shaman')
        elif entity['name'] == "Mind Vision":
            Hand.draw(entity, note='A card from your hand')
        elif entity['name'] == "Mukla, Tyrant of the Vale":
            Hand.draw(entity, kind='Banana')
            Hand.draw(entity, kind='Banana')
        elif entity['name'] == "Museum Curator":
            Hand.draw(entity, note='A deathrattle card')
        elif entity['name'] == "Nefarian":
            Hand.draw(entity, source='random', hero='your class') # FIXME
            Hand.draw(entity, source='random', hero='your class') # FIXME
        elif entity['name'] == "Neptulon":
            Hand.draw(entity, source='random', kind='murloc minion')
            Hand.draw(entity, source='random', kind='murloc minion')
            Hand.draw(entity, source='random', kind='murloc minion')
            Hand.draw(entity, source='random', kind='murloc minion')
        elif entity['name'] == "Raven Idol":
            Hand.draw(entity, kind='minion or spell')
        elif entity['name'] == "Sense Demons":
            Hand.draw(entity, kind='demon minion')
            Hand.draw(entity, kind='demon minion')
        elif entity['name'] == "Swashburglar":
            Hand.draw(entity, source='random', hero='your class') # FIXME
        elif entity['name'] == "Thoughtsteal":
            Hand.draw(entity, note='A random card from your deck')
            Hand.draw(entity, note='A random card from your deck')
        elif entity['name'] == "Tomb Spider":
            Hand.draw(entity, kind='beast minion')
        elif entity['name'] == "Toshley":
            Hand.draw(entity, kind='Spare Part')
        elif entity['name'] == "Unstable Portal":
            Hand.draw(entity, source='random', kind='minion', cost=-3)
        elif entity['name'] == "Wild Growth":
            if Utilities.resources == '10':
                Hand.draw(entity, kind='Excess Mana')
        elif entity['name'] == "Xaril, Poisoned Mind":
            Hand.draw(entity, source='random', kind='toxin')

        elif entity['name'] == "Call Pet":
            Hand.notes.append('If it\'s a beast, cost -4')
        elif entity['name'] == "Far Sight":
            Hand.notes.append('Costs (3) less')
    elif entity['player'] == Utilities.us:
        if entity['name'] == "King Mukla":
            Hand.draw(entity, kind='Banana')
            Hand.draw(entity, kind='Banana')
        elif entity['name'] == "Mulch":
            Hand.draw(entity, source='random', kind='minion')
    # if entity['player'] in [Utilities.us, Utilities.them]:
    if entity['name'] == "Elite Tauren Chieftain":
        Hand.draw(entity, kind='Power Chord spell')
    elif entity['name'] == "Spellslinger":
        Hand.draw(entity, source='random', kind='spell')
示例#43
0
def die(entity):
    if entity['player'] == Utilities.them:
        if entity['name'] == "Anub'arak":
            Hand.draw(entity, note='Anub\'arak')
        elif entity['name'] == "Clockwork Gnome":
            Hand.draw(entity, kind='Spare Part')
        elif entity['name'] == "Deadly Fork":
            Hand.draw(entity, note='Sharp Fork')
        elif entity['name'] == "Rhonin":
            Hand.draw(entity, note='Arcane Missles')
            Hand.draw(entity, note='Arcane Missles')
            Hand.draw(entity, note='Arcane Missles')
        elif entity['name'] == "Shifting Shade":
            Hand.draw(entity, note='A card from your deck')
        elif entity['name'] == "Tentacles for Arms":
            Hand.draw(entity, note='Tentacles for Arms')
        elif entity['name'] == "Tomb Pillager":
            Hand.draw(entity, note='The Coin')
        elif entity['name'] == "Toshley":
            Hand.draw(entity, kind='Spare Part')
        elif entity['name'] == "Undercity Huckster":
            Hand.draw(entity, source='random', hero='your class') # FIXME
        elif entity['name'] == "Xaril, Poisoned Mind":
            Hand.draw(entity, source='random', kind='toxin')
        elif entity['name'] == "Webspinner":
            Hand.draw(entity, source='random', kind='beast minion')
    # if entity['player'] in [Utilities.us, Utilities.them]:
    if entity['name'] == "Mechanical Yeti":
        Hand.draw(entity, kind='Spare Part')
示例#44
0
文件: Hud.py 项目: Tuxik/fpdb
 def update(self, hand, config):
      # Load a hand instance (factory will load correct type for this hand)
     self.hand_instance = Hand.hand_factory(hand, config, self.db_hud_connection)
     self.db_hud_connection.connection.rollback()
     self.hand = hand   # this is the last hand, so it is available later
示例#45
0
def play3(entity, target):
    if entity['player'] == Utilities.them:
        if entity['name'] in ["Ancient Brewmaster", "Convert", "Gadgetzan Ferryman", "Time Rewinder", "Youthful Brewmaster"]:
            Hand.draw(target, note=target['name'])
        elif entity['name'] in ["Bloodthistle Toxin", "Shadowstep"]:
            Hand.draw(target, note=target['name'], cost=-2)
        elif entity['name'] == "Convert":
            Hand.draw(target, note=target['name'])
        elif entity['name'] == "Shadowcaster":
            Hand.draw(target, note='A 1/1 copy of %s which costs (1)' % target['name'])
    elif entity['player'] == Utilities.us:
        if entity['name'] == "Freezing Trap":
            Hand.draw(target, note=target['name'], cost=+2)
        elif entity['name'] == "Sap":
            Hand.draw(target, note=target['name'])
    if target['player'] == Utilities.them:
        if entity['name'] in ["Dream", "Kindapper"]:
            Hand.draw(target, note=target['name'])
示例#46
0
文件: Hud.py 项目: Fulvio75/fpdb
 def update(self, hand, config):
      # re-load a hand instance (factory will load correct type for this hand)
     self.hand_instance = Hand.hand_factory(hand, config, self.db_hud_connection)
     self.db_hud_connection.connection.rollback()
示例#47
0
def parseFile(line_generator, config, *args):
    '''
    Main parsing function.
    line_generator can be a tail for live execution,
    or a file object for testing.
    '''
    lineNo = 0
    from re import match
    showEntity = None
    for line in line_generator(*args):
        lineNo += 1
        line_parts = match('^D \d{2}:\d{2}:\d{2}\.\d{7} ([a-zA-Z]*\.[a-zA-Z]*\(\)) -\s*([A-Z_]{2,}|)(.*)', line)
        if line_parts is None: # Any of the error messages won't match, but it's not safe to use them
            continue
        source = line_parts.group(1)
        type = line_parts.group(2)
        data = parse(line_parts.group(3))

        if source == 'GameState.DebugPrintEntityChoices()':
            if 'ChoiceType' in data and data['ChoiceType'] == 'MULLIGAN':
                if data['Player'] == config['username']:
                    logging.debug('You are player id %s' % data['id'])
                    Utilities.us = data['id']
                else:
                    logging.debug('Opponent is player id %s' % data['id'])
                    Utilities.them = data['id']
        if source == 'GameState.DebugPrintEntitiesChosen()':
            # Cards that were not mulliganed
            if data.keys()[0][:8] == 'Entities': # Entities[0], e.g.
                if data.values()[0]['zone'] == 'HAND':
                    Hand.keep(data.values()[0])
        if showEntity is not None:
            if type:
                showEntity = None
            elif 'tag' in data and data['tag'] == 'ZONE' and data['value'] == 'GRAVEYARD':
                Hand.discard(showEntity)
        if source == 'PowerTaskList.DebugPrintPower()':
            if type == 'BLOCK_END':
                Legendaries.blockEnd()
            elif type == 'BLOCK_START':
                if data['BlockType'] == 'TRIGGER':
                    if 'zone' in data['Entity']:
                        if data['Entity']['zone'] == 'GRAVEYARD':
                            Cards.die(data['Entity'])
                            Legendaries.die(data['Entity'])
                        elif data['Entity']['zone'] == 'PLAY':
                            Cards.trigger(data['Entity'])
                elif data['BlockType'] == 'POWER': # When a card actually hits the board
                    if 'Target' in data and isinstance(data['Target'], dict):
                        Cards.play3(data['Entity'], data['Target']) # A card targets another card.
                        Legendaries.play3(data['Entity'], data['Target'])
                    else:
                        Cards.play2(data['Entity'])
                        Legendaries.play2(data['Entity'])
            elif type == 'SHOW_ENTITY': # Start of a SHOW_ENTITY block of data
                showEntity = data['Entity']
            elif type == 'TAG_CHANGE':
                if data['tag'] == 'FIRST_PLAYER':
                    logging.warning('New game started')
                    Utilities.wentFirst(data['Entity'] == config['username'])
                if data['tag'] == 'JUST_PLAYED':
                    if data['Entity']['zone'] == 'HAND':
                        Hand.play(data['Entity']) # When a card is removed from a player's hand
                elif data['tag'] == 'RESOURCES':
                    if data['Entity'] != config['username']:
                        Utilities.resources = data['value']
                elif data['tag'] == 'STEP':
                    if data['value'] == 'FINAL_GAMEOVER':
                        Hand.reset()
                        Utilities.reset()
                        Legendaries.reset()
                        print 'Game Over'
                    if data['value'] == 'MAIN_READY':
                        if Utilities.ourTurn():
                            Hand.turnover()
                            Cards.turnover()
                            Legendaries.turnover()
                elif data['tag'] == 'TURN':
                    Utilities.turn = int(data['value'])
                elif data['tag'] == 'ZONE_POSITION':
                    if 'zone' in data['Entity'] and data['Entity']['zone'] == 'DECK':
                        Hand.draw(data['Entity'], int(data['value'])-1)