added multiplication

This commit is contained in:
sm
2014-12-07 21:23:31 -08:00
parent 6349277217
commit 467cda77bf
7 changed files with 70 additions and 25 deletions
+34 -20
View File
@@ -2,12 +2,12 @@ package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/sessions"
"log"
"math/rand"
"net/http"
"strconv"
"github.com/gorilla/sessions"
)
type prob struct {
@@ -22,13 +22,6 @@ type solution struct {
Score int
}
type JsonHandler func(http.ResponseWriter, *http.Request)
func (h JsonHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
h(w, req)
}
func getScore(session *sessions.Session) int {
score := session.Values["Score"]
var parsed_score int
@@ -40,7 +33,8 @@ func getScore(session *sessions.Session) int {
return parsed_score
}
func problem(w http.ResponseWriter, req *http.Request) {
func addsub(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
operation := "+"
if r := rand.Intn(2); r == 0 {
operation = "-"
@@ -63,16 +57,31 @@ func problem(w http.ResponseWriter, req *http.Request) {
r := prob{operation, first, second, score}
b, err := json.Marshal(r)
err := json.NewEncoder(w).Encode(r)
if err != nil {
log.Fatal("issue with json marshalling", err)
}
}
func mul(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
session, _ := store.Get(req, "Score")
score := getScore(session)
err := json.NewEncoder(w).Encode(
prob{
"x",
rand.Intn(11),
rand.Intn(11),
score,
},
)
if err != nil {
log.Fatal("issue with json marshalling", err)
}
j := string(b)
fmt.Println("problem", j)
fmt.Fprintf(w, j)
}
func attempt(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
first, err := strconv.Atoi(req.FormValue("first"))
if err != nil {
log.Fatal("cannot parse first", err)
@@ -97,10 +106,13 @@ func attempt(w http.ResponseWriter, req *http.Request) {
}
var result bool
if operation == "+" {
switch operation {
case "+":
result = first+second == guess
} else if operation == "-" {
case "-":
result = first-second == guess
case "*", "x":
result = first*second == guess
}
session, _ := store.Get(req, "Score")
@@ -113,11 +125,13 @@ func attempt(w http.ResponseWriter, req *http.Request) {
session.Values["Score"] = score
session.Save(req, w)
b, err := json.Marshal(solution{result, score})
err = json.NewEncoder(w).Encode(
solution{
result,
score,
},
)
if err != nil {
log.Fatal("cannot marshal solution", err)
}
j := string(b)
fmt.Println("attempt", j)
fmt.Fprintf(w, j)
}