telnetroulette/client.go
2024-06-09 11:02:18 +02:00

123 lines
2.7 KiB
Go

package main
import (
"github.com/BRNSystems/go-telnet"
"math/rand"
"strconv"
"strings"
)
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
items []item
// 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)
_, err := writer.Write([]byte(message))
if err != nil {
return
}
}
func (client *client) sendMessage(message string, sender *client) {
client.send("\a\r\n<" + sender.getMentionName() + "> " + 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
}
func (client *client) renderHP() string {
var graphic strings.Builder
graphic.WriteString(strconv.Itoa(client.HP) + " / " + strconv.Itoa(client.match.maxHP) + " ")
for i := 1; i <= client.match.maxHP; i++ {
if client.HP >= i {
graphic.WriteString("█")
} else {
graphic.WriteString("░")
}
}
return graphic.String()
}
func (client *client) renderItems() string {
if len(client.items) > 0 {
var out strings.Builder
for i := 0; i < len(client.items); i++ {
name := client.items[i].name()
out.WriteString(strconv.Itoa(i) + " - " + name + "\r\n")
}
return "My items are:\r\n" + out.String()
} else {
return ""
}
}
func (client *client) getMentionName() string {
return client.Username + "(" + strconv.Itoa(client.ID) + ")"
}
func (client *client) giveItem() {
client.items = append(client.items, item{
kind: rand.Intn(client.match.itemCount),
match: client.match,
owner: client,
})
}