Counting Objects [by John Evans]
Snippet Posted Wednesday, August 12th @ 11:25:44 PM, by George Greer in the Utils dept.
Added Jul 6, 1998. Click the link below to read it or download it.

From: John Evans <evansj@DATAWEST.NET>
Subject: My version of counting objects.

This is a simple drop-in tid-bit of code that returns the number of items
that someone is in possession of. It counts through containers recursively
so that if someone puts 14 things in a sack that is put in a sack that is
put in a sack that is put in a sack that is put in a sack that is put in a
sack that is put in a sack, it will still count the 14 items and all of
the sacks.

----------
File: utils.h
----------
int     item_count(struct char_data *ch);


----------
File: utils.c
----------
/* Will return the number of items in the container. */
int count_contents(struct obj_data *container)
{
  int count = 0;
  struct obj_data *obj;

  if (container->contains)
    for (obj = container->contains; obj; obj = obj->next_content, count++)
      if (GET_OBJ_TYPE(obj) == ITEM_CONTAINER && obj->contains)
        count += count_contents(obj);

  return(count);
}

/* Will return the number of items that the character owns. */
int item_count(struct char_data *ch)
{
  int i, count = 0;
  struct obj_data *obj;

  for (i = 0; i < NUM_WEARS; i++) {
    if (GET_EQ(ch, i)) {
      count++;
      if (GET_OBJ_TYPE(GET_EQ(ch, i)) == ITEM_CONTAINER &&
          GET_EQ(ch, i)->contains)
        count += count_contents(GET_EQ(ch, i));
    }
  }

  if (ch->carrying)
    for (obj = ch->carrying; obj; obj = obj->next_content, count++)
      if (GET_OBJ_TYPE(obj) == ITEM_CONTAINER && obj->contains)
        count += count_contents(obj);

  return(count);
}


That allows you to do something similar to the following in do_score():

  sprintf(buf, "You possess %d items.\r\n", item_count(ch));
  send_to_char(buf, ch);


Easy enough, eh?

John Evans <evansj@datawest.net>


<< Colour For Circle (More - Updated) [by Jason Berg] | Reply | View as text | Flattened | Damage Message Code [by d. Hall] >>

 


Related Links
  download
Related Articles
More by greerga
 
 

CircleMUD Snippets
 
Note: Not all of these snippets will work perfectly with your version of code, so be prepared to fix one or two bugs that may arise, and please let me know what you needed to do to fix it. Sending a corrected version is always welcome.
Finally, if you wish to use any of the snippets from this page, you are more than welcome, just mention the authors in your credits. If you wish to release any of these snippets to the public on another site, contact me FIRST.