Exemple #1
0
 def cleanup(mid_id):
     from db import sess
     from player.models import Player
     min_id = mid_id - 100
     Message.query().filter(Message.id < min_id).delete()
     sess.commit()
     Player.revise(mid_id)
Exemple #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)
Exemple #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'
        })
Exemple #4
0
def player_list(request,cur_page=1,template="admin/player/list.tpl"):  
    count = Player.get_count()
    if count != 0:
        page = int(cur_page)
        player_list = Player.get_list(page)
        p = Paginator(page,count,page_size=config.default_page_size)
        if player_list:
            return render_response(template,request=request,player_list=player_list,p=p)
    return render_response(template,request=None,player_list=None,p=None)
Exemple #5
0
 def create(self, validated_data):
     """
     Create and return a new "AdviserProject" instance, given the validated data.
     Also send created AdviserProject to selected players
     """
     new_project = AdviserProject.objects.create(**validated_data)
     players = self.initial_data.get("players", [])
     Player.send_project(players, new_project)
     return new_project
Exemple #6
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)
Exemple #7
0
def player_edit(request,player_id=0,template="admin/player/edit.tpl"):
    player = Player.get_by_id(player_id)
    if request.method == "GET":
        return render_response(template,player=player)
    elif request.method == "POST":
        form = PlayerForm(request.POST)
        if form.is_valid():
            level = form.cleaned_data['level']
            ep = form.cleaned_data['ep']
            sp = form.cleaned_data['sp']
            vm = form.cleaned_data['vm']
            grm = form.cleaned_data['grm']
            brm = form.cleaned_data['brm']
            try:
                player.level = level
                player.ep = ep
                player.sp = sp
                player.vm = vm
                player.grm = grm
                player.brm = brm
                player.save()
            except Exception,e:
                if config.debug:
                    print e
            else:
                return HttpResponse("<script type='text/javascript'>window.top.right.location.reload();window.top.art.dialog({id:'player_edit'}).close();</script>")
Exemple #8
0
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
Exemple #9
0
def player_search(request,template="admin/player/search.tpl"): 
    if request.method == "POST":
        player_name = request.POST.get('player_name')
        if player_name:
            player_list = Player.search_by_name(player_name)
            if player_list:
                count = len(player_list)
                p = Paginator(1,count,page_size=config.default_page_size)
                if player_list:
                    return render_response("admin/player/list.tpl",request=request,player_list=player_list,p=p)
    return render_response(template,request=None,player_list=None,p=None)
Exemple #10
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)
Exemple #11
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)
Exemple #12
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)
Exemple #13
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()
Exemple #14
0
 def put(self, request):
     """
     Handling PUT method. Send project to chosen players.
     :param request: Request to View.
     :return: Http response with status code 400 if players weren`t added. Http response with status code 201 if project is sended.
     """
     data = json.loads(request.body)
     if not data.get("players"):
         return HttpResponseBadRequest("Players are not added. Please, add some players.")
     project = AdviserProject.objects.get(id=data.get("project")["id"])
     if (not request.user.is_superuser) and (project.id_company.id != 
                                             request.user.adviseruser.id_company.id):
         return HttpResponseBadRequest("Permission denied")
     for player in data.get("players"):
         player = Player.get_by_id(player["id"])
         player.project = project
         player.save()
     return HttpResponse(status=201)
Exemple #15
0
    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()
Exemple #16
0
def create(request):
    err = None
    if request.method == 'POST':
        createForm = CreateForm(request.POST)
        if createForm.is_valid():
            clean = createForm.cleaned_data
            explayer = Player.objects.filter(name=clean['username'])
            if len(explayer):
                err = "Username is not available."
            else:
                player = Player.createFromUsername(clean['username'])
                player.save()
                return redirect(clean['destination_url'])
    else:
        createForm = CreateForm()
        
    return render( request, 'player/create.html', 
                   {    'form':createForm,
                        'error':err,
                   })
Exemple #17
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)
Exemple #18
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.")
Exemple #20
0
 def create_players(self):
     self.red = Player(username='******')
     self.red.save()
     self.blue = Player(username='******')
     self.blue.save()
Exemple #21
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)
Exemple #24
0
 def test_player_delete_by_id(self):
     Player.delete_by_id(1)
     try:
         Player.objects.get(1)
     except TypeError:
         pass
Exemple #25
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()