2013-05-17 3 views
0

비록 내가 포커 게임을 만들고있는 것은 아니지만, 게임의 목적은 가장 높은 포커 핸드 우승자입니다. 내 게임에는 4 명의 플레이어가 있습니다. 나는 게임 보드와 플레이어가 게임 보드의 기존 카드를 들고 손에 카드가 보이게 할 수있는 기능을 구현할 수있었습니다. 이 게임은 더 이상 카드가 없거나 플레이어가 분명히 가장 높은 포커 핸드를 가지고 있고 더 큰 핸드를 얻을 기회가 없을 때 끝납니다 (이것은 모든 카드가 앞면이 보이기 때문에 분명합니다).플레이어의 손과 게임 판을 기존 포커 핸드 평가자에게 어떻게 연결합니까?

ORIGINAL : 내 요구에 대한 https://github.com/aliang/pokerhand-eval

더 나은 솔루션 (I 현재이를 구현하려는) :

나는 내 게임에 구현하려는 앨빈 리앙하여이 파이썬 포커 손 평가자을 발견 (에서

import json 
import gameboard 
from django.shortcuts import HttpResponse, render, redirect, Http404 
from django.views.decorators.csrf import csrf_exempt 
from django.contrib.auth.decorators import login_required 

cardDict = { 
    0: "ace of clubs", 
    1: "two of clubs", 
    2: "three of clubs", 
    3: "four of clubs", 
    4: "five of clubs", 
    5: "six of clubs", 
    6: "seven of clubs", 
    7: "eight of clubs", 
    8: "nine of clubs", 
    9: "ten of clubs", 
    10: "jack of clubs", 
    11: "queen of clubs", 
    12: "king of clubs", 
    13: "ace of diamonds", 
    14: "two of diamonds", 
    15: "three of diamonds", 
    16: "four of diamonds", 
    17: "five of diamonds", 
    18: "six of diamonds", 
    19: "seven of diamonds", 
    20: "eight of diamonds", 
    21: "nine of diamonds", 
    22: "ten of diamonds", 
    23: "jack of diamonds", 
    24: "queen of diamonds", 
    25: "king of diamonds", 
    26: "ace of hearts", 
    27: "two of hearts", 
    28: "three of hearts", 
    29: "four of hearts", 
    30: "five of hearts", 
    31: "six of hearts", 
    32: "seven of hearts", 
    33: "eight of hearts", 
    34: "nine of hearts", 
    35: "ten of hearts", 
    36: "jack of hearts", 
    37: "queen of hearts", 
    38: "king of hearts", 
    39: "ace of spades", 
    40: "two of spades", 
    41: "three of spades", 
    42: "four of spades", 
    43: "five of spades", 
    44: "six of spades", 
    45: "seven of spades", 
    46: "eight of spades", 
    47: "nine of spades", 
    48: "ten of spades", 
    49: "jack of spades", 
    50: "queen of spades", 
    51: "king of spades", 
    52: "black joker", 
    53: "red joker", 
    54: "back" 
} 


@login_required 
def createGameRoom(request): 
    userName = request.user.username 
    board = gameboard.GameBoard() 
    points = [0, 0, 0, 0] 
    room = request.POST['gameRoom'] 
    roomDir = 'Game/GameRooms/game'+room+'.json' 
    gameFile = open(roomDir) 
    gameState = json.load(gameFile) 
    gameFile.close() 
    if gameState['p1Name'] == userName: 
     gameState['board'] = board.board 
     gameState['playerNum'] = 4 
     gameState['turn'] = 1 
     gameState['rounds'] = 0 
     gameState['timeLimit'] = 30 
     gameState['points'] = points 
     gameState['player1'] = [0, 0] 
     gameState['player2'] = [0, 5] 
     gameState['player3'] = [5, 5] 
     gameState['player4'] = [5, 0] 
     gameState['player1Hand'] = [] 
     gameState['player2Hand'] = [] 
     gameState['player3Hand'] = [] 
     gameState['player4Hand'] = [] 
     with open(roomDir, 'w+') as jFile: 
      json.dump(gameState, jFile) 
      jFile.close() 
    return HttpResponse(json.dumps(gameState), content_type="application/json") 

@login_required 
def resetRoom(request): 
    if request.user.is_staff: 
     board = gameboard.GameBoard() 
     points = [0, 0, 0, 0] 
     room = request.GET['room'] 
     roomDir = 'Game/GameRooms/game'+room+'.json' 
     with open(roomDir, 'w+') as jFile: 
      gameState = {'board': board.board, 
         'playerNum': 4, 
         'playerCount': 0, 
         'turn': 1, 
         'rounds': 0, 
         'timeLimit': 30, 
         'p1Name': '', 
         'p2Name': '', 
         'p3Name': '', 
         'p4Name': '', 
         'points': points, 
         'player1': [0, 0], 
         'player2': [0, 5], 
         'player3': [5, 5], 
         'player4': [5, 0], 
         'player1Hand': [], 
         'player2Hand': [], 
         'player3Hand': [], 
         'player4Hand': []} 
      json.dump(gameState, jFile) 
      jFile.close() 
     return redirect(showRooms) 
    else: 
     return HttpResponse('Error') 

@login_required 
def joinGameRoom(request): 
    room = request.GET["room"] 
    roomDir = 'Game/GameRooms/game' + room + ".json" 
    gameFile = open(roomDir) 
    gameState = json.load(gameFile) 
    gameFile.close() 
    playerNum = 0 
    print "joined room:" + str(request.user.username) 
    if gameState['playerCount'] >= 4: 
     return HttpResponse("Room is full") 
    if gameState['p1Name'] == '': 
     gameState['p1Name'] = request.user.username 
     playerNum = 1 
    elif gameState['p2Name'] == '': 
     gameState['p2Name'] = request.user.username 
     playerNum = 2 
    elif gameState['p3Name'] == '': 
     gameState['p3Name'] = request.user.username 
     playerNum = 3 
    elif gameState['p4Name'] == '': 
     gameState['p4Name'] = request.user.username 
     playerNum = 4 
    gameState['playerCount'] += 1 
    with open(roomDir, 'w+') as jFile: 
     json.dump(gameState, jFile) 
     jFile.close() 
    context = {'roomNum': room, 'playerNum': playerNum} 
    return render(request, "Games/board.html", context) 


@login_required 
def startRound(request): 
    room = request.POST['gameRoom'] 
    gameDir = 'Game/GameRooms/game'+room+'.json' 
    gameFile = open(gameDir) 
    gameState = json.load(gameFile) 
    board = gameboard.GameBoard() 
    board.start() 
    gameState['board'] = board.board 
    gameState['rounds'] += 1 
    gameState['player1'] = [0, 0] 
    gameState['player1Hand'] = [] 
    gameState['player2'] = [0, 5] 
    gameState['player2Hand'] = [] 
    gameState['player3'] = [5, 5] 
    gameState['player3Hand'] = [] 
    gameState['player4'] = [5, 0] 
    gameState['player4Hand'] = [] 
    gameFile.close() 
    with open(gameDir, 'w+') as jFile: 
     json.dump(gameState, jFile) 
     jFile.close() 
    return HttpResponse(json.dumps(gameState), content_type="application/json") 


@login_required 
@csrf_exempt 
def makeMove(request): 
    room = request.POST['roomNum'] 
    gameDir = 'Game/GameRooms/game'+room+'.json' 
    row = int(request.POST['row']) 
    column = int(request.POST['column']) 
    playerNum = request.POST['playerNum'] 
    gameFile = open(gameDir) 
    gameState = json.load(gameFile) 
    print gameState 
    gameFile.close() 
    if int(playerNum) == gameState['turn']: 
     print 'making move: ' + playerNum + " in room " + room 
     player = 'player'+playerNum 
     gameState[player] = [row, column] 
     card = gameState['board'][row][column] 
     if card != 54: 
      gameState[player + 'Hand'].append(card) 
      gameState['board'][row][column] = 54 
     gameState['turn'] += 1 
     if gameState['turn'] > 4: 
      gameState['turn'] = 1 
     with open(gameDir, 'w+') as jfile: 
      json.dump(gameState, jfile) 
    return HttpResponse(json.dumps(gameState), content_type="application/json") 


def checkOccupied(gameState, row, column): 
    isOccupied = False 
    gameFile = open('Game/GameRooms/game.json') 
    gameState = json.load(gameFile) 
    if gameState['player1'] == [row, column]: 
     isOccupied = True 
    if gameState['player2'] == [row, column]: 
     isOccupied = True 
    if gameState['player3'] == [row, column]: 
     isOccupied = True 
    if gameState['player4'] == [row, column]: 
     isOccupied = True 
    gameFile.close() 
    return isOccupied 

@login_required 
def getValidMoves(request): 
    gameFile = open('Game/GameRooms/game.json') 
    gameState = json.load(gameFile) 
    player = '' 
    if gameState['turn'] == 1: 
     player = 'player1' 
    elif gameState['turn'] == 2: 
     player = 'player2' 
    elif gameState['turn'] == 3: 
     player = 'player3' 
    elif gameState['turn'] == 4: 
     player = 'player4' 
    row = gameState[player][0] 
    column = gameState[player][1] 
    tempRow = row 
    tempCol = column 
    validMoves = [] 
    while (tempCol + 1) < 6: 
     tempCol += 1 
     occupied = checkOccupied(gameState, tempRow, tempCol) 
     if not occupied: 
      validMoves.append([tempRow, tempCol]) 
     else: 
      break 
    tempCol = column 
    while (tempCol - 1) >= 0: 
      tempCol -= 1 
      occupied = checkOccupied(gameState, tempRow, tempCol) 
      if not occupied: 
       validMoves.append((tempRow, tempCol)) 
      else: 
       break 
    tempCol = column 
    while (tempRow + 1) < 6: 
      tempRow += 1 
      occupied = checkOccupied(gameState, tempRow, tempCol) 
      if not occupied: 
       validMoves.append((tempRow, tempCol)) 
      else: 
       break 
    tempRow = row 
    while (tempRow - 1) >= 0: 
      tempRow -= 1 
      occupied = checkOccupied(gameState, tempRow, tempCol) 
      if not occupied: 
       validMoves.append((tempRow, tempCol)) 
      else: 
       break 
    return HttpResponse(json.dumps(validMoves), content_type="application/json") 

@login_required 
def getBoard(request): 
    if request.method == 'POST': 
     room = request.POST['gameRoom'] 
     gameDir = 'Game/GameRooms/game'+room+'.json' 
     gameFile = open(gameDir) 
     gameState = json.load(gameFile) 
     return HttpResponse(json.dumps(gameState), content_type="application/json") 


@login_required 
def showRooms(request): 
    context = {'room_list':range(1,9)} 
    return render(request, "Games/rooms.html", context) 
: 피터 노르 빅의 csc212의 Udacity의 과정) 여기

import itertools 

## Deck adds two cards: 
## '?B': black joker; can be used as any black card (S or C) 
## '?R': red joker; can be used as any red card (H or D) 

allranks = '23456789TJQKA' 
redcards = [r+s for r in allranks for s in 'DH'] 
blackcards = [r+s for r in allranks for s in 'SC'] 

def best_wild_hand(hand): 
"Try all values for jokers in all 5-card selections." 
hands = set(best_hand(h) 
      for h in itertools.product(*map(replacements, hand))) 
return max(hands, key=hand_rank) 

def replacements(card): 
"""Return a list of the possible replacements for a card. 
There will be more than 1 only for wild cards.""" 
if card == '?B': return blackcards 
elif card == '?R': return redcards 
else: return [card] 

def best_hand(hand): 
"From a 7-card hand, return the best 5 card hand." 
return max(itertools.combinations(hand, 5), key=hand_rank) 

def test_best_wild_hand(): 
assert (sorted(best_wild_hand("6C 7C 8C 9C TC 5C ?B".split())) 
     == ['7C', '8C', '9C', 'JC', 'TC']) 
assert (sorted(best_wild_hand("TD TC 5H 5C 7C ?R ?B".split())) 
     == ['7C', 'TC', 'TD', 'TH', 'TS']) 
assert (sorted(best_wild_hand("JD TC TH 7C 7D 7S 7H".split())) 
     == ['7C', '7D', '7H', '7S', 'JD']) 
return 'test_best_wild_hand passes' 



def hand_rank(hand): 
"Return a value indicating the ranking of a hand." 
ranks = card_ranks(hand) 
if straight(ranks) and flush(hand): 
    return (8, max(ranks)) 
elif kind(4, ranks): 
    return (7, kind(4, ranks), kind(1, ranks)) 
elif kind(3, ranks) and kind(2, ranks): 
    return (6, kind(3, ranks), kind(2, ranks)) 
elif flush(hand): 
    return (5, ranks) 
elif straight(ranks): 
    return (4, max(ranks)) 
elif kind(3, ranks): 
    return (3, kind(3, ranks), ranks) 
elif two_pair(ranks): 
    return (2, two_pair(ranks), ranks) 
elif kind(2, ranks): 
    return (1, kind(2, ranks), ranks) 
else: 
    return (0, ranks) 

def card_ranks(hand): 
"Return a list of the ranks, sorted with higher first." 
ranks = ['--23456789TJQKA'.index(r) for r, s in hand] 
ranks.sort(reverse = True) 
return [5, 4, 3, 2, 1] if (ranks == [14, 5, 4, 3, 2]) else ranks 

def flush(hand): 
"Return True if all the cards have the same suit." 
suits = [s for r,s in hand] 
return len(set(suits)) == 1 

def straight(ranks): 
"""Return True if the ordered 
ranks form a 5-card straight.""" 
return (max(ranks)-min(ranks) == 4) and len(set(ranks)) == 5 

def kind(n, ranks): 
"""Return the first rank that this hand has 
exactly n-of-a-kind of. Return None if there 
is no n-of-a-kind in the hand.""" 
for r in ranks: 
    if ranks.count(r) == n: return r 
return None 

def two_pair(ranks): 
"""If there are two pair here, return the two 
ranks of the two pairs, else None.""" 
pair = kind(2, ranks) 
lowpair = kind(2, list(reversed(ranks))) 
if pair and lowpair != pair: 
    return (pair, lowpair) 
else: 
    return None 

print test_best_wild_hand() 

는 내가 가지고있는 GamerManager 코드입니다

여기에 기본적으로, 내가 현재 가지고있는로이 평가자를 연결하는 방법을 완전히 확실하지 않다 내 플레이어 클래스

class player: 
    def __init__(self, playerNum): 
     self.name = "" 
     self.playerNum = playerNum 
     self.row = 0 
     self.column = 0 
     self.hand = [] 

    def toHand(self, card): 
     self.hand.append(card) 

    def setPiece(self, row, column): 
     self.row = row 
     self.column = column 

    def clearHand(self): 
     self.hand = [] 

입니다. 플레이어의 변화하는 손과 게임 판을 기존 포커 핸드 평가자에게 어떻게 연결합니까?

어떤 아이디어라도 도움이됩니다 (의사 코드 또는 파이썬).

답변

0

당신이해야 할 일은 카드 표현을 자신의 것으로 변환하는 것입니다. 당신은 하나의 숫자 0..51을 사용합니다. 그는 서로 다른 주문으로 양복을 입은 물건을 사용합니다. int 값 (n)을 자신의 Card 클래스로 변환하려면 다음을 시도하십시오.

s = 4 - (n // 13); 

r = n % 13; 
if r == 0: 
    r = 14 
else: 
    r += 1 

c = Card(r, s) 

그런 다음 손은 단지 Card 객체 목록입니다.

FWIW, 저는 파이썬 바인딩을 사용하는 C로 훨씬 더 빠른 공개 도메인 포커 핸드 평가기를 받았습니다. 순수한 파이썬이 아니기 때문에 공유 라이브러리를 파이썬 모듈뿐만 아니라 함께 드래그해야 할 것입니다.하지만 파이썬 모듈이 제대로 작동한다면 그것을 가르쳐 줄 것입니다.

+0

흠. 그래서 모든 것을 합치려면 라이브러리를 가져 와서 양복이있는 객체를 사용하도록 조정합니다. 그런 다음 카드 객체 목록을 가져올 것입니다. 어떤 것이 구현입니까? 나는보기에 흥미가있을 것입니다. 어떻게 당신을 구현합니까? 정말 고맙습니다! @LeeDanielCrocker – Kaylie

+0

모든 종류의 카드 게임과 시뮬레이션에 유용한 베타 테스터를 내 라이브러리에 갖고 싶습니다. 안타깝게도 방금 내 코드를 주요 리팩터링으로 시작 했으므로 이제 끝내고 GitHub에 넣을 때까지 깨끗한 코드베이스로 안내 할 수는 없습니다. 하지만 그것을 시험해보고 싶다면 몇 가지 세부 정보 (예 : 사용중인 OS, Python 버전 등)를 전자 메일로 보내면 사용할 수있는 것을 해킹 할 수 있습니다. –

관련 문제