mmg/mmg/views.py

64 lines
1.3 KiB
Python

import json
import random
from django.http import HttpResponse
from django.shortcuts import render
MAX = 12
def _generate_problem():
operation = random.choice(['+', '-'])
first = random.choice(range(MAX))
if operation == '-':
if first == 0:
second = 0
else:
second = random.choice(range(first))
else:
second = random.choice(range(MAX))
return {
'first': first,
'operation': operation,
'second': second,
}
def _validate_solution(a):
f = int(a['first'])
o = a['operation']
s = int(a['second'])
if a['answer'] == '':
g = 0
else:
g = int(a['answer'])
r = False
if o == '+':
r = bool(f + s == g)
else:
r = bool(f - s == g)
return r
def home(request):
return render(request, 'index.html')
def attempt(request):
d = request.POST.dict()
r = _validate_solution(d)
if r:
s = request.session.get('score', 0) + 1
else:
s = request.session.get('score', 0) - 1
request.session['score'] = s
return HttpResponse(
json.dumps({'status': r, 'score': s}),
content_type="application/json")
def problem(request):
d = _generate_problem()
d['score'] = request.session.get('score', 0)
return HttpResponse(json.dumps(d), content_type="application/json")