func gameResultHandler(r *http.Request, w http.ResponseWriter, redis *models.RedisLogger, user *models.Account, p Parameter) { form := p.(gameResultForm) var respData struct { Total []*leaderboardResp `json:"total_list"` Friends []*leaderboardResp `json:"friends_list"` Score int `json:"total_score"` Percent int `json:"percent"` PerFriend int `json:"percentFri"` } if form.Count == 0 { form.Count = 3 } gt := gameType(form.Type) if scores := redis.UserGameScores(gt, user.Id); len(scores) == 1 { respData.Score = int(scores[0]) } redis.SetGameScore(gt, user.Id, form.Score) // current score kvs := redis.GameScores(gt, 0, form.Count) var ids []string for _, kv := range kvs { ids = append(ids, kv.K) } ranks := redis.UserGameRanks(gt, user.Id) redis.SetGameScore(gt, user.Id, respData.Score) // recover max score n := redis.GameUserCount(gt) - 1 //log.Println(ranks, n) if len(ranks) == 1 && n > 0 && form.Score > 0 { respData.Percent = int(float64(n-ranks[0]) / float64(n) * 100.0) } //log.Println(ids) users, _ := models.FindUsersByIds(1, ids...) index := 0 for _, kv := range kvs { for i, _ := range users { if users[i].Id == kv.K { respData.Total = append(respData.Total, &leaderboardResp{ Userid: users[i].Id, Score: kv.V, Rank: index + 1, Level: users[i].Level(), Profile: users[i].Profile, Nickname: users[i].Nickname, Gender: users[i].Gender, LastLog: users[i].LastGameTime(gt).Unix(), Birth: users[i].Birth, Location: users[i].Loc, Phone: users[i].Phone, Actor: users[i].Actor, }) index++ break } } } ids = redis.Friends(models.RelFriend, user.Id) if len(ids) > 0 { total := len(ids) ids = append(ids, user.Id) scores := redis.UserGameScores(gt, ids...) if len(scores) != len(ids) { scores = make([]int64, total) } kvs = make([]models.KV, total+1) for i, _ := range ids { kvs[i].K = ids[i] kvs[i].V = scores[i] if ids[i] == user.Id { kvs[i].V = int64(form.Score) } } sort.Sort(sort.Reverse(models.KVSlice(kvs))) lb := kvs if len(kvs) > 3 { kvs = kvs[0:3] } ids = []string{} for _, kv := range kvs { ids = append(ids, kv.K) } users, _ = models.FindUsersByIds(1, ids...) index := 0 rank := 0 for i, _ := range lb { if lb[i].K == user.Id { rank = i break } } for _, kv := range kvs { for i, _ := range users { if users[i].Id == kv.K { respData.Friends = append(respData.Friends, &leaderboardResp{ Userid: users[i].Id, Score: kv.V, Rank: index + 1, Level: users[i].Level(), Profile: users[i].Profile, Nickname: users[i].Nickname, Gender: users[i].Gender, LastLog: users[i].LastGameTime(gt).Unix(), Birth: users[i].Birth, Location: users[i].Loc, Phone: users[i].Phone, Actor: users[i].Actor, }) index++ break } } } if total > 0 { respData.PerFriend = int(float64(total-rank) / float64(total) * 100.0) } } writeResponse(r.RequestURI, w, respData, nil) }