Commit 5734382e authored by ceddral's avatar ceddral
Browse files

remove players on disconnect if applicable

from lobby, always
from game, if game is empty
parent 58275d96
......@@ -394,11 +394,30 @@ func (g *Game) Register(glp *Player) {
}
func (g *Game) Unregister(name string) {
defer g.broadcastState(nil)
g.Lock()
p := g.players[name]
defer g.Unlock()
p, ok := g.players[name]
if !ok {
return
}
p.lostConnection = true
g.Unlock()
g.broadcastState(nil)
anyoneConnected := false
for _, p := range g.players {
if !p.lostConnection {
anyoneConnected = true
}
}
if !anyoneConnected {
// no one connected anymore
// remove game and all associated players
for name, p := range g.players {
p.gameKill <- struct{}{}
delete(g.players, name)
glp := gs.players[name]
glp.Close()
}
}
}
func (g *Game) Resize(w, h int, glp *Player) {
......@@ -430,6 +449,9 @@ func (g *Game) Loop(p *GamePlayer, initState GameState) {
state.patientTransition(p)
}
case input := <-p.inputEvent:
if input == nil {
break
}
key := toKey(input)
if key == keyRedraw || key == ' ' {
fullRedraw = true
......
......@@ -55,12 +55,17 @@ func (gl *GameLobby) Register(glp *Player) {
gl.Unlock()
}
// Unregister (without lock) is called on disconnect
func (gl *GameLobby) Unregister(name string) {
gl.Lock()
gl.unregisterUnlocked(name)
gl.Unlock()
glp := gs.players[name]
glp.Close()
}
// unregisterUnlocked is called on disconnect as well
// as switching context
func (gl *GameLobby) unregisterUnlocked(name string) {
p, ok := gl.players[name]
if !ok {
......
......@@ -97,14 +97,16 @@ func NewPlayer(conn net.Conn) (p *Player) {
}
func (p *Player) Close() {
p.inputKill <- struct{}{}
// do not wait for inputLoop termination (inputKill <- struct{}{})
// as Close is and must be only called from within inputLoop
close(p.inputKill)
p.conn.Close()
p.windowSizeLoopKill <- struct{}{}
p.windowSizeLoopKill <- struct{}{}
close(p.connClosed)
close(p.inputKill)
close(p.inputEvent)
close(p.windowSizeLoopKill)
delete(gs.players, p.name)
}
func StopTimer(t *time.Timer) {
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment