Example #1
0
def newplayer(request):
  success = 0
  playerid = 0
  playername = ''
  if request.method == 'POST':
    form = NewPlayerForm(request.POST)
    if form.is_valid():
      cd = form.cleaned_data
      player = Player(name=cd['name'])
      player.save()
      squares = Square.objects.all().order_by('pk')
      if len(squares)-1 >= 24:
        squarei = random.sample(range(1,len(squares)),24)
      elif len(squares)-1 > 0:
        squarei = []
        for i in range(24):
          squarei.append(random.randint(1,len(squares)-1))
      else:
        squarei = []
        for i in range(24):
          squarei.append(0)
      for i in range(25):
        if i < 12:
          spot = Boardsquare(player=player,square=squares[squarei[i]],checked=False,order=i)
        elif i == 12:
          spot = Boardsquare(player=player,square=squares[0],checked=True,order=i)
        else:
          spot = Boardsquare(player=player,square=squares[squarei[i-1]],checked=False,order=i)
        spot.save()
      playerid = player.pk
      playername = player.name
      success = 1
  else:
    form = NewPlayerForm()
  return render(request, 'bingo/newplayer.html', {'form': form, 'success': success, 'id': playerid, 'name': playername})
Example #2
0
    def post(self):
        request_data = json.loads(self.request.body)
        logging.info(request_data)
        user = users.get_current_user()

        # VALIDATION
        if not validate_request_data(self.response, request_data, ['nick', 'player_class']):
            return
        if not validate_logged_inn(self.response):
            return
        if not self._validate_has_not_player_already(user):
            return
        if Player.query(Player.nick_lower == request_data['nick'].lower()).count() > 0:
            error_400(self.response, "ERROR_NICK_TAKEN", "The nickname %s is already taken" % request_data['nick'])
            return
        if not is_valid_player_class_name(request_data['player_class']):
            error_400(self.response, "ERROR_BAD_PLAYER_CLASS", "Player class ' %s ' is not valid." % request_data['player_class'])
            return

        # REGISTER PLAYER
        new_player = Player(
            id=user.user_id(),
            nick=request_data['nick']
        )

        for player_class in player_class_metrics:
            if player_class['name'] == request_data['player_class']:
                logging.info(player_class['stat_modifiers'])
                for stat_name, stat_value in player_class['stat_modifiers'].iteritems():
                    current_stat_value = getattr(new_player, stat_name)
                    new_stat_value = current_stat_value + stat_value
                    setattr(new_player, stat_name, new_stat_value)

        new_player.put().get()
        set_json_response(self.response, new_player.get_data("full"))
Example #3
0
    def add(self, pid):
        player = Player(
            Pid=pid
        )
        player.save()

        return player.id
Example #4
0
    def create_player(self, request):
        """Creates a new player.

        This function creates a new player. It will also make sure
        that the chosen username is not yet taken.
        (NB: Currently this function does not implement any validity checks
        on the email address, such as a regex etc.)

        Returns:
            StringMessage -- confirmation of player creation

        Raises:
            ConflictException -- if username or email address is taken already
        """
        # Check username and email address for conflicts
        if Player.query(Player.email_address == request.email_address).get():
            raise endpoints.ConflictException(
                    'A Player with that email address already exists.')
        if Player.query(Player.user_name == request.user_name).get():
            raise endpoints.ConflictException(
                    'A Player with that name already exists.')

        # Create player
        player = Player(user_name=request.user_name,
                        email_address=request.email_address)
        player.put()

        # Return confirmation of player creation
        return StringMessage(message='Player successfully created.')
Example #5
0
def player_data():
    if not request.json or 'player' not in request.json:
        print(request, request.json)
        abort(400)

    db = get_db()

    player_data = request.json['player']
    friends = player_data['friends']
    puzzle_data = player_data['puzzle_data']
    del player_data['friends']
    del player_data['puzzle_data']

    player = Player.get_or_create(player_data)
    db.session.query(Player).filter(
        Player.social_id == player.social_id).update(player_data)

    for friend_social_id in friends:
        friend = Player.get_or_create({"social_id": friend_social_id})
        player.add_friendship(friend)

    for index, puzzle_id in enumerate(puzzle_data['puzzles']):
        Score.maybe_update_score({
            'player_social_id': player.social_id,
            'puzzle_id': puzzle_id,
            'score': puzzle_data['scores'][index],
            'stars': puzzle_data['stars'][index]})

    db.session.commit()

    return jsonify(
        _assemble_response(player))
Example #6
0
 def testSaveOkCheckEmail(self):
     player = Player(self.collection, self.name, self.email, self.fbid, self.artist)
     expected = self.email
     player.save()
     q = {'e': self.email}
     actual = self.collection.find_one(q)['e']
     assert_equal(expected, actual)
Example #7
0
def get_player(nick_name='', steam_id=''):
    """
    gets player by given params.
    If player changed nickname - replaces old one in db
    If no such player - creates new
    :param nick_name:
    :param steam_id:
    :param may_be_new:
    :return:Player object
    """
    print nick_name, steam_id
    if nick_name and not steam_id:
        try:  # FIXME: temporary crutch while checking old players steam_id is impossible (asker required)
            return Player.get(nick_name=nick_name)
        except:
            player = Player.create(steam_id=0, nick_name=nick_name)
            return player
    elif steam_id and not nick_name:
        return Player.get(steam_id=steam_id)
    elif steam_id and nick_name:
        try:
            player = Player.get(steam_id=steam_id)
        except:
            player = Player.create(steam_id=steam_id, nick_name=nick_name)
        if nick_name != player.nick_name:
            player.nick_name = nick_name  # TODO: test for it
            player.save()
        return player
Example #8
0
    def player(self, message, first, last):
        ''' format sms: player first last
        
        la fonction repond une phrase au hasard a un player '''
        # creation d'un player 
        player = Player(first_name=first, \
                                last_name=last, \
                                
                                number=message.peer)
                                
        # ma liste de reponse 
        list= ["vous etes un as", 
                "vous etes formidable",
                "reesayez vous pouvez le faire", 
                'vive le SENEGAL',
                u"vous n'etes pas trop doué",
                "vous êtes un pythonier"]
        # je melange ma liste et je tire une phrase au hasard
        ran = random.choice(list)
        
        # renvoie d'une reponse        
        message.respond(u"%(att)s, %(att1)s." % {'att': player, 'att1':ran})
        # sauvegarde le player
        player.save()

        return True
Example #9
0
def update_player_position(args, latitude, longitude):
    player_id = get_player_id(args)
    Player.update(
        latitude=latitude,
        longitude=longitude,
        last_modified=datetime.now()
    ).where(Player.player_id == player_id).execute()
Example #10
0
    def get(self):

        isPlayer = login.isPlayer()
        isAdmin = login.isAdmin()

        if not isAdmin and not isPlayer:
            self.response.set_status(500, message='You must log in')
            self.response.out.write('You must log in')
            return

        logging.info(self.request)

        if self.request.get('currentUser'):
            user = users.get_current_user()
            player = Player.all()
            player = player.filter('email =', user.email()).get()
            if player:
                self.response.out.write(playerToJSON(player, isAdmin))
            else:
                self.response.set_status(500, message='You\'re not a player')
                self.response.out.write('You\'re not a player')
                return

        else:
            players = Player.all()
            self.response.out.write(playersToJSON(players, isAdmin))
Example #11
0
def player_put(pid, name):
    """ Insert player via DotA2 ID """
    if not player_check(pid):
        query = Player(player_id=pid, name=name)
        query.save()
        return True
    return False
Example #12
0
 def get(self, request, player_id=None):
     if player_id==None:
         data = [model_to_dict(i) for i in Player.get_all()]
         return HttpResponse(json.dumps(data))
     player = Player.get_by_id(player_id)
     player = model_to_dict(player)
     return HttpResponse(json.dumps({"player": player}))
    def post(self):
        user = users.get_current_user()
        if not user:
            self.redirect(users.create_login_url("/"))
            return

        game_name = self.request.get("game_name")
        if not game_name:
            self.response.write("No game name specified")
            return

        game_key = db.Key.from_path("Game", game_name)
        game = db.get(game_key)

        if not game:
            game = Game(key_name=game_name)
            game.put()

        logging.info("Game: {0}".format(game))

        player = Player(user=user, parent=game)
        player.put()

        token = channel.create_channel("{0}:{1}".format(game_name, user.user_id()))

        logging.info("/game?gamename={0}&token={1}".format(game.key().id_or_name(), token))
        self.redirect("/game?gamename={0}&token={1}".format(game.key().id_or_name(), token))
Example #14
0
def test_undo_match(g):
    p = Player("test player")
    p2 = Player("test player 2")
    player_dao.create(p)
    p.id = 1
    player_dao.create(p2)
    p2.id = 2
    t = Tournament(0,'','T1','type',0)
    tournament_dao.create(t)
    t.id = 1
    match_dao.create([p.id, p2.id], t.id)
    match_id = 1
    match = Match(player1=p,player2=p2,id=match_id)
    match.score1 = 19
    match.score2 = 21
    match_dao.update(match)

    match_dao.undo(match)
    retrieved_match = match_dao.find(match_id)
    matches = match_dao.find_by_tournament(t.id)

    assert retrieved_match.score1 == 0
    assert retrieved_match.score2 == 0
    assert retrieved_match.player1.fname == p.fname
    assert retrieved_match.player2.fname == p2.fname
    assert retrieved_match.player1.id == p.id
    assert retrieved_match.player2.id == p2.id
    assert not matches[0].entered_time
Example #15
0
def fetch_and_save_tenhou_records(player_name):
    session = get_global_session()
    records_text = fetch_tenhou_records(player_name)
    records_lines = [line.strip() for line in records_text.split("<br>") if line.strip()]

    # check query target player
    player = session.query(Player).filter(Player.name == player_name).first()
    if not player:
        player = Player(player_name)
        session.add(player)
        session.commit()

    # check frequency
    now = datetime.datetime.now()
    check_point = now + datetime.timedelta(days=1)
    if not player.last_check_records_time or player.last_check_records_time > check_point:
        player.last_check_records_time = now
        session.commit()
    else:
        return "player was checked in %s, please wait for 1 day" % player.last_check_records_time

    # create all game_record
    game_record_list = []
    player_id_name_dict = dict()
    for line in records_lines:
        hash_string = GameRecord.get_record_line_hash(line)
        if session.query(GameRecord).filter(GameRecord.hash == hash_string).count() > 0:
            continue
        try:
            game_record = GameRecord(line)
        except IndexError, _ex:
            print _ex
            continue
        game_record_list.append(game_record)
Example #16
0
def twitter_callback(request):
    """ This method deals with the callback needed by twitter, and creating the their user.

    """
    if 'denied' in request.GET:
        return HttpResponseRedirect('/')

    twitter_conn = twitter(
        twitter_token = keys.CONSUMER_KEY,
        twitter_secret = keys.CONSUMER_SECRET,
        oauth_token = request.session['request_token']['oauth_token'],
        oauth_token_secret = request.session['request_token']['oauth_token_secret']
    )

    auth_tokens = twitter_conn.get_authorized_tokens()

    try:
        user = User.objects.get(username = auth_tokens['screen_name'])
    except User.DoesNotExist:
        user = create_django_user(auth_tokens['screen_name'], auth_tokens['oauth_token_secret'])
        player = Player()
        player.user = user
        player.twitter_oauth_token = auth_tokens['oauth_token']
        player.twitter_oauth_secret = auth_tokens['oauth_token_secret']
        request.session['twitter'] = player
        form = PlayerForm(initial={'username': player.user.username})
        return render(request, 'register.html', {'form': form})
    player = Player.objects.get(user=user)
    user = authenticate(username=player.user.username, password=player.twitter_oauth_secret)
    login(request, user)
    return HttpResponseRedirect('/')
Example #17
0
 def post(self):
     sig, payload = self.request.get('signed_request').split('.',1)
     sr = decode_signed_req(payload)
     
     if 'oauth_token' not in sr:
         self.response.out.write(template.render('index.html',{
             'signed_request': self.request.get('signed_request'),
             'not_authorised': True,
             }))
         return
     
     logging.warning('oauth_token provided')
     
     graph = get_facebook_data('graph',sr['oauth_token'])
     friends = get_facebook_data('friends',sr['oauth_token'])
     
     player = Player.get_or_create('facebook',graph['id'],graph['name'])
     
     action = self.request.get('action')
     
     if action:
         try:
             target = Player.get_or_create(self.request.get('target_network'),
                                           self.request.get('target_id'),
                                           self.request.get('target_username'))
             act(player,target,action,self.request.get('narration'))
             player = Player.get_by_key_name('facebook|%s' % graph['id']) # TODO: figure out why I have this step and comment on it
         except Alert, a:
             logging.warning(a)           
Example #18
0
 def test_blackjack_player_wins(self):
     player = Player('cory','password')
     game = Game('Blackjack')
     hand = Hand()
     player.bank = 100
     player.hands.append(hand)
     game.hands.append(hand)
     game.players.append(player)
     bank_before_bet = player.bank
     # cards_app.session.commit()
     cards_app.session.flush()
     bet(hand, 50)
     cards = [Card(sequence=1), Card(sequence=10)]
     hand.cards.extend(cards)
     count_blackjack(hand)
     evaluate_hit(hand)
     # player wins with nautral evaluate_hit
     assert player.bank == bank_before_bet - 50
     # player stands on 18, dealer stands on 17
     hand.cards = [Card(sequence=10), Card(sequence=8)]
     bet(hand, 50)
     game.dealer = Player('cory','password')
     dealer = game.dealer
     dealer.cards = [Card(sequence=10), Card(sequence=17)]
     dealer_hand = Hand()
     dealer_hand.cards = dealer.cards
Example #19
0
def new_player(user):
    player = Player(
        user=user, level=1, points=10)
    player.save()
    player.add_sentence
    player.add_sentence
    player.add_sentence
Example #20
0
def reset(response):
    for player in Player.all().filter('isStarred', False):
        player.delete()
    for player in Player.all().filter('isStarred', True):
        response.out.write('full')
        player.status = 'waiting'
        player.put()
Example #21
0
    def testSaveOkCheckArtist(self):

        player = Player(self.collection, self.name, self.email, self.fbid, self.artist)
        expected = player.mobject
        #import ipdb;ipdb.set_trace()
        player.save()
        actual = self.collection.find_one({'e': player.email})
        assert_equal(actual['a'], expected['a'])
Example #22
0
def create_player(first, last):

    person = Person(first_name=first, last_name=last)
    person.save()
    player = Player(person=person)
    player.save()

    return player
Example #23
0
def findPlayer(username, channel):
	try:         
		# Try to find existing player by username in this channel.
		player = Player.objects.get(username=username, channel=channel)
        except Player.DoesNotExist:
                # Player does not exist yet. Create new player with username and channel.
                player = Player(username=username, channel=channel)
       		player.save()
	return player
Example #24
0
 def get(self,network,id):
    
     target = Player.get_by_key_name(Player.make_key(network,id))
     refdate = self.request.get('refdate',None)
     self.response.out.write(template.render('status.html',{
         'status' : get_current_info(target,refdate),
         'person' : target,
         'action' : None,        
         }))
Example #25
0
 def post(self):
     if login.isAdmin():
         name = self.request.get('name')
         if name:
             newPlayer = Player(name=name, status='waiting', isStarred=False)
             newPlayer.put()
             self.response.out.write(self.request.get('name'))
         else:
             self.response.out.write('emptyName')
Example #26
0
 def put(self, request):
     player = Player()
     data = json.loads(request.body)
     if data.get("project"):
         data["project"] = AdviserProject.objects.get(id=data["project"])
     player_form = PlayerForm(data)
     if not player_form.is_valid():
         return HttpResponseBadRequest("Invalid input data. Please edit and try again.")
     player.set(data) 
     return HttpResponse(status=201)
Example #27
0
 def new_game(self, request):
     """Creates new game. Tipp: You need the urlsafe_key later"""
     player1 = Player.query(Player.name == request.player1).get()
     player2 = Player.query(Player.name == request.player2).get()
     if not (player1 and player2):
         raise endpoints.NotFoundException('No user with this name in the database')
     game = Game.new_game(player1.key, player2.key)
     # player.key gives a specific entity from the kind (Player)
     # and inputs this to new_game
     return Game.to_form(game, 'Good luck playing TICTACTOE!')
Example #28
0
 def get(self, server_key=None):
     server = self.get_server_by_key(server_key, abort=False)
     if server is None:
         self.redirect_to_server('players')
         return
     results, previous_cursor, next_cursor = self.get_results_with_cursors(
         Player.query_all_reverse(server.key), Player.query_all(server.key), RESULTS_PER_PAGE
     )
     context = {'players': results, 'previous_cursor': previous_cursor, 'next_cursor': next_cursor}
     self.render_template('players.html', context=context)
Example #29
0
class ComputerPlayerTest(TestCase):

    def setUp(self):
        self.board = Board()
        self.player = Player("X", self.board, "Allan")
        self.computer = ComputerPlayer("O",self.board )

    def test_place_marker(self):
        self.player.place_marker(4)
        self.computer.place_marker()
        assert self.board.last_cell != 4
Example #30
0
    def print_unconfirmed(self):
        table = []

        Winner = Player.alias()
        Loser  = Player.alias()
        for match in Match.select(Match, Winner, Loser).join(Winner, on=(Match.winner == Winner.slack_id)).join(Loser, on=(Match.loser == Loser.slack_id)).where(Match.pending == True).order_by(Match.played.desc()).limit(25):
            match_played_utc = match.played.replace(tzinfo=from_zone)
            match_played_pst = match_played_utc.astimezone(to_zone)
            table.append([match.id, '<@' + match.loser.slack_id + '>', '<@' + match.winner.slack_id + '>', str(match.winner_score) + '-' + str(match.loser_score), match_played_pst.strftime('%m/%d/%y %I:%M %p')])

        self.talk('```' + tabulate(table, headers=['Match', 'Needs to Confirm', 'Opponent', 'Score', 'Date']) + '```')
Example #31
0
def seed_players():
    players = Player.objects()
    if players:
        return 'already seeded'

    new_player = Player(name='matt',
                        signup_time=datetime.datetime.utcnow(),
                        birthday=datetime.date(1988, 2, 3),
                        height='77',
                        weight='165',
                        smoker=False,
                        gender='male')
    new_player.save()

    return 'ok'
Example #32
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")))
Example #33
0
def update_votes():
    '''
    Updates the Vote table with the json retrieved from Kimono.
    If a vote is not in the table it creates one.
    Returns the number of new votes and new orphan players added to the db
    '''
    logger.info('Updating votes...')
    url = settings.KIMONO['votes_url']
    votes = _get_results_collection1(url)
    # Keeping a list of players with votes but not present in the Player table
    # so that they could be added later
    logger.info(' - Updating database...')
    no_new_votes = 0
    no_new_orphans = 0
    for vote in votes:
        p_id = _id_from_url(vote['name']['href'])
        v_day = _day_from_url(vote['url'])
        # Checking if the vote already exists. If not, creates a new one, if it
        # exists it will get the current vote and update it
        try:
            v = Vote.objects.get(player__pk=p_id, day=v_day)
        except Vote.DoesNotExist:
            v = Vote()
            no_new_votes += 1
        # Creating a orphan player if there is not a player for this vote
        try:
            p = Player.objects.get(pk=p_id)
        except Player.DoesNotExist:
            p = Player(pk=p_id)
            p.role = _fix_role(vote['role'])
            p.save()
            no_new_orphans += 1
        v.player = p
        v.vote = _fix_zero(vote['vote'])
        v.gol = _fix_zero(vote['gol'])
        v.assist = _fix_zero(vote['assists'])
        v.penalties_scored_saved = _fix_zero(vote['penalties_scored_saved'])
        v.penalties_missed = _fix_zero(vote['penalties_missed'])
        v.own_gol = _fix_zero(vote['own_gol'])
        v.yellow_cards = _fix_zero(vote['yellow_cards'])
        v.red_cards = _fix_zero(vote['red_cards'])
        v.magicvote = _fix_zero(vote['own_gol'])
        v.day = v_day
        v.sub_in = _sub_in(vote['in']['class'])
        v.sub_out = _sub_out(vote['out']['class'])
        # Storing on the db
        v.save()
    return no_new_votes, no_new_orphans
Example #34
0
def init_dev_data():
    """Initializes database with data for development and testing"""
    db.drop_all()
    db.create_all()
    print("Initialized Connect 4 Database.")

    g = Game()
    db.session.add(g)

    g2 = Game()
    db.session.add(g2)

    p1 = Player(username="******",
                password="******",
                birthday=datetime.datetime.strptime('11/06/1991',
                                                    '%m/%d/%Y').date())
    p2 = Player(username="******",
                password="******",
                birthday=datetime.datetime.strptime('01/14/1987',
                                                    '%m/%d/%Y').date())
    p3 = Player(username="******",
                password="******",
                birthday=datetime.datetime.strptime('01/15/1987',
                                                    '%m/%d/%Y').date())

    db.session.add(p1)
    print("Created %s" % p1.username)
    db.session.add(p2)
    print("Created %s" % p2.username)
    db.session.add(p3)
    print("Created %s" % p3.username)

    g.player_one = p1
    g.player_two = p2

    g.turn = 7
    g.winner_id = 1
    g.creator_id = 2

    g2.player_one = p1
    g2.player_two = p3

    g2.turn = 11
    g2.winner_id = 3
    g2.creator_id = 1

    db.session.commit()
    print("Added dummy data.")
Example #35
0
    def join_game(self, request):
        """One of the players, creates the game and gets the game-id and gives that ID
        to the other player in order to play between each other"""
        player = Player.query(Player.name == request.player_name).get()
        print player
        if not player:
            raise endpoints.NotFoundException(
                'A Player with that name does not exist!, '
                'we need a second player in order to join the game')
        try:
            game = gameutils.get_by_urlsafe(request.urlsafe_key, Game)
            game.player2 = player.key
            game.put()
        except ValueError:
            raise endpoints.BadRequestException(
                'please verify the information '
                'of the second player')

        # Use a task queue to update the average attempts remaining.
        # This operation is not needed to complete the creation of a new game
        # so it is performed out of sequence.

        return game.to_form(
            'Second Player Joined the Game, we are ready to start the game!',
            player.name)
Example #36
0
def set_answer(puzzle_name, player_id, question, content_type, content):
    player = Player.get(Player.id == player_id)
    puzzle, _ = Puzzle.get_or_create(name=puzzle_name)
    try:
        answer = Answer.get((Answer.puzzle == puzzle)
                            & (Answer.player == player))
    except Answer.DoesNotExist:
        answer = Answer(puzzle=puzzle, player=player)

    answer.question = question

    if content_type == 'text':
        answer.value = content
    elif content_type == 'image':
        filename = '%s_%s.jpg' % (puzzle.id, player.id)
        path = '%s/images/%s' % (STATIC_DIR, filename)
        with open(path, 'wb') as fp:
            fp.write(content)
        answer.value = 'image:' + filename
    elif content_type == 'video':
        filename = '%s_%s.mp4' % (puzzle.id, player.id)
        path = '%s/videos/%s' % (STATIC_DIR, filename)
        with open(path, 'wb') as fp:
            fp.write(content)
        answer.value = 'video:' + filename

    answer.save()
Example #37
0
 def test_model_game(self):
     game = Game(10, 10, 5)
     player = Player("player1")
     game._players.append(player)
     self.assertEqual(game._mines, [])
     self.assertEqual(game._result, 0)
     self.assertEqual(len(game._players), 1)
Example #38
0
async def join_game(sid, data: SioJoinGame):
    """Handle the incoming request for joining a game.

    If no game for the provided ID exists or the password is wrong, an 'invalid_game_or_pwd' event will be emitted.
    """
    sio_data = SioJoinGame.parse_obj(data)
    log.debug(f"Incoming request from {sio_data.user_name} ({sid}) to join game {sio_data.game_id}.")
    # Find the game for the provided ID and try to join it.
    game = game_controller.get(sio_data.game_id)
    alread_joined, player = game.is_player(sid)
    if not alread_joined:
        player = Player(sid, sio_data.user_name, sio_data.user_id)
        if game is None:
            await sio.emit(JOIN_GAME_ERROR, room=sid)
            return
        join_succeeded = game.join(player, sio_data.game_pwd)
        if not join_succeeded:
            await sio.emit(JOIN_GAME_ERROR, room=sid)
            return
    # Update the user session.
    sess: SioSession = await sio.get_session(sid)
    sess.game = game
    sess.player = player
    await sio.save_session(sid, sess)
    log.debug(f"{sid} successfully joined game {game.id}.")
    # Join the socket IO room for the game.
    sio.enter_room(sid, game.id)
    # Emit the event that the game has been successfully joined.
    sio_data.game = game
    sio_data.user_name = player.user_name
    sio_data.user_id = player.user_id
    log.debug(f"Emitting event {GAME_JOINED} to {sio_data.user_name} ({sid}).")
    await sio.emit(GAME_JOINED, data=sio_data.emit(), room=sid)
    # Notify all other players of the room.
    await notify_player_joined(player, game)
Example #39
0
    async def ws_handler(self, request):
        ws = aiohttp.web.WebSocketResponse()
        await ws.prepare(request)

        player = Player(self.NEXT_PLAYER_ID, ws)
        self.NEXT_PLAYER_ID += 1
        self.waiting_players.put(player)
        self.players[player.id] = player

        if self.waiting_players.qsize() > 1:
            await self.create_room(self.waiting_players.get(),
                                   self.waiting_players.get())

        async for msg in ws:
            if msg.type == aiohttp.WSMsgType.TEXT:
                data = json.loads(msg.data)
                if self.validate_message(data):
                    player.room.do_action(player.id, data['action'],
                                          data['direction'])
                    await self.send_last_changes(player.room)
                    await self.send_players_info(player.room)
            elif msg.type == aiohttp.WSMsgType.ERROR:
                # TODO: Delete room and players
                pass

        return ws
Example #40
0
def set_nation(request, nation):
    player = Player.get_player_for_user(request.user)
    if player.nation is None:
        player.nation = Nation.objects.get(pk=nation)
        player.save()
        return HttpResponse(json.dumps({'status': 'OK'}))
    return HttpResponse(json.dumps({'status': 'Nation already set'}))
Example #41
0
async def action_add_players(message, msg_split):
    global LOBBY_LIST
    if GAME_STATUS != GameStatuses.IN_LOBBY:
        await message.channel.send('Cannot add players at this time.')
        return
    if len(msg_split) > 2:
        player_names = msg_split[2:]
        players_added = []
        players_not_added = []
        for player_name in player_names:
            player = Player(player_name.strip(','))
            if player in LOBBY_LIST:
                players_not_added.append(player)
            else:
                players_added.append(player)
        LOBBY_LIST += players_added

        msg_to_send = "Players added:\n"
        if len(players_added) == 0:
            msg_to_send += "None\n"
        for player in players_added:
            msg_to_send += f'{player.name}\n'

        msg_to_send += "Players not added:\n"
        if len(players_not_added) == 0:
            msg_to_send += "None\n"
        for player in players_not_added:
            msg_to_send += f'{player.name}\n'
        await message.channel.send(msg_to_send)
    else:
        await message.channel.send('You need to specify players to add.')
Example #42
0
    def do_player_list(self, args, manage_mode=False):
        """Render the HTML for a list of players"""
        year = self.get_year(args)
        if manage_mode:
            mem_key = PlayerPage.get_manage_list_mem_key(year)
        else:
            mem_key = PlayerPage.get_list_mem_key(year)
        player_div = memcache.get(mem_key)
        if player_div is None:
            data = {
                'url_args': args,
            }
            if year == ALL_YEARS:
                data['players'] = Player.gql(
                    'ORDER BY last_name ASC, first_name ASC')
            else:
                data['players'] = [
                    p.player for p in TeamList.gql('WHERE year = :1', year)
                ]
                data['players'].sort(self.sort_players)

            tpath = os.path.join(DeeWhyPage.TEMPLATE_DIR, 'players.html')
            player_div = template.render(tpath, data)
            memcache.set(mem_key, player_div)
        self.response.out.write(player_div)
Example #43
0
def add_player():
    error = None
    if request.method == 'POST':
        insert_data = dict(request.form)
        insert_data['is_active'] = 'is_active' in insert_data.keys()
        try:
            player_id = Player.execute_insert([insert_data])[0]
            flash('Гравець створений', 'isa_success')
            return redirect(url_for('.player_info', player_id=player_id))
        except mysql.connector.Error as err:
            flash(err.msg)

    cities = City.select_attrs(['id', 'name'])
    ranks = Rank.select_attrs(['id', 'name'])
    national_ranks = NationalRank.select_attrs(['id', 'name'])

    form = '\n'.join([
        '<div class="container">',
        f'<form action="/players/add" method="post">',
        render_text_input_row("last_name", "Прізвище"),
        render_text_input_row("first_name", "Ім'я"),
        render_select_row('city_id', "Місто", cities),
        render_number_input_row('rating', "Рейтинг", '100', '3000', '0.001'),
        render_select_row('rank_id', "Ранг", ranks),
        render_select_row('national_rank_id', "Розряд", national_ranks),
        render_text_input_row("pin", "EGF PIN"),
        render_checkbox_row('is_active', "Активний"),
        render_submit(),
        '</form>',
        '</div>',
    ])

    return render_template('add_player.html', form=form, error=error)
Example #44
0
def player_info(player_id):
    player = Player.execute_select({'id': player_id})[0]
    participant = Participant.execute_select({'player_id': player.id},
                                             [('t.date_start', False)])
    return render_template('player_info.html',
                           player=player,
                           participant=participant)
Example #45
0
def get_player(update) -> Player:
    """Returns Player model for current user"""
    user = update.effective_user
    player = session.query(Player).filter_by(user_id=user.id).first()
    if player:
        sync_player_data(player, user)
    else:
        player = Player(
            user_id=user.id,
            username=user.username,
            first_name=user.first_name,
            last_name=user.last_name,
            csgo_nickname=get_nickname(user),
        )
        player.create()
    return player
Example #46
0
def authorized():
    try:
        cache = _load_cache()
        result = _build_msal_app(cache=cache).acquire_token_by_auth_code_flow(
            session.get("flow", {}), request.args)
        if "error" in result:
            return render_template("auth_error.html", result=result)
        session["user"] = result.get("id_token_claims")
        email = session["user"]["preferred_username"].lower()
        session["user"]["preferred_username"] = email
        session["email"] = email
        exists = db.session.query(Player.email).filter_by(
            email=session['email']).scalar() is not None
        if not exists:
            new_player = Player(email=email)
            db.session.add(new_player)  # Adds new User record to database
            db.session.commit()  # Commits all changes
        _save_cache(cache)

        resp = make_response(redirect('/'))
        exp = result.get('id_token_claims')['exp']
        resp.set_cookie('jwt',
                        result.get('id_token'),
                        max_age=exp,
                        secure=True,
                        httponly=True,
                        samesite='Lax')
        return resp
    except ValueError:  # Usually caused by CSRF
        pass  # Simply ignore them

    return redirect('/')
Example #47
0
async def action_add_player(message, msg_split):
    global LOBBY_LIST
    if GAME_STATUS != GameStatuses.IN_LOBBY:
        await message.channel.send('Cannot add players at this time.')
        return
    if len(msg_split) > 2:
        player_name = msg_split[2]
        msg_to_send = f'{player_name} added to lobby.'
        player = Player(player_name)
        if player in LOBBY_LIST:
            await message.channel.send('Player is already in lobby. Please use another name.')
            return
        LOBBY_LIST.append(Player(player_name))
        await message.channel.send(msg_to_send)
    else:
        await message.channel.send('You need to specify a player to add.')
Example #48
0
def _create_player(name: str, url: str, elo_points: int) -> Player:
    return Player(
        id=url.replace("https://", "").split("/")[6],
        name=name,
        url=url,
        elo_points=elo_points,
    )
Example #49
0
def process_player(data, region="eu"):
    test = db.session.query(Player).get(data['id'])
    if not test:

        p = Player(id=data['id'], name=data['attributes']['name'],
                   shardId=region,
                   lifetimeGold=data['attributes']['stats']['lifetimeGold'],
                   lossStreak=data['attributes']['stats']['lossStreak'],
                   winStreak=data['attributes']['stats']['winStreak'],
                   played=data['attributes']['stats']['played'],
                   played_ranked=data['attributes']['stats']['played_ranked'],
                   wins=data['attributes']['stats']['wins'],
                   xp=data['attributes']['stats']['xp'])

        db.session.add(p)

        try:
            db.session.commit()
        except SQLAlchemyError as e:
            db.session.rollback()
            app.logger.error('ERROR: Session rollback - reason "%s"' % str(e))
    else:
        test.lifetimeGold = data['attributes']['stats']['lifetimeGold']
        test.lossStreak = data['attributes']['stats']['lossStreak']
        test.winStreak = data['attributes']['stats']['winStreak']
        test.played = data['attributes']['stats']['played']
        test.played_ranked = data['attributes']['stats']['played_ranked']
        test.wins = data['attributes']['stats']['wins']
        test.xp = data['attributes']['stats']['xp']

        try:
            db.session.commit()
        except SQLAlchemyError as e:
            db.session.rollback()
            app.logger.error('ERROR: Session rollback - reason "%s"' % str(e))
Example #50
0
    def create_player(self, name, photo):
        cur = self.con.cursor()

        if self.get_player_by_name(name=name):
            return None
        else:
            player_dict = dict(name=name, photo=photo)
            cur.execute(
                "INSERT INTO players(name, photo) VALUES(:name, :photo)",
                player_dict)
            self.con.commit()
            player_id = cur.lastrowid

            player_stats = self.add_first_stats(player_id=player_id)
            attack_stats = self.add_first_stats(attack_player_id=player_id)
            defense_stats = self.add_first_stats(defense_player_id=player_id)

            self.update_player_stats(player_id=player_id,
                                     player_stats_id=player_stats.stats_id,
                                     attack_stats_id=attack_stats.stats_id,
                                     defense_stats_id=defense_stats.stats_id)

            return Player(player_id=player_id,
                          name=name,
                          photo=photo,
                          player_stats=player_stats,
                          attack_stats=attack_stats,
                          defense_stats=defense_stats)
Example #51
0
def signup():
    '''
    Create a new user
    '''
    if request.method == 'POST':
        print request.data['phone']
        info = Player(request.data['name'], request.data['email'],
                      request.data['username'], request.data['college'],
                      request.data['phone'], request.data['level'],
                      request.data['levelId'], request.data['picture'])
        # casea = Player.query.filter(Player.email == request.data['email']).first()
        # caseb = Player.query.filter(Player.username == request.data['username']).first()
        casea = session.query(Player).filter(
            Player.email == request.data['email']).first()
        caseb = session.query(Player).filter(
            Player.username == request.data['username']).first()
        if casea:
            return {'status': 'email already exist', 'token': None}, 409
        elif caseb:
            return {'status': 'username already exist', 'token': None}, 409
        else:
            session.add(info)
            session.commit()
            session.close()
            jwt = tokenGenerate(request.data['email'])
            return {'status': 'created', 'token': jwt}, 201
    return {'status': 'enter Player details'}
Example #52
0
def register():
    """Registers the user."""
    if g.user:
        return redirect(url_for('home'))
    error = None
    if request.method == 'POST':
        if not request.form['username']:
            error = 'You have to enter a username'
        elif not request.form['email']:
            error = 'You have to enter a valid birthdate'
        elif not request.form['password']:
            error = 'You have to enter a password'
        elif request.form['password'] != request.form['password2']:
            error = 'The two passwords do not match'
        elif get_user_id(request.form['username']) is not None:
            error = 'The username is already taken'
        else:
            #p1 = Player(username="******", birthday=datetime.datetime.strptime('11/06/1991', '%m/%d/%Y').date(), pw_hash=generate_password_hash("tow"))
            db.session.add(
                Player(username=request.form['username'],
                       birthday=datetime.datetime.strptime(
                           request.form['email'], '%m/%d/%Y').date(),
                       pw_hash=generate_password_hash(
                           request.form['password'])))
            db.session.commit()
            flash('You were successfully registered and can login now')
            return redirect(url_for('login'))
    return render_template('register.html', error=error)
Example #53
0
async def new_game(sid, data: SioNewGame):
    """Handle the incoming request for creating a new game.

    A new game instance is created for the provided scenario.
    The game ID and the join password is returned as payload with event 'NEW_GAME'.

    A user_name will be provided, user_id will be initial and generated within this method.
    """
    sio_data = SioNewGame.parse_obj(data)
    log.debug(f"Incoming request for creating a new game from {sio_data.user_name} ({sid})"
              f"for scenario {sio_data.game_scenario}.")
    # Create a new game instance.
    player = Player(sid, sio_data.user_name, sio_data.user_id)
    game = GameFactory().create(Scenario(id=sio_data.game_scenario), player)
    game_controller.add(game)
    # Update the user session with the new game.
    sess: SioSession = await sio.get_session(sid)
    sess.game = game
    sess.player = player
    await sio.save_session(sid, sess)
    log.debug(f"New game created with ID {game.id} and password {game.pwd}.")
    # Create a new socket IO room for the game.
    sio.enter_room(sid, game.id)
    # Emit the event that the game has been successfully created.
    sio_data.game = game
    sio_data.user_id = player.user_id
    log.debug(f"Emitting event {NEW_GAME} to {sio_data.user_name} ({sid}).")
    await sio.emit(NEW_GAME, data=sio_data.emit(), room=sid)
Example #54
0
def process_players():
    if request.method == 'POST':
        player_1_Name = request.form['player1']
        db.session.add(Player(player_1_Name))
        player_2_Name = request.form['player2']
        db.session.add(Player(player_2_Name))
        player_3_Name = request.form['player3']
        db.session.add(Player(player_3_Name))
        player_4_Name = request.form['player4']
        db.session.add(Player(player_4_Name))
        db.session.commit()
        session['player_1_Name'] = player_1_Name
        session['player_2_Name'] = player_2_Name
        session['player_3_Name'] = player_3_Name
        session['player_4_Name'] = player_4_Name
        return redirect('/score_input')
Example #55
0
    def post(self):
        game_name = self.request.get('game_name')
        game_key = db.Key.from_path('Game', game_name)
        game = db.get(game_key)
        user = users.get_current_user()
        logging.info('Player {0} playing move for game: {1}'.format(
            game, user.nickname()))

        move_type = self.request.get('move_type')
        selected_cards = self.request.get('selected_cards')

        players = Player.all().ancestor(game).run()
        for player in players:
            if player.user == user:
                this_player = player

        if not this_player:
            raise Exception("Player not found: {0}".format(user.nickname()))

        gamestate = {
            "players": players,
            "current_hand": this_player.cards,
            "player_turn": game.player_turn
        }

        for player in players:
            channel.send_message(
                "{0}:{1}".format(game_name, player.user.user_id()),
                json.dumps(gamestate))
Example #56
0
    def post(self):
        """
        POST method adds a new player to collection
        """
        if not request.json:
            return create_error_response(415, "Unsupported media type",
                                         "Requests must be JSON")

        try:
            validate(request.json, GameBuilder.player_schema())
        except ValidationError as e:
            return create_error_response(400, "Invalid JSON document", str(e))

        new_player = Player(name=request.json["name"],
                            team=request.json["team"])

        try:
            db.session.add(new_player)
            db.session.commit()
        except IntegrityError:
            return create_error_response(
                409, "Already exists",
                "Player with name '{}' already exists".format(
                    request.json["name"]))

        return Response(status=201,
                        headers={
                            "Location":
                            api.url_for(PlayerItem, name=request.json["name"])
                        })
Example #57
0
async def load(bot):
    global loading
    loading = True
    global problem_list
    global discord_users_list
    global users
    global judgeserver
    global judges
    global locks

    global db
    db = pymysql.connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWD, MYSQL_DATABASE)

    locks["problem"] = defaultdict(lambda: asyncio.Lock())
    locks["submissions"] = defaultdict(lambda: asyncio.Lock())
    locks["judge"] = defaultdict(lambda: asyncio.Lock())
    locks["user"] = defaultdict(lambda: asyncio.Lock())
    locks["contest"] = defaultdict(lambda: asyncio.Lock())
    locks["db"] = defaultdict(lambda: threading.RLock())

    from bridge import JudgeHandler, JudgeServer
    from models import Problem, Player

    judgeserver = JudgeServer(BRIDGED_IP_ADDRESS, JudgeHandler)
    threading.Thread(target=judgeserver.serve_forever).start()

    for x in db_select("dmob_problem"):
        problem_list[x[2]] = Problem(*x)

    for x in db_select("dmob_user"):
        discord_users_list[x[0]] = await bot.get_user_info(x[0])
        users[x[0]] = Player(*x)

    loading = False
Example #58
0
 def get(self):
     games = memcache.get('gamedates')
     if not games:
         games = GameDate.all()
         games.order('date')
     game = games[0]
     players = memcache.get('players')
     if not players:
         players = Player.all()
         players.order('lname')
         players.order('fname')
         memcache.set('players', players)
     to_list = []
     for player in players:
         if not player.sub:
             to_list.append(player.email)
     email_sender = "Esri Hockey <*****@*****.**>"
     email_subject = "Esri Hockey - %d/%d/%d" % (
         game.date.month, game.date.day, game.date.year)
     email_body = """Head on over to http://esrihockey.appspot.com to let us know if you are in or out."""
     if not game.isThisWeek():
         logging.info("NOT GAME THIS WEEK")
         email_subject = "Esri Hockey - No Game This Week"
         email_body = """Reminder we are off this week. Our next game will be %d/%d/%d.""" % (
             game.date.month, game.date.day, game.date.year)
     mail.send_mail(sender=email_sender,
                    to=to_list,
                    subject=email_subject,
                    body=email_body)
Example #59
0
def updateCurrentGames():
    games = memcache.get('gamedates')
    if not games:
        games = GameDate.all()
        games.order('date')
    current_games = []
    deletedGame = False
    now = localTime()
    datetimenow = datetime.datetime(month=now.month,
                                    year=now.year,
                                    day=now.day)
    for game in games:
        #if game.date.month <= now.month and game.date.day < now.day and game.date.year <= now.year:
        if game.date < datetimenow:
            game.delete()
            deletedGame = True
        else:
            current_games.append(game)
    # when we delete a game, we should also
    # reset all players to be OUT and NOT goalie
    if deletedGame:
        players = Player.all()
        for player in players:
            player.inThisWeek = False
            if not player.sub:
                player.goalie = False
            player.team = ""
            player.put()
        memcache.set('players', players)
        comments = Comment.all()
        for comment in comments:
            comment.delete()
    return current_games
Example #60
0
    def do_body(self, args):
        """Render the HTMl for the goal scorer tally"""
        year = self.get_year(args)
        mem_key = ScorersPage.get_mem_key(year)
        scorer_page = memcache.get(mem_key)
        if scorer_page is None:
            if year == ALL_YEARS:
                players = Player.all()
            else:
                players = [
                    t.player for t in TeamList.gql('WHERE year = :1', year)
                ]

            scorers = []
            for p in players:
                tally = 0
                for g in p.goal_set:
                    round = g.result.round
                    if (year == ALL_YEARS
                            or year == round.date.year) and round.num > 0:
                        # Only count real goals - negative rounds are trials
                        tally += g.count
                if tally > 0:
                    scorers.append((p.get_short_name(), tally))
            scorers.sort(self.sort_scores)
            data = {
                'scorers': scorers,
            }

            tpath = os.path.join(DeeWhyPage.TEMPLATE_DIR, 'scorers.html')
            scorer_page = template.render(tpath, data)
            memcache.set(mem_key, scorer_page)
        self.response.out.write(scorer_page)