code

성과 시스템을 코딩하는 가장 좋은 방법

codestyles 2020. 9. 17. 07:56
반응형

성과 시스템을 코딩하는 가장 좋은 방법


내 사이트에서 사용할 성과 시스템을 디자인하는 가장 좋은 방법을 생각하고 있습니다. 데이터베이스 구조는 3 개 이상의 연속 레코드 누락을 알리는 최상의 방법 에서 찾을 수 있으며이 스레드는 개발자로부터 아이디어를 얻기위한 확장입니다.

이 웹 사이트에서 배지 / 업적 시스템에 대해 많은 이야기를 할 때 제가 가진 문제는 단지 모든 이야기이고 코드가 없다는 것입니다. 실제 코드 구현 예제는 어디에 있습니까?

저는 여기에서 사람들이 기여할 수있는 디자인을 제안하고 확장 가능한 성취 시스템을 코딩하기위한 좋은 디자인을 만들 수 있기를 바랍니다. 나는 이것이 최고라고 말하는 것은 아니지만 가능한 출발점입니다.

여러분의 아이디어를 자유롭게 기여해주십시오.


내 시스템 디자인 아이디어

일반적인 합의는 "이벤트 기반 시스템"을 만드는 것입니다. 포스트 생성, 삭제 등과 같은 알려진 이벤트가 발생할 때마다 이벤트 클래스를 이렇게 호출합니다.

$event->trigger('POST_CREATED', array('id' => 8));

그런 다음 이벤트 클래스는이 이벤트에 대해 "수신"중인 배지를 찾은 다음 requires해당 파일에 추가하고 다음 과 같이 해당 클래스의 인스턴스를 만듭니다.

require '/badges/' . $file;
$badge = new $class;

그런 다음 호출 될 때 수신 된 데이터를 전달하는 기본 이벤트를 호출합니다 trigger.

$badge->default_event($data);

배지

이것이 진정한 마술이 일어나는 곳입니다. 각 배지에는 배지 수여 여부를 결정하는 자체 쿼리 / 로직이 있습니다. 각 배지는 예를 들어 다음 형식으로 설정됩니다.

class Badge_Name extends Badge
{
 const _BADGE_500 = 'POST_500';
 const _BADGE_300 = 'POST_300';
 const _BADGE_100 = 'POST_100';

 function get_user_post_count()
 {
  $escaped_user_id = mysql_real_escape_string($this->user_id);

  $r = mysql_query("SELECT COUNT(*) FROM posts
                    WHERE userid='$escaped_user_id'");
  if ($row = mysql_fetch_row($r))
  {
   return $row[0];
  }
  return 0;
 }

 function default_event($data)
 {
  $post_count = $this->get_user_post_count();
  $this->try_award($post_count);
 }

 function try_award($post_count)
 {
  if ($post_count > 500)
  {
   $this->award(self::_BADGE_500);
  }
  else if ($post_count > 300)
  {
   $this->award(self::_BADGE_300);
  }
  else if ($post_count > 100)
  {
   $this->award(self::_BADGE_100);
  }

 }
}

award function comes from an extended class Badge which basically checks to see if the user has already be awarded that badge, if not, will update the badge db table. The badge class also takes care of retrieving all badges for a user and returning it in an array, etc (so badges can be e.g. displayed on the user profile)

what about when the system is very first implemented on an already live site?

There is also a "cron" job query that can be added to each badge. The reason for this is because when the badge system is very first implemented and initilaised, the badges that should have already been earned have not yet be awarded because this is an event based system. So a CRON job is run on demand for each badge to award anything that needs to be. For example the CRON job for the above would look like:

class Badge_Name_Cron extends Badge_Name
{

 function cron_job()
 {
  $r = mysql_query('SELECT COUNT(*) as post_count, user_id FROM posts');

  while ($obj = mysql_fetch_object($r))
  {
   $this->user_id = $obj->user_id; //make sure we're operating on the right user

   $this->try_award($obj->post_count);
  }
 }

}

As the above cron class extends the main badge class, it can re-use the logic function try_award

The reason why I create a specialised query for this is although we could "simulate" previous events, i.e. go through every user post and trigger the event class like $event->trigger() it would be very slow, especially for many badges. So we instead create an optimized query.

what user gets the award? all about awarding other users based on event

The Badge class award function acts on user_id -- they will always be given the award. By default the badge is awarded to the person who CAUSED the event to happen i.e. the session user id (this is true for the default_event function, although the CRON job obviously loops through all users and awards seperate users)

So let's take an example, on a coding challenge website users submit their coding entry. The admin then judges the entries and when complete, posts the results to the challenge page for all to see. When this happens, a POSTED_RESULTS event is called.

If you want to award badges for users for all the entries posted, lets say, if they were ranked within the top 5, you should use the cron job (although bare in mind this will update for all users, not just for that challenge the results were posted for)

If you want to target a more specific area to update with the cron job, let's see if there is a way to add filtering parameters into the cron job object, and get the cron_job function to use them. For example:

class Badge_Top5 extends Badge
{
   const _BADGE_NAME = 'top5';

   function try_award($position)
   {
     if ($position <= 5)
     {
       $this->award(self::_BADGE_NAME);
     }
   }
}

class Badge_Top5_Cron extends Badge_Top5
{
   function cron_job($challenge_id = 0)
   {
     $where = '';
     if ($challenge_id)
     {
       $escaped_challenge_id = mysql_real_escape_string($challenge_id);
       $where = "WHERE challenge_id = '$escaped_challenge_id'";
     }

     $r = mysql_query("SELECT position, user_id
                       FROM challenge_entries
                       $where");

    while ($obj = mysql_fetch_object($r))
   {
      $this->user_id = $obj->user_id; //award the correct user!
      $this->try_award($obj->position);
   }
}

The cron function will still work even if the parameter is not supplied.


I've implemented a reward system once in what you would call a document oriented database (this was a mud for players). Some highlights from my implementation, translated to PHP and MySQL:

  • Every detail about the badge is stored in the users data. If you use MySQL I would have made sure that this data is in one record per user in the database for performance.

  • Every time the person in question does something, the code triggers the badge code with a given flag, for instance flag('POST_MESSAGE').

  • One event could also trigger a counter, for instance a count of number of posts. increase_count('POST_MESSAGE'). In here you could have a check (either by a hook, or just having a test in this method) that if the POST_MESSAGE count is > 300 then you should have reward a badge, for instance: flag("300_POST").

  • In the flag method, I'd put the code to reward badges. For instance, if the Flag 300_POST is sent, then the badge reward_badge("300_POST") should be called.

  • In the flag method, you should also have the users previous flags present. so you could say when the user has FIRST_COMMENT, FIRST_POST, FIRST_READ you grant badge("NEW USER"), and when you get 100_COMMENT, 100_POST, 300_READ you can grant badge("EXPERIENCED_USER")

  • All of these flags and badges need to be stored somehow. Use some way where you think of the flags as bits. If you want this to be stored really efficiently, you think of them as bits and use the code below: (Or you could just use a bare string "000000001111000" if you don't want this complexity.

$achievments = 0;
$bits = sprintf("%032b", $achievements);

/* Set bit 10 */
$bits[10] = 1;

$achievements = bindec($bits);

print "Bits: $bits\n";
print "Achievements: $achievements\n";

/* Reload */

$bits = sprintf("%032b", $achievments);

/* Set bit 5 */
$bits[5] = 1;

$achievements = bindec($bits);

print "Bits: $bits\n";
print "Achievements: $achievements\n";
  • A nice way of storing a document for the user is to use json and store the users data in a single text column. Use json_encode and json_decode to store/retrieve the data.

  • For tracking activity on some of the users data manipulated by some other user, add a data structure on the item and use counters there as well. For instance read count. Use the same technique as described above for awarding badges, but the update should of course go into the owning users post. (For instance article read 1000 times badge).


UserInfuser is an open source gamification platform which implements a badging/points service. You can check out its API here: http://code.google.com/p/userinfuser/wiki/API_Documentation

I implemented it and tried to keep the number of functions minimal. Here is the API for a php client:

class UserInfuser($account, $api_key)
{
    public function get_user_data($user_id);
    public function update_user($user_id);
    public function award_badge($badge_id, $user_id);
    public function remove_badge($badge_id, $user_id);
    public function award_points($user_id, $points_awarded);
    public function award_badge_points($badge_id, $user_id, $points_awarded, $points_required);
    public function get_widget($user_id, $widget_type);
}

The end result is to show the data in a meaningful way through the use of widgets. These widgets include: trophy case, leaderboard, milestones, live notifications, rank and points.

The implementation of the API can be found here: http://code.google.com/p/userinfuser/source/browse/trunk/serverside/api/api.py


Achievements can be burdensome and even more so if you have to add them in later, unless you have a well-formed Event class.

This segues into my technique of implementing achievements.

I like to split them first into 'categories' and within those have tiers of accomplishment. i.e. a kills category in a game may have an award at 1 for first kill, 10 ten kills, 1000 thousand kills etc.

Then to the spine of any good application, the class handling your events. Again imagining a game with kills; when a player kills something, stuff happens. The kill is noted, etc and that is best handled in a centralized location, like and Events class that can dispatch info to other places involved.

It falls perfectly into place there, that in the proper method, instantiate your Achievements class and check it the player is due one.

As building the Achievements class it is trivial, just something that checks the database to see if the player has as many kills as are required for the next achievement.

I like to store user's achievements in a BitField using Redis but the same technique can be used in MySQL. That is, you can store the player's achievements as an int and then and that int with the bit you have defined as that achievement to see if they have already gained it. That way it uses only a single int column in the database.

The downside to this is you have to have them organized well and you will likely need to make some comments in your code so you will remember what 2^14 corresponds to later. If your achievements are enumerated in their own table then you can just do 2^pk where pk is the primary key of the achievements table. That makes the check something like

if(((2**$pk) & ($usersAchInt)) > 0){
  // fire off the giveAchievement() event 
} 

This way you can add achievements later and it will dovetail fine, just NEVER change the primary key of the achievements already awarded.

참고URL : https://stackoverflow.com/questions/4192653/best-way-to-code-achievements-system

반응형