Add leaderboard functionality with Redis integration for scores. This includes a global leaderboard system, server-side score submission handling, and real-time player ranking updates. Refactor and improve collision logic and game state management for better player experience.
This commit is contained in:
@@ -5,7 +5,10 @@ import (
|
||||
"image/color"
|
||||
"log"
|
||||
"math"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"git.zb-server.de/ZB-Server/EscapeFromTeacher/pkg/game"
|
||||
"github.com/hajimehoshi/ebiten/v2"
|
||||
"github.com/hajimehoshi/ebiten/v2/inpututil"
|
||||
"github.com/hajimehoshi/ebiten/v2/text"
|
||||
@@ -51,6 +54,7 @@ func (g *Game) UpdateGame() {
|
||||
|
||||
// --- 4. CLIENT PREDICTION ---
|
||||
if g.connected {
|
||||
g.predictionMutex.Lock()
|
||||
// Sequenznummer erhöhen
|
||||
g.inputSequence++
|
||||
input.Sequence = g.inputSequence
|
||||
@@ -60,6 +64,7 @@ func (g *Game) UpdateGame() {
|
||||
|
||||
// Lokale Physik sofort anwenden (Prediction)
|
||||
g.ApplyInput(input)
|
||||
g.predictionMutex.Unlock()
|
||||
|
||||
// Input an Server senden
|
||||
g.SendInputWithSequence(input)
|
||||
@@ -156,6 +161,42 @@ func (g *Game) handleTouchInput() {
|
||||
// --- RENDERING LOGIC ---
|
||||
|
||||
func (g *Game) DrawGame(screen *ebiten.Image) {
|
||||
// WICHTIG: GAMEOVER-Check ZUERST, bevor wir Locks holen!
|
||||
g.stateMutex.Lock()
|
||||
status := g.gameState.Status
|
||||
g.stateMutex.Unlock()
|
||||
|
||||
if status == "GAMEOVER" {
|
||||
// Game Over Screen - komplett separates Rendering ohne weitere Locks
|
||||
g.stateMutex.Lock()
|
||||
myScore := 0
|
||||
for _, p := range g.gameState.Players {
|
||||
if p.Name == g.playerName {
|
||||
myScore = p.Score
|
||||
break
|
||||
}
|
||||
}
|
||||
g.stateMutex.Unlock()
|
||||
|
||||
g.DrawGameOverLeaderboard(screen, myScore)
|
||||
return // Früher Return, damit Game-UI nicht mehr gezeichnet wird
|
||||
}
|
||||
|
||||
// State Locken für Datenzugriff
|
||||
g.stateMutex.Lock()
|
||||
|
||||
// Prüfe ob Spieler tot ist
|
||||
isDead := false
|
||||
myScore := 0
|
||||
for _, p := range g.gameState.Players {
|
||||
if p.Name == g.playerName {
|
||||
isDead = !p.IsAlive || p.IsSpectator
|
||||
myScore = p.Score
|
||||
break
|
||||
}
|
||||
}
|
||||
g.stateMutex.Unlock()
|
||||
|
||||
// 1. Hintergrund & Boden
|
||||
screen.Fill(ColSky)
|
||||
|
||||
@@ -175,10 +216,7 @@ func (g *Game) DrawGame(screen *ebiten.Image) {
|
||||
continue
|
||||
}
|
||||
|
||||
// DEBUG: Chunk-Details loggen (nur einmal)
|
||||
if len(chunkDef.Objects) == 0 {
|
||||
log.Printf("⚠️ Chunk '%s' hat 0 Objekte! Width=%d", activeChunk.ChunkID, chunkDef.Width)
|
||||
}
|
||||
// Start-Chunk hat absichtlich keine Objekte
|
||||
|
||||
for _, obj := range chunkDef.Objects {
|
||||
// Asset zeichnen
|
||||
@@ -230,22 +268,15 @@ func (g *Game) DrawGame(screen *ebiten.Image) {
|
||||
text.Draw(screen, dist, basicfont.Face7x13, ScreenWidth-150, 30, ColText)
|
||||
|
||||
// Score anzeigen
|
||||
for _, p := range g.gameState.Players {
|
||||
if p.Name == g.playerName {
|
||||
scoreStr := fmt.Sprintf("Score: %d", p.Score)
|
||||
text.Draw(screen, scoreStr, basicfont.Face7x13, ScreenWidth-150, 50, ColText)
|
||||
break
|
||||
}
|
||||
}
|
||||
} else if g.gameState.Status == "GAMEOVER" {
|
||||
// Game Over Screen mit allen Scores
|
||||
text.Draw(screen, "GAME OVER", basicfont.Face7x13, ScreenWidth/2-50, 100, color.RGBA{255, 0, 0, 255})
|
||||
scoreStr := fmt.Sprintf("Score: %d", myScore)
|
||||
text.Draw(screen, scoreStr, basicfont.Face7x13, ScreenWidth-150, 50, ColText)
|
||||
|
||||
y := 150
|
||||
for _, p := range g.gameState.Players {
|
||||
scoreMsg := fmt.Sprintf("%s: %d pts", p.Name, p.Score)
|
||||
text.Draw(screen, scoreMsg, basicfont.Face7x13, ScreenWidth/2-80, y, color.White)
|
||||
y += 20
|
||||
// Spectator Overlay wenn tot
|
||||
if isDead {
|
||||
// Halbtransparenter roter Overlay
|
||||
vector.DrawFilledRect(screen, 0, 0, ScreenWidth, 80, color.RGBA{150, 0, 0, 180}, false)
|
||||
text.Draw(screen, "☠ DU BIST TOT - SPECTATOR MODE ☠", basicfont.Face7x13, ScreenWidth/2-140, 30, color.White)
|
||||
text.Draw(screen, fmt.Sprintf("Dein Final Score: %d", myScore), basicfont.Face7x13, ScreenWidth/2-90, 55, color.RGBA{255, 255, 0, 255})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -349,3 +380,154 @@ func (g *Game) DrawAsset(screen *ebiten.Image, assetID string, worldX, worldY fl
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// DrawGameOverLeaderboard zeigt Leaderboard mit Team-Name-Eingabe
|
||||
func (g *Game) DrawGameOverLeaderboard(screen *ebiten.Image, myScore int) {
|
||||
screen.Fill(color.RGBA{20, 20, 30, 255})
|
||||
|
||||
// Leaderboard immer beim ersten Mal anfordern (ohne Lock hier!)
|
||||
if !g.scoreSubmitted && g.gameMode == "solo" {
|
||||
g.submitScore() // submitScore() ruft requestLeaderboard() auf
|
||||
} else {
|
||||
// Für Coop: Nur Leaderboard anfordern, nicht submitten
|
||||
g.leaderboardMutex.Lock()
|
||||
needsLeaderboard := len(g.leaderboard) == 0 && g.connected
|
||||
g.leaderboardMutex.Unlock()
|
||||
|
||||
if needsLeaderboard {
|
||||
g.requestLeaderboard()
|
||||
}
|
||||
}
|
||||
|
||||
// Großes GAME OVER
|
||||
text.Draw(screen, "GAME OVER", basicfont.Face7x13, ScreenWidth/2-50, 60, color.RGBA{255, 0, 0, 255})
|
||||
|
||||
// Linke Seite: Raum-Ergebnisse - Daten KOPIEREN mit Lock, dann außerhalb zeichnen
|
||||
text.Draw(screen, "=== RAUM ERGEBNISSE ===", basicfont.Face7x13, 50, 120, color.RGBA{255, 255, 0, 255})
|
||||
|
||||
type playerScore struct {
|
||||
name string
|
||||
score int
|
||||
}
|
||||
|
||||
// Lock NUR für Datenkopie
|
||||
g.stateMutex.Lock()
|
||||
players := make([]playerScore, 0, len(g.gameState.Players))
|
||||
for _, p := range g.gameState.Players {
|
||||
players = append(players, playerScore{name: p.Name, score: p.Score})
|
||||
}
|
||||
g.stateMutex.Unlock()
|
||||
|
||||
// Sortieren und Zeichnen OHNE Lock
|
||||
sort.Slice(players, func(i, j int) bool {
|
||||
return players[i].score > players[j].score
|
||||
})
|
||||
|
||||
y := 150
|
||||
for i, p := range players {
|
||||
medal := ""
|
||||
if i == 0 {
|
||||
medal = "🥇 "
|
||||
} else if i == 1 {
|
||||
medal = "🥈 "
|
||||
} else if i == 2 {
|
||||
medal = "🥉 "
|
||||
}
|
||||
scoreMsg := fmt.Sprintf("%d. %s%s: %d pts", i+1, medal, p.name, p.score)
|
||||
text.Draw(screen, scoreMsg, basicfont.Face7x13, 50, y, color.White)
|
||||
y += 20
|
||||
}
|
||||
|
||||
// Rechte Seite: Global Leaderboard - Daten KOPIEREN mit Lock, dann außerhalb zeichnen
|
||||
text.Draw(screen, "=== TOP 10 BESTENLISTE ===", basicfont.Face7x13, 650, 120, color.RGBA{255, 215, 0, 255})
|
||||
|
||||
// Lock NUR für Datenkopie
|
||||
g.leaderboardMutex.Lock()
|
||||
leaderboardCopy := make([]game.LeaderboardEntry, len(g.leaderboard))
|
||||
copy(leaderboardCopy, g.leaderboard)
|
||||
g.leaderboardMutex.Unlock()
|
||||
|
||||
// Zeichnen OHNE Lock
|
||||
ly := 150
|
||||
if len(leaderboardCopy) == 0 {
|
||||
text.Draw(screen, "Laden...", basicfont.Face7x13, 700, ly, color.Gray{150})
|
||||
} else {
|
||||
for i, entry := range leaderboardCopy {
|
||||
if i >= 10 {
|
||||
break
|
||||
}
|
||||
var col color.Color = color.White
|
||||
marker := ""
|
||||
if entry.PlayerCode == g.playerCode {
|
||||
col = color.RGBA{0, 255, 0, 255}
|
||||
marker = " ← DU"
|
||||
}
|
||||
medal := ""
|
||||
if i == 0 {
|
||||
medal = "🥇 "
|
||||
} else if i == 1 {
|
||||
medal = "🥈 "
|
||||
} else if i == 2 {
|
||||
medal = "🥉 "
|
||||
}
|
||||
leaderMsg := fmt.Sprintf("%d. %s%s: %d%s", i+1, medal, entry.PlayerName, entry.Score, marker)
|
||||
text.Draw(screen, leaderMsg, basicfont.Face7x13, 650, ly, col)
|
||||
ly += 20
|
||||
}
|
||||
}
|
||||
|
||||
// Team-Name-Eingabe nur für Coop-Host (in der Mitte unten)
|
||||
if g.gameMode == "coop" && g.isHost {
|
||||
text.Draw(screen, "Host: Gib Team-Namen ein", basicfont.Face7x13, ScreenWidth/2-100, ScreenHeight-180, color.RGBA{255, 215, 0, 255})
|
||||
|
||||
// Team-Name Feld
|
||||
fieldW := 300
|
||||
fieldX := ScreenWidth/2 - fieldW/2
|
||||
fieldY := ScreenHeight - 140
|
||||
|
||||
col := color.RGBA{70, 70, 80, 255}
|
||||
if g.activeField == "teamname" {
|
||||
col = color.RGBA{90, 90, 100, 255}
|
||||
}
|
||||
vector.DrawFilledRect(screen, float32(fieldX), float32(fieldY), float32(fieldW), 40, col, false)
|
||||
vector.StrokeRect(screen, float32(fieldX), float32(fieldY), float32(fieldW), 40, 2, color.RGBA{255, 215, 0, 255}, false)
|
||||
|
||||
display := g.teamName
|
||||
if g.activeField == "teamname" && (time.Now().UnixMilli()/500)%2 == 0 {
|
||||
display += "|"
|
||||
}
|
||||
if display == "" {
|
||||
display = "Team Name..."
|
||||
}
|
||||
text.Draw(screen, display, basicfont.Face7x13, fieldX+10, fieldY+25, color.White)
|
||||
|
||||
// Submit Button
|
||||
submitBtnY := ScreenHeight - 85
|
||||
submitBtnW := 200
|
||||
submitBtnX := ScreenWidth/2 - submitBtnW/2
|
||||
|
||||
btnCol := color.RGBA{0, 150, 0, 255}
|
||||
if g.teamName == "" {
|
||||
btnCol = color.RGBA{100, 100, 100, 255} // Grau wenn kein Name
|
||||
}
|
||||
vector.DrawFilledRect(screen, float32(submitBtnX), float32(submitBtnY), float32(submitBtnW), 40, btnCol, false)
|
||||
vector.StrokeRect(screen, float32(submitBtnX), float32(submitBtnY), float32(submitBtnW), 40, 2, color.White, false)
|
||||
text.Draw(screen, "SUBMIT SCORE", basicfont.Face7x13, submitBtnX+50, submitBtnY+25, color.White)
|
||||
} else if g.gameMode == "solo" && g.scoreSubmitted {
|
||||
// Solo: Zeige Bestätigungsmeldung
|
||||
text.Draw(screen, "Score eingereicht!", basicfont.Face7x13, ScreenWidth/2-70, ScreenHeight-100, color.RGBA{0, 255, 0, 255})
|
||||
} else if g.gameMode == "coop" && !g.isHost {
|
||||
// Coop Non-Host: Warten auf Host
|
||||
text.Draw(screen, "Warte auf Host...", basicfont.Face7x13, ScreenWidth/2-70, ScreenHeight-100, color.Gray{180})
|
||||
}
|
||||
|
||||
// Back Button (oben links)
|
||||
backBtnW, backBtnH := 120, 40
|
||||
backBtnX, backBtnY := 20, 20
|
||||
vector.DrawFilledRect(screen, float32(backBtnX), float32(backBtnY), float32(backBtnW), float32(backBtnH), color.RGBA{150, 0, 0, 255}, false)
|
||||
vector.StrokeRect(screen, float32(backBtnX), float32(backBtnY), float32(backBtnW), float32(backBtnH), 2, color.White, false)
|
||||
text.Draw(screen, "< ZURÜCK", basicfont.Face7x13, backBtnX+20, backBtnY+25, color.White)
|
||||
|
||||
// Unten: Anleitung
|
||||
text.Draw(screen, "ESC oder ZURÜCK-Button = Menü", basicfont.Face7x13, ScreenWidth/2-110, ScreenHeight-30, color.Gray{180})
|
||||
}
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"image/color"
|
||||
_ "image/png"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"math/rand"
|
||||
mrand "math/rand"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
@@ -30,10 +32,11 @@ import (
|
||||
const (
|
||||
ScreenWidth = 1280
|
||||
ScreenHeight = 720
|
||||
StateMenu = 0
|
||||
StateLobby = 1
|
||||
StateGame = 2
|
||||
RefFloorY = 540
|
||||
StateMenu = 0
|
||||
StateLobby = 1
|
||||
StateGame = 2
|
||||
StateLeaderboard = 3
|
||||
RefFloorY = 540
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -66,10 +69,18 @@ type Game struct {
|
||||
|
||||
// Spieler Info
|
||||
playerName string
|
||||
playerCode string // Eindeutiger UUID für Leaderboard
|
||||
roomID string
|
||||
activeField string // "name" oder "room"
|
||||
activeField string // "name" oder "room" oder "teamname"
|
||||
gameMode string // "solo" oder "coop"
|
||||
isHost bool
|
||||
teamName string // Team-Name für Coop beim Game Over
|
||||
|
||||
// Leaderboard
|
||||
leaderboard []game.LeaderboardEntry
|
||||
scoreSubmitted bool
|
||||
showLeaderboard bool
|
||||
leaderboardMutex sync.Mutex
|
||||
|
||||
// Lobby State (für Change Detection)
|
||||
lastPlayerCount int
|
||||
@@ -84,6 +95,7 @@ type Game struct {
|
||||
inputSequence uint32 // Sequenznummer für Inputs
|
||||
pendingInputs map[uint32]InputState // Noch nicht bestätigte Inputs
|
||||
lastServerSeq uint32 // Letzte vom Server bestätigte Sequenz
|
||||
predictionMutex sync.Mutex // Mutex für pendingInputs
|
||||
|
||||
// Kamera
|
||||
camX float64
|
||||
@@ -107,11 +119,13 @@ func NewGame() *Game {
|
||||
activeField: "name",
|
||||
gameMode: "",
|
||||
pendingInputs: make(map[uint32]InputState),
|
||||
leaderboard: make([]game.LeaderboardEntry, 0),
|
||||
|
||||
joyBaseX: 150, joyBaseY: ScreenHeight - 150,
|
||||
joyStickX: 150, joyStickY: ScreenHeight - 150,
|
||||
}
|
||||
g.loadAssets()
|
||||
g.loadOrCreatePlayerCode()
|
||||
return g
|
||||
}
|
||||
|
||||
@@ -166,6 +180,48 @@ func (g *Game) loadAssets() {
|
||||
|
||||
// --- UPDATE ---
|
||||
func (g *Game) Update() error {
|
||||
// Game Over Handling
|
||||
if g.appState == StateGame && g.gameState.Status == "GAMEOVER" {
|
||||
// Back Button (oben links) - Touch Support
|
||||
backBtnW, backBtnH := 120, 40
|
||||
backBtnX, backBtnY := 20, 20
|
||||
if isHit(backBtnX, backBtnY, backBtnW, backBtnH) {
|
||||
g.appState = StateMenu
|
||||
g.connected = false
|
||||
g.scoreSubmitted = false
|
||||
g.teamName = ""
|
||||
g.activeField = ""
|
||||
if g.conn != nil {
|
||||
g.conn.Drain()
|
||||
g.conn.Close()
|
||||
}
|
||||
g.gameState = game.GameState{Players: make(map[string]game.PlayerState)}
|
||||
log.Println("🔙 Zurück zum Menü (Back Button)")
|
||||
return nil
|
||||
}
|
||||
|
||||
// ESC zurück zum Menü
|
||||
if inpututil.IsKeyJustPressed(ebiten.KeyEscape) {
|
||||
g.appState = StateMenu
|
||||
g.connected = false
|
||||
g.scoreSubmitted = false
|
||||
g.teamName = ""
|
||||
g.activeField = ""
|
||||
if g.conn != nil {
|
||||
g.conn.Drain()
|
||||
g.conn.Close()
|
||||
}
|
||||
g.gameState = game.GameState{Players: make(map[string]game.PlayerState)}
|
||||
log.Println("🔙 Zurück zum Menü (ESC)")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Host: Team-Name Eingabe
|
||||
if g.isHost {
|
||||
g.handleGameOverInput()
|
||||
}
|
||||
}
|
||||
|
||||
switch g.appState {
|
||||
case StateMenu:
|
||||
g.updateMenu()
|
||||
@@ -173,6 +229,8 @@ func (g *Game) Update() error {
|
||||
g.updateLobby()
|
||||
case StateGame:
|
||||
g.UpdateGame()
|
||||
case StateLeaderboard:
|
||||
g.updateLeaderboard()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -180,6 +238,18 @@ func (g *Game) Update() error {
|
||||
func (g *Game) updateMenu() {
|
||||
g.handleMenuInput()
|
||||
|
||||
// Leaderboard Button
|
||||
lbBtnW, lbBtnH := 200, 50
|
||||
lbBtnX := ScreenWidth - lbBtnW - 20
|
||||
lbBtnY := 20
|
||||
if isHit(lbBtnX, lbBtnY, lbBtnW, lbBtnH) {
|
||||
g.appState = StateLeaderboard
|
||||
if !g.connected {
|
||||
go g.connectForLeaderboard()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Name-Feld
|
||||
fieldW, fieldH := 250, 40
|
||||
nameX := ScreenWidth/2 - fieldW/2
|
||||
@@ -286,6 +356,8 @@ func (g *Game) Draw(screen *ebiten.Image) {
|
||||
g.DrawLobby(screen)
|
||||
case StateGame:
|
||||
g.DrawGame(screen)
|
||||
case StateLeaderboard:
|
||||
g.DrawLeaderboard(screen)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -364,6 +436,14 @@ func (g *Game) DrawMenu(screen *ebiten.Image) {
|
||||
text.Draw(screen, "Join with Code", basicfont.Face7x13, joinBtnX+90, joinBtnY+30, ColText)
|
||||
}
|
||||
|
||||
// Leaderboard Button
|
||||
lbBtnW := 200
|
||||
lbBtnX := ScreenWidth - lbBtnW - 20
|
||||
lbBtnY := 20
|
||||
vector.DrawFilledRect(screen, float32(lbBtnX), float32(lbBtnY), float32(lbBtnW), 50, ColBtnNormal, false)
|
||||
vector.StrokeRect(screen, float32(lbBtnX), float32(lbBtnY), float32(lbBtnW), 50, 2, color.RGBA{255, 215, 0, 255}, false)
|
||||
text.Draw(screen, "🏆 LEADERBOARD", basicfont.Face7x13, lbBtnX+35, lbBtnY+30, color.RGBA{255, 215, 0, 255})
|
||||
|
||||
text.Draw(screen, "WASD / Arrows - SPACE to Jump", basicfont.Face7x13, ScreenWidth/2-100, ScreenHeight-30, color.Gray{150})
|
||||
}
|
||||
|
||||
@@ -517,12 +597,56 @@ func (g *Game) handleMenuInput() {
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Game) handleGameOverInput() {
|
||||
// Team-Name Feld
|
||||
fieldW := 300
|
||||
fieldX := ScreenWidth/2 - fieldW/2
|
||||
fieldY := ScreenHeight - 140
|
||||
|
||||
// Click auf Team-Name Feld?
|
||||
if isHit(fieldX, fieldY, fieldW, 40) {
|
||||
g.activeField = "teamname"
|
||||
return
|
||||
}
|
||||
|
||||
// Submit Button
|
||||
submitBtnW := 200
|
||||
submitBtnX := ScreenWidth/2 - submitBtnW/2
|
||||
submitBtnY := ScreenHeight - 85
|
||||
|
||||
if isHit(submitBtnX, submitBtnY, submitBtnW, 40) {
|
||||
if g.teamName != "" {
|
||||
g.submitTeamScore()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Tastatur-Eingabe für Team-Name
|
||||
if g.activeField == "teamname" {
|
||||
if inpututil.IsKeyJustPressed(ebiten.KeyEnter) {
|
||||
if g.teamName != "" {
|
||||
g.submitTeamScore()
|
||||
}
|
||||
g.activeField = ""
|
||||
} else if inpututil.IsKeyJustPressed(ebiten.KeyBackspace) {
|
||||
if len(g.teamName) > 0 {
|
||||
g.teamName = g.teamName[:len(g.teamName)-1]
|
||||
}
|
||||
} else {
|
||||
chars := string(ebiten.InputChars())
|
||||
if len(g.teamName) < 30 { // Max 30 Zeichen
|
||||
g.teamName += chars
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func generateRoomCode() string {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
mrand.Seed(time.Now().UnixNano())
|
||||
chars := "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
code := make([]byte, 6)
|
||||
for i := range code {
|
||||
code[i] = chars[rand.Intn(len(chars))]
|
||||
code[i] = chars[mrand.Intn(len(chars))]
|
||||
}
|
||||
return string(code)
|
||||
}
|
||||
@@ -672,6 +796,214 @@ func (g *Game) getMyPlayerID() string {
|
||||
return g.playerName
|
||||
}
|
||||
|
||||
// loadOrCreatePlayerCode lädt oder erstellt einen eindeutigen Spieler-Code
|
||||
func (g *Game) loadOrCreatePlayerCode() {
|
||||
const codeFile = "player_code.txt"
|
||||
|
||||
// Versuche zu laden
|
||||
data, err := ioutil.ReadFile(codeFile)
|
||||
if err == nil {
|
||||
g.playerCode = strings.TrimSpace(string(data))
|
||||
log.Printf("🔑 Player-Code geladen: %s", g.playerCode)
|
||||
return
|
||||
}
|
||||
|
||||
// Erstelle neuen Code (16 Byte = 32 Hex-Zeichen)
|
||||
bytes := make([]byte, 16)
|
||||
if _, err := rand.Read(bytes); err != nil {
|
||||
log.Fatal("Fehler beim Generieren des Player-Codes:", err)
|
||||
}
|
||||
g.playerCode = hex.EncodeToString(bytes)
|
||||
|
||||
// Speichern
|
||||
if err := ioutil.WriteFile(codeFile, []byte(g.playerCode), 0644); err != nil {
|
||||
log.Printf("⚠️ Konnte Player-Code nicht speichern: %v", err)
|
||||
} else {
|
||||
log.Printf("🆕 Neuer Player-Code erstellt: %s", g.playerCode)
|
||||
}
|
||||
}
|
||||
|
||||
// submitScore sendet den individuellen Score an den Server (für Solo-Mode)
|
||||
func (g *Game) submitScore() {
|
||||
if g.scoreSubmitted || !g.connected {
|
||||
return
|
||||
}
|
||||
|
||||
// Finde eigenen Score
|
||||
myScore := 0
|
||||
for _, p := range g.gameState.Players {
|
||||
if p.Name == g.playerName {
|
||||
myScore = p.Score
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
submission := game.ScoreSubmission{
|
||||
PlayerName: g.playerName,
|
||||
PlayerCode: g.playerCode,
|
||||
Score: myScore,
|
||||
}
|
||||
|
||||
g.conn.Publish("score.submit", submission)
|
||||
g.scoreSubmitted = true
|
||||
log.Printf("📊 Score eingereicht: %d Punkte", myScore)
|
||||
|
||||
// Leaderboard abrufen
|
||||
g.requestLeaderboard()
|
||||
}
|
||||
|
||||
// submitTeamScore sendet den Team-Score an den Server (für Coop-Mode)
|
||||
func (g *Game) submitTeamScore() {
|
||||
if g.scoreSubmitted || !g.connected || g.teamName == "" {
|
||||
return
|
||||
}
|
||||
|
||||
// Berechne Team-Score (Summe aller Spieler-Scores)
|
||||
teamScore := 0
|
||||
for _, p := range g.gameState.Players {
|
||||
teamScore += p.Score
|
||||
}
|
||||
|
||||
submission := game.ScoreSubmission{
|
||||
PlayerName: g.teamName, // Team-Name statt Spieler-Name
|
||||
PlayerCode: g.playerCode,
|
||||
Score: teamScore,
|
||||
}
|
||||
|
||||
g.conn.Publish("score.submit", submission)
|
||||
g.scoreSubmitted = true
|
||||
g.activeField = ""
|
||||
log.Printf("📊 Team-Score eingereicht: %s - %d Punkte", g.teamName, teamScore)
|
||||
|
||||
// Leaderboard abrufen
|
||||
g.requestLeaderboard()
|
||||
}
|
||||
|
||||
// requestLeaderboard fordert das Leaderboard vom Server an (asynchron)
|
||||
func (g *Game) requestLeaderboard() {
|
||||
if !g.connected {
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
inbox := g.conn.Conn.NewRespInbox()
|
||||
sub, err := g.conn.Subscribe(inbox, func(entries *[]game.LeaderboardEntry) {
|
||||
g.leaderboardMutex.Lock()
|
||||
g.leaderboard = *entries
|
||||
g.leaderboardMutex.Unlock()
|
||||
log.Printf("📊 Leaderboard empfangen: %d Einträge", len(*entries))
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Printf("⚠️ Fehler beim Leaderboard-Request: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Request senden
|
||||
g.conn.PublishRequest("leaderboard.get", inbox, &struct{}{})
|
||||
|
||||
// Warte kurz auf Antwort, dann unsubscribe
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
sub.Unsubscribe()
|
||||
}()
|
||||
}
|
||||
|
||||
func (g *Game) connectForLeaderboard() {
|
||||
serverURL := "nats://localhost:4222"
|
||||
nc, err := nats.Connect(serverURL)
|
||||
if err != nil {
|
||||
log.Printf("❌ NATS Verbindung fehlgeschlagen: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
g.conn, err = nats.NewEncodedConn(nc, nats.JSON_ENCODER)
|
||||
if err != nil {
|
||||
log.Printf("❌ EncodedConn Fehler: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
g.connected = true
|
||||
log.Println("✅ Verbunden für Leaderboard")
|
||||
|
||||
// Leaderboard abrufen
|
||||
g.requestLeaderboard()
|
||||
}
|
||||
|
||||
func (g *Game) updateLeaderboard() {
|
||||
// Back Button (oben links) - Touch Support
|
||||
backBtnW, backBtnH := 120, 40
|
||||
backBtnX, backBtnY := 20, 20
|
||||
if isHit(backBtnX, backBtnY, backBtnW, backBtnH) {
|
||||
g.appState = StateMenu
|
||||
return
|
||||
}
|
||||
|
||||
// ESC = zurück zum Menü
|
||||
if inpututil.IsKeyJustPressed(ebiten.KeyEscape) {
|
||||
g.appState = StateMenu
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Game) DrawLeaderboard(screen *ebiten.Image) {
|
||||
screen.Fill(color.RGBA{20, 20, 30, 255})
|
||||
|
||||
// Titel
|
||||
text.Draw(screen, "=== TOP 10 LEADERBOARD ===", basicfont.Face7x13, ScreenWidth/2-100, 80, color.RGBA{255, 215, 0, 255})
|
||||
|
||||
// Leaderboard abrufen wenn leer
|
||||
g.leaderboardMutex.Lock()
|
||||
if len(g.leaderboard) == 0 && g.connected {
|
||||
g.leaderboardMutex.Unlock()
|
||||
g.requestLeaderboard()
|
||||
g.leaderboardMutex.Lock()
|
||||
}
|
||||
|
||||
y := 150
|
||||
if len(g.leaderboard) == 0 {
|
||||
text.Draw(screen, "Noch keine Einträge...", basicfont.Face7x13, ScreenWidth/2-80, y, color.Gray{150})
|
||||
} else {
|
||||
for i, entry := range g.leaderboard {
|
||||
if i >= 10 {
|
||||
break
|
||||
}
|
||||
|
||||
// Eigenen Eintrag markieren
|
||||
var col color.Color = color.White
|
||||
marker := ""
|
||||
if entry.PlayerCode == g.playerCode {
|
||||
col = color.RGBA{0, 255, 0, 255}
|
||||
marker = " ← DU"
|
||||
}
|
||||
|
||||
// Medaillen
|
||||
medal := ""
|
||||
if i == 0 {
|
||||
medal = "🥇 "
|
||||
} else if i == 1 {
|
||||
medal = "🥈 "
|
||||
} else if i == 2 {
|
||||
medal = "🥉 "
|
||||
}
|
||||
|
||||
leaderMsg := fmt.Sprintf("%d. %s%s: %d pts%s", i+1, medal, entry.PlayerName, entry.Score, marker)
|
||||
text.Draw(screen, leaderMsg, basicfont.Face7x13, ScreenWidth/2-150, y, col)
|
||||
y += 30
|
||||
}
|
||||
}
|
||||
g.leaderboardMutex.Unlock()
|
||||
|
||||
// Back Button (oben links)
|
||||
backBtnW, backBtnH := 120, 40
|
||||
backBtnX, backBtnY := 20, 20
|
||||
vector.DrawFilledRect(screen, float32(backBtnX), float32(backBtnY), float32(backBtnW), float32(backBtnH), color.RGBA{150, 0, 0, 255}, false)
|
||||
vector.StrokeRect(screen, float32(backBtnX), float32(backBtnY), float32(backBtnW), float32(backBtnH), 2, color.White, false)
|
||||
text.Draw(screen, "< ZURÜCK", basicfont.Face7x13, backBtnX+20, backBtnY+25, color.White)
|
||||
|
||||
// Zurück-Button Anleitung
|
||||
text.Draw(screen, "ESC oder ZURÜCK-Button = Menü", basicfont.Face7x13, ScreenWidth/2-110, ScreenHeight-40, color.Gray{150})
|
||||
}
|
||||
|
||||
func main() {
|
||||
ebiten.SetWindowSize(ScreenWidth, ScreenHeight)
|
||||
ebiten.SetWindowTitle("Escape From Teacher")
|
||||
|
||||
@@ -50,6 +50,9 @@ func (g *Game) ApplyInput(input InputState) {
|
||||
|
||||
// ReconcileWithServer gleicht lokale Prediction mit Server-State ab
|
||||
func (g *Game) ReconcileWithServer(serverState game.PlayerState) {
|
||||
g.predictionMutex.Lock()
|
||||
defer g.predictionMutex.Unlock()
|
||||
|
||||
// Server-bestätigte Sequenz
|
||||
g.lastServerSeq = serverState.LastInputSeq
|
||||
|
||||
|
||||
@@ -28,6 +28,11 @@ func main() {
|
||||
globalWorld = game.NewWorld()
|
||||
loadServerAssets(globalWorld)
|
||||
|
||||
// 1b. Redis-Leaderboard initialisieren
|
||||
if err := server.InitLeaderboard("localhost:6379"); err != nil {
|
||||
log.Fatal("❌ Konnte nicht zu Redis verbinden: ", err)
|
||||
}
|
||||
|
||||
// 2. NATS VERBINDUNG
|
||||
natsURL := "nats://localhost:4222"
|
||||
nc, err := nats.Connect(natsURL)
|
||||
@@ -99,6 +104,22 @@ func main() {
|
||||
}
|
||||
})
|
||||
|
||||
// 5. HANDLER: SCORE SUBMISSION
|
||||
_, _ = ec.Subscribe("score.submit", func(submission *game.ScoreSubmission) {
|
||||
log.Printf("📊 Score-Submission: %s (%s) mit %d Punkten", submission.PlayerName, submission.PlayerCode, submission.Score)
|
||||
added := server.GlobalLeaderboard.AddScore(submission.PlayerName, submission.PlayerCode, submission.Score)
|
||||
if added {
|
||||
log.Printf("✅ Score akzeptiert für %s", submission.PlayerName)
|
||||
}
|
||||
})
|
||||
|
||||
// 6. HANDLER: LEADERBOARD REQUEST
|
||||
_, _ = ec.Subscribe("leaderboard.get", func(subject, reply string, _ *struct{}) {
|
||||
top10 := server.GlobalLeaderboard.GetTop10()
|
||||
log.Printf("📊 Leaderboard-Request beantwortet: %d Einträge", len(top10))
|
||||
ec.Publish(reply, top10)
|
||||
})
|
||||
|
||||
log.Println("✅ Server bereit. Warte auf Spieler...")
|
||||
|
||||
// Block forever
|
||||
|
||||
Reference in New Issue
Block a user