Initial commit

This commit is contained in:
cpp 2020-11-17 07:27:46 +01:00
commit 45b71573b1
3 changed files with 111 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
game
*.swp

85
game.go Normal file
View file

@ -0,0 +1,85 @@
package main
import (
"fmt"
"io/ioutil"
"os"
"encoding/json"
"log"
"net/http"
"math/rand"
"strconv"
)
type Phrase struct {
Phrase string `json:"phrase"`
Mode bool `json:"mode"`
Answer string `json:"answer"`
}
type Phrases struct {
Phrases []Phrase `json:"phrases"`
}
var phrases Phrases
func ParseJSON() {
jsonFile, err := os.Open("phrases.json")
if err != nil {
log.Fatal(err)
}
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
err = json.Unmarshal(byteValue, &phrases)
if err != nil {
log.Fatal(err)
}
}
func requestHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
i := rand.Intn(len(phrases.Phrases))
fmt.Fprintf(w, `
<meta charset="UTF-8"><html><body>%s
<form action="/answer/%d" method="POST">
<input type="text" autocomplete="off" name="answer" />
<input type="submit" value="verifique" />
</form>
</body></html>
`, phrases.Phrases[i].Phrase, i)
}
func answerHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
i, err := strconv.Atoi(r.URL.Path[len("/answer/"):])
if err != nil {
log.Fatal(err)
}
p := phrases.Phrases[i]
pageContent := "<meta charset=\"UTF-8\"><html><body><b>" + p.Phrase + "</b><br /"
if p.Mode == true {
pageContent += "<i>aquí nececitamos el subjuntivo:</i><br />"
} else {
pageContent += "<i>aquí nececitamos el indicativo:</i><br />"
}
pageContent += p.Answer + "<br /> tu respuesta estaba "
if r.FormValue("answer") == p.Answer {
pageContent += "<b>correcta!</b>. Buen hecho<br /"
} else {
pageContent += "<b>falsa :'-(</b><br />"
}
j := rand.Intn(len(phrases.Phrases)-1)
if j>=i {
j++
}
pageContent+= "<br />frase nueva: " + phrases.Phrases[j].Phrase + `<br />
<form action="/answer/`+ strconv.Itoa(j) +`" method="POST">
<input type="text" autocomplete="off" name="answer" />
<input type="submit" value="verifique" />
</form>`
pageContent += "</body></html>"
fmt.Fprintf(w,pageContent)
}
func main() {
ParseJSON()
/* for _, phrase := range phrases.Phrases {
fmt.Println(phrase.Phrase)
}*/
http.HandleFunc("/", requestHandler)
http.HandleFunc("/answer/", answerHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}

24
phrases.json Normal file
View file

@ -0,0 +1,24 @@
{
"phrases": [
{
"phrase": "Quiero que (saber, tú) toda la verdad",
"mode": true,
"answer": "sepas"
},
{
"phrase": "Me gusta que (ir, vosotr@s) siempre al teatro",
"mode": true,
"answer": "vayáis"
},
{
"phrase": "A la madre de Osvaldo le alegra que él (estudiar, él) todos los días",
"mode": true,
"answer": "estudie"
},
{
"phrase": "ojalá (llover)",
"mode": true,
"answer": "llueva"
}
]
}