tome_matrix/match.go

106 lines
2.4 KiB
Go

package main
import (
"log"
"strings"
"git.saintnet.tech/tomecraft/tome_game"
"git.saintnet.tech/tomecraft/tome_lib"
"github.com/google/uuid"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id"
)
type Match struct {
ID uuid.UUID
Game *tome_game.Game
P1 id.UserID
P1Room id.RoomID
P2 id.UserID
P2Room id.RoomID
Dealer id.UserID
MatrixRoom id.RoomID
}
type MatchResp struct {
Body string
Private bool
}
func EmptyMatchResp() MatchResp {
return MatchResp{
Body: "",
Private: false,
}
}
func NewMatch() *Match {
return &Match{
ID: uuid.New(),
Game: nil,
P1: "",
P1Room: "",
P2: "",
P2Room: "",
MatrixRoom: "",
}
}
func (m *Match) ParseAction(sender id.UserID, msg string) MatchResp {
var cmd tome_lib.Command
if sender == m.P1 {
cmd.PlayerID = tome_lib.SentinalID
} else if sender == m.P2 {
cmd.PlayerID = tome_lib.ScourgeID
}
msg_s := strings.Split(msg, " ")
ctype := tome_lib.CmdType(msg_s[0])
if ctype != tome_lib.ActCmd && msg_s[0] != tome_lib.StateCmd && ctype != tome_lib.DebugCmd && ctype != tome_lib.DebugCmd {
return EmptyMatchResp()
}
cmd.Type = ctype
cmd.Cmd = strings.Join(msg_s[1:], " ")
res := m.Game.Parse(&cmd)
match_res := MatchResp{
Body: res.String(),
Private: (cmd.Type == tome_lib.ActCmd && cmd.String() == "d"),
}
return match_res
}
func (m *Match) JoinOrLeave(members map[id.UserID]struct {
DisplayName *string `json:"display_name"`
AvatarURL *string `json:"avatar_url"`
}, evt *event.MemberEventContent) {
_, p1ok := members[m.P1]
_, p2ok := members[m.P2]
if evt.Membership == event.MembershipJoin {
if m.Game != nil {
//players are already here, we don't care about joins
return
}
if p1ok && p2ok {
log.Println("both players are in the room now")
m.Game = tome_game.NewGame([]int{}, []int{})
}
} else if evt.Membership == event.MembershipLeave {
if !p1ok || !p2ok {
log.Println("player has left match")
if m.Game.Status != tome_lib.StatusDraw &&
m.Game.Status != tome_lib.StatusScourgeWin &&
m.Game.Status != tome_lib.StatusSentinalWin {
m.Game.Status = tome_lib.StatusStop
log.Println("user left match before it ended; stopping")
}
}
} else {
log.Println("disregarding membership event we don't care about")
}
}
func (m *Match) IsPlayer(person id.UserID) bool {
return (person == m.P1 || person == m.P2 || person == m.Dealer)
}