Example #1
0
	def put(self, request):
		"""
		Adds a team.
		"""
		try:
			post_fields = read_json(request.body)
		except ValueError:
			return HttpResponse(_("JSON, please!"), status=400)
		
		try:
			assert type(post_fields['name']) is str
			assert type(post_fields['players']) is list
			for item in post_fields['players']:
				assert type(item) is str
		except (AssertionError, KeyError):
			return HttpResponse(_("Hack attempt detected."), status=400)
		
		team = Team()
		team.race = self.token.race
		team.name = post_fields['name']
		team.save()
		
		for player_name in post_fields['players']:
			player = Player()
			player.team = team
			player.name = player_name
			player.save()
		
		response = {
			'id': team.pk
		}
		return HttpResponse(make_json(response), status=200)
Example #2
0
def createPlayer(index):
    battles_total = random.randint(10, 1000)
    player = Player()
    player.name = getName()
    player.battles_total = battles_total
    player.wins_total = random.randint(10, battles_total)
    player.days_total = random.randint(battles_total / 50, 1000)
    player.vehicles_x = random.randint(0, 10)
    player.exp_total = random.randint(100, 10000)
    player.save()
    return player
Example #3
0
def new_player(request, game_id):
    current_player = request.session.get("PLAYER_NAME", "")
    if current_player:
        Player.objects.filter(game=Game.objects.get(id=game_id),
                              name=current_player).delete()

    player = Player(game=Game.objects.get(id=game_id),
                    name=request.data["name"])
    player.save()

    request.session["PLAYER_NAME"] = request.data["name"]
    return Response(status=status.HTTP_200_OK, data="1")
Example #4
0
    def is_logged(self, request):
        """
        This endpoint is used to check if the user is logged in and can be treated
        as a player. If user is logged in, additional information is provided.

        Response body: \n
        `is_logged` (boolean) \n
        `player_id` (integer) - this ID should be used to consume the user API \n
        `is_new` (boolean) - true if the player model is newly created.
            Can be used to implement a "welcome message"
        """

        # administrator is not the user!
        is_logged = Player.is_user_logged(request.user)

        result = {
            "is_logged": is_logged,
        }

        if is_logged:
            player, is_new = Player.objects.get_or_create(user=request.user)

            result["player_id"] = player.pk
            result["is_new"] = is_new

        return Response(result)
Example #5
0
    def createPlayer(user_data):
        album_id = user_data['album_id']

        try:
            # player = Player.create_player(album_id)
            player_data = {'album_id': album_id}
            player = Player(album_id)
            # player = Player.create_player(album_id=album_id)

            player.save()
            return {'created': True}

        except Exception as e:
            print(str(e))
            raise Exception(e)

        return None
Example #6
0
def game_join(request):
    if request.method == "POST":
        gameID = request.POST.get("gameID", "")
        playerID = request.POST.get("playerID", "")
        playerName = request.POST.get("playerName", "")

        try:
            game = Game.objects.get(gameID=gameID)
            player = Player(game=game,
                            cookie=playerID,
                            name=playerName,
                            holdings=1500)
            player.save()

            return JsonResponse({"status": "success", "data": None})
        except Exception as e:
            return JsonResponse({"status": "error", "data": e})
    else:
        return JsonResponse({"status": "error", "data": None})
def mock_data():

    db.drop_all()
    db.create_all()

    # insert teams
    cubs = Team("Chicago Cubs")
    yankees = Team('New York Yankees')
    tigers = Team("Detroit Tigers")
    db.session.add_all([cubs, yankees, tigers])

    db.session.flush()

    # insert players
    arizzo = Player("Anthony Rizzo", "1B", cubs.id)
    kbryant = Player("Kris Bryant", "3B", cubs.id)
    kschwarber = Player("Kyle Schwarber", "LF", cubs.id)
    jbaez = Player("Javier Baez", "2B", cubs.id)
    db.session.add_all([arizzo, kbryant, kschwarber, jbaez])

    db.session.flush()

    # insert stats
    ba = Statistic("Batting Average", "Batting", "%", True)
    obp = Statistic("On Base Percentage", "Batting", "%", True)
    slg = Statistic("Slugging Percentage", "Batting", "%", True)

    db.session.add_all([ba, obp, slg])

    db.session.flush()

    # insert player stat records
    db.session.add(PlayerStat(ba.id, arizzo.id, .273, .268))
    db.session.add(PlayerStat(obp.id, arizzo.id, .366, .219))
    db.session.add(PlayerStat(slg.id, arizzo.id, .214, .485))

    db.session.add(PlayerStat(ba.id, kbryant.id, .289, .348))
    db.session.add(PlayerStat(obp.id, kbryant.id, .390, .464))
    db.session.add(PlayerStat(slg.id, kbryant.id, .530, .630))

    db.session.commit()
Example #8
0
def game_create(request):
    if request.method == "POST":
        # Generate a random, 6-digit number
        gameID = 0
        while gameID < 100000 or gameID > 999999:
            gameID = math.floor(random.random() * 10**6)

        # Create the game model
        game = Game(gameID=gameID)
        game.save()

        # Create the player model
        playerID = request.POST.get("playerID", "")
        playerName = request.POST.get("playerName", "")
        player = Player(game=game,
                        cookie=playerID,
                        name=playerName,
                        holdings=1500)
        player.save()

        return JsonResponse({"status": "success", "data": {"gameID": gameID}})
    else:
        return JsonResponse({"status": "error", "data": None})
Example #9
0
def create_or_join_room(request):
    """
    request.POST = {
        "room_code": "<>",
        "player_name": "<>"
    }
    """
    if 'player_id' not in request.session:
        request.session['player_id'] = get_random_id()

    player_name = request.POST['player_name']
    if not player_name:
        player_name = random.choice(animal_names)

    if Room.objects.filter(room_code=request.POST['room_code']).exists():

        try:
            r = Room.objects.get(room_code=request.POST['room_code'])
        except Room.DoesNotExist:
            return HttpResponse(json.dumps({
                "status": "error",
                "message": "Room does not exist."
            }, default=json_custom_parser), content_type='application/json', status=400)

        new_player = Player(**{
            "room_code": r.room_code,
            "player_id": request.session['player_id'],
            "alias": player_name
        })
        new_player.save()
        return HttpResponse(json.dumps({
            "status": "success",
            "data": {
                "room_code": r.room_code,
                "player_name": player_name,
                "player_id": request.session['player_id'],
                "creator_player_id": r.creator_player_id,
            }
        }, default=json_custom_parser), content_type='application/json', status=200)

    else:

        Room.objects.filter(creator_player_id=request.session['player_id']).delete()
        new_room = Room(**{
            "room_code": request.POST['room_code'],
            "creator_player_id": request.session['player_id'],
        })
        new_room.save()

        new_player = Player(**{
            "room_code": request.POST['room_code'],
            "player_id": request.session['player_id'],
            "alias": player_name
        })
        new_player.save()

        return HttpResponse(json.dumps({
            "status": "success",
            "data": {
                "room_code": new_room.room_code,
                "player_name": player_name,
                "player_id": request.session['player_id'],
                "creator_player_id": new_room.creator_player_id,
            }
        }, default=json_custom_parser), content_type='application/json', status=200)
Example #10
0
def get_recent_matches(summoner_id, region):
    """
    Retrieves game data for last 10 games played by a summoner, given a summoner ID and region.

    This potentially executes several queries:
    -first, we get match history.
        -game stats
        -IDs of participants
    -then we make a list of summoner IDs that we don't have in the DB
        -this gets broken up into MAX_IDS chunks and each chunk is a queried as a single call for basic summoner data

    Since match history returns the last 10 games, and each game can have 9 other players
    (assuming non-hexakill mode) - that's 90 potentially unknown summoner IDs + 1 for the summoner in question,
    giving us 91 summoner IDs that we need to query.

    91 / 40 = 2.275 rounded up is 3 queries at most for summoner ID data.

    3 + 1 (for the initial match history call) = 4 calls at most.
    """

    #print 'get_recent_matches()', summoner_id, region

    recent = riot_api.get_recent_games(summoner_id, region)

    # First make a set of the associated summoner IDs (a set cannot have duplicate entries).
    unique_players = set()
    for g in recent['games']:
        if 'fellowPlayers' in g:
            for p in g['fellowPlayers']:
                unique_players.add(p['summonerId'])

    # Now we take note of any summoner IDs we already have cached (so we can remove them).
    to_remove = set()
    for p in unique_players:
        try:
            Summoner.objects.filter(region=region).get(summoner_id=p)
            to_remove.add(p)
        except ObjectDoesNotExist:
            pass

    # Remove the already cached summoner IDs from the working set.
    for p in to_remove:
        unique_players.remove(p)

    player_list = list(unique_players)  # make a list of the set, so we can call chunks() on it

    # Don't forget, we have to check for the summoner ID whose history we're examining as well!
    try:
        Summoner.objects.filter(region=region).get(summoner_id=summoner_id)
    except ObjectDoesNotExist:  # if it isn't cached, and it isn't in the list yet, add it
        if summoner_id not in player_list:
            player_list.append(summoner_id)

    query_list = list(chunks(player_list, MAX_IDS))  # query_list now holds a list of lists of at most MAX_ID elements

    # Now ask the API for info on summoners, at most MAX_ID at a time.
    #print 'Now asking for participants...'
    summoner_dto = []
    for i in query_list:
        summoner_dto.append(riot_api.get_summoners(ids=i, region=region))

    #print 'Done getting participants!'

    # TODO: This part is sometimes getting duplicate summoners! (fixed?)
    # Now put those summoner DTOs in the cache.
    for chunk in summoner_dto:
        for player in chunk:
            # for v in chunk[player]:
            #     print v, len(v)
            #print u'ADDING summoner {}'.format(chunk[player]['name'])
            summoner = Summoner(summoner_id=chunk[player]['id'],
                                name=chunk[player]['name'],
                                std_name=chunk[player]['name'].replace(' ', '').lower(),
                                profile_icon_id=chunk[player]['profileIconId'],
                                revision_date=chunk[player]['revisionDate'],
                                summoner_level=chunk[player]['summonerLevel'],
                                region=region)

            # Sometimes requests will go out synchronously for the same summoner.
            # This means the cache is not hit and a double query for a single summoner occurs.
            # Duplicate summoners are prevented via the unique_together constraint on summoner_id and region,
            # which will throw IntegrityError and prevent the dupe from being made.
            try:
                #print summoner.name, len(summoner.name)
                summoner.save()
            except IntegrityError:
                pass

    # Requires summoners (as well as all related field values) to be cached before-hand (summoner caching done above).
    for match in recent['games']:
        # first fill in the simple stuff
        game = Game(summoner_id=Summoner.objects.filter(region=region).get(summoner_id=summoner_id),
                    champion_id=Champion.objects.get(champion_id=match['championId']),
                    create_date=match['createDate'],
                    game_id=match['gameId'],
                    game_mode=match['gameMode'],
                    game_type=match['gameType'],
                    invalid=match['invalid'],
                    ip_earned=match['ipEarned'],
                    level=match['level'],
                    map_id=match['mapId'],
                    spell_1=SummonerSpell.objects.get(spell_id=match['spell1']),
                    spell_2=SummonerSpell.objects.get(spell_id=match['spell2']),
                    sub_type=match['subType'],
                    team_id=match['teamId'],
                    region=region,
                    champion_key=Champion.objects.get(champion_id=match['championId']).key)

        stats = RawStat()

        # Here we add stats that were returned (only stats that aren't None or 0 will be returned by API)
        for i in match['stats']:
            setattr(stats, inflection.underscore(i), match['stats'][i])

        stats.save()

        # associate the RawStat object with this game
        game.stats = stats

        game_saved = False

        # Ensures no dupes of Game (or any related objects).
        try:
            game.save()
            game_saved = True
        except IntegrityError:
            pass

        # if game saved, we're good and just need to add the participating players
        if game_saved:
            # associate each Player object with this game
            if 'fellowPlayers' in match:
                for p in match['fellowPlayers']:
                    player = Player(champion=Champion.objects.get(champion_id=p['championId']),
                                    summoner=Summoner.objects.filter(region=region).get(summoner_id=p['summonerId']),
                                    team_id=p['teamId'],
                                    participant_of=game)
                    player.save()
        else:  # if it didn't save, we can get rid of the stats object too.
            stats.delete()
Example #11
0
def main_page(request):
    if Player.is_user_logged(request.user):
        return redirect("/game")

    return redirect("/")
Example #12
0
def get_recent_matches(summoner_id, region):
    """
    Retrieves game data for last 10 games played by a summoner, given a summoner ID and region.

    This potentially executes several queries:
    -first, we get match history.
        -game stats
        -IDs of participants
    -then we make a list of summoner IDs that we don't have in the DB
        -this gets broken up into MAX_IDS chunks and each chunk is a queried as a single call for basic summoner data

    Since match history returns the last 10 games, and each game can have 9 other players
    (assuming non-hexakill mode) - that's 90 potentially unknown summoner IDs + 1 for the summoner in question,
    giving us 91 summoner IDs that we need to query.

    91 / 40 = 2.275 rounded up is 3 queries at most for summoner ID data.

    3 + 1 (for the initial match history call) = 4 calls at most.
    """

    #print 'get_recent_matches()', summoner_id, region

    recent = riot_api.get_recent_games(summoner_id, region)

    # First make a set of the associated summoner IDs (a set cannot have duplicate entries).
    unique_players = set()
    for g in recent['games']:
        if 'fellowPlayers' in g:
            for p in g['fellowPlayers']:
                unique_players.add(p['summonerId'])

    # Now we take note of any summoner IDs we already have cached (so we can remove them).
    to_remove = set()
    for p in unique_players:
        try:
            Summoner.objects.filter(region=region).get(summoner_id=p)
            to_remove.add(p)
        except ObjectDoesNotExist:
            pass

    # Remove the already cached summoner IDs from the working set.
    for p in to_remove:
        unique_players.remove(p)

    player_list = list(
        unique_players
    )  # make a list of the set, so we can call chunks() on it

    # Don't forget, we have to check for the summoner ID whose history we're examining as well!
    try:
        Summoner.objects.filter(region=region).get(summoner_id=summoner_id)
    except ObjectDoesNotExist:  # if it isn't cached, and it isn't in the list yet, add it
        if summoner_id not in player_list:
            player_list.append(summoner_id)

    query_list = list(
        chunks(player_list, MAX_IDS)
    )  # query_list now holds a list of lists of at most MAX_ID elements

    # Now ask the API for info on summoners, at most MAX_ID at a time.
    #print 'Now asking for participants...'
    summoner_dto = []
    for i in query_list:
        summoner_dto.append(riot_api.get_summoners(ids=i, region=region))

    #print 'Done getting participants!'

    # TODO: This part is sometimes getting duplicate summoners! (fixed?)
    # Now put those summoner DTOs in the cache.
    for chunk in summoner_dto:
        for player in chunk:
            # for v in chunk[player]:
            #     print v, len(v)
            #print u'ADDING summoner {}'.format(chunk[player]['name'])
            summoner = Summoner(summoner_id=chunk[player]['id'],
                                name=chunk[player]['name'],
                                std_name=chunk[player]['name'].replace(
                                    ' ', '').lower(),
                                profile_icon_id=chunk[player]['profileIconId'],
                                revision_date=chunk[player]['revisionDate'],
                                summoner_level=chunk[player]['summonerLevel'],
                                region=region)

            # Sometimes requests will go out synchronously for the same summoner.
            # This means the cache is not hit and a double query for a single summoner occurs.
            # Duplicate summoners are prevented via the unique_together constraint on summoner_id and region,
            # which will throw IntegrityError and prevent the dupe from being made.
            try:
                #print summoner.name, len(summoner.name)
                summoner.save()
            except IntegrityError:
                pass

    # Requires summoners (as well as all related field values) to be cached before-hand (summoner caching done above).
    for match in recent['games']:
        # first fill in the simple stuff
        game = Game(
            summoner_id=Summoner.objects.filter(region=region).get(
                summoner_id=summoner_id),
            champion_id=Champion.objects.get(champion_id=match['championId']),
            create_date=match['createDate'],
            game_id=match['gameId'],
            game_mode=match['gameMode'],
            game_type=match['gameType'],
            invalid=match['invalid'],
            ip_earned=match['ipEarned'],
            level=match['level'],
            map_id=match['mapId'],
            spell_1=SummonerSpell.objects.get(spell_id=match['spell1']),
            spell_2=SummonerSpell.objects.get(spell_id=match['spell2']),
            sub_type=match['subType'],
            team_id=match['teamId'],
            region=region,
            champion_key=Champion.objects.get(
                champion_id=match['championId']).key)

        stats = RawStat()

        # Here we add stats that were returned (only stats that aren't None or 0 will be returned by API)
        for i in match['stats']:
            setattr(stats, inflection.underscore(i), match['stats'][i])

        stats.save()

        # associate the RawStat object with this game
        game.stats = stats

        game_saved = False

        # Ensures no dupes of Game (or any related objects).
        try:
            game.save()
            game_saved = True
        except IntegrityError:
            pass

        # if game saved, we're good and just need to add the participating players
        if game_saved:
            # associate each Player object with this game
            if 'fellowPlayers' in match:
                for p in match['fellowPlayers']:
                    player = Player(
                        champion=Champion.objects.get(
                            champion_id=p['championId']),
                        summoner=Summoner.objects.filter(region=region).get(
                            summoner_id=p['summonerId']),
                        team_id=p['teamId'],
                        participant_of=game)
                    player.save()
        else:  # if it didn't save, we can get rid of the stats object too.
            stats.delete()