Пример #1
0
    def player_save(self, team, team_object):

        self.stdout.write('Get team {team_name}'.format(team_name=team.full_name))
        for player_object in team_object['players']:
            try:
                player = team.players.get(
                    first_name=player_object['first_name'],
                    last_name=player_object['last_name'])
                self.stdout.write('Update player {first_name} {last_name}'.format(
                    first_name=player_object['first_name'],
                    last_name=player_object['last_name']))
            except Player.DoesNotExist:
                self.stdout.write('Create player {first_name} {last_name}'.format(
                    first_name=player_object['first_name'],
                    last_name=player_object['last_name']))
                player = Player()

            for attr, value in player_object.items():
                if attr == 'birthplace':
                    birth_places = value.split(', ')
                    player.birthplace_city = birth_places[0]
                    player.birthplace_country = birth_places[1]
                    player.is_USA = len(birth_places) == 3
                else:
                    setattr(player, attr, value)
            player.save()
            team.players.add(player)
Пример #2
0
class TestPlayer(TestCase):
    def setUp(self):
        self.type = Type(name=Type.NORMAL)
        self.type.save()

        self.move = Move(name='Tackle', type=self.type, base_power=50)
        self.move.save()

        self.pokemon = Pokemon(name="Charmander", type1=self.type)
        self.pokemon.save()

        self.player_pokemon = PlayerPokemon(pokemon=self.pokemon, move1=self.move)
        self.player_pokemon.save()

        self.red = Player(username='******') # Will need to be changed to use a real Team
        self.red.save()

        self.player_pokemon.player = self.red
        self.player_pokemon.pokemon = self.pokemon
        self.player_pokemon.save()

    def test_get_and_update_usable_pokemon(self):
        self.red.check_usable_pokemon()

        self.assertEqual(self.red.usable_pokemon, 1)

    def test_get_and_update_usable_pokemon_when_one_faints(self):
        self.assertEqual(self.player_pokemon.player.usable_pokemon, 1)

        self.player_pokemon.take_damage(self.player_pokemon.hp)
        self.player_pokemon.player.check_usable_pokemon()

        self.assertEqual(self.player_pokemon.player.usable_pokemon, 0)
Пример #3
0
def _register(request):
    """
    Register a new user & player, or render the registration form

    """

    form = RegistrationForm(request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        user = User.objects.create_user(
            username=username,
            password=form.cleaned_data['password1'],
        )

        # Create a new player object for user
        player = Player()
        player.user = user
        player.save()

        # render the form (on login tab) with username filled in, and display a success message
        loginform = LoginForm({'username': username})
        return render(request, 'login_and_register.html', {
            'registerform': form,
            'loginform': loginform,
            'tab': 'login',
            'success': True
            })

    loginform = LoginForm()
    return render(request, 'login_and_register.html', {
        'registerform': form,
        'loginform': loginform,
        'tab': 'register'
        })
Пример #4
0
def index(request):
    if request.method == 'POST':
        if 'delete' in request.POST:
            player_list = Player.objects.order_by('-last_name')
            delete_player = player_list.get(pk=request.POST['delete-player'])
            delete_player.delete()
            player_list = Player.objects.order_by('-last_name')
            new_form = AddPlayerForm()
            context = {'player_list': player_list, 'form': new_form}
            render(request, 'player/index.html', context)
        else:
            form = AddPlayerForm(request.POST)
            if form.is_valid():
                new_player = Player()
                new_player.first_name = form.cleaned_data['first_name']
                new_player.last_name = form.cleaned_data['last_name']
                new_player.number = form.cleaned_data['number']
                new_player.save()
                new_form = AddPlayerForm()
                player_list = Player.objects.order_by('-last_name')
                context = {'player_list': player_list, 'form': new_form}
                render(request, 'player/index.html', context)
    form = AddPlayerForm()
    player_list = Player.objects.order_by('-last_name')
    context = {'player_list': player_list, 'form': form}
    return render(request, 'player/index.html', context)
Пример #5
0
def player_scorecard(data):

    try:
        if data['espn_object_id'] != None:
            data['espn_object_id'] = int(data['espn_object_id'])
        else:
            pass
    except:
        data['espn_object_id'] = None

    if data['espn_object_id'] != None and len(
            Player.objects.filter(espn_object_id=data['espn_object_id'])) == 1:
        return Player.objects.get(espn_object_id=data['espn_object_id'])
    elif len(Player.objects.filter(fullname=data['name'])) == 1:
        return Player.objects.get(fullname=data['name'])
    elif len(Player.objects.filter(card_name=data['name'])) == 1:
        return Player.objects.get(card_name=data['name'])
    elif len(Player.objects.filter(nickname=data['name'])) == 1:
        return Player.objects.get(nickname=data['name'])
    elif len(Player.objects.filter(name=data['name'])) == 1:
        return Player.objects.get(name=data['name'])
    else:
        p = Player(**data)
        p.save()
        return p
Пример #6
0
Файл: views.py Проект: iizs/aor
def _create_player(user_id, name=None, email=None, auth_provider=Player.IIZS_NET):
    p = Player()
    p.user_id=user_id
    p.name=name
    p.email=email
    p.auth_provider=auth_provider
    p.save()
    return p
Пример #7
0
 def addPlayers(self):
     from player.models import Player
     for i in range(self.numplayers):
         p = Player()
         p.game = self
         p.race = Race.objects.get(name='race_%d' % i)
         p.name = "Player %d" % i
         p.save()
     self.selectHome()
Пример #8
0
    def create_player(cls, ep):
        username = ep.get('username', '')
        username += '_ai_' + User.objects.make_random_password(length=8)
        newu = User(username=username)
        newu.save()
        p = Player(user=newu, ptype=ep['ptype'])
        p.save()

        return p
Пример #9
0
 def test_player_set(self):
     test = Player(id=10,
                   name="player3",
                   description="player3 description",
                   mac_address="00:00:00:q1:ss:88",
                   status=False)
     test.save()
     self.assertEqual(test.name, "player3")
     self.assertEqual(test.mac_address, "00:00:00:q1:ss:88")
Пример #10
0
def new(request):
    if request.method == 'GET':
        return render(request, 'player/new.html',{})
    elif request.method == 'POST':
        if request.POST['name'] == '':
            return render(request,'player/new.html',{'error':'You must have a username'})
        else:
            player = Player(name = request.POST['name'])
            player.save()
            return HttpResponseRedirect('/player/%s/' % player.id)
Пример #11
0
def new(request):
    if request.method == 'GET':
        return render(request, 'player/new.html',{})
    elif request.method == 'POST':
        if request.POST['name'] == '':
            return render(request,'player/new.html',{'error':'You must have a username'})
        else:
            player = Player(name = request.POST['name'])
            player.save()
            return HttpResponseRedirect('/player/%s/' % player.id)
Пример #12
0
def register_view(request):
    form = RegistrationForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        name_ = form.cleaned_data['name']
        username_ = form.cleaned_data['username']
        email_ = form.cleaned_data['email']
        password_ = form.cleaned_data['password']
        re_password_ = form.cleaned_data['re_password']
        user_type_ = form.cleaned_data['user_type']
        user = User.objects.create_user(first_name=name_,
                                        username=username_,
                                        password=password_,
                                        email=email_)

        activation_string = user.email + SALT
        activation_key = md5(activation_string.encode("ascii")).hexdigest()

        activation_link = BASE_URL + "/accounts/activate?user="******"&activation_key=" + activation_key
        print("Activation Url - " + activation_link)

        with mail.get_connection() as connection:
            mail.EmailMessage(
                "GameStop - Activate your account",
                "To activate your account, follow the link - " +
                activation_link,
                "*****@*****.**",
                [email_],
                connection=connection,
            ).send()

        if (user_type_ == '1'):
            dev_ = Developer(user=user)
            dev_.registered = False
            dev_.activation_key = activation_key
            dev_.save()
        else:
            player_ = Player(user=user)
            player_.registered = False
            player_.activation_key = activation_key
            player_.save()
        #login(request, user)
        return HttpResponseRedirect("/home")

    context = {'form': form}
    return render(request, 'accounts/register.html', context)
Пример #13
0
    def test_meeting_between_players_without_challenge(self):
        user_1 = User.objects.create_user('user_1', '*****@*****.**',
                                          'qweqweqwe')
        user_2 = User.objects.create_user('user_2', '*****@*****.**',
                                          'qweqweqwe')
        pos = GEOSGeometry('POINT(37.00000 -5.00000)')
        player_1 = Player(user=user_1, pos=pos)
        player_1.save()
        player_2 = Player(user=user_2, pos=pos)
        player_2.save()

        response = self.c.authenticate(self.get_username(player_1.pk),
                                       self.pwd)
        self.assertEqual(response.status_code, 200)
        # step 1
        response = self.c.post('/api/player/meeting/{0}/'.format(player_2.pk),
                               {})
        self.assertEqual(response.status_code, 201)

        response = self.c.authenticate(self.get_username(player_2.pk),
                                       self.pwd)
        self.assertEqual(response.status_code, 200)
        # step 2
        response = self.c.post('/api/player/meeting/{0}/'.format(player_1.pk),
                               {})
        self.assertEqual(response.status_code, 200)

        secret = Meeting.objects.get(player1=player_1, player2=player_2).secret
        response = self.c.authenticate(self.get_username(player_1.pk),
                                       self.pwd)
        self.assertEqual(response.status_code, 200)
        # step 3
        response = self.c.post(
            '/api/player/meeting/{0}/captured/{1}/'.format(
                player_2.pk, secret), {})
        self.assertEqual(response.status_code, 200)

        response = self.c.authenticate(self.get_username(player_2.pk),
                                       self.pwd)
        self.assertEqual(response.status_code, 200)
        # step 4
        response = self.c.get(
            '/api/player/meeting/{0}/qrclue/'.format(player_1.pk), {})
        self.assertEqual(response.status_code, 200)
Пример #14
0
def detail(request, team_id):
    team = get_object_or_404(Team, pk=team_id)
    if request.method == 'POST':
        if 'add-available' in request.POST:
            add_player = Player.objects.get(pk=request.POST['add-player'])
            team.players.add(add_player)
            new_form = AddPlayerForm()
            team_players = team.players.all()
            all_players = Player.objects.all()
            available_players = []
            for player in all_players:
                if player not in team_players:
                    available_players.append(player)
            context = {'team': team, 'form': new_form, 'available_players': available_players }
            return render(request, 'team/detail.html', context)
        else:
            form = AddPlayerForm(request.POST)
            if form.is_valid():
                new_player = Player()
                new_player.first_name = form.cleaned_data['first_name']
                new_player.last_name = form.cleaned_data['last_name']
                new_player.number = form.cleaned_data['number']
                new_player.save()
                team.players.add(new_player)
                new_form = AddPlayerForm()
                team_players = team.players.all()
                all_players = Player.objects.all()
                available_players = []
                for player in all_players:
                    if player not in team_players:
                        available_players.append(player)
                context = {'team': team, 'form': new_form, 'available_players': available_players }
                return render(request, 'team/detail.html', context)
    else:
        form = AddPlayerForm()
    team_players = team.players.all()
    all_players = Player.objects.all()
    available_players = []
    for player in all_players:
        if player not in team_players:
            available_players.append(player)
    context = {'team': team, 'form': form, 'available_players': available_players }
    return render(request, 'team/detail.html', context)
Пример #15
0
def _dashboard(request):
    """
    Return game UI if player has existing game,
    otherwise create a new game then return game UI
    """

    # Get the player for this user, if they don't have one (maybe a superuser?) create one for them
    try:
        player = Player.objects.get(pk=request.user)
    except Player.DoesNotExist:
        player = Player()
        player.user = request.user
        player.save()

    # Check for an existing game for the player
    try:
        gamestate = player.gamestate
        return _terminal(request, gamestate)
    except GameState.DoesNotExist:
        return _create_game(request, player)
Пример #16
0
    def register(request):
        login = request.POST.get("user", None)
        pas = request.POST.get("pass", None)
        city = request.POST.get("city", None)
        school = request.POST.get("school", None)

        if not login:
            return JsonResponse({"status": "user_invalid"})

        if not pas:
            return JsonResponse({"status": "password_invalid"})

        player = Model.objects.filter(login=login)
        if player:
            return JsonResponse({"status": "exists"})

        player = Model()
        player.login = login
        player.password = pas
        player.status = PLAYER_STATUS_OFFLINE

        player.save()

        return JsonResponse({"status": "ok", "result": {}, "payload": {"player": player.json()}})
class GameTest(APITestCase):
    def setUp(self):
        # User
        self.username = "******"
        self.email = "*****@*****.**"
        self.password = "******"
        self.user = User._default_manager.create_user(
            username=self.username,
            email=self.email,
        )
        self.user.set_password(self.password)
        self.user.save()

        # Board
        self.board_name = 'boardcito'
        self.board_owner = self.user
        self.board = Board(
            name=self.board_name,
            owner=self.board_owner
        )
        self.board.save()

        # Room
        self.room = Room(
            name='roomcito',
            board=self.board,
            game_has_started=True,
            owner=self.user,
        )
        self.room.save()

        # Game
        self.game = Game(room=self.room)
        self.game.save()

        # Player
        self.player = Player(
            user=self.user,
            game=self.game,
            colour='colorcito'
        )
        self.player.save()
        self.client.force_authenticate(self.user)

    def test_game_bad_request(self):
        data = {
            'type': 'build_settlement',
            'payload': {
                'index': 0,
                'level': 0
            }
        }

        needed_resources = [('brick', 1), ('lumber', 1),
                            ('grain', 1), ('wool', 1)]

        self.player.increase_resources(needed_resources)

        response = self.client.post(
            reverse('player-action', args=[self.game.id+10000]),
            data,
            format='json'
        )
        self.assertEqual(response.status_code, 404)

    def test_game_bad_action(self):
        data = {
            'type': 'bad_action',
            'payload': {
                'index': 0,
                'level': 0
            }
        }

        needed_resources = [('brick', 1), ('lumber', 1),
                            ('grain', 1), ('wool', 1)]

        self.player.increase_resources(needed_resources)

        response = self.client.post(
            reverse('player-action', args=[self.game.id]),
            data,
            format='json'
        )
        self.assertEqual(response.status_code, 404)
        self.assertEqual(response.data, "Wrong action.")

    def test_settlement_ok(self):
        data = {
            'type': 'build_settlement',
            'payload': {
                'index': 0,
                'level': 0
            }
        }

        needed_resources = [('brick', 1), ('lumber', 1),
                            ('grain', 1), ('wool', 1)]

        self.player.increase_resources(needed_resources)

        response = self.client.post(
            reverse('player-action', args=[self.game.id]),
            data,
            format='json'
        )
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_settlement_few_resources(self):
        data = {
            'type': 'build_settlement',
            'payload': {
                'index': 0,
                'level': 0
            }
        }

        needed_resources = [('lumber', 1), ('grain', 1), ('wool', 1)]

        self.player.increase_resources(needed_resources)

        response = self.client.post(
            reverse('player-action', args=[self.game.id]),
            data,
            format='json'
        )
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(response.data, "Not enough resources")

    def test_settlement_out_of_bounds(self):
        data = {
            'type': 'build_settlement',
            'payload': {
                'index': 10,
                'level': 10
            }
        }

        response = self.client.post(
            reverse('player-action', args=[self.game.id]),
            data,
            format='json'
        )

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_settlement_game_not_exits(self):
        data = {
            'type': 'build_settlement',
            'payload': {
                'index': 0,
                'level': 0
            }
        }

        response = self.client.post(
            reverse('player-action', args=[30]),
            data,
            format='json'
        )

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_road_ok(self):

        resources = [('brick', 1), ('lumber', 1)]
        self.player.increase_resources(resources)
        data = {
            'type': 'build_road',
            'payload': [
                {
                    'level': 0,
                    'index': 0
                },
                {
                    'level': 0,
                    'index': 1,
                }

            ]
        }

        response = self.client.post(
            reverse('player-action', args=[self.game.id]),
            data,
            format='json'
        )
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_road_oob(self):
        data = {
            'type': 'build_road',
            'payload': [
                {
                    'level': 10,
                    'index': 20
                },
                {
                    'level': 42,
                    'index': 69,
                }

            ]
        }

        response = self.client.post(
            reverse('player-action', args=[self.game.id]),
            data,
            format='json'
        )

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_road_non_adjacent(self):
        data = {
            'type': 'build_road',
            'payload': [
                {
                    'level': 0,
                    'index': 0
                },
                {
                    'level': 2,
                    'index': 0,
                }

            ]
        }

        response = self.client.post(
            reverse('player-action', args=[self.game.id]),
            data,
            format='json'
        )

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_road_repeated_arguments(self):
        data = {
            'type': 'build_road',
            'payload': [
                {
                    'level': 0,
                    'index': 0
                },
                {
                    'level': 0,
                    'index': 0,
                }

            ]
        }

        response = self.client.post(
            reverse('player-action', args=[self.game.id]),
            data,
            format='json'
        )

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_road_insufficient_arguments(self):
        data = {
            'type': 'build_road',
            'payload': [
                {
                    'level': 0,
                    'index': 0
                }

            ]
        }

        response = self.client.post(
            reverse('player-action', args=[self.game.id]),
            data,
            format='json'
        )

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_road_too_many_arguments(self):
        data = {
            'type': 'build_road',
            'payload': [
                {
                    'level': 0,
                    'index': 0
                },
                {
                    'level': 0,
                    'index': 1,
                },
                {
                    'level': 0,
                    'index': 2
                },

            ]
        }

        response = self.client.post(
            reverse('player-action', args=[self.game.id]),
            data,
            format='json'
        )

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_road_used_edge(self):
        data = {
            'type': 'build_road',
            'payload': [
                {
                    'level': 0,
                    'index': 0
                },
                {
                    'level': 0,
                    'index': 1,
                }

            ]
        }
        response = self.client.post(
            reverse('player-action', args=[self.game.id]),
            data,
            format='json'
        )

        # Second road SHOULD FAIL

        response = self.client.post(
            reverse('player-action', args=[self.game.id]),
            data,
            format='json'
        )

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_buy_card(self):

        resources = [('wool', 1), ('ore', 1), ('grain', 1)]
        self.player.increase_resources(resources)
        data = {
            'type': 'buy_card',
            'payload': None
        }
        response = self.client.post(
            reverse('player-action', args=[self.game.id]),
            data,
            format='json'
        )

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_buy_card_no_resources(self):
        data = {
            'type': 'buy_card',
            'payload': None
        }
        response = self.client.post(
            reverse('player-action', args=[self.game.id]),
            data,
            format='json'
        )

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_bank_trade_ok(self):
        data = {
            'type': 'bank_trade',
            'payload': {
                'give': 'wool',
                'receive': 'grain'
            }
        }
        give = self.player.get_resource('wool')
        give.amount = 4
        give.save()

        response = self.client.post(
            reverse('player-action', args=[self.game.id]),
            data,
            format='json'
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, "Trade done.")

    def test_bank_trade_equal_receive_and_give(self):
        data = {
            'type': 'bank_trade',
            'payload': {
                'give': 'wool',
                'receive': 'wool'
            }
        }
        response = self.client.post(
            reverse('player-action', args=[self.game.id]),
            data,
            format='json'
        )

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(response.data, "Resources must be different.")

    def test_bank_trade_bad_receive(self):
        data = {
            'type': 'bank_trade',
            'payload': {
                'give': 'wool',
                'receive': 'badreceive'
            }
        }
        response = self.client.post(
            reverse('player-action', args=[self.game.id]),
            data,
            format='json'
        )

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(response.data, "Resource not exists.")

    def test_bank_trade_few_resources(self):
        data = {
            'type': 'bank_trade',
            'payload': {
                'give': 'wool',
                'receive': 'grain'
            }
        }
        give = self.player.get_resource('wool')
        give.amount = 3
        give.save()

        response = self.client.post(
            reverse('player-action', args=[self.game.id]),
            data,
            format='json'
        )
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(response.data, "Insufficient resources.")
Пример #18
0
class TestRound(TestCase):
    def test_fight(self):
        self.do_setup(red_attack=3, red_speed=10, blue_attack=3, blue_speed=7)

        round1 = Round(battle=self.battle, red=self.red, blue=self.blue)
        round1.save()

        red_team = PlayerPokemon.objects.filter(player=round1.red)
        blue_team = PlayerPokemon.objects.filter(player=round1.blue)

        current_red_pokemon = None
        current_blue_pokemon = None

        for red_pokemon, blue_pokemon in izip(red_team, blue_team):
            if red_pokemon.lead:
                current_red_pokemon = red_pokemon

            if blue_pokemon.lead:
                current_blue_pokemon = blue_pokemon

            if current_red_pokemon and current_blue_pokemon:
                break

        self.assertEqual(self.battle.winner, None)
        self.assertEqual(current_red_pokemon.hp, 18)
        self.assertEqual(current_blue_pokemon.hp, 19)

        round1.red_selected_move = current_red_pokemon.move1
        round1.blue_selected_move = current_blue_pokemon.move1
        round1.save()

        round2 = round1.advance_round()
        round2.save()

        """
        red_team = PlayerPokemon.objects.filter(player=round1.red)
        blue_team = PlayerPokemon.objects.filter(player=round1.blue)

        for red_pokemon, blue_pokemon in izip(red_team, blue_team):
            if red_pokemon.lead:
                current_red_pokemon = red_pokemon
            if blue_pokemon.lead:
                current_blue_pokemon = blue_pokemon

        self.assertEqual(self.battle.winner, None)
        self.assertLess(current_red_pokemon.hp, 18)
        self.assertLess(current_blue_pokemon.hp, 18)

        round3 = round2.advance_round()
        round3.save()

        red_team = PlayerPokemon.objects.filter(player=round1.red)
        blue_team = PlayerPokemon.objects.filter(player=round1.blue)

        for red_pokemon, blue_pokemon in izip(red_team, blue_team):
            if red_pokemon.lead:
                current_red_pokemon = red_pokemon
            if blue_pokemon.lead:
                current_blue_pokemon = blue_pokemon

        self.assertEqual(self.battle.winner, None)
        self.assertEqual(current_red_pokemon.hp, 4)
        self.assertEqual(current_blue_pokemon.hp, 4)

        round4 = round3.advance_round()
        round4.save()

        red_team = PlayerPokemon.objects.filter(player=round4.red)
        blue_team = PlayerPokemon.objects.filter(player=round4.blue)

        for red_pokemon, blue_pokemon in izip(red_team, blue_team):
            if red_pokemon.lead:
                current_red_pokemon = red_pokemon
            if blue_pokemon.lead:
                current_blue_pokemon = blue_pokemon

        self.assertEqual(self.battle.winner, None)
        self.assertEqual(current_red_pokemon.hp, 1)
        self.assertEqual(current_blue_pokemon.hp, 1)

        round5 = round4.advance_round()

        red_team = PlayerPokemon.objects.filter(player=round4.red)
        blue_team = PlayerPokemon.objects.filter(player=round4.blue)

        for red_pokemon, blue_pokemon in izip(red_team, blue_team):
            if red_pokemon.lead:
                current_red_pokemon = red_pokemon
            if blue_pokemon.lead:
                current_blue_pokemon = blue_pokemon

        self.assertEqual(self.battle.winner, self.red)
        self.assertEqual(current_red_pokemon.hp, 1)
        self.assertEqual(current_blue_pokemon.hp, 0)
        """

    def do_setup(self, red_attack, red_speed, blue_attack, blue_speed):
        self.create_players()
        self.create_pokemon(blue_attack, blue_speed, red_attack, red_speed)

        self.battle = Battle(red=self.red, blue=self.blue)
        self.battle.save()

    def create_players(self):
        self.red = Player(username='******')
        self.red.save()
        self.blue = Player(username='******')
        self.blue.save()

    def create_pokemon(self, blue_attack, blue_speed, red_attack, red_speed):
        self.move_type = Type(name=Type.NORMAL)
        self.move_type.save()

        self.red_type = Type(name=Type.FIRE)
        self.red_type.save()

        self.blue_type = Type(name=Type.WATER)
        self.blue_type.save()

        self.move = Move(name='Tackle', type=self.move_type, base_power=50)
        self.move.save()

        self.red_pokemon = Pokemon(type1=self.red_type)
        self.red_pokemon.save()

        self.blue_pokemon = Pokemon(name='Squirtle', type1=self.blue_type,
                                    base_hp=44, base_attack=48, base_defence=65, base_special=50, base_speed=43)
        self.blue_pokemon.save()

        self.red_playerpokemon = PlayerPokemon(pokemon=self.red_pokemon, player=self.red,
                                               lead=True, move1=self.move)
        self.red_playerpokemon.save()
        self.blue_playerpokemon = PlayerPokemon(pokemon=self.blue_pokemon, player=self.blue,
                                                lead=True, move1=self.move)
        self.blue_playerpokemon.save()
def loadnewplayer(request):
    
    file_name = request.POST['text_ob']
    full_path = os.path.join(settings.MEDIA_ROOT,settings.FILEBROWSER_DIRECTORY,file_name)


    
    player = Player(question="Do you like "+file_name+" ?",  pub_date=datetime.now(),  file_name=file_name, frame_num_start=0, frame_num_stop=0)

    player.save() 
    choice1 = Choice(player=player, choice="like", votes=0)
    choice1.save()

       
    
    print "player save"
    player_id = player.id

#    player = get_object_or_404(Player, pk=player_id)

    Interface = DjangoInterface(full_path)
 #  p = get_object_or_404(player, pk=player_id)

    mode = 1
    u_input = 0
    print_height = 30
    disp = Interface.refresh()

    frame_id_start = None
    frame_id_stop = None
    count = 0
    temp = None
    while disp != None:
        count += 1
        temp = disp
        frame_line = disp[0]
        frame_text = disp[1]
        frame_dtime = disp[2]
        frame_time = disp[3] 
        [year, month, day] = frame_dtime.split('-')
        [hour, minute, second] = frame_time.split(':')

        print "frame dtime:",frame_dtime
        print "frame time:",frame_time
        print "year:",year
        print "month:", month
        print "day:",day
        print "player?",player_id
        frame = Frame(player=player, 
                            line_num_mod=int(frame_line),
                            frame=frame_text,
                            commit_dtime=datetime(int(year), int(month), int(day), int(hour), int(minute), int(second)))

        frame.save()    

        frame_id_stop = frame.id
        if count == 1:
            frame_id_start = frame.id                

        disp = Interface.nFrameButton()
    print "frame start num",frame_id_start
    print "frame stop num",frame_id_stop 
    player.frame_num_start = frame_id_start
    player.frame_num_stop = frame_id_stop

    player.save()
    print "test", player.frame_num_start
    print "test", player.frame_num_stop
    
        #[linenum, frame.stdout.read(), date, time] 
        
#    print "request ",request.POST
#    for key in request.POST.iterkeys():
#        print "key:"+key
#    file_ob = request.FILES['file_ob']    
#    file_name = request.FILES['file_ob'].name
#    print "file name ........"+file_name
#    interface = DjangoInterface(file_ob.temporary_file_path)    
#
#    player = Player.objects.create(question="how is "+file_name+" ?",  pub_date=datetime.now(),  file_name=file_name, frame_num_start=0, frame_num_stop=1)
    return HttpResponseRedirect(reverse('player.views.results', args=(player.id,)))
def post_upload_callback(sender, **kwargs):
    for key in kwargs.iterkeys():
        print key

    if kwargs['file'].extension == ".zip":
        
        thefile = kwargs['file'] 

        # Convert file and dir into absolute paths
        print settings.MEDIA_ROOT
        print settings.FILEBROWSER_DIRECTORY
        fullpath = os.path.join(settings.MEDIA_ROOT,settings.FILEBROWSER_DIRECTORY,str(thefile))
        print "full path: "+fullpath

        dirname = os.path.dirname(fullpath)
        try:
            # Get a real Python file handle on the uploaded file
            fullpathhandle = open(fullpath, 'r') 
            zfobj = zipfile.ZipFile(fullpathhandle)

            cur_dir = os.getcwd()
            os.chdir(dirname)
            zfobj.extractall()
            os.chdir(cur_dir)

        except:
            e = sys.exc_info()[1] 
            print e

        # Now try and delete the uploaded .zip file  
        try:
            os.remove(fullpath)
        except:
            pass
      
        file_path = os.path.splitext(fullpath)[0]
        file_name = os.path.basename(file_path)
        username = kwargs['request'].META['USER']
        player = Player(username = username, question="Do you like "+file_name+" ?",  pub_date=datetime.now(),  file_name=file_name, frame_num_start=0, frame_num_stop=0)
        player.save() 
        choice1 = Choice(player=player, choice="like", votes=0)
        choice1.save()
   
        player_id = player.id
        try:
            Interface = DjangoInterface(file_path)
        except:
            e = sys.exc_info()[1] 
            print e
      
        mode = 1
        u_input = 0
        print_height = 30
        disp = Interface.refresh()
        frame_id_start = None
        frame_id_stop = None
        count = 0
        temp = None
        while disp != None:
            count += 1
            temp = disp
            frame_line = disp[0]
            frame_text = disp[1]
            frame_dtime = disp[2]
            frame_time = disp[3] 
            [year, month, day] = frame_dtime.split('-')
            [hour, minute, second] = frame_time.split(':')
            frame_text = HTML_CONV.plaintext2html(frame_text)
            print "frame dtime:",frame_dtime
            print "frame time:",frame_time
            print "year:",year
            print "month:", month
            print "day:",day
            print "player?",player_id
           
            frame = Frame(player=player, 
                            line_num_mod=int(frame_line),
                            frame=frame_text,
                            commit_dtime=datetime(int(year), int(month), int(day), int(hour), int(minute), int(second)))
   
            frame.save()    
    
            frame_id_stop = frame.id
            if count == 1:
                frame_id_start = frame.id                
    
            disp = Interface.nFrameButton()
        print "frame start num: ",frame_id_start
        print "frame stop num: ",frame_id_stop 
        player.frame_num_start = frame_id_start
        player.frame_num_stop = frame_id_stop
    
        player.save()
        player_id = player.id
        file_dirname = os.path.dirname(file_path)
        folder_path = file_dirname + "/." + file_name + "/"
        try:
            os.remove(folder_path)
        except:
            pass
        CurrentPlayer.g(player_id)
Пример #21
0
    def parse(self, excel):
        # search player nick name from title of PS excel audit file
        # working with RU files

        head = pandas.read_excel(excel, nrows=0, usecols=[0])
        player = head.columns[0]
        lang = detect(player)
        date_format = [
            r'%d.%m.%Y %I:%M %p', r'%Y/%m/%d %I:%M %p', r'%Y-%m-%d %H:%M:%S'
        ]
        if lang == 'ru':
            player = re.search(r'для (\S+)', player)
        else:
            player = re.search(r'Audit .(\S+). ', player)
        player = player.group(1)
        # search for player object
        # if there is now player - create new instance of Player model
        if 'pk' in self.kwargs.keys():
            player_obj = Player.objects.get(pk=self.kwargs['pk'])
            if player_obj.name != player:
                player_obj.name = player_obj.name + ', ' + player
                player_obj.save()
        else:
            player_obj = Player.objects.filter(name=player)
            if len(player_obj) < 1:
                player_obj = Player(name=player)
                player_obj.save()
            else:
                player_obj = player_obj[0]

        # cutin empty colums
        excel_rows = pandas.read_excel(excel, header=2, parse_dates=False)
        excel_rows.dropna(axis=1, how='all', inplace=True)
        excel.close()
        # set list of keys
        columns = excel_rows.columns.values.tolist()
        keys = [
            'date_played',
            'action',
            'action_number',
            'game',
            'curency',
            'summary',
            's_coins',
            't_money',
            'w_money',
            'cashier',
            'get_s_coins',
            't_money_cashier',
            'w_money_cashier',
        ]
        # queryset of patterns
        pattern_query = PatternBody.objects.all()
        # run loop to create PlayerAudit instences,
        # format date to date field and write action type
        for _, row in excel_rows.iterrows():
            kwargs = {}
            for key in range(len(keys)):
                kwargs[keys[key]] = row[columns[key]]
            for item in date_format:
                try:
                    kwargs['date_played'] = datetime.strptime(
                        str(kwargs[keys[0]]), item)
                except ValueError:
                    continue
            for item in pattern_query:
                if item.pattern in kwargs['action']:
                    kwargs['action_type'] = item.pattern_type.pattern_name
                    break
            audit = PlayerAudit(player=player_obj, **kwargs)
            audit.save()