def __init__(self, session): self.deck = Deck() self.deck.shuffle() self.layout = dict() self.selected = dict() self.requests = {} self.session = session self.scores = {client.id: 0 for client in self.session.clients} self.current_yeller = None self.reset_requests()
class ModelTester(unittest.TestCase): def setUp(self): '''Create the Model''' from model import Deck self.deckNoCards = Deck() self.deckCards = Deck("test.csv") def testEmptyDeck(self): self.assertEqual(self.deckNoCards.size(), 0) def testImportedDeck(self): self.assertEqual(self.deckCards.size(), 8)
def __init__(self): self.model = Model() self.view = View() # create selection matrix for filter # create top row of card ranks top_row = [SelectionItem('', is_top_left=True)] + [ SelectionItem(Card.ranks[rank], is_card=False, is_top_row=True) for rank in range(1, RANKS + 1) ] # create selection item for each card self.model.selection_matrix = [top_row] + [[ SelectionItem(str(Card(rank, suit)), card=Card(rank, suit)) for rank in range(1, RANKS + 1) ] for suit in range(1, SUITS + 1)] # add leftmost column for suits for i in range(1, len(self.model.selection_matrix)): self.model.selection_matrix[i] = [ SelectionItem(Card.suits[i], is_card=False) ] + self.model.selection_matrix[i] # deselect all for row in self.model.selection_matrix: for item in row: item.is_selected = False # initialize game state self.model.deck = Deck() self.model.player_hand = Hand() self.model.dealer_hand = Hand() self.model.drawn_cards = []
def initRound(self): self.deck = Deck() self.activePlayers = [0 for i in range(MAX_PLAYERS)] self.playersHands = [Hand([]) for i in range(MAX_PLAYERS)] self.activeBets = [0 for i in range(MAX_PLAYERS)] self.actedThisRound = [0 for i in range(MAX_PLAYERS)] self.money = [0 for i in range(MAX_PLAYERS)] for i in range(MAX_PLAYERS): self.players[i].holeCards = [] # calculate the remaining players and deal them the hole cards for i in range(MAX_PLAYERS): if self.players[i].stack != 0: self.activePlayers[i] = 1 self.blindIndex = int(self.roundsPlayed / HANDS_PER_ROUND) if self.blindIndex > len(BIG_BLINDS) - 1: self.blindIndex = len(BIG_BLINDS) - 1 if ( self.dealer == -1 ): self.dealer = 0 else: self.dealer = self.findNext(self.dealer) self.smallBlind = self.findNext(self.dealer) self.bigBlind = self.findNext(self.smallBlind) self.pots = [] self.pots.append(Pot(0, self.activePlayers.copy())) self.communityCards = [] self.flop = [] self.turn = [] self.river = []
def create_deck(deck_name, deck_type, number_of_cards): deck = Deck(deck_name=deck_name, deck_type=deck_type, number_of_cards=number_of_cards) db.session.add(deck) db.session.commit() return deck
def aquireDeckList(self,modes=[Modes.RANKED, Modes.CASUAL]): if not self.__cards: self.aquireCardList() if os.path.isfile(FILENAME_DECKS_LIST): print "loading decks from file..." with open(FILENAME_DECKS_LIST) as file: self.__decks = pickle.load(file) else: arenaWins, constructedsWins = self.aquireResults(modes) print "aquiring decks from database..." rows = self.execute("SELECT d.cardstring, d.klass_id, m.mode_id, count(m.id) FROM matches m, match_decks md, decks d WHERE m.id = md.match_id AND d.id = md.deck_id AND d.klass_id IS NOT NULL AND d.klass_id > 0 AND d.unique_deck_id IS NOT NULL AND m.mode_id in (" + ','.join(map(str,modes)) + ") AND d.cardstring REGEXP '^([0-9]+_[1-9],)*([0-9]+_[1-9])$' GROUP BY d.cardstring, m.mode_id") print "processing aquired decks..." self.__decks = {} for row in rows: cards = self.parseCardstring(row['cardstring']) uniqueCardString = Deck.cardstringOfCardsMap(cards) if uniqueCardString in self.__decks: deck = self.__decks[uniqueCardString] else: deck = Deck(row['klass_id']) deck.addCardsMap(cards) self.__decks[uniqueCardString] = deck if row['mode_id'] == Modes.ARENA : deck.nbArenaMatches += row['count(m.id)'] if row['cardstring'] in arenaWins: deck.nbArenaWins += arenaWins[row['cardstring']] else: deck.nbConstructedMatches += row['count(m.id)'] if row['cardstring'] in constructedsWins: deck.nbConstructedWins += constructedsWins[row['cardstring']] print "dumping decks to file..." with open(FILENAME_DECKS_LIST,'w') as file: pickle.dump(self.__decks, file,pickle.HIGHEST_PROTOCOL) return utils.dictValues(self.__decks)
def shuffle_and_sort(): """Create a deck, then shuffle it, then re-sort it""" d = Deck() print(d) d.shuffle() print(d) d.sort() print(d)
def play_game(ngames=100): verbose = ngames == 1 cost_of_hut = 0.05 cost_of_station = 3 ntrees = 9 ngardens = 3 ncurses = 3 """ IDEAL GAME SCENARIOS: selfish vs. selfish: RARELY WIN selfish vs. default: MOSTLY WIN -> SELFISH selfish vs. generous: ALWAYS WIN -> SELFISH generous vs. generous: RARELY WIN """ player_types = ["reasonable", "reasonable"] # # player_types = ["default", "generous"] # # player_types = ["super-selfish", "super-selfish"] # # player_types = ["selfish", "reasonable"] # # player_types = ["selfish", "selfish"] # # player_types = ["reasonable", "selfish"] # # player_types = ["selfish", "super-selfish"] # # player_types = ["super-selfish", "reasonable"] # # player_types = ["super-selfish", "generous"] # # player_types = ["selfish", "default"] # 8/10, all S # player_types = ["selfish", "generous"] # 5/10, all S # player_types = ["generous", "generous"] # 0/10 # player_types = ["reasonable", "reasonable"] # 0/10 board = Board((6, 6), { "hut": cost_of_hut, "station": cost_of_station }, ntrees=ntrees) deck = Deck({"garden": ngardens, "curse": ncurses}) g = Game(board, deck, verbose=verbose) ps = get_players(player_types) ss = [] ws = [] for i in xrange(ngames): status, winner = g.play(ps, print_end_status=False) ss.append(status) ws.append(winner) g.reset() import collections print '==================' print collections.Counter(ws) print collections.Counter(ss)
def parse(md): dealer = int(md[0:1]) if dealer < 1 or dealer > 4: raise Exception('Unexpected dealer: ' + md) hands = [] remaining_cards = Deck.cards() for hand_str in md[1:].split(','): if '' == hand_str: hands.append(Hand(remaining_cards)) else: hand = Hand.parse(hand_str) hands.append(hand) for card in hand.cards: remaining_cards.remove(card) if len(hands) != 4: raise Exception('Unexpected number of hands: ' + md) return VugraphMD(dealer, hands)
def deck_equality(): """Show two sets of equal contents are equal""" d = Deck() print(d is deepcopy(d))
def deal_hand(): """Deal 5 cards from the deck into 3 different hands""" d = Deck() hands = d.deal(3, 5) print(hands)
def test_deck(): d = Deck() assert len(d.cards) == 52
def test_cards(self): cards = Deck.cards() self.assertEqual(len(cards), 52) self.assertEqual(Card('c', '2'), cards[0]) self.assertEqual(Card('s', 'a'), cards[-1])
def init_deck(mashes): return Deck(mashes, 3)
def setUp(self): '''Create the Model''' from model import Deck self.deckNoCards = Deck() self.deckCards = Deck("test.csv")
class Game: BOARD_SHAPE = (3, 4) MAX_CARDS = 18 MAX_NORMAL = BOARD_SHAPE[0] * BOARD_SHAPE[1] DELAY = .1 SET_TIMEOUT = 5 SESSION_CALLS = ('remove', 'select', 'deselect', 'place', 'set_yelled', 'score_update', 'set_stolen', 'too_late', 'end_game', 'resume', 'more_requested') def __init__(self, session): self.deck = Deck() self.deck.shuffle() self.layout = dict() self.selected = dict() self.requests = {} self.session = session self.scores = {client.id: 0 for client in self.session.clients} self.current_yeller = None self.reset_requests() def has_set(self): for c1, c2, c3 in itertools.combinations(self.layout.values(), 3): if c1.third(c2) == c3: return True return False def reset_requests(self): for id in self.session.client_ids(): self.requests[id] = False @classmethod def iterxy(cls): for y in range(cls.BOARD_SHAPE[1]): for x in range(cls.BOARD_SHAPE[0]): yield x, y for ex_x in range(3): yield cls.BOARD_SHAPE[0], ex_x for ex_x in range(3): yield cls.BOARD_SHAPE[0] + 1, ex_x def request_more(self, client): self.requests[client.id] = True num_requested = len([r for r in self.requests.values() if r]) self.session.more_requested(client.id, num_requested, len(self.requests)) if all(self.requests.values()): self.place_three() self.reset_requests() def yell_set(self, client): if self.current_yeller is None: self.session.set_yelled(client.id) self.current_yeller = (client, time.time() + self.SET_TIMEOUT) self.requests[client.id] = False else: yeller, timeout = self.current_yeller if self.current_yeller != client: if time.time() > timeout: self.deselect_all() self.scores[yeller.id] -= 1 self.session.score_update(self.scores) self.session.set_stolen(client.id) self.current_yeller = (client, time.time() + self.TIMEOUT) self.requests[client.id] = False else: self.session.too_late(client.id, int(timeout - time.time())) def deselect_all(self): selected = copy.deepcopy(self.selected) for (x, y), card in selected.items(): self.deselect_card(card, x, y) self.selected.clear() def cards_remain(self): return self.deck.cards_remaining() > 0 def next_spot(self): for x, y in self.iterxy(): if self.card_at(x, y) is None: return x, y return None, None def card_at(self, x, y): return self.layout.get((x, y), None) def valid_card(self, card, x, y): card_at = self.card_at(x, y) if not card_at == card: log_warn("Card at %d %d is %s, not %s", x, y, card_at, card) return False return True def remove_card(self, card, x, y): if not self.valid_card(card, x, y): log_warn("Cannot remove card") return self.session.remove(card.properties, x, y) if (x, y) in self.selected: del self.selected[(x, y)] del self.layout[(x, y)] def select_card(self, card, x, y): if not self.valid_card(card, x, y): log_warn("Cannot select card") return self.session.select(card.properties, x, y) self.selected[(x, y)] = card def check_set(self, client): if len(self.selected) == 3 and is_set(*self.selected.values()): self.scores[client.id] += 1 self.session.score_update(self.scores) selected = copy.deepcopy(self.selected) for (x, y), card in selected.items(): self.remove_card(card, x, y) self.selected.clear() self.fill_board() self.reorganize() log("{} cards remaining".format(self.deck.cards_remaining())) log("Set present? {}".format(self.has_set())) if self.deck.cards_remaining() == 0 and not self.has_set(): self.session.end_game(self.scores) return True else: log("%d cards selected : not a set", len(self.selected)) self.scores[client.id] -= 1 self.session.score_update(self.scores) self.selected.clear() self.current_yeller = None self.session.resume() def place_three(self): for _ in range(3): self.place_next() def deselect_card(self, card, x, y): if not self.valid_card(card, x, y): log_warn("Cannot deselect card") return if not (x, y) in self.selected: log_warn("Deselecting non-selected card") else: del self.selected[(x, y)] self.session.deselect(card.properties, x, y) def place_card(self, card): if len(self.layout) == self.MAX_CARDS: log_warn("Attempted to place more than MAX_CARDS") return x, y = self.next_spot() if x is None: log_error("MAX_CARDS not placed but no next_spot available") return self.layout[(x, y)] = card self.session.place(card.properties, x, y) #time.sleep(self.DELAY) def place_next(self): if len(self.layout) == self.MAX_CARDS: log_warn("Cannot place more than %d cards", self.MAX_CARDS) return card = self.deck.draw() self.place_card(card) def fill_board(self): while self.cards_remain() and len(self.layout) < self.MAX_NORMAL: self.place_next() def iloc(self, i): for idx, (x, y) in enumerate(self.iterxy()): if idx == i: return x, y, self.card_at(x, y) def reorganize(self): for i in range(self.MAX_CARDS)[::-1]: if i < self.MAX_NORMAL: return x, y, c = self.iloc(i) if c is None: continue else: log("Reorganizing card %d", i) self.remove_card(c, x, y) self.place_card(c) updated = True def disconnect(self, client): self.session.end_game(self.scores, "Player {} exited early -- ".format(client.id)) return True
card_suit="Major_Arcana", card_image="/static/02_High_Priestess.jpg") card_fool = Card(card_name="fool", card_number="II", card_desc="Description of the fool", card_reversed_desc="Reversed fool", card_suit="Major_Arcana", card_image="/static/thefool.jpg") card_moon = Card(card_name="the moon", card_number="II", card_desc="Description of the moon", card_reversed_desc="Reversed moon", card_suit="Major_Arcana", card_image="/static/themoon.jpeg") deck_tarot = Deck(deck_name="Rider-Waite", deck_type="Tarot", number_of_cards=78) three_card_spread = Spread(spread_name="3 card", qty_cards_in_spread=3) amanda_user = User(user_name="Amanda2021") test_reading = Reading(reading_name="test") card_reading1 = CardReading(card_id=card_death.card_id, reading_id=test_reading.reading_id) db.session.add(card_empress) db.session.add(card_priestess) db.session.add(card_fool) db.session.add(deck_tarot)