コード例 #1
0
ファイル: views.py プロジェクト: eikonomega/Tic-Tac-Toe
def game(request):
    """
    Display blank game board, reset session variables, and record a game
    start event.

    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/usermanagement/login')

    template = loader.get_template('game.html')
    context = RequestContext(request)

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

    # Retrieve past moves from session.
    request.session['player_moves'] = []
    request.session['computer_moves'] = []

    return HttpResponse(template.render(context))
コード例 #2
0
ファイル: generate_events.py プロジェクト: abrookins/quest
    def handle(self, *args, **options):
        events = []
        data = {"name": options['name'], "data": {"important!": "you rock"}}
        if options['user_id'] > 0:
            data['user_id'] = options['user_id']

        for i in range(options['num']):
            events.append(Event(**data))

        Event.objects.bulk_create(events)
コード例 #3
0
ファイル: views.py プロジェクト: gajop/analytics-web
def registerEvent(request, event):
    try:
        name = event["name"]
        value_str = event.get("value_str")
        value_float = event.get("value_float")
        game_instance_id = event["session_id"]
        time = event.get("time")
    except KeyError as k:
        raise Exception("Missing required parameter: " + k.message)
    game_instance = GameInstance.objects.filter(pk=game_instance_id).first()
    if game_instance is None:
        raise Exception("No session with id = " + str(game_instance_id) + ". Did you forget to call openSession(...)?")
    if time is not None:
        upload_date = game_instance.started_date + timedelta(seconds=time)
    else:
        upload_date = timezone.now()
    event = Event(name=name, value_str=value_str, value_float=value_float, game_instance=game_instance, upload_date=upload_date)
    event.save()
    return True
コード例 #4
0
ファイル: views.py プロジェクト: eikonomega/Tic-Tac-Toe
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))
コード例 #5
0
ファイル: views.py プロジェクト: eikonomega/Tic-Tac-Toe
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")