class Dealer: def __init__(self, stack=None): self.stack = stack self.trump_color = '' def reset_card_deck(self): self.stack = CardDeck() def deal_cards(self, players=None, amount=0): for _ in range(amount): for player in players: player.receive_card(self.stack.draw_card()) def determine_trump(self): if len(self.stack) > 0: self.trump_color = self.stack.draw_card().color return self.trump_color
def get_accusationCards(options): """ This function parses the cards from the options and returns Card objects""" card_deck = CardDeck() char_card = None weapon_card = None room_card = None card_names = options.cards.split(",") for card_name in card_names: if card_name == "None": continue requested_card = card_deck.get_card(card_name) cardtype = requested_card.get_cardtype() if cardtype == "character": char_card = requested_card elif cardtype == "weapon": weapon_card = requested_card elif cardtype == "room": room_card = requested_card return char_card, weapon_card, room_card
def main(): deck = CardDeck() print(deck) print("") deck.shuffle() print(deck) deck.shuffle() print(deck) print("") deck.reset() print(deck)
def test(): card_deck = CardDeck() message_types = ['start', 'move', 'invalidMove', 'accuse','mustDisprove', 'disprove', 'win', 'lose', 'end'] for message_type in message_types: if message_type != "accuse" and message_type != "disprove" and message_type != "mustDisprove": create_message(message_type) else: char_card = None weapon_card = None room_card = None need_card_types = ['character','weapon','room'] for cardtype in need_card_types: requested_card = card_deck.get_random_card(cardtype) if requested_card != None: if cardtype == "character": char_card = requested_card elif cardtype == "weapon": weapon_card = requested_card elif cardtype == "room": room_card = requested_card card_names = ",".join([x.get_name() for x in [char_card,weapon_card,room_card]]) create_message(message_type,card_names)
def play(self): cd = CardDeck() cd.shuffle() self.__p1 = Player('Player1') self.__p2 = Player('Player2') while(cd.getSize() >= 2): self.__p1.collectCard(cd.deal()) self.__p2.collectCard(cd.deal()) self.__p1.useWonPile() self.__p2.useWonPile() down = Pile() for t in range(1, 101): if(not(self.enoughCards(1))): break c1 = Card(None,None) c2 = Card(None,None) c1 = self.__p1.playCard() c2 = self.__p2.playCard() print("\nTurn ", t, "!") print(self.__p1.getName() ,": ", c1, " ") print(self.__p2.getName() ,": ", c2, " ") if(c1.compareTo(c2) > 0): self.__p1.collectCard(c1) self.__p1.collectCard(c2) elif(c1.compareTo(c2) < 0): self.__p2.collectCard(c1) self.__p2.collectCard(c2) else: down.clear() down.addCard(c1) down.addCard(c2) done = False while(not(done)): num = c1.getRank() if(not(self.enoughCards(num))): break print("\nWar! Players put down ") print(num , " cards(s).") for m in range(1, num+1): c1 = self.__p1.playCard() c2 = self.__p2.playCard() down.addCard(c1) down.addCard(c2) print(self.__p1.getName(), ": ", c1, " ") print(self.__p2.getName(), ": ", c2, " ") if(c1.compareTo(c2) > 0): self.__p1.collectCards(down) done = True elif(c1.compareTo(c2) < 0): self.__p2.collectCards(down) done = True print(self.__p1.numCards(), " to ", self.__p2.numCards())
def __init__(self, *args, **kwargs): PodSixNet.Server.Server.__init__(self, *args, **kwargs) self.currentIndex=-1 print "STARTING UP THE SERVER" self.card_deck = CardDeck() self.confidential_card_types = ['character','weapon','room'] self.confidential_file = [] self.character_index_names = {0:"Mr. Green",1:"Miss Scarlett",2:"Mrs. Peacock"} self.character_indexes = dict((y,x) for x,y in self.character_index_names.iteritems()) self.minPlayers = 3 # Minimum number of players to play the game self.active_turn = 0 self.disprove_turn = 0 self.playerChannels = [] self.disproved_response = [] self.select_confidential_cards()
def __init__(self): self.stack = CardDeck() self.round_number = 0 self.players = [] self.trump_color = ''
def disproveAccusation(self,message_type,accusation_lines,card_names_to_limit=None): card_deck = CardDeck() accusation_form = Form(False) disproving = False if len(accusation_lines) > 0: disproving = True accusation_form.add_object('new_title', Text('Current Suggestion:', label_style=['bold','underline'])) for k in xrange(len(accusation_lines)): accusation_message, accusation_pos,accusation_message_str = accusation_lines[k] accusation_form.add_object('accusation_{0}'.format(k), Text('{0}'.format(accusation_message_str), label_style=['bold'])) accusation_form.add_object('spacer', Text('', label_style=['bold','underline'])) accusation_form.add_object('disprove_title_{0}'.format(k), Text('Select card(s) to disprove:', label_style=['bold','underline'])) else: if message_type == "New Suggestion": accusation_form.add_object('suggestion_title', Text('Select card(s) for suggestion:', label_style=['bold','underline'])) else: accusation_form.add_object('suggestion_title', Text('Select card(s) for accusation:', label_style=['bold','underline'])) screen = self.getScreen(message_type,disproving) tracker = [] character_menu = Select(border_width=2, top=50) character_list = card_deck.get_cardlist("character") char_found = False for character_name in character_list: if card_names_to_limit and len(card_names_to_limit) > 1 and character_name in card_names_to_limit: character_menu.add_option(character_name,character_name) tracker.append(character_name) char_found = True elif card_names_to_limit and len(card_names_to_limit) == 1: character_menu.add_option(character_name,character_name) tracker.append(character_name) char_found = True elif not card_names_to_limit: character_menu.add_option(character_name,character_name) tracker.append(character_name) char_found = True if char_found: accusation_form.add_object('title_character', Text('Select Character:', label_style=['bold'])) accusation_form.add_object('character', character_menu) else: accusation_form.add_object('title_character', Text('Select Character:', label_style=['bold'])) accusation_form.add_object('title_character_1', Text('Sorry, no Character cards', label_style=['bold'])) accusation_form.add_object('title_character_2', Text('in your deck to select', label_style=['bold'])) #if disproving: accusation_form.add_object('weapon_title', Text('with a', label_style=['bold'])) weapon_list = card_deck.get_cardlist("weapon") weapon_menu = Select(border_width=2, top=50) weapon_found = False for weapon_name in weapon_list: if card_names_to_limit and len(card_names_to_limit) > 1 and weapon_name in card_names_to_limit: weapon_menu.add_option(weapon_name,weapon_name) tracker.append(weapon_name) weapon_found = True elif card_names_to_limit and len(card_names_to_limit) == 1: weapon_menu.add_option(weapon_name,weapon_name) tracker.append(weapon_name) weapon_found = True elif not card_names_to_limit: weapon_menu.add_option(weapon_name,weapon_name) tracker.append(weapon_name) weapon_found = True if weapon_found: accusation_form.add_object('title_weapon', Text('Select Weapon:', label_style=['bold'])) accusation_form.add_object('weapon', weapon_menu) else: accusation_form.add_object('title_weapon', Text('Select Weapon:', label_style=['bold'])) accusation_form.add_object('title_weapon_1', Text('Sorry, no Weapon cards', label_style=['bold'])) accusation_form.add_object('title_weapon_2', Text('in your deck to select', label_style=['bold'])) #if disproving: accusation_form.add_object('room_title', Text('in the', label_style=['bold'])) room_list = card_deck.get_cardlist("room") room_menu = Select(border_width=2, top=50) room_found = False for room_name in room_list: if card_names_to_limit and room_name in card_names_to_limit: room_menu.add_option(room_name,room_name) tracker.append(room_name) room_found = True elif not card_names_to_limit: room_menu.add_option(room_name,room_name) tracker.append(room_name) room_found = True if room_found: accusation_form.add_object('title_room', Text('Select Room:', label_style=['bold'])) accusation_form.add_object('room', room_menu) else: accusation_form.add_object('title_room', Text('Select Room:', label_style=['bold'])) accusation_form.add_object('title_room_1', Text('Sorry, no Room cards', label_style=['bold'])) accusation_form.add_object('title_room_2', Text('in your deck to select', label_style=['bold'])) if disproving: accusation_form.add_object('submit', Button('Disprove', accusation_form.submit, ())) accusation_form.add_object('skip', Button('Skip', accusation_form.skip, ())) else: if message_type == "New Suggestion": accusation_form.add_object('submit', Button('Make Suggestion', accusation_form.submit, ())) else: accusation_form.add_object('submit', Button('Make Final Accusation', accusation_form.submit, ())) accusation_form.add_object('skip', Button('Skip', accusation_form.skip, ())) accusation_form.add_object('Clear', Button('Clear', accusation_form.clear, ())) form_input = accusation_form.run(screen) if accusation_form._skip: return {} elif disproving and len(form_input) == 0: return None elif not disproving and len(form_input) != 3: return None return form_input
from CardDeck import CardDeck import sys import json import time import os # Deck attribute defined to Store and track list of cards while playing the game. deck = [] # Player Objects define. We need two players player1 = Player() player2 = Player() # Created and instance of UserManagement userMgmt = UserManagement() # Created and instance of CardDeck, which returns deck of cards cd = CardDeck() # Main function to start the game. Checks to see if two players are avalable in the game. If not, the game will not proceed. def startGame(): # Checks to see if player1 is defined if not player1.name: print("\n ###### WELCOME ###### \n") print(" 1. To play the game, ensure you're logged in\n") print(" 2. Choose register Option, if not already registered\n ") print(" 3. Type login or register to begin\n") print(" 4. Want to quit the game, type quit\n") if not player1.name and not player2.name: choice = input("Enter Your Choice: ") if len(choice) > 0:
def __init__(self): self.endGame = False self.playerScore = 0 self.dealerScore = 0 self.cardDeck = CardDeck() # the game holds a deck of cards.
""" Schwimmen - Card Game The main class creates all objects to start the game. The game will be executed in a while loop which will be terminated when the user's life has reached 0 or when both of the opponents's life have reached 0. """ from CardDeck import CardDeck from User import User from Opponent import Opponent from Pool import Pool from Game import Game # Create a card deck, user, 2 x opponent, a pool and a game object carddeck = CardDeck() # Merges Suits and Numbers carddeck.merge_suits_numbers() # Initialize objects by giving them names and card deck lists user = User("User", carddeck.card_deck) opponent = Opponent("Opponent", carddeck.card_deck) opponent2 = Opponent("Opponent2", carddeck.card_deck) pool = Pool("Pool", carddeck.card_deck) game = Game() # The game will be executed as long as the user's life has not reached 0 while user.life > 0: # Display life points, cards in the pool and user cards print("-" * 75, "\n") print(
class ClueLessServer(PodSixNet.Server.Server,ClueLessGame): channelClass = ClientChannel def __init__(self, *args, **kwargs): PodSixNet.Server.Server.__init__(self, *args, **kwargs) self.currentIndex=-1 print "STARTING UP THE SERVER" self.card_deck = CardDeck() self.confidential_card_types = ['character','weapon','room'] self.confidential_file = [] self.character_index_names = {0:"Mr. Green",1:"Miss Scarlett",2:"Mrs. Peacock"} self.character_indexes = dict((y,x) for x,y in self.character_index_names.iteritems()) self.minPlayers = 3 # Minimum number of players to play the game self.active_turn = 0 self.disprove_turn = 0 self.playerChannels = [] self.disproved_response = [] self.select_confidential_cards() def check_confidential_file(self,card_list): print "self.confidential_file: ", self.confidential_file print "final accusation: ", card_list if len(set(self.confidential_file).difference(set(card_list))) == 0: return True print "difference: ", set(self.confidential_file).difference(set(card_list)) return False def make_final_accusation(self,data): cards = data['cards'] playerId = data['playerId'] player = self.playerChannels[playerId] isWinner = self.check_confidential_file(cards.values()) if isWinner: player.Send({"action":"winner"}) for x in xrange(len(self.playerChannels)): if x == playerId: continue player = self.playerChannels[x] player.Send({"action":"loser"}) else: player.Send({"action":"loser"}) for x in xrange(len(self.playerChannels)): if x == playerId: continue player = self.playerChannels[x] player.Send({"action":"endgame"}) def make_suggestion(self,data): """ Notify all users of all the suggestion """ print "MAKING SUGGESTION ON SERVER WITH DATA: ", data cards = data['cards'] playerId = data['playerId'] spotArrayIndex = data['spotArrayIndex'] self.broadcast_suggestion(cards,playerId) self.force_disproval(cards,playerId) #self.move_accused_player(cards,spotArrayIndex) def move_accused_player(self,cards,spotArrayIndex): cards = cards.values() print "accused cards: ", cards if len(set(cards).intersection(set(self.character_index_names.values()))) > 0: char_card = list(set(cards).intersection(set(self.character_index_names.values())))[0] player_index = self.character_indexes[char_card] player = self.playerChannels[player_index] player.Send({"action":"movePlayer","spotArrayIndex":spotArrayIndex}) def disproved(self,data): cards = data['cards'] print "CARDS: ", cards if cards == False: self.disproved_response.append(False) else: card_names = cards.values() self.disproved_response.extend(card_names) print "NEW DISPROVED_RESPONSE: ", self.disproved_response def force_disproval(self,cards,playerId): disprovedCards = False tracker = [playerId] nextPlayerId = playerId+1 if playerId < len(self.playerChannels)-1 else 0 print "PlayerId who just made suggestion: ", playerId while len(tracker) < len(self.playerChannels): print "nextPlayerId: ", nextPlayerId player = self.playerChannels[nextPlayerId] player.Send({"action":"forceDisproval","cards":cards}) disprovedCards = self.get_disproval_response() if disprovedCards: break tracker.append(nextPlayerId) nextPlayerId = nextPlayerId+1 if nextPlayerId < len(self.playerChannels)-1 else 0 player = self.playerChannels[playerId] if disprovedCards: player.Send({"action":"isDisproved","cards":disprovedCards}) else: player.Send({"action":"notDisproved"}) def get_disproval_response(self): self.disproved_response = [] while len(self.disproved_response) == 0: self.tick() time.sleep(0.01) if False in self.disproved_response: return False else: return self.disproved_response def broadcast_suggestion(self,cards,playerId): for x in xrange(len(self.playerChannels)): if x == playerId: continue print "Broadcasting suggestion for Player: ", x player = self.playerChannels[x] player.Send({"action":"newSuggestion","cards":cards}) def Connected(self, channel, addr): self.currentIndex+=1 print "new connection index for player: ", self.currentIndex channel.gameid=self.currentIndex channel.Send({"action":"setId","ID":self.currentIndex}) self.add_player(channel) def close(self, gameid): try: game = [a for a in self.games if a.gameid==gameid][0] game.player0.Send({"action":"close"}) game.player1.Send({"action":"close"}) except: pass def tick(self): # Check for any wins # Loop through all of the squares self.Pump() def select_confidential_cards(self): """ This function selects cards from the confidential file""" """ for cardtype in self.confidential_card_types: self.confidential_file.append(self.card_deck.get_random_card(cardtype).get_name()) """ for cardname in ['Miss Scarlett','Ballroom','Revolver']: card = self.card_deck.get_card(cardname) self.confidential_file.append(card.get_name()) print "FINAL CONFIDENTIAL FILE CARDS: ", self.confidential_file def add_player(self,playerChannel): """ This function adds another player to the game""" self.playerChannels.append(playerChannel) if len(self.playerChannels) >= self.minPlayers: self.startGame() def startGame(self): print "STARTING GAME FROM SERVER!" assigned_characters,assigned_cards = self.distribute_cards() #self.active_turn = random.choice(xrange(len(self.playerChannels))) self.active_turn = 0 for x in xrange(len(self.playerChannels)): player = self.playerChannels[x] player_character = assigned_characters[x].get_name() player_cards = [card.get_name() for card in assigned_cards[x]] print "player: ", x print "has cards: ", player_cards player.Send({"action":"startgame","youAre":x,"turn":self.active_turn,"character":player_character,"cards":player_cards,'numplayers':len(self.playerChannels)}) def distribute_cards(self): """ This function iterates through the card deck, randomly assigns players a character, and the rest of cards in the deck """ card_tracker = [] + self.confidential_file assigned_chars = [] # Assigned character for each player assigned_cards = [[] for x in xrange(len(self.playerChannels))] # Assigned cards for each player for x in xrange(len(self.playerChannels)): player = self.playerChannels[x] #char_card = self.card_deck.get_random_card("character",card_tracker) char_card = self.card_deck.get_card(self.character_index_names[x]) #card_tracker.append(char_card) assigned_chars.append(char_card) print "player: ", x, "is: ", char_card.get_name() print "card_tracker: ", card_tracker print "confidential file: ", self.confidential_file assigned_card_names= ([["Prof. Plum","Kitchen","Library","Wrench","Lead Pipe","Dagger"], ["Mr. Green","Mrs. White"," Rope","Conservatory","Lounge","Hall"], ["Mrs. Peacock","Col. Mustard","Dagger","Candlestick","Dining Room","Billiard Room"] ]) for x in xrange(len(assigned_card_names)): allcards = [] for cardname in assigned_card_names[x]: card = self.card_deck.get_card(cardname) if not card: print "ERROR COULD NOT FIND: ", cardname allcards.append(card) assigned_cards[x] = allcards print "final assigned_chars: ", assigned_chars print "final assigned_cards: ", assigned_cards return assigned_chars,assigned_cards def increment_active_turn(self): self.active_turn = self.active_turn+1 if self.active_turn < len(self.playerChannels)-1 else 0 def updateTurn(self): self.increment_active_turn() for x in xrange(len(self.playerChannels)): player = self.playerChannels[x] player.Send({"action":"updateTurn","turn":self.active_turn}) def endGame(self): for player in self.playerChannels: player.Send({"action":"endGame"}) def update_playerMove(self,spotArrayIndex,playerId): for x in xrange(len(self.playerChannels)): #if x == playerId: continue # skip the previous active players update player = self.playerChannels[x] player.Send({"action":"movePlayer","spotArrayIndex":spotArrayIndex}) self.updateTurn()
def __init__(self): self.deck = CardDeck()
class Evaluator: def __init__(self): self.deck = CardDeck() # Group a set of cards by value def gen_value_groups(self,cards): new_cards = self.copy_cards(cards) return self.sorted_partition(new_cards,elem_prop = (lambda c: self.deck.card_value(c))) # Group a set of cards by suit def gen_suit_groups(self, cards): new_cards = self.copy_cards(cards) return self.sorted_partition(new_cards,elem_prop = (lambda c: self.deck.card_suit(c))) # Sort a set of cards in ascending or descending order, based on the card value (e.g. 3,7,queen,ace, etc.) def gen_ordered_cards(self, cards, dir = 'increase'): new_cards = self.copy_cards(cards) self.kd_sort(new_cards,prop_func=(lambda c: self.deck.card_value(c)),dir = dir) return new_cards # Sorting cards # Auxiliary funcs copied from prims/prims1.py def find_list_item(self, L,item,key=(lambda x: x)): for x in L: if item == key(x): return x def kd_sort(self, elems, prop_func = (lambda x: x), dir = 'increase'): elems.sort(key=prop_func) # default of the sort func is increasing order if dir =='decrease' or dir =='decr': elems.reverse() # This groups a set of elements by shared values of a specified property (which is determined by # prop_func), where the equality of two values is determined by eq_func. For example, this might # be used to group a set of cards by card-value. Then all the 5's would be returned as one group, all # the queens as another, etc. def partition(self, elems, prop_func = (lambda x:x), eq_func = (lambda x,y: x == y)): self.kd_sort(elems,prop_func=prop_func) partition = [] subset = False last_key = False for elem in elems: new_key = apply(prop_func, [elem]) if not(subset) or not(apply(eq_func,[last_key,new_key])): if subset: partition.append(subset) subset = [elem] last_key = new_key else: subset.append(elem) if subset: partition.append(subset) return partition # This partitions elements and then sorts the groups by the subset_prop function, which defaults to group size. # Thus, using the defaults, the largest groups would be at the beginning of the sorted partition. def sorted_partition(self, elems,elem_prop = (lambda x:x), subset_prop = (lambda ss: len(ss)), eq_func = (lambda x,y: x ==y), dir = "decrease"): p = self.partition(elems,prop_func = elem_prop, eq_func = eq_func) self.kd_sort(p,prop_func = subset_prop,dir = dir) return p def sort_cards(self, cards, prop_func = (lambda c: c[0]), dir = 'decrease'): self.kd_sort(cards,prop_func=prop_func,dir=dir) # This is the most important function in this file. It takes a set of cards and computes # their power rating, which is a list of integers, the first of which indicates the type of # hand: 9 - straight flush, 8 - 4 of a kind, 7 - full house, 6 - flush, 5 - straight, 4 - 3 of kind # 3 - two pair, 2 - one pair, 1 - high card. The remaining integers are tie-breaker information # required in cases where, for example, two players both have a full house. def calc_cards_power (self, cards, target_len = 5): def has_len (length, items): return length == len(items) vgroups = self.gen_value_groups(cards) flush = self.find_flush(cards, target_len = target_len) if flush: str_in_flush = self.find_straight(flush,target_len = target_len) if flush and str_in_flush: return self.calc_straight_flush_power(str_in_flush) elif has_len(4, vgroups[0]): return self.calc_4_kind_power(vgroups) elif has_len(3, vgroups[0]) and len(vgroups) > 1 and len(vgroups[1]) >= 2: return self.calc_full_house_power(vgroups) elif flush: return self.calc_simple_flush_power(flush) else: straight = self.find_straight(cards) if straight: return self.calc_straight_power(straight) elif has_len(3,vgroups[0]): return self.calc_3_kind_power(vgroups) elif has_len(2,vgroups[0]): if len(vgroups) > 1 and has_len(2,vgroups[1]): return self.calc_2_pair_power(vgroups) else: return self.calc_pair_power(vgroups) else: return self.calc_high_card_power(cards) def card_power_greater(self, p1,p2): # Both are power ratings = lists of power integers returned by calc_cards_power if not(p1) or not(p2): return False elif p1[0] == p2[0]: return self.card_power_greater(p1[1:],p2[1:]) elif p1[0] > p2[0]: return True else: return False # Functions for finding flushes and straights in a set of cards (of any length) def find_flush(self, cards, target_len = 5): sgroups = self.gen_suit_groups(cards) if len(sgroups[0]) >= target_len: return sgroups[0] else: return False def find_straight(self, cards, target_len = 5): ace = self.find_list_item(cards,14,key=(lambda c: self.deck.card_value(c))) scards = self.gen_ordered_cards(cards, dir = 'decrease') def scan(cards, straight): if len(straight) == target_len: return straight elif ace and 2 == self.deck.card_value(straight[0]) and len(straight) == target_len - 1: return [ace] + straight elif not(cards): return False # null check is late since variable 'cards not involved in 1st 2 cases c = cards.pop(0) if self.deck.card_value(c) == (self.deck.card_value(straight[0]) - 1): return scan(cards,[c] + straight) elif self.deck.card_value(c) == self.deck.card_value(straight[0]): return scan(cards,straight) else: # Broken straight, so start again with the current card return scan(cards,[c]) top_card = scards.pop(0) return scan(scards,[top_card]) # Simple auxiliary function for finding and sorting all card values in a set of card groups, and then returning # the largest 'count of them. def max_group_vals(self, groups,count): vals = [self.deck.card_value(g[0]) for g in groups] self.kd_sort(vals,dir='decrease') return vals[0:count] # Straights are presumably sorted in ASCENDING order def calc_straight_flush_power(self, straight): return [9,self.deck.card_value(straight[-1])] def calc_4_kind_power(self, value_groups): return [8,self.deck.card_value(value_groups[0][0])] + self.max_group_vals(value_groups[1:],1) def calc_full_house_power(self, value_groups): return [7] + [self.deck.card_value(vg[0]) for vg in value_groups[0:2]] def calc_simple_flush_power(self, flush, target_len = 5): new_flush = self.copy_cards(flush) self.sort_cards(new_flush) return [6] + [self.deck.card_value(c) for c in new_flush[0:target_len]] def calc_straight_power(self, straight): return [5,self.deck.card_value(straight[-1])] def calc_3_kind_power(self, value_groups): return [4,self.deck.card_value(value_groups[0][0])] + self.max_group_vals(value_groups[1:],2) def calc_2_pair_power(self, value_groups): return [3,self.deck.card_value(value_groups[0][0]),self.deck.card_value(value_groups[1][0])] + self.max_group_vals(value_groups[2:],1) def calc_pair_power(self, value_groups): return [2,self.deck.card_value(value_groups[0][0])] + self.max_group_vals(value_groups[1:],3) def calc_high_card_power(self, cards): ocards = self.gen_ordered_cards(cards,dir='decrease') return [1] + [self.deck.card_value(c) for c in ocards][0:5] # The basic card data structure: a 2-element list def card_eq (self, c1, c2): return self.deck.card_value(c1) == self.deck.card_value(c2) and self.deck.card_suit(c1) == self.deck.card_suit(c2) def copy_card(self, c): return self.deck.create_card(self.deck.card_value(c),self.deck.card_suit(c)) def copy_cards(self, cards): return [self.copy_card(c) for c in cards] # Main routine for testing the generation and classification (via power ratings) of many poker hands. def power_test(self, hands, hand_size = 7): for i in range(hands): deck = self.card_deck() cards = deck.deal_n_cards(hand_size) print "Hand: " , self.card_names(cards), ' Power: ', self.calc_cards_power(cards)
def main(): cards = CardDeck() cards.ShowCards() cards.GiveCard() cards.Give5Card()
def reset_card_deck(self): self.stack = CardDeck()
model.compile(loss='binary_crossentropy', optimizer='sgd') log_str += 'Neural Network has been built\n' else: model = keras.models.load_model( 'C:/Users/akami/Documents/GitHub/Projects/BlackJackNeuralNetwork/TrainingData/GenerationFiles/ModelFiles/epoch_' + str(epoch_num) + '.h5') model.fit(train_X, train_Y, epochs=32, batch_size=256, verbose=1) model.save( 'C:/Users/akami/Documents/GitHub/Projects/BlackJackNeuralNetwork/TrainingData/GenerationFiles/ModelFiles/epoch_' + str(epoch_num) + '.h5') log_str += 'Neural Network has been trained\nThere will be ' + str( num_scenario) + ' ran\n===============================\n\n' log.printString(log_str, log_path, access='w') cardDeck = CardDeck(num_decks) TotalCount = 0 scenarios = [] df_out = pd.DataFrame() for i in range(num_scenario): log_str = 'Scenario ' + str( i) + ':\n==============================================\n' if (cardDeck.NumDeck * 52) - cardDeck.currentCard >= 20: cardDeck.shuffleCards() TotalCount = 0 log_str += '\t- Deck Shuffled\n' log.printString(log_str, log_path, access='a')
class Game: def __init__(self): self.endGame = False self.playerScore = 0 self.dealerScore = 0 self.cardDeck = CardDeck() # the game holds a deck of cards. def __hitOrStay(self): while True: try: playerInput = input('Do you want to hit(h) or stay(s)? ') if (playerInput == 'h' or playerInput == 's'): break else: print('Please enter a valid input') except: print('Please enter a valid input') finally: return playerInput def __addOneOrEleven(self): inp = 1 while True: try: inp = int(input('Add one(1) or eleven(11)? ')) if (inp == 1 or inp == 11): break except: print('Please input a valid input (1 or 11) ') return inp def __playerTurn(self): # get next card and add to player score card = self.cardDeck.getACard() # if the next card is Ace, and both 1 and 11 fit in the score ask the player whether to treat is as 1 or 11 print(f'The card drawn is {self.cardDeck.getName(card[0], card[1])}') if (card[1] == 1 and self.playerScore <= 10): self.playerScore += self.__addOneOrEleven() elif (card[1] >= 10): self.playerScore += 10 else: self.playerScore += card[1] print(f'Your current score is {self.playerScore}.\n') # if the score is beyond 21 - player loses - bust. if (self.playerScore > 21): print(f". That's a bust! You lose.") self.endGame = True if (self.playerScore == 21): print(f"BLACKJACK!! You Win!!") self.endGame = True def __dealerTurn(self): print(f'Alright your final score is {self.playerScore}.\n') print('The dealer is going to start drawing now!') while (self.dealerScore <= self.playerScore): time.sleep(3) print('Dealer hits') card = self.cardDeck.getACard() print( f'The card drawn is {self.cardDeck.getName(card[0], card[1])}') if (card[1] == 1): if (self.dealerScore <= 10): self.dealerScore += 11 else: self.dealerScore += 1 elif (card[1] >= 10): self.dealerScore += 10 else: self.dealerScore += card[1] print(f'Current dealer score is {self.dealerScore}.\n') if (self.dealerScore > 21): print(f'The dealer has busted! You Win!!') self.endGame = True elif (self.dealerScore > self.playerScore): print(f'The dealer wins. You lose.') self.endGame = True def run(self): # first - we need to decide whose turn it is. while True: if self.endGame: break playerInput = self.__hitOrStay() if playerInput == 'h': #hit self.__playerTurn() elif playerInput == 's': #stay self.__dealerTurn()