Implement chat
This commit is contained in:
@@ -28,6 +28,8 @@ var (
|
||||
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() {
|
||||
@@ -109,6 +111,22 @@ func handleConnection(conn net.Conn) {
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
@@ -118,10 +136,14 @@ func processActions() {
|
||||
player := players[playerID]
|
||||
player.Lock()
|
||||
for _, action := range actions {
|
||||
if action.Type == pb.Action_MOVE {
|
||||
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()
|
||||
@@ -144,6 +166,11 @@ func processActions() {
|
||||
p.Unlock()
|
||||
}
|
||||
|
||||
// Add chat messages to the server message
|
||||
chatMutex.RLock()
|
||||
state.ChatMessages = chatHistory
|
||||
chatMutex.RUnlock()
|
||||
|
||||
data, err := proto.Marshal(state)
|
||||
if err != nil {
|
||||
log.Printf("Failed to marshal game state: %v", err)
|
||||
|
||||
Reference in New Issue
Block a user