implemented scores

This commit is contained in:
Stephen McQuay 2013-05-09 00:37:35 -07:00
parent 6aaa72475a
commit 8458c38468
2 changed files with 36 additions and 5 deletions

View File

@ -3,6 +3,7 @@ package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/sessions"
"log"
"math/rand"
"net/http"
@ -28,6 +29,20 @@ func (h JsonHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
h(w, req)
}
func getScore(session *sessions.Session) int {
score := session.Values["Score"]
var parsed_score int
if score == nil {
parsed_score = 0
} else {
parsed_score = score.(int)
}
return parsed_score
}
func setScore(session *sessions.Session) {
}
func problem(w http.ResponseWriter, req *http.Request) {
operation := "+"
if r := rand.Intn(2); r == 0 {
@ -46,7 +61,10 @@ func problem(w http.ResponseWriter, req *http.Request) {
second = rand.Intn(MAX)
}
r := prob{operation, first, second, 66}
session, _ := store.Get(req, "Score")
score := getScore(session)
r := prob{operation, first, second, score}
b, err := json.Marshal(r)
if err != nil {
@ -62,11 +80,14 @@ func attempt(w http.ResponseWriter, req *http.Request) {
if err != nil {
log.Fatal("cannot parse first", err)
}
operation := req.FormValue("operation")
second, err := strconv.Atoi(req.FormValue("second"))
if err != nil {
log.Fatal("cannot parse second", err)
}
var guess int
answer := req.FormValue("answer")
if answer == "" {
@ -77,9 +98,6 @@ func attempt(w http.ResponseWriter, req *http.Request) {
log.Fatal("cannot parser answer", err)
}
}
if err != nil {
log.Fatal("cannot parse answer", err)
}
var result bool
if operation == "+" {
@ -88,7 +106,19 @@ func attempt(w http.ResponseWriter, req *http.Request) {
result = first-second == guess
}
b, err := json.Marshal(solution{result, 66})
session, _ := store.Get(req, "Score")
score := getScore(session)
if result {
score += 1
} else {
score -= 1
}
session, _ = store.Get(req, "Score")
session.Values["Score"] = score
session.Save(req, w)
b, err := json.Marshal(solution{result, score})
if err != nil {
log.Fatal("cannot marshal solution", err)
}

View File

@ -20,6 +20,7 @@ function deal_with_answer(e) {
"answer": $("#answer").val(),
};
$.post("/api/v0/attempt/", data, function(d) {
$("#score").text(d["Score"]);
if(d["Status"]) {
$("body").removeClass("wrong");
new_problem();