add quit channel to clean up after self

This commit is contained in:
bdnugget 2025-01-18 22:27:22 +01:00
parent fb018e2a7d
commit d86cbe15a3
3 changed files with 80 additions and 65 deletions

View File

@ -17,6 +17,7 @@ type Game struct {
Music rl.Music
Chat *Chat
MenuOpen bool
QuitChan chan struct{} // Channel to signal shutdown
}
func New() *Game {
@ -38,6 +39,7 @@ func New() *Game {
Projection: rl.CameraPerspective,
},
Chat: NewChat(),
QuitChan: make(chan struct{}),
}
game.Player.UserData = game
game.Chat.userData = game
@ -259,6 +261,7 @@ func (g *Game) DrawMenu() {
case "Settings":
// TODO: Implement settings
case "Exit Game":
close(g.QuitChan) // Signal all goroutines to shut down
rl.CloseWindow()
}
}

View File

@ -52,7 +52,7 @@ func main() {
game.Player.Model = game.Models[modelIndex].Model
game.Player.Texture = game.Models[modelIndex].Texture
go network.HandleServerCommunication(conn, playerID, game.Player, game.OtherPlayers)
go network.HandleServerCommunication(conn, playerID, game.Player, game.OtherPlayers, game.QuitChan)
rl.PlayMusicStream(game.Music)
rl.SetMusicVolume(game.Music, 0.5)
@ -65,4 +65,7 @@ func main() {
game.Update(deltaTime)
game.Render()
}
// Wait for clean shutdown
<-game.QuitChan
}

View File

@ -56,15 +56,18 @@ func ConnectToServer() (net.Conn, int32, error) {
return conn, playerID, nil
}
func HandleServerCommunication(conn net.Conn, playerID int32, player *types.Player, otherPlayers map[int32]*types.Player) {
// Create a buffered reader for the connection
func HandleServerCommunication(conn net.Conn, playerID int32, player *types.Player, otherPlayers map[int32]*types.Player, quitChan <-chan struct{}) {
reader := bufio.NewReader(conn)
actionTicker := time.NewTicker(types.ClientTickRate)
defer actionTicker.Stop()
go func() {
for range actionTicker.C {
for {
select {
case <-quitChan:
return
case <-actionTicker.C:
player.Lock()
if len(player.ActionQueue) > 0 {
actions := make([]*pb.Action, len(player.ActionQueue))
@ -87,9 +90,14 @@ func HandleServerCommunication(conn net.Conn, playerID int32, player *types.Play
player.Unlock()
}
}
}
}()
for {
select {
case <-quitChan:
return
default:
// Read message length (4 bytes)
lengthBuf := make([]byte, 4)
if _, err := io.ReadFull(reader, lengthBuf); err != nil {
@ -142,6 +150,7 @@ func HandleServerCommunication(conn net.Conn, playerID int32, player *types.Play
}
}
}
}
// Helper function to write length-prefixed messages
func writeMessage(conn net.Conn, msg proto.Message) error {