212 lines
5.0 KiB
Go
212 lines
5.0 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"encoding/binary"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net"
|
|
"sync"
|
|
"time"
|
|
|
|
pb "gitea.boner.be/bdnugget/goonserver/actions"
|
|
|
|
"google.golang.org/protobuf/proto"
|
|
)
|
|
|
|
const (
|
|
port = ":6969" // Port to listen on
|
|
tickRate = 600 * time.Millisecond
|
|
)
|
|
|
|
type Player struct {
|
|
sync.Mutex
|
|
ID int
|
|
X, Y int // Position on the game grid
|
|
}
|
|
|
|
var (
|
|
players = make(map[int]*Player)
|
|
actionQueue = make(map[int][]*pb.Action) // Queue to store actions for each player
|
|
playerConns = make(map[int]net.Conn) // Map to store player connections
|
|
mu sync.RWMutex // Add mutex for protecting shared maps
|
|
chatHistory = make([]*pb.ChatMessage, 0, 100)
|
|
chatMutex sync.RWMutex
|
|
)
|
|
|
|
func main() {
|
|
ln, err := net.Listen("tcp", port)
|
|
if err != nil {
|
|
log.Fatalf("Failed to listen on port %s: %v", port, err)
|
|
}
|
|
defer ln.Close()
|
|
fmt.Printf("Server is listening on port %s\n", port)
|
|
|
|
go func() {
|
|
for {
|
|
conn, err := ln.Accept()
|
|
if err != nil {
|
|
log.Printf("Failed to accept connection: %v", err)
|
|
continue
|
|
}
|
|
go handleConnection(conn)
|
|
}
|
|
}()
|
|
|
|
lastTick := time.Now()
|
|
for {
|
|
if time.Since(lastTick) >= tickRate {
|
|
lastTick = time.Now()
|
|
processActions()
|
|
}
|
|
}
|
|
}
|
|
|
|
func handleConnection(conn net.Conn) {
|
|
defer conn.Close()
|
|
|
|
mu.Lock()
|
|
playerID := len(players) + 1
|
|
newPlayer := &Player{ID: playerID, X: 5, Y: 5}
|
|
players[playerID] = newPlayer
|
|
playerConns[playerID] = conn
|
|
mu.Unlock()
|
|
fmt.Printf("Player %d connected\n", playerID)
|
|
|
|
// Send player ID to the client
|
|
serverMsg := &pb.ServerMessage{
|
|
PlayerId: int32(playerID),
|
|
CurrentTick: 0,
|
|
}
|
|
if err := writeMessage(conn, serverMsg); err != nil {
|
|
log.Printf("Failed to send player ID to player %d: %v", playerID, err)
|
|
return
|
|
}
|
|
|
|
// Listen for incoming actions from this player
|
|
reader := bufio.NewReader(conn)
|
|
for {
|
|
// Read message length
|
|
lengthBuf := make([]byte, 4)
|
|
if _, err := io.ReadFull(reader, lengthBuf); err != nil {
|
|
log.Printf("Error reading message length from player %d: %v", playerID, err)
|
|
delete(players, playerID)
|
|
delete(playerConns, playerID)
|
|
delete(actionQueue, playerID)
|
|
return
|
|
}
|
|
messageLength := binary.BigEndian.Uint32(lengthBuf)
|
|
|
|
// Read message body
|
|
messageBuf := make([]byte, messageLength)
|
|
if _, err := io.ReadFull(reader, messageBuf); err != nil {
|
|
log.Printf("Error reading message from player %d: %v", playerID, err)
|
|
delete(players, playerID)
|
|
delete(playerConns, playerID)
|
|
delete(actionQueue, playerID)
|
|
return
|
|
}
|
|
|
|
batch := &pb.ActionBatch{}
|
|
if err := proto.Unmarshal(messageBuf, batch); err != nil {
|
|
log.Printf("Failed to unmarshal action batch for player %d: %v", playerID, err)
|
|
continue
|
|
}
|
|
|
|
// Queue the actions for processing
|
|
if batch.PlayerId == int32(playerID) {
|
|
actionQueue[playerID] = append(actionQueue[playerID], batch.Actions...)
|
|
}
|
|
}
|
|
}
|
|
|
|
func addChatMessage(playerID int32, content string) {
|
|
chatMutex.Lock()
|
|
defer chatMutex.Unlock()
|
|
|
|
msg := &pb.ChatMessage{
|
|
PlayerId: playerID,
|
|
Content: content,
|
|
Timestamp: time.Now().UnixNano(),
|
|
}
|
|
|
|
if len(chatHistory) >= 100 {
|
|
chatHistory = chatHistory[1:]
|
|
}
|
|
chatHistory = append(chatHistory, msg)
|
|
}
|
|
|
|
func processActions() {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
|
|
// Update players based on queued actions
|
|
for playerID, actions := range actionQueue {
|
|
player := players[playerID]
|
|
player.Lock()
|
|
for _, action := range actions {
|
|
switch action.Type {
|
|
case pb.Action_MOVE:
|
|
player.X = int(action.X)
|
|
player.Y = int(action.Y)
|
|
fmt.Printf("Player %d moved to (%d, %d)\n", playerID, player.X, player.Y)
|
|
case pb.Action_CHAT:
|
|
addChatMessage(int32(playerID), action.ChatMessage)
|
|
fmt.Printf("Player %d says: %s\n", playerID, action.ChatMessage)
|
|
}
|
|
}
|
|
player.Unlock()
|
|
actionQueue[playerID] = nil // Clear the action queue after processing
|
|
}
|
|
|
|
// Prepare and broadcast the current game state
|
|
currentTick := time.Now().UnixNano() / int64(tickRate)
|
|
state := &pb.ServerMessage{
|
|
CurrentTick: currentTick,
|
|
Players: make([]*pb.PlayerState, 0, len(players)),
|
|
}
|
|
|
|
// Convert players to PlayerState
|
|
for id, p := range players {
|
|
p.Lock()
|
|
state.Players = append(state.Players, &pb.PlayerState{
|
|
PlayerId: int32(id),
|
|
X: int32(p.X),
|
|
Y: int32(p.Y),
|
|
})
|
|
p.Unlock()
|
|
}
|
|
|
|
// Add new chat messages to the state
|
|
chatMutex.RLock()
|
|
state.ChatMessages = chatHistory[max(0, len(chatHistory)-5):] // Only send last 5 messages
|
|
chatMutex.RUnlock()
|
|
|
|
// Send to each connected player
|
|
for _, conn := range playerConns {
|
|
if err := writeMessage(conn, state); err != nil {
|
|
log.Printf("Failed to send update: %v", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Helper function to write length-prefixed messages
|
|
func writeMessage(conn net.Conn, msg proto.Message) error {
|
|
data, err := proto.Marshal(msg)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Write length prefix
|
|
lengthBuf := make([]byte, 4)
|
|
binary.BigEndian.PutUint32(lengthBuf, uint32(len(data)))
|
|
if _, err := conn.Write(lengthBuf); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Write message body
|
|
_, err = conn.Write(data)
|
|
return err
|
|
}
|