Представление рук и распознавание комбинаций рук в игре в покер - PullRequest
0 голосов
/ 06 июня 2019

Я пытаюсь написать простую игру в покер.Мой код можно найти ниже.Мне было интересно, как я могу кодировать следующие комбинации: три в одном, прямой, фулл-хаус, и четыре в своем роде.Я не использую костюмы, и у меня есть только базовое понимание Python.Любой совет приветствуется.Спасибо.

Я пробовал несколько разных комбинаций, но я даже близко не подошел к его кодированию.

import random

print('The game ends if you fold')
print('11 = Jack')
print('12 = Queen')
print('13 = King')
print('14 = Ace')

#Choose a random card
cardOne = random.randint(1, 14)
cardTwo = random.randint(1, 14)

#Print the users hand
print('YOUR CARDS')
print(cardOne)
print(cardTwo)

oppCardOne = random.randint(1, 14)
oppCardTwo = random.randint(1, 14)

print("OPPONENT'S CARDS")
print(oppCardOne)
print(oppCardTwo)

def fold():
  print('Lol, ok u lose champ')
  exit()

swampOne = random.randint(1,14)
print('First Swamp Card:', swampOne)
print('What would you like to do?')
print('1: Keep Playing')
print('2: Fold')

decision = int(input())

if decision == 1:
  print("Damn, you've got some buzungas")

if decision == 2:
  fold()

swampTwo = random.randint(1,14)
print('Second Swamp Card:', swampTwo)
print('What would you like to do?')
print('1: Keep Playing')
print('2: Fold')

decision = int(input())

if decision == 1:
  print("Damn, you've got some buzungas")

if decision == 2:
  fold()

swampThree = random.randint(1,14)
print('Third Swamp Card:', swampThree)
print('What would you like to do?')
print('1: Keep Playing')
print('2: Fold')

decision = int(input())

if decision == 1:
  print("Damn, you've got some buzungas")

if decision == 2:
  fold()

fourthStreet = random.randint(1, 14)
print('fourth Street:', fourthStreet)
print('What would you like to do?')
print('1: Keep Playing')
print('2: Fold')

decision = int(input())

if decision == 1:
  print("Damn, you've got some buzungas")

if decision == 2:
  fold()


river = random.randint(1, 14)
print('River:', river)
print('What would you like to do?')
print('1: Keep Playing')
print('2: Fold')

decision = int(input())

if decision == 1:
  print('Good Luck')

if decision == 2:
  fold()


#User combos



#Highest compile
if cardOne > oppCardOne or oppCardTwo:
  combo = 1
if cardTwo > oppCardOne or oppCardTwo:
  combo = 1
#Pair
if cardOne or cardTwo == swampOne or swampTwo or swampThree or fourthStreet or river:
  combo = 2
#Two pairs
if cardOne and cardTwo == swampOne or swampTwo or swampThree or fourthStreet or river:
  combo = 3
if cardOne == swampOne and swampTwo or swampOne and swampThree or swampOne and fourthStreet or swampOne and river:
  combo = 3
if cardOne == (swampTwo and swampOne) or (swampTwo and swampThree) or (swampTwo and fourthStreet) or (swampTwo and river):
  combo = 3
if cardOne == (swampThree and swampOne) or (swampThree and swampTwo) or (swampThree and fourthStreet) or (swampThree and river):
  combo = 3
if cardOne == (fourthStreet and swampOne) or (fourthStreet and swampTwo) or (fourthStreet and swampThree) or (fourthStreet and river):
  combo = 3
if cardOne == (river and swampOne) or (river and swampTwo) or (river and swampThree) or (river and fourthStreet):
  combo = 3
#Two pars card two
if cardTwo == swampOne and swampTwo or swampOne and swampThree or swampOne and fourthStreet or swampOne and river:
  combo = 3
if cardTwo == (swampTwo and swampOne) or (swampTwo and swampThree) or (swampTwo and fourthStreet) or (swampTwo and river):
  combo = 3
if cardTwo == (swampThree and swampOne) or (swampThree and swampTwo) or (swampThree and fourthStreet) or (swampThree and river):
  combo = 3
if cardTwo == (fourthStreet and swampOne) or (fourthStreet and swampTwo) or (fourthStreet and swampThree) or (fourthStreet and river):
  combo = 3
if cardTwo == (river and swampOne) or (river and swampTwo) or (river and swampThree) or (river and fourthStreet):
  combo = 3
#Hand pairs
if cardOne == cardTwo:
  combo = 3
#Three of a kind









#Opponent Combos
if oppCardOne > cardOne or cardTwo:
  oppCombo = 1
if oppCardTwo > cardOne or cardTwo:
  oppCombo = 1
if oppCardOne or oppCardTwo == swampOne or swampTwo or swampThree or fourthStreet or river:
  oppCombo = 2
if oppCardOne and oppCardTwo == swampOne or swampTwo or swampThree or fourthStreet or river:
  oppCombo = 3






#Determine who wins
if combo > oppCombo:
  print('YOU WIN YA SCHMUCK')
  exit()
elif oppCombo > combo:
  print('HA, YOU LOSE')
  exit()
else:
  print('TIE')
  exit()




print(combo)

Я не получаю никаких сообщений об ошибках, поскольку на самом деле я не получилначал кодировать эти комбинации.

Ответы [ 2 ]

0 голосов
/ 06 июня 2019

Я написал несколько кодов для покера, некоторые из которых были для класса программирования, который я преподавал.Одна вещь, которую я узнал, состоит в том, что, не обращая внимания на ответ @ mneedham, лучше всего представлять карту как число от 0 до 51. Это имеет много преимуществ с точки зрения того, как вы обрабатываете 5-карточную руку.для конкретных комбинаций.

Если две карты, представленные в виде числа от 0 до 51, совпадают по рангу, то их число, измененное на 13, будет одинаковым.Таким образом, вы можете сделать что-то подобное, чтобы оценить руки с соответствующим рангом:

def evaluate_hand(cards):
    # build a list of lists for collecting cards of the same rank
    ranks = []
    for i in range(13):
        ranks.append([])

    # put each card in the appropriate rank list
    for i in cards:
        ranks[i % 13].append(i)

    # Sort our rank list descending by sublist length
    ranks = sorted(ranks, key=len, reverse=True)

    # Show what we end up with
    print(ranks)

    # Now show what we've got
    if len(ranks[0]) == 4:
        print("Four of a kind")
    elif len(ranks[0]) == 3 and len(ranks[1]) == 2:
        print("Full house")
    elif len(ranks[0]) == 3:
        print("Three of a kind")
    elif len(ranks[0]) == 2 and len(ranks[1]) == 2:
        print("Two pair")
    elif len(ranks[0]) == 2:
        print("Pair")
    else:
        print("Nada")

evaluate_hand([31, 4, 23, 17, 30])
evaluate_hand([36, 4, 23, 17, 30])
evaluate_hand([36, 4, 23, 19, 30])
evaluate_hand([4, 5, 6, 7, 8])

Результат:

[[4, 17, 30], [31], [23], [], [], [], [], [], [], [], [], [], []]
Three of a kind
[[4, 17, 30], [36, 23], [], [], [], [], [], [], [], [], [], [], []]
Full house
[[4, 30], [36, 23], [19], [], [], [], [], [], [], [], [], [], []]
Two pair
[[4], [5], [6], [7], [8], [], [], [], [], [], [], [], []]
Nada

Чтобы распознать флеш, проверьте, все ли 5 ​​значений карт, разделенные на 13, даюттот же номер.Чтобы распознать стрит, создайте список значений каждой карты, модифицированных 13 (создайте список рангов), отсортируйте их, а затем убедитесь, что полученные числа являются последовательными.Если оба эти теста пройдены, у вас стрит-флеш.Я оставлю вам код этих чеков.

Получить костюм на любое число очень просто:

def show_suit(card):
    print(['Diamond', 'Heart', 'Spade', 'Club'][int(card / 13)])

Так же и получить названный ранг:

def show_rank(card):
    rank_names = { 0: 'Ace', 10: 'Jack', 11: 'Queen', 12: 'King'}
    rank = card % 13
    print(rank_names[rank] if rank in rank_names else rank)
0 голосов
/ 06 июня 2019

Может оказаться полезным определить карты как питон classes. Таким образом, вы можете упорядочить детали карты (масть, стоимость) и составить «руку» из пяти объектов карты. Тогда вы можете делать простые if операторы для каждой руки.

...