Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make player.Dead a send ONLY channel #29

Merged
merged 1 commit into from
Sep 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,11 @@ func wsHandler(ws *websocket.Conn) {
defer ws.Close()

var clientIp = ws.Request().RemoteAddr
deadChan := make(chan bool, 1)
p := &player.Player{
Conn: ws,
Pieces: make([]int32, 12),
Dead: make(chan bool, 1),
Dead: deadChan,
}
defer close(p.Dead)

Expand All @@ -46,7 +47,7 @@ func wsHandler(ws *websocket.Conn) {
lobby <- p

log.Println("Someone connected", clientIp, "Total players:", numPlayers.Load())
<-p.Dead // block until player exits
<-deadChan // block until player exits
numPlayers.Add(^uint32(0)) // if player exits, minus 1
log.Println(p.Name, "just left the game. Total players:", numPlayers.Load())
}
Expand Down Expand Up @@ -128,7 +129,7 @@ func listenForJoins() {
p1.Dead <- true

case <-p1.Quit:
//p1 has quit before match began
//p1 has quit before match started
cancel()
p1.Dead <- true
}
Expand Down
8 changes: 4 additions & 4 deletions player/member.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ type Player struct {
Conn *websocket.Conn // client's WS connection
Name string // Name can only be RED or BLACK
Pieces []int32 // pieces IDs owned by this player. Max count 12
Dead chan bool // to signal layer was kicked out or left AFTER match START
Quit <-chan bool // to detect player has quit BEFORE match started
Dead chan<- bool // to signal this player was kicked out or left AFTER match starts
Quit <-chan bool // to detect player has quit BEFORE match starts
}

// pingCodec is used to send Ping msg to client
Expand All @@ -27,7 +27,7 @@ var pingCodec = websocket.Codec{Marshal: func(v interface{}) (data []byte, paylo
func (p *Player) SendMessage(payload proto.Message) {
bb, err := proto.Marshal(payload)
if err != nil {
log.Println("Failed to Marhal message", err)
log.Println("Failed to Marshal message", err)
p.Dead <- true
}
if err := websocket.Message.Send(p.Conn, bb); err != nil {
Expand Down Expand Up @@ -60,7 +60,7 @@ func (p *Player) StartHeartBeat(ctx context.Context) {
select {
case <-tt.C:
if err := pingCodec.Send(p.Conn, nil); err != nil {
//p has left early
//This player has quit early
qq <- true
return
}
Expand Down
Loading