Example #1
0
def handleInquireMsg(skt, gameinfo, msg):
    # 处理询问消息:
    # 询问消息:分为两部分----前面的player操作 + 彩池信息
    inquireMsgRe = r'inquire/\s*\n([\s\S]*)\s*\ntotal\s+pot:\s+(\d+)\s*\n/inquire'
    # Player操作:用户id 筹码 持有金币 下注 操作
    playerOpsRe = r'(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(.*)\s+'
    inquireMatch = re.search(inquireMsgRe, msg)
    if inquireMatch:
        writeLog('\nGet inquire message')
        print 'Get inquire message: '
        opsMsg = inquireMatch.group(1)
        potMsg = inquireMatch.group(2)
        opsSet = opsMsg.split('\n')
        actionSet = []
        for ops in opsSet:
            opsMatch = re.search(playerOpsRe, ops)
            if opsMatch:
                player = opsMatch.group(1)
                jetton = opsMatch.group(2)
                money = opsMatch.group(3)
                bet = opsMatch.group(4)
                op = opsMatch.group(5)
                action = Action()
                action.setAction(player, jetton, money, bet, op)
                #action.saveActionLog()
                actionSet.append(action)
        gameinfo.actions = actionSet
        gameinfo.updatePlayerInfo()
        gameinfo.potNum = int(potMsg)
        decisionProcess(skt, gameinfo)
Example #2
0
def parsePlayersTights(gameinfo):
    # 通过分析各玩家的投注行为,获取各玩家的松紧策略
    # 说明:
    # 我们每过25局分析一次各玩家的投注行为,从而维护一个玩家松紧系数向量。
    # 那么,我们就可以根据这个向量实施相应的策略

    # pts表示对应player对应的tight系数
    # 如 pts[1111] = 2
    pts = []

    writeLog('\nParse Players Tights...')
    print 'Parse Players Tights....'

    # 这里,我们考虑到内存问题,选择了这样一种策略:
    # 每次计算后清空player的历史操作,仅仅将结果赋值到变量tightlevel中
    # 这样,后面计算时,前面的结果就自动保存为一个结果,然后再相加
    for ph in gameinfo.phSet:
        # ph表示一个玩家的操作历史
        phtights = ph.tightlevel
        for ctp in ph.cardtopot:
            cards = ctp.holdcards
            phtights += parseTightFromHoldCards(ctp.holdcards)
        aveTight = float(phtights) / (len(ph.cardtopot) + 1)
        pt = {}
        pt['id'] = ph.id
        pt['tight'] = aveTight
        pts.append(pt)
        ph.setTightLevel(aveTight)
        ph.cardtopot = []

    return pts
Example #3
0
def handleFlopMsg(gameinfo, msg):
    # 公牌信息处理
    # 翻牌消息:
    flopMsgRe = r'flop/\s*\n(\w+)\s+(\w+)\s*\n(\w+)\s+(\w+)\s*\n(\w+)\s+(\w+)\s*\n/flop'
    flopMatch = re.search(flopMsgRe, msg)
    if flopMatch:
        writeLog('\nGet flop cards:')
        print 'Get flop cards: '
        color1 = flopMatch.group(1)
        point1 = flopMatch.group(2)
        card1 = Card()
        card1.setCardInfo(color1, point1)
        card1.printCardInfo()
        card1.saveCardLog()
        color2 = flopMatch.group(3)
        point2 = flopMatch.group(4)
        card2 = Card()
        card2.setCardInfo(color2, point2)
        card2.printCardInfo()
        card2.saveCardLog()
        color3 = flopMatch.group(5)
        point3 = flopMatch.group(6)
        card3 = Card()
        card3.setCardInfo(color3, point3)
        card3.printCardInfo()
        card3.saveCardLog()
        gameinfo.addPublicCards(card1)
        gameinfo.addPublicCards(card2)
        gameinfo.addPublicCards(card3)
Example #4
0
def sendMsgToServer(sock=None, msg=None):
    if msg:
        writeLog('\nSend My Operation: ')
        writeLog(msg)
        print '\nSend My Operation: '
        print msg
        try:
            sock.send(msg)
        except socket.error, msg:
            print 'Message Send Failure. Error Message: ' + msg[1]
Example #5
0
def buildConnection(myip=None, myport=0, uip=None, uport=0):
    skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    myaddr = (myip, myport)
    try:
        skt.bind(myaddr)
    except socket.error, msg:
        err = 'Binding Failure. Error Message: ' + msg[1]
        print err
        writeLog(err)
Example #6
0
def listenServerInfo(sock=None, gameinfo=None):
    print 'Client is waiting message from remote gameserver...'
    while True:
        msg = sock.recv(2048)
        if msg:
            writeLog('\nReceived Message: ')
            writeLog(msg)
            print '\nReceived message: '
            print msg
            # thread.start_new_thread(handleMsg, (sock, msg, gameinfo))
            handleMsg(sock, msg, gameinfo)
            msg = ''
        else:
            continue
Example #7
0
def riverRoundDecision(gameinfo):
    (msg, aplayers) = handleActive(gameinfo)
    if msg:
        log = 'River Round Decision: ' + msg
        writeLog(log)
        return msg

    allcards = gameinfo.holdCards + gameinfo.publicCards
    (value, level, cards) = parseRiverRoundLevel(allcards)

    mytight2 = 0
    # 玩家排名的策略分析
    mytight1 = gameinfo.mytight
    # 通过分析用户松紧策略决定自己的松紧策略
    mytight2 = getMyTightFromPalyerTights(gameinfo, aplayers)
    # 取两种策略分析的最大值
    tightPolicy = max(mytight1, mytight2)

    tightInfo = 'River Round Tight Policy: ' + str(tightPolicy)
    writeLog(tightInfo)

    cardsLevelMsg = 'River Round Cards Level: ' + getLevelByIndex(level)
    writeLog(cardsLevelMsg)

    msg = getRiverMsgBasedOnTightLevel(gameinfo, tightPolicy, level, value,
                                       gameinfo.riverNum)

    log = 'River Round Decision: ' + msg
    writeLog(log)

    return msg
Example #8
0
def handlePotMsg(gameinfo, msg):
    # 彩池分配消息处理:
    # 彩池分配消息:
    potwinMsgRe = r'pot-win/\s*\n([\s\S]*)\s*\n/pot-win'
    # 彩池单分配:
    potMsgRe = r'(\d+):\s+(\d+)'
    potwinItems = re.findall(potwinMsgRe, msg)
    if potwinItems:
        writeLog('\nGet pot num message')
        print 'Get pot num message'
        potwinMsg = potwinItems[0]
        potwins = potwinMsg.split('\n')
        for potwin in potwins:
            potwinMatch = re.search(potMsgRe, potwin)
            if potwinMatch:
                player = potwinMatch.group(1)
                pot = potwinMatch.group(2)
                playerInfo = gameinfo.getPlayerById(player)
                playerHistory = gameinfo.getPHById(player)
                if not playerHistory:
                    playerHistory = PlayerHistory(player)
                playerHistory.addPlayerHistory(playerInfo.holdcards, int(pot))
                writeLog('Pot-win info: ')
                print 'Pot-win info: '
                writeLog('Player ID: %s' % player)
                print 'Player ID: ', player
                writeLog('Player Pot: %s' % pot)
                print 'PlayerPot: ', pot
Example #9
0
def handleShowdownMsg(gameinfo, msg):
    # 摊牌消息处理:
    # 摊牌消息: 牌池信息 + 排名信息
    showdownMsgRe = r'showdown/\s*\ncommon/\s*\n([\s\S]*)\s*\n/common\s*\n([\s\S]*)\s*\n/showdown'
    # 牌池信息:
    cardMsgRe = r'(\w+)\s+(\w+)'
    # 排名信息:
    rankMsgRe = r'(\d+):\s+(\d+)\s+(\w+)\s+(\w+)\s+(\w+)\s+(\w+)\s+(\w+)'
    showdownMatch = re.search(showdownMsgRe, msg)
    if showdownMatch:
        writeLog('\nGet showdown message:')
        print 'Get showdown message: '
        cardMsg = showdownMatch.group(1)
        rankMsg = showdownMatch.group(2)
        cards = cardMsg.split('\n')
        ranks = rankMsg.split('\n')
        print 'Handling common cards information...'
        writeLog('Common cards information:')
        for card in cards:
            cardMatch = re.search(cardMsgRe, card)
            if cardMatch:
                color = cardMatch.group(1)
                point = cardMatch.group(2)
                print color, point
                clrinfo = 'Card color: %s' % color
                pitinfo = 'Card point: %s' % point
                writeLog(clrinfo)
                writeLog(pitinfo)
        writeLog('\nPlayer rank information')
        print 'Handling rank information...'
        for rank in ranks:
            rankMatch = re.search(rankMsgRe, rank)
            if rankMatch:
                rank = rankMatch.group(1)
                player = rankMatch.group(2)
                color1 = rankMatch.group(3)
                point1 = rankMatch.group(4)
                color2 = rankMatch.group(5)
                point2 = rankMatch.group(6)
                nut_hand = rankMatch.group(7)
                card1 = Card()
                card1.setCardInfo(color1, point1)
                card1.printCardInfo()
                card1.saveCardLog()
                card2 = Card()
                card2.setCardInfo(color1, point1)
                card2.printCardInfo()
                card2.saveCardLog()
                gameinfo.updateRankInfo(player, card1, card2, rank, nut_hand)
Example #10
0
def handleTurnMsg(gameinfo, msg):
    # 转牌消息处理:
    # 转牌消息:
    turnMsgRe = r'turn/\s*\n(\w+)\s+(\w+)\s*\n/turn'
    turnMatch = re.search(turnMsgRe, msg)
    if turnMatch:
        writeLog('\nGet turn card:')
        print 'Get turn card:'
        color = turnMatch.group(1)
        point = turnMatch.group(2)
        card = Card()
        card.setCardInfo(color, point)
        card.printCardInfo()
        card.saveCardLog()
        gameinfo.addPublicCards(card)
Example #11
0
def handleRiverMsg(gameinfo, msg):
    # 河牌消息处理:
    # 河牌消息
    riverMsgRe = r'river/\s*\n(\w+)\s+(\w+)\s*\n/river'
    riverMatch = re.search(riverMsgRe, msg)
    if riverMatch:
        writeLog('\nGet river card:')
        print 'Get river card: '
        color = riverMatch.group(1)
        point = riverMatch.group(2)
        card = Card()
        card.setCardInfo(color, point)
        card.printCardInfo()
        card.saveCardLog()
        gameinfo.addPublicCards(card)
Example #12
0
def handleHoldMsg(gameinfo, msg):
    # 处理手牌消息:
    # 持有手牌:花色 大小 花色 大小(共两张牌)
    holdMsgRe = r'hold/\s*\n(\w+)\s+(\w+)\s*\n(\w+)\s+(\w+)\s*\n/hold'
    holdMatch = re.search(holdMsgRe, msg)
    if holdMatch:
        writeLog('\nGet hold cards message: ')
        print 'Get hold cards message: '
        color1 = holdMatch.group(1)
        point1 = holdMatch.group(2)
        card1 = Card()
        card1.setCardInfo(color1, point1)
        card1.saveCardLog()
        card1.printCardInfo()
        color2 = holdMatch.group(3)
        point2 = holdMatch.group(4)
        card2 = Card()
        card2.setCardInfo(color2, point2)
        card2.saveCardLog()
        card2.printCardInfo()
        gameinfo.addHoldCards(card1)
        gameinfo.addHoldCards(card2)
Example #13
0
def parseRiverRoundLevel(rivercards):
    result = []
    maxRet = None
    # combinations方法将实现多选多的过程
    combs = itertools.combinations(rivercards, 5)
    for cards in combs:
        (value, level) = parseFlopRoundLevel(cards)
        ret = (value, level, cards)
        result.append(ret)
    if result:
        sortedRet = sorted(result, reverse=True)
        maxRet = sortedRet[0]

    valueMsg = 'River Round Max Cards Value: ' + str(maxRet[0])
    writeLog(valueMsg)
    print valueMsg

    levelMsg = 'River Round Max Cards Level: ' + getLevelByIndex(maxRet[1])
    writeLog(levelMsg)
    print levelMsg

    return maxRet
Example #14
0
def flopRoundDecision(gameinfo):
    (msg, aplayers) = handleActive(gameinfo)
    if msg:
        log = 'Flop Round Decision: ' + msg
        writeLog(log)
        return msg

    allcards = gameinfo.holdCards + gameinfo.publicCards
    (value, level) = parseFlopRoundLevel(allcards)

    mytight2 = 0
    # 玩家排名的策略分析
    mytight1 = gameinfo.mytight
    '''
	# 通过分析用户松紧策略决定自己的松紧策略
	mytight2 = getMyTightFromPalyerTights(gameinfo, aplayers)
	'''

    # 策略分析取值
    if mytight1 == 0:
        tightPolicy = 0
    else:
        tightPolicy = max(mytight1, mytight2)

    tightInfo = 'Flop Round Tight Policy: ' + str(tightPolicy)
    writeLog(tightInfo)

    cardsLevelMsg = 'Flop Round Cards Level: ' + getLevelByIndex(level)
    writeLog(cardsLevelMsg)

    msg = getFlopMsgBasedOnTightLevel(gameinfo, tightPolicy, level, value,
                                      gameinfo.flopNum)

    log = 'Flop Round Decision: ' + msg
    writeLog(log)

    return msg
Example #15
0
def testSVM():
	## loading data
	log = "Step 1: loading data..."
	writeLog(log)
	print log
	test_x, test_y = loadDigitTestData()
	# scales from -1 to 1
	test_x = test_x/255.0*2 - 1

	# initialize the vote matrix for testing data, Votes[m, 10]
	m, dump = shape(test_y)
	Votes = mat(zeros((m, 10)))

	## testing data
	log = "Step 2: testing data..."
	for i in range(10):
		for j in range(i+1, 10):
			log = "--working on model: " + str(i) + '&' + str(j)
			print log
			writeLog(log)
			# loading the models
			d = shelve.open('./models/svm_' + str(i) + '_' + str(j))
			svmClassifier = d['svm']
			d.close()
			# testing using the given model and votes
			Votes_k, Votes_l = SVM.testDigitScores(svmClassifier, test_x, m)

			# write to the Votes
			Votes[:, i] += Votes_k
			Votes[:, j] += Votes_l

	## saving Votes matrix
	log = "Step 3: saving votes..."
	print log
	writeLog(log)
	d = shelve.open('./models/Votes_Score_noscale')
	d['vote'] = Votes
	d.close()
Example #16
0
def handleBlindMsg(gameinfo, msg):
    # 处理盲注消息:
    blindMsgRe = r'blind/\s*\n([\s\S]*)\s*\n/blind'
    # 盲注值:用户id;赌注(盲注)
    blindBetRe = r'(\d+):\s+(\d+)'
    blindItems = re.findall(blindMsgRe, msg)
    if blindItems:
        writeLog('\nGet blind bet message: ')
        print '\nGet blind bet message: '
        blindInfo = blindItems[0]
        blinds = blindInfo.split('\n')
        bet = []
        for blind in blinds:
            blindMatch = re.search(blindBetRe, blind)
            if blindMatch:
                betValue = blindMatch.group(2)
                bet.append(betValue)
        gameinfo.smallBlindBet = bet[0]
        smallbet = 'small bet: %s' % bet[0]
        writeLog(smallbet)
        if len(bet) == 2:
            gameinfo.bigBlindBet = bet[1]
            bigbet = 'big bet: %s' % bet[1]
            writeLog(bigbet)
Example #17
0
    myaddr = (myip, myport)
    try:
        skt.bind(myaddr)
    except socket.error, msg:
        err = 'Binding Failure. Error Message: ' + msg[1]
        print err
        writeLog(err)

    uaddr = (uip, uport)
    try:
        skt.connect(uaddr)
    except socket.error, msg:
        err = 'Connection Failure. Error Message: ' + msg[1]
        print err
        writeLog(err)

    return skt


# 监听处理服务器发送的信息
def listenServerInfo(sock=None, gameinfo=None):
    print 'Client is waiting message from remote gameserver...'
    while True:
        msg = sock.recv(2048)
        if msg:
            writeLog('\nReceived Message: ')
            writeLog(msg)
            print '\nReceived message: '
            print msg
            # thread.start_new_thread(handleMsg, (sock, msg, gameinfo))
Example #18
0
def handRoundDecision(gameinfo):
    # 通过handleActive函数分析当前未弃牌的玩家数,并作出最简单只剩下自己时的操作
    (msg, aplayers) = handleActive(gameinfo)
    if msg:
        log = 'Hand Round Decision:' + msg
        writeLog(log)
        return msg

    # 玩家排名策略分析
    mytight1 = parseRaisePolicy(gameinfo)
    gameinfo.mytight = mytight1
    if mytight1 == 4:
        msg = 'fold \n'
        log = 'Hand Round Decision: ' + msg
        writeLog(log)
        return msg

    mytight2 = 0
    '''
	# 通过分析用户松紧策略决定自己的松紧策略
	mytight2 = getMyTightFromPalyerTights(gameinfo, aplayers)
	if mytight2 == 3:
		mytight2 = 1
	elif mytight2 == 0:
		mytight2 = 2
	'''

    # 策略分析取值
    if mytight1 == 0:
        tightPolicy = 0
    else:
        tightPolicy = max(mytight1, mytight2)

    tightInfo = 'Hand Round Tight Policy: ' + str(tightPolicy)
    writeLog(tightInfo)

    myrole = gameinfo.myplayer.role
    opSet = parseOperationSet(gameinfo)

    joinFlag = handCardsHandle(gameinfo.holdCards,
                               myseatrole=myrole,
                               tightPolicy=tightPolicy)

    if joinFlag:
        bigBet = int(gameinfo.bigBlindBet) / 4 + gameinfo.minRaiseCount
        smallBet = max(int(gameinfo.minRaiseCount), int(gameinfo.bigBlindBet))
        holdLevel = parseHoldLevel(gameinfo.holdCards)
        writeLog('Hold Cards Level: ' + str(holdLevel))
        # 如果我的总筹码能够承受我希望加注的钱,那么就加注
        if bigBet < int(gameinfo.myplayer.jetton):
            if 4 in opSet:
                if gameinfo.holdNum <= 3:
                    if holdLevel >= 3:
                        msg = 'raise %s \n' % bigBet
                    elif holdLevel == 2:
                        msg = 'raise %s \n' % smallBet
                    else:
                        msg = 'call \n'
                elif gameinfo.holdNum <= 5:
                    if holdLevel == 3:
                        msg = 'raise %s \n' % bigBet
                    elif holdLevel == 3:
                        msg = 'raise %s \n' % smallBet
                    else:
                        msg = 'call \n'
                else:
                    if holdLevel == 4:
                        msg = 'raise %s \n' % smallBet
                    else:
                        msg = 'fold \n'
            else:
                # 前面的小伙伴们都是all_in了,我就只有两条路可选了:
                # 要么一起all_in一起嗨,要么fold等下轮了...
                # 这可是关系到身家性命,当然不能马虎对待了
                # 此处的想法是,不要轻易的all_in
                holdLevel = parseHoldLevel(gameinfo.holdCards)
                if holdLevel == 4:
                    msg = 'all_in \n'
                else:
                    msg = 'fold \n'
        # 完蛋,钱不够,那就all_in吧,死活一条命嘛
        else:
            if holdLevel == 4:
                msg = 'all_in \n'
            else:
                msg = 'fold \n'
    else:
        msg = 'fold \n'

    log = 'Hand Round Decision: ' + msg
    writeLog(log)
    return msg
Example #19
0
def handleSeatMsg(gameinfo, msg):
    # 匹配收到的信息中是否有座次信息,有则处理,否则进行其他检查
    # 座次信息正则表达式
    seatMsgRe = r'seat/\s\s*\n([\s\S]*)\s\s*\n/seat'
    # 庄家信息:用户id 筹码 持有金币
    buttonMsgRe = r'button:\s+(\d+)\s+(\d+)\s+(\d+)'
    # 小盲注信息:用户id 筹码 持有金币
    smallBlindMsgRe = r'small\s+blind:\s+(\d+)\s+(\d+)\s+(\d+)'
    # 大盲注信息:用户id  筹码 持有金币
    bigBlindMsgRe = r'big\s+blind:\s+(\d+)\s+(\d+)\s+(\d+)'
    # 其他用户信息:用户id 筹码 持有金币
    norlmalMsgRe = r'(\d+)\s+(\d+)\s+(\d+)'
    seatItems = re.findall(seatMsgRe, msg)
    if seatItems:
        gameinfo.someDataClean()
        gameinfo.gameNum += 1
        writeLog('\nGet seat message: ')
        print 'Get seat message: '
        seatInfo = seatItems[0]
        seats = seatInfo.split('\n')
        normalSeats = 3
        # seats对应所有玩家,seat对应每一个玩家
        for seat in seats:
            buttonMatch = re.search(buttonMsgRe, seat)
            if buttonMatch:
                # role: button (BTN)
                seatRole = 1
                id = buttonMatch.group(1)
                jetton = buttonMatch.group(2)
                money = buttonMatch.group(3)
                gameinfo.addNewPlayer(id, jetton, money, seatRole)
                print 'Add new player: '
                print 'role: button'
                print 'id: ', id
                print 'jetton: ', jetton
                print 'money: ', money
                continue
            smallBlindMatch = re.search(smallBlindMsgRe, seat)
            if smallBlindMatch:
                # role: small blind (SB)
                seatRole = 2
                id = smallBlindMatch.group(1)
                jetton = smallBlindMatch.group(2)
                money = smallBlindMatch.group(3)
                gameinfo.addNewPlayer(id, jetton, money, seatRole)
                print 'Add new player: '
                print 'role: small blind'
                print 'id: ', id
                print 'jetton: ', jetton
                print 'money: ', money
                continue
            bigBlindMatch = re.search(bigBlindMsgRe, seat)
            if bigBlindMatch:
                # role: big blind (BB)
                seatRole = 3
                id = bigBlindMatch.group(1)
                jetton = bigBlindMatch.group(2)
                money = bigBlindMatch.group(3)
                gameinfo.addNewPlayer(id, jetton, money, seatRole)
                print 'Add new player: '
                print 'role: big blind'
                print 'id: ', id
                print 'jetton: ', jetton
                print 'money: ', money
                continue
            normalMatch = re.search(norlmalMsgRe, seat)
            if normalMatch:
                # role: normal (EP EP MP MP LP)
                normalSeats += 1
                id = normalMatch.group(1)
                jetton = normalMatch.group(2)
                money = normalMatch.group(3)
                gameinfo.addNewPlayer(id, jetton, money, normalSeats)
                print 'Add new player: '
                print 'role: normal'
                print 'id: ', id
                print 'jetton: ', jetton
                print 'money: ', money
                continue
Example #20
0
def handCardsHandle(mycards, myseatrole, tightPolicy=1):
    '''
	分析手牌,然后确定是否应该加入牌局
	对于tightPolicy,其表示我们在玩牌时的松紧策略
	'''
    # tightPolicy表示是否实行紧方式
    # inFlag 用于表示是否决定玩一手牌。
    # 位置划分:
    # ep(前位):8--大盲注后两个,4/3---依次递减
    # mp(中位):8--EP后两个,6/5---依次递减
    # lp(末位):8--MP后一个,7删除
    # button(庄家)
    # blind(大小盲注)
    # 这里,我们使用经验,选择执行20%策略
    # 基于概率事件,通过经验:
    # ep: 44+/AKo/ATs+/AQo+
    # mp: 33+/A8s+/ATo+/KJo+
    # lp: 22+/A2s+
    # button: 22+/A2s+/T9s+/AJo+
    # blind: 22+/AKo/AQs/AJs/KQs
    # 另外,对于松机制
    # 所有:22+/AJo+/A4s+/98s+/KQo/KJs
    inFlag = False
    # 使用最紧机制
    # 最紧机制通常适用于这样的情况:
    # 1、起手牌时,对手中存在all_in时,实行最紧策略,不要轻易all_in
    # 2、当自己的金钱远远大于第二名时,实行最紧策略。原因在于不要轻易加入牌局,除非自己有着极大的赢牌几率
    # 3、当牌局的紧策略玩家出现加注和all_in操作时,我们实行最紧机制
    if tightPolicy == 3:
        inFlag = (
            justifyMode(
                mycards, pointMax=6, pointMin=6, plus=True, isuit=False)
            or justifyMode(
                mycards, pointMax=14, pointMin=13, plus=False, isuit=False)
            or justifyMode(
                mycards, pointMax=14, pointMin=10, plus=True, isuit=True)
            or justifyMode(
                mycards, pointMax=13, pointMin=12, plus=True, isuit=True))
    # 使用紧机制
    # 紧机制通常适用于这样一些情况:
    # 1、当自己的金钱为第一名且稍微领先第二名时,实行紧策略
    # 2、当牌局的紧策略玩家出现跟注时,我们实行紧机制
    elif tightPolicy == 2:
        if PlayerRole[myseatrole] == 'EP':
            inFlag = (
                justifyMode(
                    mycards, pointMax=3, pointMin=3, plus=True, isuit=False)
                or justifyMode(
                    mycards, pointMax=14, pointMin=13, plus=False, isuit=False)
                or justifyMode(
                    mycards, pointMax=14, pointMin=10, plus=True, isuit=True)
                or justifyMode(
                    mycards, pointMax=14, pointMin=12, plus=False, isuit=False)
                or justifyMode(
                    mycards, pointMax=13, pointMin=12, plus=False,
                    isuit=False))
        elif PlayerRole[myseatrole] == 'MP':
            inFlag = (
                justifyMode(
                    mycards, pointMax=3, pointMin=3, plus=True, isuit=False)
                or justifyMode(
                    mycards, pointMax=14, pointMin=9, plus=True, isuit=True)
                or justifyMode(
                    mycards, pointMax=14, pointMin=12, plus=True, isuit=False)
                or justifyMode(
                    mycards, pointMax=13, pointMin=11, plus=True, isuit=False)
                or justifyMode(
                    mycards, pointMax=13, pointMin=12, plus=False,
                    isuit=False))
        elif PlayerRole[myseatrole] == 'LP':
            inFlag = (
                justifyMode(
                    mycards, pointMax=3, pointMin=3, plus=True, isuit=False)
                or justifyMode(
                    mycards, pointMax=9, pointMin=8, plus=True, isuit=True)
                or justifyMode(
                    mycards, pointMax=14, pointMin=9, plus=True, isuit=True)
                or justifyMode(
                    mycards, pointMax=14, pointMin=11, plus=True, isuit=False)
                or justifyMode(
                    mycards, pointMax=13, pointMin=12, plus=False,
                    isuit=False))
        elif PlayerRole[myseatrole] == 'BTN':
            inFlag = (
                justifyMode(
                    mycards, pointMax=3, pointMin=3, plus=True, isuit=False)
                or justifyMode(
                    mycards, pointMax=14, pointMin=9, plus=True, isuit=True)
                or justifyMode(
                    mycards, pointMax=10, pointMin=9, plus=True, isuit=True)
                or justifyMode(
                    mycards, pointMax=14, pointMin=11, plus=True, isuit=False))
        elif PlayerRole[myseatrole] == 'SB' or PlayerRole[myseatrole] == 'BB':
            inFlag = (
                justifyMode(
                    mycards, pointMax=3, pointMin=3, plus=True, isuit=False)
                or justifyMode(
                    mycards, pointMax=7, pointMin=6, plus=True, isuit=True)
                or justifyMode(
                    mycards, pointMax=14, pointMin=13, plus=False, isuit=False)
                or justifyMode(
                    mycards, pointMax=14, pointMin=11, plus=False, isuit=True)
                or justifyMode(
                    mycards, pointMax=13, pointMin=12, plus=False, isuit=True))
    # 使用最松机制
    elif tightPolicy == 1:
        inFlag = (
            justifyMode(
                mycards, pointMax=2, pointMin=2, plus=True, isuit=False)
            or justifyMode(
                mycards, pointMax=14, pointMin=5, plus=True, isuit=False)
            or justifyMode(
                mycards, pointMax=14, pointMin=2, plus=True, isuit=True)
            or justifyMode(
                mycards, pointMax=10, pointMin=9, plus=True, isuit=True)
            or justifyMode(
                mycards, pointMax=13, pointMin=12, plus=False, isuit=False)
            or justifyMode(
                mycards, pointMax=13, pointMin=11, plus=False, isuit=True)
            or justifyMode(
                mycards, pointMax=13, pointMin=10, plus=False, isuit=True)
            or justifyMode(
                mycards, pointMax=12, pointMin=9, plus=False, isuit=False))
    # 最后这一种,实行的机制最松
    # 22+/A8+/A2s+/76s+/109+/97s+/KJ/K10/K9s/Q10/Q9s/Q8s
    # 那么,哪些情况下实行最松机制呢?
    # 1、对于当自己的经济状况处于5-6名次时,同样执行最松机制,但是执行的方法为all_in
    # 2、自暴自弃:当自己的经济状况处于7-8名·,执行全all_in机制————投机方法
    elif tightPolicy == 0:
        inFlag = (
            justifyMode(
                mycards, pointMax=2, pointMin=2, plus=True, isuit=False)
            or justifyMode(
                mycards, pointMax=14, pointMin=8, plus=True, isuit=False)
            or justifyMode(
                mycards, pointMax=14, pointMin=4, plus=True, isuit=True) or
            justifyMode(mycards, pointMax=9, pointMin=8, plus=True, isuit=True)
            or justifyMode(
                mycards, pointMax=13, pointMin=11, plus=False, isuit=False)
            or justifyMode(
                mycards, pointMax=13, pointMin=10, plus=False, isuit=False)
            or justifyMode(
                mycards, pointMax=13, pointMin=9, plus=False, isuit=False)
            or justifyMode(
                mycards, pointMax=13, pointMin=8, plus=False, isuit=True)
            or justifyMode(
                mycards, pointMax=12, pointMin=10, plus=False, isuit=False)
            or justifyMode(
                mycards, pointMax=12, pointMin=9, plus=False, isuit=True)
            or justifyMode(
                mycards, pointMax=12, pointMin=8, plus=False, isuit=True))

    if inFlag:
        writeLog('\nHand Round: Join this set!!!')
        print '\nHand Round: Join this set!!!'
    else:
        writeLog('\nHand Round: Do not join this set!!!')
        print '\nHand Round: Do not join this set!!!'

    return inFlag
Example #21
0
import sys
from gameinfo import GameInfo
from connhandle import buildConnection, sendMsgToServer, listenServerInfo
from util import writeLog, fileClean, setFileName

if __name__ == '__main__':
    uip = sys.argv[1]
    uport = int(sys.argv[2])
    myip = sys.argv[3]
    myport = int(sys.argv[4])
    myid = sys.argv[5]
    myname = 'kobe'

    print '\ngameserver ip: ', uip
    print 'gameserver port: ', uport
    print 'my ip: ', myip
    print 'my port: ', myport
    print 'my id:', myid
    print 'my name: ', myname
    setFileName(myid)
    fileClean()

    gameinfo = GameInfo()
    gameinfo.myid = myid
    skt = buildConnection(myip, myport, uip, uport)
    # 发送注册信息
    regmsg = 'reg: %s %s\n' % (myid, myname)
    regSend = 'Send message: %s' % regmsg
    writeLog(regSend)
    sendMsgToServer(skt, regmsg)
    listenServerInfo(skt, gameinfo)
Example #22
0
def predictSVM():
	## loading the Votes
	log = "Step 1: loading votes..."
	writeLog(log)
	print log
	d = shelve.open('./models/Votes_Score_noscale')
	Votes = d['vote']
	d.close()

	## loading the testing data
	log = "Step 2: loading testing data..."
	writeLog(log)
	print log
	test_x, test_y = loadDigitTestData()

	## predict the testing data
	log = "Step 3: predicting the data..."
	writeLog(log)
	print log
	predict_y =  Votes.argmax(axis=1)
	m, n = shape(test_y)
	matchCount = 0
	for i in range(m):
		if predict_y[i] == test_y[i]:
			matchCount += 1
		else:
		# 	print i
		# 	print str(test_y[i]) + '\t' + str(predict_y[i]) + '\t' + str(Votes[i])
		# 	raw_input()
			writeLog(str(test_y[i]) + '\t' + str(predict_y[i]) + '\t' + str(Votes[i]))


	accuracy = float(matchCount) / m
	log =  "step 4: show the result..."
	writeLog(log)
	print log
	log = 'The classify accuracy is: %.3f%%' % (accuracy * 100)  
	writeLog(log)
	print log
Example #23
0
def buildSVM(k, l):
	'''
	Description: Build the SVM model for classes in Digit Data.

	@param:
		k: the SVM model for first class, 0<=k<=9
		l: the SVM model for second class, 0<=l<=9

	@procedure
		saves the SVM simplier model between class k and l.
	'''
	## Step 1: load data
	log = "Step 1: loading data..."
	writeLog(log)
	print log
	train_x, train_y, test_x, test_y = loadDigitData()

	# set_printoptions(threshold='nan')

	# extract k, l classes
	K_IndexTrain = nonzero(train_y.A == k)[0]
	L_IndexTrain = nonzero(train_y.A == l)[0]
	IndexTrain = concatenate((K_IndexTrain, L_IndexTrain))
	# random shuffle the array
	IndexTrain = random.permutation(IndexTrain)

	K_IndexTest  = nonzero(test_y.A == k)[0]
	L_IndexTest  = nonzero(test_y.A == l)[0]
	IndexTest  = concatenate((K_IndexTest, L_IndexTest))
	# random shuffle the array
	IndexTest = random.permutation(IndexTest)


	train_x = train_x[IndexTrain]
	train_y = train_y[IndexTrain]
	test_x = test_x[IndexTest]
	test_y = test_y[IndexTest]

	# sets label to -1 and +1
	train_y[train_y==k] = -1
	train_y[train_y==l] = 1
	test_y[test_y==k] = -1
	test_y[test_y==l] = 1

	# scales the features value between [-1~1]
	train_x = train_x/255.0*2 - 1
	test_x = test_x/255.0*2 - 1


	## Step 2: training data
	log = "Step 2: training data..."
	writeLog(log)
	print log

	C = 16
	toler = 0.001
	maxIter = 50
	svmClassifier = SVM.train(train_x, train_y.T, C, toler, maxIter, kernel = ('rbf', 13))
	# saves the model to disk for feature prediction
	svmClassifier.save('./models/svm_' + str(k) + '_' + str(l))
	# simpleSVM = SVMSimpleStruct(svmClassifier)
	# simpleSVM.save('./models/simple_svm_' + str(k_class))

	# # load the model
	# print 'Step 2: loading model..
	# d = shelve.open('./models/svm_' + str(k) + '_' + str(l))
	# svmClassifier = d['svm']
	# d.close()


	# # Step 3: testing data
	log = "Step 3: testing data..."
	writeLog(log)
	print log
	accuracy = SVM.test(svmClassifier, test_x, test_y)

	## Step 4: show the results 
	log = 'The classify accuracy is: %.3f%%' % (accuracy * 100)  
	print log
	writeLog(log)
Example #24
0
def decisionProcess(skt, gameinfo):
    writeLog('\nDecision Process...')
    writeLog('Game Number: ' + str(gameinfo.gameNum))
    writeLog('Hold Cards Count: ' + str(len(gameinfo.holdCards)))
    writeLog('Public Cards Count: ' + str(len(gameinfo.publicCards)))
    '''
	我们通过gameinfo中的公牌数量来判断当前局应该执行什么操作
	'''
    if len(gameinfo.publicCards) == 0:
        writeLog('Hold Cards Round: ')
        gameinfo.holdNum += 1
        msg = decision.handRoundDecision(gameinfo)
    elif len(gameinfo.publicCards) == 3:
        writeLog('Flop Cards Round: ')
        gameinfo.flopNum += 1
        msg = decision.flopRoundDecision(gameinfo)
    elif len(gameinfo.publicCards) == 4:
        writeLog('Turn Cards Round: ')
        gameinfo.turnNum += 1
        msg = decision.turnRoundDecision(gameinfo)
    elif len(gameinfo.publicCards) == 5:
        writeLog('River Cards Round: ')
        gameinfo.riverNum += 1
        msg = decision.riverRoundDecision(gameinfo)
    else:
        msg = 'fold \n'
    sendMsgToServer(skt, msg)
Example #25
0
def train(X, y, C, toler, maxIter, kernel):
	'''
	Description: Training entrance.

	@param:
		X: 		training features 
		y: 		training labels
		C:		slack variable
		toler:	termination condition for iteration
		maxIter: maxmium iteration
		kernel: kernel type {linear | rbf}

	@return
		svm: SVM struct
	'''

	startTime = time.time()

	svm = SVMStruct(mat(X), mat(y).T, C, toler, kernel)

	# Termination conditions:
	# 1) Maxmium iteration or 
	# 2) No more alpha need to be changed after go through all the data.
	# 	 which means, all the samples satisfy the KKT conditions.
	iteration = 0
	entireSet = True
	alphaPairChanged = 0
	while (iteration < maxIter) and ((alphaPairChanged > 0) or (entireSet)):
		alphaPairChanged = 0

		# update alphas through whole data set
		if entireSet:
			for i in range(svm.m):
				# print 'innerLoop: ' + str(i)
				alphaPairChanged += innerLoop(svm, i)
			log = "iter: %d on Entire Set | Alphas Pairs Changed: %d" % (iteration, alphaPairChanged)
			writeLog(log)
			print log
		# update alphas through all non-boundary data set
		else:
			nonBoundIndexes = nonzero((svm.alphas.A > 0) & (svm.alphas.A < C))[0] # [0] row index
			for i in nonBoundIndexes:
				# print 'NonBoundInnerLoop: ' + str(i)
				alphaPairChanged += innerLoop(svm, i)
			log = "iter: %d on Non-Bound Set | Alphas Pairs Changed: %d" % (iteration, alphaPairChanged)
			writeLog(log)
			print log
		iteration += 1

		# change update order: Entire Set <=> Non-boundary Set
		if entireSet:
			entireSet = False
		elif alphaPairChanged == 0:
			entireSet = True

	# training end
	log = 'SVM training costs %fs' % (time.time() - startTime)
	print log
	writeLog(log)

	return svm