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 make_pile(): """Create a pile of cards containing the ace of hearts and the five of clubs""" p = Pile([ Card(Faces.ACE, Suits.HEARTS), Card(Faces.FIVE, Suits.CLUBS), ]) print(p)
def pile_difference(): """Take the difference of two piles of sets""" p1 = Pile([ Card(Faces.ACE, Suits.HEARTS), Card(Faces.FIVE, Suits.CLUBS), ]) p2 = Pile([ Card(Faces.FIVE, Suits.CLUBS), ]) print(p1 - p2)
def insert_peek_and_pop(): """Peek and pop from the head of a pile""" p1 = Pile([ Card(Faces.ACE, Suits.HEARTS), Card(Faces.FIVE, Suits.CLUBS), ]) print(p1) p1.insert(Card(Faces.JACK, Suits.SPADES)) print(p1) print(p1.peek()) print(p1) print(p1.pop()) print(p1)
def createDeck(): """ Create and return shuffled deck as array of cards.""" Deck = [] face_values = ["A", "J", "Q", "K"] suit_list = ["Hearts", "Diamonds", "Spades", "Clubs"] for suit in suit_list: for num_val in range(2, 11): Deck.append(Card(str(num_val), num_val)) for face_val in face_values: Deck.append(Card(face_val, Card.face_card_dict.get(face_val))) shuffle(Deck) return Deck
def testFlushComparators(self): trick_suit = 's' trump_card = Card('h', 'A') tests = [ ([Card('d', 'K')], [Card('d', 'K')]), ] for test in tests: cards1, cards2 = test flush1 = Flush(cards_to_tractors(cards1, trick_suit, trump_card)) flush2 = Flush(cards_to_tractors(cards2, trick_suit, trump_card)) self.assertFalse(flush1 > flush2 or flush2 > flush1 or flush1 < flush2 or flush2 < flush1) self.assertTrue(flush1 == flush2)
def test_upadte_nobles(self): b = Board(2) noble = b.nobles[0] player = Player(1) for i in range(10): player.cards.add(Card(i, 1, Gem.RED, 0, {})) player.cards.add(Card(i, 1, Gem.GREEN, 0, {})) player.cards.add(Card(i, 1, Gem.BLUE, 0, {})) player.cards.add(Card(i, 1, Gem.WHITE, 0, {})) player.cards.add(Card(i, 1, Gem.BLACK, 0, {})) b._check_and_update_nobles(player) self.assertEqual(len(player.nobles), 1) self.assertEqual(next(iter(player.nobles)), noble)
def testJokerTrump(self): # Card('joker', '8') object represents the trump suit and value, not an actual card trump_card = Card('joker', '8') want = tractor_generator(self.joker_8_trump_tractor_data, trump_card) self.assertEqual( cards_to_tractors(self.test_cards, self.trick_suit, trump_card), want)
def registr_kard4(message): cvv = message.text if cvv.isdigit() and len(cvv) == 3: card.cvv = cvv new_card = Card(user_id_fk=card.id, card_number=card.number, card_name=card.name, card_date=card.date, card_cvv=card.cvv) session.add(new_card) session.commit() user.state = 2 botuseon.send_message(message.from_user.id, 'CVV записаний. Дякуємо за повну реєстрацію', reply_markup=keyboard5) elif message.text.lower() == 'назад': if user.state != 2: botuseon.send_message(message.from_user.id, 'Оберіть дію', reply_markup=keyboard2) else: botuseon.send_message(message.from_user.id, 'Оберіть дію', reply_markup=keyboard5) else: botuseon.send_message(message.from_user.id, 'Введіть корректний <b>CVV/CVV2</b> код.', parse_mode='html') botuseon.register_next_step_handler(message, registr_kard4)
def cardify(id): card = DB.query(Card).filter_by(multiverse_id = id).first() if card: return card card = Card(multiverse_id=id, name = get_card_name(id)) DB.add(card) DB.commit() return card
def testJokerTrump(self): trump_card = Card('joker', 'A') lesser_flush = Flush( cards_to_tractors(self.joker_A_trump_flush_order['lesser'], self.trick_suit, trump_card)) greater_flush = Flush( cards_to_tractors(self.joker_A_trump_flush_order['greater'], self.trick_suit, trump_card)) self.assertLess(lesser_flush, greater_flush)
def input_card(): """Take user input of a card's typeable name, and get the relevant card object""" while True: inp = str(input("Enter the typeable name of a card: ")) card = Card.get_from_typeable_name(inp) if card is not None: break print(card)
def testJokerTrump(self): trump_card = Card('joker', 'A') flush_1 = Flush( cards_to_tractors(self.joker_A_trump_flush_data['flush_1'], self.trick_suit, trump_card)) flush_2 = Flush( cards_to_tractors(self.joker_A_trump_flush_data['flush_2'], self.trick_suit, trump_card)) self.assertEqual(flush_1 == flush_2, self.joker_A_trump_flush_data['is_equal'])
def cards_from_str(s): if isinstance(s, list): return s if s is None: return s cards = [] parts = s.split(' ') explicit_map = { 'smalljoker': Card('joker', 'small'), 'bigjoker': Card('joker', 'big'), } for part in parts: if part in explicit_map: cards.append(explicit_map[part]) continue suit = part[-1] value = part[:-1] cards.append(Card(suit, value)) return cards
def test_compare(): # check_hand( # [Card(9,3), Card(10, 2), Card(12, 4)], hands.HIGH_CARD # ) assert HandScoring.compare_hands(set([Card(10, 1)]), set([Card(10, 2)])) == 0 assert HandScoring.compare_hands(set([Card(10, 1), Card(10, 3)]), set([Card(10, 2)])) == 1 assert HandScoring.compare_hands(set([Card(10, 1), Card(9, 1)]), set([Card(10, 2)])) == 0
def add_card(): """Add a new card to the DB.""" name = request.form.get('name') skill = request.form.get('skill') new_card = Card(name=name, skill=skill) db.session.add(new_card) db.session.commit() return jsonify({"success": True})
def download_cardbox(_id: str): box = CardBox.fetch(db, _id) if not box: abort(404) content = Card.fetch_content_to_list(db, _id) vars_box = vars(box) vars_box['content'] = content # use flask jsonify to create valid json response return jsonify(vars_box)
def add_card(): """Add a new card to the DB.""" name = request.get_json().get('name') skill = request.get_json().get('skill') new_card = Card(name=name, skill=skill) db.session.add(new_card) db.session.commit() # the new_card variable we created on line 35 did not have its card_id set # we call db.session.refresh(new_card) to update the variable to the version from the database # that way, its card_id will be set db.session.refresh(new_card) return {"success": True, "cardAdded": {"skill": new_card.skill, "name": new_card.name, "imgUrl": new_card.image_url, "cardId": new_card.card_id}}
def save_new_card(): """This route view recieves card information using Post method, stores it in database and returns json response""" newCard = request.get_json() user_id = get_user_id() fname = newCard.get('fname') lname = newCard.get('lname') phone_list = newCard.get('phone_number') email_list = newCard.get('email_id') jobTitle = newCard.get('jobTitle') company = newCard.get('company') description = newCard.get('description') isCompany = CompanyInfo.query.filter(CompanyInfo.company_name == company).first() if isCompany is None: c_id = db.session.add(CompanyInfo(company_name = company)) db.session.commit() company_data = CompanyInfo.query.filter(CompanyInfo.company_name == company).first() db.session.add(Card(user_id = user_id, first_name = fname, last_name = lname, company_id = company_data.company_id, job_title = jobTitle, discription = description)) db.session.commit() card = Card.query.filter(Card.user_id == user_id).order_by(Card.card_id.desc()).first() for phone in phone_list: db.session.add(PhoneInfo(card_id = card.card_id, phone_number = phone['phone_num'])) for email in email_list: db.session.add(EmailInfo(card_id = card.card_id, email_id = email['email_id'])) db.session.commit() # # client = Client(account_sid, auth_token) message = client.messages \ .create( body=f'{fname} {lname} has been added successfully.', from_='+12066732998', to='+12139521102' ) return jsonify({'message': 'Success','status':200})
def card_submission(): """Allows user to enter in credit card info and then sends user inuptted info to dashboard""" if request.method == 'POST': # print "This is our request object", request.form names = request.form.getlist("card1_name[]") # print "This is name", names # print names[0] debts = request.form.getlist("card1_debt[]") aprs = request.form.getlist("card1_apr[]") dates = request.form.getlist("card1_date[]") # session.get user_id = session.get("user_id") min_payment = session.get("min_payment") # print "Name", names # print "Debt", debts # print "APR", aprs # print "Date", dates # print "Min Payment", min_payment # print "This is the session", session # print "user id", user_id for i in range(len(names)): # print "Name", names[i] # print "Debt", debts[i] # print "APR", aprs[i] # print "Date", dates[i] # print "Min Payment", min_payment # print "This is the session", session # print "user id", user_id card = Card.query.filter_by(user_id=user_id).all() if card == None: flash("In order to generate a payment plan for you we need some information on your current debts. ") else: new_card = Card(card_name = names[i], card_debt = debts[i], card_apr = aprs[i], card_date = dates[i], min_payment=min_payment, user_id = user_id) db.session.add(new_card) db.session.commit() flash("Thank you for entering this information! We've calculated your payment plan:") return redirect(url_for('dashboard'))
def feud(hands, pots): #the function will return a vector with the values that have to be added to each #player's stack winnings = [0 for i in range(MAX_PLAYERS)] for pot in pots: act_sum = pot.sum #we want to establish who has the best hand for this pot best_hand = [ Card(1 // 13, 1 % 13), Card(2 // 13, 2 % 13), Card(3 // 13, 3 % 13), Card(4 // 13, 4 % 13), Card(19 // 13, 19 % 13) ] #we initialize it with the worst possible hand for i in range(len(pot.active_players)): if pot.active_players[i] == 1 and HandCompare(hands[i], best_hand) == 1: best_hand = hands[i] #we decide in how many ways we should split the pot winners = 0 for i in range(len(pot.active_players)): if pot.active_players[i] == 1 and HandCompare(hands[i], best_hand) == -1: winners += 1 #then we give each player what he deserves for i in range(len(pot.active_players)): if pot.active_players[i] == 1 and HandCompare(hands[i], best_hand) == -1: winnings[i] += act_sum / winners return winnings
def aquireCardList(self): if os.path.isfile(FILENAME_CARDS_LIST): print "loading cards from file..." with open(FILENAME_CARDS_LIST) as file: self.__cards = pickle.load(file) else: mechanics = self.aquireMechanics() print "aquiring cards from database..." rows = self.execute("SELECT * FROM cards WHERE collectible = 1 AND type_name != 'Hero' AND mana IS NOT NULL") print "processing aquired cards..." self.__cards = {} for row in rows: card = Card(id=row['id'],name=row['name'],type=Dao.strCardTypeToEnum(row['type_name']),isClassCard=not row['klass_id'] is None,rarity=row['rarity_id'],manacost=row['mana'],attack=row['attack'],health=row['health']) if card.id in mechanics: card.mechanics = mechanics[card.id] self.__cards[card.id] = card print "dumping cards to file..." with open(FILENAME_CARDS_LIST,'w') as file: pickle.dump(self.__cards, file,pickle.HIGHEST_PROTOCOL) return utils.dictValues(self.__cards)
def compute_best_hand(self): if len(self.cards)==5: return self.cards if len(self.cards)==6: best_hand = [Card(1 // 13, 1 % 13), Card(2 // 13, 2 % 13), Card(3 // 13, 3 % 13), Card(4 // 13, 4 % 13), Card(19 // 13, 19 % 13)] for i in range(6): new_contender =[] for j in range(6): if j!=i: new_contender.append(self.cards[j]) if HandCompare(new_contender, best_hand)==1: best_hand = new_contender return best_hand if len(self.cards)==7: best_hand = [Card(1 // 13, 1 % 13), Card(2 // 13, 2 % 13), Card(3 // 13, 3 % 13), Card(4 // 13, 4 % 13), Card(19 // 13, 19 % 13)] for i in range(7): for h in range(7): if h!=i: new_contender = [] for j in range(7): if j != i and j != h: new_contender.append(self.cards[j]) if HandCompare(new_contender, best_hand) == 1: best_hand = new_contender return best_hand
def set_card(): json_data = request.get_json() if json_data: name = json_data.get('full_name') if name: client = User(name=name) db.session.add(client) db.session.commit() card = Card(user_id=client.id, bonus=0, level=0) db.session.add(card) db.session.commit() return jsonify(id=card.id), 201 else: return jsonify(msg='Not full_name'), 400 else: return jsonify(msg='Bad json'), 400
def _load_all_cards(self): '''Loads all development cards from CSV file''' fo = open('config/cards.csv') reader = csv.reader(fo) next(reader, None) # skip header id = 0 for _ in range(3): self.all_cards.append([]) for line in reader: assert len(line) == 8 level = int(line[0]) assert (level >= 1 and level <= 3) card = Card( id, level, Gem._value2member_map_[line[1]], int(line[2]), self._get_cost([gem for gem in Gem], line[3:])) self.all_cards[level - 1].append(card) self.cards_map[id] = card id += 1 fo.close()
def crawl(): url = get_crawl_url("01") print(url) r = retry_session().get(url) if r.status_code != requests.codes.ok: logging.error(f"failed to get url {url}") return result = r.json() card_list = result["card_set"]["card_list"] cards = [] for item in card_list: card = Card(card_id=item.get("card_id"), card_type=item.get("card_type"), card_name=item.get("card_name", {}).get("schinese"), rarity=item.get("rarity"), color=extract_card_color(item), item_def=item.get("item_def"), price=None) cards.append(card) return cards
def challenge(db, challenger_id, challenged_id, box_id): new_duel_id = gen_duel_id() box = CardBox.fetch(db, box_id) content = Card.fetch_content(db, box_id) vs_dict = dict(duel_id=new_duel_id, challenger=challenger_id, challenged=challenged_id, box_id=box_id, box_name=box.name, box_content=content, started=False, finish_time=None, winner='') db.hset(TABLE_VS, new_duel_id, json.dumps(vs_dict)) db.rpush(challenger_id + CHALLENGE_SUFFIX, new_duel_id) db.rpush(challenged_id + CHALLENGE_SUFFIX, new_duel_id) return new_duel_id
def load_cards(): """Loads cards in a deck into database.""" print 'Cards' # Delete all rows in table, so if we need to run this a second time, # we won't be trying to add duplicate cards. Card.query.delete() # Read cards file and insert data for line in open('cards.txt', 'rU'): line = line.rstrip() num, shade, shape, color = line.split('|') card = Card(number=num, shading=shade, shape=shape, color=color) # Add each card to the session db.session.add(card) # Commit at end db.session.commit()
def create_card(keyword, buzzword_1, buzzword_2, buzzword_3, buzzword_4, buzzword_5, room_id=None, player_created=False): """Create and return a new Taboo card""" card = Card(room_id=room_id, keyword=keyword, buzzword_1=buzzword_1, buzzword_2=buzzword_2, buzzword_3=buzzword_3, buzzword_4=buzzword_4, buzzword_5=buzzword_5, player_created=player_created) db.session.add(card) db.session.commit() return card
def test_can_afford(self): player = Player(0) card = Card(0, 1, Gem.GREEN, 0, { Gem.GREEN: 1, Gem.RED: 1, Gem.BLACK: 1 }) self.assertEqual(player.can_afford(card), False) player.set_gems({Gem.GREEN: 1, Gem.RED: 1, Gem.BLACK: 1}) self.assertEqual(player.can_afford(card), True) player.set_gems({Gem.GOLD: 3}) self.assertEqual(player.can_afford(card), True) player.set_gems({Gem.GOLD: 1, Gem.RED: 1, Gem.BLACK: 1}) self.assertEqual(player.can_afford(card), True) player.set_gems({Gem.GOLD: 1, Gem.RED: 1, Gem.BLACK: 0}) self.assertEqual(player.can_afford(card), False) player.set_gems({Gem.GOLD: 1, Gem.RED: 1, Gem.BLUE: 2}) self.assertEqual(player.can_afford(card), False)
def test_init(self): self.assertEqual(Card('c', '2').suit, 'c') self.assertEqual(Card('c', '2').level, '2')