105 lines
2.3 KiB
Go

package routes
import (
"dk/internal/actions"
"dk/internal/components"
"dk/internal/models/towns"
"dk/internal/models/users"
"dk/internal/router"
"dk/internal/session"
"slices"
"strconv"
)
func Index(ctx router.Ctx, _ []string) {
user, ok := ctx.UserValue("user").(*users.User)
if !ok || user == nil {
components.RenderPage(ctx, "", "intro.html", nil)
return
}
switch user.Currently {
case "In Town":
ctx.Redirect("/town", 303)
case "Exploring":
ctx.Redirect("/explore", 303)
default:
ctx.Redirect("/explore", 303)
}
}
func Move(ctx router.Ctx, _ []string) {
user := ctx.UserValue("user").(*users.User)
dir, err := strconv.Atoi(string(ctx.PostArgs().Peek("direction")))
if err != nil {
ctx.SetContentType("text/plain")
ctx.SetBodyString("move form parsing error")
return
}
currently, newX, newY, err := actions.Move(user, actions.Direction(dir))
if err != nil {
ctx.SetContentType("text/plain")
ctx.SetBodyString("move error: " + err.Error())
return
}
user.Currently = currently
user.X, user.Y = newX, newY
if currently == "In Town" {
ctx.Redirect("/town", 303)
return
}
ctx.Redirect("/explore", 303)
}
func Explore(ctx router.Ctx, _ []string) {
user := ctx.UserValue("user").(*users.User)
if user.Currently != "Exploring" {
ctx.Redirect("/", 303)
return
}
components.RenderPage(ctx, "", "explore.html", nil)
}
func Teleport(ctx router.Ctx, params []string) {
sess := ctx.UserValue("session").(*session.Session)
id, err := strconv.Atoi(params[0])
if err != nil {
sess.SetFlash("error", "Error teleporting; "+err.Error())
ctx.Redirect("/", 302)
return
}
town, err := towns.Find(id)
if err != nil {
sess.SetFlash("error", "Failed to teleport. Unknown town.")
ctx.Redirect("/", 302)
return
}
user := ctx.UserValue("user").(*users.User)
if !slices.Contains(user.GetTownIDs(), id) {
sess.SetFlash("error", "You don't have a map to "+town.Name+".")
ctx.Redirect("/", 302)
return
}
if user.TP < town.TPCost {
sess.SetFlash("error", "You don't have enough TP to teleport to "+town.Name+".")
ctx.Redirect("/", 302)
return
}
user.TP -= town.TPCost
user.X, user.Y = town.X, town.Y
user.Currently = "In Town"
user.Save()
sess.SetFlash("success", "You teleported to "+town.Name+" successfully!")
ctx.Redirect("/town", 302)
}