示例#1
0
    def test_overtrumping_your_teammate_is_not_mandatory_in_amsterdam_deals_if_teammate_is_winning(
            self) -> None:
        players = [Player(), Player(), Player(), Player()]
        players[0].hand = {Card(suit=Suit.HEARTS, rank=Rank.KING)}
        players[1].hand = {Card(suit=Suit.SPADES, rank=Rank.TEN)}
        players[2].hand = {Card(suit=Suit.HEARTS, rank=Rank.NINE)}
        players[3].hand = {
            Card(suit=Suit.DIAMONDS, rank=Rank.ACE),
            Card(suit=Suit.SPADES, rank=Rank.EIGHT),
            Card(suit=Suit.SPADES, rank=Rank.JACK),
        }

        deal = Deal(players=players,
                    bidder_index=0,
                    trump_suit=Suit.SPADES,
                    rules=RuleSet.AMSTERDAM)
        trick = Trick(deal=deal, leading_player_index=0)
        trick.play(Card(suit=Suit.HEARTS, rank=Rank.KING))
        trick.play(Card(suit=Suit.SPADES, rank=Rank.TEN))
        trick.play(Card(suit=Suit.HEARTS, rank=Rank.NINE))

        # Playing a higher trump is legal, but not necessary. The player may also drop the ace.
        # Note however that playing a lower trump is still illegal.
        self.assertEqual(
            {
                Card(suit=Suit.DIAMONDS, rank=Rank.ACE),
                Card(suit=Suit.SPADES, rank=Rank.JACK),
            }, trick.legal_cards)

        # In an Amsterdam deal, the player is forced to play the higher trump card.
        deal.rules = RuleSet.ROTTERDAM
        self.assertEqual({
            Card(suit=Suit.SPADES, rank=Rank.JACK),
        }, trick.legal_cards)
示例#2
0
    def test_cards_can_be_compared_before_a_suit_is_led(self) -> None:
        players = [Player(), Player(), Player(), Player()]
        deal = Deal(players=players, bidder_index=0)
        trick = Trick(deal=deal, leading_player_index=0)

        # The queen should be consider higher, as we are assuming we are not
        # dealing with a trump suit, given that no trump suit was even specified yet.
        self.assertEqual(
            1,
            trick.compare_cards(Card(suit=Suit.HEARTS, rank=Rank.JACK),
                                Card(suit=Suit.HEARTS, rank=Rank.QUEEN)))

        # Unrelated cards cannot be compared properly without a trump suit or a led suit.
        self.assertEqual(
            0,
            trick.compare_cards(
                Card(suit=Suit.HEARTS, rank=Rank.JACK),
                Card(suit=Suit.SPADES, rank=Rank.ACE),
            ))

        deal.trump_suit = Suit.HEARTS

        # Now that we have a trump suit defined, the higher trump should rank higher.
        self.assertEqual(
            -1,
            trick.compare_cards(Card(suit=Suit.HEARTS, rank=Rank.JACK),
                                Card(suit=Suit.HEARTS, rank=Rank.QUEEN)))
示例#3
0
    def test_overtrumping_the_opponent_is_mandatory_if_teammate_is_not_leading(
            self) -> None:
        players = [Player(), Player(), Player(), Player()]
        players[0].hand = {Card(suit=Suit.HEARTS, rank=Rank.KING)}
        players[1].hand = {Card(suit=Suit.DIAMONDS, rank=Rank.TEN)}
        players[2].hand = {Card(suit=Suit.SPADES, rank=Rank.QUEEN)}
        players[3].hand = {
            Card(suit=Suit.DIAMONDS, rank=Rank.ACE),
            Card(suit=Suit.SPADES, rank=Rank.EIGHT),
            Card(suit=Suit.SPADES, rank=Rank.JACK),
        }

        deal = Deal(players=players,
                    bidder_index=0,
                    trump_suit=Suit.SPADES,
                    rules=RuleSet.ROTTERDAM)
        trick = Trick(deal=deal, leading_player_index=0)
        trick.play(Card(suit=Suit.HEARTS, rank=Rank.KING))
        trick.play(Card(suit=Suit.DIAMONDS, rank=Rank.TEN))
        trick.play(Card(suit=Suit.SPADES, rank=Rank.QUEEN))

        self.assertEqual({
            Card(suit=Suit.SPADES, rank=Rank.JACK),
        }, trick.legal_cards)

        # No matter whether this game is Rotterdam or Amsterdam style, the trump is the only legitimate option.
        deal.rules = RuleSet.AMSTERDAM
        self.assertEqual({
            Card(suit=Suit.SPADES, rank=Rank.JACK),
        }, trick.legal_cards)
示例#4
0
    def test_a_deal_can_return_the_teammate_of_a_player(self) -> None:
        players = [Player(name="1"), Player(name="2"), Player(name="3"), Player(name="4")]
        deal = Deal(players=players, bidder_index=0)

        self.assertEqual(2, deal.get_teammate_index(Player(name="1")))
        self.assertEqual(3, deal.get_teammate_index(Player(name="2")))
        self.assertEqual(0, deal.get_teammate_index(Player(name="3")))
        self.assertEqual(1, deal.get_teammate_index(Player(name="4")))
示例#5
0
    def test_a_deal_asks_for_trump_suit_when_started(self) -> None:
        players = [Player(), Player(), Player(), Player()]

        suit_identifier: str
        suit: Suit
        for (suit_identifier, suit) in Suit.suits().items():
            with patch("builtins.input", return_value=suit_identifier):
                deal = Deal(players=players, bidder_index=0)
                deal.initialize()

                self.assertEqual(deal.trump_suit, suit)
示例#6
0
    def get(self):
        deal = Deal.get_latest_deal()
        last_deal = Deal.all().order("-published").get()
        ### last_deal = None ### for testing

        # Only add this deal and call match if it's new!
        if last_deal is None or last_deal.title != deal.title or self.request.GET.has_key('force'):
            deal.put()
            match(deal, result_key=str(deal.key()))
            print ("new deal.  match submitted")
            print (deal.alltext)
        else:
            print ("existing deal")
示例#7
0
    def test_overtrumping_your_teammate_is_still_mandatory_in_amsterdam_deals_if_it_is_the_led_suit(
            self) -> None:
        players = [Player(), Player(), Player(), Player()]
        players[0].hand = {Card(suit=Suit.HEARTS, rank=Rank.KING)}
        players[1].hand = {Card(suit=Suit.SPADES, rank=Rank.TEN)}
        players[2].hand = {
            Card(suit=Suit.HEARTS, rank=Rank.NINE),
            Card(suit=Suit.HEARTS, rank=Rank.QUEEN),
            Card(suit=Suit.DIAMONDS, rank=Rank.ACE),
        }
        deal = Deal(players=players,
                    bidder_index=0,
                    trump_suit=Suit.HEARTS,
                    rules=RuleSet.ROTTERDAM)
        trick = Trick(deal=deal, leading_player_index=0)

        trick.play(Card(suit=Suit.HEARTS, rank=Rank.KING))
        trick.play(Card(suit=Suit.SPADES, rank=Rank.TEN))

        # Despite the fact that the teammate is leading the trick so far, playing a lower trump
        # or any other card is not allowed: when following suit in trump, over-trumping is still
        # mandatory.
        self.assertEqual({
            Card(suit=Suit.HEARTS, rank=Rank.NINE),
        }, trick.legal_cards)
示例#8
0
    def test_a_player_must_not_follow_suit_if_not_possible(self) -> None:
        players = [Player(), Player(), Player(), Player()]
        deal = Deal(players=players, bidder_index=0)
        trick = Trick(deal=deal, leading_player_index=0)

        players[0].hand = {Card(suit=Suit.SPADES, rank=Rank.ACE)}
        players[1].hand = {
            Card(suit=Suit.HEARTS, rank=Rank.KING),
            Card(suit=Suit.HEARTS, rank=Rank.QUEEN),
            Card(suit=Suit.DIAMONDS, rank=Rank.KING),
        }

        trick.play(Card(suit=Suit.SPADES, rank=Rank.ACE))

        # The next player may play any of these cards despite them not following suit.
        self.assertEqual(
            {
                Card(suit=Suit.HEARTS, rank=Rank.KING),
                Card(suit=Suit.HEARTS, rank=Rank.QUEEN),
                Card(suit=Suit.DIAMONDS, rank=Rank.KING),
            },
            trick.legal_cards,
        )

        # Playing this card should be acceptable despite it not following suit.
        trick.play(Card(suit=Suit.HEARTS, rank=Rank.KING))
示例#9
0
    def test_lower_trump_is_allowed_if_no_other_cards_are_in_hand(
            self) -> None:
        players = [Player(), Player(), Player(), Player()]
        players[0].hand = {Card(suit=Suit.HEARTS, rank=Rank.KING)}
        players[1].hand = {Card(suit=Suit.DIAMONDS, rank=Rank.ACE)}
        players[2].hand = {
            Card(suit=Suit.DIAMONDS, rank=Rank.TEN),
            Card(suit=Suit.DIAMONDS, rank=Rank.KING),
            Card(suit=Suit.DIAMONDS, rank=Rank.QUEEN),
            Card(suit=Suit.DIAMONDS, rank=Rank.EIGHT),
            Card(suit=Suit.DIAMONDS, rank=Rank.SEVEN),
        }
        deal = Deal(players=players, bidder_index=0, trump_suit=Suit.DIAMONDS)
        trick = Trick(deal=deal, leading_player_index=0)

        trick.play(Card(suit=Suit.HEARTS, rank=Rank.KING))
        trick.play(Card(suit=Suit.DIAMONDS, rank=Rank.ACE))

        self.assertEqual(
            {
                Card(suit=Suit.DIAMONDS, rank=Rank.TEN),
                Card(suit=Suit.DIAMONDS, rank=Rank.KING),
                Card(suit=Suit.DIAMONDS, rank=Rank.QUEEN),
                Card(suit=Suit.DIAMONDS, rank=Rank.EIGHT),
                Card(suit=Suit.DIAMONDS, rank=Rank.SEVEN),
            },
            trick.legal_cards,
        )
示例#10
0
    def test_a_deal_throws_an_error_when_initialized_with_bad_info(self) -> None:
        players = [Player(), Player(), Player()]

        for bidder_index in range(4):
            # No matter who is supposed to start, a deal with not exactly 4 players cannot be instantiated.
            self.assertRaises(AssertionError, lambda: Deal(players=players, bidder_index=bidder_index))

        players = [Player(), Player(), Player(), Player()]

        # Bad bidder indices are not allowed.
        self.assertRaises(AssertionError, lambda: Deal(players=players, bidder_index=-1))
        self.assertRaises(AssertionError, lambda: Deal(players=players, bidder_index=4))

        # Invalid suits are not allowed.
        # noinspection PyTypeChecker
        self.assertRaises(AssertionError, lambda: Deal(players=players, bidder_index=0, trump_suit=-1))  # type: ignore
示例#11
0
    def test_a_player_must_follow_suit_if_possible(self) -> None:
        players = [Player(), Player(), Player(), Player()]
        deal = Deal(players=players, bidder_index=0)
        trick = Trick(deal=deal, leading_player_index=0)

        players[0].hand = {Card(suit=Suit.SPADES, rank=Rank.ACE)}
        players[1].hand = {
            Card(suit=Suit.SPADES, rank=Rank.KING),
            Card(suit=Suit.SPADES, rank=Rank.QUEEN),
            Card(suit=Suit.HEARTS, rank=Rank.KING),
        }

        trick.play(Card(suit=Suit.SPADES, rank=Rank.ACE))

        # The first player has led spades; the next player should have two legal choices.
        self.assertEqual(
            {
                Card(suit=Suit.SPADES, rank=Rank.KING),
                Card(suit=Suit.SPADES, rank=Rank.QUEEN),
            }, trick.legal_cards)

        self.assertEqual(
            True,
            Card(suit=Suit.HEARTS, rank=Rank.KING)
            in deal.players[trick.player_index_to_play].hand)
        # If the player attempts to play a different card anyway, then despite holding the card
        # in their hand, it should raise an exception.
        self.assertRaises(AssertionError, trick.play,
                          Card(suit=Suit.HEARTS, rank=Rank.KING))
示例#12
0
    def test_winning_card_detection_returns_none_if_no_card_was_played(
            self) -> None:
        players = [Player(), Player(), Player(), Player()]
        deal = Deal(players=players, bidder_index=0, trump_suit=Suit.DIAMONDS)
        trick = Trick(deal=deal, leading_player_index=0)

        self.assertEqual(None, trick.winning_card)
        self.assertEqual(None, trick.winning_card_index)
示例#13
0
        def play_bad_card() -> None:
            players = [Player(), Player(), Player(), Player()]
            deal = Deal(players=players, bidder_index=0)
            trick = Trick(deal=deal, leading_player_index=0)
            players[0].hand = {Card(suit=Suit.SPADES, rank=Rank.ACE)}

            # The player does not actually have this card; it should throw AssertionError
            trick.play(Card(suit=Suit.HEARTS, rank=Rank.ACE))
示例#14
0
def add_deal(request):
    data = json.loads(request.body)

    DRINK_CATEGORIES = {'beer': 1, 'wine': 2, 'liquor': 3}

    DEAL_TYPES = {'price': 1, 'percent-off': 2, 'price-off': 3}

    location_id = data.get('location_id')

    location = Location.objects.get(id=location_id)
    deal_data = data.get('deal')
    deal = Deal()
    deal.save()

    for day in deal_data.get('daysOfWeek'):
        for tp_data in deal_data.get('timePeriods'):
            # push the time periods to the time_periods array
            activeHour = ActiveHour()
            activeHour.dayofweek = day
            activeHour.start = tp_data.get("startTime")
            activeHour.end = tp_data.get("endTime")

            if activeHour.end == "":
                activeHour.end = None

            activeHour.save()
            deal.activeHours.add(activeHour)

    deal_detail_data = deal_data.get('dealDetails')
    for detail in deal_detail_data:
        drink_names = detail.get("names")
        category = DRINK_CATEGORIES[detail.get("category")]
        type = DEAL_TYPES[detail.get("dealType")]
        dealDetail = DealDetail(drinkName=drink_names,
                                drinkCategory=category,
                                detailType=type,
                                value=detail.get("dealValue"))

        dealDetail.save()
        deal.dealDetails.add(dealDetail)

    location.deals.add(deal)
    location.save()

    return HttpResponse('success')
示例#15
0
    def save_to_db(self, dic):
        assert all(map(dic.has_key, ['title', 'original_price', 'price', 'detail', 'url'])),\
            "Information incomplete."
        
        url = dic['url']
        original_price = dic['original_price'].text.encode('utf8')
        price = dic['price'].text.encode('utf8')
        title = dic['title'].text # title is unicode
        detail = dic['detail'].renderContents(encoding='utf8')
        detail = utils.clean_detail(detail, self.home_url)
            
        # Data formatting & validation.
        try:
            original_price, price = map(lambda s: int(re.search(r'(\d+)', s).group()),
                                        [original_price, price])
        except TypeError:
            logging.error("Price conversion failed. Detailed info: %s", [original_price, price])
            return
        except AttributeError:
            logging.error("Regex failed on %s", [original_price, price])
            return
        
        if len(title) > 500 or len(title) < 10:
            logging.error("Title length too short or too long : %s", title)
            return
        
        if len(detail) < 20:
            logging.error("Detail too short. %s", detail)
            return

        # Save to db.
        try:
            site = Site.select(Site.q.url == self.home_url)
            assert(site.count() == 1), "%s not found or dups." % self.home_url
            
            title = utils.lstrip(title, [s.decode('utf8') for s in ('今日团购', '今日精选', ':')])
            title = title.strip()
            title='[%s] %s' % (site[0].name, title)
            
            city_name = self.index_urls[url]
            city = City.select(City.q.name == city_name.decode('utf8'))
            assert city.count() == 1, "%s not found or dups." % city_name
            cityID = city[0].id
            
            if Deal.select(AND(Deal.q.title == title, Deal.q.cityID == cityID)).count() > 0:
                logging.info("Title dups %s" % title)
                return
            deal = Deal(url=url, title=title, price=price, originalPrice=original_price,
                        detail=detail.decode('utf8'),cityID=cityID, siteID=site[0].id)
            logging.info('%s OK', url)
        except:
            # Simple handling for the moment.
            logging.error("Error occured while saving data : %s", sys.exc_info())
示例#16
0
def deals(request, id=0):
    if request.method == 'GET':
        all_deals = Deal.objects.all().order_by('id')
        serializer = DealSerializer(all_deals)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = DealSerializer(data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'PUT':
        deal = Deal(id=id)
        serializer = DealSerializer(deal, data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        deal = Deal(id=id)
        deal.delete()
        return Response("DELETED", status=status.HTTP_200_OK)
示例#17
0
def request_quotes():
    user = current_identity
    company = Company.query.filter_by(id=current_identity.company_id).first()
    data = request.get_json()
    suppliers = []
    uuid = uuid4()
    status = 'enquiry' if data['suppliers'] else 'order'
    d = Deal(user.email, company, uuid, data['port'], data['vessel'],
             data['imo'], data['loa'], data['buyer'], None,
             data['grossTonnage'], data['additionalInfo'], data['eta'],
             data['etd'], data['portCallReason'], data['agent'],
             data['currency'], data['location'], status, data['voyage'],
             data['trade'])
    for order in data['orders']:
        new_order = Order(order['grade'], order['quantity'],
                          order['specification'], order['maxSulphur'],
                          order['unit'], order['comments'], d)
        db.session.add(new_order)
    db.session.add(d)
    db.session.commit()
    orders = [{
        'id': o.id,
        'grade': o.grade,
        'quantity': o.quantity,
        'unit': o.unit,
        'maxSulphur': o.maxSulphur,
        'spec': o.spec,
        'comments': o.comments
    } for o in Order.query.filter_by(deal_id=d.id)]
    deal = {
        'id': d.id,
        'port': d.port,
        'vessel': d.vessel,
        'imo': d.imo,
        'loa': d.loa,
        'grossTonnage': d.grossTonnage,
        'buyer': d.buyer,
        'orderedBy': d.orderedBy,
        'eta': d.eta,
        'etd': d.etd,
        'portCallReason': d.portCallReason,
        'agent': d.agent,
        'currency': d.currency,
        'location': d.location,
        'additionalInfo': d.additionalInfo,
        'quotes': [],
        'orders': orders,
        'status': d.status
    }
    response = jsonify({'deal': deal})
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response
示例#18
0
    def test_cards_can_be_compared_after_trump_suit_is_led(self) -> None:
        players = [Player(), Player(), Player(), Player()]
        players[0].hand = {Card(suit=Suit.SPADES, rank=Rank.QUEEN)}
        deal = Deal(players=players, bidder_index=0, trump_suit=Suit.SPADES)
        trick = Trick(deal=deal, leading_player_index=0)

        # The trick starts with the trump suit.
        trick.play(Card(suit=Suit.SPADES, rank=Rank.QUEEN))

        # The Johnny scores higher than the ten, in contrast to the normal order.
        # Same thing for the Nerf (9).
        self.assertEqual(
            -1,
            trick.compare_cards(
                Card(suit=Suit.SPADES, rank=Rank.JACK),
                Card(suit=Suit.SPADES, rank=Rank.TEN),
            ))
        self.assertEqual(
            -1,
            trick.compare_cards(
                Card(suit=Suit.SPADES, rank=Rank.NINE),
                Card(suit=Suit.SPADES, rank=Rank.TEN),
            ))

        # Any trump card will rank higher than any non-trump card.
        for first_rank, second_rank, second_suit in product(Rank, Rank, Suit):
            # We are testing non-trump cards for the second card, so skip the trump cards.
            if second_suit == deal.trump_suit:
                continue

            self.assertEqual(
                -1,
                trick.compare_cards(
                    Card(suit=Suit.SPADES, rank=first_rank),
                    Card(suit=second_suit, rank=second_rank),
                ),
            )

        # Any two cards that both aren't trump will be incomparable.
        for first_rank, first_suit, second_rank, second_suit in product(
                Rank, Suit, Rank, Suit):
            # If the suits match or any equals trump, skip.
            if first_suit == deal.trump_suit or second_suit == deal.trump_suit or first_suit == second_suit:
                continue

            self.assertEqual(
                0,
                trick.compare_cards(Card(suit=first_suit, rank=first_rank),
                                    Card(suit=second_suit, rank=second_rank)))
示例#19
0
    def test_a_card_can_be_played_in_a_trick(self) -> None:
        players = [Player(), Player(), Player(), Player()]
        deal = Deal(players=players, bidder_index=0)
        trick = Trick(deal=deal, leading_player_index=0)

        players[0].hand = {Card(suit=Suit.SPADES, rank=Rank.ACE)}
        trick.play(Card(suit=Suit.SPADES, rank=Rank.ACE))

        # The turn must shift to the next player
        self.assertEqual(1, trick.player_index_to_play)
        # The card must be removed from the player's hand
        self.assertEqual(0, len(players[0].hand))
        # The card resides within the played cards of the trick
        self.assertEqual(
            True,
            Card(suit=Suit.SPADES, rank=Rank.ACE) in trick.played_cards)
示例#20
0
    def test_only_higher_trump_cards_are_legal_if_led_suit_is_trump_and_higher_trumps_are_available(
            self) -> None:
        players = [Player(), Player(), Player(), Player()]
        players[0].hand = {Card(suit=Suit.HEARTS, rank=Rank.KING)}
        players[1].hand = {
            Card(suit=Suit.HEARTS, rank=Rank.QUEEN),
            Card(suit=Suit.HEARTS, rank=Rank.ACE),
            Card(suit=Suit.DIAMONDS, rank=Rank.ACE),
        }
        deal = Deal(players=players, bidder_index=0, trump_suit=Suit.HEARTS)
        trick = Trick(deal=deal, leading_player_index=0)

        trick.play(Card(suit=Suit.HEARTS, rank=Rank.KING))

        self.assertEqual({
            Card(suit=Suit.HEARTS, rank=Rank.ACE),
        }, trick.legal_cards)
示例#21
0
    def test_the_highest_card_in_a_trick_with_trumps(self) -> None:
        players = [Player(), Player(), Player(), Player()]
        deal = Deal(players=players, bidder_index=0, trump_suit=Suit.DIAMONDS)
        trick = Trick(deal=deal, leading_player_index=0)

        players[0].hand = {Card(suit=Suit.SPADES, rank=Rank.JACK)}
        players[1].hand = {Card(suit=Suit.SPADES, rank=Rank.TEN)}
        players[2].hand = {Card(suit=Suit.SPADES, rank=Rank.KING)}
        players[3].hand = {Card(suit=Suit.DIAMONDS, rank=Rank.SEVEN)}
        trick.play(Card(suit=Suit.SPADES, rank=Rank.JACK))
        trick.play(Card(suit=Suit.SPADES, rank=Rank.TEN))
        trick.play(Card(suit=Suit.SPADES, rank=Rank.KING))
        trick.play(Card(suit=Suit.DIAMONDS, rank=Rank.SEVEN))

        # Player 4 played a seven, but because it is a trump card, he will win.
        self.assertEqual(3, trick.winning_card_index)
        self.assertEqual(Card(suit=Suit.DIAMONDS, rank=Rank.SEVEN),
                         trick.winning_card)
示例#22
0
    def test_the_highest_card_in_a_trick_without_trumps(self) -> None:
        players = [Player(), Player(), Player(), Player()]
        deal = Deal(players=players, bidder_index=0, trump_suit=Suit.HEARTS)
        trick = Trick(deal=deal, leading_player_index=0)

        players[0].hand = {Card(suit=Suit.SPADES, rank=Rank.JACK)}
        players[1].hand = {Card(suit=Suit.SPADES, rank=Rank.TEN)}
        players[2].hand = {Card(suit=Suit.SPADES, rank=Rank.KING)}
        players[3].hand = {Card(suit=Suit.DIAMONDS, rank=Rank.ACE)}
        trick.play(Card(suit=Suit.SPADES, rank=Rank.JACK))
        trick.play(Card(suit=Suit.SPADES, rank=Rank.TEN))
        trick.play(Card(suit=Suit.SPADES, rank=Rank.KING))
        trick.play(Card(suit=Suit.DIAMONDS, rank=Rank.ACE))

        # Player 4 played an ace, but it is in the wrong suit.
        # Player 1 played a jack, but it is not the trump suit, so the 10 wins.
        self.assertEqual(1, trick.winning_card_index)
        self.assertEqual(Card(suit=Suit.SPADES, rank=Rank.TEN),
                         trick.winning_card)
示例#23
0
    def test_winning_card_can_be_done_for_incomplete_tricks(self) -> None:
        players = [Player(), Player(), Player(), Player()]
        players[0].hand = {Card(suit=Suit.HEARTS, rank=Rank.KING)}
        players[1].hand = {Card(suit=Suit.HEARTS, rank=Rank.TEN)}
        players[2].hand = {Card(suit=Suit.HEARTS, rank=Rank.NINE)}
        players[3].hand = {Card(suit=Suit.HEARTS, rank=Rank.ACE)}
        deal = Deal(players=players, bidder_index=0, trump_suit=Suit.DIAMONDS)
        trick = Trick(deal=deal, leading_player_index=0)

        trick.play(Card(suit=Suit.HEARTS, rank=Rank.KING))
        self.assertEqual(Card(suit=Suit.HEARTS, rank=Rank.KING),
                         trick.winning_card)
        trick.play(Card(suit=Suit.HEARTS, rank=Rank.TEN))
        self.assertEqual(Card(suit=Suit.HEARTS, rank=Rank.TEN),
                         trick.winning_card)
        trick.play(Card(suit=Suit.HEARTS, rank=Rank.NINE))
        self.assertEqual(Card(suit=Suit.HEARTS, rank=Rank.TEN),
                         trick.winning_card)
        trick.play(Card(suit=Suit.HEARTS, rank=Rank.ACE))
        self.assertEqual(Card(suit=Suit.HEARTS, rank=Rank.ACE),
                         trick.winning_card)
示例#24
0
    def test_all_cards_are_legal_if_suit_cannot_be_followed_and_no_trump_is_available(
            self) -> None:
        players = [Player(), Player(), Player(), Player()]
        players[0].hand = {Card(suit=Suit.SPADES, rank=Rank.QUEEN)}
        players[1].hand = {
            Card(suit=Suit.HEARTS, rank=Rank.QUEEN),
            Card(suit=Suit.HEARTS, rank=Rank.ACE),
            Card(suit=Suit.DIAMONDS, rank=Rank.ACE),
        }
        deal = Deal(players=players, bidder_index=0, trump_suit=Suit.CLUBS)
        trick = Trick(deal=deal, leading_player_index=0)

        trick.play(Card(suit=Suit.SPADES, rank=Rank.QUEEN))

        self.assertEqual(
            {
                Card(suit=Suit.HEARTS, rank=Rank.QUEEN),
                Card(suit=Suit.HEARTS, rank=Rank.ACE),
                Card(suit=Suit.DIAMONDS, rank=Rank.ACE),
            },
            trick.legal_cards,
        )
示例#25
0
    def test_lower_trump_is_allowed_if_led_suit_is_trump_and_no_higher_trumps_are_available(
            self) -> None:
        players = [Player(), Player(), Player(), Player()]
        players[0].hand = {Card(suit=Suit.HEARTS, rank=Rank.KING)}
        players[1].hand = {
            Card(suit=Suit.HEARTS, rank=Rank.QUEEN),
            Card(suit=Suit.HEARTS, rank=Rank.SEVEN),
            Card(suit=Suit.HEARTS, rank=Rank.EIGHT),
            Card(suit=Suit.CLUBS, rank=Rank.SEVEN),
        }
        deal = Deal(players=players, bidder_index=0, trump_suit=Suit.HEARTS)
        trick = Trick(deal=deal, leading_player_index=0)

        trick.play(Card(suit=Suit.HEARTS, rank=Rank.KING))

        self.assertEqual(
            {
                Card(suit=Suit.HEARTS, rank=Rank.QUEEN),
                Card(suit=Suit.HEARTS, rank=Rank.EIGHT),
                Card(suit=Suit.HEARTS, rank=Rank.SEVEN),
            },
            trick.legal_cards,
        )
示例#26
0
    def test_cards_can_be_compared_if_non_trump_suit_is_led(self) -> None:
        players = [Player(), Player(), Player(), Player()]
        players[0].hand = {Card(suit=Suit.SPADES, rank=Rank.QUEEN)}
        deal = Deal(players=players, bidder_index=0, trump_suit=Suit.CLUBS)
        trick = Trick(deal=deal, leading_player_index=0)

        # The led suit will be Spades, but the trump suit is Clubs.
        trick.play(Card(suit=Suit.SPADES, rank=Rank.QUEEN))

        # Any trump card will rank higher than any non-trump card, regardless whether
        # that other card was in the led suit or not.
        for first_rank, second_rank, second_suit in product(Rank, Rank, Suit):
            # We are testing non-trump cards for the second card, so skip the trump cards.
            if second_suit == deal.trump_suit:
                continue

            assert deal.trump_suit is not None
            self.assertEqual(
                -1,
                trick.compare_cards(
                    Card(suit=deal.trump_suit, rank=first_rank),
                    Card(suit=second_suit, rank=second_rank),
                ),
            )

        # Any card in the led suit beats any other card that is not trump or in the led suit.
        for first_rank, second_rank, second_suit in product(Rank, Rank, Suit):
            # We are testing second cards that are non-trump and not the led suit, so skip those.
            if second_suit == deal.trump_suit or second_suit == trick.led_suit:
                continue

            assert trick.led_suit is not None
            self.assertEqual(
                -1,
                trick.compare_cards(
                    Card(suit=trick.led_suit, rank=first_rank),
                    Card(suit=second_suit, rank=second_rank),
                ),
            )

        # Two cards both in the led suit will obey the regular order.
        self.assertEqual(
            -1,
            trick.compare_cards(
                Card(suit=Suit.SPADES, rank=Rank.QUEEN),
                Card(suit=Suit.SPADES, rank=Rank.JACK),
            ))
        self.assertEqual(
            -1,
            trick.compare_cards(
                Card(suit=Suit.SPADES, rank=Rank.TEN),
                Card(suit=Suit.SPADES, rank=Rank.NINE),
            ))

        # Two cards that both are neither trump nor the led suit will be incomparable.
        for first_rank, first_suit, second_rank, second_suit in product(
                Rank, Suit, Rank, Suit):
            if first_suit in [
                    deal.trump_suit, trick.led_suit
            ] or second_suit in [deal.trump_suit, trick.led_suit]:
                continue

            self.assertEqual(
                0,
                trick.compare_cards(
                    Card(suit=first_suit, rank=first_rank),
                    Card(suit=second_suit, rank=second_rank),
                ),
            )
示例#27
0
    def test_a_trick_without_played_cards_has_no_leading_suit(self) -> None:
        players = [Player(), Player(), Player(), Player()]
        deal = Deal(players=players, bidder_index=0)
        trick = Trick(deal=deal, leading_player_index=0)

        self.assertEqual(None, trick.led_suit)
示例#28
0
 def test_a_deal_can_be_initialized(self) -> None:
     players = [Player(), Player(), Player(), Player()]
     for bidder_index in range(4):
         deal = Deal(players=players, bidder_index=bidder_index)
         self.assertEqual(True, isinstance(deal, Deal))
示例#29
0
 def test_a_deal_throws_an_error_if_an_invalid_player_requests_his_teammate(self) -> None:
     players = [Player(name="1"), Player(name="2"), Player(name="3"), Player(name="4")]
     deal = Deal(players=players, bidder_index=0)
     unknown_player = Player(name="5")
     self.assertRaises(ValueError, deal.get_teammate_index, [unknown_player])
示例#30
0
 def bad_initialization() -> None:
     players = [Player(), Player(), Player(), Player()]
     with patch("builtins.input", return_value="bad_suit"):
         deal = Deal(players=players, bidder_index=0)
         deal.initialize()
示例#31
0
    def test_trick_initialization(self) -> None:
        players = [Player(), Player(), Player(), Player()]
        deal = Deal(players=players, bidder_index=0)
        trick = Trick(deal=deal, leading_player_index=0)

        self.assertEqual(True, isinstance(trick, Trick))
示例#32
0
    def test_a_deal_can_be_initialized_with_preset_trump_suit(self) -> None:
        players = [Player(), Player(), Player(), Player()]

        for suit in Suit:
            deal = Deal(players=players, bidder_index=0, trump_suit=suit)
            self.assertEqual(True, isinstance(deal, Deal))
示例#33
0
import webbrowser

import sqlobject

import settings
from models import Deal

conn = sqlobject.connectionForURI(settings.CONNECTION_STRING)
sqlobject.sqlhub.processConnection = conn

deals = Deal.select()
f = open('dump.html', 'wb')

print >> f, """
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
"""
for deal in deals:
    print >> f, '<li>'
    print >> f, '<ul>'
    print >> f, '<li>%s</li>' % deal.title.encode('utf8')
    print >> f, '<li>%s/%s</li>' % (deal.price, deal.originalPrice)
    print >> f, '<li>%s</li>' % deal.detail.encode('utf8')
    print >> f, '</ul>'
    print >> f, '</li>'
print >> f, '</ul>'
print >> f, '</body>'
print >> f, '</html>'