def __init__(self): self.scores = {} self.player_names = [] self.hands = {} self.green_deck = Deck('green') self.green_deck.shuffle() self.red_deck = Deck('red') self.red_deck.shuffle()
def test_deck_random_shuffle(self) -> None: deck_1, deck_2 = Deck(), Deck() deck_1.shuffle() deck_2.shuffle() # This is technically a flaky test since both decks # could be identical, but the odds of this are 1 in 52!. self.assertNotEqual(deck_1.cards, deck_2.cards)
def test_deck_reshuffle_is_possible(self) -> None: deck_1, deck_2 = Deck(), Deck() seed = random.randint(0, 100000) deck_1.shuffle(seed) deck_2.shuffle(seed) # Shuffling twice should yield a different deck. # This is technically a flaky test but the odds of this test # failing despite functioning as intended is 1 in 52!. deck_2.shuffle(seed) self.assertNotEqual(deck_1.cards, deck_2.cards)
def test_decks_are_equal_only_if_their_cards_are_equally_ordered( self) -> None: deck_1 = Deck(cards=[ Card(suit=Suit.HEARTS, rank=Rank.ACE), Card(suit=Suit.CLUBS, rank=Rank.JACK), ]) deck_2 = Deck(cards=[ Card(suit=Suit.HEARTS, rank=Rank.ACE), Card(suit=Suit.CLUBS, rank=Rank.JACK), ]) self.assertEqual(deck_1, deck_2)
def test_deck_shuffle_with_seed(self) -> None: deck_1, deck_2, deck_3 = Deck(), Deck(), Deck() seed_1, seed_2 = random.randint(0, 100000), random.randint(0, 100000) deck_1.shuffle(seed_1) deck_2.shuffle(seed_1) deck_3.shuffle(seed_2) # Identical seeds must lead to identical shuffles. self.assertEqual(deck_1.cards, deck_2.cards) # Different seeds should lead to different shuffles. # This is technically a flaky test but the odds of this test # failing despite functioning as intended is 1 in 52!. self.assertNotEqual(deck_1.cards, deck_3.cards)
def newDeck(): if current_user.is_authenticated: try: deckid = uuid.uuid4().hex d = Deck( deckid=deckid, name=request.json['deckname'], author_public_name=request.json['author'] if 'author' in request.json else current_user.public_name, description=request.json['description'] if 'description' in request.json else '', author=current_user, inventory_type='', used_in_inventory={}, cards=request.json['cards'] if 'cards' in request.json else {}) db.session.add(d) db.session.commit() return jsonify({ 'new deck created': request.json['deckname'], 'deckid': deckid, }) except Exception: pass else: return jsonify({'Not logged in.'})
def join_game(gameName): if not current_user.is_authenticated: return redirect(url_for('login')) game = Game.query.filter_by(gamename=gameName).first() user = User.query.filter_by(username=current_user.username).first_or_404() if not bool(game): return "Sorry doesn't exist" if game.no_players == 1: if game.player1_id == user.id: pass else: game.player2_id = user.id game.player2_name = user.username game.no_players = 2 deck = Deck().deck gm = GameMove(game_id=game.id, turn_player_id=game.player1_id, turn_player_name=game.player1_name, player1_hand=" ".join(deck[:10]), player2_hand=" ".join(deck[10:20]), player_action="seed hand") db.session.add(gm) db.session.commit() else: if not (game.player1_id == user.id or game.player2_id == user.id): return "filled to capacity" gm = GameMove.query.filter_by(game_id=game.id).order_by(GameMove.id.desc()).first() bluff_query = request.form.get('bluffquery', " ") actual_query = request.form.get('actualquery', " ") actual_pattern = "^(((10|[0-9])|[AKQJ])[HCSD]\s)*(((10|[0-9])|[AKQJ])[HCSD])$" bluff_pattern = "^(10|[0-9])+ ((10|[0-9])|[AKQJ])$" game = Game.query.filter_by(gamename=gameName).first() gm = GameMove.query.filter_by(game_id=game.id).order_by(GameMove.id.desc()).first() actual_list = actual_query.split(" ") hand = return_hand(game, user) hand_list = hand.split(" ") if(get_turn(game) != user.id): return render_template("game_screen.html", user=user, hand=return_hand(game, user), gamename=game.gamename, game=game) if not (set(actual_list)).issubset(set(hand_list)): return render_template("game_screen.html", user=user, hand=return_hand(game, user), gamename=game.gamename, game=game) else: mod_hand = " ".join([h for h in hand_list if h not in actual_list]) if gm.player1_hand == hand: new_gm = GameMove(game_id=game.id, turn_player_id=user.id, turn_player_name=user.username, player1_hand=mod_hand, player2_hand=gm.player2_hand, player_action="play cards", cards_played=actual_query, cards_bluffed=bluff_query) else: new_gm = GameMove(game_id=game.id, turn_player_id=user.id, turn_player_name=user.username, player1_hand=gm.player1_hand, player2_hand=mod_hand, player_action="play cards", cards_played=actual_query, cards_bluffed=bluff_query) db.session.add(new_gm) db.session.commit() return render_template("game_screen.html", user=user, hand=return_hand(game, user), gamename=game.gamename, game=game)
def test_deck_initialisation(self) -> None: deck = Deck() # We assume a Piquet deck which has 32 cards. self.assertEqual(len(deck.cards), 32) # The collection of cards must be unique. self.assertEqual(len(set(deck.cards)), 32)
def save_deck_to_db(deck): if Deck.objects(Q(name=deck['name'])).first() is not None: return False new_deck = Deck(name=deck['name'], description=deck['description'], length=deck['length'], cards=deck['cards']) new_deck.save() return True
def generate_deck(): ''' Generates list of cards and stores it to model ''' deck = [a for a in CARD_SCORES.keys()] * 4 random.shuffle(deck, random.random) for card in deck: card = Deck(str(card)) db_session.add(card) save()
def test_a_deck_can_be_dealt(self) -> None: deck = Deck() players = [Player(), Player(), Player(), Player()] deck.deal(players) # The deck is fully depleted self.assertEqual(0, len(deck.cards)) for player in players: # Each player has the required amount of cards self.assertEqual(8, len(player.hand))
def test_doesnt_have_pairs(self): deck = Deck(custom_ranks={ "2": 2, "3": 3, "4": 4, "5": 5 }, custom_suits={"𓆏": "GREEN"}) self.assertTrue(deck.evaluator.has_pairs(1) is False)
def test_a_deck_cannot_be_dealt_if_not_evenly(self) -> None: deck = Deck() players = [Player(), Player(), Player()] # What we are testing is the scenario where the deck's cards cannot # be dealt evenly among the players, so we must assert it. self.assertNotEqual(len(deck.cards) % len(players), 0) # In this scenario, the method should throw a ValueError. self.assertRaises(ValueError, deck.deal, players)
def test_doesnt_have_flush(self): deck = Deck(custom_cards=[ Card(rank="3", rank_value=3, suit="𓆏", color="RED"), Card(rank="3", rank_value=3, suit="𓆏", color="RED"), Card(rank="3", rank_value=3, suit="𓆏", color="RED"), Card(rank="4", rank_value=4, suit="𓃰", color="BLACK"), Card(rank="K", rank_value=13, suit="𓃰", color="BLACK"), Card(rank="Q", rank_value=12, suit="𓃰", color="BLACK") ]) self.assertTrue(deck.evaluator.has_flush(4) is False)
def main(): # デッキを作成 deck = Deck() card_nums = [ 'A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'Joker' ] card_ranks = [12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14] card_suits = ['spade', 'heart', 'diamond', 'club'] card_mapping = {} for (num, rank) in zip(card_nums, card_ranks): card_mapping[num] = rank for rank in card_ranks[:13]: # デッキにJoker含むカード54枚を加える for suit in card_suits: card = Card(suit=suit, rank=rank) deck.cards.append(card) deck.cards.append(Card(suit='*', rank=card_mapping['Joker'])) deck.cards.append(Card(suit='*', rank=card_mapping['Joker'])) # print(len(deck.cards)) # for card in deck.cards: # print(card) # プレイヤー追加と初期設定 player1 = Player(name='player1') player2 = Player(name='player2') player1.doubt_pct = 0.35 player2.doubt_pct = 0.2 # 20ゲーム x 50回試行する result_p1 = [] for j in range(10): datum = [] for i in range(20): data = play_game(player1, player2, deck) datum.append([data[0].name, data[1]]) print('-' * 100) print('-' * 100) print('-' * 100) # スコアを集計 p1_score, p2_score = utils.calc_data(datum) result_p1.append(p1_score) print('player1のスコア: {} \nplayer2のスコア: {}'.format(p1_score, p2_score)) df = pd.DataFrame(data=result_p1, columns=['score']) print('##' * 50) print('合計: {} \n平均: {} \n分散: {}'.format(df['score'].sum(), df['score'].mean(), df['score'].var())) df.plot() plt.show()
def test_has_pairs(self): deck = Deck(custom_ranks={ "2": 2, "3": 3, "4": 4, "5": 5 }, custom_suits={"𓆏": "GREEN"}) deck.add_cards([Card(rank="3", rank_value=3, suit="𓆏", color="RED")]) self.assertTrue(deck.evaluator.has_pairs(1))
def test_has_6_card_straight(self): deck = Deck(custom_cards=[ Card(rank="3", rank_value=3, suit="𓆏", color="RED"), Card(rank="5", rank_value=5, suit="𓃰", color="BLACK"), Card(rank="6", rank_value=6, suit="𓆏", color="RED"), Card(rank="7", rank_value=7, suit="𓆏", color="RED"), Card(rank="8", rank_value=8, suit="𓃰", color="BLACK"), Card(rank="9", rank_value=9, suit="𓃰", color="BLACK"), Card(rank="10", rank_value=10, suit="𓃰", color="BLACK") ]) self.assertTrue(deck.evaluator.has_straight(6))
def test_has_three_pairs(self): deck = Deck(custom_cards=[ Card(rank="3", rank_value=3, suit="𓆏", color="RED"), Card(rank="5", rank_value=5, suit="𓃰", color="BLACK"), Card(rank="3", rank_value=3, suit="𓆏", color="RED"), Card(rank="4", rank_value=4, suit="𓆏", color="RED"), Card(rank="4", rank_value=4, suit="𓃰", color="BLACK"), Card(rank="5", rank_value=5, suit="𓃰", color="BLACK"), Card(rank="6", rank_value=6, suit="𓃰", color="BLACK") ]) self.assertTrue(deck.evaluator.has_n_pairs(3))
def listing(request): #if post request, save new quiz and then show listing if request.method == 'POST': #Get name and filename name = request.POST['deck-name'] filename = request.POST['deck-filename'] #Create new entry in db deck = Deck(name=name, filename=filename) deck.save() #Get available decks decks = Deck.objects.all() #decks = [{'name':name, 'last_result':res} for name,res in zip(decks, r)] context = {'decks': decks} return render(request, 'quizzes/listing.html', context)
def load_data_as_xml(data_dump_as_xml): tree = etree.parse(data_dump_as_xml) docinfo = tree.docinfo if docinfo.encoding != "UTF-8": raise XMLDataDumpException("Not supported encoding: %s" % docinfo.encoding) root = tree.getroot() if root.tag != "data": raise XMLDataDumpException("%s: %s != 'data'" % (root.sourceline, root.tag)) for shelf_xml in root: if shelf_xml.tag != "shelf": raise XMLDataDumpException("%s: %s != 'shelf'" % (shelf_xml.sourceline, shelf_xml.tag)) shelf = Shelf() shelf.name = shelf_xml.get("name") try: shelf.save() except IntegrityError as e: raise XMLDataDumpException("%s: cannot add shelf: %s" % (shelf_xml.sourceline, str(e))) for deck_data in shelf_xml: if deck_data.tag != "deck": raise XMLDataDumpException( "%s: %s != 'deck'" % (deck_data.sourceline, deck_data.tag)) deck = Deck() deck.shelf = shelf deck.name = deck_data.get("name") deck.save() for card_data in deck_data: if card_data.tag != "card": raise XMLDataDumpException( "%s: %s != 'card'" % (card_data.sourceline, card_data.tag)) if card_data[0].tag != "question": raise XMLDataDumpException( "%s: %s != 'question'" % (card_data[0].sourceline, card_data[0].tag)) if card_data[1].tag != "answer": raise XMLDataDumpException( "%s: s%s != 'answer'" % (card_data[1].sourceline, card_data[1].tag)) card = Card() card.deck = deck card.question = card_data[0].text card.answer = card_data[1].text card.save()
def add_deck(deck): if deck is not None: entry = db.session.query(Deck).filter(Deck.id == deck.id).first() subscribe = deck.id in subscribed if not entry: try: D = Deck(deck.id, deck.name, deck.issuer, deck.issue_mode, deck.number_of_decimals, subscribe) db.session.add(D) db.session.commit() except Exception as e: print(e) pass else: db.session.query(Deck).filter(Deck.id == deck.id).update( {"subscribed": subscribe}) db.session.commit()
def create_deck(): """Handle a new deck creation Create a new deck and add to DB. Redirect to homepage. If form is not valid, present form. """ if not g.user: flash("Access unauthorized.", "danger") return redirect("/") form = CreateDeckForm() if form.validate_on_submit(): deck = Deck(name=form.deckname.data, description=form.description.data, visibility=form.visibility.data) g.user.decks.append(deck) db.session.commit() return redirect("/") return render_template('/createdeck.html', form=form)
def deck_new(): """Form for creating a new deck.""" # Must be logged in to create a deck if "user_id" not in session: return redirect("/") form = DeckNewForm() if form.validate_on_submit(): deck = Deck(user_id=session["user_id"], title=form.title.data, description=form.description.data, date=datetime.datetime.utcnow(), public=False) db.session.add(deck) db.session.commit() return redirect(f"/deck/{deck.id}") return render_template("deckNew.html", form=form)
def test_get_foak_probability(): foak_count = 0 iterations = 100000 for i in range(0, iterations): deck = Deck(custom_suits={"𓆏": "GREEN", "𓃰": "GREY"}) deck.double_cards() deck.shuffle() deck.remove_cards(lambda_statement=lambda x: x.rank != "A", index=13) if deck.evaluator.has_four_of_a_kind(): foak_count += 1 print( "The probability of having a four-of-a-kind given this custom deck is around {} %." .format(foak_count / iterations * 100))
def __init__(self, room_id): self.room_id = room_id #room id self.current_occupants = [] # List of users in the room self.player_states = {} # player_id to PlayerState # self.game_state = GameState() # maybe we want a game state? self.board = [] self.pot = 0 self.deck = Deck() self.positions = [None] * NUM_SEATS # mapping of playerid to location self.button_pos = 0 self.current_turn = 0 # which position in the array is the current turn self.allowed_moves = [ Action.FOLD, Action.CHECK, Action.CALL, Action.BET, Action.RAISE ] self.min_raise = BIG_BLIND_AMOUNT #minimum amount you must raise. Based on what the previous person raised by. self.history = [] #list of events of this game self.street = Street.DEALING self.best_hand = { } # mapping of playerid to their best hand based on this board. noned out at the end of each hand
def add_deck(deck): if deck is not None: try: entry = session.query(Deck).filter(Deck.id == deck.id).first() except: entry = None subscribe = any(deck_id in subscribed for deck_id in ('*', deck.id)) if entry is None: try: data = hexlify(deck.asset_specific_data).decode() D = Deck( deck.id, deck.name, deck.issuer, deck.issue_mode, deck.number_of_decimals, subscribe, data) session.add(D) except Exception as e: pass else: session.query(Deck).filter(Deck.id == deck.id).update({"subscribed": subscribe}) commit()
def test_get_straights_probability(): for i in range(3, 9): straight_count = 0 straight_length = i iterations = 50000 for j in range(0, iterations): deck = Deck(custom_suits={"𓆏": "GREEN", "𓃰": "GREY"}) deck.double_cards() deck.shuffle() deck.remove_cards(lambda_statement=lambda x: x.rank != "A", index=13) if deck.evaluator.has_straight(straight_length): straight_count += 1 print( "The probability of this deck containing a {}-card straight is around {} %." .format(straight_length, straight_count / iterations * 100))
def add_edit_deck(request, shelf_id=None, deck_id=None): if deck_id: deck = get_object_or_404(Deck, pk=deck_id) else: deck = Deck() if request.method == "GET": deck_form = DeckForm(instance=deck) elif request.method == "POST": deck_form = DeckForm(request.POST, instance=deck) if deck_form.is_valid(): deck = deck_form.save(commit=False) if not hasattr(deck, "shelf"): shelf = get_object_or_404(Shelf, pk=shelf_id) deck.shelf = shelf else: shelf_id = deck.shelf.id deck.save() return redirect( reverse("pamietacz.views.show_shelf", args=(shelf_id, ))) return render(request, "add_edit_deck.html", { "deck_form": deck_form, "action": request.get_full_path() })
def importDeck(): if current_user.is_authenticated: try: [name, author, description, cards] = deckImport(request.json['deckText']) if len(cards) > 0: deckid = uuid.uuid4().hex d = Deck(deckid=deckid, name=name, author_public_name=author, description=description, author=current_user, inventory_type='', used_in_inventory={}, cards=cards) db.session.add(d) db.session.commit() return jsonify({'deckid': deckid}) return jsonify({'Cannot import this deck.'}) except Exception: pass else: return jsonify({'Not logged in.'})
def test_get_diminishing_straights_probabibilty(): """ Given a custom deck, calculate the probability of the deck having a 3-card straight. Then remove the lowest cards, one by one, and calculate the probabilities again, etc. """ straight_length = 3 max_iterations = 50000 straight_count_frequencies = dict() for i in range(3, 13): straight_count_frequencies[i] = 0 for i in range(max_iterations): deck = Deck(custom_suits={"𓆏": "GREEN", "𓃰": "GREY"}) deck.double_cards() deck.shuffle() deck.remove_cards(lambda_statement=lambda x: x.rank != "A", index=13) hand = deck.get_sample_hand(12) while len(hand.cards) >= straight_length: if hand.evaluator.has_straight(straight_length): straight_count_frequencies[len(hand.cards)] += 1 hand.remove_lowest_ranked_card() for i in sorted(straight_count_frequencies.keys()): print( "The probability of a hand containing a {}-card straight given its {} highest cards is around {} %." .format(straight_length, i, straight_count_frequencies[i] / max_iterations * 100))