Exemplo n.º 1
0
    def get(self, request, game_id, *args, **kwargs):
        try:
            game = Game.objects.get(pk=game_id)
        except Game.DoesNotExist:
            raise Http404("Game does not exist")

        if request.user.is_authenticated():
            player = Player.objects.get(user=request.user)
            teams = game.teams.all()

            player_team = None
            for team in teams:
                if team.player == player:
                    player_team = team
            if player_team is None:
                raise Http404("Player is not authorised.")

            team_presenters = [TeamPresenter.from_team(team, game) for team in teams]
            is_player_next = is_team_next(player_team, game)

            other_teams = []
            for team in teams:
                if team is not player_team and team.alive:
                    other_teams.append(team)

            context = {
                "game_id": game_id,
                "player_team": TeamPresenter.from_team(player_team, game),
                "teams": team_presenters,
                "attack_form": AttackForm(other_teams=other_teams),
                "is_player_next": is_player_next,
            }
            return render(request, self.template_name, context)
        else:
            raise Http404("Player is not logged in.")
Exemplo n.º 2
0
 def from_team(cls, team, game):
     return cls(
         player=PlayerPresenter.from_player(team.player),
         is_next=is_team_next(team, game),
         winner=team.winner,
         alive=team.alive,
         tiles=cls.make_tiles(team, game)
     )
Exemplo n.º 3
0
    def get(self, request, game_id, *args, **kwargs):
        try:
            game = Game.objects.get(pk=game_id)
        except Game.DoesNotExist:
            raise Http404("Game does not exist")

        if request.user.is_authenticated:
            player = Player.objects.get(user=request.user)
            teams = game.teams.all()

            player_team = None
            for team in teams:
                if team.player == player:
                    player_team = team
            if player_team is None:
                raise Http404("Player is not authorised.")

            team_presenters = [
                TeamPresenter.from_team(
                    team,
                    game
                )
                for team in teams
            ]
            is_player_next = is_team_next(player_team, game)

            other_teams = []
            for team in teams:
                if team is not player_team and team.alive:
                    other_teams.append(team)

            context = {
                'game_id': game_id,
                'player_team': TeamPresenter.from_team(player_team, game),
                'teams': team_presenters,
                'attack_form': AttackForm(other_teams=other_teams),
                'is_player_next': is_player_next
            }
            return render(request, self.template_name, context)
        else:
            raise Http404("Player is not logged in.")
Exemplo n.º 4
0
    def test_non_alive_team(self):
        self.team1.alive = False
        self.team1.save()

        self.assertTrue(is_team_next(self.team2, self.game))
Exemplo n.º 5
0
 def test_team_is_not_next(self):
     self.assertFalse(is_team_next(self.team2, self.game))
     self.assertFalse(is_team_next(self.team3, self.game))
Exemplo n.º 6
0
 def test_team_is_next(self):
     self.assertTrue(is_team_next(self.team1, self.game))
Exemplo n.º 7
0
    def post(self, request, game_id, *args, **kwargs):
        if request.user.is_authenticated():
            try:
                game = Game.objects.get(pk=game_id)
            except Game.DoesNotExist:
                raise Http404("Game does not exist.")

            player = Player.objects.get(user=request.user)

            # Verify the player is involved in this game
            teams = game.teams.all()
            player_team = None
            for team in teams:
                if team.player == player:
                    player_team = team
            if player_team is None:
                raise Http404("Player is not authorised.")

            # Verify it is the player's turn to attack
            is_next = is_team_next(player_team, game)
            if not is_next:
                messages.error(request, 'It\'s not your turn!')
                return HttpResponseRedirect(reverse('game', args=[game_id]))

            other_teams = []
            for team in teams:
                if team is not player_team and team.alive:
                    other_teams.append(team)

            attack_form = AttackForm(request.POST, other_teams=other_teams)
            if attack_form.is_valid():
                target_x = attack_form.cleaned_data['target_x']
                target_y = attack_form.cleaned_data['target_y']
                target_team = attack_form.cleaned_data['target_team']

                other_team = Team.objects.get(pk=target_team)

                # Verify shot hasn't already been attempted
                past_shots = Shot.objects.filter(game=game,
                                                 attacking_team=player_team,
                                                 defending_team=other_team,
                                                 x=target_x,
                                                 y=target_y)

                if len(past_shots) > 0:
                    messages.error(request, 'You\'ve already shot there!')
                    return HttpResponseRedirect(reverse('game',
                                                        args=[game_id]))

                shot = Shot(game=game,
                            attacking_team=player_team,
                            defending_team=other_team,
                            x=target_x,
                            y=target_y)
                shot.save()

                player_team.last_turn = game.turn
                player_team.save()

                game.turn = game.turn + 1
                game.save()

                # Check for hit
                ship_tiles = set()
                for ship in other_team.ships.all():
                    ship_tiles.update(set(ship.get_tiles()))
                other_team_hit = (int(target_x), int(target_y)) in ship_tiles

                # Check for death
                past_shot_tiles = set([
                    (past_shot.x, past_shot.y)
                    for past_shot in Shot.objects.filter(
                        game=game, defending_team=other_team)
                ])
                hit_tiles = past_shot_tiles.intersection(ship_tiles)
                if len(hit_tiles) == len(ship_tiles):
                    other_team.alive = False
                    other_team.save()
                other_team_defeated = not other_team.alive

                # Check for winner
                alive_teams = game.teams.filter(alive=True)
                if len(alive_teams) == 1:
                    alive_teams[0].winner = True
                    alive_teams[0].save()

                if other_team_hit:
                    messages.success(request, 'Hit!')
                    if other_team_defeated:
                        messages.success(
                            request, 'You defeated {name}!'.format(
                                name=other_team.player.user.username))
                else:
                    messages.warning(request, 'Miss!')
                return HttpResponseRedirect(reverse('game', args=[game_id]))
            else:
                return HttpResponseRedirect('/')
        else:
            messages.warning(request, 'You must be logged in to do that.')
            return HttpResponseRedirect('/login')
Exemplo n.º 8
0
 def from_team(cls, team, game):
     return cls(player=PlayerPresenter.from_player(team.player),
                is_next=is_team_next(team, game),
                winner=team.winner,
                alive=team.alive,
                tiles=cls.make_tiles(team, game))
Exemplo n.º 9
0
    def test_non_alive_team(self):
        self.team1.alive = False
        self.team1.save()

        self.assertTrue(is_team_next(self.team2, self.game))
Exemplo n.º 10
0
 def test_team_is_not_next(self):
     self.assertFalse(is_team_next(self.team2, self.game))
     self.assertFalse(is_team_next(self.team3, self.game))
Exemplo n.º 11
0
 def test_team_is_next(self):
     self.assertTrue(is_team_next(self.team1, self.game))
Exemplo n.º 12
0
    def post(self, request, game_id, *args, **kwargs):
        if request.user.is_authenticated():
            try:
                game = Game.objects.get(pk=game_id)
            except Game.DoesNotExist:
                raise Http404("Game does not exist.")

            player = Player.objects.get(user=request.user)

            # Verify the player is involved in this game
            teams = game.teams.all()
            player_team = None
            for team in teams:
                if team.player == player:
                    player_team = team
            if player_team is None:
                raise Http404("Player is not authorised.")

            # Verify it is the player's turn to attack
            is_next = is_team_next(player_team, game)
            if not is_next:
                messages.error(request, "It's not your turn!")
                return HttpResponseRedirect(reverse("game", args=[game_id]))

            other_teams = []
            for team in teams:
                if team is not player_team and team.alive:
                    other_teams.append(team)

            attack_form = AttackForm(request.POST, other_teams=other_teams)
            if attack_form.is_valid():
                target_x = attack_form.cleaned_data["target_x"]
                target_y = attack_form.cleaned_data["target_y"]
                target_team = attack_form.cleaned_data["target_team"]

                other_team = Team.objects.get(pk=target_team)

                # Verify shot hasn't already been attempted
                past_shots = Shot.objects.filter(
                    game=game, attacking_team=player_team, defending_team=other_team, x=target_x, y=target_y
                )

                if len(past_shots) > 0:
                    messages.error(request, "You've already shot there!")
                    return HttpResponseRedirect(reverse("game", args=[game_id]))

                shot = Shot(game=game, attacking_team=player_team, defending_team=other_team, x=target_x, y=target_y)
                shot.save()

                player_team.last_turn = game.turn
                player_team.save()

                game.turn = game.turn + 1
                game.save()

                # Check for hit
                ship_tiles = set()
                for ship in other_team.ships.all():
                    ship_tiles.update(set(ship.get_tiles()))
                other_team_hit = (int(target_x), int(target_y)) in ship_tiles

                # Check for death
                past_shot_tiles = set(
                    [
                        (past_shot.x, past_shot.y)
                        for past_shot in Shot.objects.filter(game=game, defending_team=other_team)
                    ]
                )
                hit_tiles = past_shot_tiles.intersection(ship_tiles)
                if len(hit_tiles) == len(ship_tiles):
                    other_team.alive = False
                    other_team.save()
                other_team_defeated = not other_team.alive

                # Check for winner
                alive_teams = game.teams.filter(alive=True)
                if len(alive_teams) == 1:
                    alive_teams[0].winner = True
                    alive_teams[0].save()

                if other_team_hit:
                    messages.success(request, "Hit!")
                    if other_team_defeated:
                        messages.success(request, "You defeated {name}!".format(name=other_team.player.user.username))
                else:
                    messages.warning(request, "Miss!")
                return HttpResponseRedirect(reverse("game", args=[game_id]))
            else:
                return HttpResponseRedirect("/")
        else:
            messages.warning(request, "You must be logged in to do that.")
            return HttpResponseRedirect("/login")