示例#1
0
文件: views.py 项目: dhui/pingpong
    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)
        points_per_game = int(data["pointsPerGame"])

        # Basic validation
        if points_per_game not in POSSIBLE_POINTS_PER_GAME:
            raise Http404("Invalid points per game: %s" % points_per_game)
        if len(data["teams"]) != 2:
            raise Http404("Invalid # of teams: %s" % len(data["teams"]))

        class TeamProxy(object):
            """
            Proxy object for holding data used to create a team that participated in a match.
            """

            def __init__(self, players, perf):
                self.players = players
                self.perf = perf

        team_proxies = []

        for team in data["teams"]:
            players = Player.objects.filter(id__in=team["players"])
            if not players:
                raise Http404("No players found: %s" % team["players"])
            perf = TeamPerf(score=int(team["score"]), errors=int(team["errors"]))
            # Update the score for the deuce case
            if data["deuce"]:
                if team["wonDeuce"]:
                    perf.score = points_per_game
                else:
                    perf.score = points_per_game - 1
            team_proxies.append(TeamProxy(players, perf))

        # Score validation - one team must have won
        if sum((1 if t.perf.score == points_per_game else 0 for t in team_proxies)) != 1:
            raise Http404("One team must win")
        # Can't have more errors than another team's points
        for team in team_proxies:
            for other_team in team_proxies:
                if other_team == team:
                    continue
                if other_team.perf.score < team.perf.errors:
                    raise Http404("Errors must be less than opposing team's score")

        match = Match(points_per_game=points_per_game)
        for team_proxy in team_proxies:
            team = Team.get_or_create(team_proxy.players)
            team_perf = team_proxy.perf
            team_perf.team = team
            team_perf.save()
            if team_perf.score == points_per_game:
                match.winner_perf = team_perf
            else:
                match.loser_perf = team_perf
        match.save()

        return render_to_json({})
示例#2
0
文件: views.py 项目: dhui/pingpong
 def post(self, request, *args, **kwargs):
     data = json.loads(request.body)
     name = data["name"]
     try:
         player = Player.objects.get(name=name)
         player.active = True
         player.save()
     except Player.DoesNotExist:
         player = Player.objects.create(name=name)
     return render_to_json({"id": player.id})
示例#3
0
文件: views.py 项目: dhui/pingpong
 def delete(self, request, *args, **kwargs):
     data = json.loads(request.body)
     player = Player.objects.get(id=data["id"])
     player.active = False
     player.save()
     return render_to_json({})