telnetroulette/client.go
2024-06-08 13:52:22 +02:00

79 lines
1.7 KiB
Go

package main
import (
"github.com/BRNSystems/go-telnet"
"strconv"
)
type Client struct {
Client *telnet.Client
Username string
ID int
History []string
HistoryIndex int
context *telnet.Context
writer *telnet.Writer
reader *telnet.Reader
match *Match
isHost bool
hp int
// Add more fields as needed
}
func NewClient(context *telnet.Context, writer *telnet.Writer, reader *telnet.Reader) int {
client := Client{}
clientsMutex.Lock()
clients = append(clients, &client)
clientID := len(clients) - 1
defer clientsMutex.Unlock()
clients[clientID].ID = clientID
clients[clientID].Username = "Client #" + strconv.Itoa(clientID)
clients[clientID].context = context
clients[clientID].writer = writer
clients[clientID].reader = reader
clients[clientID].isHost = false
clients[clientID].hp = -1
return clientID
}
func RemoveClient(clientID int) {
clientsMutex.Lock()
defer clientsMutex.Unlock()
clients = append(clients[:clientID], clients[clientID+1:]...)
}
func (client Client) send(message string) {
writer := *(client.writer)
writer.Write([]byte(message))
}
func (client Client) sendMessage(message string, sender *Client) {
client.send("\a\r\n<" + sender.Username + "(" + strconv.Itoa(sender.ID) + ")> " + message + "\r\n")
}
func getIDByName(name string) int {
clientsMutex.Lock()
defer clientsMutex.Unlock()
for _, client := range clients {
if client.Username == name {
return client.ID
}
}
return -1
}
func getByIDOrName(by string) int {
//if integer assume clientID
var toClientID int
toClientID, err := strconv.Atoi(by)
if err != nil {
toClientID = getIDByName(by)
}
if toClientID < len(clients) && toClientID >= 0 {
return toClientID
}
return -1
}