based database and account progress

This commit is contained in:
2025-01-19 21:52:37 +01:00
parent 0731339fe8
commit 3f7205d73e
4 changed files with 176 additions and 64 deletions
+69 -8
View File
@@ -17,14 +17,16 @@ import (
)
const (
port = ":6969" // Port to listen on
tickRate = 600 * time.Millisecond
port = ":6969" // Port to listen on
tickRate = 600 * time.Millisecond
protoVersion = 1
)
type Player struct {
sync.Mutex
ID int
X, Y int // Position on the game grid
ID int
X, Y int
Username string
}
var (
@@ -106,6 +108,26 @@ func handleConnection(conn net.Conn) {
var playerID int
var authErr error
if batch.ProtocolVersion == 0 {
response := &pb.ServerMessage{
AuthSuccess: false,
ErrorMessage: "Client using outdated protocol (pre-versioning)",
ProtocolVersion: protoVersion,
}
writeMessage(conn, response)
return
}
if batch.ProtocolVersion < protoVersion {
response := &pb.ServerMessage{
AuthSuccess: false,
ErrorMessage: fmt.Sprintf("Client protocol version too old (client: %d, required: %d)", batch.ProtocolVersion, protoVersion),
ProtocolVersion: protoVersion,
}
writeMessage(conn, response)
return
}
switch action.Type {
case pb.Action_REGISTER:
playerID, authErr = db.RegisterPlayer(action.Username, action.Password)
@@ -136,17 +158,49 @@ func handleConnection(conn net.Conn) {
x, y = 5, 5 // Default position
}
player := &Player{
ID: playerID,
X: x,
Y: y,
username, err := db.GetUsername(playerID)
if err != nil {
log.Printf("Error getting username for player %d: %v", playerID, err)
return
}
player := &Player{
ID: playerID,
X: x,
Y: y,
Username: username,
}
// Prevent multiple logins
mu.Lock()
for _, p := range players {
if p.Username == username {
mu.Unlock()
response := &pb.ServerMessage{
AuthSuccess: false,
ErrorMessage: "Account already logged in",
}
writeMessage(conn, response)
return
}
}
players[playerID] = player
playerConns[playerID] = conn
mu.Unlock()
// Send initial state with correct position
response = &pb.ServerMessage{
PlayerId: int32(playerID),
AuthSuccess: true,
Players: []*pb.PlayerState{{
PlayerId: int32(playerID),
X: int32(x),
Y: int32(y),
Username: username,
}},
ProtocolVersion: protoVersion,
}
// Ensure player state is saved on any kind of disconnect
defer func() {
if err := db.SavePlayerState(playerID, player.X, player.Y); err != nil {
@@ -209,11 +263,17 @@ func handleConnection(conn net.Conn) {
}
func addChatMessage(playerID int32, content string) {
player, exists := players[int(playerID)]
if !exists {
return
}
chatMutex.Lock()
defer chatMutex.Unlock()
msg := &pb.ChatMessage{
PlayerId: playerID,
Username: player.Username,
Content: content,
Timestamp: time.Now().UnixNano(),
}
@@ -261,6 +321,7 @@ func processActions() {
PlayerId: int32(id),
X: int32(p.X),
Y: int32(p.Y),
Username: p.Username,
})
p.Unlock()
}