Use ticker like in client network.go to simplify logic

This commit is contained in:
bdnugget 2025-01-18 14:23:04 +01:00
parent 23474c19dc
commit b73d8de851

14
main.go
View File

@ -43,6 +43,11 @@ func main() {
defer ln.Close() defer ln.Close()
fmt.Printf("Server is listening on port %s\n", port) fmt.Printf("Server is listening on port %s\n", port)
// Create ticker for fixed game state updates
ticker := time.NewTicker(tickRate)
defer ticker.Stop()
// Handle incoming connections in a separate goroutine
go func() { go func() {
for { for {
conn, err := ln.Accept() conn, err := ln.Accept()
@ -54,14 +59,11 @@ func main() {
} }
}() }()
lastTick := time.Now() // Main game loop
for { for range ticker.C {
if time.Since(lastTick) >= tickRate {
lastTick = time.Now()
processActions() processActions()
} }
} }
}
func handleConnection(conn net.Conn) { func handleConnection(conn net.Conn) {
defer conn.Close() defer conn.Close()
@ -178,7 +180,7 @@ func processActions() {
p.Unlock() p.Unlock()
} }
// Add new chat messages to the state // Add chat messages to the state
chatMutex.RLock() chatMutex.RLock()
state.ChatMessages = chatHistory[max(0, len(chatHistory)-5):] // Only send last 5 messages state.ChatMessages = chatHistory[max(0, len(chatHistory)-5):] // Only send last 5 messages
chatMutex.RUnlock() chatMutex.RUnlock()