Ejemplo n.º 1
0
u16 Game::GetGameOverScores(void)
{
    Settings & conf = Settings::Get();

    u8 k_size = 0;

    switch(conf.MapsWidth())
    {
	case Maps::SMALL:	k_size = 140; break;
	case Maps::MEDIUM:	k_size = 100; break;
	case Maps::LARGE:	k_size =  80; break;
	case Maps::XLARGE:	k_size =  60; break;
	default: break;
    }

    u8 flag = 0;
    u8 nk = 0;
    u16 end_days = world.CountDay();

    for(u16 ii = 1; ii <= end_days; ++ii)
    {
	nk = ii * k_size / 100;

	if(0 == flag && nk > 60){ end_days = ii + (world.CountDay() - ii) / 2; flag = 1; }
	else
	if(1 == flag && nk > 120) end_days = ii + (world.CountDay() - ii) / 2;
	else
	if(nk > 180) break;
    }

    return GetRating() * (200 - nk) / 100;
}
Ejemplo n.º 2
0
QString CPlayer::replace_tokens(QString str, bool hidePlayingState)
{
    QString status_text = "";
    switch(GetState())
    {
    case PLAYER_STOPPED:
        if(GetPlayer()=="")
            status_text = "";
        else
            status_text = "Stopped";
        break;
    case PLAYER_PAUSED:
        status_text = "Paused";
        break;
    case PLAYER_PLAYING:
        status_text = (hidePlayingState? "" : "Playing");
        break;
    }

    replace_token(str,"title"    ,GetTitle());
    replace_token(str,"artist"   ,GetArtist());
    replace_token(str,"album"    ,GetAlbum());
    replace_token(str,"duration" ,GetDuration(),GetDuration());
    replace_token(str,"played"   ,GetPosition(),GetDuration());
    replace_token(str,"remaining",GetDuration() - GetPosition(),GetDuration());
    replace_token(str,"status"   ,status_text);
    replace_token(str,"player"   ,GetPlayer());
    replace_token(str,"file"     ,GetFilePath());
    replace_token(str,"shuffle"  ,(GetShuffle() ? "Shuffle" : ""));
    replace_token(str,"repeat"   ,(GetRepeat() ? "Repeat" : ""));
    replace_token(str,"rating"   ,QString::number(GetRating()));
    replace_token(str,"lyrics"   ,GetLyrics());
    return str;
}
Ejemplo n.º 3
0
void ArenaTeam::FinishGame(int32 mod)
{
    // Rating can only drop to 0
    if (int32(Stats.Rating) + mod < 0)
        Stats.Rating = 0;
    else
    {
        Stats.Rating += mod;

        // Check if rating related achivements are met
        for (MemberList::iterator itr = Members.begin(); itr != Members.end(); ++itr)
            if (Player* member = ObjectAccessor::FindPlayer(itr->Guid))
                member->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING, Stats.Rating, Type);
    }

    // Update number of games played per season or week
    Stats.WeekGames += 1;
    Stats.SeasonGames += 1;

    // Update team's rank, start with rank 1 and increase until no team with more rating was found
    Stats.Rank = 1;
    ArenaTeamMgr::ArenaTeamContainer::const_iterator i = sArenaTeamMgr->GetArenaTeamMapBegin();
    for (; i != sArenaTeamMgr->GetArenaTeamMapEnd(); ++i)
    {
        if (i->second->GetType() == Type && i->second->GetStats().Rating > Stats.Rating)
            ++Stats.Rank;
    }

	if (Type == ARENA_TEAM_5v5 && GetRating() > 1900)
	{
		Stats.Rating = 1900; //FIX: Max Rating: 1900
	}
}
Ejemplo n.º 4
0
void RatingsButton::AddProperties(debug::IntrospectionData& introspection)
{
  introspection
    .add(GetAbsoluteGeometry())
    .add("rating", GetRating())
    .add("focused-star", focused_star_)
    .add("editable", editable_);
}
Ejemplo n.º 5
0
bool ArenaTeam::AddMember(ObjectGuid playerGuid)
{
    std::string playerName;
    uint8 playerClass;

    // Check if arena team is full (Can't have more than type * 2 players)
    if (GetMembersSize() >= GetType() * 2)
        return false;

    // Get player name and class either from db or character cache
    Player* player = ObjectAccessor::FindPlayer(playerGuid);
    if (player)
    {
        playerClass = player->getClass();
        playerName = player->GetName();
    }
    else
    {
        CharacterCacheEntry const* cInfo = sCharacterCache->GetCharacterCacheByGuid(playerGuid);
        if (!cInfo)
            return false;

        playerName = cInfo->Name;
        playerClass = cInfo->Class;
    }

    // Check if player is already in a similar arena team
    if ((player && player->GetArenaTeamId(GetSlot())) || sCharacterCache->GetCharacterArenaTeamIdByGuid(playerGuid, GetType()) != 0)
    {
        TC_LOG_DEBUG("bg.arena", "Arena: %s %s already has an arena team of type %u", playerGuid.ToString().c_str(), playerName.c_str(), GetType());
        return false;
    }

    // Set player's personal rating
    uint32 personalRating = 0;

    if (sWorld->getIntConfig(CONFIG_ARENA_START_PERSONAL_RATING) > 0)
        personalRating = sWorld->getIntConfig(CONFIG_ARENA_START_PERSONAL_RATING);
    else if (GetRating() >= 1000)
        personalRating = 1000;

    // Try to get player's match maker rating from db and fall back to config setting if not found
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MATCH_MAKER_RATING);
    stmt->setUInt32(0, playerGuid.GetCounter());
    stmt->setUInt8(1, GetSlot());
    PreparedQueryResult result = CharacterDatabase.Query(stmt);

    uint32 matchMakerRating;
    if (result)
        matchMakerRating = (*result)[0].GetUInt16();
    else
        matchMakerRating = sWorld->getIntConfig(CONFIG_ARENA_START_MATCHMAKER_RATING);

    // Remove all player signatures from other petitions
    // This will prevent player from joining too many arena teams and corrupt arena team data integrity
    Player::RemovePetitionsAndSigns(playerGuid, static_cast<CharterTypes>(GetType()));

    // Feed data to the struct
    ArenaTeamMember newMember;
    newMember.Name             = playerName;
    newMember.Guid             = playerGuid;
    newMember.Class            = playerClass;
    newMember.SeasonGames      = 0;
    newMember.WeekGames        = 0;
    newMember.SeasonWins       = 0;
    newMember.WeekWins         = 0;
    newMember.PersonalRating   = personalRating;
    newMember.MatchMakerRating = matchMakerRating;

    Members.push_back(newMember);
    sCharacterCache->UpdateCharacterArenaTeamId(playerGuid, GetSlot(), GetId());

    // Save player's arena team membership to db
    stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ARENA_TEAM_MEMBER);
    stmt->setUInt32(0, TeamId);
    stmt->setUInt32(1, playerGuid.GetCounter());
    CharacterDatabase.Execute(stmt);

    // Inform player if online
    if (player)
    {
        player->SetInArenaTeam(TeamId, GetSlot(), GetType());
        player->SetArenaTeamIdInvited(0);

        // Hide promote/remove buttons
        if (CaptainGuid != playerGuid)
            player->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_MEMBER, 1);
    }

    TC_LOG_DEBUG("bg.arena", "Player: %s [%s] joined arena team type: %u [Id: %u, Name: %s].", playerName.c_str(), playerGuid.ToString().c_str(), GetType(), GetId(), GetName().c_str());

    return true;
}
Ejemplo n.º 6
0
void CVideoInfoTag::ToSortable(SortItem& sortable, Field field) const
{
  switch (field)
  {
  case FieldDirector:                 sortable[FieldDirector] = m_director; break;
  case FieldWriter:                   sortable[FieldWriter] = m_writingCredits; break;
  case FieldGenre:                    sortable[FieldGenre] = m_genre; break;
  case FieldCountry:                  sortable[FieldCountry] = m_country; break;
  case FieldTagline:                  sortable[FieldTagline] = m_strTagLine; break;
  case FieldPlotOutline:              sortable[FieldPlotOutline] = m_strPlotOutline; break;
  case FieldPlot:                     sortable[FieldPlot] = m_strPlot; break;
  case FieldTitle:
  {
    // make sure not to overwrite an existing title with an empty one
    std::string title = m_strTitle;
    if (!title.empty() || sortable.find(FieldTitle) == sortable.end())
      sortable[FieldTitle] = title;
    break;
  }
  case FieldVotes:                    sortable[FieldVotes] = GetRating().votes; break;
  case FieldStudio:                   sortable[FieldStudio] = m_studio; break;
  case FieldTrailer:                  sortable[FieldTrailer] = m_strTrailer; break;
  case FieldSet:                      sortable[FieldSet] = m_strSet; break;
  case FieldTime:                     sortable[FieldTime] = GetDuration(); break;
  case FieldFilename:                 sortable[FieldFilename] = m_strFile; break;
  case FieldMPAA:                     sortable[FieldMPAA] = m_strMPAARating; break;
  case FieldPath:
  {
    // make sure not to overwrite an existing path with an empty one
    std::string path = GetPath();
    if (!path.empty() || sortable.find(FieldPath) == sortable.end())
      sortable[FieldPath] = path;
    break;
  }
  case FieldSortTitle:
  {
    // seasons with a custom name/title need special handling as they should be sorted by season number
    if (m_type == MediaTypeSeason && !m_strSortTitle.empty())
      sortable[FieldSortTitle] = StringUtils::Format(g_localizeStrings.Get(20358).c_str(), m_iSeason);
    else
      sortable[FieldSortTitle] = m_strSortTitle;
    break;
  }
  case FieldTvShowStatus:             sortable[FieldTvShowStatus] = m_strStatus; break;
  case FieldProductionCode:           sortable[FieldProductionCode] = m_strProductionCode; break;
  case FieldAirDate:                  sortable[FieldAirDate] = m_firstAired.IsValid() ? m_firstAired.GetAsDBDate() : (m_premiered.IsValid() ? m_premiered.GetAsDBDate() : StringUtils::Empty); break;
  case FieldTvShowTitle:              sortable[FieldTvShowTitle] = m_strShowTitle; break;
  case FieldAlbum:                    sortable[FieldAlbum] = m_strAlbum; break;
  case FieldArtist:                   sortable[FieldArtist] = m_artist; break;
  case FieldPlaycount:                sortable[FieldPlaycount] = m_playCount; break;
  case FieldLastPlayed:               sortable[FieldLastPlayed] = m_lastPlayed.IsValid() ? m_lastPlayed.GetAsDBDateTime() : StringUtils::Empty; break;
  case FieldTop250:                   sortable[FieldTop250] = m_iTop250; break;
  case FieldYear:                     sortable[FieldYear] = m_premiered.GetYear(); break;
  case FieldSeason:                   sortable[FieldSeason] = m_iSeason; break;
  case FieldEpisodeNumber:            sortable[FieldEpisodeNumber] = m_iEpisode; break;
  case FieldNumberOfEpisodes:         sortable[FieldNumberOfEpisodes] = m_iEpisode; break;
  case FieldNumberOfWatchedEpisodes:  sortable[FieldNumberOfWatchedEpisodes] = m_iEpisode; break;
  case FieldEpisodeNumberSpecialSort: sortable[FieldEpisodeNumberSpecialSort] = m_iSpecialSortEpisode; break;
  case FieldSeasonSpecialSort:        sortable[FieldSeasonSpecialSort] = m_iSpecialSortSeason; break;
  case FieldRating:                   sortable[FieldRating] = GetRating().rating; break;
  case FieldUserRating:               sortable[FieldUserRating] = m_iUserRating; break;
  case FieldId:                       sortable[FieldId] = m_iDbId; break;
  case FieldTrackNumber:              sortable[FieldTrackNumber] = m_iTrack; break;
  case FieldTag:                      sortable[FieldTag] = m_tags; break;

  case FieldVideoResolution:          sortable[FieldVideoResolution] = m_streamDetails.GetVideoHeight(); break;
  case FieldVideoAspectRatio:         sortable[FieldVideoAspectRatio] = m_streamDetails.GetVideoAspect(); break;
  case FieldVideoCodec:               sortable[FieldVideoCodec] = m_streamDetails.GetVideoCodec(); break;
  case FieldStereoMode:               sortable[FieldStereoMode] = m_streamDetails.GetStereoMode(); break;

  case FieldAudioChannels:            sortable[FieldAudioChannels] = m_streamDetails.GetAudioChannels(); break;
  case FieldAudioCodec:               sortable[FieldAudioCodec] = m_streamDetails.GetAudioCodec(); break;
  case FieldAudioLanguage:            sortable[FieldAudioLanguage] = m_streamDetails.GetAudioLanguage(); break;

  case FieldSubtitleLanguage:         sortable[FieldSubtitleLanguage] = m_streamDetails.GetSubtitleLanguage(); break;

  case FieldInProgress:               sortable[FieldInProgress] = m_resumePoint.IsPartWay(); break;
  case FieldDateAdded:                sortable[FieldDateAdded] = m_dateAdded.IsValid() ? m_dateAdded.GetAsDBDateTime() : StringUtils::Empty; break;
  case FieldMediaType:                sortable[FieldMediaType] = m_type; break;
  case FieldRelevance:                sortable[FieldRelevance] = m_relevance; break;
  default: break;
  }
}
Ejemplo n.º 7
0
void CVideoInfoTag::Serialize(CVariant& value) const
{
  value["director"] = m_director;
  value["writer"] = m_writingCredits;
  value["genre"] = m_genre;
  value["country"] = m_country;
  value["tagline"] = m_strTagLine;
  value["plotoutline"] = m_strPlotOutline;
  value["plot"] = m_strPlot;
  value["title"] = m_strTitle;
  value["votes"] = StringUtils::Format("%i", GetRating().votes);
  value["studio"] = m_studio;
  value["trailer"] = m_strTrailer;
  value["cast"] = CVariant(CVariant::VariantTypeArray);
  for (unsigned int i = 0; i < m_cast.size(); ++i)
  {
    CVariant actor;
    actor["name"] = m_cast[i].strName;
    actor["role"] = m_cast[i].strRole;
    actor["order"] = m_cast[i].order;
    if (!m_cast[i].thumb.empty())
      actor["thumbnail"] = CTextureUtils::GetWrappedImageURL(m_cast[i].thumb);
    value["cast"].push_back(actor);
  }
  value["set"] = m_strSet;
  value["setid"] = m_iSetId;
  value["setoverview"] = m_strSetOverview;
  value["tag"] = m_tags;
  value["runtime"] = GetDuration();
  value["file"] = m_strFile;
  value["path"] = m_strPath;
  value["imdbnumber"] = GetUniqueID();
  value["mpaa"] = m_strMPAARating;
  value["filenameandpath"] = m_strFileNameAndPath;
  value["originaltitle"] = m_strOriginalTitle;
  value["sorttitle"] = m_strSortTitle;
  value["episodeguide"] = m_strEpisodeGuide;
  value["premiered"] = m_premiered.IsValid() ? m_premiered.GetAsDBDate() : StringUtils::Empty;
  value["status"] = m_strStatus;
  value["productioncode"] = m_strProductionCode;
  value["firstaired"] = m_firstAired.IsValid() ? m_firstAired.GetAsDBDate() : StringUtils::Empty;
  value["showtitle"] = m_strShowTitle;
  value["album"] = m_strAlbum;
  value["artist"] = m_artist;
  value["playcount"] = m_playCount;
  value["lastplayed"] = m_lastPlayed.IsValid() ? m_lastPlayed.GetAsDBDateTime() : StringUtils::Empty;
  value["top250"] = m_iTop250;
  value["year"] = m_premiered.GetYear();
  value["season"] = m_iSeason;
  value["episode"] = m_iEpisode;
  for (const auto& i : m_uniqueIDs)
    value["uniqueid"][i.first] = i.second;

  value["rating"] = GetRating().rating;
  CVariant ratings = CVariant(CVariant::VariantTypeObject);
  for (const auto& i : m_ratings)
  {
    CVariant rating;
    rating["rating"] = i.second.rating;
    rating["votes"] = i.second.votes;
    rating["default"] = i.first == m_strDefaultRating;

    ratings[i.first] = rating;
  }
  value["ratings"] = ratings;
  value["userrating"] = m_iUserRating;
  value["dbid"] = m_iDbId;
  value["fileid"] = m_iFileId;
  value["track"] = m_iTrack;
  value["showlink"] = m_showLink;
  m_streamDetails.Serialize(value["streamdetails"]);
  CVariant resume = CVariant(CVariant::VariantTypeObject);
  resume["position"] = (float)m_resumePoint.timeInSeconds;
  resume["total"] = (float)m_resumePoint.totalTimeInSeconds;
  value["resume"] = resume;
  value["tvshowid"] = m_iIdShow;
  value["dateadded"] = m_dateAdded.IsValid() ? m_dateAdded.GetAsDBDateTime() : StringUtils::Empty;
  value["type"] = m_type;
  value["seasonid"] = m_iIdSeason;
  value["specialsortseason"] = m_iSpecialSortSeason;
  value["specialsortepisode"] = m_iSpecialSortEpisode;
}
Ejemplo n.º 8
0
void VideoMetadata::toMap(MetadataMap &metadataMap)
{
    if (this == NULL)
        return;

    QString coverfile;
    if (IsHostSet()
        && !GetCoverFile().startsWith("/")
        && !GetCoverFile().isEmpty()
        && !IsDefaultCoverFile(GetCoverFile()))
    {
        coverfile = generate_file_url("Coverart", GetHost(),
                GetCoverFile());
    }
    else
    {
        coverfile = GetCoverFile();
    }

    metadataMap["coverfile"] = coverfile;

    QString screenshotfile;
    if (IsHostSet() && !GetScreenshot().startsWith("/")
        && !GetScreenshot().isEmpty())
    {
        screenshotfile = generate_file_url("Screenshots",
                GetHost(), GetScreenshot());
    }
    else
    {
        screenshotfile = GetScreenshot();
    }

    metadataMap["screenshotfile"] = screenshotfile;

    QString bannerfile;
    if (IsHostSet() && !GetBanner().startsWith("/")
        && !GetBanner().isEmpty())
    {
        bannerfile = generate_file_url("Banners", GetHost(),
                GetBanner());
    }
    else
    {
        bannerfile = GetBanner();
    }

    metadataMap["bannerfile"] = bannerfile;

    QString fanartfile;
    if (IsHostSet() && !GetFanart().startsWith("/")
        && !GetFanart().isEmpty())
    {
        fanartfile = generate_file_url("Fanart", GetHost(),
                GetFanart());
    }
    else
    {
        fanartfile = GetFanart();
    }

    metadataMap["fanartfile"] = fanartfile;

    metadataMap["filename"] = GetFilename();
    metadataMap["title"] = GetTitle();
    metadataMap["subtitle"] = GetSubtitle();
    metadataMap["tagline"] = GetTagline();
    metadataMap["director"] = GetDirector();
    metadataMap["studio"] = GetStudio();
    metadataMap["description"] = GetPlot();
    metadataMap["genres"] = GetDisplayGenres(*this);
    metadataMap["countries"] = GetDisplayCountries(*this);
    metadataMap["cast"] = GetDisplayCast(*this).join(", ");
    metadataMap["rating"] = GetDisplayRating(GetRating());
    metadataMap["length"] = GetDisplayLength(GetLength());
    metadataMap["year"] = GetDisplayYear(GetYear());

    metadataMap["releasedate"] = MythDateToString(GetReleaseDate(), kDateFull);

    metadataMap["userrating"] = GetDisplayUserRating(GetUserRating());
    metadataMap["season"] = GetDisplaySeasonEpisode(GetSeason(), 1);
    metadataMap["episode"] = GetDisplaySeasonEpisode(GetEpisode(), 1);

    if (GetSeason() > 0 || GetEpisode() > 0)
    {
        metadataMap["s##e##"] = QString("s%1e%2").arg(GetDisplaySeasonEpisode
                                             (GetSeason(), 2))
                        .arg(GetDisplaySeasonEpisode(GetEpisode(), 2));
        metadataMap["##x##"] = QString("%1x%2").arg(GetDisplaySeasonEpisode
                                             (GetSeason(), 1))
                        .arg(GetDisplaySeasonEpisode(GetEpisode(), 2));
    }
    else
        metadataMap["s##e##"] = metadataMap["##x##"] = QString();

    metadataMap["trailerstate"] = TrailerToState(GetTrailer());
    metadataMap["userratingstate"] =
            QString::number((int)(GetUserRating()));
    metadataMap["watchedstate"] = WatchedToState(GetWatched());

    metadataMap["videolevel"] = ParentalLevelToState(GetShowLevel());

    metadataMap["insertdate"] = MythDateToString(GetInsertdate(), kDateFull);
    metadataMap["inetref"] = GetInetRef();
    metadataMap["homepage"] = GetHomepage();
    metadataMap["child_id"] = QString::number(GetChildID());
    metadataMap["browseable"] = GetDisplayBrowse(GetBrowse());
    metadataMap["watched"] = GetDisplayWatched(GetWatched());
    metadataMap["processed"] = GetDisplayProcessed(GetProcessed());
    metadataMap["category"] = GetCategory();
}
Ejemplo n.º 9
0
static int AddStats(DBProvider * pdb, int gm_id, int player_id, int player,
		    const char *table, int nMatchTo, statcontext * sc)
{
	gchar *buf;
	GString *column, *value;
	int totalmoves, unforced;
	float errorcost, errorskill;
	float aaaar[3][2][2][2];
	float r;
	int ret;
	char tmpf[G_ASCII_DTOSTR_BUF_SIZE];

	int gms_id = GetNextId(pdb, table);
	if (gms_id == -1)
		return FALSE;

	totalmoves = sc->anTotalMoves[player];
	unforced = sc->anUnforcedMoves[player];

	getMWCFromError(sc, aaaar);
	errorskill = aaaar[CUBEDECISION][PERMOVE][player][NORMALISED];
	errorcost = aaaar[CUBEDECISION][PERMOVE][player][UNNORMALISED];

	column = g_string_new(NULL);
	value = g_string_new(NULL);


	if (strcmp("matchstat", table) == 0) {
		APPENDI("matchstat_id", gms_id);
		APPENDI("session_id", gm_id);
	} else {
		APPENDI("gamestat_id", gms_id);
		APPENDI("game_id", gm_id);
	}

	APPENDI("player_id", player_id);
	APPENDI("total_moves", totalmoves);
	APPENDI("unforced_moves", unforced);
	APPENDI("unmarked_moves", sc->anMoves[player][SKILL_NONE]);
	APPENDI("good_moves", 0);
	APPENDI("doubtful_moves", sc->anMoves[player][SKILL_DOUBTFUL]);
	APPENDI("bad_moves", sc->anMoves[player][SKILL_BAD]);
	APPENDI("very_bad_moves", sc->anMoves[player][SKILL_VERYBAD]);
	APPENDF("chequer_error_total_normalised",
		sc->arErrorCheckerplay[player][0]);
	APPENDF("chequer_error_total", sc->arErrorCheckerplay[player][1]);
	APPENDF("chequer_error_per_move_normalised",
		Ratio(sc->arErrorCheckerplay[player][0], unforced));
	APPENDF("chequer_error_per_move",
		Ratio(sc->arErrorCheckerplay[player][1], unforced));
	APPENDI("chequer_rating",
		GetRating(Ratio
			  (scMatch.arErrorCheckerplay[player][0],
			   unforced)));
	APPENDI("very_lucky_rolls", sc->anLuck[player][LUCK_VERYGOOD]);
	APPENDI("lucky_rolls", sc->anLuck[player][LUCK_GOOD]);
	APPENDI("unmarked_rolls", sc->anLuck[player][LUCK_NONE]);
	APPENDI("unlucky_rolls", sc->anLuck[player][LUCK_BAD]);
	APPENDI("very_unlucky_rolls", sc->anLuck[player][LUCK_VERYBAD]);
	APPENDF("luck_total_normalised", sc->arLuck[player][0]);
	APPENDF("luck_total", sc->arLuck[player][1]);
	APPENDF("luck_per_move_normalised",
		Ratio(sc->arLuck[player][0], totalmoves));
	APPENDF("luck_per_move", Ratio(sc->arLuck[player][1], totalmoves));
	APPENDI("luck_rating",
		getLuckRating(Ratio(sc->arLuck[player][0], totalmoves)));
	APPENDI("total_cube_decisions", sc->anTotalCube[player]);
	APPENDI("close_cube_decisions", sc->anCloseCube[player]);
	APPENDI("doubles", sc->anDouble[player]);
	APPENDI("takes", sc->anTake[player]);
	APPENDI("passes", sc->anPass[player]);
	APPENDI("missed_doubles_below_cp",
		sc->anCubeMissedDoubleDP[player]);
	APPENDI("missed_doubles_above_cp",
		sc->anCubeMissedDoubleTG[player]);
	APPENDI("wrong_doubles_below_dp", sc->anCubeWrongDoubleDP[player]);
	APPENDI("wrong_doubles_above_tg", sc->anCubeWrongDoubleTG[player]);
	APPENDI("wrong_takes", sc->anCubeWrongTake[player]);
	APPENDI("wrong_passes", sc->anCubeWrongPass[player]);
	APPENDF("error_missed_doubles_below_cp_normalised",
		sc->arErrorMissedDoubleDP[player][0]);
	APPENDF("error_missed_doubles_above_cp_normalised",
		sc->arErrorMissedDoubleTG[player][0]);
	APPENDF("error_wrong_doubles_below_dp_normalised",
		sc->arErrorWrongDoubleDP[player][0]);
	APPENDF("error_wrong_doubles_above_tg_normalised",
		sc->arErrorWrongDoubleTG[player][0]);
	APPENDF("error_wrong_takes_normalised",
		sc->arErrorWrongTake[player][0]);
	APPENDF("error_wrong_passes_normalised",
		sc->arErrorWrongPass[player][0]);
	APPENDF("error_missed_doubles_below_cp",
		sc->arErrorMissedDoubleDP[player][1]);
	APPENDF("error_missed_doubles_above_cp",
		sc->arErrorMissedDoubleTG[player][1]);
	APPENDF("error_wrong_doubles_below_dp",
		sc->arErrorWrongDoubleDP[player][1]);
	APPENDF("error_wrong_doubles_above_tg",
		sc->arErrorWrongDoubleTG[player][1]);
	APPENDF("error_wrong_takes", sc->arErrorWrongTake[player][1]);
	APPENDF("error_wrong_passes", sc->arErrorWrongPass[player][1]);
	APPENDF("cube_error_total_normalised",
		errorskill * sc->anCloseCube[player]);
	APPENDF("cube_error_total", errorcost * sc->anCloseCube[player]);
	APPENDF("cube_error_per_move_normalised", errorskill);
	APPENDF("cube_error_per_move", errorcost);
	APPENDI("cube_rating", GetRating(errorskill));;
	APPENDF("overall_error_total_normalised",
		errorskill * sc->anCloseCube[player] +
		sc->arErrorCheckerplay[player][0]);
	APPENDF("overall_error_total",
		errorcost * sc->anCloseCube[player] +
		sc->arErrorCheckerplay[player][1]);
	APPENDF("overall_error_per_move_normalised",
		Ratio(errorskill * sc->anCloseCube[player] +
		      sc->arErrorCheckerplay[player][0],
		      sc->anCloseCube[player] + unforced));
	APPENDF("overall_error_per_move",
		Ratio(errorcost * sc->anCloseCube[player] +
		      sc->arErrorCheckerplay[player][1],
		      sc->anCloseCube[player] + unforced));
	APPENDI("overall_rating",
		GetRating(Ratio
			  (errorskill * sc->anCloseCube[player] +
			   sc->arErrorCheckerplay[player][0],
			   sc->anCloseCube[player] + unforced)));
	APPENDF("actual_result", sc->arActualResult[player]);
	APPENDF("luck_adjusted_result", sc->arLuckAdj[player]);
	APPENDI("snowie_moves",
		totalmoves + scMatch.anTotalMoves[!player]);
	APPENDF("snowie_error_rate_per_move",
		Ratio(errorskill * scMatch.anCloseCube[player] +
		      scMatch.arErrorCheckerplay[player][0],
		      totalmoves + scMatch.anTotalMoves[!player]));
	/*time */
	APPENDI("time_penalties", 0);
	APPENDF("time_penalty_loss_normalised", 0.0);
	APPENDF("time_penalty_loss", 0.0);
	/* matches only */
	r = 0.5f + scMatch.arActualResult[player] -
	    scMatch.arLuck[player][1] + scMatch.arLuck[!player][1];
	if (nMatchTo && r > 0.0f && r < 1.0f)
		APPENDF("luck_based_fibs_rating_diff",
			relativeFibsRating(r, nMatchTo));
	if (nMatchTo && (scMatch.fCube || scMatch.fMoves)) {
		APPENDF("error_based_fibs_rating",
			absoluteFibsRating(aaaar[CHEQUERPLAY][PERMOVE]
					   [player][NORMALISED],
					   aaaar[CUBEDECISION][PERMOVE]
					   [player][NORMALISED], nMatchTo,
					   rRatingOffset));
		if (scMatch.anUnforcedMoves[player])
			APPENDF("chequer_rating_loss",
				absoluteFibsRatingChequer(aaaar
							  [CHEQUERPLAY]
							  [PERMOVE][player]
							  [NORMALISED],
							  nMatchTo));
		if (scMatch.anCloseCube[player])
			APPENDF("cube_rating_loss",
				absoluteFibsRatingCube(aaaar[CUBEDECISION]
						       [PERMOVE][player]
						       [NORMALISED],
						       nMatchTo));
	}

	/* for money sessions only */
	if (scMatch.fDice && !nMatchTo && scMatch.nGames > 1) {

		APPENDF("actual_advantage",
			scMatch.arActualResult[player] / scMatch.nGames);
		APPENDF("actual_advantage_ci",
			1.95996f * sqrt(scMatch.arVarianceActual[player] /
					scMatch.nGames));
		APPENDF("luck_adjusted_advantage",
			scMatch.arLuckAdj[player] / scMatch.nGames);
		APPENDF("luck_adjusted_advantage_ci",
			1.95996f * sqrt(scMatch.arVarianceLuckAdj[player] /
					scMatch.nGames));
	}

	g_string_truncate(column, column->len - 2);
	g_string_truncate(value, value->len - 2);
	buf = g_strdup_printf("INSERT INTO %s (%s) VALUES(%s)", table,
			      column->str, value->str);
	ret = pdb->UpdateCommand(buf);
	g_free(buf);
	g_string_free(column, TRUE);
	g_string_free(value, TRUE);
	return ret;
}
Ejemplo n.º 10
0
extern GList *
formatGS(const statcontext * psc, const int nMatchTo, const enum _formatgs fg)
{

    GList *list = NULL;
    char **aasz;
    float aaaar[3][2][2][2];

    getMWCFromError(psc, aaaar);

    switch (fg) {
    case FORMATGS_CHEQUER:
        {

            static int ai[4] = { SKILL_NONE, SKILL_DOUBTFUL,
                SKILL_BAD, SKILL_VERYBAD
            };
            static const char *asz[4] = {
                N_("Unmarked moves"),
                N_("Moves marked doubtful"),
                N_("Moves marked bad"),
                N_("Moves marked very bad")
            };
            int i;

            /* chequer play part */

            list = g_list_append(list, numberEntry(_("Total moves"), psc->anTotalMoves[0], psc->anTotalMoves[1]));

            list = g_list_append(list, numberEntry(_("Unforced moves"),
                                                   psc->anUnforcedMoves[0], psc->anUnforcedMoves[1]));
            for (i = 0; i < 4; ++i)
                list = g_list_append(list,
                                     numberEntry(gettext(asz[i]), psc->anMoves[0][ai[i]], psc->anMoves[1][ai[i]]));

            /* total error rate */

            aasz = g_malloc(3 * sizeof(*aasz));

            aasz[0] = g_strdup_printf(_("Error total %s"), total_text(nMatchTo));

            for (i = 0; i < 2; ++i)
                aasz[i + 1] = errorRate(-aaaar[CHEQUERPLAY][TOTAL][i][NORMALISED],
                                        -aaaar[CHEQUERPLAY][TOTAL][i][UNNORMALISED], nMatchTo);

            list = g_list_append(list, aasz);

            /* error rate per move */

            aasz = g_malloc(3 * sizeof(*aasz));

            aasz[0] = g_strdup_printf(_("Error rate %s"), rate_text(nMatchTo));

            for (i = 0; i < 2; ++i)
                aasz[i + 1] = errorRateMP(-aaaar[CHEQUERPLAY][PERMOVE][i][NORMALISED],
                                          -aaaar[CHEQUERPLAY][PERMOVE][i][UNNORMALISED], nMatchTo);

            list = g_list_append(list, aasz);

            /* chequer play rating */

            aasz = g_malloc(3 * sizeof(*aasz));

            aasz[0] = g_strdup(_("Chequerplay rating"));

            for (i = 0; i < 2; ++i)
                if (psc->anUnforcedMoves[i])
                    aasz[i + 1] = g_strdup(Q_(aszRating[GetRating(aaaar[CHEQUERPLAY][PERMOVE][i][NORMALISED])]));
                else
                    aasz[i + 1] = g_strdup(_("n/a"));

            list = g_list_append(list, aasz);

        }

        break;

    case FORMATGS_CUBE:
        {
            static const char *asz[] = {
                N_("Total cube decisions"),
                N_("Close or actual cube decisions"),
                N_("Doubles"),
                N_("Takes"),
                N_("Passes")
            };

            static const char *asz2[] = {
                N_("Missed doubles below CP"),
                N_("Missed doubles above CP"),
                N_("Wrong doubles below DP"),
                N_("Wrong doubles above TG"),
                N_("Wrong takes"),
                N_("Wrong passes")
            };

            int i, j;

            const int *ai[5], *ai2[6];
            const float *af2[2][6];

            ai[0] = psc->anTotalCube;
            ai[1] = psc->anCloseCube;
            ai[2] = psc->anDouble;
            ai[3] = psc->anTake;
            ai[4] = psc->anPass;

            ai2[0] = psc->anCubeMissedDoubleDP;
            ai2[1] = psc->anCubeMissedDoubleTG;
            ai2[2] = psc->anCubeWrongDoubleDP;
            ai2[3] = psc->anCubeWrongDoubleTG;
            ai2[4] = psc->anCubeWrongTake;
            ai2[5] = psc->anCubeWrongPass;

            af2[0][0] = psc->arErrorMissedDoubleDP[0];
            af2[0][1] = psc->arErrorMissedDoubleTG[0];
            af2[0][2] = psc->arErrorWrongDoubleDP[0];
            af2[0][3] = psc->arErrorWrongDoubleTG[0];
            af2[0][4] = psc->arErrorWrongTake[0];
            af2[0][5] = psc->arErrorWrongPass[0];
            af2[1][0] = psc->arErrorMissedDoubleDP[1];
            af2[1][1] = psc->arErrorMissedDoubleTG[1];
            af2[1][2] = psc->arErrorWrongDoubleDP[1];
            af2[1][3] = psc->arErrorWrongDoubleTG[1];
            af2[1][4] = psc->arErrorWrongTake[1];
            af2[1][5] = psc->arErrorWrongPass[1];

            for (i = 0; i < 5; ++i)
                list = g_list_append(list, numberEntry(gettext(asz[i]), ai[i][0], ai[i][1]));
            for (i = 0; i < 6; ++i) {
                aasz = g_malloc(3 * sizeof(*aasz));

                aasz[0] = g_strdup_printf("%s (%s)", gettext(asz2[i]), total_text(nMatchTo));

                for (j = 0; j < 2; ++j)
                    aasz[j + 1] = cubeEntry(ai2[i][j], -af2[j][i][0], -af2[j][i][1], nMatchTo);

                list = g_list_append(list, aasz);

            }

            /* total error rate */

            aasz = g_malloc(3 * sizeof(*aasz));

            aasz[0] = g_strdup_printf(_("Error total %s"), total_text(nMatchTo));

            for (i = 0; i < 2; ++i)
                aasz[i + 1] = errorRate(-aaaar[CUBEDECISION][TOTAL][i][NORMALISED],
                                        -aaaar[CUBEDECISION][TOTAL][i][UNNORMALISED], nMatchTo);

            list = g_list_append(list, aasz);

            /* error rate per cube decision */

            aasz = g_malloc(3 * sizeof(*aasz));

            aasz[0] = g_strdup_printf(_("Error rate %s"), rate_text(nMatchTo));

            for (i = 0; i < 2; ++i)
                aasz[i + 1] = errorRateMP(-aaaar[CUBEDECISION][PERMOVE][i][NORMALISED],
                                          -aaaar[CUBEDECISION][PERMOVE][i][UNNORMALISED], nMatchTo);

            list = g_list_append(list, aasz);

            /* cube decision rating */

            aasz = g_malloc(3 * sizeof(*aasz));

            aasz[0] = g_strdup(_("Cube decision rating"));

            for (i = 0; i < 2; ++i)
                if (psc->anCloseCube[i])
                    aasz[i + 1] = g_strdup(Q_(aszRating[GetRating(aaaar[CUBEDECISION][PERMOVE][i][NORMALISED])]));
                else
                    aasz[i + 1] = g_strdup(_("n/a"));

            list = g_list_append(list, aasz);



        }
        break;

    case FORMATGS_LUCK:
        {

            static const char *asz[] = {
                N_("Rolls marked very lucky"),
                N_("Rolls marked lucky"),
                N_("Rolls unmarked"),
                N_("Rolls marked unlucky"),
                N_("Rolls marked very unlucky")
            };
            int i;

            for (i = 0; i < 5; ++i)
                list = g_list_append(list, numberEntry(gettext(asz[i]), psc->anLuck[0][4 - i], psc->anLuck[1][4 - i]));


            /* total luck */

            aasz = g_malloc(3 * sizeof(*aasz));

            aasz[0] = g_strdup_printf(_("Luck total %s"), total_text(nMatchTo));

            for (i = 0; i < 2; ++i)
                aasz[i + 1] = errorRate(psc->arLuck[i][0], psc->arLuck[i][1], nMatchTo);

            list = g_list_append(list, aasz);

            /* luck rate per move */

            aasz = g_malloc(3 * sizeof(*aasz));

            aasz[0] = g_strdup_printf(_("Luck rate %s"), rate_text(nMatchTo));

            for (i = 0; i < 2; ++i)
                if (psc->anTotalMoves[i])
                    aasz[i + 1] = errorRateMP(psc->arLuck[i][0] /
                                              psc->anTotalMoves[i], psc->arLuck[i][1] / psc->anTotalMoves[i], nMatchTo);
                else
                    aasz[i + 1] = g_strdup(_("n/a"));

            list = g_list_append(list, aasz);

            /* chequer play rating */

            aasz = g_malloc(3 * sizeof(*aasz));

            aasz[0] = g_strdup(_("Luck rating"));

            for (i = 0; i < 2; ++i)
                if (psc->anTotalMoves[i])
                    aasz[i + 1] = g_strdup(Q_(aszLuckRating[getLuckRating(psc->arLuck[i][0] / psc->anTotalMoves[i])]));
                else
                    aasz[i + 1] = g_strdup(_("n/a"));

            list = g_list_append(list, aasz);

        }
        break;

    case FORMATGS_OVERALL:

        {
            int i, n;

            /* total error rate */

            aasz = g_malloc(3 * sizeof(*aasz));

            if (psc->fCube || psc->fMoves) {

                aasz[0] = g_strdup_printf(_("Error total %s"), total_text(nMatchTo));

                for (i = 0; i < 2; ++i)
                    aasz[i + 1] = errorRate(-aaaar[COMBINED][TOTAL][i][NORMALISED],
                                            -aaaar[COMBINED][TOTAL][i][UNNORMALISED], nMatchTo);

                list = g_list_append(list, aasz);

                /* error rate per decision */

                aasz = g_malloc(3 * sizeof(*aasz));

                aasz[0] = g_strdup_printf(_("Error rate %s"), rate_text(nMatchTo));

                for (i = 0; i < 2; ++i)
                    aasz[i + 1] = errorRateMP(-aaaar[COMBINED][PERMOVE][i][NORMALISED],
                                              -aaaar[COMBINED][PERMOVE][i][UNNORMALISED], nMatchTo);

                list = g_list_append(list, aasz);

                /* eq. snowie error rate */

                aasz = g_malloc(3 * sizeof(*aasz));

                aasz[0] = g_strdup(_("Snowie error rate"));

                for (i = 0; i < 2; ++i)
                    if ((n = psc->anTotalMoves[0] + psc->anTotalMoves[1]) > 0)
                        aasz[i + 1] = errorRateMP(-aaaar[COMBINED][TOTAL][i][NORMALISED] / n, 0.0f, nMatchTo);
                    else
                        aasz[i + 1] = g_strdup(_("n/a"));

                list = g_list_append(list, aasz);

                /* rating */

                aasz = g_malloc(3 * sizeof(*aasz));

                aasz[0] = g_strdup(_("Overall rating"));

                for (i = 0; i < 2; ++i)
                    if (psc->anCloseCube[i] + psc->anUnforcedMoves[i])
                        aasz[i + 1] = g_strdup(Q_(aszRating[GetRating(aaaar[COMBINED][PERMOVE][i][NORMALISED])]));
                    else
                        aasz[i + 1] = g_strdup(_("n/a"));

                list = g_list_append(list, aasz);

            }

            if (psc->fDice) {

                /* luck adj. result */

                if ((psc->arActualResult[0] > 0.0f || psc->arActualResult[1] > 0.0f) && psc->fDice) {

                    list = g_list_append(list, luckAdjust(_("Actual result"), psc->arActualResult, nMatchTo));

                    list = g_list_append(list, luckAdjust(_("Luck adjusted result"), psc->arLuckAdj, nMatchTo));

                    if (nMatchTo) {

                        /* luck based fibs rating */

                        float r = 0.5f + psc->arActualResult[0] - psc->arLuck[0][1] + psc->arLuck[1][1];

                        aasz = g_malloc(3 * sizeof(*aasz));

                        aasz[0] = g_strdup(_("Luck based FIBS rating diff."));
                        aasz[2] = g_strdup("");

                        if (r > 0.0f && r < 1.0f)
                            aasz[1] = g_strdup_printf("%+7.2f", relativeFibsRating(r, ms.nMatchTo));
                        else
                            aasz[1] = g_strdup_printf(_("n/a"));

                        list = g_list_append(list, aasz);

                    }

                }

            }

            if (psc->fCube || psc->fMoves) {

                /* error based fibs rating */

                if (nMatchTo) {

                    aasz = g_malloc(3 * sizeof(*aasz));
                    aasz[0] = g_strdup(_("Error based abs. FIBS rating"));

                    for (i = 0; i < 2; ++i)
                        if (psc->anCloseCube[i] + psc->anUnforcedMoves[i])
                            aasz[i + 1] = g_strdup_printf("%6.1f",
                                                          absoluteFibsRating(aaaar[CHEQUERPLAY][PERMOVE][i][NORMALISED],
                                                                             aaaar[CUBEDECISION][PERMOVE][i]
                                                                             [NORMALISED], nMatchTo, rRatingOffset));
                        else
                            aasz[i + 1] = g_strdup_printf(_("n/a"));

                    list = g_list_append(list, aasz);

                    /* chequer error fibs rating */

                    aasz = g_malloc(3 * sizeof(*aasz));
                    aasz[0] = g_strdup(_("Chequerplay errors rating loss"));

                    for (i = 0; i < 2; ++i)
                        if (psc->anUnforcedMoves[i])
                            aasz[i + 1] = g_strdup_printf("%6.1f",
                                                          absoluteFibsRatingChequer(aaaar[CHEQUERPLAY][PERMOVE][i]
                                                                                    [NORMALISED], nMatchTo));
                        else
                            aasz[i + 1] = g_strdup_printf(_("n/a"));

                    list = g_list_append(list, aasz);

                    /* cube error fibs rating */

                    aasz = g_malloc(3 * sizeof(*aasz));
                    aasz[0] = g_strdup(_("Cube errors rating loss"));

                    for (i = 0; i < 2; ++i)
                        if (psc->anCloseCube[i])
                            aasz[i + 1] = g_strdup_printf("%6.1f",
                                                          absoluteFibsRatingCube(aaaar[CUBEDECISION][PERMOVE][i]
                                                                                 [NORMALISED], nMatchTo));
                        else
                            aasz[i + 1] = g_strdup_printf(_("n/a"));

                    list = g_list_append(list, aasz);

                }

            }

            if (psc->fDice && !nMatchTo && psc->nGames > 1) {

                static const char *asz[2][2] = {
                    {N_("Advantage (actual) in ppg"),
                     /* xgettext: no-c-format */
                     N_("95% confidence interval (ppg)")},
                    {N_("Advantage (luck adjusted) in ppg"),
                     /* xgettext: no-c-format */
                     N_("95% confidence interval (ppg)")}
                };
                int i, j;
                const float *af[2][2];
                af[0][0] = psc->arActualResult;
                af[0][1] = psc->arVarianceActual;
                af[1][0] = psc->arLuckAdj;
                af[1][1] = psc->arVarianceLuckAdj;

                for (i = 0; i < 2; ++i) {

                    /* ppg */

                    aasz = g_malloc(3 * sizeof(*aasz));
                    aasz[0] = g_strdup(gettext(asz[i][0]));

                    for (j = 0; j < 2; ++j)
                        aasz[j + 1] =
                            g_strdup_printf("%+*.*f", fOutputDigits + 3, fOutputDigits, af[i][0][j] / psc->nGames);

                    list = g_list_append(list, aasz);

                    /* std dev. */

                    aasz = g_malloc(3 * sizeof(*aasz));
                    aasz[0] = g_strdup(gettext(asz[i][1]));

                    for (j = 0; j < 2; ++j) {
                        float ci = 1.95996f * sqrtf(af[i][1][j] / psc->nGames);
                        float max = af[i][0][j] + ci;
                        float min = af[i][0][j] - ci;
                        aasz[j + 1] = g_strdup_printf("[%*.*f,%*.*f]",
                                                      fOutputDigits + 3, fOutputDigits, min,
                                                      fOutputDigits + 3, fOutputDigits, max);
                    }
                    list = g_list_append(list, aasz);

                }


            }

        }

        break;

    default:

        g_assert_not_reached();
        break;

    }

    return list;


}
Ejemplo n.º 11
0
static void output_match_messages(int wp,int bp,int g, char* mess)
{


  int p;
  char *outStr;

  asprintf(&outStr,"Creating: %s (%d) %s (%d) %s %s %d %d\n",
	   player_globals.parray[wp].name,
	   game_globals.garray[g].white_rating,
	   player_globals.parray[bp].name,
	   game_globals.garray[g].black_rating,
	   rstr[game_globals.garray[g].rated],
	   bstr[game_globals.garray[g].type],
	   game_globals.garray[g].wInitTime/60000,
	   game_globals.garray[g].wIncrement/1000);
  pprintf(wp, "%s", outStr);
  pprintf(bp, "%s", outStr);
  free(outStr);

  asprintf(&outStr, "{Game %d (%s vs. %s) %s %s %s match.}\n",
          g + 1, player_globals.parray[wp].name,
          player_globals.parray[bp].name,
          mess,
          rstr[game_globals.garray[g].rated],
          bstr[game_globals.garray[g].type]);
  pprintf(wp, "%s", outStr);
  pprintf(bp, "%s", outStr);

  for (p = 0; p < player_globals.p_num; p++) {
    struct player *pp = &player_globals.parray[p];
    int gnw, gnb;


    if ((p == wp) || (p == bp))
      continue;
    if (pp->status != PLAYER_PROMPT)
      continue;
    if (CheckPFlag(p, PFLAG_GIN)) {
      pprintf_prompt(p, "%s", outStr);

    }
    gnw = in_list(p, L_GNOTIFY, player_globals.parray[wp].login);
    gnb = in_list(p, L_GNOTIFY, player_globals.parray[bp].login);
    if (gnw || gnb) {
      pprintf(p, "\nGame notification: ");

      if (gnw)
        pprintf_highlight(p, player_globals.parray[wp].name);
      else
        pprintf(p, player_globals.parray[wp].name);

      pprintf(p, " (%s) vs. ",
              ratstr(GetRating(&player_globals.parray[wp], game_globals.garray[g].type)));

      if (gnb)
        pprintf_highlight(p, player_globals.parray[bp].name);
      else
        pprintf(p, player_globals.parray[bp].name);
      pprintf(p, " (%s) %s %s %d %d: Game %d\n",
                     ratstr(GetRating(&player_globals.parray[bp], game_globals.garray[g].type)),
                     rstr[game_globals.garray[g].rated], bstr[game_globals.garray[g].type],
                     game_globals.garray[g].wInitTime/60000, game_globals.garray[g].wIncrement/1000, g+1);


    }

  }

  free(outStr);
}
Ejemplo n.º 12
0
ECode RatingBar::DispatchRatingChange(
    /* [in] */ Boolean fromUser)
{
    if (mOnRatingBarChangeListener != NULL) {
        mOnRatingBarChangeListener->OnRatingChanged((IRatingBar*)this->Probe(EIID_IRatingBar), GetRating(), fromUser);
    }

    return NOERROR;
}
Ejemplo n.º 13
0
void RatingsButton::Draw(nux::GraphicsEngine& GfxContext, bool force_draw)
{
  int rating =  static_cast<int>(GetRating() * NUM_STARS);
  // FIXME: 9/26/2011
  // We should probably support an API for saying whether the ratings
  // should or shouldn't support half stars...but our only consumer at
  // the moment is the applications scope which according to design
  // (Bug #839759) shouldn't. So for now just force rounding.
  //    int total_half_stars = rating % 2;
  //    int total_full_stars = rating / 2;
  int total_full_stars = rating;

  nux::Geometry const& geo = GetGeometry();
  nux::Geometry geo_star(geo);
  geo_star.width = star_size_.CP(scale);
  geo_star.height = star_size_.CP(scale);

  gPainter.PaintBackground(GfxContext, geo);
  // set up our texture mode
  nux::TexCoordXForm texxform;
  texxform.SetWrap(nux::TEXWRAP_CLAMP_TO_BORDER, nux::TEXWRAP_CLAMP_TO_BORDER);
  texxform.SetTexCoordType(nux::TexCoordXForm::OFFSET_SCALE_COORD);
  texxform.SetFilter(nux::TEXFILTER_LINEAR, nux::TEXFILTER_LINEAR);

  // clear what is behind us
  unsigned int alpha = 0, src = 0, dest = 0;

  GfxContext.GetRenderStates().GetBlend(alpha, src, dest);
  GfxContext.GetRenderStates().SetBlend(true, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

  nux::Color col = nux::color::Black;
  col.alpha = 0;
  GfxContext.QRP_Color(geo.x,
                       geo.y,
                       geo.width,
                       geo.height,
                       col);

  for (int index = 0; index < NUM_STARS; ++index)
  {
    dash::Style& style = dash::Style::Instance();
    auto texture = style.GetStarSelectedIcon();
    if (index < total_full_stars)
    {
      if (GetVisualState() == nux::ButtonVisualState::VISUAL_STATE_NORMAL)
        texture = style.GetStarSelectedIcon();
      else if (GetVisualState() == nux::ButtonVisualState::VISUAL_STATE_PRELIGHT)
        texture = style.GetStarSelectedIcon();
      else if (GetVisualState() == nux::ButtonVisualState::VISUAL_STATE_PRESSED)
        texture = style.GetStarSelectedIcon();
    }
    else
    {
      if (GetVisualState() == nux::ButtonVisualState::VISUAL_STATE_NORMAL)
        texture = style.GetStarDeselectedIcon();
      else if (GetVisualState() == nux::ButtonVisualState::VISUAL_STATE_PRELIGHT)
        texture = style.GetStarDeselectedIcon();
      else if (GetVisualState() == nux::ButtonVisualState::VISUAL_STATE_PRESSED)
        texture = style.GetStarDeselectedIcon();
    }

    GfxContext.QRP_1Tex(geo_star.x,
                        geo_star.y,
                        geo_star.width,
                        geo_star.height,
                        texture->GetDeviceTexture(),
                        texxform,
                        nux::Color(1.0f, 1.0f, 1.0f, 1.0f));

    if (focused_star_ == index)
    {
      GfxContext.QRP_1Tex(geo_star.x,
                          geo_star.y,
                          geo_star.width,
                          geo_star.height,
                          style.GetStarHighlightIcon()->GetDeviceTexture(),
                          texxform,
                          nux::Color(1.0f, 1.0f, 1.0f, 0.5f));
    }

    geo_star.x += geo_star.width + star_gap_.CP(scale);

  }

  GfxContext.GetRenderStates().SetBlend(alpha, src, dest);

}
Ejemplo n.º 14
0
bool ArenaTeam::AddMember(uint64 playerGuid)
{
    std::string playerName;
    uint8 playerClass;

    // Check if arena team is full (Can't have more than type * 2 players)
    if (GetMembersSize() >= GetType() * 2)
        return false;

    // xinef: Get player name and class from player storage or global data storage
    Player* player = ObjectAccessor::FindPlayerInOrOutOfWorld(playerGuid);
    if (player)
    {
        playerClass = player->getClass();
        playerName = player->GetName();
    }
    else
    {
        GlobalPlayerData const* playerData = sWorld->GetGlobalPlayerData(GUID_LOPART(playerGuid));
        if (!playerData)
            return false;

        playerName = playerData->name;
        playerClass = playerData->playerClass;
    }

    // Check if player is already in a similar arena team
    if ((player && player->GetArenaTeamId(GetSlot())) || Player::GetArenaTeamIdFromStorage(GUID_LOPART(playerGuid), GetSlot()) != 0)
    {
        sLog->outError("Arena: Player %s (guid: %u) already has an arena team of type %u", playerName.c_str(), GUID_LOPART(playerGuid), GetType());
        return false;
    }

    // Set player's personal rating
    uint32 personalRating = 0;

    if (sWorld->getIntConfig(CONFIG_ARENA_START_PERSONAL_RATING) > 0)
        personalRating = sWorld->getIntConfig(CONFIG_ARENA_START_PERSONAL_RATING);
    else if (GetRating() >= 1000)
        personalRating = 1000;

    // xinef: zomg! sync query
    // Try to get player's match maker rating from db and fall back to config setting if not found
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MATCH_MAKER_RATING);
    stmt->setUInt32(0, GUID_LOPART(playerGuid));
    stmt->setUInt8(1, GetSlot());
    PreparedQueryResult result = CharacterDatabase.Query(stmt);

    uint16 matchMakerRating;
    uint16 maxMMR;
    if (result)
    {
        matchMakerRating = (*result)[0].GetUInt16();
        uint16 Max = (*result)[1].GetUInt16();
        maxMMR = std::max(Max, matchMakerRating);
    }
    else
    {
        matchMakerRating = sWorld->getIntConfig(CONFIG_ARENA_START_MATCHMAKER_RATING);
        maxMMR = matchMakerRating;
    }

    // Remove all player signatures from other petitions
    // This will prevent player from joining too many arena teams and corrupt arena team data integrity
    Player::RemovePetitionsAndSigns(playerGuid, GetType());

    // Feed data to the struct
    ArenaTeamMember newMember;
    //newMember.Name             = playerName;
    newMember.Guid             = playerGuid;
    newMember.Class            = playerClass;
    newMember.SeasonGames      = 0;
    newMember.WeekGames        = 0;
    newMember.SeasonWins       = 0;
    newMember.WeekWins         = 0;
    newMember.PersonalRating   = personalRating;
    newMember.MatchMakerRating = matchMakerRating;
    newMember.MaxMMR           = maxMMR;

    Members.push_back(newMember);
    sWorld->UpdateGlobalPlayerArenaTeam(GUID_LOPART(playerGuid), GetSlot(), GetId());

    // Save player's arena team membership to db
    stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ARENA_TEAM_MEMBER);
    stmt->setUInt32(0, TeamId);
    stmt->setUInt32(1, GUID_LOPART(playerGuid));
    CharacterDatabase.Execute(stmt);

    // Inform player if online
    if (player)
    {
        player->SetInArenaTeam(TeamId, GetSlot(), GetType());
        player->SetArenaTeamIdInvited(0);

        // Hide promote/remove buttons
        if (CaptainGuid != playerGuid)
            player->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_MEMBER, 1);
    }

    return true;
}
Ejemplo n.º 15
0
int com_match(int p, param_list param)
{
  struct player *pp = &player_globals.parray[p];
  int adjourned;                /* adjourned game? */
  int g;                        /* more adjourned game junk */
  int p1;
  int bh = 0, partner = 0, pp1 = 0;
  struct pending* pendfrom;
  struct pending* pendto;
  struct pending* pend;
  int wt = -1;                  /* white start time */
  int winc = -1;                /* white increment */
  int bt = -1;                  /* black start time */
  int binc = -1;                /* black increment */
  int rated = -1;               /* 1 = rated, 0 = unrated */
  int white = -1;               /* 1 = want white, 0 = want black */
  char category[100], board[100];
  textlist *clauses = NULL;
  int type = 0;

  category[0] ='\0';
  board[0] ='\0';

  if ((pp->game >= 0) && ((game_globals.garray[pp->game].status == GAME_EXAMINE)
|| (game_globals.garray[pp->game].status == GAME_SETUP))) {

    pprintf(p, "You can't challenge while you are examining a game.\n");
    return COM_OK;
  }

  if (pp->game >= 0) {
    pprintf(p, "You can't challenge while you are playing a game.\n");
    return COM_OK;
  }

  /* Makes sure that the user has not been ratebanned - Added by johnthegreat*/
  if (in_list(p, L_RATEBAN, player_globals.parray[p].name))
  {
  	pprintf_prompt(p,"You are banned from playing rated games.");
   	return COM_OK;
  }

  stolower(param[0].val.word);
  p1 = player_find_part_login(param[0].val.word);
  if (p1 < 0) {
    pprintf(p, "No user named \"%s\" is logged in.\n", param[0].val.word);
    return COM_OK;
  }

  if (p1 == p) {                /* Allowing to match yourself to enter
                                   analysis mode */
    //ExamineScratch (p, param, 0);
    	pprintf(p, "Your can not match yourself.\n");
	return COM_OK;
  }

  if (!CheckPFlag(p1, PFLAG_OPEN)) {
    pprintf(p, "Player \"%s\" is not open to match requests.\n", player_globals.parray[p1].name);
    return COM_OK;
  }

  if (player_globals.parray[p1].game >= 0) {
    pprintf(p, "Player \"%s\" is playing a game.\n", player_globals.parray[p1].name);    return COM_OK;
  }

  if (CheckPFlag(p, PFLAG_TOURNEY) && !CheckPFlag(p1, PFLAG_TOURNEY)) {
    pprintf(p, "You may only match players with their tournament variable set.\n");
    return COM_OK;
  }

  if (!CheckPFlag(p, PFLAG_TOURNEY) && CheckPFlag(p1, PFLAG_TOURNEY)) {
    pprintf(p, "%s is in a tournament, and cannot accept other challenges.\n", player_globals.parray[p1].name);
    return COM_OK;
  }

	if (!net_globals.con[pp->socket]->timeseal)
	{
		return COM_OK;

	}
  if (!CheckPFlag(p, PFLAG_OPEN)) {
    PFlagON(p, PFLAG_OPEN);
    pprintf(p, "Setting you open for matches.\n");
  }


/* look for an adjourned game between p and p1 */
  g = game_new();
  adjourned = (game_read(g, p, p1) >= 0) || (game_read(g, p1, p) >= 0);
  if (adjourned) {
    type = game_globals.garray[g].type;
    wt = game_globals.garray[g].wInitTime / 60000;
    bt = game_globals.garray[g].bInitTime / 60000;
    winc = game_globals.garray[g].wIncrement / 1000;
    binc = game_globals.garray[g].bIncrement / 1000;
    rated = game_globals.garray[g].rated;
  }
  game_remove(g);

  pendto = find_pend(p, p1, PEND_MATCH);

  pendfrom = find_pend(p1, p, PEND_MATCH);

  if (!adjourned) {
      if (player_censored(p1, p))
        {
          pprintf(p, "Player \"%s\" is censoring you.\n",
              player_globals.parray[p1].name);
          return COM_OK;
        }
      if (player_censored(p, p1))
        {
          pprintf(p, "You are censoring \"%s\".\n",
              player_globals.parray[p1].name);
          return COM_OK;
        }
    if (in_list(p1, L_NOPLAY, pp->name)) {
      pprintf(p, "You are on %s's noplay list.\n", player_globals.parray[p1].name);
      return COM_OK;
    }
    if (in_list(p, L_NOPLAY, player_globals.parray[p1].name)) {
      pprintf(p, "You have %s on your noplay list.\n", player_globals.parray[p1].name);
      return COM_OK;
    }

    /* Makes sure that the opponent has not been ratebanned - Added by johnthegreat*/
    if (in_list(p1, L_RATEBAN, player_globals.parray[p1].name))
    {
    	pprintf(p,"%s has been banned from playing rated games.",player_globals.parray[p1].name);
    	return COM_OK;
    }

    if (CheckPFlag(p1, PFLAG_WHITELIST) && !player_isAllowedPlay(p1, p)) {
        struct player *pp2 = player_getStruct(p1);
        pprintf(p, "%s is not allowing requests from you.\n", pp2->name);
        return COM_OK;
    }

    if (param[1].type != TYPE_NULL) {
      if (!parse_match_string(p, &wt,&bt,&winc,&binc,&white,&rated,category,
                                                  board,param[1].val.string))

	  return COM_OK; /* couldn't parse */
    }

    if (rated == -1)
      rated = BoolCheckPFlag(p, PFLAG_RATED);
    if (!CheckPFlag(p, PFLAG_REG) || !CheckPFlag(p1, PFLAG_REG))
      rated = 0;

    if (winc == -1)
      winc = (wt == -1) ? pp->d_inc : 0;  /* match 5 == match 5 0 */

    if (wt == -1)
      wt = pp->d_time;

    if (bt == -1)
      bt = wt;

    if (binc == -1)
      binc = winc;

    if (category[0])
	{
			if (!board[0] && strcmp(category,"bughouse") && strcmp(category,"zh"))
			{
				pprintf(p, "You must specify a board and a category.\n");
				return COM_OK;
			} else if (board[0])
			{
				char fname[MAX_FILENAME_SIZE];

				if (!strcmp(board,"FR"))
					sprintf(fname, "%s/%s", BOARD_DIR, board);
				else
					sprintf(fname, "%s/%s/%s", BOARD_DIR, category, board);

				if (!file_exists(fname))
				{
					pprintf(p, "No such category/board: %s/%s\n", category, board);
					return COM_OK;
				}
			}
    }
    type = game_isblitz(category,board);

    if (type == TYPE_BUGHOUSE) {
      if (rated && pp->partner >= 0 && player_globals.parray[p1].partner >= 0) {
        if (!CheckPFlag(pp->partner, PFLAG_REG)
              || !CheckPFlag(player_globals.parray[p1].partner, PFLAG_REG))
          rated = 0;
      }
    }
    if (rated && (type == TYPE_NONSTANDARD)) {
      pprintf(p, "Game is non-standard - reverting to unrated\n");
      rated = 0;
    }
    if (rated && (type == TYPE_UNTIMED)) {
      pprintf(p, "Game is untimed - reverting to unrated\n");
      rated = 0;
    }
    if ((pendfrom == NULL) && !CheckPFlag(p1, PFLAG_ROPEN)
        && (rated != BoolCheckPFlag(p1, PFLAG_RATED))) {
      pprintf(p, "%s only wants to play %s games.\n", player_globals.parray[p1].name,
              rstr[!rated]);
      pprintf_highlight(p1, "Ignoring");
      pprintf(p1, " %srated match request from %s.\n",
              (rated ? "" : "un"), pp->name);
      return COM_OK;
    }

    /* Now check formula. */
    if (!adjourned
        && !GameMatchesFormula(p,p1, wt,winc,bt,binc, rated, type, &clauses)) {
      pprintf(p, "Match request does not fit formula for %s:\n",
              player_globals.parray[p1].name);
      pprintf(p, "%s's formula: %s\n", player_globals.parray[p1].name, player_globals.parray[p1].formula);
      ShowClauses (p, p1, clauses);
      ClearTextList(clauses);
      pprintf_highlight(p1, "Ignoring");
      pprintf_prompt(p1, " (formula): %s (%d) %s (%d) %s.\n",
                     pp->name,
                     GetRating(&player_globals.parray[p], type),
                     player_globals.parray[p1].name,
                     GetRating(&player_globals.parray[p1], type),
            game_str(rated, wt * 60, winc, bt * 60, binc, category, board));
      return COM_OK;
    }

    if (type == TYPE_BUGHOUSE) {
      bh = 1;
      partner = pp->partner;
      pp1 = player_globals.parray[p1].partner;

      if (pp < 0) {
        pprintf(p, "You have no partner for bughouse.\n");
        return COM_OK;
      }
      if (pp1 < 0) {
        pprintf(p, "Your opponent has no partner for bughouse.\n");
        return COM_OK;
      }
      if (partner == pp1) { /* should be an impossible case - DAV */
        pprintf(p, "You and your opponent both chose the same partner!\n");
        return COM_OK;
      }
      if (partner == p1 || pp1 == p) {
        pprintf(p, "You and your opponent can't choose each other as partners!\n");
        return COM_OK;
      }
      if (player_globals.parray[partner].partner != p) { /* another impossible case - DAV */
        pprintf(p, "Your partner hasn't chosen you as his partner!\n");
        return COM_OK;
      }
      if (player_globals.parray[pp1].partner != p1) { /* another impossible case - DAV */
        pprintf(p, "Your opponent's partner hasn't chosen your opponent as his partner!\n");
        return COM_OK;
      }
      if (!CheckPFlag(partner, PFLAG_OPEN) || player_globals.parray[partner].game >= 0) {
        pprintf(p, "Your partner isn't open to play right now.\n");
        return COM_OK;
      }
      if (!CheckPFlag(pp1, PFLAG_OPEN) || player_globals.parray[pp1].game >= 0) {
        pprintf(p, "Your opponent's partner isn't open to play right now.\n");
        return COM_OK;
      }

      /* Bypass NOPLAY lists, censored lists, ratedness, privacy, and formula for now */
      /*  Active challenger/ee will determine these. */
    }
    /* Ok match offer will be made */

  }                             /* adjourned games shouldn't have to worry
                                   about that junk? */
				/* keep incase of adjourned bughouse in future*/

  if (pendto != NULL) {
    pprintf(p, "Updating offer already made to \"%s\".\n", player_globals.parray[p1].name);
  }

  if (pendfrom != NULL) {
    if (pendto != NULL) {
      pprintf(p, "Pending list error!.\n");
      d_printf( "CHESSD: This shouldn't happen. You can't have a match pending from and to the same person.\n");
      return COM_OK;
    }

    if (adjourned || ((wt == pendfrom->btime) &&
                      (winc == pendfrom->binc) &&
                      (bt == pendfrom->wtime) &&
                      (binc == pendfrom->winc) &&
                      (rated == pendfrom->rated) &&
                      ((white == -1) || (white + pendfrom->seek_color == 1)) &&
               (!strcmp(category, pendfrom->category)) &&
                 (!strcmp(board, pendfrom->board_type)))) {
      /* Identical match, should accept! */
      accept_match(pendfrom,p, p1);
      return COM_OK;

    } else {
      delete_pending(pendfrom);
    }
  }

  if (pendto == NULL)
    pend = add_pending(p,p1,PEND_MATCH);
  else
    pend = pendto;

  pend->wtime = wt;
  pend->winc = winc;
  pend->btime = bt;
  pend->binc = binc;
  pend->rated = rated;
  pend->seek_color = white;
  pend->game_type = type;
  pend->category = strdup(category);
  pend->board_type = strdup (board);

  if (pendfrom != NULL) {
    pprintf(p, "Declining offer from %s and offering new match parameters.\n", player_globals.parray[p1].name);
    pprintf(p1, "\n%s declines your match offer a match with these parameters:", pp->name);
  }

  if (pendto != NULL) {
    pprintf(p, "Updating match request to: ");
    pprintf(p1, "\n%s updates the match request.\n", pp->name);
  } else {
    pprintf(p, "Issuing: ");
    pprintf(p1, "\n");
  }

  pprintf(p, "%s (%s) %s", pp->name,
          ratstrii(GetRating(&player_globals.parray[p], type), p),
          colorstr[white + 1]);
  pprintf_highlight(p, "%s", player_globals.parray[p1].name);
  pprintf(p, " (%s) %s%s.\n",
          ratstrii(GetRating(&player_globals.parray[p1], type), p1),
          game_str(rated, wt , winc, bt , binc, category, board),
          adjustr[adjourned]);
  pprintf(p1, "Challenge: ");
  pprintf_highlight(p1, "%s", pp->name);
  pprintf(p1, " (%s) %s",
          ratstrii(GetRating(&player_globals.parray[p], type), p),
          colorstr[white + 1]);
  pprintf(p1, "%s (%s) %s%s.\n", player_globals.parray[p1].name,
          ratstrii(GetRating(&player_globals.parray[p1], type), p1),
          game_str(rated, wt , winc, bt , binc, category, board),
          adjustr[adjourned]);
  Bell (p1);

  if (bh) {

    pprintf(partner, "\nYour bughouse partner issuing %s (%s) %s",
            pp->name, ratstrii(GetRating(&player_globals.parray[p], type), p),
            colorstr[white + 1]);
    pprintf_highlight(partner, "%s", player_globals.parray[p1].name);
    pprintf(partner, " (%s) %s.\n",
            ratstrii(GetRating(&player_globals.parray[p1], type), p1),
            game_str(rated, wt , winc, bt , binc, category, board));
    pprintf(partner, "Your game would be ");
    pprintf_highlight(partner, "%s", player_globals.parray[pp1].name);
    pprintf_prompt(partner, " (%s) %s%s (%s) %s.\n",
          ratstrii(GetRating(&player_globals.parray[pp1], type), pp1),
          colorstr[white + 1], player_globals.parray[partner].name,
          ratstrii(GetRating(&player_globals.parray[partner], type), partner),
          game_str(rated, wt , winc, bt , binc, category, board));
    Bell (partner);

    pprintf(pp1, "\nYour bughouse partner was challenged ");
    pprintf_highlight(pp1, "%s", pp->name);
    pprintf(pp1, " (%s) %s", ratstrii(GetRating(&player_globals.parray[p], type), p),
                             colorstr[white + 1]);
    pprintf(pp1, "%s (%s) %s.\n", player_globals.parray[p1].name,
            ratstrii(GetRating(&player_globals.parray[p1], type), p1),
            game_str(rated, wt , winc, bt , binc, category, board));
    pprintf(pp1, "Your game would be %s (%s) %s", player_globals.parray[pp1].name,
          ratstrii(GetRating(&player_globals.parray[pp1], type), pp1),
          colorstr[white + 1]);
    pprintf_highlight(pp1, "%s", player_globals.parray[partner].name);
    pprintf_prompt(pp1, " (%s) %s.\n",
          ratstrii(GetRating(&player_globals.parray[partner], type), partner),
          game_str(rated, wt , winc, bt , binc, category, board));
    Bell(pp1);
  }

  check_lists_match (p,p1);

  print_match_rating_info (p,p1,type,rated);

  pprintf_prompt(p1, "You can \"accept\" or \"decline\", or propose different parameters.\n");

  return COM_OK;
}
Ejemplo n.º 16
0
bool ArenaTeam::AddMember(const uint64& PlayerGuid)
{
    std::string plName;
    uint8 plClass;
    uint32 plPRating;
    uint32 plMMRating;

    // arena team is full (can't have more than type * 2 players!)
    if (GetMembersSize() >= GetType() * 2)
        return false;

    Player *pl = sObjectMgr.GetPlayer(PlayerGuid);
    if (pl)
    {
        if (pl->GetArenaTeamId(GetSlot()))
        {
            sLog.outError("Arena::AddMember() : player already in this sized team");
            return false;
        }

        plClass = pl->getClass();
        plName = pl->GetName();
    }
    else
    {
        //                                                     0     1
        QueryResult result = CharacterDatabase.PQuery("SELECT name, class FROM characters WHERE guid='%u'", GUID_LOPART(PlayerGuid));
        if (!result)
            return false;

        plName = (*result)[0].GetString();
        plClass = (*result)[1].GetUInt8();

        // check if player already in arenateam of that size
        if (Player::GetArenaTeamIdFromDB(PlayerGuid, GetType()) != 0)
        {
            sLog.outError("Arena::AddMember() : player already in this sized team");
            return false;
        }
    }

    plMMRating = sWorld.getIntConfig(CONFIG_ARENA_START_MATCHMAKER_RATING);
    plPRating = 0;
    
    if (sWorld.getIntConfig(CONFIG_ARENA_START_PERSONAL_RATING) > 0)
        plPRating = sWorld.getIntConfig(CONFIG_ARENA_START_PERSONAL_RATING);
    else if (GetRating() >= 1000)
        plPRating = 1000;

    sWorld.getIntConfig(CONFIG_ARENA_START_PERSONAL_RATING);

    QueryResult result = CharacterDatabase.PQuery("SELECT matchmaker_rating FROM character_arena_stats WHERE guid='%u' AND slot='%u'", GUID_LOPART(PlayerGuid), GetSlot());
    if (result)
        plMMRating = (*result)[0].GetUInt32();

    // remove all player signs from another petitions
    // this will be prevent attempt joining player to many arenateams and corrupt arena team data integrity
    Player::RemovePetitionsAndSigns(PlayerGuid, GetType());

    ArenaTeamMember newmember;
    newmember.name              = plName;
    newmember.guid              = PlayerGuid;
    newmember.Class             = plClass;
    newmember.games_season      = 0;
    newmember.games_week        = 0;
    newmember.wins_season       = 0;
    newmember.wins_week         = 0;
    newmember.personal_rating   = plPRating;
    newmember.matchmaker_rating = plMMRating;

    m_members.push_back(newmember);

    CharacterDatabase.PExecute("INSERT INTO arena_team_member (arenateamid, guid) VALUES ('%u', '%u')", m_TeamId, GUID_LOPART(newmember.guid));

    if (pl)
    {
        pl->SetInArenaTeam(m_TeamId, GetSlot(), GetType());
        pl->SetArenaTeamIdInvited(0);

        // hide promote/remove buttons
        if (m_CaptainGuid != PlayerGuid)
            pl->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_MEMBER, 1);
        sLog.outArena("Player: %s [GUID: %u] joined arena team type: %u [Id: %u].", pl->GetName(), pl->GetGUIDLow(), GetType(), GetId());
    }
    return true;
}
Ejemplo n.º 17
0
bool ArenaTeam::AddMember(const uint64& playerGuid)
{
    std::string playerName;
    uint8 playerClass;

    // Check if arena team is full (Can't have more than type * 2 players)
    if (GetMembersSize() >= GetType() * 2)
        return false;

    // Get player name and class either from db or ObjectMgr
    Player* player = ObjectAccessor::FindPlayer(playerGuid);
    if (player)
    {
        playerClass = player->getClass();
        playerName = player->GetName();
    }
    else
    {
        //          0     1
        // SELECT name, class FROM characters WHERE guid = ?
        PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHARACTER_SELECT_CHARACTER_NAME_CLASS);
        stmt->setUInt32(0, GUID_LOPART(playerGuid));
        PreparedQueryResult result = CharacterDatabase.Query(stmt);

        if (!result)
            return false;

        playerName = (*result)[0].GetString();
        playerClass = (*result)[1].GetUInt8();
    }

    // Check if player is already in a similar arena team
    if ((player && player->GetArenaTeamId(GetSlot())) || Player::GetArenaTeamIdFromDB(playerGuid, GetType()) != 0)
    {
        sLog->outError("Arena: Player %s (guid: %u) already has an arena team of type %u", playerName.c_str(), GUID_LOPART(playerGuid), GetType());
        return false;
    }

    // Set player's personal rating
    uint32 personalRating = 0;

    if (sWorld->getIntConfig(CONFIG_ARENA_START_PERSONAL_RATING) >= 0)
        personalRating = sWorld->getIntConfig(CONFIG_ARENA_START_PERSONAL_RATING);
    else if (GetRating() >= 1000)
        personalRating = 1000;

    // Try to get player's match maker rating from db and fall back to config setting if not found
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHARACTER_SELECT_MATCH_MAKER_RATING);
    stmt->setUInt32(0, GUID_LOPART(playerGuid));
    stmt->setUInt8(1, GetSlot());
    PreparedQueryResult result = CharacterDatabase.Query(stmt);

    uint32 matchMakerRating;
    if (result)
        matchMakerRating = (*result)[0].GetUInt32();
    else
        matchMakerRating = sWorld->getIntConfig(CONFIG_ARENA_START_MATCHMAKER_RATING);

    // Remove all player signatures from other petitions
    // This will prevent player from joining too many arena teams and corrupt arena team data integrity
    Player::RemovePetitionsAndSigns(playerGuid, GetType());

    // Feed data to the struct
    ArenaTeamMember newmember;
    newmember.Name             = playerName;
    newmember.Guid             = playerGuid;
    newmember.Class            = playerClass;
    newmember.SeasonGames      = 0;
    newmember.WeekGames        = 0;
    newmember.SeasonWins       = 0;
    newmember.WeekWins         = 0;
    newmember.PersonalRating   = personalRating;
    newmember.MatchMakerRating = matchMakerRating;

    Members.push_back(newmember);

    // Save player's arena team membership to db
    stmt = CharacterDatabase.GetPreparedStatement(CHARACTER_INSERT_ARENA_TEAM_MEMBER);
    stmt->setUInt32(0, TeamId);
    stmt->setUInt32(1, GUID_LOPART(playerGuid));
    CharacterDatabase.Execute(stmt);

    // Inform player if online
    if (player)
    {
        player->SetInArenaTeam(TeamId, GetSlot(), GetType());
        player->SetArenaTeamIdInvited(0);

        // Hide promote/remove buttons
        if (CaptainGuid != playerGuid)
            player->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_MEMBER, 1);
    }

    sLog->outArena("Player: %s [GUID: %u] joined arena team type: %u [Id: %u].", playerName.c_str(), GUID_LOPART(playerGuid), GetType(), GetId());

    return true;
}
Ejemplo n.º 18
0
// Sets schedule usage for the passed period and slot numbers
void SquadronClass::ScheduleAircraft (Flight fl, MissionRequest mis)

	{
	int		i,j,sn,nv,nr,role,got=0;
	//TJL 10/30/03
	int want_alert = 0;
	VehicleClassDataType *vc;

	role = MissionData[mis->mission].skill;
	if (MissionData[mis->mission].flags & AMIS_DONT_USE_AC)
		{
		// Just fill up our slots sequentially
		for (i=0; i<VEHICLES_PER_UNIT; i++)
			{
			if (mis->aircraft < 12)
				nv = 2;
			else
				nv = 3;
			if (nv + got > mis->aircraft)
				nv = mis->aircraft-got;
			fl->SetNumVehicles(i,nv);
			got += nv;
			}
		memset(fl->slots,255,PILOTS_PER_FLIGHT);
		// Fake got for pilot assignments
		if (got > 4)
			got = 4;
		}
	else
		{
		// schedule the aircraft
		for (sn=0; sn<PILOTS_PER_FLIGHT; sn++)
			{
			if (mis->slots[sn] < VEHICLES_PER_UNIT)
				{
				// KCK: Add turn-around time to final block to determine when
				// aircraft will be available next
				int	finalBlock = mis->final_block + (AIRCRAFT_TURNAROUND_TIME_MINUTES / MIN_PLAN_AIR);
				if (finalBlock >= ATM_MAX_CYCLES)
					finalBlock = ATM_MAX_CYCLES;
				for (j=mis->start_block; j<=mis->final_block; j++)
					SetSchedule(mis->slots[sn], (1 << j));
				}
			}

		fl->SetRoster(0);
		for (i=0; i<PILOTS_PER_FLIGHT; i++)
			{
			if (mis->slots[i] < VEHICLES_PER_UNIT)
				{
				nv = GetNumVehicles(mis->slots[i]);
				if (nv+got > mis->aircraft)
					nv = mis->aircraft-got;
				got += nv;
				fl->slots[i] = mis->slots[i];
				// KCK NOTE: doing this is safe, since flight isn't inserted yet.
				fl->SetNumVehicles(fl->slots[i], nv);
				SetAssigned (GetAssigned() + nv);
				// Lower score for this role, to prevent repicks of same mission
				// KCK NOTE: this is local only - other machines will not get this data
				nr = FloatToInt32(0.75F * GetRating(role)) + 1;
				if (nr < 1)
					nr = 1;
				SetRating(role, nr);
				}
			}
		}

	// Set aircraft availablity bits
	for (i=0; i<PILOTS_PER_FLIGHT; i++)
		{
		if (i<got)
			fl->plane_stats[i] = AIRCRAFT_AVAILABLE;
		else
			fl->plane_stats[i] = AIRCRAFT_NOT_ASSIGNED;
		fl->MakeFlightDirty (DIRTY_PLANE_STATS, DDP[120].priority);
//				fl->MakeFlightDirty (DIRTY_PLANE_STATS, SEND_RELIABLE);
		fl->pilots[i] = NO_PILOT;
		}
	fl->last_player_slot = PILOTS_PER_FLIGHT;

	// Large flights (i.e.: transport 'copters) only use 4 pilots
	if (got > PILOTS_PER_FLIGHT)
		got = PILOTS_PER_FLIGHT;

	// Find and fill an empty takeoff slot at this airbase
	fl->SetUnitAirbase(GetUnitAirbaseID());
	
	// Name this flight
	vc = GetVehicleClassData(fl->GetVehicleID(0));
	fl->callsign_id = vc->CallsignIndex;
	GetCallsignID(&fl->callsign_id,&fl->callsign_num,vc->CallsignSlots);
	if (fl->callsign_num)
		SetCallsignID(fl->callsign_id,fl->callsign_num);
	}