Форум программистов, компьютерный форум, киберфорум
Python для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.62/34: Рейтинг темы: голосов - 34, средняя оценка - 4.62
1 / 1 / 0
Регистрация: 03.04.2015
Сообщений: 128

Перекод с Unreal Engine 4 на Python

12.01.2020, 12:48. Показов 7122. Ответов 13
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуйте! Я написал на Unreal Engine 4 симулятор покера Texas Hold'em для исследований. Писал около двух недель, но получилось. Проблема возникла в скорости расчётов раздач. У меня на 10000 раздач уходит пять минут, а это очень долго. Я решился спросить, может ли кто-нибудь добрый помочь мне написать тот же покер только на Python'е? Я не знаю, сколько времени это может занять, но почему-то кажется, что часа три, если писать будет мастер. В качестве доказательств могу скинуть свой покер в ЛС, кто попросит. Весит он 300 мегабайт.

https://ibb.co/vJDvzwW
https://ibb.co/MgWGM4x
https://ibb.co/RTF9BpB
https://ibb.co/9cMYPcg
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
12.01.2020, 12:48
Ответы с готовыми решениями:

Unreal Engine 4
Всем привет. У кого есть ссылка на готовый оффлайн или онлайн инсталлер Unreal Engine 4? Сойдет всё, только не торрент, у меня с...

Программист Unreal Engine 4 C++
Уровень зарплаты от 100 000 до 150 000 руб. на руки Город Москва Обязанности: Написание кода в соответствии с поставленными...

Работа на Unreal Engine 4
Доброго времени суток. Мы занимаемся разработкой модификации Mafia II Extended Edition и переводим её на движок Unreal Engine 4. В связи с...

13
Эксперт Python
1356 / 653 / 207
Регистрация: 23.03.2014
Сообщений: 3,057
12.01.2020, 12:54
yellyex, Вам очень хочется похвастать?
0
1 / 1 / 0
Регистрация: 03.04.2015
Сообщений: 128
12.01.2020, 12:58  [ТС]
Dax, да Вы что! Нет, я просто правда хотел бы перейти на питон из-за скорости вычислений. Я пытался писать на нём, но не смог и решил остаться в UE4. Мне правда нужна помощь.

Добавлено через 1 минуту
У меня нет денег, так бы заплатил за работу. Я понимал, что просто так мне никто-ничего не напишет, поэтому решил доказать, что я правда потрудился сам, чтобы, если кто согласился мне помочь, то не бездельнику.
0
Эксперт Python
1356 / 653 / 207
Регистрация: 23.03.2014
Сообщений: 3,057
12.01.2020, 13:01
yellyex, да я верю, верю, Вам, как я понимаю, нужен PyQT для обеспечения интерфейса, python - для логики.
Я бы на Вашем месте, начал танцевать от именно той печки)
0
1 / 1 / 0
Регистрация: 03.04.2015
Сообщений: 128
12.01.2020, 13:02  [ТС]
Dax, Нет, сойдёт и стандартная консоль. QT интерфейс не нужен.
0
Эксперт Python
1356 / 653 / 207
Регистрация: 23.03.2014
Сообщений: 3,057
12.01.2020, 13:02
Unreal Engine 4 , к сожалению, не владею, так бы, я думаю, перевести получилось быстро.
0
1 / 1 / 0
Регистрация: 03.04.2015
Сообщений: 128
12.01.2020, 13:06  [ТС]
UE4 на С++ работает. Просто дело даже не в перекоде, а в написании покера с нуля на питоне, так как мой код в UE4 совсем не оптимизированный. Я нашёл несколько примеров покера на питоне, но не могу разобраться, чтобы они мне подходили.
Пример 1:
Кликните здесь для просмотра всего текста
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import random
 
 
class Card(object):
    RANKS = (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
 
    SUITS = ('C', 'D', 'H', 'S')
 
    # constructor
    def __init__(self, rank=12, suit='S'):
        if (rank in Card.RANKS):
            self.rank = rank
        else:
            self.rank = 12
 
        if (suit in Card.SUITS):
            self.suit = suit
        else:
            self.suit = 'S'
 
    # string representation of a Card object
    def __str__(self):
        if (self.rank == 14):
            rank = 'A'
        elif (self.rank == 13):
            rank = 'K'
        elif (self.rank == 12):
            rank = 'Q'
        elif (self.rank == 11):
            rank = 'J'
        else:
            rank = str(self.rank)
        return rank + self.suit
 
    # equality tests
    def __eq__(self, other):
        return self.rank == other.rank
 
    def __ne__(self, other):
        return self.rank != other.rank
 
    def __lt__(self, other):
        return self.rank < other.rank
 
    def __le__(self, other):
        return self.rank <= other.rank
 
    def __gt__(self, other):
        return self.rank > other.rank
 
    def __ge__(self, other):
        return self.rank >= other.rank
 
 
class Deck(object):
    # constructor
    def __init__(self, n=1):
        self.deck = []
        for i in range(n):
            for suit in Card.SUITS:
                for rank in Card.RANKS:
                    card = Card(rank, suit)
                    self.deck.append(card)
 
    # shuffle the deck
    def shuffle(self):
        random.shuffle(self.deck)
 
    # deal a card
    def deal(self):
        if (len(self.deck) == 0):
            return None
        else:
            return self.deck.pop(0)
 
 
class Poker(object):
    def __init__(self, num_players=2, num_cards=5):
        self.deck = Deck()
        self.deck.shuffle()
        self.all_hands = []
        self.numCards_in_Hand = num_cards
 
        # deal all the hands
        for i in range(num_players):
            hand = []
            for j in range(self.numCards_in_Hand): #self.numCards_in_Hand
                #while self.numCards_in_Hand < 6:
                #for j in range(1):
                card = self.deck.deal()
                hand.append(card)       #self.deck.deal() switch for "card"
                #print(card)
                #count += 1
            self.all_hands.append(hand)
 
    # simulates the play of the game
    def play(self):
        # sort the hands of each player and print
        for i in range(len(self.all_hands)):
            sorted_hand = sorted(self.all_hands[i], reverse=True)
            self.all_hands[i] = sorted_hand
            hand_str = ''
            for card in sorted_hand:
                hand_str = hand_str + str(card) + ' '
            print('Player ' + str(i + 1) + ' : ' + hand_str)
 
        # determine the type of each hand and print
        points_hand = []  # create a list to store points for each hand
 
        # determine winner and print
 
    # determine if a hand is a royal flush
    # takes as argument a list of 5 Card objects
    # returns a number (points) for that hand
    def is_royal(self, hand):
        same_suit = True          #checking for same suit
        for i in range(len(hand) - 1):
            same_suit = same_suit and (hand[i].suit == hand[i + 1].suit)
 
        if (not same_suit):
            return 0
 
        rank_order = True   #checking if king, queen, jack, ace
        for i in range(len(hand)):
            rank_order = rank_order and (hand[i].rank == 14 - i)
 
        if (not rank_order):
            return 0
 
        points = 10 * 15 ** 5 + (hand[0].rank) * 15 ** 4 + (hand[1].rank) * 15 ** 3
        points = points + (hand[2].rank) * 15 ** 2 + (hand[3].rank) * 15 ** 1
        points = points + (hand[4].rank)
 
        return points
 
 
    def is_straight_flush (self, hand):
        same_suit = True
        for i in range(len(hand) - 1):
            same_suit = same_suit and (hand[i].suit == hand[i + 1].suit)
 
        if (not same_suit):
            return 0
 
        rank_order = True  # checking if the 5 cards in numerical sequence but of the same suit.
        for i in range(len(hand) - 1):
            rank_order = rank_order and (hand[i + 1].rank == hand[i].rank + 1)
 
        if (not rank_order):
            return 0
 
        points = 10 * 15 ** 5 + (hand[0].rank) * 15 ** 4 + (hand[1].rank) * 15 ** 3
        points = points + (hand[2].rank) * 15 ** 2 + (hand[3].rank) * 15 ** 1
        points = points + (hand[4].rank)
 
        return points
 
    '''
    def is_four_kind (self, hand):
      ...
  
    def is_full_house (self, hand):
      ...
  
    def is_flush (self, hand):
      ...
  
    def is_straight (self, hand):
      ...
  
    def is_three_kind (self, hand):
      ...
  
    def is_two_pair (self, hand):
      ...
  
    '''
 
    # determine if a hand is one pair
    # takes as argument a list of 5 Card objects
    # returns a number (points) for that hand
    def is_one_pair(self, hand):
        one_pair = False
        for i in range(len(hand) - 1):
            if (hand[i].rank == hand[i + 1].rank):
                one_pair = True
                break
        if (not one_pair):
            return 0
 
        points = 2 * 15 ** 5 + (hand[0].rank) * 15 ** 4 + (hand[1].rank) * 15 ** 3
        points = points + (hand[2].rank) * 15 ** 2 + (hand[3].rank) * 15 ** 1
        points = points + (hand[4].rank)
 
        return points
 
    '''
    def is_high_card (self, hand):
      ...
  
    '''
 
 
def main():
    # prompt the user to enter the number of players
    num_players = int(input('Enter number of players: '))
    while ((num_players < 2) or (num_players > 6)):
        num_players = int(input('Enter number of players: '))
 
    # create the Poker object
    game = Poker(num_players)
 
    # play the game - poker
    game.play()
 
    score = Poker
 
# do not remove this line above main()
if __name__ == '__main__':
    main()

Пример2:
Кликните здесь для просмотра всего текста
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import random
 
class Card( object ):
  def __init__(self, name, value, suit, symbol):
    self.value = value
    self.suit = suit
    self.name = name
    self.symbol = symbol
    self.showing = False
 
  def __repr__(self):
    if self.showing:
      return self.symbol
    else:
      return "Card"
 
class Deck(object):
  def shuffle(self, times=1 ):
    random.shuffle(self.cards)
    print("Deck Shuffled")
 
  def deal(self):
    return self.cards.pop(0)
 
class StandardDeck(Deck):
  def __init__(self):
    self.cards = []
    suits = {"Hearts":"♡", "Spades":"♠", "Diamonds":"♢", "Clubs":"♣"}
    values = {"Two":2,
              "Three":3,
              "Four":4,
              "Five":5,
              "Six":6,
              "Seven":7,
              "Eight":8,
              "Nine":9,
              "Ten":10,
              "Jack":11,
              "Queen":12,
              "King":13,
              "Ace":14 }
 
    for name in values:
      for suit in suits:
        symbolIcon = suits[suit]
        if values[name] < 11:
          symbol = str(values[name])+symbolIcon
        else:
          symbol = name[0]+symbolIcon
        self.cards.append( Card(name, values[name], suit, symbol) )
 
  def __repr__(self):
    return "Standard deck of cards:{0} remaining".format(len(self.cards))
 
class Player(object):
  def __init__(self):
    self.cards = []
 
  def cardCount(self):
    return len(self.cards)
 
  def addCard(self, card):
    self.cards.append(card)
 
 
class PokerScorer(object):
  def __init__(self, cards):
    # Number of cards
    if not len(cards) == 5:
      return "Error: Wrong number of cards"
 
    self.cards = cards
 
  def flush(self):
    suits = [card.suit for card in self.cards]
    if len( set(suits) ) == 1:
      return True
    return False
 
  def straight(self):
    values = [card.value for card in self.cards]
    values.sort()
 
    if not len( set(values)) == 5:
      return False 
 
    if values[4] == 14 and values[0] == 2 and values[1] == 3 and values[2] == 4 and values[3] == 5:
      return 5
 
    else:
      if not values[0] + 1 == values[1]: return False 
      if not values[1] + 1 == values[2]: return False
      if not values[2] + 1 == values[3]: return False
      if not values[3] + 1 == values[4]: return False
 
    return values[4]
 
  def highCard(self):
    values = [card.value for card in self.cards]
    highCard = None
    for card in self.cards:
      if highCard is None:
        highCard = card
      elif highCard.value < card.value: 
        highCard=card
 
    return highCard
 
  def highestCount(self):
    count = 0
    values = [card.value for card in self.cards]
    for value in values:
      if values.count(value) > count:
        count = values.count(value)
 
    return count
 
  def pairs(self):
    pairs = []
    values = [card.value for card in self.cards]
    for value in values:
      if values.count(value) == 2 and value not in pairs:
        pairs.append(value)
 
    return pairs
        
  def fourKind(self):
    values = [card.value for card in self.cards]
    for value in values:
      if values.count(value) == 4:
        return True
 
  def fullHouse(self):
    two = False
    three = False
    
    values = [card.value for card in self.cards]
    if values.count(values) == 2:
      two = True
    elif values.count(values) == 3:
      three = True
 
    if two and three:
      return True
 
    return False
 
def interpreterVideoPoker():
  player = Player()
 
  # Intial Amount
  points = 100
 
  # Cost per hand
  handCost = 5
 
  end = False
  while not end:
    print( "You have {0} points".format(points) )
    print()
 
    points-=5
 
    ## Hand Loop
    deck = StandardDeck()
    deck.shuffle()
 
    # Deal Out
    for i in range(5):
      player.addCard(deck.deal())
 
    # Make them visible
    for card in player.cards:
      card.showing = True
    print(player.cards)
 
    validInput = False
    while not validInput:
      print("Which cards do you want to discard? ( ie. 1, 2, 3 )")
      print("*Just hit return to hold all, type exit to quit")
      inputStr = input()
 
      if inputStr == "exit":
        end=True
        break
 
      try:
        inputList = [int(inp.strip()) for inp in inputStr.split(",") if inp]
 
        for inp in inputList:
          if inp > 6:
            continue 
          if inp < 1:
            continue 
 
        for inp in inputList:
          player.cards[inp-1] = deck.deal()
          player.cards[inp-1].showing = True
 
        validInput = True
      except:
        print("Input Error: use commas to separated the cards you want to hold")
 
    print(player.cards)
    #Score
    score = PokerScorer(player.cards)
    straight = score.straight()
    flush = score.flush()
    highestCount = score.highestCount()
    pairs = score.pairs()
 
    # Royal flush
    if straight and flush and straight == 14:
      print("Royal Flush!!!")
      print("+2000")
      points += 2000
 
    # Straight flush
    elif straight and flush:
      print("Straight Flush!")
      print("+250")
      points += 250
 
    # 4 of a kind
    elif score.fourKind():
      print("Four of a kind!")
      print("+125")
      points += 125
 
    # Full House
    elif score.fullHouse():
      print("Full House!")
      print("+40")
      points += 40
 
    # Flush
    elif flush:
      print("Flush!")
      print("+25")
      points += 25
 
    # Straight
    elif straight:
      print("Straight!")
      print("+20")
      points += 20
 
    # 3 of a kind
    elif highestCount == 3:
      print("Three of a Kind!")
      print("+15")
      points += 15
 
    # 2 pair
    elif len(pairs) == 2:
      print("Two Pairs!")
      print("+10")
      points += 10
 
    # Jacks or better
    elif pairs and pairs[0] > 10:
      print ("Jacks or Better!")
      print("+5")
      points += 5
 
    player.cards=[]
 
    print()
    print()
    print()
0
Эксперт Python
1356 / 653 / 207
Регистрация: 23.03.2014
Сообщений: 3,057
12.01.2020, 13:06
но, кок-что для Вас,yellyex, есть:https://github.com/zakharskorokhodov/zPoker
1
1 / 1 / 0
Регистрация: 03.04.2015
Сообщений: 128
12.01.2020, 13:19  [ТС]
Я ещё две недели буду писать код на питоне

Добавлено через 5 минут
Я попробую упросить задачу. Вот код с примера выше. Кто может слепить его в единое целое?

Часть 1:
Кликните здесь для просмотра всего текста
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from classes import game_class
game = game_class.Game()
 
 
def show_log():
    for x, line in enumerate(game.log):
        print(x, line)
    game.log = []
 
while True:
    game.hand_init()
 
    game.process_hand()
 
    game.hand_result()
 
    if len(game.with_bank_plrs()) == 1:
        break
 
    game.hand_number += 1
 
show_log()  # Debug
 
winner, = game.plrs
 
print(winner.name, winner.bank)

Часть 2:
Кликните здесь для просмотра всего текста
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
from .config_class import CardConfig as cfg
 
 
class Card(cfg):
    """Класс одной карты"""
    def __init__(self, sui, val):
        super(Card, self).__init__()
        self.sui = sui
        self.val = val + 2
        self.name = cfg.suits[self.sui] + cfg.vals[self.val - 2]
 
if __name__ == '__main__':
    main()

Часть 3:
Кликните здесь для просмотра всего текста
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
from .config_class import ComboConfig as cfg
import copy
 
 
class Combo(cfg):
    """docstring for Combo"""
    def test_cards(self):
        normal_pool = sorted(self.pool, key=lambda card: card.val, reverse=True)
 
        pool_vals = [card.val for card in normal_pool]
        pool_suis = [card.sui for card in normal_pool]
 
        if 14 in pool_vals:
            ace_pool = copy.deepcopy(self.pool)
            for card in ace_pool:
                if card.val == 14:
                    card.val = 1
            ace_pool = sorted(ace_pool, key=lambda card: card.val, reverse=True)
 
        result = {}
 
        def put_result():
            self.cards = result['cards']
 
            cards_names = ' '.join([card.name for card in result['cards']])
            self.text = result['text'] + cards_names
 
            pre_power = ''.join([str(hex(card.val))[2:] for card in self.cards])
 
            if len(pre_power) == 2:
                pre_power += '000'
 
            power_0x = str(result['combo_index']) + pre_power
 
            self.power = int(power_0x, 16)
 
        def high_card():
            if self.power > 0:
                return None
            result['cards'] = normal_pool[:5]
            result['text'] = 'Старшая карта '
            result['combo_index'] = 0
 
            put_result()
 
        def one_pair():
            if self.power > 1:
                return None
            res = [card for card in normal_pool if pool_vals.count(card.val) == 2]
 
            if len(res) == 2:
                cards = [card for card in normal_pool if card.val != res[0].val]
 
                result['cards'] = res + cards[:3]
                result['text'] = 'Одна пара '
                result['combo_index'] = 1
 
                put_result()
 
        def two_pairs():
            if self.power > 2 or len(normal_pool) < 5:
                return None
            res = [card for card in normal_pool if pool_vals.count(card.val) == 2][:4]
 
            if len(res) == 4:
                cards = [card for card in normal_pool if card.val != res[0].val and card.val != res[2].val]
 
                result['cards'] = res + [cards[0]]
                result['text'] = 'Две пары '
                result['combo_index'] = 2
 
                put_result()
 
        def three():
            if self.power > 3 or len(normal_pool) < 5:
                return None
            res = [card for card in normal_pool if pool_vals.count(card.val) == 3]
 
            if len(res) == 3:
                cards = [card for card in normal_pool if card.val != res[0].val]
 
                result['cards'] = res + cards[:2]
                result['text'] = 'Тройка '
                result['combo_index'] = 3
 
                put_result()
 
        def straight():
            if self.power > 4 or len(normal_pool) < 5:
                return None
 
            def check_str(cards):
                straight_test = True
                x = 0
                while x < 4:
                    straight_test = straight_test and cards[x].val - 1 == cards[x+1].val
                    x += 1
                return {'straight_test': straight_test, 'cards': cards}
 
            res_list = []
 
            if 14 in pool_vals:
                x = 0
                while True:
                    pre_res = check_str(ace_pool[-5-x:][:5])
                    res_list.append(pre_res)
                    x += 1
                    if x == len(ace_pool) - 4:
                        break
 
            x = 0
            while True:
                pre_res = check_str(normal_pool[-5-x:][:5])
                res_list.append(pre_res)
                x += 1
                if x == len(normal_pool) - 4:
                    break
 
            for res in res_list:
                if res['straight_test']:
 
                    result['cards'] = res['cards']
                    result['text'] = 'Стрит '
                    result['combo_index'] = 4
 
                    put_result()
 
        def flush():
            if self.power > 5 or len(normal_pool) < 5:
                return None
            res = [card for card in normal_pool if pool_suis.count(card.sui) > 4]
 
            if res:
                result['cards'] = res
                result['text'] = 'Флеш '
                result['combo_index'] = 5
 
                put_result()
 
        def full_house():
            if self.power > 6 or len(normal_pool) < 5:
                return None
            three_res = [card for card in normal_pool if pool_vals.count(card.val) > 2]
            if three_res:
                two_res = [card for card in normal_pool if pool_vals.count(card.val) > 1 and card.val != three_res[0].val]
                if two_res:
                    result['cards'] = three_res[:3] + two_res[:2]
                    result['text'] = 'Фул-хаус '
                    result['combo_index'] = 6
 
                    put_result()
 
        def four():
            if self.power > 7 or len(normal_pool) < 5:
                return None
 
            res = [card for card in normal_pool if pool_vals.count(card.val) == 4]
 
            if res:
                cards = [card for card in normal_pool if card.val != res[0].val]
 
                result['cards'] = res + [cards[0]]
                result['text'] = 'Каре '
                result['combo_index'] = 7
 
                put_result()
 
        def straight_flush():
            if len(normal_pool) < 5:
                return None
 
            def check_sf(cards):
                straight_test = True
                flush_test = True
                x = 0
                while x < 4:
                    straight_test = straight_test and cards[x].val - 1 == cards[x+1].val
                    flush_test = flush_test and cards[x].sui == cards[x+1].sui
                    x += 1
                return {'straight_test': straight_test, 'flush_test': flush_test, 'cards': cards}
 
            res_list = []
 
            if 14 in pool_vals:
                x = 0
                while True:
                    pre_res = check_sf(ace_pool[-5-x:][:5])
                    res_list.append(pre_res)
                    x += 1
                    if x == len(ace_pool) - 4:
                        break
 
            x = 0
            while True:
                pre_res = check_sf(normal_pool[-5-x:][:5])
                res_list.append(pre_res)
                x += 1
                if x == len(normal_pool) - 4:
                    break
 
            for res in res_list:
                if res['straight_test'] and res['flush_test']:
 
                    result['cards'] = res['cards']
                    result['text'] = 'Стрит-флэш '
                    result['combo_index'] = 8
 
                    put_result()
 
        straight_flush()
        four()
        full_house()
        flush()
        straight()
        three()
        two_pairs()
        one_pair()
        high_card()
 
    def __init__(self, pool):
        super(Combo, self).__init__()
        self.pool = pool
        self.power = 0
        self.text = ''
        self.cards = []
        self.test_cards()
 
if __name__ == '__main__':
    main()

Часть 4:
Кликните здесь для просмотра всего текста
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import sys
 
 
class GameConfig(object):
    """Первоначальные настройки для класса Game"""
    n_of_players = 6
    all_players_bank = 6000
    states = ['pre_flop', 'flop', 'turn', 'river']
    double_blinds = True
    double_blinds_interval = n_of_players
    start_sb = 50
    start_bb = start_sb * 2
    players_names = [
        'Андрей',
        'Василий',
        'Пётр',
        'Сергей',
        'Ольга',
        'Мария',
        'Вадим',
        'Дмитрий',
        'Антон',
    ]
 
    def __init__(self):
        super(GameConfig, self).__init__()
 
 
class PlayerConfig(object):
    """docstring for Player_Config"""
    def __init__(self):
        super(PlayerConfig, self).__init__()
 
 
class CardConfig(object):
    """Первоначальные настройки для класса Card"""
    if sys.stdout.encoding == 'cp866':  # Консоль windows
        suits = [chr(3), chr(4), chr(5), chr(6)]
    elif sys.stdout.encoding == 'UTF-8':  # unix
        suits = [chr(0x2665), chr(0x2666), chr(0x2663), chr(0x2660)]
    elif sys.stdout.encoding == 'cp1251':  # GUI windows
        suits = ['h', 'd', 'c', 's']
    vals = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
 
    def __init__(self):
        super(CardConfig, self).__init__()
 
 
class ComboConfig(object):
    """Первоначальные настройки для класса Combo"""
 
    def __init__(self):
        super(ComboConfig, self).__init__()
 
if __name__ == '__main__':
    main()

Часть 5:
Кликните здесь для просмотра всего текста
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
from .config_class import GameConfig as cfg
from .card_class import Card
from .player_class import Player
import random
 
 
class Game(cfg):
    """Класс игры"""
    def __log(self, *args):
        message = ' '.join([str(arg) for arg in args])
        #print(message)
        self.log.append(message)
 
    def __create_plrs(self):
        self.plrs = []
        bank = cfg.all_players_bank // cfg.n_of_players
        names = cfg.players_names[:]
        random.shuffle(names)
 
        for plr in range(cfg.n_of_players):
            name = names.pop()
            plr = Player(bank, name)
            self.plrs.append(plr)
 
    def __select_dealer(self):
        plr = random.choice(self.plrs)
        plr.dealer = True
        self.current_plr_id = self.plrs.index(plr)
 
    def __init__(self):
        super(Game, self).__init__()
        self.log = []
        self.river = []
        self.bank = 0
        self.min_bit = 0
        self.sb = 0
        self.bb = 0
        self.hand_number = 1
        self.deck = []
 
        self.__create_plrs()
        self.__select_dealer()
 
    def __create_deck(self):
        deck = []
        for sui in range(len(Card.suits)):
            for val in range(len(Card.vals)):
                c = Card(sui, val)
                deck.append(c)
        return deck
 
    def __give_cards(self):
        random.shuffle(self.deck)
        for plr in self.plrs:
            plr.cards = []
            plr_card_1 = [self.deck.pop()]
            plr_card_2 = [self.deck.pop()]
            plr.cards += plr_card_1 + plr_card_2
 
    def hand_init(self):
        self.deck = self.__create_deck()
        random.shuffle(self.deck)
        self.__give_cards()
 
    def __next_act_plr(self):
        self.current_plr_id += 1
        if self.current_plr_id > len(self.plrs) - 1:
                self.current_plr_id = 0
 
        skip_list = ['Fold', 'All-in']
        while self.plrs[self.current_plr_id].last_act in skip_list:
            self.current_plr_id += 1
            if self.current_plr_id > len(self.plrs) - 1:
                self.current_plr_id = 0
 
        next_plr = self.plrs[self.current_plr_id]
 
        return next_plr
 
    def __daler_id(self):
        dealer, = [plr for plr in self.plrs if plr.dealer]
 
        ind = self.plrs.index(dealer)
 
        return ind
 
    def __clear_acts(self, full=False):
        if full:
            for plr in self.plrs:
                plr.last_act = 'None'
        else:
            for plr in self.plrs:
                if plr.last_act != 'Fold' and plr.last_act != 'All-in':
                    plr.last_act = 'None'
 
    def __clear_bits(self):
        for plr in self.plrs:
            plr.last_bit = 0
 
    def hand_result(self):
 
        def select_winner():
            self.__log('=' * 80)
            if len(self.active_plrs(no_fold=True)) == 1:
                winner, = self.active_plrs(no_fold=True)
                winner.bank += self.bank
                self.__log(winner.name, 'не открывая карты')
            else:
                win_combo_power = max(plr.combo.power for plr in self.plrs)
                winners = [plr for plr in self.plrs if plr.combo.power == win_combo_power]
                if len(winners) == 1:
                    winner, = winners
                    winner.bank += self.bank
                    self.__log(winner.name, winner.combo.text)
                else:
                    for plr in winners:
                        plr.bank += self.bank // len(winners)
                        self.__log(', '.join([plr.name for plr in winners]), winners[0].combo.text)
            self.bank = 0
            self.__log('=' * 80)
 
        def remove_loosers():
            loosers = []
            for plr in self.plrs:
                if plr.bank == 0:
                    loosers.append(plr)
 
            for looser in loosers:
                self.plrs.remove(looser)
 
        def move_dealer():
            old_dealer_id = self.__daler_id()
            old_dealer = self.plrs[old_dealer_id]
            old_dealer.dealer = False
 
            new_dealer_id = old_dealer_id + 1
            if new_dealer_id == len(self.plrs):
                new_dealer_id = 0
 
            while self.plrs[new_dealer_id] not in self.with_bank_plrs():
                new_dealer_id += 1
                if new_dealer_id == len(self.plrs):
                    new_dealer_id = 0
 
            new_dealer = self.plrs[new_dealer_id]
            new_dealer.dealer = True
 
            self.current_plr_id = self.plrs.index(new_dealer)
 
        select_winner()
        move_dealer()
        remove_loosers()
 
        self.river = []
        self.__clear_acts('full')
 
    def with_bank_plrs(self):
        plrs_list = [plr for plr in self.plrs if plr.bank > 0]
        return plrs_list
 
    def active_plrs(self, no_fold=False, no_allin=False):
        if no_fold and no_allin:
            skip_list = ['Fold', 'All-in']
        elif no_fold:
            skip_list = ['Fold']
        elif no_allin:
            skip_list = ['All-in']
 
        plrs = [plr for plr in self.plrs if plr.last_act not in skip_list]
        return plrs
 
    def __process_the_state(self, state):
 
        def take_blinds():
            if cfg.double_blinds:  # Вычисление блайндов если умножаются
                double_index = (self.hand_number - 1) // cfg.double_blinds_interval  # Делим без остатка номер раздачи (от 0) на промежуток
 
                self.sb = cfg.start_sb * (2 ** double_index)  # Умножаем стартовый блайнд на 2 в степени double_index
                self.bb = cfg.start_bb * (2 ** double_index)
            else:
                self.sb = cfg.start_sb
                self.bb = cfg.start_bb
 
            sb_plr = self.__next_act_plr()
            act = sb_plr.small_blind(self.sb)
            self.bank += act['bit']
            self.__log(self.plrs.index(sb_plr), sb_plr.name, sb_plr.last_act, sb_plr.last_bit)
 
            bb_plr = self.__next_act_plr()
            act = bb_plr.big_blind(self.bb)
            self.bank += act['bit']
            self.__log(self.plrs.index(bb_plr), bb_plr.name, bb_plr.last_act, bb_plr.last_bit)
 
            self.min_bit = self.bb
 
        def take_bits():
            while True:
 
                bb_flag = False
                if len(self.active_plrs(no_fold=True, no_allin=True)) > 1:
                    plr = self.__next_act_plr()
 
                    if plr.last_bit == self.bb and plr.last_act == 'BB':
                        bb_flag = True
                    elif plr.last_bit == self.min_bit and plr.last_act == 'Raise':
                        break
                else:
                    plr, = self.active_plrs(no_fold=True, no_allin=True)
                    break
 
                plr.action(self.plrs, self.river, self.min_bit, self.bb)
                self.bank += plr.last_bit
 
                self.__log(self.plrs.index(plr), plr.name, plr.last_act, plr.last_bit, plr.combo.text)
 
                if bb_flag and plr.last_bit == 0 and self.min_bit > 0:
                    break
 
                if plr.last_bit > self.min_bit:
                    self.min_bit = plr.last_bit
 
        if state == self.states[0]:
            take_blinds()
        elif state == self.states[1]:
            self.river += [self.deck.pop()]
            self.river += [self.deck.pop()]
            self.river += [self.deck.pop()]
        elif state == self.states[2]:
            self.river += [self.deck.pop()]
        elif state == self.states[3]:
            self.river += [self.deck.pop()]
 
        self.__log(self.hand_number, state, self.__daler_id(), ' '.join([c.name for c in self.river]), '-' * 30)
 
        take_bits()
 
        # Очищаем записи о действиях игроков
        self.__clear_acts()
        self.__clear_bits()
        self.min_bit = 0
        self.current_plr_id = self.__daler_id()
 
    def process_hand(self):
        for state in cfg.states:
 
            if len(self.active_plrs(no_fold=True, no_allin=True)) < 2:
                break
            self.__process_the_state(state)
 
 
if __name__ == '__main__':
    main()

Часть 6:
Кликните здесь для просмотра всего текста
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
from .config_class import PlayerConfig as cfg
from .combo_class import Combo
import random
 
 
class Player(cfg):
    """docstring for PLayer"""
    def __init__(self, bank, name):
        super(Player, self).__init__()
        self.dealer = False
        self.last_act = 'None'
        self.last_bit = 0
        self.combo = None
 
        self.bank = bank
        self.name = name
 
    def __check_combo(self, river):
        check_cards = self.cards + river
        self.combo = Combo(check_cards)
 
    def action(self, players, river, min_bit, bb):
        self.__check_combo(river)
        actions = ['Fold', 'Check', 'Call', 'Raise', 'All-in']
        max_bank = max([player.bank for player in players])
 
        if min_bit > 0 and self.last_bit < min_bit:
            actions.remove('Check')
 
        if min_bit == 0 or min_bit == self.last_bit:
            actions.remove('Fold')
 
        if self.bank <= min_bit or min_bit == 0 or self.last_bit == min_bit:
            actions.remove('Call')
 
        if self.bank < min_bit + bb:
            actions.remove('Raise')
 
        if self.bank > max_bank:
            actions.remove('All-in')
 
        min_power = 761856
 
        act_power = self.combo.power // min_power
 
        if act_power < 1:
            act = actions[0]
        else:
            act = actions[1]
 
        #act = random.choice(actions)
 
        if act == 'Check':
            self.last_act = 'Check'
            self.last_bit = 0
        elif act == 'Fold':
            self.last_act = 'Fold'
            self.last_bit = 0
        elif act == 'Call':
            self.last_act = 'Call'
            self.last_bit = min_bit
            self.bank -= self.last_bit
        elif act == 'Raise':
            self.last_act = 'Raise'
            self.last_bit = min_bit + bb
            self.bank -= self.last_bit
        elif act == 'All-in':
            self.last_act = 'All-in'
            self.last_bit = self.bank
            self.bank = 0
 
    def small_blind(self, sb):
        if self.bank > sb:
            self.last_act = 'SB'
            self.last_bit = sb
            self.bank -= sb
        else:
            self.last_act = 'All-in'
            self.last_bit = self.bank
            self.bank = 0
 
        return {'name': self.last_act, 'bit': self.last_bit}
 
    def big_blind(self, bb):
        if self.bank > bb:
            self.last_act = 'BB'
            self.last_bit = bb
            self.bank -= bb
        else:
            self.last_act = 'All-in'
            self.last_bit = self.bank
            self.bank = 0
 
        return {'name': self.last_act, 'bit': self.last_bit}
 
if __name__ == '__main__':
    main()


Добавлено через 2 минуты
Есть небольшие изменения.
Раздаются карты:
5 карт на стол
по 2 карты каждому из 6 игроков.
Без флопов, тёрнов и риверов. Раздаются моментально.
После этого я уже собираю статистику, которая мне нужна. Мой покер попроще, чем настоящий.
0
Эксперт PythonЭксперт Java
19530 / 11067 / 2931
Регистрация: 21.10.2017
Сообщений: 23,294
12.01.2020, 13:47
Цитата Сообщение от yellyex Посмотреть сообщение
UE4 на С++ работает
И ты думаешь, питон быстрее будет?
0
1 / 1 / 0
Регистрация: 03.04.2015
Сообщений: 128
12.01.2020, 13:54  [ТС]
iSmokeJC, Я понял, что Вы имели ввиду. Нет код то на С++, но работает он медленно. На питоне через консоль в 100 раз быстрее.

Добавлено через 43 секунды
Цели:

Создаётся колода, раздаются карты игрокам и на стол, считаются комбинации игроков, комбинации сравниваются и выбирается победитель/и. Данные выводятся в консоль. Нужно добавить переменные по выигрышной комбинации и по выигрышному игроку.

Пример результата:

Board: 5c 6d Ac 4h 2h
Player 1: 5h Ad
Player 2: Kc Kh
Player 3: Qd Jс
Player 4: 10s 9c
Player 5: 8s Jh
Player 6: 2d 3h

Win: Player 6
Win: Straight - 2h 3h 4h 5c 6d
0
1 / 1 / 0
Регистрация: 03.04.2015
Сообщений: 128
13.01.2020, 01:31  [ТС]
Нашёл пример покера и пытаюсь собрать во едино. Наверно он был написан на второй версии питона, так как после print скобок нет. Расставил вручную, но наткнулся на непонятную мне ошибку.

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
import time
import multiprocessing
import argparse
import re
import holdem_functions
import holdem_argparser
 
# Constants
suit_index_dict = {"s": 0, "c": 1, "h": 2, "d": 3}
reverse_suit_index = ("s", "c", "h", "d")
val_string = "AKQJT98765432"
hand_rankings = ("High Card", "Pair", "Two Pair", "Three of a Kind",
                 "Straight", "Flush", "Full House", "Four of a Kind",
                 "Straight Flush", "Royal Flush")
suit_value_dict = {"T": 10, "J": 11, "Q": 12, "K": 13, "A": 14}
for num in xrange(2, 10):
    suit_value_dict[str(num)] = num
 
class Card:
    # Takes in strings of the format: "As", "Tc", "6d"
    def __init__(self, card_string):
        value, self.suit = card_string[0], card_string[1]
        self.value = suit_value_dict[value]
        self.suit_index = suit_index_dict[self.suit]
 
    def __str__(self):
        return val_string[14 - self.value] + self.suit
 
    def __repr__(self):
        return val_string[14 - self.value] + self.suit
 
    def __eq__(self, other):
        if self is None:
            return other is None
        elif other is None:
            return False
        return self.value == other.value and self.suit == other.suit
 
# Returns deck of cards with all hole cards and board cards removed
def generate_deck(hole_cards, board):
    deck = []
    for suit in reverse_suit_index:
        for value in val_string:
            deck.append(Card(value + suit))
    taken_cards = []
    for hole_card in hole_cards:
        for card in hole_card:
            if card is not None:
                taken_cards.append(card)
    if board and len(board) > 0:
        taken_cards.extend(board)
    for taken_card in taken_cards:
        deck.remove(taken_card)
    return tuple(deck)
 
# Generate all possible hole card combinations
def generate_hole_cards(deck):
    import itertools
    return itertools.combinations(deck, 2)
 
# Generate num_iterations random boards
def generate_random_boards(deck, num_iterations, board_length):
    import random
    import time
    random.seed(time.time())
    for _ in xrange(num_iterations):
        yield random.sample(deck, 5 - board_length)
 
# Generate all possible boards
def generate_exhaustive_boards(deck, num_iterations, board_length):
    import itertools
    return itertools.combinations(deck, 5 - board_length)
 
# Returns a board of cards all with suit = flush_index
def generate_suit_board(flat_board, flush_index):
    histogram = [card.value for card in flat_board
                 if card.suit_index == flush_index]
    histogram.sort(reverse=True)
    return histogram
 
# Returns a list of two tuples of the form: (value of card, frequency of card)
def preprocess(histogram):
    return [(14 - index, frequency) for index, frequency in
            enumerate(histogram) if frequency]
 
 
# Takes an iterable sequence and returns two items in a tuple:
# 1: 4-long list showing how often each card suit appears in the sequence
# 2: 13-long list showing how often each card value appears in the sequence
def preprocess_board(flat_board):
    suit_histogram, histogram = [0] * 4, [0] * 13
    # Reversing the order in histogram so in the future, we can traverse
    # starting from index 0
    for card in flat_board:
        histogram[14 - card.value] += 1
        suit_histogram[card.suit_index] += 1
    return suit_histogram, histogram, max(suit_histogram)
 
# Returns tuple: (Is there a straight flush?, high card)
def detect_straight_flush(suit_board):
    contiguous_length, fail_index = 1, len(suit_board) - 5
    # Won't overflow list because we fail fast and check ahead
    for index, elem in enumerate(suit_board):
        current_val, next_val = elem, suit_board[index + 1]
        if next_val == current_val - 1:
            contiguous_length += 1
            if contiguous_length == 5:
                return True, current_val + 3
        else:
            # Fail fast if straight not possible
            if index >= fail_index:
                if (index == fail_index and next_val == 5 and
                        suit_board[0] == 14):
                    return True, 5
                break
            contiguous_length = 1
    return False,
 
# Returns the highest kicker available
def detect_highest_quad_kicker(histogram_board):
    for elem in histogram_board:
        if elem[1] < 4:
            return elem[0]
 
# Returns tuple: (Is there a straight?, high card)
def detect_straight(histogram_board):
    contiguous_length, fail_index = 1, len(histogram_board) - 5
    # Won't overflow list because we fail fast and check ahead
    for index, elem in enumerate(histogram_board):
        current_val, next_val = elem[0], histogram_board[index + 1][0]
        if next_val == current_val - 1:
            contiguous_length += 1
            if contiguous_length == 5:
                return True, current_val + 3
        else:
            # Fail fast if straight not possible
            if index >= fail_index:
                if (index == fail_index and next_val == 5 and
                        histogram_board[0][0] == 14):
                    return True, 5
                break
            contiguous_length = 1
    return False,
 
# Returns tuple of the two highest kickers that result from the three of a kind
def detect_three_of_a_kind_kickers(histogram_board):
    kicker1 = -1
    for elem in histogram_board:
        if elem[1] != 3:
            if kicker1 == -1:
                kicker1 = elem[0]
            else:
                return kicker1, elem[0]
 
# Returns the highest kicker available
def detect_highest_kicker(histogram_board):
    for elem in histogram_board:
        if elem[1] == 1:
            return elem[0]
 
# Returns tuple: (kicker1, kicker2, kicker3)
def detect_pair_kickers(histogram_board):
    kicker1, kicker2 = -1, -1
    for elem in histogram_board:
        if elem[1] != 2:
            if kicker1 == -1:
                kicker1 = elem[0]
            elif kicker2 == -1:
                kicker2 = elem[0]
            else:
                return kicker1, kicker2, elem[0]
 
# Returns a list of the five highest cards in the given board
# Note: Requires a sorted board to be given as an argument
def get_high_cards(histogram_board):
    return histogram_board[:5]
 
# Return Values:
# Royal Flush: (9,)
# Straight Flush: (8, high card)
# Four of a Kind: (7, quad card, kicker)
# Full House: (6, trips card, pair card)
# Flush: (5, [flush high card, flush second high card, ..., flush low card])
# Straight: (4, high card)
# Three of a Kind: (3, trips card, (kicker high card, kicker low card))
# Two Pair: (2, high pair card, low pair card, kicker)
# Pair: (1, pair card, (kicker high card, kicker med card, kicker low card))
# High Card: (0, [high card, second high card, third high card, etc.])
def detect_hand(hole_cards, given_board, suit_histogram,
                full_histogram, max_suit):
    # Determine if flush possible. If yes, four of a kind and full house are
    # impossible, so return royal, straight, or regular flush.
    if max_suit >= 3:
        flush_index = suit_histogram.index(max_suit)
        for hole_card in hole_cards:
            if hole_card.suit_index == flush_index:
                max_suit += 1
        if max_suit >= 5:
            flat_board = list(given_board)
            flat_board.extend(hole_cards)
            suit_board = generate_suit_board(flat_board, flush_index)
            result = detect_straight_flush(suit_board)
            if result[0]:
                return (8, result[1]) if result[1] != 14 else (9,)
            return 5, get_high_cards(suit_board)
 
    # Add hole cards to histogram data structure and process it
    full_histogram = full_histogram[:]
    for hole_card in hole_cards:
        full_histogram[14 - hole_card.value] += 1
    histogram_board = preprocess(full_histogram)
 
    # Find which card value shows up the most and second most times
    current_max, max_val, second_max, second_max_val = 0, 0, 0, 0
    for item in histogram_board:
        val, frequency = item[0], item[1]
        if frequency > current_max:
            second_max, second_max_val = current_max, max_val
            current_max, max_val = frequency, val
        elif frequency > second_max:
            second_max, second_max_val = frequency, val
 
    # Check to see if there is a four of a kind
    if current_max == 4:
        return 7, max_val, detect_highest_quad_kicker(histogram_board)
    # Check to see if there is a full house
    if current_max == 3 and second_max >= 2:
        return 6, max_val, second_max_val
    # Check to see if there is a straight
    if len(histogram_board) >= 5:
        result = detect_straight(histogram_board)
        if result[0]:
            return 4, result[1]
    # Check to see if there is a three of a kind
    if current_max == 3:
        return 3, max_val, detect_three_of_a_kind_kickers(histogram_board)
    if current_max == 2:
        # Check to see if there is a two pair
        if second_max == 2:
            return 2, max_val, second_max_val, detect_highest_kicker(
                histogram_board)
        # Return pair
        else:
            return 1, max_val, detect_pair_kickers(histogram_board)
    # Check for high cards
    return 0, get_high_cards(histogram_board)
 
# Returns the index of the player with the winning hand
def compare_hands(result_list):
    best_hand = max(result_list)
    winning_player_index = result_list.index(best_hand) + 1
    # Check for ties
    if best_hand in result_list[winning_player_index:]:
        return 0
    return winning_player_index
 
# Print results
def print_results(hole_cards, winner_list, result_histograms):
    float_iterations = float(sum(winner_list))
    print ("Winning Percentages:")
    for index, hole_card in enumerate(hole_cards):
        winning_percentage = float(winner_list[index + 1]) / float_iterations
        if hole_card == (None, None):
            print ("(?, ?) : "), winning_percentage
        else:
            print (hole_card, ": "), winning_percentage
    print ("Ties: ", float(winner_list[0]) / float_iterations, "\n")
    for player_index, histogram in enumerate(result_histograms):
        print ("Player" + str(player_index + 1) + " Histogram: ")
        for index, elem in enumerate(histogram):
            print (hand_rankings[index], ": "), float(elem) / float_iterations
        print
 
# Returns the winning percentages
def find_winning_percentage(winner_list):
    float_iterations = float(sum(winner_list))
    percentages = []
    for num_wins in winner_list:
        winning_percentage = float(num_wins) / float_iterations
        percentages.append(winning_percentage)
    return percentages
 
# Populate provided data structures with results from simulation
def find_winner(generate_boards, deck, hole_cards, num, board_length,
                given_board, winner_list, result_histograms):
    # Run simulations
    result_list = [None] * len(hole_cards)
    for remaining_board in generate_boards(deck, num, board_length):
        # Generate a new board
        if given_board:
            board = given_board[:]
            board.extend(remaining_board)
        else:
            board = remaining_board
        # Find the best possible poker hand given the created board and the
        # hole cards and save them in the results data structures
        suit_histogram, histogram, max_suit = (
            preprocess_board(board))
        for index, hole_card in enumerate(hole_cards):
            result_list[index] = detect_hand(hole_card, board, suit_histogram,
                                             histogram, max_suit)
        # Find the winner of the hand and tabulate results
        winner_index = compare_hands(result_list)
        winner_list[winner_index] += 1
        # Increment what hand each player made
        for index, result in enumerate(result_list):
            result_histograms[index][result[0]] += 1
 
 
# CHECK ==================================================================================================
 
# Wrapper class which holds the arguments for library calls
# Mocks actual argparse object
class LibArgs:
    def __init__(self, board, exact, num, input_file, hole_cards):
        self.board = board
        self.cards = hole_cards
        self.n = num
        self.input = input_file
        self.exact = exact
 
# Parses arguments passed to holdem_calc as a library call
def parse_lib_args(args):
    error_check_arguments(args)
    # Parse hole cards and board
    hole_cards, board = None, None
    if not args.input:
        hole_cards, board = parse_cards(args.cards, args.board)
    return hole_cards, args.n, args.exact, board, args.input
 
# Parses command line arguments to holdem_calc
def parse_args():
    # Define possible command line arguments
    parser = argparse.ArgumentParser(
        description="Find the odds that a Texas Hold'em hand will win. Note "
        "that cards must be given in the following format: As, Jc, Td, 3h.")
    parser.add_argument("cards", nargs="*", type=str, metavar="hole card",
                        help="Hole cards you want to find the odds for.")
    parser.add_argument("-b", "--board", nargs="*", type=str, metavar="card",
                        help="Add board cards")
    parser.add_argument("-e", "--exact", action="store_true",
                        help="Find exact odds by enumerating every possible "
                        "board")
    parser.add_argument("-n", type=int, default=100000,
                        help="Run N Monte Carlo simulations")
    parser.add_argument("-i", "--input", type=str,
                        help="Read hole cards and boards from an input file. "
                        "Commandline arguments for hole cards and board will "
                        "be ignored")
    # Parse command line arguments and check for errors
    args = parser.parse_args()
    error_check_arguments(args)
    # Parse hole cards and board
    hole_cards, board = None, None
    if not args.input:
        hole_cards, board = parse_cards(args.cards, args.board)
    return hole_cards, args.n, args.exact, board, args.input
 
# Parses a line taken from the input file and returns the hole cards and board
def parse_file_args(line):
    if line is None or len(line) == 0:
        print (line)
        print ("Invalid format")
        exit()
    values = line.split("|")
    if len(values) > 2 or len(values) < 1:
        print (line)
        print ("Invalid format")
        exit()
    hole_cards = values[0].split()
    all_cards = list(hole_cards)
    board = None
    if len(values) == 2:
        board = values[1].split()
        all_cards.extend(board)
    error_check_cards(all_cards)
    return parse_cards(hole_cards, board)
 
# Parses hole cards and board
def parse_cards(cards, board):
    hole_cards = create_hole_cards(cards)
    if board:
        board = parse_board(board)
    return hole_cards, board
 
# Error check the command line arguments
def error_check_arguments(args):
    # Check that the number of Monte Carlo simulations is a positive number
    if args.n <= 0:
        print ("Number of Monte Carlo simulations must be positive.")
        exit()
    # Check that we can open the specified input file
    if args.input:
        file_name = args.input
        try:
            input_file = open(file_name, 'r')
            input_file.close()
        except IOError:
            print ("Error opening file ") + file_name
            exit()
    # Check to make sure all cards are of a valid format
    all_cards = list(args.cards)
    if args.board:
        all_cards.extend(args.board)
    error_check_cards(all_cards)
 
# Error check the command line arguments
def error_check_arguments(args):
    # Check that the number of Monte Carlo simulations is a positive number
    if args.n <= 0:
        print ("Number of Monte Carlo simulations must be positive.")
        exit()
    # Check that we can open the specified input file
    if args.input:
        file_name = args.input
        try:
            input_file = open(file_name, 'r')
            input_file.close()
        except IOError:
            print ("Error opening file ") + file_name
            exit()
    # Check to make sure all cards are of a valid format
    all_cards = list(args.cards)
    if args.board:
        all_cards.extend(args.board)
    error_check_cards(all_cards)
 
# Checking that the hole cards + board are formatted properly and unique
def error_check_cards(all_cards):
    card_re = re.compile('[AKQJT98765432][scdh]')
    for card in all_cards:
        if card != "?" and not card_re.match(card):
            print ("Invalid card given.")
            exit()
        else:
            if all_cards.count(card) != 1 and card != "?":
                print ("The cards given must be unique.")
                exit()
 
# Returns tuple of two-tuple hole_cards: e.g. ((As, Ks), (Ad, Kd), (Jh, Th))
def create_hole_cards(raw_hole_cards):
    # Checking that there are an even number of hole cards
    if (raw_hole_cards is None or len(raw_hole_cards) < 2 or
            len(raw_hole_cards) % 2):
        print ("You must provide a non-zero even number of hole cards")
        exit()
    # Create two-tuples out of hole cards
    hole_cards, current_hole_cards = [], []
    for hole_card in raw_hole_cards:
        if hole_card != "?":
            current_card = holdem_functions.Card(hole_card)
            current_hole_cards.append(current_card)
        else:
            current_hole_cards.append(None)
        if len(current_hole_cards) == 2:
            if None in current_hole_cards:
                if (current_hole_cards[0] is not None or
                        current_hole_cards[1] is not None):
                    print ("Unknown hole cards must come in pairs")
                    exit()
            hole_cards.append((current_hole_cards[0], current_hole_cards[1]))
            current_hole_cards = []
    if hole_cards.count((None, None)) > 1:
        print ("Can only have one set of unknown hole cards")
    return tuple(hole_cards)
 
# Returns list of board cards: e.g. [As Ks Ad Kd]
def parse_board(board):
    if len(board) > 5 or len(board) < 3:
        print ("Board must have a length of 3, 4, or 5.")
        exit()
    if "?" in board:
        print ("Board cannot have unknown cards")
        exit()
    return create_cards(board)
 
# Instantiates new cards from the arguments and returns them in a tuple
def create_cards(card_strings):
    return [holdem_functions.Card(arg) for arg in card_strings]
Добавлено через 7 минут
Скачать источник, так как сюда не позволяет вставить весь код.
https://cloud.mail.ru/public/Cf8S/2rhXv7Mei

Добавлено через 37 минут
Не нужно склеивать весь код. Нужно выбрать только те блоки, чтобы получился результат:

Создаётся колода, раздаются карты игрокам и на стол, считаются комбинации игроков, комбинации сравниваются и выбирается победитель/и. Данные выводятся в консоль.

Board: 5c 6d Ac 4h 2h
Player 1: 5h Ad
Player 2: Kc Kh
Player 3: Qd Jс
Player 4: 10s 9c
Player 5: 8s Jh
Player 6: 2d 3h

Win: Player 6
Win: Straight - 2h 3h 4h 5c 6d
0
 Аватар для sdasdaw
406 / 278 / 93
Регистрация: 14.03.2017
Сообщений: 777
19.01.2020, 07:54
Цитата Сообщение от yellyex Посмотреть сообщение
Нет код то на С++
у вас не C++, а Blueprint

и не удивлюсь, что вся производительность падает из-за того что во втором скрине не подсоединен узел к условию
вешать такие вещи на Event Tick - гениально, при этом говорить, что код работает медленно
0
1943 / 1768 / 825
Регистрация: 23.01.2014
Сообщений: 6,230
19.01.2020, 09:03
Цитата Сообщение от yellyex Посмотреть сообщение
о наткнулся на непонятную мне ошибку
Какую, в каком коде?
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
19.01.2020, 09:03
Помогаю со студенческими работами здесь

Движок Unreal Engine
Посоветуйте какой-нибудь видео урок или литературу по данному движку

Unity vs Unreal Engine 4
Всем привет. Есть желание попробовать сделать свою игру. Рпг с &quot;видом сверху&quot; как Baldur's Gate. Сейчас Unity и Unreal Engine 4 практически...

Unreal Engine 4 2d сайдскроллер
Возник вопрос по переключению 2d анимации. Вообщем в блюпринтах смену анимации выставил. Но хочется реализовать всё это через C++. Помогите...

Библиотека в Unreal Engine
Нигде не смог найти ответ. Решил обратится сюда). Так вот. Какую графическую библиотеку использует за основу UE? Либо у них своя отдельная...

Flex от NVidia и Unreal Engine
Сколько пытался скачать - пйдж нот фаунд. Зареган как надо и на сайте Unreal, гитхабе, и NVidia, Flex для Unity качаю и запускаю, но по...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
14
Ответ Создать тему
Новые блоги и статьи
Установка Android SDK, NDK, JDK, CMake и т.д.
8Observer8 25.01.2026
Содержание блога Перейдите по ссылке: https:/ / developer. android. com/ studio и в самом низу страницы кликните по архиву "commandlinetools-win-xxxxxx_latest. zip" Извлеките архив и вы увидите. . .
Вывод текста со шрифтом TTF на Android с помощью библиотеки SDL3_ttf
8Observer8 25.01.2026
Содержание блога Если у вас не установлены Android SDK, NDK, JDK, и т. д. то сделайте это по следующей инструкции: Установка Android SDK, NDK, JDK, CMake и т. д. Сборка примера Скачайте. . .
Использование SDL3-callbacks вместо функции main() на Android, Desktop и WebAssembly
8Observer8 24.01.2026
Содержание блога Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а. . .
моя боль
iceja 24.01.2026
Выложила интерполяцию кубическими сплайнами www. iceja. net REST сервисы временно не работают, только через Web. Написала за 56 рабочих часов этот сайт с нуля. При помощи perplexity. ai PRO , при. . .
Модель сукцессии микоризы
anaschu 24.01.2026
Решили писать научную статью с неким РОманом
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь(не выше 3-го порядка) постоянного тока с элементами R, L, C, k(ключ), U, E, J. Программа находит переходные токи и напряжения на элементах схемы классическим методом(1 и 2 з-ны. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru