Esempio n. 1
0
def user_registration(request):
    """
    Provide user registration form and process completed forms.

    In typical Django fashion, this view provides and processes a single
    form.  In this case, a user registration form.

    """

    # Redirect user to game if already logged in.
    if request.user.is_authenticated():
        return HttpResponseRedirect('/tic_tac_toe/game')

    form_message = None

    # User has submitted the form.
    if request.method == 'POST':
        user_form = UserForm(request.POST)

        if user_form.is_valid(): # All validation rules pass
            new_user = User.objects.create_user(
                user_form.cleaned_data['username'],
                user_form.cleaned_data['email'],
                user_form.cleaned_data['password']
            )
            new_user.first_name = user_form.cleaned_data['first_name']
            new_user.last_name = user_form.cleaned_data['last_name']
            new_user.save()

            analytics_event = Event(
                event_type='USER_REGISTRATION_FINISH',
                event_url=request.path,
                event_model=new_user.__class__.__name__,
                event_model_id=new_user.id
            )
            analytics_event.save()

            email_message = EmailCommunication(
                '*****@*****.**',
                [new_user.email],
                '//Registration Confirmation',
                'email/player_registration.html',
                {'first_name': new_user.first_name})
            email_message.send_message()

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

            return HttpResponseRedirect('/tic_tac_toe/game')  # Redirect after POST

        else:
            form_message = (
                'There are errors in some form fields, please fix '
                'them and resubmit.')

    # User has not yet submitted the form.
    else:
        user_form = UserForm()

        analytics_event = Event(
            event_type='USER_REGISTRATION_START',
            event_url=request.path,
            event_model=User.__name__
        )
        analytics_event.save()

    template = loader.get_template('registration.html')
    context = RequestContext(
        request,
        {
            'form_message': form_message,
            'registration_form': user_form,
        }
    )
    return HttpResponse(template.render(context))
Esempio n. 2
0
def process_player_move(request):
    """
    Process Ajax requests received from client containing player moves.

    The method requires the HTTPRequest object to be an ajax request to
    function properly (it won't do anything otherwise).

    The method is a little long and could probably be broken up.  In lieu
    of that, it has numerous comments.

    """
    if request.is_ajax():

        # Get previous computer/player moves from session.
        player_moves = request.session['player_moves']
        computer_moves = request.session['computer_moves']

        # Does current move attempt to take already occupied space?
        for move_list in [player_moves, computer_moves]:
            if int(request.POST['id']) in move_list:
                json_response = {
                    'error_message': (
                        "You seem to lack a basic understanding "
                        "of the rules. You can't pick a previously "
                        "selected space.")
                }
                break

        else:
            # Add new move player to move history.
            player_moves.append(int(request.POST['id']))

            # Re-save player move list into session.
            request.session['player_moves'] = player_moves

            # Determine next computer move and add it to move history.
            game_engine = GameEngine(
                request.session['player_moves'],
                request.session['computer_moves'])

            next_computer_move, game_status = game_engine.next_computer_move()
            computer_moves.append(next_computer_move)

            # Re-save computer move list into session.
            request.session['computer_moves'] = computer_moves

            # What to do if the game is over and the computer won.
            if game_status == "Game Over (Computer Win)":
                email_message = EmailCommunication(
                    '*****@*****.**',
                    [request.user.email],
                    '//OH SNAP!',
                    'email/lost_game.html',
                    {'first_name': request.user.first_name})

                email_message.send_message()

                analytics_event = Event(
                    event_type='TIC_TAC_TOE_FINISH_LOST',
                    event_url=request.path,
                    event_model=request.user.__class__.__name__,
                    event_model_id=request.user.id)

                analytics_event.save()

            # What to do if the game is over and ended in a draw.
            elif game_status == "Draw":
                email_message = EmailCommunication(
                    '*****@*****.**',
                    [request.user.email],
                    '//YOU ALMOST WON!',
                    'email/draw_game.html',
                    {'first_name': request.user.first_name})

                email_message.send_message()

                analytics_event = Event(
                    event_type='TIC_TAC_TOE_FINISH_DRAW',
                    event_url=request.path,
                    event_model=request.user.__class__.__name__,
                    event_model_id=request.user.id)

                analytics_event.save()

            # Return most recent moves and game status to the client.
            json_response = {
                'player_move': player_moves[-1],
                'player_moves': player_moves,
                'computer_move': computer_moves[-1],
                'computer_moves': computer_moves,
                'game_status': game_status
            }

        return HttpResponse(
            json.dumps(json_response),
            mimetype="application/json")