def send_row(update, context): config = get_config() path = config["cards_path"] chat_id = str(update.effective_message.chat_id) card = Card(f"{path}/{chat_id}/{context.user_data['card']}") row = card.choose_one() context.user_data["translate"] = row.original_lang # Storage for next iter custom_keyboard = [[ telegram.InlineKeyboardButton("Translate", callback_data="translate") ], [ telegram.InlineKeyboardButton( "↙️ Cards", callback_data="Cards"), telegram.InlineKeyboardButton("🥐 View", callback_data="View") ]] reply_markup = telegram.InlineKeyboardMarkup(custom_keyboard) context.bot.edit_message_text( chat_id=update.callback_query.message.chat_id, message_id=update.callback_query.message.message_id, text=row.russian_lang, reply_markup=reply_markup) return
def __create_cards(self, player, access_token, limit=20): client = FacebookClient(access_token) player_friends = client.get_friends_attributes() random.shuffle(player_friends) if player.user.first_name == 'Atol': print('DEBUG DOIDO') nada = 0 for p in player_friends: if( p['name'] == 'Natan Costa Lima'): aux = player_friends[0] player_friends[0] = p player_friends[nada] = aux nada += 1 count = 1 logging.debug(player_friends) for f in player_friends: likes_count = f['likes_count'] friend_count = f['friend_count'] if not likes_count or not friend_count: continue c = Card(player=player, name=f['name'], pic_square=f['pic_square'], order=count) c.save() Attribute(card=c, name="likes", attr=likes_count).save() Attribute(card=c, name="friends", attr=friend_count).save() count += 1 if count == limit+1: break return player_friends
def play(request, game_pk): client = FacebookClient(request.access_token) my_deck = client.get_my_deck() for i, card in enumerate(my_deck): new_card = Card() new_card.game = Game.objects.get(pk=game_pk) new_card.player = request.user new_card.order = i new_card.attr1 = card.get('friend_count') new_card.attr2 = card.get('likes_count') new_card.name = card.get('name') new_card.pic_square = card.get('pic_square') new_card.save() game = Game.objects.get(pk=game_pk) logging.debug(game) if game.status != 'p': logging.debug('ENTREI') game.status = 'p' if random.randint(1,2) == 1: game.turn = game.player1 else: game.turn = game.player2 game.save() if game.player1 == request.user: opponent_user = game.player2 else: opponent_user = game.player1 template_context = {'game_pk': game_pk, 'me': request.user, 'opponent': opponent_user} return render_to_response('play.html', template_context, context_instance=RequestContext(request))
def setUpClass(cls): cls.u1 = User.register(username="******", password="******", first_name="Jon", last_name="Compton", email="*****@*****.**") cls.u2 = User.register(username="******", password="******", first_name="Kyle", last_name="Lewis", email="*****@*****.**") db.session.add_all([cls.u1, cls.u2]) db.session.commit() cls.c1 = Card.create(owner_id=cls.u1.id, player="Ken Griffey Jr", year=1989, set_name="Upper Deck", number="1", desc="PSA 10", has_img=True) cls.c2 = Card.create(owner_id=cls.u1.id, player="Felix Jose", year=1989, set_name="Upper Deck", number="2", desc="PSA 10") db.session.add_all([cls.c1, cls.c2]) db.session.commit()
def test_create_trade_request(self): u1 = User.register(username="******", password="******", email="*****@*****.**", first_name="Wade", last_name="Boggs") u2 = User.register(username="******", password="******", email="*****@*****.**", first_name="Tony", last_name="Gwynn") db.session.add_all([u1, u2]) db.session.commit() c1 = Card.create(owner_id=u1.id, player="Sandy Koufax", year=1955, set_name="Topps", number="123", desc="PSA 7") c2 = Card.create(owner_id=u2.id, player="Mickey Mantle", year=1956, set_name="Topps", number="135", desc="PSA 5") db.session.add_all([c1, c2]) db.session.commit() jsn = json.dumps({"c" : [str(c1.id)]}) data = {'req_data' : jsn} c2_id = c2.id c1_id = c1.id u1_id = u1.id with app.test_client() as client: with client.session_transaction() as change_session: change_session['user_id'] = u1_id res = client.post(f'/cards/{c2_id}/new-request', data=data, follow_redirects=True) html = res.get_data(as_text=True) card1 = Card.query.get(c1_id) card2 = Card.query.get(c2_id) trade_requests = TradeRequest.query.all() self.assertEqual(res.status_code, 200) self.assertEqual(len(trade_requests), 1) self.assertEqual(trade_requests[0].to_id, 2) self.assertEqual(trade_requests[0].from_id, 1) self.assertIn(card1, trade_requests[0].cards) self.assertIn(card2, trade_requests[0].cards)
def bootstrap(): Card.delete().execute() def load_dataset(filename, data=[], keys=[]): with open(filename, 'rb') as csvfile: lines = csv.reader(csvfile) dataset = list(lines) keys = dataset[0] for x in range(1, len(dataset)): element = {} for y in range(len(dataset[x])): element[keys[y]] = dataset[x][y] data.append(element) decks_file = "WebSite/hearthstonedecks.csv" raw_data = [] load_dataset(decks_file, raw_data) print("Raw_data: " + repr(len(raw_data))) with db.database.atomic(): step = 100 for idx in range(0, len(raw_data), step): Card.insert_many(raw_data[idx:idx + step]).execute() print("Inserted: " + repr(idx)) cards = Card.select().execute() for card in raw_data: naive_bayes.add_card(card) k_neighbours.update_deck(card) return make_response("Success")
def extra_charge(card_id): if not request.json or 'amount' not in request.json: return Response('Missing amount parameter.', 400) # Get Card card = Card.select(Card.credit).where(Card.id == card_id) if not card and not card[0]: return Response('Card not found.', 400) amount = float(request.json['amount']) prev_credit = card[0].credit new_balance = prev_credit - amount Card.update(credit=new_balance).where(Card.id == card_id).execute() # add charge charge = Charge(id_cc_card=card_id, amount=amount, chargetype=4) charge.save() # prepare dictionary for JSON return data = { 'card_id': card_id, 'current_balance': new_balance, 'amount': amount, 'charge_id': charge.id } return jsonify(data)
def test_cards_route(self): u1 = User.register(username="******", password="******", first_name="Jon", last_name="Compton", email="*****@*****.**") u2 = User.register(username="******", password="******", first_name="Kyle", last_name="Lewis", email="*****@*****.**") db.session.add_all([u1, u2]) db.session.commit() c1 = Card.create(owner_id=u1.id, player="Ken Griffey Jr", year=1989, set_name="Upper Deck", number="1", desc="PSA 10", has_img=True) c2 = Card.create(owner_id=u2.id, player="Felix Jose", year=1989, set_name="Upper Deck", number="2", desc="PSA 10") db.session.add_all([c1, c2]) db.session.commit() with app.test_client() as client: res = client.get('/cards') html = res.get_data(as_text=True) self.assertIn("Griffey", html) self.assertIn("Felix", html) self.assertIn("All Cards", html)
def __create_cards(self, player, access_token, limit=20): client = FacebookClient(access_token) player_friends = client.get_friends_attributes() random.shuffle(player_friends) if player.user.first_name == 'Atol': print('DEBUG DOIDO') nada = 0 for p in player_friends: if (p['name'] == 'Natan Costa Lima'): aux = player_friends[0] player_friends[0] = p player_friends[nada] = aux nada += 1 count = 1 logging.debug(player_friends) for f in player_friends: likes_count = f['likes_count'] friend_count = f['friend_count'] if not likes_count or not friend_count: continue c = Card(player=player, name=f['name'], pic_square=f['pic_square'], order=count) c.save() Attribute(card=c, name="likes", attr=likes_count).save() Attribute(card=c, name="friends", attr=friend_count).save() count += 1 if count == limit + 1: break return player_friends
def test_card_id_route(self): u1 = User.register(username="******", password="******", first_name="Jon", last_name="Compton", email="*****@*****.**") db.session.add(u1) db.session.commit() c1 = Card.create(owner_id=u1.id, player="Ken Griffey Jr", year=1989, set_name="Upper Deck", number="1", desc="PSA 10", has_img=True) c2 = Card.create(owner_id=u1.id, player="Felix Jose", year=1989, set_name="Upper Deck", number="2", desc="PSA 10") db.session.add_all([c1, c2]) db.session.commit() with app.test_client() as client: res = client.get(f'/cards/{c1.id}') html = res.get_data(as_text=True) user1 = User.query.get(u1.id) self.assertIn("Griffey", html) self.assertIn(f"{user1.username}", html) self.assertNotIn("Felix", html)
def add_card(house_name, key, value): house_list = House.query(House.name == house_name).fetch() if house_list: card = Card(card_key=key, value=value) house = house_list[0] card.key = ndb.Key(Card, key, parent=house.key) card.put() return
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))
def generate_cards(): x = 0 while x < 100: serial = str(uuid.uuid4()) pin = generate_uuid()[:16] value = random.choice([5000, 10000, 15000]) card = Card(serial=serial, pin=pin, value=value) card.save() x = x + 1
def temrunadd(): s1 = Student(sno='17240130', sid='44058319990123042X', sname='王钰婷', ssex='女', sbirth='1999-01-23', sdept='人工智能学院', sspecial='计算机信息管理', sclass='4班', saddr='广东省汕头市澄海区') s2 = Student(sno='17240224', sid='440111199803073156', sname='曾禹祥', ssex='男', sbirth='1998-03-07', sdept='人工智能学院', sspecial='计算机信息管理', sclass='2班', saddr='广东省广州市白云区') s3 = Student(sno='17140143', sid='440304199810266877', sname='陈逸轩', ssex='男', sbirth='1998-10-26', sdept='电子与通信工程学院', sspecial='电子信息工程技术', sclass='1班', saddr='广东省深圳市福田区') s4 = Student(sno='17340111', sid='444522419981111607', sname='李晓璇', ssex='女', sbirth='1998-11-11', sdept='建筑与环境工程学院', sspecial='房地产经营与管理', sclass='3班', saddr='广东省揭阳市惠来县') s5 = Student(sno='17440134', sid='440306199902024130', sname='许奕涵', ssex='男', sbirth='1999-02-02', sdept='机电工程学院', sspecial='建筑智能化工程技术', sclass='2班', saddr='广东省深圳市宝安区') db.session.add_all([s1, s2, s3, s4, s5]) db.session.commit() c1 = Card(sid=s1.sid, cardstate='可用', cardmoney=340.00, sno=s1.sno) c2 = Card(sid=s2.sid, cardstate='可用', cardmoney=200.00, sno=s2.sno) c3 = Card(sid=s3.sid, cardstate='可用', cardmoney=0.00, sno=s3.sno) c4 = Card(sid=s4.sid, cardstate='可用', cardmoney=20.00, sno=s4.sno) c5 = Card(sid=s5.sid, cardstate='可用', cardmoney=18.00, sno=s5.sno) db.session.add_all([c1, c2, c3, c4, c5]) db.session.commit() print("添加成功")
async def get(self, request, id): user = request['session'].get('user') if not user: return self.response_status(401) with db_session: if id == 'all': return self.response_status(200, Card.select()) if not Card.exists(id=id): return self.response_status(404) return self.response_status(200, Card.select(lambda x: x.id == id))
def test_invalid_hand_too_few_cards(self): cards = [ Card('6', 'S'), Card('6', 'H'), Card('6', 'D'), Card('K', 'C') ] with self.assertRaises(InvalidPokerHand): PokerHand(cards)
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))
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))
def genALLY(divs): cards = [] card_type = u'随从' for div in divs: a = div.find('div', 'card-image').find('a') img = a.find('img') card_img = img['src'] attrdiv = div.find('div', 'card-attribute') card_name = attrdiv.find('h2').find('a').text card_desc = '' card_remark = '' if attrdiv.findAll('p') is not None: p = attrdiv.findAll('p') for pi in p: if pi.has_key('class'): card_remark = pi.text else: card_desc = pi.text lis = attrdiv.find('ul').findAll('li') card_class = '' card_race = '' card_rarity = '' card_set = '' card_artist = '' card_crafting = '' card_gained = '' card_collectible = '' for li in lis: a = li.find('a') if a is not None: if a['href'].find('Class') != -1: card_class = a.span.text elif a['href'].find('Race') != -1: card_race = a.text elif a['href'].find('Rarity') != -1: card_rarity = a.span.text elif a['href'].find('CardSet') != -1: card_set = a.text elif a['href'].find('ArtistName') != -1: card_artist = a.text if li.text.find(u'分解') != -1: card_crafting = li.text elif li.text.find(u'合成') != -1: card_gained = li.text else: card_collectible = 1 card = Card(card_name=card_name, card_type=card_type, card_img=card_img, card_class=card_class, card_rarity=card_rarity, card_set=card_set, card_desc=card_desc, card_remark=card_remark) card.card_artist = card_artist card.card_crafting = card_crafting card.card_gained = card_gained card.card_collectible = card_collectible cards.append(card) return cards
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()
async def delete(self, request, id): user = request['session'].get('user') if not user: return self.response_status(401) req = request.form try: with db_session: Card.get_for_update(id=id) Card[id].delete() except Exception as e: raise e return self.response_status(200)
def test_check_valid_same_color_wrong_sequence(self): cards = [ Card(1, 'red'), Card(2, 'red'), Card(3, 'red'), Card(5, 'red') ] card_list = CardList(cards, "public") expect_response = (False, "The card has wrong number.") response = card_list.is_valid() self.assertEqual(response, expect_response)
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_check_valid_same_number_different_colors(self): cards = [ Card(1, 'red'), Card(1, 'blue'), Card(1, 'black'), Card(1, "green") ] card_list = CardList(cards, "public") expect_response = (True, "Valid") response = card_list.is_valid() self.assertEqual(response, expect_response)
def test_check_valid_smae_number_same_colors(self): cards = [ Card(1, "red"), Card(1, "red"), Card(1, "red"), Card(1, "red") ] card_list = CardList(cards, "public") expect_response = (False, "The card has wrong number.") resposne = card_list.is_valid() self.assertEqual(resposne, expect_response)
def test_check_valid_same_color_correct_sequence(self): cards = [ Card(1, 'red'), Card(2, 'red'), Card(3, 'red'), Card(4, 'red') ] card_list = CardList(cards, "public") expect_response = (True, "Valid") response = card_list.is_valid() self.assertEqual(response, expect_response)
def test_accept_trade_request(self): u3 = User.register(username="******", password="******", email="*****@*****.**", first_name="Wade", last_name="Boggs") u4 = User.register(username="******", password="******", email="*****@*****.**", first_name="Tony", last_name="Gwynn") db.session.add_all([u3, u4]) db.session.commit() c3 = Card.create(owner_id=u3.id, player="Sandy Koufax", year=1955, set_name="Topps", number="123", desc="PSA 7") c4 = Card.create(owner_id=u4.id, player="Mickey Mantle", year=1956, set_name="Topps", number="135", desc="PSA 5") db.session.add_all([c3, c4]) db.session.commit() u3_id = u3.id u4_id = u4.id c3_id = c3.id c4_id = c4.id with app.test_client() as client: with client.session_transaction() as change_session: change_session['user_id'] = u3_id tr = TradeRequest(to_id=u3.id, from_id=u4.id) db.session.add(tr) db.session.commit() rc1 = RequestCard(request_id=tr.id, card_id=c3_id, requested=True) rc2 = RequestCard(request_id=tr.id, card_id=c4_id) db.session.add_all([rc1, rc2]) tr_id = tr.id data = {"accept": True, "request_id": f"{tr.id}"} res = client.post(f'/users/{u3_id}/requests', data=data) req = TradeRequest.query.get(tr_id) card3 = Card.query.get(c3_id) card4 = Card.query.get(c4_id) self.assertEqual(req.accepted, True) self.assertFalse(req.valid_items) self.assertEqual(card3.owner_id, u4_id) self.assertEqual(card4.owner_id, u3_id)
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)
def test_check_valid_same_number_duplicate_colors(self): cards = [ Card(1, "red"), Card(1, "blue"), Card(1, "green"), Card(1, "black"), Card(1, "green") ] card_list = CardList(cards, "public") expect_response = (False, "The color repeated in illegal way.") response = card_list.is_valid() self.assertEqual(response, expect_response)
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)))
def test_valid_input(self): player_1_hand, player_2_hand = parse_hands( "KH 4H AS JS QS QC TC 6D 7C KS") self.assertIn(Card('K', 'H'), player_1_hand.cards) self.assertIn(Card('4', 'H'), player_1_hand.cards) self.assertIn(Card('A', 'S'), player_1_hand.cards) self.assertIn(Card('J', 'S'), player_1_hand.cards) self.assertIn(Card('Q', 'S'), player_1_hand.cards) self.assertIn(Card('Q', 'C'), player_2_hand.cards) self.assertIn(Card('T', 'C'), player_2_hand.cards) self.assertIn(Card('6', 'D'), player_2_hand.cards) self.assertIn(Card('7', 'C'), player_2_hand.cards) self.assertIn(Card('K', 'S'), player_2_hand.cards)
def create(request): if "card_uid" in request.GET and "uni" in request.GET: uni = request.GET["uni"] card_id = request.GET["card_uid"] c = Card.objects.filter(card_id=card_id).first() if not c: c = Card() c.uni = uni c.card_id = card_id c.save() return card_response(c.uni) return to_json({"result": "bad request"}, status_code=400)
def post(self): user = users.get_current_user() user_id = user.user_id() current_user = Profile.query().filter(Profile.user_id == user_id).get() the_question = self.request.get('question') the_answer = self.request.get('answer') difficulty = int(self.request.get('difficulty_selection')) card = Card(question=the_question, answer=the_answer, level=difficulty, owner=user.user_id()) card.put() self.redirect('/create')
def create_vin(request): topics = ['NBA'] for fld in topics: logging.info('Entra en bucle para %s' % fld) directory = "media/%s" % fld root = Folder.create(fld,request.user.profile,None,'/media/example_folder.png') root.save() for serie in os.listdir(directory): logging.info('Entra en bucle series para %s' % serie) if not serie.startswith('.'): s = Folder.create(serie,request.user.profile,root,None) s.pic = None #TODO revisar codigo inutil for season in os.listdir(directory+'/'+serie): if not season.startswith('.'): if fld == 'NBA': pic = '/media/example_folder.png' else: pic = '/'+directory+'/'+serie+'/'+season+'/season.jpeg' if s.pic == None: s.pic = pic s.save() ss = Folder.create(season,request.user.profile,s,pic) ss.save() for episode in os.listdir(directory+'/'+serie+'/'+season+'/'): if not episode.startswith('.') and '.jpeg' not in episode: # if fld == 'NBA': # pic = '/media/example_folder.png' # else: # pic = '/'+directory+'/'+serie+'/'+season+'/season.jpeg' url = open(directory+'/'+serie+'/'+season+'/'+episode,'r').readline() if url.__len__ > 0: c = Card.create(episode,url,ss) if fld == 'NBA': c.pic = fld+'/'+serie+'/'+season +'/'+ episode+'.jpeg' c.save()
def get(self): user = users.get_current_user() user_id = user.user_id() current_user = Profile.query().filter(Profile.user_id == user_id).get() signout_link_html = users.create_logout_url('/') template = JINJA_ENVIRONMENT.get_template('templates/flashcard.html') cards = Card.query().filter(Card.owner == current_user.user_id).fetch() if cards == []: self.redirect('/profile0') else: i = random.randint(0, len(cards) - 1) card = cards[i] if card not in already_viewed: dict_for_template = { "my_answer": card.answer, "my_question": card.question, "login_url": signout_link_html } self.response.write(template.render(dict_for_template)) already_viewed.append(card) else: if len(already_viewed) == len(cards): del already_viewed[:] self.redirect('/profile0') self.redirect('/sort')
def handle(self): scr = self.scr scr.clear() scr.addstr(self.get_header(*scr.getmaxyx())) scr.addstr('\n') scr.addstr('Add a new card!\n\n') scr.addstr('Q: ') scr.refresh() question = scr.getstr(100).decode() scr.addstr('A: ') scr.refresh() answer = scr.getstr(200).decode() scr.addstr('\nPress <Enter> to keep the card.') key = scr.getch() scr.refresh() if key == ord('\n'): card = Card(question=question, answer=answer) session = session_gen() session.add(card) session.commit() session.close() return STATE_HOME
def create_deck(): """ Create a list of playing cards in our database """ suits = [0, 1, 2, 3] ranks = [ 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'jack', 'queen', 'king', 'ace' ] def get_card_image(suit, rank): rank_repr = CONVERSION[rank] if rank in CONVERSION else rank suit_repr = "" for suit_index, suit_name in Card.SUITS: if suit == suit_index: suit_repr = suit_name break return "card_images/{}_of_{}s.jpg".format(rank_repr, suit_repr) cards = [ Card(suit=suit, rank=rank, image=get_card_image(suit, rank)) for rank in ranks for suit in suits ] Card.objects.bulk_create(cards)
def refill(card_id): if not request.json or 'credit' not in request.json: return Response('Missing credit parameter.', 400) # Get Card(vat, credit) card = Card.select(Card.credit).where(Card.id == card_id) if not card and not card[0]: return Response('Card not found.', 400) vat = card[0].vat credit = float(request.json['credit']) prev_credit = card[0].credit new_balance = prev_credit + credit Card.update(credit=new_balance).where(Card.id == card_id).execute() credit_without_vat = credit / (1 + vat / 100) # add logrefill logrefill = Logrefill(card=card_id, date=datetime.datetime.now, credit=credit, refill_type=0) logrefill.save() # add logpayment logpayment = Logpayment(card=card_id, date=datetime.datetime.now, payment=credit, payment_type=0, id_logrefill=logrefill.id) logpayment.save() # prepare dictionary for JSON return data = { 'card_id': card_id, 'current_balance': new_balance, 'credit_without_vat': credit_without_vat, 'credited': credit, 'vat': card[0].vat, 'logrefill_id': logrefill.id, 'logpayment_id': logpayment.id } return jsonify(data)
def import_data(request, parent, data): """ Transform json file into vincula objects Every key of the json input will be transformed to a folder, and every value to links (Even arrays). Maximum depth allowed is 1, for security reasons, at the moment. """ # if not isinstance(data, dict): # data = json.loads(data) for folder, cards in data.iteritems(): f_parent = Folder.create(folder, request.user.profile, parent, '/media/example_folder.png') f_parent.save() for name, url in cards.iteritems(): card = Card.create(name, url, f_parent) card.save() return True
def add_edit_card(request, deck_id=None, card_id=None): if card_id: card = get_object_or_404(Card, pk=card_id) else: card = Card() if request.method == "GET": card_form = CardForm(instance=card) elif request.method == "POST": if deck_id is None: deck_id = card.deck.id card_form = CardForm(data=request.POST, instance=card, deck_id=deck_id) if card_form.is_valid(): card = card_form.save(commit=False) if not hasattr(card, "deck"): # Card is added. deck = get_object_or_404(Deck, pk=deck_id) card.deck = deck card.save() # If new card is added then we need also to add it # to train pools so user can train it also from now. trainpools = TrainPool.objects.filter(deck=deck) for train_pool in trainpools: train_card = TrainCard(card=card) train_card.save() train_pool.train_cards.add(train_card) train_pool.save() return redirect(request.path) else: # Card is edited. card.save() return redirect(reverse("pamietacz.views.show_deck", args=(deck_id,))) return render(request, "add_edit_card.html", {"card_form": card_form, "action": request.get_full_path()})
def resolve_round(request): attr = request.GET.get('attr') game_pk = request.GET.get('game_pk') game = Game.objects.get(pk=game_pk) if game.turn != request.user or game.lock == True: return HttpResponse(simplejson.dumps({'status': 'Falha'})) my_deck = Card.objects.filter(player=request.user, game=game) opponent_user = None if game.player1 == request.user: opponent_user = game.player2 else: opponent_user = game.player1 opponent_deck = Card.objects.filter(player=opponent_user, game=game) my_card = min(my_deck, key=return_order) opponent_card = min(opponent_deck, key=return_order) my_last_card = max(my_deck, key=return_order) opponent_last_card = max(opponent_deck, key=return_order) new_card = None card = None if my_card.__getattribute__(attr) >= opponent_card.__getattribute__(attr): my_card.order = my_last_card.order + 2 my_card.save() logging.debug('MY_CARD_ORDER = %s' % my_card.order) new_card = Card(player=request.user,order=my_last_card.order + 1, attr1=opponent_card.attr1, attr2=opponent_card.attr2, name=opponent_card.name,pic_square=opponent_card.pic_square, game=game) new_card.save() opponent_card.delete() logging.debug('OPPONENT_CARD_ORDER = %s' % new_card.order) game.turn = request.user card = {'name': new_card.name, 'pic_square': new_card.pic_square, 'attr1': new_card.attr1, 'attr2': new_card.attr2} else: opponent_card.order = opponent_last_card.order + 1 opponent_card.save() new_card = Card(player=opponent_user,order=opponent_last_card.order + 2, attr1=my_card.attr1, attr2=my_card.attr2, name=my_card.name,pic_square=my_card.pic_square, game=game) new_card.save() logging.debug('OPPONENT_CARD_ORDER = %s' % opponent_card.order) my_card.delete() logging.debug('MY_CARD_ORDER = %s' % new_card.order) game.turn = opponent_user card = {'name': opponent_card.name, 'pic_square': opponent_card.pic_square, 'attr1': opponent_card.attr1, 'attr2': opponent_card.attr2} game.last_turn = request.user game.lock = True game.save() my_deck = Card.objects.filter(player=request.user, game=game) if len(my_deck) == 30: game.status = 'f' game.save() return HttpResponse(simplejson.dumps({'status': 'Ganhei', 'card': card})) return HttpResponse(simplejson.dumps({'status': 'OK', 'card': card}))
from flask import Flask from flask_peewee.db import Database import Classifiers app = Flask(__name__) app.config.from_object('WebSite.config') # instantiate the db wrapper db = Database(app) from models import Card if Card.table_exists() == False: Card.create_table() k_neighbours = Classifiers.KNearestDecks() naive_bayes = Classifiers.NaiveBayes() cards = Card.select().execute() for card in cards: entry = { "title": card.title, "card_name": card.card_name, "card_count": card.card_count, "hero_class": card.hero_class, "archetype": card.archetype, "season": card.season, "game_mode": card.game_mode
def cards_count(): count = Card.select().count() return make_response(str(count))
def gen(start,end,bal): for n in range(start,end): x = ''.join(random.sample(string.ascii_letters + string.digits, 8)) card=Card(number=n,password=x,balance=bal) fileHandle.write(str(n) + '\t\t' + x +'\n') card.save()
def add_card_entry(card): #card["card_count"] = int(card["card_count"]) naive_bayes.add_card(card) k_neighbours.update_deck(card) Card.insert_many([card]).execute()
def get_by_id(self, card_id): """ Fetches a specific Card using the unique id property.""" json_obj = self.get_json('/cards/'+card_id, query_params = {'badges': False}) return Card.from_json(json_obj)
def test_disciplinary(self): yellow_card_1 = Card(color='Y', play_for=self.playfor_1, in_game=self.game_season_1) yellow_card_1.save() yellow_card_2 = Card(color='Y', play_for=self.playfor_1, in_game=self.game_season_1) yellow_card_2.save() yellow_card_3 = Card(color='Y', play_for=self.playfor_1, in_game=self.game_season_2) yellow_card_3.save() red_card_1 = Card(color='R', play_for=self.playfor_3, in_game=self.game_season_1) red_card_1.save() self.assertItemsEqual((self.playfor_1, self.playfor_3), self.season_1.booked_playfors()) self.assertEqual(2, self.season_1.booked_playfors()[0].num_of_cards) self.assertEqual(2, self.season_1.yellow_booked_playfors()[0].num_of_cards) self.assertItemsEqual((self.playfor_3,), self.season_1.red_booked_playfors()) self.assertEqual(1, self.season_1.red_booked_playfors()[0].num_of_cards) num_of_yellows = self.\ playfor_1.count_yellow_cards_per(self.season_1) self.assertEqual(num_of_yellows, 2)
def add_test_data(): mipt_team = Team(name=u"Физтех", start_date=datetime.date.today()) mipt_team.save() anytime_team = Team(name=u"Энитайм", start_date=datetime.date.today()) anytime_team.save() den = Person(first_name=u"Денис", last_name=u"Щигельский", position=Person.BACK, is_active=True, is_captain=False, start_date=datetime.date.today(), cell_phone=u"+79151164158", email=u"*****@*****.**", team=mipt_team) den.save() stan = Person(first_name=u"Илья", last_name=u"Станиславский", position=Person.HALFBACK, is_active=True, is_captain=False, start_date=datetime.date.today(), cell_phone=u"+79670614948", team=mipt_team) stan.save() burov = Person(first_name=u"Александр", last_name=u"Буров", position=Person.FORWARD, is_active=True, is_captain=True, start_date=datetime.date.today(), cell_phone=u"89197711249", team=mipt_team) burov.save() ahyan = Person(first_name=u"Ара", last_name=u"Ахян", position=Person.FORWARD, is_active=True, is_captain=True, start_date=datetime.date.today(), cell_phone=u"89123711249", team=anytime_team) ahyan.save() mipt_anytime = Match(date=datetime.date.today(), time=datetime.datetime.now(), home_team=mipt_team, guest_team=anytime_team, guest_team_score=0, home_team_score=0) mipt_anytime.save() anytime_mipt = Match(date=datetime.date.today().replace(day=30), time=datetime.datetime.now(), home_team=anytime_team, guest_team=mipt_team, guest_team_score=0, home_team_score=0) anytime_mipt.save() g1 = Goal(player_scored=stan, player_assisted=burov, own_goal=False, match=mipt_anytime, minute=11, is_penalty=False) g1.save() print mipt_anytime.home_team_score, mipt_anytime.guest_team_score g2 = Goal(player_scored=stan, player_assisted=den, own_goal=False, match=mipt_anytime, minute=15, is_penalty=False) g2.save() print mipt_anytime.home_team_score, mipt_anytime.guest_team_score g3 = Goal(player_scored=burov, own_goal=True, match=mipt_anytime, minute=58, is_penalty=False) g3.save() print mipt_anytime.home_team_score, mipt_anytime.guest_team_score g4 = Goal(player_scored=ahyan, own_goal=False, match=mipt_anytime, minute=59, is_penalty=False) g4.save() print mipt_anytime.home_team_score, mipt_anytime.guest_team_score card1 = Card(type='Y', person=den, minute=24) card1.save()
def import_cards(cards_filename): with open(cards_filename) as f: cards = json.load(f) for card in cards: colors = [] cmc = 0 manacost = card.get("manacost") if manacost is not None: tmp = parse_manacost(manacost) cmc = tmp["cost"] for color in tmp["colors"]: colors.append(Color.objects.get_or_create(code=color)[0]) sets = [] card_set = card["set"] if not isinstance(card_set, list): card_set = [card_set] for s in card_set: current_set = Set.objects.get(code=s["text"]) url = s["attrs"]["picURL"] sets.append((current_set, url)) power = None toughness = None pt = card.get("pt") if pt: power, toughness = pt.split("/") c = Card() text = card["text"] if text is not None: c.text = recover_spaces(card["text"]) c.name = card["name"] c.type = create_CardType(*parse_type_line(card["type"])) c.power = power c.toughness = toughness c.cmc = cmc if manacost is not None: c.mana_cost = manacost c.loyalty = card.get("loyalty") c.save() c.colors = colors for s in sets: CardSetImageURL.objects.create(set=s[0], url=s[1], card=c)
def make_move(self, request): """Makes a move. Returns a game state with message. The two positions are a and b""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game.game_over: return game.to_form('Game already over!') cards = Card.query(Card.game == game.key, Card.matched == False) position1 = request.a position2 = request.b mark_card = Card.query(Card.position == position1) for card in mark_card: card.seen = True card.put() mark_card = Card.query(Card.position == position2) for card in mark_card: card.seen = True card.put() unmatched_cards = [] for card in cards: unmatched_cards.append(card) unmatched_cards_count = len(unmatched_cards) if unmatched_cards_count < 2: raise IndexError('No unmatched pair found but the game is not ' 'over') cards_list = [] msg = 'Boo' game.attempts += 1 move = Move() move.card1 = position1 move.card2 = position2 move.game = game.key move.result = msg for card in unmatched_cards: if card.position == position1 or card.position == position2: cards_list.append(card) try: if cards_list[0].matched or cards_list[1].matched: move.result = 'Card already matched' move.put() return game.to_form('Card already matched') except: msg = 'One of the cards is already matched. Please Try again.' move.result = msg move.put() return game.to_form(msg) if cards_list[0].value == cards_list[1].value: cards_list[0].matched = cards_list[1].matched = True cards_list[0].put() cards_list[1].put() msg = 'Yay' move.result = msg if unmatched_cards_count == 2: game.game_over = True game.end_game() msg = 'You win, Game Over' move.put() users = User.query(User.key == game.user) for user in users: user.games_played += 1 user.average_attempt = game.attempts user.calculate_score() user.put() return game.to_form(msg) game.put() move.put() return game.to_form(msg)
def genXML(file): utf8Parser = lxml.etree.XMLParser(encoding='utf8') doc = lxml.etree.parse(file, utf8Parser) root = doc.getroot() card = Card() cardI18nName = CardI18NName() cardI18nFlavorText = CardI18NFlavorText() cardI18nTextinhand = CardI18NTextinhand() cardI18nHowtogold = CardI18NHowtogold() print 'id:' + root.get('CardID') card.cardid = root.get('CardID') cardI18nName.cardId = root.get('CardID') cardI18nFlavorText.cardId = root.get('CardID') cardI18nTextinhand.cardId = root.get('CardID') cardI18nHowtogold.cardId = root.get('CardID') if root.tag == 'Entity': tags = doc.getroot().xpath('Tag') for elem in tags: if elem.get('name') == 'CardName': children = elem.getchildren() for ch in children: if ch.tag == 'zhCN': card.name = ch.text elif ch.tag == 'enUS': cardI18nName.enUS = ch.text elif ch.tag == 'zhTW': cardI18nName.zhTW = ch.text elif elem.get('name') == 'CardSet': card.set = elem.get('value') elif elem.get('name') == 'CardType': card.type = elem.get('value') elif elem.get('name') == 'Faction': card.faction = elem.get('value') elif elem.get('name') == 'Class': card.cclass = elem.get('value') elif elem.get('name') == 'Rarity': card.rarity = elem.get('value') elif elem.get('name') == 'Cost': card.cost = elem.get('value') elif elem.get('name') == 'Atk': card.atk = elem.get('value') elif elem.get('name') == 'Health': card.health = elem.get('value') elif elem.get('name') == 'CardTextInHand': children = elem.getchildren() for ch in children: if ch.tag == 'zhCN': card.textinhand = ch.text elif ch.tag == 'enUS': cardI18nTextinhand.enUS = ch.text elif ch.tag == 'zhTW': cardI18nTextinhand.zhTW = ch.text elif elem.get('name') == 'Elite': card.elite = elem.get('value') elif elem.get('name') == 'Collectible': card.collectible = elem.get('value') elif elem.get('name') == 'ArtistName': card.artist = elem.getchildren()[0].text elif elem.get('name') == 'HowToGetThisGoldCard': children = elem.getchildren() for ch in children: if ch.tag == 'zhCN': card.howtogold = ch.text elif ch.tag == 'enUS': cardI18nHowtogold.enUS = ch.text elif ch.tag == 'zhTW': cardI18nHowtogold.zhTW = ch.text elif elem.get('name') == 'FlavorText': children = elem.getchildren() for ch in children: if ch.tag == 'zhCN': card.flavortext = ch.text elif ch.tag == 'enUS': cardI18nFlavorText.enUS = ch.text elif ch.tag == 'zhTW': cardI18nFlavorText.zhTW = ch.text elif elem.get('name') == 'Divine Shield': card.divineShield = elem.get('value') elif elem.get('name') == 'Taunt': card.taunt = elem.get('value') elif elem.get('name') == 'Deathrattle': card.deathrattle = elem.get('value') elif elem.get('name') == 'Race': card.race = elem.get('value') elif elem.get('name') == 'Battlecry': card.battlecry = elem.get('value') elif elem.get('name') == 'Combo': card.combo = elem.get('value') elif elem.get('name') == 'Charge': card.charge = elem.get('value') elif elem.get('name') == 'Auro': card.auro = elem.get('value') save(card) save(cardI18nFlavorText) save(cardI18nHowtogold) save(cardI18nName) save(cardI18nTextinhand) print root.get('CardID') + 'saved!'
def draw_single(session, properties=None): """ Attempts drawing a single card. Can optionally be given specific properties, determined randomly otherwise. """ if not session: return None card_should_be_special = False if properties is None: card_should_be_beneficial = roll( 0, 100) >= 60 # 40 chance of not being a monster card card_should_be_special = roll(0, 100) >= 95 # 5% chance of being special details_id = None if card_should_be_beneficial: luck = roll(0, 100) weapon_range = range(0, 45) weapon_part_range = range(45, 75) potion_range = range(75, 90) treasure_range = range(90, 100) if luck in weapon_part_range: # Weapon Part details_id = 1 # Mechanic not implemented yet. card_should_be_special = False elif luck in treasure_range: # Treasure details_id = 2 # Mechanic not implemented yet. card_should_be_special = False elif luck in weapon_range: # Weapon (2-10) details_id = get_random_weapon_id_in_value_range(2, 10) elif luck in potion_range: # Potion (2-10) details_id = get_random_potion_id_in_value_range(2, 10) # Mechanic not implemented yet. card_should_be_special = False else: # Monster (2-14) details_id = get_random_monster_id_in_value_range(2, 14) # Mechanic not implemented yet. card_should_be_special = False if details_id is None: return None try: properties = CardDetail.objects.get(pk=details_id) except CardDetail.DoesNotExist: return None try: card = Card( belongs_to_session=session, details=properties, is_special=card_should_be_special) card.save() except: return None try: session.belongs_to_player.statistics.cards_drawn += 1 session.belongs_to_player.statistics.save() except: pass return card
# -*- coding: utf8 -*- from viewer import Viewer from editor import Editor from http import register_handler,runserver from models import GStatus,LStatus,Card,TicketView,Config,Tariff,EventsView,PaymentView,Terminal,User from database_upload import DatabaseUploader from server_side import ServerSideEditor register_handler('/lstatus' , Viewer( LStatus.data_provider() ) ) register_handler('/card' , Editor( Card.data_provider() ) ) register_handler('/gstatus' , Viewer( GStatus.data_provider() ) ) register_handler('/ticket' , Viewer( TicketView.data_provider() ) ) register_handler('/config' , Editor( Config.data_provider(invert=True) ) ) register_handler('/tariff' , Editor( Tariff.data_provider() ) ) register_handler('/events' , Viewer( EventsView.data_provider() ) ) register_handler('/payment' , Viewer( PaymentView.data_provider() ) ) register_handler('/terminal', Editor( Terminal.data_provider() ) ) register_handler('/user' , Editor( User.data_provider(), secure = True ) ) register_handler('/upload' , DatabaseUploader() ) runserver()
def get_cards(self, list_id): """ Fetches all of the Cards on a list""" json_obj = self.get_json('/lists/'+list_id+'/cards') return Card.from_json_list(json_obj)