Skip to content

Commit

Permalink
prijava in odjava iz turnirja malo lepše
Browse files Browse the repository at this point in the history
  • Loading branch information
mytja committed Jan 28, 2024
1 parent 11ba5c4 commit 0c8179e
Show file tree
Hide file tree
Showing 9 changed files with 168 additions and 12 deletions.
2 changes: 1 addition & 1 deletion backend/internal/consts/consts.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,5 +170,5 @@ var GAMES = []Game{

const TOURNAMENT_GAME_END_TIMEOUT = 10
const TOURNAMENT_SOFT_TIMEOUT_EXTENSION = 400
const TALON_OPEN_TIME_PART = 0.18
const TALON_OPEN_TIME_PART = 0.2
const TALON_TIMEOUT = 3
17 changes: 17 additions & 0 deletions backend/internal/httphandlers/tournament.go
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,18 @@ func (s *httpImpl) NewTournament(w http.ResponseWriter, r *http.Request) {
return
}

// ogabno
// TODO: znebi se te katastrofe
t, err := s.db.GetTournamentByArgs(startTime, division, name)
if err != nil {
s.sugared.Errorw("error while fetching tournament. could not start tournament organizer", "err", err)
w.WriteHeader(http.StatusInternalServerError)
return
}

to := tournament2.NewTournament(t.ID, s.sugared, s.db, s.wsServer, startTime, false, "")
go to.RunOrganizer()

w.WriteHeader(http.StatusOK)
}

Expand Down Expand Up @@ -399,6 +411,11 @@ func (s *httpImpl) UpdateTournament(w http.ResponseWriter, r *http.Request) {
return
}

if startTime != tournament.StartTime {
to := tournament2.NewTournament(tournamentId, s.sugared, s.db, s.wsServer, startTime, false, "")
defer func() { go to.RunOrganizer() }()
}

tournament.StartTime = startTime

division, err := strconv.Atoi(r.FormValue("division"))
Expand Down
19 changes: 10 additions & 9 deletions backend/internal/httphandlers/tournament_participant.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"github.com/mytja/Tarok/backend/internal/events"
"github.com/mytja/Tarok/backend/internal/helpers"
sql2 "github.com/mytja/Tarok/backend/internal/sql"
tournament2 "github.com/mytja/Tarok/backend/internal/tournament"
Expand Down Expand Up @@ -89,13 +91,17 @@ func (s *httpImpl) RemoveParticipation(w http.ResponseWriter, r *http.Request) {
return
}

// 5 minut pred začetkom se zaprejo odjave
if tournament.StartTime < int(time.Now().Unix()*1000)+300_000*3 {
// Po začetku turnirja se zaprejo odjave
if tournament.StartTime < int(time.Now().Unix()*1000) {
s.sugared.Errorw("the registration is closed", "err", err, "tournamentId", tournamentId)
w.WriteHeader(http.StatusForbidden)
return
}

s.sugared.Debugw("sending destroyGame", "tournamentId", tournamentId)
events.Publish(fmt.Sprintf("tournament.%s.destroyGame", tournamentId), user.ID)
s.sugared.Debugw("sent destroyGame", "tournamentId", tournamentId)

tournamentUser, err := s.db.GetTournamentParticipantByTournamentUser(tournamentId, participantId)
if err != nil {
w.WriteHeader(http.StatusNotFound)
Expand Down Expand Up @@ -143,13 +149,6 @@ func (s *httpImpl) AddParticipation(w http.ResponseWriter, r *http.Request) {
return
}

// 5 minut pred začetkom se zaprejo prijave
if tournament.StartTime < int(time.Now().Unix()*1000)+300_000*3 {
s.sugared.Errorw("the registration is closed", "err", err, "tournamentId", tournamentId)
w.WriteHeader(http.StatusForbidden)
return
}

_, err = s.db.GetTournamentParticipantByTournamentUser(tournamentId, user.ID)
if err == nil {
s.sugared.Errorw("participant is already registered", "err", err, "tournamentId", tournamentId)
Expand Down Expand Up @@ -177,6 +176,8 @@ func (s *httpImpl) AddParticipation(w http.ResponseWriter, r *http.Request) {
return
}

events.Publish(fmt.Sprintf("tournament.%s.createGame", tournamentId), user.ID)

WriteJSON(w, map[string]string{}, http.StatusCreated)
}

Expand Down
1 change: 1 addition & 0 deletions backend/internal/sql/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ type SQL interface {
GetGames() (games []Game, err error)

GetTournament(id string) (tournament Tournament, err error)
GetTournamentByArgs(startTime int, division int, name string) (tournament Tournament, err error)
InsertTournament(tournament Tournament) (err error)
GetAllTournaments() (tournament []Tournament, err error)
GetAllNotStartedTournaments() (tournament []Tournament, err error)
Expand Down
5 changes: 5 additions & 0 deletions backend/internal/sql/tournament.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ func (db *sqlImpl) GetTournament(id string) (tournament Tournament, err error) {
return tournament, err
}

func (db *sqlImpl) GetTournamentByArgs(startTime int, division int, name string) (tournament Tournament, err error) {
err = db.db.Get(&tournament, "SELECT * FROM tournament WHERE start_time=$1 AND division=$2 AND name=$name", startTime, division, name)
return tournament, err
}

func (db *sqlImpl) InsertTournament(tournament Tournament) (err error) {
s := `INSERT INTO tournament (
created_by,
Expand Down
125 changes: 124 additions & 1 deletion backend/internal/tournament/goroutine.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package tournament

import (
"fmt"
"github.com/mytja/Tarok/backend/internal/consts"
"github.com/mytja/Tarok/backend/internal/events"
"github.com/mytja/Tarok/backend/internal/messages"
"github.com/mytja/Tarok/backend/internal/ws"
"sort"
"strings"
"time"
)

Expand Down Expand Up @@ -43,7 +45,9 @@ func (s *tournamentImpl) OpenLobbies() {
return
}

if !s.test && tournament.StartTime/1000 > s.startTime {
s.logger.Debugw("start times", "startTime", s.startTime, "tStartTime", tournament.StartTime)

if !s.test && tournament.StartTime/1000 != s.startTime {
s.startTime = tournament.StartTime
s.openedLobbies = false

Expand Down Expand Up @@ -266,6 +270,11 @@ func (s *tournamentImpl) EndTournament() {
func (s *tournamentImpl) StartGame() bool {
s.round++

for i, v := range s.queuedGames {
s.games[i] = v
delete(s.queuedGames, i)
}

s.logger.Infow("starting new tournament round", "tournamentId", s.tournamentId, "round", s.round)

round, err := s.db.GetTournamentRoundByTournamentNumber(s.tournamentId, s.round)
Expand Down Expand Up @@ -319,8 +328,121 @@ func (s *tournamentImpl) HardTimeoutRunningGames() {
}
}

func (s *tournamentImpl) DestroyGame(playerId string) {
if !s.openedLobbies {
s.logger.Debugw("lobbies haven't opened yet")
return
}

s.logger.Debugw("destroying a game for player", "playerId", playerId)

for i, v := range s.games {
if v == nil {
continue
}
s.logger.Debugw("checking game for destruction", "gameId", i)
found := false
for _, l := range v.Players {
if strings.Contains(l.GetUser().ID, "bot") {
continue
}
if l.GetUser().ID == playerId {
found = true
break
}
}
if !found {
continue
}
s.logger.Debugw("destroying game", "gameId", i)
// da se izognemo zamaševanju eventbusa mora biti to gorutina
go s.wsServer.EndGame(i)
delete(s.games, i)
break
}
}

func (s *tournamentImpl) CreateGame(playerId string) {
if !s.openedLobbies {
s.logger.Debugw("lobbies haven't opened yet")
return
}

user, err := s.db.GetUser(playerId)
if err != nil {
s.logger.Errorw("failure while fetching user from the database", "err", err, "userId", playerId, "tournamentId", s.tournamentId)
return
}

rounds, err := s.db.GetAllTournamentRounds(s.tournamentId)
if err != nil {
s.logger.Errorw("failure while fetching tournament rounds", "err", err, "tournamentId", s.tournamentId)
return
}
if len(rounds) == 0 {
s.logger.Errorw("failure: no tournament rounds", "err", err, "tournamentId", s.tournamentId)
return
}

if len(rounds) == s.round {
s.logger.Errorw("failure: cannot sign up. Too late", "err", err, "tournamentId", s.tournamentId)
return
}

round1 := rounds[0]
gameId := s.wsServer.NewGame(4, "normal", true, playerId, 0, round1.Time, false, false, false, len(rounds)-s.round)
var game *ws.Game
if s.roundStarted {
s.queuedGames[gameId] = s.wsServer.GetGame(gameId)
game = s.queuedGames[gameId]
} else {
s.games[gameId] = s.wsServer.GetGame(gameId)
game = s.games[gameId]
}
game.TournamentID = s.tournamentId
game.Players[playerId] = ws.NewUser(playerId, user, s.logger)
game.Players[playerId].SetBotStatus(true)
game.Players[playerId].SetTimer(float64(game.StartTime) * (1 + consts.TALON_OPEN_TIME_PART))

s.wsServer.ManuallyStartGame(playerId, gameId)
game.GameCount = 0

// jebeš eventbus
go func() {
time.Sleep(100 * time.Millisecond)
events.Publish("lobby.newPrivateGame", gameId, playerId)
}()

s.logger.Debugw("created a game", "gameId", gameId)
}

func (s *tournamentImpl) handleEvents() {
err := events.Subscribe(fmt.Sprintf("tournament.%s.createGame", s.tournamentId), s.CreateGame)
if err != nil {
s.logger.Warnw("cannot read from the client")
}
err = events.Subscribe(fmt.Sprintf("tournament.%s.destroyGame", s.tournamentId), s.DestroyGame)
if err != nil {
s.logger.Warnw("cannot read from the client")
}
}

func (s *tournamentImpl) unsubscribeEvents() {
s.logger.Debugw("unsubscribing from tournament events", "tournamentId", s.tournamentId)

err := events.Unsubscribe(fmt.Sprintf("tournament.%s.createGame", s.tournamentId), s.CreateGame)
if err != nil {
s.logger.Warnw("cannot read from the client")
}
err = events.Unsubscribe(fmt.Sprintf("tournament.%s.destroyGame", s.tournamentId), s.DestroyGame)
if err != nil {
s.logger.Warnw("cannot read from the client")
}
}

func (s *tournamentImpl) RunOrganizer() {
s.logger.Infow("starting tournament organizer goroutine", "tournamentId", s.tournamentId)
s.handleEvents()

if s.test {
s.logger.Infow("running a virtual (testing) tournament", "tournamentId", s.tournamentId, "user", s.testerId)
Expand Down Expand Up @@ -388,5 +510,6 @@ func (s *tournamentImpl) RunOrganizer() {
time.Sleep(1 * time.Second)
}

s.unsubscribeEvents()
s.logger.Infow("exiting tournament organizer goroutine. tournament is now officially over", "tournamentId", s.tournamentId)
}
2 changes: 2 additions & 0 deletions backend/internal/tournament/impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ type tournamentImpl struct {
wsServer ws.Server
tournamentId string
games map[string]*ws.Game
queuedGames map[string]*ws.Game
openedLobbies bool
round int
startTime int
Expand All @@ -37,6 +38,7 @@ func NewTournament(tournamentId string, logger *zap.SugaredLogger, db sql.SQL, w
startTime: startTime / 1000,
roundStarted: false,
games: make(map[string]*ws.Game),
queuedGames: make(map[string]*ws.Game),
nextRoundTime: 0,
test: test,
testerId: testerId,
Expand Down
2 changes: 1 addition & 1 deletion backend/internal/ws/bots.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package ws

var BOT_NAMES = []string{"Tim", "Nik", "Gal", "Anže", "Mark", "Žiga", "Ana", "Lojze", "Janez", "Marija", "Jože", "Maja", "Mojca"}
var BOT_NAMES = []string{"Tim", "Nik", "Gal", "Anže", "Mark", "Žiga", "Ana", "Lojze", "Janez", "Marija", "Jože", "Maja", "Mojca", "Bor"}
7 changes: 7 additions & 0 deletions backend/internal/ws/gameend.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import (
)

func (s *serverImpl) EndGame(gameId string) {
s.logger.Debugw("ending the game", "gameId", gameId)

game, exists := s.games[gameId]
if !exists {
events.Publish("lobby.broadcast", &lobby_messages.LobbyMessage{Data: &lobby_messages.LobbyMessage_GameDisbanded{GameDisbanded: &lobby_messages.GameDisbanded{GameId: gameId}}})
Expand All @@ -32,6 +34,8 @@ func (s *serverImpl) EndGame(gameId string) {
return
}

s.logger.Debugw("calculating final results of the game", "gameId", gameId)

results := make([]*messages.ResultsUser, 0)
for u, user := range game.Players {
if !user.GetBotStatus() && game.Started {
Expand Down Expand Up @@ -94,13 +98,16 @@ func (s *serverImpl) EndGame(gameId string) {
User: results,
}}}}})

s.logger.Debugw("game is ending", "gameId", gameId)
game.Ending = true

time.Sleep(200 * time.Millisecond)
events.Publish("lobby.broadcast", &lobby_messages.LobbyMessage{Data: &lobby_messages.LobbyMessage_GameDisbanded{GameDisbanded: &lobby_messages.GameDisbanded{GameId: gameId}}})
time.Sleep(3 * time.Second) // nekaj spanca, preden izbrišemo vse skupaj.
delete(s.games, gameId)
s.logger.Debugw("deleted the game from the map", "gameId", gameId)
events.Publish("lobby.broadcast", &lobby_messages.LobbyMessage{Data: &lobby_messages.LobbyMessage_GameDisbanded{GameDisbanded: &lobby_messages.GameDisbanded{GameId: gameId}}})
s.logger.Debugw("successfully ended the game", "gameId", gameId)
}

func (s *serverImpl) GameAddRounds(userId string, gameId string, rounds int) {
Expand Down

0 comments on commit 0c8179e

Please sign in to comment.