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 gameOver chan write only #30

Merged
merged 1 commit into from
Oct 7, 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
42 changes: 21 additions & 21 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,30 @@ import (
"golang.org/x/net/websocket"
)

const SERVER_VERSION = "2024.7.0"

const SERVER_VERSION = "1.0.8"
const maxRequestSize int = 1 << 10 //1KB

var numPlayers atomic.Uint32 // total number of LIVE players
var lobby = make(chan *player.Player, 2) // waiting room for players

func main() {
portNum, err := strconv.Atoi(os.Getenv("PORT"))
if err != nil {
portNum = 9876
}
port := strconv.Itoa(portNum)

http.HandleFunc("/", func(writer http.ResponseWriter, r *http.Request) {
fmt.Fprintf(writer, `<p>This is a socket server. Dial ws://%s:%s/game </p>`, r.URL.Host, port)
})

http.Handle("/game", websocket.Handler(wsHandler))

go listenForJoins()
log.Println("Server listening at http://localhost:" + port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}

// wsHandler handles every new WS connection and redirects Player to Lobby
func wsHandler(ws *websocket.Conn) {
ws.MaxPayloadBytes = maxRequestSize
Expand Down Expand Up @@ -52,24 +69,7 @@ func wsHandler(ws *websocket.Conn) {
log.Println(p.Name, "just left the game. Total players:", numPlayers.Load())
}

func main() {
portNum, err := strconv.Atoi(os.Getenv("PORT"))
if err != nil {
portNum = 9876
}
port := strconv.Itoa(portNum)

http.HandleFunc("/", func(writer http.ResponseWriter, r *http.Request) {
fmt.Fprintf(writer, `<p>This is a socket server. Dial ws://%s:%s/game </p>`, r.URL.Host, port)
})
http.Handle("/game", websocket.Handler(wsHandler))

go listenForJoins()
log.Println("Server listening at http://localhost:" + port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}

// Keep Listening for new players joining lobby
// Keep Listening for new players joining lobby. Then forward a pair to new match room
func listenForJoins() {
for {
//welcome 1st player
Expand All @@ -85,7 +85,7 @@ func listenForJoins() {
},
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
go p1.StartHeartBeat(ctx)
go p1.StartHeartbeat(ctx)
p1.SendMessage(msgOne)

//waiting for 2nd player to join (TIMEOUT at 30 seconds)
Expand Down
6 changes: 3 additions & 3 deletions player/member.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
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
Pieces []int32 // pieces IDs owned by this player. Max size 12
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
}
Expand Down Expand Up @@ -51,8 +51,8 @@ func (p *Player) HasThisPiece(pieceId int32) bool {
return slices.Contains(p.Pieces, pieceId)
}

// StartHeartBeat keeps checking if this player is still connected (when waiting for opponent)
func (p *Player) StartHeartBeat(ctx context.Context) {
// StartHeartbeat keeps checking (every second) if this player is still connected (when waiting for opponent)
func (p *Player) StartHeartbeat(ctx context.Context) {
tt := time.NewTicker(time.Second)
qq := make(chan bool)
p.Quit = qq
Expand Down
2 changes: 1 addition & 1 deletion room/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func generateGameMap(p1 *player.Player, p2 *player.Player) map[int32]*game.Piece
}

// GeneratePlayerPieces using Secure RNG for both player 1 (RED) and player 2 (BLACK)
func generatePlayerPieces(p1 *player.Player, p2 *player.Player, gameOver chan bool) {
func generatePlayerPieces(p1 *player.Player, p2 *player.Player, gameOver chan<- bool) {
for i := 0; i < len(p1.Pieces); i++ {
val, err := rand.Int(rand.Reader, big.NewInt(int64(upperLimit)))
if err != nil {
Expand Down
14 changes: 7 additions & 7 deletions room/room.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
)

// RunMatch between the two players `p1` and `p2`. If match ends, send signal through `gameOver` channel
func RunMatch(p1 *player.Player, p2 *player.Player, gameOver chan bool) {
func RunMatch(p1 *player.Player, p2 *player.Player, gameOver chan<- bool) {
log.Println("🟢 Match has begun!")

//make random pieceId's for both
Expand Down Expand Up @@ -45,7 +45,7 @@ func RunMatch(p1 *player.Player, p2 *player.Player, gameOver chan bool) {
if isPlayerRedTurn {
// ============= IT'S PLAYER 1 (RED's) TURN =============//
var rawBytes []byte
p1.Conn.SetReadDeadline(time.Now().Add(time.Second * 30))
p1.Conn.SetReadDeadline(time.Now().Add(time.Second * 40))
if err := websocket.Message.Receive(p1.Conn, &rawBytes); err != nil {
log.Println(p1.Name, "disconnected. Cause:", err)
p2.SendMessage(&game.BasePayload{
Expand All @@ -69,7 +69,7 @@ func RunMatch(p1 *player.Player, p2 *player.Player, gameOver chan bool) {

//if MESSAGE TYPE == "move"
if payload.GetMovePayload() != nil {
log.Println("move", payload.GetMovePayload().String())
//log.Println("move", payload.GetMovePayload().String())
valid := processMovePiece(&payload, gameMap, p1, p2)
if !valid {
gameOver <- true
Expand All @@ -78,7 +78,7 @@ func RunMatch(p1 *player.Player, p2 *player.Player, gameOver chan bool) {
isPlayerRedTurn = false
} else if payload.GetCapturePayload() != nil {
//if MESSAGE TYPE == "capture"
log.Println("capture", payload.GetCapturePayload().String())
//log.Println("capture", payload.GetCapturePayload().String())
isKingBefore := getKingStatusBefore(payload.GetCapturePayload(), gameMap)
valid := processCapturePiece(&payload, gameMap, p1, p2)
if !valid {
Expand All @@ -103,7 +103,7 @@ func RunMatch(p1 *player.Player, p2 *player.Player, gameOver chan bool) {
} else if !isPlayerRedTurn {
// ============= IT'S PLAYER 2 (BLACK's) TURN =============//
var rawBytes []byte
p2.Conn.SetReadDeadline(time.Now().Add(time.Second * 30))
p2.Conn.SetReadDeadline(time.Now().Add(time.Second * 40))
if err := websocket.Message.Receive(p2.Conn, &rawBytes); err != nil {
log.Println(p2.Name, "disconnected. Cause:", err.Error())
p1.SendMessage(&game.BasePayload{
Expand All @@ -127,7 +127,7 @@ func RunMatch(p1 *player.Player, p2 *player.Player, gameOver chan bool) {

//if MESSAGE TYPE == "move"
if payload.GetMovePayload() != nil {
log.Println("move", payload.GetMovePayload().String())
//log.Println("move", payload.GetMovePayload().String())
valid := processMovePiece(&payload, gameMap, p2, p1)
if !valid {
gameOver <- true
Expand All @@ -136,7 +136,7 @@ func RunMatch(p1 *player.Player, p2 *player.Player, gameOver chan bool) {
isPlayerRedTurn = true
} else if payload.GetCapturePayload() != nil {
//if MESSAGE TYPE == "capture"
log.Println("capture", payload.GetCapturePayload().String())
//log.Println("capture", payload.GetCapturePayload().String())
isKingBefore := getKingStatusBefore(payload.GetCapturePayload(), gameMap)
valid := processCapturePiece(&payload, gameMap, p2, p1)
if !valid {
Expand Down
Loading