game_op.go 1.8 KB
Newer Older
chenweijian's avatar
chenweijian committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
package user_m

import (
	"hilo-user/_const/enum/user_e"
	"hilo-user/domain"
	"hilo-user/resource/mysql"
	"sort"
	"time"
)

type StartGamePlayer struct {
	TxGroupId   mysql.Str // 房间id
	GameId      mysql.ID  // 游戏id
	MgId        mysql.Str // 游戏sdk id
	UserId      mysql.ID  // 用户id
	CreatedTime time.Time // 加入游戏时间
}

// 获取可以开始的游戏
// condition
//	1. 游戏还没开始
//  2. 游戏人数大于等于2个
//  3. 第二个加入的人距离现在已经超过15秒
func GetCanStartGames(model *domain.Model) []GameInfo {
	//	1. 游戏还没开始
	sql := "SELECT g.tx_group_id,p.user_id,g.mg_id,p.user_id,p.created_time FROM `user_info` g,`user_player` p where p.user_id = g.id AND g.`status` = ?;"
	var startGamePlayers []StartGamePlayer
	if err := model.DB().Raw(sql, user_e.GameStatusNoStart).Find(&startGamePlayers).Error; err != nil {
		model.Log.Errorf("GetCanStartGames fail,sql:%v,err:%v", sql, err)
		return nil
	}
	// userId -> userPlayer
	var startGamePlayersMap = make(map[mysql.ID][]StartGamePlayer)
	for i, p := range startGamePlayers {
		startGamePlayersMap[p.GameId] = append(startGamePlayersMap[p.GameId], startGamePlayers[i])
	}
	var res []GameInfo
	for userId, players := range startGamePlayersMap {
		//  2. 游戏人数大于等于2个
		if len(players) < 2 {
			continue
		}
		model.Log.Infof("startGamePlayer,userId:%v,player:%+v", userId, players)
		//  3. 第二个加入的人距离现在已经超过15秒
		sort.Slice(players, func(i, j int) bool {
			return players[i].CreatedTime.Before(players[j].CreatedTime)
		})
		// 客户端15秒,服务端延迟1秒
		if time.Now().Sub(players[1].CreatedTime).Seconds() >= 16 {
			res = append(res, GameInfo{
				Id:        userId,
				MgId:      players[1].MgId,
				TxGroupId: players[1].TxGroupId,
			})
		}
	}
	return res
}