Example #1
0
 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()
Example #2
0
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
Example #3
0
    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)
Example #4
0
    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 create_deck():
    """
    Returns a deck populated with the standard 52 cards from a plain deck
    """
    rand = random.Random(os.urandom(4))
    deck = Deck(rand)
    for suit in Suit:
        for rank in Rank:
            deck.add_card(Card(suit, rank))
    
    return deck
Example #6
0
    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))
Example #7
0
    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)
Example #8
0
    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)
Example #9
0
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)
Example #10
0
    def update_user_deck(user, cls):
        deck_name = request.args.get('name', None)
        deck_content_str = request.args.get('content', '')

        if deck_name == None or not Deck.check_verify_deck(deck_content_str):
            return jsonify({
                'result': -2,
                'msg': 'Not Object'
            })

        Deck.upload_deck(str(user.id), deck_name, deck_content_str)

        return jsonify({
            'result': 0,
        })
Example #11
0
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.'})
Example #12
0
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)
Example #13
0
    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)
Example #14
0
def make_tmp_file(name):
    deck = Deck.objects(Q(name=name)).first()
    file = open('tmp/' + name + '.txt', 'w')
    descr = deck.description.split('\n')
    for line in descr:
        file.write('#' + line + '\n')
    for line in deck.cards:
        file.write(line + '\n')
    return file
Example #15
0
def get_deck_list():
    deck_list = []
    for deck in Deck.objects():
        deck_list.append({
            'name': deck.name,
            'length': deck.length,
            'description': deck.description
        })
    return deck_list
Example #16
0
    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)
Example #17
0
 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
Example #18
0
    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)
Example #19
0
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()
Example #20
0
    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)
Example #21
0
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()
Example #22
0
    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))
Example #23
0
    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))
Example #24
0
 def get_user_decks(user, cls):
     deck_name = request.args.get('name', '')
     deck = Deck.get_decks_by_name(str(user.id), deck_name)
     if deck == None:
         return jsonify({
             'result': -3,
             'msg': 'Deck Not Found'
         })
     else:
         return jsonify({
             'result': 0,
             'data': deck.to_JSON()
         })
Example #25
0
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()})
Example #26
0
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()
    })
Example #27
0
 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()
Example #28
0
    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))
Example #29
0
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)
Example #31
0
    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))
Example #32
0
    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))
Example #33
0
            player.name)))
player.money = Decimal(money)
player.start_money = player.money
bet = 0

# Building the Deck with the number of packs of cards specified
while True:
    try:
        packs = int(
            input("How many packs of cards should make up your deck? [1-10] "))
        if packs < 0:
            raise ValueError()
        break
    except ValueError:
        print("{} is not a valid number of packs. They will throw you out of Vegas for that kinda crap".format(packs))
deck = Deck(packs)
deck.shuffle()

# Setting the play variable and the game counter
play_another = 'y'
while play_another != 'n':
    # clear screen between rounds
    clearscreen()

    if (deck.cards_left() < 10):
        print(
            "There were only {} cards left in the deck, so the dealer reshuffled.".format(
                deck.cards_left()))
        deck = Deck(packs)
        deck.shuffle()
    player_hand = Hand()