playerID
This commit is contained in:
parent
f16e8647dc
commit
1d6d3ab2ea
38
main.go
38
main.go
@ -21,8 +21,11 @@ type Player struct {
|
||||
X, Y int // Position on the game grid
|
||||
}
|
||||
|
||||
var players = make(map[int]*Player)
|
||||
var actionQueue = make(map[int][]*pb.Action) // Queue to store actions for each player
|
||||
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
|
||||
)
|
||||
|
||||
func main() {
|
||||
ln, err := net.Listen("tcp", port)
|
||||
@ -47,7 +50,6 @@ func main() {
|
||||
for {
|
||||
if time.Since(lastTick) >= tickRate {
|
||||
lastTick = time.Now()
|
||||
// log.Printf("Last tick: %s", lastTick)
|
||||
processActions()
|
||||
}
|
||||
}
|
||||
@ -59,6 +61,7 @@ func handleConnection(conn net.Conn) {
|
||||
// Assign a new player ID and add the player to the game state
|
||||
playerID := len(players) + 1
|
||||
players[playerID] = &Player{ID: playerID, X: 5, Y: 5} // Start at default position
|
||||
playerConns[playerID] = conn // Store the connection
|
||||
fmt.Printf("Player %d connected\n", playerID)
|
||||
|
||||
// Send player ID to the client
|
||||
@ -82,6 +85,7 @@ func handleConnection(conn net.Conn) {
|
||||
if err != nil {
|
||||
log.Printf("Error reading from player %d: %v", playerID, err)
|
||||
delete(players, playerID)
|
||||
delete(playerConns, playerID) // Remove connection on error
|
||||
return
|
||||
}
|
||||
|
||||
@ -97,6 +101,7 @@ func handleConnection(conn net.Conn) {
|
||||
}
|
||||
|
||||
func processActions() {
|
||||
// Update players based on queued actions
|
||||
for playerID, actions := range actionQueue {
|
||||
player := players[playerID]
|
||||
for _, action := range actions {
|
||||
@ -106,6 +111,31 @@ func processActions() {
|
||||
fmt.Printf("Player %d moved to (%d, %d)\n", playerID, player.X, player.Y)
|
||||
}
|
||||
}
|
||||
actionQueue[playerID] = nil // Clear the queue after processing
|
||||
actionQueue[playerID] = nil // Clear the action queue after processing
|
||||
}
|
||||
|
||||
// Prepare and broadcast the positions of all players
|
||||
for playerID := range players {
|
||||
state := &pb.ServerMessage{}
|
||||
for id, p := range players {
|
||||
state.Players = append(state.Players, &pb.PlayerState{
|
||||
PlayerId: int32(id),
|
||||
X: int32(p.X),
|
||||
Y: int32(p.Y),
|
||||
})
|
||||
}
|
||||
|
||||
data, err := proto.Marshal(state)
|
||||
if err != nil {
|
||||
log.Printf("Failed to marshal player state: %v", err)
|
||||
continue
|
||||
}
|
||||
|
||||
// Send to each connected player
|
||||
for _, conn := range playerConns {
|
||||
if _, err := conn.Write(data); err != nil {
|
||||
log.Printf("Failed to send update to player %d: %v", playerID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user