Exemplo n.º 1
0
def run():
    print("importing player data now")
    
    with open('./../resources/NFL Salary Visualization - nfl_salaries.csv', newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            first_name = row['player'].split(' ')[0]
            last_name = row['player'].split(' ')[1]
            salary = row['salary']
            team_name = teams.teams[row['team']]
            position_name = positions.positions[row['position']]

            team = Team.objects.filter(name=team_name).first()
            if not team:
                team = Team(name=team_name, name_abbreviated=row['team'])
                team.save()


            position = Position.objects.filter(name=position_name).first()
            if not position:
                position = Position(name=position_name, name_abbreviated=row['position'])
                position.save()
            
            player = Player(
                email='{}.{}@{}.net'.format(first_name, last_name, team.name_abbreviated),
                first_name=first_name,
                password='******',
                last_name=last_name,
                position=position,
                team=team,
                salary=int(salary))
            player.save()
    print('syncing now')
    sync_entities()
Exemplo n.º 2
0
    def players(self, fake):
        teams = Team.objects.all()
        player = Role.objects.filter(type='P').first()
        users = UserRole.objects.filter(role_id=player.id)

        total = 0
        for team in teams:
            counter = 0
            while counter < 10:
                try:
                    player = Player(user_id=users[total].user.id,
                                    team_id=team.id,
                                    jersey_number=counter + 1,
                                    height=fake.random_int(min=100,
                                                           max=255,
                                                           step=1))
                except ObjectDoesNotExist:
                    raise Warning('Issue with adding user as Player')
                player.save()
                self.stdout.write(
                    self.style.SUCCESS('Player Created  : %s %s' %
                                       (users[total].user.first_name,
                                        users[total].user.username)))
                total += 1
                counter += 1
Exemplo n.º 3
0
    def post(self, request, *args, **kwargs):
        user_form = UserForm(data=request.POST)
        player_form = PlayerForm(data=request.POST)

        if user_form.is_valid() and player_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()

            player = Player(user=user)
            player.save()

            user = authenticate(
                username=user_form.cleaned_data['username'],
                password=user_form.cleaned_data['password']
            )
            login(request, user)

            return HttpResponseRedirect('/')
        else:
            context = {
                'user_form': user_form
            }
            messages.error(request, 'Something went wrong...')
            return render(request, self.template_name, context)
Exemplo n.º 4
0
    def test_ship_creation(self):
        """Test that Ship instances are created correctly."""
        game = Game()
        game.save()

        user = User(username='******', password='******')
        user.save()

        player = Player(user=user)
        player.save()

        team = Team(player=player, game=game)
        team.save()

        ship = Ship(
            team=team,
            x=0,
            y=0,
            length=3,
            direction=Ship.CARDINAL_DIRECTIONS['WEST']
        )

        self.assertTrue(isinstance(ship, Ship))
        self.assertEqual(
            str(ship),
            'Game 1 - user\'s 3L at (0, 0) facing West'
        )
    def get_golfer_by_id(self, player_id):
        """
        Extracts data from a golfer based on their player_id. Looks like the
        table on ESPN doesn't include every golfer that could potentially show
        up in a tournament.
        """
        response = requests.get(
            "http://www.espn.com/golf/player/_/id/{}/".format(player_id))
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')
            mod_content = soup.find("div", class_="mod-content")
            player_bio = mod_content.find("div", class_="player-bio")

            player_name_full = mod_content.find("h1").text

            first_name = player_name_full.split(' ')[0]
            last_name = " ".join(player_name_full.split(' ')[1:])
            country = player_bio.find("ul", class_="general-info").find(
                "li", class_="first").text

            try:
                existing_player = Player.objects.object(player_id=player_id)
                print("Golfer with id: {} already exists".format(player_id))
            except:
                new_player = Player(player_id=player_id,
                                    first_name=first_name,
                                    last_name=last_name,
                                    country=country)
                new_player.save()
                print("{} {} added to the players database".format(
                    first_name, last_name))
        else:
            raise ValueError(
                "Could not find a player by id: {}".format(player_id))
Exemplo n.º 6
0
def linkaccounts(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/')
    if request.method == 'POST':
        username = request.POST['MCUsername']
        password = request.POST['MCPassword']
        verified = minecraft.connect_minecraft(username, password)
        if verified is False:
            return render(request, 'linkaccounts.html', {
                'error': True,
                'errormsg': 'minerap.com does not recognize your login credentials. Please try again'
            })
        else:
            if utils.minecraftAccountAlreadyExists(verified):
                return render(request, 'linkaccounts.html', {
                    'error': True,
                    'errormsg': 'Your minecraft account has already been registered on The White Book. Please use another.'
                })
            else: 
                now = datetime.datetime.utcnow().replace(tzinfo=utc)               
                player = Player(user=request.user, mc_username=verified, score=0, rank=0, most_recent=(now - datetime.timedelta(seconds=60)))
                player.save()
                return HttpResponseRedirect('/')
    if request.method == 'GET':
        return render(request, 'linkaccounts.html', {})
class PlayerPresenterTestCase(TestCase):
    def setUp(self):
        self.user = User.objects.create_user("user1", "", "password")
        self.player = Player(user=self.user)
        self.player.save()

        self.winning_game = Game()
        self.losing_game = Game()
        self.in_progress_game = Game()
        self.winning_game.save()
        self.losing_game.save()
        self.in_progress_game.save()

        self.winning_team = Team(game=self.winning_game, player=self.player, alive=True, winner=True)
        self.losing_team = Team(game=self.losing_game, player=self.player, alive=False, winner=False)
        self.in_progress_team = Team(game=self.in_progress_game, player=self.player, alive=True, winner=False)
        self.winning_team.save()
        self.losing_team.save()
        self.in_progress_team.save()

    def test_from_player(self):
        presenter = PlayerPresenter.from_player(self.player)

        self.assertEqual(presenter.username, self.user.username)
        self.assertEqual(presenter.win_count, 1)
        self.assertEqual(presenter.loss_count, 1)
        self.assertEqual(presenter.in_progress_count, 1)
Exemplo n.º 8
0
def player_list(request, format=None):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        snippets = Player.objects.all()
        serializer = PlayerSerializer(snippets, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = PlayerSerializer(data=request.data)
        print("In player list")
        ##d = Team(id=1, name="Thomas Davis")
        ##c = Player(id=9, name="Thomas", DOB='28/01/1998')
        ##d.players.add(c)
        ##data = request.data['Home_Team']
        ##snippet = Player.objects.get(name=name)
        print(request.data['TeamID'])
        if serializer.is_valid():
            player = Player(name=request.data['name'], DOB=request.data['DOB'])
            player.save()
            print(player.name)
            print(player.id)
            ##serializer.save()
            addPlayer = Player(id=player.id,
                               name=request.data['name'],
                               DOB=request.data['DOB'])
            team = Team(id=request.data['TeamID'])
            team.players.add(addPlayer)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 9
0
def generate_players():
    gender = 'male'
    if reset():
        gender = 'female'

    name = names.get_first_name(gender=gender)
    battles_total = random.randint(0, 200)
    wins_total = random.randint(0, battles_total)
    days_total = 123
    vehicles_x = random.randint(0, 25)
    if battles_total == 0:
        exp_total = 0
    else:
        exp_total = random.randint(1000, 100000)

    is_hidden = reset(20)

    player = Player(name=name,
                    battles_total=battles_total,
                    wins_total=wins_total,
                    days_total=days_total,
                    vehicles_x=vehicles_x,
                    exp_total=exp_total,
                    is_hidden=is_hidden)

    player.save()
Exemplo n.º 10
0
class TeamPresenterTestCase(TestCase):

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

        self.user = User.objects.create_user('user', '', 'password')

        self.player = Player(user=self.user)
        self.player.save()

        self.team = Team(player=self.player, game=self.game)
        self.team.save()

    def test_from_team(self):
        presenter = TeamPresenter.from_team(team=self.team, game=self.game)

        self.assertEqual(presenter.player.username, self.user.username)
        self.assertTrue(presenter.is_next)
        self.assertEqual(presenter.winner, self.team.winner)
        self.assertEqual(presenter.alive, self.team.alive)
        self.assertEqual(len(presenter.tiles), GAME_SIZE)
        self.assertEqual(len(presenter.tiles[0]), GAME_SIZE)

    def test_make_tiles(self):
        tiles = TeamPresenter.make_tiles(team=self.team, game=self.game)

        self.assertEqual(len(tiles), GAME_SIZE)
        for i in range(0, GAME_SIZE):
            self.assertEqual(len(tiles[i]), GAME_SIZE)
Exemplo n.º 11
0
def create_player(request, player):
    "Creates a new player"
    try:
        p = Player(pid=Player.generate_pid(), name=player)
        p.save()
        return JsonResponse(p.to_json())
    except IntegrityError:
        return JsonErrorResponse({'error': 'invalid name for new player'})
Exemplo n.º 12
0
def regConPlayer(request):
    club = request.POST['club']
    name = request.POST['name']
    gender = request.POST['gender']
    nname = request.POST['nname']

    qs = Player(p_club=club, p_name=name, p_gender=gender, p_nname=nname)
    qs.save()

    return HttpResponseRedirect(reverse('players:playerAll'))
Exemplo n.º 13
0
    def test_existent_user(self):
        user = User.objects.create_user('user1', '', 'password')
        player = Player(user=user)
        player.save()

        url = reverse('player_profile', args=[user.username])
        resp = self.client.get(url)

        self.assertEqual(resp.status_code, 200)
        pq = PyQuery(resp.content)

        self.assertEqual(pq('h2').text(), user.username)
Exemplo n.º 14
0
def regConPlayer(request) :
	pid = request.POST['pid']
	nick = request.POST['nick']
	email = request.POST['email']
	name = request.POST['name']
	birth = request.POST['birth']
	position = request.POST['position']
	team = request.POST['team']

	qs = Player(p_pid=pid, p_nick=nick, p_email=email, p_name=name, p_birth=birth, p_position=position, p_team=team)
	qs.save()

	return HttpResponseRedirect(reverse('players:playerAll'))
Exemplo n.º 15
0
    def test_team_creation(self):
        """Test that Team instances are created correctly."""
        game = Game()
        game.save()

        user = User.objects.create_user('user', '', 'password')

        player = Player(user=user)
        player.save()

        team = Team(player=player, game=game)

        self.assertTrue(isinstance(team, Team))
        self.assertEqual(str(team), 'Game 1 - user (last_turn=0)')
Exemplo n.º 16
0
class LogoutViewTestCase(TestCase):
    def setUp(self):
        self.user = User.objects.create_user('user', '', 'password')

        self.player = Player(user=self.user)
        self.player.save()

    def test_get(self):
        self.client.login(username=self.user.username, password='******')

        url = reverse('logout')
        resp = self.client.get(url)

        self.assertRedirects(resp, reverse('home'))
        self.assertNotIn('_auth_user_id', self.client.session)
Exemplo n.º 17
0
def create_player(player):
    """Creates an quarterback object combining different elements from the list"""

    player = Player(
        year=player["year"],
        name=player["name"],
        team=player["team"],
        position=player["position"],
        rush_attempts=player["rush_attempts"],
        rush_yards=player["rush_yards"],
        yards_per_rush=player["yards_per_rush"],
        rush_touchdowns=player["rush_touchdowns"],
        rushes_per_touchdown=player["rushes_per_touchdown"],
        fumbles=player["fumbles"],
        pass_attempts=player["pass_attempts"],
        pass_completions=player["pass_completions"],
        completion_percentage=player["completion_percentage"],
        pass_yards=player["pass_yards"],
        yards_per_pass_attempt=player["yards_per_pass_attempt"],
        yards_per_completion=player["yards_per_completion"],
        pass_touchdowns=player["pass_touchdowns"],
        passes_per_touchdown=player["passes_per_touchdown"],
        interceptions=player["interceptions"],
        targets=player["targets"],
        receptions=player["receptions"],
        catch_percentage=player["catch_percentage"],
        receiving_yards=player["receiving_yards"],
        yards_per_reception=player["yards_per_reception"],
        yards_per_target=player["yards_per_target"],
        receiving_touchdowns=player["receiving_touchdowns"],
        receptions_per_touchdown=player["receptions_per_touchdown"],
        targets_per_touchdown=player["targets_per_touchdown"],
        total_attempts=player["total_attempts"],
        total_yards=player["total_yards"],
        yards_per_attempt=player["yards_per_attempt"],
        total_touchdowns=player["total_touchdowns"],
        attempts_per_touchdown=player["attempts_per_touchdown"],
        games=player["games"],
        attempts_per_game=player["attempts_per_game"],
        points=player["points"],
        points_per_game=player["points_per_game"],
        points_per_attempt=player["points_per_attempt"],
        average_value_over_replacement=player[
            "average_value_over_replacement"],
        starting_value_over_replacement=player[
            "starting_value_over_replacement"])
    player.save()
    return player
Exemplo n.º 18
0
def settingsRefreshPlayers(request):
    item = "NEMA"
    if request.method == "POST":
        log = request.POST.get('log')
        players = []
        rows_created = 0
        rows_updated = 0

        for item in log.splitlines():
            if "' logged in" in item:
                steam_id = ""
                ingame_name = ""
                server_id = ""

                item = item.split("'")

                #item = item[2].split(':')
                steam_id = item[1].split(':')[0].split(' ')[1]
                #item = item[1].split('(')
                ingame_name = item[1].split(':')[1].split('(')[0]
                server_id = item[1].split(':')[1].split('(')[1][:-1]

                if server_id.isdigit():
                    obj = Player.objects.filter(steam_id=steam_id).first()
                    if obj is None:
                        player = Player(steam_id=steam_id,
                                        ingame_name=ingame_name,
                                        server_id=int(server_id))
                        player.save()
                        rows_created += 1
                        #line = str(steam_id) + '###' + str(ingame_name) + '###' + str(server_id)
                        #players.append(line)
                    else:
                        if obj.ingame_name != ingame_name or obj.server_id != int(
                                server_id):
                            obj.server_id = int(server_id)
                            obj.save()
                            rows_updated += 1
        item = players

        messages.success(
            request, 'Players created: ' + str(rows_created) +
            '  Players updated: ' + str(rows_updated))

    page_title = " - Refresh player list"
    context = {'page_title': page_title, 'item': item}
    return render(request, 'settings/settings_login_refresh.html', context)
Exemplo n.º 19
0
    def handle(self, *args, **options):
        number = 10

        if options['number']:
            number = options['number']

        for i in range(0, number):
            gender = 'male'

            if self.reset():
                gender = 'female'

            name = names.get_first_name(gender=gender)
            battles_total = random.randint(0, 1200)
            wins_total = random.randint(0, battles_total)

            if wins_total > 0:
                days_total = random.randint(1, 1000)
            else:
                days_total = 0

            vehicles_x = random.randint(0, 25)
            if battles_total == 0:
                exp_total = 0
            else:
                exp_total = random.randint(1000, 100000)

            is_hidden = self.reset(15)

            date = timezone.now() - timedelta(days=days_total)

            player = Player(name=name,
                            battles_total=battles_total,
                            wins_total=wins_total,
                            days_total=days_total,
                            vehicles_x=vehicles_x,
                            exp_total=exp_total,
                            is_hidden=is_hidden,
                            created_at=date)

            try:
                player.save()
            except IntegrityError as e:
                print('Catch unique name')
                player.name += str(random.randint(1, 9999))
                player.save()
Exemplo n.º 20
0
class SignupViewTestCase(TestCase):

    def setUp(self):
        self.user = User.objects.create_user('user', '', 'password')

        self.player = Player(user=self.user)
        self.player.save()

    def test_get_logged_out(self):
        url = reverse('signup')
        resp = self.client.get(url)

        self.assertEqual(resp.status_code, 200)
        pq = PyQuery(resp.content)

        self.assertEqual(len(pq('input#id_username')), 1)
        self.assertEqual(len(pq('input#id_password')), 1)

    def test_get_logged_in(self):
        self.client.login(
            username=self.user.username,
            password='******'
        )

        url = reverse('signup')
        resp = self.client.get(url)

        self.assertRedirects(resp, reverse('home'))

    def test_post(self):
        url = reverse('signup')
        resp = self.client.post(url, {
            'username': ['newuser'],
            'password': ['password']
        })

        player = Player.objects.all().order_by('-id')[0]

        self.assertEqual(player.user.username, 'newuser')
        self.assertTrue(player.user.check_password('password'))
        self.assertRedirects(resp, reverse('home'))
        self.assertIn('_auth_user_id', self.client.session)
        self.assertEqual(
            int(self.client.session['_auth_user_id']),
            player.user.id
        )
Exemplo n.º 21
0
class PlayerPresenterTestCase(TestCase):

    def setUp(self):
        self.user = User.objects.create_user('user1', '', 'password')
        self.player = Player(user=self.user)
        self.player.save()

        self.winning_game = Game()
        self.losing_game = Game()
        self.in_progress_game = Game()
        self.winning_game.save()
        self.losing_game.save()
        self.in_progress_game.save()

        self.winning_team = Team(
            game=self.winning_game,
            player=self.player,
            alive=True,
            winner=True
        )
        self.losing_team = Team(
            game=self.losing_game,
            player=self.player,
            alive=False,
            winner=False
        )
        self.in_progress_team = Team(
            game=self.in_progress_game,
            player=self.player,
            alive=True,
            winner=False
        )
        self.winning_team.save()
        self.losing_team.save()
        self.in_progress_team.save()

    def test_from_player(self):
        presenter = PlayerPresenter.from_player(self.player)

        self.assertEqual(presenter.username, self.user.username)
        self.assertEqual(presenter.win_count, 1)
        self.assertEqual(presenter.loss_count, 1)
        self.assertEqual(presenter.in_progress_count, 1)
Exemplo n.º 22
0
class LogoutViewTestCase(TestCase):

    def setUp(self):
        self.user = User.objects.create_user('user', '', 'password')

        self.player = Player(user=self.user)
        self.player.save()

    def test_get(self):
        self.client.login(
            username=self.user.username,
            password='******'
        )

        url = reverse('logout')
        resp = self.client.get(url)

        self.assertRedirects(resp, reverse('home'))
        self.assertNotIn('_auth_user_id', self.client.session)
Exemplo n.º 23
0
    def test_game_creation(self):
        """Test that Game instances are created correctly."""
        game = Game()
        game.save()

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

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

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

        self.assertTrue(isinstance(game, Game))
        self.assertEqual(str(game), '1 - user1 user2')
Exemplo n.º 24
0
    def post(self, request, format=None):
        postArgs = request.POST

        race = Race.objects.get(id=int(postArgs["race"]))
        actorClass = Class.objects.get(id=int(postArgs["class"]))

        #TODO Store rolls and use the last one rather than accepting any input, in case there are cheaters...
        newPlayer = Player(base_strength=int(postArgs["str"]),
                           base_dexterity=int(postArgs["dex"]),
                           base_constitution=int(postArgs["con"]),
                           base_intelligence=int(postArgs["int"]),
                           base_wisdom=int(postArgs["wis"]),
                           base_charisma=int(postArgs["cha"]),
                           race=race,
                           actor_class=actorClass,
                           owner=request.user)

        newPlayer.save()

        return Response({"ok": True})
Exemplo n.º 25
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)'
        )
Exemplo n.º 26
0
    def post(self, request, *args, **kwargs):
        user_form = UserForm(data=request.POST)
        player_form = PlayerForm(data=request.POST)

        if user_form.is_valid() and player_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()

            player = Player(user=user)
            player.save()

            user = authenticate(username=user_form.cleaned_data['username'],
                                password=user_form.cleaned_data['password'])
            login(request, user)

            return HttpResponseRedirect('/')
        else:
            context = {'user_form': user_form}
            messages.error(request, 'Something went wrong...')
            return render(request, self.template_name, context)
Exemplo n.º 27
0
class SignupViewTestCase(TestCase):
    def setUp(self):
        self.user = User.objects.create_user('user', '', 'password')

        self.player = Player(user=self.user)
        self.player.save()

    def test_get_logged_out(self):
        url = reverse('signup')
        resp = self.client.get(url)

        self.assertEqual(resp.status_code, 200)
        pq = PyQuery(resp.content)

        self.assertEqual(len(pq('input#id_username')), 1)
        self.assertEqual(len(pq('input#id_password')), 1)

    def test_get_logged_in(self):
        self.client.login(username=self.user.username, password='******')

        url = reverse('signup')
        resp = self.client.get(url)

        self.assertRedirects(resp, reverse('home'))

    def test_post(self):
        url = reverse('signup')
        resp = self.client.post(url, {
            'username': ['newuser'],
            'password': ['password']
        })

        player = Player.objects.all().order_by('-id')[0]

        self.assertEqual(player.user.username, 'newuser')
        self.assertTrue(player.user.check_password('password'))
        self.assertRedirects(resp, reverse('home'))
        self.assertIn('_auth_user_id', self.client.session)
        self.assertEqual(int(self.client.session['_auth_user_id']),
                         player.user.id)
Exemplo n.º 28
0
class IsTeamNextTestCase(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.user3 = User.objects.create_user('user3', '', 'password')

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

        self.team1 = Team(player=self.player1, game=self.game, last_turn=1)
        self.team2 = Team(player=self.player2, game=self.game, last_turn=2)
        self.team3 = Team(player=self.player3, game=self.game, last_turn=3)
        self.team1.save()
        self.team2.save()
        self.team3.save()

    def test_team_is_next(self):
        self.assertTrue(is_team_next(self.team1, self.game))

    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))

    def test_non_alive_team(self):
        self.team1.alive = False
        self.team1.save()

        self.assertTrue(is_team_next(self.team2, self.game))
Exemplo n.º 29
0
    def post(self, request, *args, **kwargs):
        nick = request.POST.get('nickname')
        faction = request.POST.get('faction')
        level = request.POST.get('level')
        ap = request.POST.get('ap')
        email = request.POST.get('email')

        if not nick and faction and level and ap and email:
            return HttpResponseBadRequest(
                content=json.dumps({'error': 'Bad request. '
                                             'Must include all the necessary '
                                             'fields.'}),
                content_type='application/json'
            )

        try:
            player = Player.objects.get(email=email)
        except Player.DoesNotExist:
            player = Player()

        player.nickname = nick
        if faction == u'RESISTANCE':
            player.faction = player.FACTION_CHOICES.RESISTANCE
        else:
            player.faction = Player.FACTION_CHOICES.ENLIGHTENED

        player.ap = int(ap)
        player.email = email

        player.save()

        response = OrderedDict()
        response['status'] = 'success'
        response['position'] = player.position()

        return HttpResponse(
            content=json.dumps(response),
            content_type='application/json'
        )
Exemplo n.º 30
0
class GamePresenterTestCase(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()

    def test_from_game(self):
        presenter = GamePresenter.from_game(self.game)

        self.assertEqual(presenter.id, self.game.id)
        self.assertEqual(len(presenter.teams), 2)
Exemplo n.º 31
0
class IsTeamNextTestCase(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.user3 = User.objects.create_user('user3', '', 'password')

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

        self.team1 = Team(player=self.player1, game=self.game, last_turn=1)
        self.team2 = Team(player=self.player2, game=self.game, last_turn=2)
        self.team3 = Team(player=self.player3, game=self.game, last_turn=3)
        self.team1.save()
        self.team2.save()
        self.team3.save()

    def test_team_is_next(self):
        self.assertTrue(is_team_next(self.team1, self.game))

    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))

    def test_non_alive_team(self):
        self.team1.alive = False
        self.team1.save()

        self.assertTrue(is_team_next(self.team2, self.game))
Exemplo n.º 32
0
class LoginViewTestCase(TestCase):
    def setUp(self):
        self.active_user = User.objects.create_user('active_user', '',
                                                    'password')
        self.inactive_user = User.objects.create_user('inactive_user', '',
                                                      'password')

        self.inactive_user.is_active = False
        self.inactive_user.save()

        self.player1 = Player(user=self.active_user)
        self.player2 = Player(user=self.inactive_user)
        self.player1.save()
        self.player2.save()

    def test_get(self):
        url = reverse('login')
        resp = self.client.get(url)

        self.assertEqual(resp.status_code, 200)
        pq = PyQuery(resp.content)

        self.assertEqual(len(pq('input#username')), 1)
        self.assertEqual(len(pq('input#password')), 1)

    def test_post(self):
        url = reverse('login')
        resp = self.client.post(url, {
            'username': '******',
            'password': '******'
        })

        self.assertIn('_auth_user_id', self.client.session)
        self.assertEqual(int(self.client.session['_auth_user_id']),
                         self.active_user.id)
        self.assertRedirects(resp, reverse('home'))

    def test_post_inactive_user(self):
        url = reverse('login')
        resp = self.client.post(url, {
            'username': '******',
            'password': '******'
        })

        self.assertEqual(resp.status_code, 200)

        pq = PyQuery(resp.content)
        self.assertIn('Your account is disabled', pq('.alert-danger').text())

    def test_post_bad_password(self):
        url = reverse('login')
        resp = self.client.post(url, {
            'username': '******',
            'password': '******'
        })

        self.assertEqual(resp.status_code, 200)

        pq = PyQuery(resp.content)
        self.assertIn('Your username and/or password is incorrect',
                      pq('.alert-danger').text())
Exemplo n.º 33
0
class HomeViewTestCase(TestCase):
    def setUp(self):
        self.game1 = Game()
        self.game2 = Game()
        self.game1.save()
        self.game2.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.team_game1 = Team(player=self.player1, game=self.game1)
        self.team_game2 = Team(player=self.player1,
                               game=self.game2,
                               alive=False)
        self.team_game1.save()
        self.team_game2.save()

    def test_logged_out(self):
        url = reverse('home')
        resp = self.client.get(url)

        self.assertEqual(resp.status_code, 200)
        pq = PyQuery(resp.content)

        self.assertIn('You\'re not logged in', pq('h3').text())
        links = [e.attr('href') for e in pq('.container a').items()]
        self.assertIn(reverse('login'), links)
        self.assertIn(reverse('signup'), links)

    def test_logged_in_with_matches(self):
        self.client.login(username=self.user1.username, password='******')

        url = reverse('home')
        resp = self.client.get(url)

        self.assertEqual(resp.status_code, 200)
        pq = PyQuery(resp.content)

        # Assert links to 'Create New Game' plus ongoing games are shown
        self.assertIn('Your Active Games', pq('h3').text())
        links = [e.attr('href') for e in pq('.container a').items()]
        self.assertIn(reverse('game', args=[self.game1.id]), links)
        self.assertNotIn(reverse('game', args=[self.game2.id]), links)
        self.assertIn(reverse('create_game'), links)

    def test_logged_in_without_matches(self):
        self.client.login(username=self.user2.username, password='******')

        url = reverse('home')
        resp = self.client.get(url)

        self.assertEqual(resp.status_code, 200)
        pq = PyQuery(resp.content)

        # Assert only link to 'Create New Game' is shown
        self.assertEqual(len(pq('.container a')), 1)
        links = [e.attr('href') for e in pq('.container a').items()]
        self.assertIn(reverse('create_game'), links)
Exemplo n.º 34
0
class CreateGameViewTestCase(TestCase):
    def setUp(self):
        self.user1 = User.objects.create_user('user1', '', 'password')
        self.user2 = User.objects.create_user('user2', '', 'password')
        self.user3 = User.objects.create_user('user3', '', 'password')

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

    def test_get(self):
        url = reverse('create_game')
        resp = self.client.get(url)

        self.assertEqual(resp.status_code, 200)
        pq = PyQuery(resp.content)

        # Assert there's a field for entering a username
        self.assertEqual(len(pq('[name="opponent_username_0"]')), 1)

    def test_post_logged_out(self):
        url = reverse('create_game')
        resp = self.client.post(url,
                                {'opponent_username_0': self.user2.username})

        self.assertEqual(resp.status_code, 302)
        self.assertRedirects(resp, reverse('login'))

    def test_post_logged_in_invalid_username(self):
        self.client.login(username=self.user1.username, password='******')

        url = reverse('create_game')
        resp = self.client.post(url,
                                {'opponent_username_0': 'nonexistantuser'})

        self.assertEqual(resp.status_code, 200)
        pq = PyQuery(resp.content)

        # Assert error is shown
        self.assertEqual(len(pq('.alert-danger')), 1)
        self.assertIn('User does not exist', pq('.alert-danger').text())

    def test_post_logged_in_valid_username(self):
        self.client.login(username=self.user1.username, password='******')

        url = reverse('create_game')
        resp = self.client.post(url,
                                {'opponent_username_0': self.user2.username})

        game = Game.objects.all().order_by('-id')[0]
        teams = game.teams.all()
        team_names = [team.player.user.username for team in teams]

        self.assertRedirects(resp, reverse('game', args=[game.id]))
        self.assertEqual(len(teams), 2)
        self.assertIn(self.user1.username, team_names)
        self.assertIn(self.user2.username, team_names)

    def test_post_logged_in_multiple_username(self):
        self.client.login(username=self.user1.username, password='******')

        url = reverse('create_game')
        resp = self.client.post(
            url, {
                'opponent_username_0': self.user2.username,
                'opponent_username_1': self.user3.username
            })

        game = Game.objects.all().order_by('-id')[0]
        teams = game.teams.all()
        team_names = [team.player.user.username for team in teams]

        self.assertRedirects(resp, reverse('game', args=[game.id]))
        self.assertEqual(len(teams), 3)
        self.assertIn(self.user1.username, team_names)
        self.assertIn(self.user2.username, team_names)
        self.assertIn(self.user3.username, team_names)
Exemplo n.º 35
0
class AttackViewTestCase(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.user3 = User.objects.create_user('user3', '', 'password')

        self.player1 = Player(user=self.user1)
        self.player2 = Player(user=self.user2)
        self.player3 = Player(user=self.user3)
        self.player1.save()
        self.player2.save()
        self.player3.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()

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

        self.assertEqual(resp.status_code, 302)
        self.assertRedirects(resp, reverse('login'))

    def test_post_non_existent_game(self):
        self.client.login(username=self.user3.username, password='******')

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

        self.assertEqual(resp.status_code, 404)

    def test_post_logged_in_not_playing(self):
        self.client.login(username=self.user3.username, password='******')

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

        self.assertEqual(resp.status_code, 404)

    def test_post_logged_in_playing_not_turn(self):
        self.client.login(username=self.user2.username, password='******')

        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('It\'s not your turn', pq('.alert-danger').text())

    def test_post_logged_in_playing_miss(self):
        self.client.login(username=self.user1.username, password='******')

        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-warning')), 1)
        self.assertIn('Miss', pq('.alert-warning').text())

    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())

    def test_post_logged_in_playing_hit(self):
        self.client.login(username=self.user1.username, password='******')

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

        url = reverse('attack', args=[self.game.id])
        resp = self.client.post(url, {
            'target_x': 1,
            'target_y': 1,
            '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-success')), 1)
        self.assertIn('Hit', pq('.alert-success').text())

    def test_post_logged_in_playing_defeat(self):
        self.client.login(username=self.user1.username, password='******')

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

        url = reverse('attack', args=[self.game.id])
        resp = self.client.post(url, {
            'target_x': 1,
            'target_y': 1,
            '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-success')), 2)
        self.assertIn('Hit', pq('.alert-success').text())
        self.assertIn('You defeated user2', pq('.alert-success').text())
Exemplo n.º 36
0
class GameViewTestCase(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.user3 = User.objects.create_user('user3', '', 'password')

        self.player1 = Player(user=self.user1)
        self.player2 = Player(user=self.user2)
        self.player3 = Player(user=self.user3)
        self.player1.save()
        self.player2.save()
        self.player3.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()

    def test_non_existant_game(self):
        url = reverse('game', args=[2])
        resp = self.client.get(url)

        self.assertEqual(resp.status_code, 404)

    def test_logged_out(self):
        url = reverse('game', args=[self.game.id])
        resp = self.client.get(url)

        self.assertEqual(resp.status_code, 404)

    def test_logged_in_playing_current_turn(self):
        self.client.login(username=self.user1.username, password='******')

        url = reverse('game', args=[self.game.id])
        resp = self.client.get(url)

        self.assertEqual(resp.status_code, 200)
        pq = PyQuery(resp.content)

        # Assert we have one board for each player
        self.assertEqual(len(pq('.board')), 2)
        self.assertIn('user1\'s board', pq('.board h3').text())
        self.assertIn('user2\'s board', pq('.board h3').text())
        # Assert the player is given an attack form
        self.assertEqual(len(pq('#attack-form')), 1)

    def test_logged_in_playing_not_current_turn(self):
        self.client.login(username=self.user2.username, password='******')

        url = reverse('game', args=[self.game.id])
        resp = self.client.get(url)

        self.assertEqual(resp.status_code, 200)
        pq = PyQuery(resp.content)

        # Assert we have one board for each player
        self.assertEqual(len(pq('.board')), 2)
        self.assertIn('user1\'s board', pq('.board h3').text())
        self.assertIn('user2\'s board', pq('.board h3').text())
        # Assert the player is not given an attack form
        self.assertEqual(len(pq('#attack-form')), 0)

    def test_logged_in_not_playing(self):
        self.client.login(username=self.user3.username, password='******')

        url = reverse('game', args=[self.game.id])
        resp = self.client.get(url)

        self.assertEqual(resp.status_code, 404)
import sys
import os
import csv
sys.path.append(os.path.abspath(os.path.curdir))
os.environ['DJANGO_SETTINGS_MODULE'] = 'fantasyfootball.settings'
from players.models import Player

player_file = 'playerout.csv'
with open(player_file,'rb') as f:
    reader = csv.reader(f,delimiter=',')
    for row in reader:
        player = Player(name = row[0], team_name = row[1], player_position = row[4], buy_value = row[2], next_three = row[5], last_three =row[6], expected= row[10], idn = row[9], news =row[3], chance_of_playing =row[8] , expected_three=row[11])
        try:
            player.save()
        except:
            # if the're a problem anywhere, you wanna know about it
            print "there was a problem with line"
            raise


Exemplo n.º 38
0
class HomeViewTestCase(TestCase):

    def setUp(self):
        self.game1 = Game()
        self.game2 = Game()
        self.game1.save()
        self.game2.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.team_game1 = Team(
            player=self.player1,
            game=self.game1
        )
        self.team_game2 = Team(
            player=self.player1,
            game=self.game2,
            alive=False
        )
        self.team_game1.save()
        self.team_game2.save()

    def test_logged_out(self):
        url = reverse('home')
        resp = self.client.get(url)

        self.assertEqual(resp.status_code, 200)
        pq = PyQuery(resp.content)

        self.assertIn('You\'re not logged in', pq('h3').text())
        links = [e.attr('href') for e in pq('.container a').items()]
        self.assertIn(reverse('login'), links)
        self.assertIn(reverse('signup'), links)

    def test_logged_in_with_matches(self):
        self.client.login(
            username=self.user1.username,
            password='******'
        )

        url = reverse('home')
        resp = self.client.get(url)

        self.assertEqual(resp.status_code, 200)
        pq = PyQuery(resp.content)

        # Assert links to 'Create New Game' plus ongoing games are shown
        self.assertIn('Your Active Games', pq('h3').text())
        links = [e.attr('href') for e in pq('.container a').items()]
        self.assertIn(reverse('game', args=[self.game1.id]), links)
        self.assertNotIn(reverse('game', args=[self.game2.id]), links)
        self.assertIn(reverse('create_game'), links)

    def test_logged_in_without_matches(self):
        self.client.login(
            username=self.user2.username,
            password='******'
        )

        url = reverse('home')
        resp = self.client.get(url)

        self.assertEqual(resp.status_code, 200)
        pq = PyQuery(resp.content)

        # Assert only link to 'Create New Game' is shown
        self.assertEqual(len(pq('.container a')), 1)
        links = [e.attr('href') for e in pq('.container a').items()]
        self.assertIn(reverse('create_game'), links)
Exemplo n.º 39
0
    def handle(self, *args, **options):

        startTime = datetime.now()

        total = self.req_total()
        total_pages = total[0]
        total_players = total[1]
        if total_players == Player.objects.count():
            return self.stdout.write("There is no new card")
        json_to_db = []
        for k in range(1, total_pages + 1):

            page_json = self.req_json(k)
            # json listesine at
            for i in range(int(page_json["count"])):
                #page deki oyuncu sayısı kadar for ve db ye kaydekilecek jsonlar json_to_db ye atanır.
                json_to_db.append(page_json["items"][i])

            if (k > 0 and k % 50 == 0) or k == total_pages:
                for turn in range(len(json_to_db)):

                    player_prop = json_to_db[turn]

                    rol = player_prop["position"]
                    if rol == "RW" or rol == "LW" or rol == "ST" or rol == "CF":
                        new = "Attacker"
                    elif rol == "CM" or rol == "CDM" or rol == "RM" or rol == "LM" or rol == "CAM":
                        new = "Midfielder"
                    elif rol == "CB" or rol == "RB" or rol == "LB" or rol == "RWB" or rol == "LWB":
                        new = "Defender"
                    elif rol == "GK":
                        new = "Goalkeeper"
                    dude = Player(
                        commonName=player_prop["commonName"],
                        firstName=player_prop["firstName"],
                        lastName=player_prop["lastName"],
                        query_helper=player_prop["commonName"] +
                        player_prop["firstName"] + player_prop["lastName"],
                        position=player_prop["position"],
                        playStyle=player_prop["playStyle"],
                        playStyleId=player_prop["playStyleId"],
                        height=player_prop["height"],
                        weight=player_prop["weight"],
                        birthdate=player_prop["birthdate"],
                        age=player_prop["age"],
                        acceleration=player_prop["acceleration"],
                        aggression=player_prop["aggression"],
                        agility=player_prop["agility"],
                        balance=player_prop["balance"],
                        ballcontrol=player_prop["ballcontrol"],
                        foot=player_prop["foot"],
                        skillMoves=player_prop["skillMoves"],
                        crossing=player_prop["crossing"],
                        curve=player_prop["curve"],
                        dribbling=player_prop["dribbling"],
                        finishing=player_prop["finishing"],
                        freekickaccuracy=player_prop["freekickaccuracy"],
                        gkdiving=player_prop["gkdiving"],
                        gkhandling=player_prop["gkhandling"],
                        gkkicking=player_prop["gkkicking"],
                        gkpositioning=player_prop["gkpositioning"],
                        gkreflexes=player_prop["gkreflexes"],
                        headingaccuracy=player_prop["headingaccuracy"],
                        interceptions=player_prop["interceptions"],
                        jumping=player_prop["jumping"],
                        longpassing=player_prop["longpassing"],
                        longshots=player_prop["longshots"],
                        marking=player_prop["marking"],
                        penalties=player_prop["penalties"],
                        positioning=player_prop["positioning"],
                        potential=player_prop["potential"],
                        reactions=player_prop["reactions"],
                        shortpassing=player_prop["shortpassing"],
                        shotpower=player_prop["shotpower"],
                        slidingtackle=player_prop["slidingtackle"],
                        sprintspeed=player_prop["sprintspeed"],
                        standingtackle=player_prop["standingtackle"],
                        stamina=player_prop["stamina"],
                        strength=player_prop["strength"],
                        vision=player_prop["vision"],
                        volleys=player_prop["volleys"],
                        weakFoot=player_prop["weakFoot"],
                        atkWorkRate=player_prop["atkWorkRate"],
                        defWorkRate=player_prop["defWorkRate"],
                        playerType=player_prop["playerType"],
                        name=player_prop["name"],
                        quality=player_prop["quality"],
                        color=player_prop["color"],
                        isGK=player_prop["isGK"],
                        positionFull=player_prop["positionFull"],
                        isSpecialType=player_prop["isSpecialType"],
                        contracts=player_prop["contracts"],
                        fitness=player_prop["fitness"],
                        rawAttributeChemistryBonus=player_prop[
                            "rawAttributeChemistryBonus"],
                        isLoan=player_prop["isLoan"],
                        squadPosition=player_prop["squadPosition"],
                        itemType=player_prop["itemType"],
                        discardValue=player_prop["discardValue"],
                        card_id=player_prop["id"],
                        modelName=player_prop["modelName"],
                        baseId=player_prop["baseId"],
                        rating=player_prop["rating"],
                        role=new)
                    dude.save()
                json_to_db = []

            if k % 25 == 0:
                self.stdout.write(str(datetime.now() - startTime))

        self.stdout.write(str(datetime.now() - startTime))
Exemplo n.º 40
0
def create(request, team_id):
    if request.method == "POST":
        name = request.POST.get('name')
        number = request.POST.get('number')
        position = request.POST.get('position')
        height = request.POST.get('height', '')
        weight = request.POST.get('weight', '')
        birthday = request.POST.get('birthday', '')
        email = request.POST.get('email', '')
        #isAdmin = request.POST.get('isAdmin')

        # Team instance
        try:
            team = Team.objects.get(id=team_id)
        except:
            team = None

        if team:
            try:
                image = request.FILES['image']
                player = Player(team=team, name=name, number=number, 
                                figure=image, position=position, birthday=birthday,
                                email=email, height=height, weight=weight)
            except: # Without image.
                player = Player(team=team, name=name, number=number, 
                                position=position, birthday=birthday, email=email, 
                                height=height, weight=weight)

        #if isAdmin == "true":
        #    player.isAdmin = True
        #else:
        #    player.isAdmin = False

            try:
                player.save()
            except:
                # TODO: Log system.
                # 2016.05.24 Message framework.
                messages.error(request, _('UNABLED_TO_CREATE_PLAYER'))
                return redirect('player_index', team_id=team_id)
 
        #player.team.add(team)

        # Init time.
        time = datetime.datetime.strptime(u'00:00', '%M:%S')

        try:
            # Init PlayerState object.
            PlayerState(player=player, game_played=0, game_started=0, time=time,
                        two_points_attempt=0, two_points_made=0,
                        three_points_attempt=0, three_points_made=0,
                        FTA=0, FTM=0, OREB=0, DREB=0, REB=0, AST=0, STL=0, BLK=0,
                        TO=0, PF=0, PTS=0).save()
        except:
            # TODO: Log system.

            # Restore player.
            Player.objects.get(team=team, name=name).delete()

            # 2016.05.24 Message framework.
            messages.error(request, _('UNABLED_TO_CREATE_PLAYER'))
            return redirect('player_index', team_id=team_id)

        # Send invitation mail.
        if email:
            try:
                # 2016.05.17 Version 1 email.
                subject = "Welcome to the DataHoops - Sign Up and Join the Team"
                from_email = settings.DEFAULT_FROM_EMAIL
                to = email
                html_content = "<h2>Welcome to the DataHoops!</h2><p>Hi "+smart_unicode(name)+",</p><p>You can use DataHoops to track your stats and improve your game!</p><p>To get started, <a href='http://www.datahoops.com/teams/myteams/"+str(team_id)+"/players/"+str(player.id)+"/invitation/'>click to log in/register</a> now.</p>"
                msg = EmailMessage(subject, html_content, from_email, [to])
                msg.content_subtype = "html"
                msg.send()
            except:
                # TODO: Log system.
                pass

        # 2016.05.24 Message framework.
        messages.success(request, _('PLAYER_CREATED'))

        return HttpResponseRedirect('/teams/myteams/%s/players/' % team_id)
    else:
        # 2016.04.14 General team information.
        # Query team instance.
        team = Team.objects.get(id=team_id)

        # Query team states instance.
        stats = TeamState.objects.get(team=team)
        
        # FG measurement.
        if stats.two_points_attempt or stats.three_points_attempt:
            FG = (stats.two_points_made + stats.three_points_made) / (stats.two_points_attempt + stats.three_points_attempt) * 100
        else:
            FG = 0.0

        if stats.game:
            # PPG measurement.
            PPG = stats.PTS / stats.game
            # AST/Game measurement.
            AST = stats.AST / stats.game
            # REB/Game measurement.
            REB = stats.REB / stats.game
        else:
            PPG = AST = REB = 0.0

        return render(request, 'players/create.html', locals())
Exemplo n.º 41
0
    def handle(self, *args, **options):
        all_players = PlayerList().info()

        for api_player in all_players:
            info_msg = "'{} ({})'".format(
                api_player['DISPLAY_FIRST_LAST'],
                api_player['PERSON_ID']
            )

            # Get the player, or create him if doesn't exist
            qs = Player.objects.filter(PERSON_ID=api_player['PERSON_ID'])
            if qs.exists():
                if options['skip']:
                    self.stdout.write(
                        self.style.SUCCESS("Skipping " + info_msg)
                    )
                    continue

                player = qs[0]
                self.stdout.write(self.style.SUCCESS("Updating " + info_msg))
            else:
                player = Player()
                self.stdout.write(self.style.SUCCESS("Adding " + info_msg))

            try:
                name = api_player['DISPLAY_LAST_COMMA_FIRST']
                last, first = name.replace(' ', '').split(',', 1)
            except ValueError:
                # Only one name
                first = api_player['DISPLAY_LAST_COMMA_FIRST']
                last = ''
            player.first_name = first
            player.last_name = last
            player.PERSON_ID = api_player['PERSON_ID']
            player.PLAYERCODE = api_player['PLAYERCODE']

            # Add player photo only on creation
            if not player.photo:
                base_url = ('http://i.cdn.turner.com/nba/nba/.element/'
                            'img/2.0/sect/statscube/players/large/')
                filename = api_player['PLAYERCODE'] + '.png'
                photo_url = base_url + filename

                # Try three times
                session = requests.Session()
                adapter = requests.adapters.HTTPAdapter(max_retries=3)
                session.mount('http://', adapter)
                response = session.get(photo_url)

                if response:
                    image_content = ContentFile(response.content)
                    player.photo.save(filename, image_content)

            player.save()

            # Player current season
            try:
                player_stats = PlayerGeneralSplits(
                    api_player['PERSON_ID']
                ).overall()[0]
            except IndexError:
                self.stdout.write(self.style.ERROR("No stats for " + info_msg))
                continue

            season, __ = Season.objects.get_or_create(
                abbr=player_stats['GROUP_VALUE'],
            )

            qs = PlayerSeason.objects.filter(
                player=player, season=season,
            )
            if qs.exists():
                player_season = qs[0]
            else:
                player_season = PlayerSeason()

            # Team
            if api_player['TEAM_ID'] and api_player['TEAM_CODE']:
                team = Team.objects.get(TEAM_ID=api_player['TEAM_ID'])
            else:
                # Player played this season, but was cut/moved to D-League
                team = None
            player_season.team = team

            player_season.player = player
            player_season.season = season

            player_season.ROSTERSTATUS = api_player['ROSTERSTATUS']
            player_season.GAMES_PLAYED_FLAG = api_player['GAMES_PLAYED_FLAG']

            player_season.pts = player_stats['PTS']
            player_season.reb = player_stats['REB']
            player_season.ast = player_stats['AST']
            player_season.stl = player_stats['STL']
            player_season.blk = player_stats['BLK']
            player_season.fg_pct = player_stats['FG_PCT']
            player_season.fg3_pct = player_stats['FG3_PCT']
            player_season.ft_pct = player_stats['FT_PCT']

            player_season.save()

        self.stdout.write(self.style.SUCCESS("Successfully updated players"))
Exemplo n.º 42
0
 def test_player_creation(self):
     player = Player(name='Foo')
     player.save()
     self.assertEqual(player.name, 'Foo')
Exemplo n.º 43
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)
Exemplo n.º 44
0
#!/usr/bin/env python
import os, sys
import csv

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "allstars.settings")

from players.models import Player, AllStarTeamMember

if __name__ == "__main__":
    player_data = csv.DictReader(open('lahman58-csv/Master.csv', 'r'))
    for player in player_data:
        
        p = Player()
        p.name = "{0} {1}".format(player['nameFirst'], player['nameLast'])
        p.player_id = player['playerID']
        if player['weight']:
            p.weight = int(player['weight'])
        if player['birthYear']:
            p.birth_year = int(player['birthYear'])
        p.save()

    team_data = csv.DictReader(open('lahman58-csv/Allstar.csv', 'r'))
    for team_player in team_data:
        player = Player.objects.get(player_id=team_player['playerID'])
        AllStarTeamMember.objects.create(
                player = player,
                year = int(team_player['yearID']),
                league = team_player['lgID'],
                )
Exemplo n.º 45
0
class LoginViewTestCase(TestCase):

    def setUp(self):
        self.active_user = User.objects.create_user(
            'active_user', '', 'password'
        )
        self.inactive_user = User.objects.create_user(
            'inactive_user', '', 'password'
        )

        self.inactive_user.is_active = False
        self.inactive_user.save()

        self.player1 = Player(user=self.active_user)
        self.player2 = Player(user=self.inactive_user)
        self.player1.save()
        self.player2.save()

    def test_get(self):
        url = reverse('login')
        resp = self.client.get(url)

        self.assertEqual(resp.status_code, 200)
        pq = PyQuery(resp.content)

        self.assertEqual(len(pq('input#username')), 1)
        self.assertEqual(len(pq('input#password')), 1)

    def test_post(self):
        url = reverse('login')
        resp = self.client.post(url, {
            'username': '******',
            'password': '******'
        })

        self.assertIn('_auth_user_id', self.client.session)
        self.assertEqual(
            int(self.client.session['_auth_user_id']),
            self.active_user.id
        )
        self.assertRedirects(resp, reverse('home'))

    def test_post_inactive_user(self):
        url = reverse('login')
        resp = self.client.post(url, {
            'username': '******',
            'password': '******'
        })

        self.assertEqual(resp.status_code, 200)

        pq = PyQuery(resp.content)
        self.assertIn(
            'Your account is disabled',
            pq('.alert-danger').text()
        )

    def test_post_bad_password(self):
        url = reverse('login')
        resp = self.client.post(url, {
            'username': '******',
            'password': '******'
        })

        self.assertEqual(resp.status_code, 200)

        pq = PyQuery(resp.content)
        self.assertIn(
            'Your username and/or password is incorrect',
            pq('.alert-danger').text()
        )