Example #1
0
    def test_post_logged_in_playing_duplicate(self):
        self.client.login(username=self.user1.username, password='******')

        shot = Shot(game=self.game,
                    attacking_team=self.team1,
                    defending_team=self.team2,
                    x=0,
                    y=0)
        shot.save()

        url = reverse('attack', args=[self.game.id])
        resp = self.client.post(url, {
            'target_x': 0,
            'target_y': 0,
            'target_team': self.team2.id,
        },
                                follow=True)

        game_url = 'http://testserver{}'.format(
            reverse('game', args=[self.game.id]))
        self.assertIn((game_url, 302), resp.redirect_chain)

        pq = PyQuery(resp.content)

        # Assert error is shown
        self.assertEqual(len(pq('.alert-danger')), 1)
        self.assertIn('You\'ve already shot there', pq('.alert-danger').text())
Example #2
0
    def setUp(self):
        self.game = Game()
        self.game.save()

        self.user1 = User.objects.create_user('user1', '', 'password')
        self.user2 = User.objects.create_user('user2', '', 'password')

        self.player1 = Player(user=self.user1)
        self.player2 = Player(user=self.user2)
        self.player1.save()
        self.player2.save()

        self.team1 = Team(player=self.player1, game=self.game)
        self.team2 = Team(player=self.player2, game=self.game)
        self.team1.save()
        self.team2.save()

        self.ship = Ship(
            team=self.team2,
            x=3,
            y=3,
            length=3,
            direction=Ship.CARDINAL_DIRECTIONS['SOUTH']
        )
        self.ship.save()

        self.shot_miss = Shot(
            game=self.game,
            attacking_team=self.team1,
            defending_team=self.team2,
            x=2,
            y=3
        )
        self.shot_miss.save()

        self.shot_hit = Shot(
            game=self.game,
            attacking_team=self.team1,
            defending_team=self.team2,
            x=3,
            y=5
        )
        self.shot_hit.save()
Example #3
0
    def test_shot_creation(self):
        """Test that Shot instances are created correctly."""
        game = Game()
        game.save()

        attacking_user = User.objects.create_user(
            'attacking_user',
            '',
            'password'
        )
        defending_user = User.objects.create_user(
            'defending_user',
            '',
            'password'
        )
        attacking_user.save()
        defending_user.save()

        attacking_player = Player(user=attacking_user)
        defending_player = Player(user=defending_user)
        attacking_player.save()
        defending_player.save()

        attacking_team = Team(player=attacking_player, game=game)
        defending_team = Team(player=defending_player, game=game)
        attacking_team.save()
        defending_team.save()

        shot = Shot(
            game=game,
            attacking_team=attacking_team,
            defending_team=defending_team,
            x=0,
            y=0
        )

        self.assertTrue(isinstance(shot, Shot))
        self.assertEqual(
            str(shot),
            'Game 1 - attacking_user attacked defending_user (0, 0)'
        )
Example #4
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')
Example #5
0
class TilePresenterTestCase(TestCase):

    def setUp(self):
        self.game = Game()
        self.game.save()

        self.user1 = User.objects.create_user('user1', '', 'password')
        self.user2 = User.objects.create_user('user2', '', 'password')

        self.player1 = Player(user=self.user1)
        self.player2 = Player(user=self.user2)
        self.player1.save()
        self.player2.save()

        self.team1 = Team(player=self.player1, game=self.game)
        self.team2 = Team(player=self.player2, game=self.game)
        self.team1.save()
        self.team2.save()

        self.ship = Ship(
            team=self.team2,
            x=3,
            y=3,
            length=3,
            direction=Ship.CARDINAL_DIRECTIONS['SOUTH']
        )
        self.ship.save()

        self.shot_miss = Shot(
            game=self.game,
            attacking_team=self.team1,
            defending_team=self.team2,
            x=2,
            y=3
        )
        self.shot_miss.save()

        self.shot_hit = Shot(
            game=self.game,
            attacking_team=self.team1,
            defending_team=self.team2,
            x=3,
            y=5
        )
        self.shot_hit.save()

    def test_from_team(self):
        presenter = TilePresenter.from_team(
            x=0,
            y=1,
            team=self.team2,
            game=self.game
        )

        self.assertEqual(presenter.x, 0)
        self.assertEqual(presenter.y, 1)
        self.assertEqual(presenter.name, 'A1')
        self.assertTrue(presenter.is_empty)
        self.assertFalse(presenter.is_hit)

    def test_from_team_with_miss(self):
        presenter = TilePresenter.from_team(
            x=2,
            y=3,
            team=self.team2,
            game=self.game
        )

        self.assertEqual(presenter.x, 2)
        self.assertEqual(presenter.y, 3)
        self.assertEqual(presenter.name, 'C3')
        self.assertTrue(presenter.is_empty)
        self.assertTrue(presenter.is_hit)

    def test_from_team_with_ship(self):
        presenter = TilePresenter.from_team(
            x=3,
            y=4,
            team=self.team2,
            game=self.game
        )

        self.assertEqual(presenter.x, 3)
        self.assertEqual(presenter.y, 4)
        self.assertEqual(presenter.name, 'D4')
        self.assertFalse(presenter.is_empty)
        self.assertFalse(presenter.is_hit)

    def test_from_team_with_hit_ship(self):
        presenter = TilePresenter.from_team(
            x=3,
            y=5,
            team=self.team2,
            game=self.game
        )

        self.assertEqual(presenter.x, 3)
        self.assertEqual(presenter.y, 5)
        self.assertEqual(presenter.name, 'D5')
        self.assertFalse(presenter.is_empty)
        self.assertTrue(presenter.is_hit)
Example #6
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")