Private
Public Access
1
0

Add WebAssembly support for assets and chunks, implement gameover screen rendering, and enhance server gameplay logic with dynamic speeds, team naming, and score components.

This commit is contained in:
Sebastian Unterschütz
2026-01-04 14:30:31 +01:00
parent ce51a2ba4f
commit 95d61bf66e
68 changed files with 913 additions and 424 deletions

View File

@@ -5,8 +5,8 @@ import "time"
const (
// Server Settings
Port = ":8080"
AssetPath = "./cmd/client/assets/assets.json"
ChunkDir = "./cmd/client/assets/chunks"
AssetPath = "./cmd/client/web/assets/assets.json"
ChunkDir = "./cmd/client/web/assets/chunks"
// Physics
Gravity = 0.5

View File

@@ -66,10 +66,11 @@ type LoginPayload struct {
// Input vom Spieler während des Spiels
type ClientInput struct {
Type string `json:"type"` // "JUMP", "START", "LEFT_DOWN", "RIGHT_DOWN", etc.
Type string `json:"type"` // "JUMP", "START", "LEFT_DOWN", "RIGHT_DOWN", "SET_TEAM_NAME", etc.
RoomID string `json:"room_id"`
PlayerID string `json:"player_id"`
Sequence uint32 `json:"sequence"` // Sequenznummer für Client Prediction
Sequence uint32 `json:"sequence"` // Sequenznummer für Client Prediction
TeamName string `json:"team_name,omitempty"` // Für SET_TEAM_NAME Input
}
type JoinRequest struct {
@@ -105,6 +106,7 @@ type GameState struct {
TimeLeft int `json:"time_left"`
WorldChunks []ActiveChunk `json:"world_chunks"`
HostID string `json:"host_id"`
TeamName string `json:"team_name"` // Team-Name (vom Host gesetzt)
ScrollX float64 `json:"scroll_x"`
CollectedCoins map[string]bool `json:"collected_coins"` // Welche Coins wurden eingesammelt (Key: ChunkID_ObjectIndex)
CollectedPowerups map[string]bool `json:"collected_powerups"` // Welche Powerups wurden eingesammelt
@@ -125,7 +127,8 @@ type LeaderboardEntry struct {
PlayerName string `json:"player_name"`
PlayerCode string `json:"player_code"` // Eindeutiger Code für Verifikation
Score int `json:"score"`
Timestamp int64 `json:"timestamp"` // Unix-Timestamp
Timestamp int64 `json:"timestamp"` // Unix-Timestamp
ProofCode string `json:"proof_code"` // Beweis-Code zum Verifizieren des Scores
}
// Score-Submission vom Client an Server
@@ -133,8 +136,16 @@ type ScoreSubmission struct {
PlayerName string `json:"player_name"`
PlayerCode string `json:"player_code"`
Score int `json:"score"`
Name string `json:"name"` // Alternativer Name-Feld (für Kompatibilität)
Mode string `json:"mode"` // "solo" oder "coop"
Name string `json:"name"` // Alternativer Name-Feld (für Kompatibilität)
Mode string `json:"mode"` // "solo" oder "coop"
TeamName string `json:"team_name"` // Team-Name für Coop-Mode
}
// Score-Submission Response vom Server an Client
type ScoreSubmissionResponse struct {
Success bool `json:"success"`
ProofCode string `json:"proof_code"`
Score int `json:"score"`
}
// Start-Request vom Client

View File

@@ -83,7 +83,7 @@ func (w *World) GenerateColliders(activeChunks []ActiveChunk) []Collider {
continue
}
if def.Type == "obstacle" || def.Type == "platform" {
if def.Type == "obstacle" || def.Type == "platform" || def.Type == "wall" {
c := Collider{
Rect: Rect{
OffsetX: ac.X + obj.X + def.DrawOffX + def.Hitbox.OffsetX,

View File

@@ -2,7 +2,10 @@ package server
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"log"
"time"
@@ -39,17 +42,31 @@ func InitLeaderboard(redisAddr string) error {
return nil
}
func (lb *Leaderboard) AddScore(name, code string, score int) bool {
// GenerateProofCode erstellt einen kryptografisch sicheren Proof-Code
func GenerateProofCode(playerCode string, score int, timestamp int64) string {
// Secret Salt (sollte eigentlich aus Config kommen, aber für Demo hier hardcoded)
secret := "EscapeFromTeacher_Secret_2026"
data := fmt.Sprintf("%s:%d:%d:%s", playerCode, score, timestamp, secret)
hash := sha256.Sum256([]byte(data))
// Nehme erste 12 Zeichen des Hex-Hash
return hex.EncodeToString(hash[:])[:12]
}
func (lb *Leaderboard) AddScore(name, code string, score int) (bool, string) {
// Erstelle eindeutigen Key für diesen Score: PlayerCode + Timestamp
timestamp := time.Now().Unix()
uniqueKey := code + "_" + time.Now().Format("20060102_150405")
// Generiere Proof-Code
proofCode := GenerateProofCode(code, score, timestamp)
// Score speichern
entry := game.LeaderboardEntry{
PlayerName: name,
PlayerCode: code,
Score: score,
Timestamp: timestamp,
ProofCode: proofCode,
}
data, _ := json.Marshal(entry)
@@ -61,8 +78,8 @@ func (lb *Leaderboard) AddScore(name, code string, score int) bool {
Member: uniqueKey,
})
log.Printf("🏆 Leaderboard: %s mit %d Punkten (Entry: %s)", name, score, uniqueKey)
return true
log.Printf("🏆 Leaderboard: %s mit %d Punkten (Entry: %s, Proof: %s)", name, score, uniqueKey, proofCode)
return true, proofCode
}
func (lb *Leaderboard) GetTop10() []game.LeaderboardEntry {

View File

@@ -23,6 +23,8 @@ type ServerPlayer struct {
InputX float64 // -1 (Links), 0, 1 (Rechts)
LastInputSeq uint32 // Letzte verarbeitete Input-Sequenz
Score int
DistanceScore int // Score basierend auf zurückgelegter Distanz
BonusScore int // Score aus Coins und anderen Boni
IsAlive bool
IsSpectator bool
@@ -68,9 +70,12 @@ type Room struct {
Countdown int
NextStart time.Time
HostID string
TeamName string // Name des Teams (vom Host gesetzt)
CollectedCoins map[string]bool // Key: "chunkID_objectIndex"
CollectedPowerups map[string]bool // Key: "chunkID_objectIndex"
ScoreAccum float64 // Akkumulator für Distanz-Score
CurrentSpeed float64 // Aktuelle Geschwindigkeit (steigt mit der Zeit)
GameStartTime time.Time // Wann das Spiel gestartet wurde
// Chunk-Pool für fairen Random-Spawn
ChunkPool []string // Verfügbare Chunks für nächsten Spawn
@@ -100,7 +105,8 @@ func NewRoom(id string, nc *nats.Conn, w *game.World) *Room {
CollectedCoins: make(map[string]bool),
CollectedPowerups: make(map[string]bool),
ChunkSpawnedCount: make(map[string]int),
pW: 40, pH: 60, // Fallback
CurrentSpeed: config.RunSpeed, // Startet mit normaler Geschwindigkeit
pW: 40, pH: 60, // Fallback
}
// Initialisiere Chunk-Pool mit allen verfügbaren Chunks
@@ -281,6 +287,12 @@ func (r *Room) HandleInput(input game.ClientInput) {
if input.PlayerID == r.HostID && r.Status == "LOBBY" {
r.StartCountdown()
}
case "SET_TEAM_NAME":
// Nur Host darf Team-Name setzen und nur in der Lobby
if input.PlayerID == r.HostID && r.Status == "LOBBY" {
r.TeamName = input.TeamName
log.Printf("🏷️ Team-Name gesetzt: '%s' (von Host %s)", r.TeamName, p.Name)
}
}
}
@@ -301,9 +313,19 @@ func (r *Room) Update() {
r.Countdown = int(rem.Seconds()) + 1
if rem <= 0 {
r.Status = "RUNNING"
r.GameStartTime = time.Now()
r.CurrentSpeed = config.RunSpeed
}
} else if r.Status == "RUNNING" {
r.GlobalScrollX += config.RunSpeed
// Geschwindigkeit erhöhen: +0.5 pro 10 Sekunden (max +5.0 nach 100 Sekunden)
elapsed := time.Since(r.GameStartTime).Seconds()
speedIncrease := (elapsed / 10.0) * 0.5
if speedIncrease > 5.0 {
speedIncrease = 5.0
}
r.CurrentSpeed = config.RunSpeed + speedIncrease
r.GlobalScrollX += r.CurrentSpeed
// Bewegende Plattformen updaten
r.UpdateMovingPlatforms()
}
@@ -333,9 +355,9 @@ func (r *Room) Update() {
// X Bewegung
// Symmetrische Geschwindigkeit: Links = Rechts
// Nach rechts: RunSpeed + 11, Nach links: RunSpeed - 11
// Ergebnis: Rechts = 18, Links = -4 (beide gleich weit vom Scroll)
currentSpeed := config.RunSpeed + (p.InputX * 11.0)
// Nach rechts: CurrentSpeed + 11, Nach links: CurrentSpeed - 11
// Verwendet r.CurrentSpeed statt config.RunSpeed für dynamische Geschwindigkeit
currentSpeed := r.CurrentSpeed + (p.InputX * 11.0)
nextX := p.X + currentSpeed
hitX, typeX := r.CheckCollision(nextX+r.pDrawOffX+r.pHitboxOffX, p.Y+r.pDrawOffY+r.pHitboxOffY, r.pW, r.pH)
@@ -343,7 +365,7 @@ func (r *Room) Update() {
if typeX == "wall" {
// Wand getroffen - kann klettern!
p.OnWall = true
// X-Position nicht ändern (bleibt an der Wand)
// X-Position NICHT ändern (bleibt vor der Wand stehen)
} else if typeX == "obstacle" {
// Godmode prüfen
if p.HasGodMode && time.Now().Before(p.GodModeEndTime) {
@@ -405,15 +427,9 @@ func (r *Room) Update() {
hitY, typeY := r.CheckCollision(p.X+r.pDrawOffX+r.pHitboxOffX, nextY+r.pDrawOffY+r.pHitboxOffY, r.pW, r.pH)
if hitY {
if typeY == "wall" {
// An der Wand: Nicht töten, sondern Position halten
if p.OnWall {
p.VY = 0
} else {
// Von oben/unten gegen Wand - töten (kein Klettern in Y-Richtung)
p.Y = nextY
r.KillPlayer(p)
continue
}
// An der Wand: Nicht töten, Position halten und klettern ermöglichen
p.VY = 0
p.OnWall = true
} else if typeY == "obstacle" {
// Obstacle - immer töten
p.Y = nextY
@@ -774,6 +790,7 @@ func (r *Room) Broadcast() {
TimeLeft: r.Countdown,
WorldChunks: r.ActiveChunks,
HostID: r.HostID,
TeamName: r.TeamName,
ScrollX: r.GlobalScrollX,
CollectedCoins: r.CollectedCoins,
CollectedPowerups: r.CollectedPowerups,

View File

@@ -60,7 +60,8 @@ func (r *Room) CheckCoinCollision(p *ServerPlayer) {
if game.CheckRectCollision(playerHitbox, coinHitbox) {
// Coin einsammeln!
r.CollectedCoins[coinKey] = true
p.Score += 200
p.BonusScore += 200
p.Score = p.DistanceScore + p.BonusScore
log.Printf("💰 %s hat Coin eingesammelt! Score: %d", p.Name, p.Score)
}
}
@@ -143,18 +144,28 @@ func (r *Room) UpdateDistanceScore() {
return
}
// Jeder Spieler bekommt Punkte basierend auf seiner eigenen Distanz
// Punkte = (X-Position / TileSize) = Distanz in Tiles
// Zähle lebende Spieler
aliveCount := 0
for _, p := range r.Players {
if p.IsAlive && !p.IsSpectator {
// Berechne Score basierend auf X-Position
// 1 Punkt pro Tile (64px)
newScore := int(p.X / 64.0)
aliveCount++
}
}
// Nur updaten wenn höher als aktueller Score
if newScore > p.Score {
p.Score = newScore
}
if aliveCount == 0 {
return
}
// Pro lebendem Spieler werden Punkte hinzugefügt
// Dies akkumuliert die Punkte: mehr Spieler = schnellere Punktesammlung
// Jeder Tick (bei 60 FPS) fügt aliveCount Punkte hinzu
pointsToAdd := aliveCount
// Jeder lebende Spieler bekommt die gleichen Punkte
for _, p := range r.Players {
if p.IsAlive && !p.IsSpectator {
p.DistanceScore += pointsToAdd
p.Score = p.DistanceScore + p.BonusScore
}
}
}