ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/server/player.c
Revision: 1.2
Committed: Fri Feb 3 07:25:25 2006 UTC (18 years, 3 months ago) by root
Content type: text/plain
Branch: MAIN
Changes since 1.1: +18 -6 lines
Log Message:
initial cfperl/cf.schmorp.de import

File Contents

# User Rev Content
1 root 1.1 /*
2     * static char *rcsid_player_c =
3 root 1.2 * "$Id: player.c,v 1.1.1.1 2006/02/03 07:14:35 root Exp $";
4 root 1.1 */
5    
6     /*
7     CrossFire, A Multiplayer game for X-windows
8    
9     Copyright (C) 2002 Mark Wedel & Crossfire Development Team
10     Copyright (C) 1992 Frank Tore Johansen
11    
12     This program is free software; you can redistribute it and/or modify
13     it under the terms of the GNU General Public License as published by
14     the Free Software Foundation; either version 2 of the License, or
15     (at your option) any later version.
16    
17     This program is distributed in the hope that it will be useful,
18     but WITHOUT ANY WARRANTY; without even the implied warranty of
19     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20     GNU General Public License for more details.
21    
22     You should have received a copy of the GNU General Public License
23     along with this program; if not, write to the Free Software
24     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25    
26     The author can be reached via e-mail to crossfire-devel@real-time.com
27     */
28    
29     #include <global.h>
30     #ifndef WIN32 /* ---win32 remove headers */
31     #include <pwd.h>
32     #endif
33     #ifndef __CEXTRACT__
34     #include <sproto.h>
35     #endif
36     #include <sounds.h>
37     #include <living.h>
38     #include <object.h>
39     #include <spells.h>
40     #include <skills.h>
41     #include <newclient.h>
42    
43 root 1.2 extern int same_party (partylist *a, partylist *b);
44    
45 root 1.1 player *find_player(const char *plname)
46     {
47     player *pl;
48     for(pl=first_player;pl!=NULL;pl=pl->next)
49     {
50     if(pl->ob != NULL && !strcmp(query_name(pl->ob),plname))
51     return pl;
52     };
53     return NULL;
54     }
55    
56     player* find_player_partial_name( const char* plname )
57     {
58     player* pl;
59     player* found = NULL;
60     size_t namelen = strlen( plname );
61     for ( pl = first_player; pl != NULL; pl = pl->next )
62     {
63     if ( strlen( pl->ob->name ) < namelen )
64     continue;
65    
66     if ( !strcmp( pl->ob->name, plname) )
67     return pl;
68    
69     if ( !strncasecmp( pl->ob->name, plname, namelen ) )
70     {
71     if ( found )
72     return NULL;
73    
74     found = pl;
75     }
76     }
77     return found;
78     }
79    
80     void display_motd(object *op) {
81     char buf[MAX_BUF];
82     char motd[HUGE_BUF];
83     FILE *fp;
84     int comp;
85     int size;
86    
87     sprintf(buf, "%s/%s", settings.confdir, settings.motd);
88     if ((fp=open_and_uncompress(buf, 0, &comp)) == NULL) {
89     return;
90     }
91     motd[0]='\0';
92     size=0;
93     while (fgets(buf, MAX_BUF, fp) != NULL) {
94     if( *buf == '#')
95     continue;
96     strncat(motd+size,buf,HUGE_BUF-size);
97     size+=strlen(buf);
98     }
99     draw_ext_info(NDI_UNIQUE | NDI_GREEN, 0, op, MSG_TYPE_MOTD, MSG_SUBTYPE_NONE, motd, NULL);
100     close_and_delete(fp, comp);
101     }
102    
103     void send_rules(object *op) {
104     char buf[MAX_BUF];
105     char rules[HUGE_BUF];
106     FILE *fp;
107     int comp;
108     int size;
109    
110     sprintf(buf, "%s/%s", settings.confdir, settings.rules);
111     if ((fp=open_and_uncompress(buf, 0, &comp)) == NULL) {
112     return;
113     }
114     rules[0]='\0';
115     size=0;
116     while (fgets(buf, MAX_BUF, fp) != NULL) {
117     if( *buf == '#')
118     continue;
119     if (size + strlen(buf)>=HUGE_BUF)
120     {
121     LOG(llevDebug, "Warning, rules size is > %d bytes.\n", HUGE_BUF);
122     break;
123     }
124     strncat(rules+size,buf,HUGE_BUF-size);
125     size+=strlen(buf);
126     }
127     draw_ext_info(NDI_UNIQUE | NDI_GREEN, 0, op, MSG_TYPE_ADMIN, MSG_TYPE_ADMIN_RULES, rules, NULL);
128     close_and_delete(fp, comp);
129     }
130    
131     void send_news(object *op) {
132     char buf[MAX_BUF];
133     char news[HUGE_BUF];
134     char subject[MAX_BUF];
135     FILE *fp;
136     int comp;
137     int size;
138    
139     sprintf(buf, "%s/%s", settings.confdir, settings.news);
140     if ((fp=open_and_uncompress(buf, 0, &comp)) == NULL)
141     return;
142     news[0]='\0';
143     subject[0]='\0';
144     size=0;
145     while (fgets(buf, MAX_BUF, fp) != NULL) {
146     if( *buf == '#')
147     continue;
148     if ( *buf =='%'){ /* send one news */
149     if (size>0)
150     draw_ext_info_format(NDI_UNIQUE | NDI_GREEN, 0, op,
151     MSG_TYPE_ADMIN, MSG_TYPE_ADMIN_NEWS,
152     "!! informations: %s\n%s",
153     "%s\n%s",
154     subject, news); /*send previously read news*/
155     strcpy(subject,buf+1);
156     strip_endline(subject);
157     size=0;
158     news[0]='\0';
159     }
160     else{
161     if (size + strlen(buf)>=HUGE_BUF)
162     {
163     LOG(llevDebug, "Warning, one news item has size > %d bytes.\n", HUGE_BUF);
164     break;
165     }
166     strncat(news+size,buf,HUGE_BUF-size);
167     size+=strlen(buf);
168     }
169     }
170    
171     draw_ext_info_format(NDI_UNIQUE | NDI_GREEN, 0, op,
172     MSG_TYPE_ADMIN, MSG_TYPE_ADMIN_NEWS,
173     "!! informations: %s\n%s\n",
174     "%s\n%s",
175     subject, news);
176     close_and_delete(fp, comp);
177     }
178    
179     int playername_ok(const char *cp) {
180     /* Don't allow - or _ as first character in the name */
181     if (*cp == '-' || *cp == '_') return 0;
182    
183     for(;*cp!='\0';cp++)
184     if(!((*cp>='a'&&*cp<='z')||(*cp>='A'&&*cp<='Z'))&&*cp!='-'&&*cp!='_')
185     return 0;
186     return 1;
187     }
188    
189     /* This no longer sets the player map. Also, it now updates
190     * all the pointers so the caller doesn't need to do that.
191     * Caller is responsible for setting the correct map.
192     */
193    
194     /* Redo this to do both get_player_ob and get_player.
195     * Hopefully this will be less bugfree and simpler.
196     * Returns the player structure. If 'p' is null,
197     * we create a new one. Otherwise, we recycle
198     * the one that is passed.
199     */
200     static player* get_player(player *p) {
201     object *op=arch_to_object(get_player_archetype(NULL));
202     int i;
203    
204     if (!p) {
205     player *tmp;
206    
207     p = (player *) malloc(sizeof(player));
208     if(p==NULL)
209     fatal(OUT_OF_MEMORY);
210    
211     /* This adds the player in the linked list. There is extra
212     * complexity here because we want to add the new player at the
213     * end of the list - there is in fact no compelling reason that
214     * that needs to be done except for things like output of
215     * 'who'.
216     */
217     tmp=first_player;
218     while(tmp!=NULL&&tmp->next!=NULL)
219     tmp=tmp->next;
220     if(tmp!=NULL)
221     tmp->next=p;
222     else
223     first_player=p;
224    
225     p->next = NULL;
226     }
227    
228     /* Clears basically the entire player structure except
229     * for next and socket.
230     */
231     memset((void*)((char*)p + offsetof(player, maplevel)), 0,
232     sizeof(player) - offsetof(player, maplevel));
233    
234     /* There are some elements we want initialized to non zero value -
235     * we deal with that below this point.
236     */
237     p->party=NULL;
238     p->outputs_sync=16; /* Every 2 seconds */
239     p->outputs_count=1; /* Keeps present behaviour */
240     p->unapply = unapply_nochoice;
241     p->Swap_First = -1;
242    
243     #ifdef AUTOSAVE
244     p->last_save_tick = 9999999;
245     #endif
246    
247     strcpy(p->savebed_map, first_map_path); /* Init. respawn position */
248    
249     op->contr=p; /* this aren't yet in archetype */
250     p->ob = op;
251     op->speed_left=0.5;
252     op->speed=1.0;
253     op->direction=5; /* So player faces south */
254     op->stats.wc=2;
255     op->run_away = 25; /* Then we panick... */
256    
257     roll_stats(op);
258     p->state=ST_ROLL_STAT;
259     clear_los(op);
260    
261     p->gen_sp_armour=10;
262     p->last_speed= -1;
263     p->shoottype=range_none;
264     p->bowtype=bow_normal;
265     p->petmode=pet_normal;
266     p->listening=9;
267     p->last_weapon_sp= -1;
268     p->peaceful=1; /* default peaceful */
269     p->do_los=1;
270     p->explore=0;
271     p->no_shout=0; /* default can shout */
272    
273     strncpy(p->title, op->arch->clone.name, sizeof(p->title)-1);
274     p->title[sizeof(p->title)-1] = '\0';
275     op->race = add_string (op->arch->clone.race);
276    
277     CLEAR_FLAG(op,FLAG_READY_SKILL);
278    
279     /* we need to clear these to -1 and not zero - otherwise,
280     * if a player quits and starts a new character, we wont
281     * send new values to the client, as things like exp start
282     * at zero.
283     */
284     for (i=0; i < NUM_SKILLS; i++) {
285     p->last_skill_exp[i] = -1;
286     p->last_skill_ob[i] = NULL;
287     }
288     for (i=0; i < NROFATTACKS; i++) {
289     p->last_resist[i] = -1;
290     }
291     p->last_stats.exp = -1;
292     p->last_weight = (uint32)-1;
293    
294     p->socket.update_look=0;
295     p->socket.look_position=0;
296     return p;
297     }
298    
299    
300     /* This loads the first map an puts the player on it. */
301     static void set_first_map(object *op)
302     {
303     strcpy(op->contr->maplevel, first_map_path);
304     op->x = -1;
305     op->y = -1;
306     enter_exit(op, NULL);
307     }
308    
309     /* Tries to add player on the connection passwd in ns.
310     * All we can really get in this is some settings like host and display
311     * mode.
312     */
313    
314     int add_player(NewSocket *ns) {
315     player *p;
316    
317     p=get_player(NULL);
318     memcpy(&p->socket, ns, sizeof(NewSocket));
319     p->socket.faces_sent = malloc(p->socket.faces_sent_len*sizeof(*p->socket.faces_sent));
320     if(p->socket.faces_sent == NULL)
321     fatal(OUT_OF_MEMORY);
322     memcpy(p->socket.faces_sent, ns->faces_sent, p->socket.faces_sent_len*sizeof(*p->socket.faces_sent));
323     /* Needed because the socket we just copied over needs to be cleared.
324     * Note that this can result in a client reset if there is partial data
325     * on the uncoming socket.
326     */
327     p->socket.inbuf.len = 0;
328     set_first_map(p->ob);
329    
330     CLEAR_FLAG(p->ob, FLAG_FRIENDLY);
331     add_friendly_object(p->ob);
332     send_rules(p->ob);
333     send_news(p->ob);
334     display_motd(p->ob);
335     get_name(p->ob);
336     return 0;
337     }
338    
339     /*
340     * get_player_archetype() return next player archetype from archetype
341     * list. Not very efficient routine, but used only creating new players.
342     * Note: there MUST be at least one player archetype!
343     */
344     archetype *get_player_archetype(archetype* at)
345     {
346     archetype *start = at;
347     for (;;) {
348     if (at==NULL || at->next==NULL)
349     at=first_archetype;
350     else
351     at=at->next;
352     if(at->clone.type==PLAYER)
353     return at;
354     if (at == start) {
355     LOG (llevError, "No Player archetypes\n");
356     exit (-1);
357     }
358     }
359     }
360    
361    
362     object *get_nearest_player(object *mon) {
363     object *op = NULL;
364     player *pl = NULL;
365     objectlink *ol;
366     unsigned lastdist;
367     rv_vector rv;
368    
369     for(ol=first_friendly_object,lastdist=1000;ol!=NULL;ol=ol->next) {
370     /* We should not find free objects on this friendly list, but it
371     * does periodically happen. Given that, lets deal with it.
372     * While unlikely, it is possible the next object on the friendly
373     * list is also free, so encapsulate this in a while loop.
374     */
375     while (QUERY_FLAG(ol->ob, FLAG_FREED) || !QUERY_FLAG(ol->ob, FLAG_FRIENDLY)) {
376     object *tmp=ol->ob;
377    
378     /* Can't do much more other than log the fact, because the object
379     * itself will have been cleared.
380     */
381     LOG(llevDebug,"get_nearest_player: Found free/non friendly object on friendly list\n");
382     ol = ol->next;
383     remove_friendly_object(tmp);
384     if (!ol) return op;
385     }
386    
387     /* Remove special check for player from this. First, it looks to cause
388     * some crashes (ol->ob->contr not set properly?), but secondly, a more
389     * complicated method of state checking would be needed in any case -
390     * as it was, a clever player could type quit, and the function would
391     * skip them over while waiting for confirmation. Remove
392     * on_same_map check, as can_detect_enemy also does this
393     */
394     if (!can_detect_enemy(mon,ol->ob,&rv))
395     continue;
396    
397     if(lastdist>rv.distance) {
398     op=ol->ob;
399     lastdist=rv.distance;
400     }
401     }
402     for (pl=first_player; pl != NULL; pl=pl->next) {
403     if (on_same_map(mon, pl->ob)&& can_detect_enemy(mon, pl->ob,&rv)) {
404    
405     if(lastdist>rv.distance) {
406     op=pl->ob;
407     lastdist=rv.distance;
408     }
409     }
410     }
411     #if 0
412     LOG(llevDebug,"get_nearest_player() finds player: %s\n",op?op->name:"(null)");
413     #endif
414     return op;
415     }
416    
417     /* I believe this can safely go to 2, 3 is questionable, 4 will likely
418     * result in a monster paths backtracking. It basically determines how large a
419     * detour a monster will take from the direction path when looking
420     * for a path to the player. The values are in the amount of direction
421     * the deviation is
422     */
423     #define DETOUR_AMOUNT 2
424    
425     /* This is used to prevent infinite loops. Consider a case where the
426     * player is in a chamber (with gate closed), and monsters are outside.
427     * with DETOUR_AMOUNT==2, the function will turn each corner, trying to
428     * find a path into the chamber. This is a good thing, but since there
429     * is no real path, it will just keep circling the chamber for
430     * ever (this could be a nice effect for monsters, but not for the function
431     * to get stuck in. I think for the monsters, if max is reached and
432     * we return the first direction the creature could move would result in the
433     * circling behaviour. Unfortunately, this function is also used to determined
434     * if the creature should cast a spell, so returning a direction in that case
435     * is probably not a good thing.
436     */
437     #define MAX_SPACES 50
438    
439    
440     /*
441     * Returns the direction to the player, if valid. Returns 0 otherwise.
442     * modified to verify there is a path to the player. Does this by stepping towards
443     * player and if path is blocked then see if blockage is close enough to player that
444     * direction to player is changed (ie zig or zag). Continue zig zag until either
445     * reach player or path is blocked. Thus, will only return true if there is a free
446     * path to player. Though path may not be a straight line. Note that it will find
447     * player hiding along a corridor at right angles to the corridor with the monster.
448     *
449     * Modified by MSW 2001-08-06 to handle tiled maps. Various notes:
450     * 1) With DETOUR_AMOUNT being 2, it should still go and find players hiding
451     * down corriders.
452     * 2) I think the old code was broken if the first direction the monster
453     * should move was blocked - the code would store the first direction without
454     * verifying that the player can actually move in that direction. The new
455     * code does not store anything in firstdir until we have verified that the
456     * monster can in fact move one space in that direction.
457     * 3) I'm not sure how good this code will be for moving multipart monsters,
458     * since only simple checks to blocked are being called, which could mean the monster
459     * is blocking itself.
460     */
461     int path_to_player(object *mon, object *pl, unsigned mindiff) {
462     rv_vector rv;
463     sint16 x,y;
464     int lastx,lasty,dir,i,diff, firstdir=0,lastdir, max=MAX_SPACES, mflags, blocked;
465     mapstruct *m ,*lastmap;
466    
467     get_rangevector(mon, pl, &rv, 0);
468    
469     if (rv.distance<mindiff) return 0;
470    
471     x=mon->x;
472     y=mon->y;
473     m=mon->map;
474     dir = rv.direction;
475     lastdir = firstdir = rv.direction; /* perhaps we stand next to pl, init firstdir too */
476     diff = FABS(rv.distance_x)>FABS(rv.distance_y)?FABS(rv.distance_x):FABS(rv.distance_y);
477     /* If we can't solve it within the search distance, return now. */
478     if (diff>max) return 0;
479     while (diff >1 && max>0) {
480     lastx = x;
481     lasty = y;
482     lastmap = m;
483     x = lastx + freearr_x[dir];
484     y = lasty + freearr_y[dir];
485    
486     mflags = get_map_flags(m, &m, x, y, &x, &y);
487     blocked = (mflags & P_OUT_OF_MAP) ? MOVE_ALL : GET_MAP_MOVE_BLOCK(m, x, y);
488    
489     /* Space is blocked - try changing direction a little */
490     if ((mflags & P_OUT_OF_MAP) || ((OB_TYPE_MOVE_BLOCK(mon, blocked))
491     && (m == mon->map && blocked_link(mon, m, x, y)))) {
492     /* recalculate direction from last good location. Possible
493     * we were not traversing ideal location before.
494     */
495     get_rangevector_from_mapcoord(lastmap, lastx, lasty, pl, &rv, 0);
496     if (rv.direction != dir) {
497     /* OK - says direction should be different - lets reset the
498     * the values so it will try again.
499     */
500     x = lastx;
501     y = lasty;
502     m = lastmap;
503     dir = firstdir = rv.direction;
504     } else {
505     /* direct path is blocked - try taking a side step to
506     * either the left or right.
507     * Note increase the values in the loop below to be
508     * more than -1/1 respectively will mean the monster takes
509     * bigger detour. Have to be careful about these values getting
510     * too big (3 or maybe 4 or higher) as the monster may just try
511     * stepping back and forth
512     */
513     for (i=-DETOUR_AMOUNT; i<=DETOUR_AMOUNT; i++) {
514     if (i==0) continue; /* already did this, so skip it */
515     /* Use lastdir here - otherwise,
516     * since the direction that the creature should move in
517     * may change, you could get infinite loops.
518     * ie, player is northwest, but monster can only
519     * move west, so it does that. It goes some distance,
520     * gets blocked, finds that it should move north,
521     * can't do that, but now finds it can move east, and
522     * gets back to its original point. lastdir contains
523     * the last direction the creature has successfully
524     * moved.
525     */
526    
527     x = lastx + freearr_x[absdir(lastdir+i)];
528     y = lasty + freearr_y[absdir(lastdir+i)];
529     m = lastmap;
530     mflags = get_map_flags(m, &m, x, y, &x, &y);
531     if (mflags & P_OUT_OF_MAP) continue;
532     blocked = GET_MAP_MOVE_BLOCK(m, x, y);
533     if (OB_TYPE_MOVE_BLOCK(mon, blocked)) continue;
534    
535     if (m == mon->map && blocked_link(mon, m, x, y)) break;
536     }
537     /* go through entire loop without finding a valid
538     * sidestep to take - thus, no valid path.
539     */
540     if (i==(DETOUR_AMOUNT+1))
541     return 0;
542     diff--;
543     lastdir=dir;
544     max--;
545     if (!firstdir) firstdir = dir+i;
546     } /* else check alternate directions */
547     } /* if blocked */
548     else {
549     /* we moved towards creature, so diff is less */
550     diff--;
551     max--;
552     lastdir=dir;
553     if (!firstdir) firstdir = dir;
554     }
555     if (diff<=1) {
556     /* Recalculate diff (distance) because we may not have actually
557     * headed toward player for entire distance.
558     */
559     get_rangevector_from_mapcoord(m, x, y, pl, &rv, 0);
560     diff = FABS(rv.distance_x)>FABS(rv.distance_y)?FABS(rv.distance_x):FABS(rv.distance_y);
561     }
562     if (diff>max) return 0;
563     }
564     /* If we reached the max, didn't find a direction in time */
565     if (!max) return 0;
566    
567     return firstdir;
568     }
569    
570     void give_initial_items(object *pl,treasurelist *items) {
571     object *op,*next=NULL;
572    
573     if(pl->randomitems!=NULL)
574     create_treasure(items,pl,GT_STARTEQUIP | GT_ONLY_GOOD,1,0);
575    
576     for (op=pl->inv; op; op=next) {
577     next = op->below;
578    
579     /* Forces get applied per default, unless they have the
580     * flag "neutral" set. Sorry but I can't think of a better way
581     */
582     if(op->type==FORCE && !QUERY_FLAG(op, FLAG_NEUTRAL))
583     SET_FLAG(op,FLAG_APPLIED);
584    
585     /* we never give weapons/armour if these cannot be used
586     * by this player due to race restrictions
587     */
588     if (pl->type == PLAYER) {
589     if ((!QUERY_FLAG(pl, FLAG_USE_ARMOUR) &&
590     (op->type == ARMOUR || op->type == BOOTS ||
591     op->type == CLOAK || op->type == HELMET ||
592     op->type == SHIELD || op->type == GLOVES ||
593     op->type == BRACERS || op->type == GIRDLE)) ||
594     (!QUERY_FLAG(pl, FLAG_USE_WEAPON) && op->type == WEAPON)) {
595     remove_ob (op);
596     free_object (op);
597     continue;
598     }
599     }
600    
601     /* This really needs to be better - we should really give
602     * a substitute spellbook. The problem is that we don't really
603     * have a good idea what to replace it with (need something like
604     * a first level treasurelist for each skill.)
605     * remove duplicate skills also
606     */
607     if(op->type==SPELLBOOK || op->type == SKILL) {
608     object *tmp;
609    
610     for (tmp=op->below; tmp; tmp=tmp->below)
611     if (tmp->type == op->type && tmp->name == op->name) break;
612    
613     if (tmp) {
614     remove_ob(op);
615     free_object(op);
616     LOG(llevError,"give_initial_items: Removing duplicate object %s\n",
617     tmp->name);
618     continue;
619     }
620     if (op->nrof > 1) op->nrof = 1;
621     }
622    
623     if (op->type == SPELLBOOK && op->inv) {
624     CLEAR_FLAG(op->inv, FLAG_STARTEQUIP);
625     }
626    
627     /* Give starting characters identified, uncursed, and undamned
628     * items. Just don't identify gold or silver, or it won't be
629     * merged properly.
630     */
631     if (need_identify(op)) {
632     SET_FLAG(op, FLAG_IDENTIFIED);
633     CLEAR_FLAG(op, FLAG_CURSED);
634     CLEAR_FLAG(op, FLAG_DAMNED);
635     }
636     if(op->type==SPELL) {
637     remove_ob(op);
638     free_object(op);
639     continue;
640     }
641     if(op->type==SKILL) {
642     SET_FLAG(op, FLAG_CAN_USE_SKILL);
643     op->stats.exp = 0;
644     op->level = 1;
645     }
646     } /* for loop of objects in player inv */
647    
648     /* Need to set up the skill pointers */
649     link_player_skills(pl);
650     }
651    
652     void get_name(object *op) {
653     op->contr->write_buf[0]='\0';
654     op->contr->state=ST_GET_NAME;
655     send_query(&op->contr->socket,0,"What is your name?\n:");
656     }
657    
658     void get_password(object *op) {
659     op->contr->write_buf[0]='\0';
660     op->contr->state=ST_GET_PASSWORD;
661     send_query(&op->contr->socket,CS_QUERY_HIDEINPUT, "What is your password?\n:");
662     }
663    
664     void play_again(object *op)
665     {
666     op->contr->state=ST_PLAY_AGAIN;
667     op->chosen_skill = NULL;
668     send_query(&op->contr->socket, CS_QUERY_SINGLECHAR, "Do you want to play again (a/q)?");
669     /* a bit of a hack, but there are various places early in th
670     * player creation process that a user can quit (eg, roll
671     * stats) that isn't removing the player. Taking a quick
672     * look, there are many places that call play_again without
673     * removing the player - it probably makes more sense
674     * to leave it to play_again to remove the object in all
675     * cases.
676     */
677     if (!QUERY_FLAG(op, FLAG_REMOVED))
678     remove_ob(op);
679     /* Need to set this to null - otherwise, it could point to garbage,
680     * and draw() doesn't check to see if the player is removed, only if
681     * the map is null or not swapped out.
682     */
683     op->map = NULL;
684     }
685    
686    
687     int receive_play_again(object *op, char key)
688     {
689     if(key=='q'||key=='Q') {
690     remove_friendly_object(op);
691     leave(op->contr,0); /* ericserver will draw the message */
692     return 2;
693     }
694     else if(key=='a'||key=='A') {
695     player *pl = op->contr;
696     const char *name = op->name;
697    
698     add_refcount(name);
699     remove_friendly_object(op);
700     free_object(op);
701     pl = get_player(pl);
702     op = pl->ob;
703     add_friendly_object(op);
704     op->contr->password[0]='~';
705     FREE_AND_CLEAR_STR(op->name);
706     FREE_AND_CLEAR_STR(op->name_pl);
707    
708     /* Lets put a space in here */
709     new_draw_info(NDI_UNIQUE, 0, op, "\n");
710     get_name(op);
711     op->name = name; /* Alrady added a refcount above */
712     op->name_pl = add_string(name);
713     set_first_map(op);
714     } else {
715     /* user pressed something else so just ask again... */
716     play_again(op);
717     }
718     return 0;
719     }
720    
721     void confirm_password(object *op) {
722    
723     op->contr->write_buf[0]='\0';
724     op->contr->state=ST_CONFIRM_PASSWORD;
725     send_query(&op->contr->socket, CS_QUERY_HIDEINPUT, "Please type your password again.\n:");
726     }
727    
728     void get_party_password(object *op, partylist *party) {
729     if (party == NULL) {
730     LOG(llevError, "get_party_password(): tried to make player %s join a NULL party", op->name);
731     return;
732     }
733     op->contr->write_buf[0]='\0';
734     op->contr->state=ST_GET_PARTY_PASSWORD;
735     op->contr->party_to_join = party;
736     send_query(&op->contr->socket, CS_QUERY_HIDEINPUT, "What is the password?\n:");
737     }
738    
739    
740     /* This rolls four 1-6 rolls and sums the best 3 of the 4. */
741     int roll_stat(void) {
742     int a[4],i,j,k;
743    
744     for(i=0;i<4;i++)
745     a[i]=(int)RANDOM()%6+1;
746    
747     for(i=0,j=0,k=7;i<4;i++)
748     if(a[i]<k)
749     k=a[i],j=i;
750    
751     for(i=0,k=0;i<4;i++) {
752     if(i!=j)
753     k+=a[i];
754     }
755     return k;
756     }
757    
758     void roll_stats(object *op) {
759     int sum=0;
760     int i = 0, j = 0;
761     int statsort[7];
762    
763     do {
764     op->stats.Str=roll_stat();
765     op->stats.Dex=roll_stat();
766     op->stats.Int=roll_stat();
767     op->stats.Con=roll_stat();
768     op->stats.Wis=roll_stat();
769     op->stats.Pow=roll_stat();
770     op->stats.Cha=roll_stat();
771     sum=op->stats.Str+op->stats.Dex+op->stats.Int+
772     op->stats.Con+op->stats.Wis+op->stats.Pow+
773     op->stats.Cha;
774     } while(sum<82||sum>116);
775    
776     /* Sort the stats so that rerolling is easier... */
777     statsort[0] = op->stats.Str;
778     statsort[1] = op->stats.Dex;
779     statsort[2] = op->stats.Int;
780     statsort[3] = op->stats.Con;
781     statsort[4] = op->stats.Wis;
782     statsort[5] = op->stats.Pow;
783     statsort[6] = op->stats.Cha;
784    
785     /* a quick and dirty bubblesort? */
786     do {
787     if (statsort[i] < statsort[i + 1]) {
788     j = statsort[i];
789     statsort[i] = statsort[i + 1];
790     statsort[i + 1] = j;
791     i = 0;
792     } else {
793     i++;
794     }
795     } while (i < 6);
796    
797     op->stats.Str = statsort[0];
798     op->stats.Dex = statsort[1];
799     op->stats.Con = statsort[2];
800     op->stats.Int = statsort[3];
801     op->stats.Wis = statsort[4];
802     op->stats.Pow = statsort[5];
803     op->stats.Cha = statsort[6];
804    
805    
806     op->contr->orig_stats.Str=op->stats.Str;
807     op->contr->orig_stats.Dex=op->stats.Dex;
808     op->contr->orig_stats.Int=op->stats.Int;
809     op->contr->orig_stats.Con=op->stats.Con;
810     op->contr->orig_stats.Wis=op->stats.Wis;
811     op->contr->orig_stats.Pow=op->stats.Pow;
812     op->contr->orig_stats.Cha=op->stats.Cha;
813    
814     op->level=1;
815     op->stats.exp=0;
816     op->stats.ac=0;
817    
818     op->contr->levhp[1] = 9;
819     op->contr->levsp[1] = 6;
820     op->contr->levgrace[1] = 3;
821    
822     fix_player(op);
823     op->stats.hp = op->stats.maxhp;
824     op->stats.sp = op->stats.maxsp;
825     op->stats.grace = op->stats.maxgrace;
826     op->contr->orig_stats=op->stats;
827     }
828    
829     void Roll_Again(object *op)
830     {
831     esrv_new_player(op->contr, 0);
832     send_query(&op->contr->socket,CS_QUERY_SINGLECHAR,"[y] to roll new stats [n] to use stats\n[1-7] [1-7] to swap stats.\nRoll again (y/n/1-7)? ");
833     }
834    
835     void Swap_Stat(object *op,int Swap_Second)
836     {
837     signed char tmp;
838     char buf[MAX_BUF];
839    
840     if ( op->contr->Swap_First == -1 ) {
841     new_draw_info(NDI_UNIQUE, 0,op,"How the hell did you get here?!?!!!");
842     new_draw_info(NDI_UNIQUE, 0,op,"Error in Swap_Stat code,");
843     new_draw_info(NDI_UNIQUE, 0,op,"mail korg@rdt.monash.edu.au");
844     return;
845     }
846    
847     tmp = get_attr_value(&op->contr->orig_stats, op->contr->Swap_First);
848    
849     set_attr_value(&op->contr->orig_stats, op->contr->Swap_First,
850     get_attr_value(&op->contr->orig_stats, Swap_Second));
851    
852     set_attr_value(&op->contr->orig_stats, Swap_Second, tmp);
853    
854     sprintf(buf,"%s done\n", short_stat_name[Swap_Second]);
855     new_draw_info(NDI_UNIQUE, 0,op, buf);
856     op->stats.Str = op->contr->orig_stats.Str;
857     op->stats.Dex = op->contr->orig_stats.Dex;
858     op->stats.Con = op->contr->orig_stats.Con;
859     op->stats.Int = op->contr->orig_stats.Int;
860     op->stats.Wis = op->contr->orig_stats.Wis;
861     op->stats.Pow = op->contr->orig_stats.Pow;
862     op->stats.Cha = op->contr->orig_stats.Cha;
863     op->stats.ac=0;
864    
865     op->level=1;
866     op->stats.exp=0;
867     op->stats.ac=0;
868    
869     op->contr->levhp[1] = 9;
870     op->contr->levsp[1] = 6;
871     op->contr->levgrace[1] = 3;
872    
873     fix_player(op);
874     op->stats.hp = op->stats.maxhp;
875     op->stats.sp = op->stats.maxsp;
876     op->stats.grace = op->stats.maxgrace;
877     op->contr->orig_stats=op->stats;
878     op->contr->Swap_First=-1;
879     }
880    
881    
882     /* This code has been greatly reduced, because with set_attr_value
883     * and get_attr_value, the stats can be accessed just numeric
884     * ids. stat_trans is a table that translate the number entered
885     * into the actual stat. It is needed because the order the stats
886     * are displayed in the stat window is not the same as how
887     * the number's access that stat. The table does that translation.
888     */
889     int key_roll_stat(object *op, char key)
890     {
891     int keynum = key -'0';
892     char buf[MAX_BUF];
893     static sint8 stat_trans[] = {-1, STR, DEX, CON, INT, WIS, POW, CHA};
894    
895     if (keynum>0 && keynum<=7) {
896     if (op->contr->Swap_First==-1) {
897     op->contr->Swap_First=stat_trans[keynum];
898     sprintf(buf,"%s ->", short_stat_name[stat_trans[keynum]]);
899     new_draw_info(NDI_UNIQUE, 0,op,buf);
900     }
901     else
902     Swap_Stat(op,stat_trans[keynum]);
903    
904     send_query(&op->contr->socket,CS_QUERY_SINGLECHAR,"");
905     return 1;
906     }
907     switch (key) {
908     case 'n':
909     case 'N': {
910     SET_FLAG(op, FLAG_WIZ);
911     if(op->map==NULL) {
912     LOG(llevError,"Map == NULL in state 2\n");
913     break;
914     }
915    
916     #if 0
917     /* So that enter_exit will put us at startx/starty */
918     op->x= -1;
919    
920     enter_exit(op,NULL);
921     #endif
922     SET_ANIMATION(op, 2); /* So player faces south */
923     /* Enter exit adds a player otherwise */
924     add_statbonus(op);
925     send_query(&op->contr->socket,CS_QUERY_SINGLECHAR,"Now choose a character.\nPress any key to change outlook.\nPress `d' when you're pleased.\n");
926     op->contr->state = ST_CHANGE_CLASS;
927     if (op->msg)
928     new_draw_info(NDI_BLUE, 0, op, op->msg);
929     return 0;
930     }
931     case 'y':
932     case 'Y':
933     roll_stats(op);
934     send_query(&op->contr->socket,CS_QUERY_SINGLECHAR,"");
935     return 1;
936    
937     case 'q':
938     case 'Q':
939     play_again(op);
940     return 1;
941    
942     default:
943     send_query(&op->contr->socket,CS_QUERY_SINGLECHAR,"Yes, No, Quit or 1-6. Roll again?");
944     return 0;
945     }
946     return 0;
947     }
948    
949     /* This function takes the key that is passed, and does the
950     * appropriate action with it (change class, or other things.
951     */
952    
953     int key_change_class(object *op, char key)
954     {
955     int tmp_loop;
956    
957     if(key=='q'||key=='Q') {
958     remove_ob(op);
959     play_again(op);
960     return 0;
961     }
962     if(key=='d'||key=='D') {
963     char buf[MAX_BUF];
964    
965     /* this must before then initial items are given */
966     esrv_new_player(op->contr, op->weight+op->carrying);
967     create_treasure(find_treasurelist("starting_wealth"),op, 0, 0, 0);
968    
969     /* Lauwenmark : Here we handle the BORN global event */
970     execute_global_event(EVENT_BORN, op);
971    
972     /* Lauwenmark : We then generate a LOGIN event */
973     execute_global_event(EVENT_LOGIN, op->contr, op->contr->socket.host);
974     op->contr->state=ST_PLAYING;
975    
976     if (op->msg) {
977     free_string(op->msg);
978     op->msg=NULL;
979     }
980    
981     /* We create this now because some of the unique maps will need it
982     * to save here.
983     */
984     sprintf(buf,"%s/%s/%s",settings.localdir,settings.playerdir,op->name);
985     make_path_to_file(buf);
986    
987     #ifdef AUTOSAVE
988     op->contr->last_save_tick = pticks;
989     #endif
990     start_info(op);
991     CLEAR_FLAG(op, FLAG_WIZ);
992     give_initial_items(op,op->randomitems);
993     link_player_skills(op);
994     esrv_send_inventory(op, op);
995     fix_player(op);
996     return 0;
997     }
998    
999     /* Following actually changes the class - this is the default command
1000     * if we don't match with one of the options above.
1001     */
1002    
1003     tmp_loop = 0;
1004     while(!tmp_loop) {
1005     const char *name = add_string (op->name);
1006     int x = op->x, y = op->y;
1007     remove_statbonus(op);
1008     remove_ob (op);
1009     op->arch = get_player_archetype(op->arch);
1010     copy_object (&op->arch->clone, op);
1011     op->stats = op->contr->orig_stats;
1012     free_string (op->name);
1013     op->name = name;
1014     free_string(op->name_pl);
1015     op->name_pl = add_string(name);
1016     op->x = x;
1017     op->y = y;
1018     SET_ANIMATION(op, 2); /* So player faces south */
1019     insert_ob_in_map (op, op->map, op,0);
1020     strncpy(op->contr->title, op->arch->clone.name, sizeof(op->contr->title)-1);
1021     op->contr->title[sizeof(op->contr->title)-1] = '\0';
1022     add_statbonus(op);
1023     tmp_loop=allowed_class(op);
1024     }
1025     update_object(op,UP_OBJ_FACE);
1026     esrv_update_item(UPD_FACE,op,op);
1027     fix_player(op);
1028     op->stats.hp=op->stats.maxhp;
1029     op->stats.sp=op->stats.maxsp;
1030     op->stats.grace=0;
1031     if (op->msg)
1032     new_draw_info(NDI_BLUE, 0, op, op->msg);
1033     send_query(&op->contr->socket,CS_QUERY_SINGLECHAR,"Press any key for the next race.\nPress `d' to play this race.\n");
1034     return 0;
1035     }
1036    
1037     int key_confirm_quit(object *op, char key)
1038     {
1039     char buf[MAX_BUF];
1040    
1041     if(key!='y'&&key!='Y'&&key!='q'&&key!='Q') {
1042     op->contr->state=ST_PLAYING;
1043     new_draw_info(NDI_UNIQUE, 0,op,"OK, continuing to play.");
1044     return 1;
1045     }
1046    
1047     /* Lauwenmark : Here we handle the REMOVE global event */
1048     execute_global_event(EVENT_REMOVE, op);
1049     terminate_all_pets(op);
1050     leave_map(op);
1051     op->direction=0;
1052     new_draw_info_format(NDI_UNIQUE | NDI_ALL, 5, NULL,
1053     "%s quits the game.",op->name);
1054    
1055     strcpy(op->contr->killer,"quit");
1056     check_score(op);
1057     op->contr->party=NULL;
1058     if (settings.set_title == TRUE)
1059     op->contr->own_title[0]='\0';
1060    
1061     if(!QUERY_FLAG(op,FLAG_WAS_WIZ)) {
1062     mapstruct *mp, *next;
1063    
1064     /* We need to hunt for any per player unique maps in memory and
1065     * get rid of them. The trailing slash in the path is intentional,
1066     * so that players named 'Ab' won't match against players 'Abe' pathname
1067     */
1068     sprintf(buf,"%s/%s/%s/", settings.localdir, settings.playerdir, op->name);
1069     for (mp=first_map; mp!=NULL; mp=next) {
1070     next = mp->next;
1071     if (!strncmp(mp->path, buf, strlen(buf)))
1072     delete_map(mp);
1073     }
1074    
1075     delete_character(op->name, 1);
1076     }
1077     play_again(op);
1078     return 1;
1079     }
1080    
1081     void flee_player(object *op) {
1082     int dir,diff;
1083     rv_vector rv;
1084    
1085     if(op->stats.hp < 0) {
1086     LOG(llevDebug, "Fleeing player is dead.\n");
1087     CLEAR_FLAG(op, FLAG_SCARED);
1088     return;
1089     }
1090    
1091     if(op->enemy==NULL) {
1092     LOG(llevDebug,"Fleeing player had no enemy.\n");
1093     CLEAR_FLAG(op, FLAG_SCARED);
1094     return;
1095     }
1096    
1097     /* Seen some crashes here. Since we don't store an
1098     * op->enemy_count, it is possible that something destroys the
1099     * actual enemy, and the object is recycled.
1100     */
1101     if (op->enemy->map == NULL) {
1102     CLEAR_FLAG(op, FLAG_SCARED);
1103     op->enemy=NULL;
1104     return;
1105     }
1106    
1107     if(!(random_roll(0, 4, op, PREFER_LOW)) && did_make_save(op, op->level, 0)) {
1108     op->enemy=NULL;
1109     CLEAR_FLAG(op, FLAG_SCARED);
1110     return;
1111     }
1112     get_rangevector(op, op->enemy, &rv, 0);
1113    
1114     dir=absdir(4+rv.direction);
1115     for(diff=0;diff<3;diff++) {
1116     int m=1-(RANDOM()&2);
1117     if(move_ob(op,absdir(dir+diff*m),op)||
1118     (diff==0 && move_ob(op,absdir(dir-diff*m),op))) {
1119     return;
1120     }
1121     }
1122     /* Cornered, get rid of scared */
1123     CLEAR_FLAG(op, FLAG_SCARED);
1124     op->enemy=NULL;
1125     }
1126    
1127    
1128     /* check_pick sees if there is stuff to be picked up/picks up stuff.
1129     * IT returns 1 if the player should keep on moving, 0 if he should
1130     * stop.
1131     */
1132     int check_pick(object *op) {
1133     object *tmp, *next;
1134     tag_t next_tag=0, op_tag;
1135     int stop = 0;
1136     int j, k, wvratio;
1137     char putstring[128], tmpstr[16];
1138    
1139    
1140     /* if you're flying, you cna't pick up anything */
1141     if (op->move_type & MOVE_FLYING)
1142     return 1;
1143    
1144     op_tag = op->count;
1145    
1146     next = op->below;
1147     if (next)
1148     next_tag = next->count;
1149    
1150     /* loop while there are items on the floor that are not marked as
1151     * destroyed */
1152     while (next && ! was_destroyed (next, next_tag))
1153     {
1154     tmp = next;
1155     next = tmp->below;
1156     if (next)
1157     next_tag = next->count;
1158    
1159     if (was_destroyed (op, op_tag))
1160     return 0;
1161    
1162     if ( ! can_pick (op, tmp))
1163     continue;
1164    
1165     if (op->contr->search_str[0]!='\0' && settings.search_items == TRUE)
1166     {
1167     if (item_matched_string (op, tmp, op->contr->search_str))
1168     pick_up (op, tmp);
1169     continue;
1170     }
1171    
1172     /* high not bit set? We're using the old autopickup model */
1173     if(!(op->contr->mode & PU_NEWMODE)) {
1174     switch (op->contr->mode) {
1175     case 0: return 1; /* don't pick up */
1176     case 1: pick_up (op, tmp);
1177     return 1;
1178     case 2: pick_up (op, tmp);
1179     return 0;
1180     case 3: return 0; /* stop before pickup */
1181     case 4: pick_up (op, tmp);
1182     break;
1183     case 5: pick_up (op, tmp);
1184     stop = 1;
1185     break;
1186     case 6:
1187     if (QUERY_FLAG (tmp, FLAG_KNOWN_MAGICAL) &&
1188     ! QUERY_FLAG(tmp, FLAG_KNOWN_CURSED))
1189     pick_up(op, tmp);
1190     break;
1191    
1192     case 7:
1193     if (tmp->type == MONEY || tmp->type == GEM)
1194     pick_up(op, tmp);
1195     break;
1196    
1197     default:
1198     /* use value density */
1199     if ( ! QUERY_FLAG (tmp, FLAG_UNPAID)
1200     && (query_cost (tmp, op, F_TRUE) * 100
1201     / (tmp->weight * MAX (tmp->nrof, 1)))
1202     >= op->contr->mode)
1203     pick_up(op,tmp);
1204     }
1205     }
1206     else { /* old model */
1207     /* NEW pickup handling */
1208     if(op->contr->mode & PU_DEBUG)
1209     {
1210     /* some debugging code to figure out item information */
1211     if(tmp->name!=NULL)
1212     sprintf(putstring,"item name: %s item type: %d weight/value: %d",
1213     tmp->name, tmp->type,
1214     (int)(query_cost(tmp, op, F_TRUE)*100 / (tmp->weight * MAX(tmp->nrof,1))));
1215     else
1216     sprintf(putstring,"item name: %s item type: %d weight/value: %d",
1217     tmp->arch->name, tmp->type,
1218     (int)(query_cost(tmp, op, F_TRUE)*100 / (tmp->weight * MAX(tmp->nrof,1))));
1219     new_draw_info(NDI_UNIQUE, 0,op,putstring);
1220    
1221     sprintf(putstring,"...flags: ");
1222     for(k=0;k<4;k++)
1223     {
1224     for(j=0;j<32;j++)
1225     {
1226     if((tmp->flags[k]>>j)&0x01)
1227     {
1228     sprintf(tmpstr,"%d ",k*32+j);
1229     strcat(putstring, tmpstr);
1230     }
1231     }
1232     }
1233     new_draw_info(NDI_UNIQUE, 0,op,putstring);
1234    
1235     #if 0
1236     /* print the flags too */
1237     for(k=0;k<4;k++)
1238     {
1239     fprintf(stderr,"%d [%d] ", k, k*32+31);
1240     for(j=0;j<32;j++)
1241     {
1242     fprintf(stderr,"%d",tmp->flags[k]>>(31-j)&0x01);
1243     if(!((j+1)%4))fprintf(stderr," ");
1244     }
1245     fprintf(stderr," [%d]\n", k*32);
1246     }
1247     #endif
1248     }
1249     /* philosophy:
1250     * It's easy to grab an item type from a pile, as long as it's
1251     * generic. This takes no game-time. For more detailed pickups
1252     * and selections, select-items shoul dbe used. This is a
1253     * grab-as-you-run type mode that's really useful for arrows for
1254     * example.
1255     * The drawback: right now it has no frontend, so you need to
1256     * stick the bits you want into a calculator in hex mode and then
1257     * convert to decimal and then 'pickup <#>
1258     */
1259    
1260     /* the first two modes are exclusive: if NOTHING we return, if
1261     * STOP then we stop. All the rest are applied sequentially,
1262     * meaning if any test passes, the item gets picked up. */
1263    
1264     /* if mode is set to pick nothing up, return */
1265    
1266     if(op->contr->mode & PU_NOTHING) return 1;
1267    
1268     /* if mode is set to stop when encountering objects, return */
1269     /* take STOP before INHIBIT since it doesn't actually pick
1270     * anything up */
1271    
1272     if(op->contr->mode & PU_STOP) return 0;
1273    
1274     /* useful for going into stores and not losing your settings... */
1275     /* and for battles wher you don't want to get loaded down while
1276     * fighting */
1277     if(op->contr->mode & PU_INHIBIT) return 1;
1278    
1279     /* prevent us from turning into auto-thieves :) */
1280     if (QUERY_FLAG (tmp, FLAG_UNPAID)) continue;
1281    
1282     /* ignore known cursed objects */
1283     if (QUERY_FLAG (tmp, FLAG_KNOWN_CURSED) && op->contr->mode & PU_NOT_CURSED) continue;
1284    
1285     /* all food and drink if desired */
1286     /* question: don't pick up known-poisonous stuff? */
1287     if(op->contr->mode & PU_FOOD)
1288     if (tmp->type == FOOD)
1289     { pick_up(op, tmp); if(0)fprintf(stderr,"FOOD\n"); continue; }
1290     if(op->contr->mode & PU_DRINK)
1291     if (tmp->type == DRINK || (tmp->type == POISON && !QUERY_FLAG(tmp, FLAG_KNOWN_CURSED)))
1292     { pick_up(op, tmp); if(0)fprintf(stderr,"DRINK\n"); continue; }
1293    
1294     if(op->contr->mode & PU_POTION)
1295     if (tmp->type == POTION)
1296     { pick_up(op, tmp); if(0)fprintf(stderr,"POTION\n"); continue; }
1297    
1298     /* spellbooks, skillscrolls and normal books/scrolls */
1299     if(op->contr->mode & PU_SPELLBOOK)
1300     if (tmp->type == SPELLBOOK)
1301     { pick_up(op, tmp); if(0)fprintf(stderr,"SPELLBOOK\n"); continue; }
1302     if(op->contr->mode & PU_SKILLSCROLL)
1303     if (tmp->type == SKILLSCROLL)
1304     { pick_up(op, tmp); if(0)fprintf(stderr,"SKILLSCROLL\n"); continue; }
1305     if(op->contr->mode & PU_READABLES)
1306     if (tmp->type == BOOK || tmp->type == SCROLL)
1307     { pick_up(op, tmp); if(0)fprintf(stderr,"READABLES\n"); continue; }
1308    
1309     /* wands/staves/rods/horns */
1310     if (op->contr->mode & PU_MAGIC_DEVICE)
1311     if (tmp->type == WAND || tmp->type == ROD || tmp->type == HORN)
1312     { pick_up(op, tmp); if(0)fprintf(stderr,"MAGIC_DEVICE\n"); continue; }
1313    
1314     /* pick up all magical items */
1315     if(op->contr->mode & PU_MAGICAL)
1316     if (QUERY_FLAG (tmp, FLAG_KNOWN_MAGICAL) && ! QUERY_FLAG(tmp, FLAG_KNOWN_CURSED))
1317     { pick_up(op, tmp); if(0)fprintf(stderr,"MAGICAL\n"); continue; }
1318    
1319     if(op->contr->mode & PU_VALUABLES)
1320     {
1321     if (tmp->type == MONEY || tmp->type == GEM)
1322     { pick_up(op, tmp); if(0)fprintf(stderr,"MONEY/GEM\n"); continue; }
1323     }
1324    
1325     /* rings & amulets - talismans seems to be typed AMULET */
1326     if(op->contr->mode & PU_JEWELS)
1327     if (tmp->type == RING || tmp->type == AMULET)
1328     { pick_up(op, tmp); if(0)fprintf(stderr,"JEWELS\n"); continue; }
1329    
1330     /* bows and arrows. Bows are good for selling! */
1331     if(op->contr->mode & PU_BOW)
1332     if (tmp->type == BOW)
1333     { pick_up(op, tmp); if(0)fprintf(stderr,"BOW\n"); continue; }
1334     if(op->contr->mode & PU_ARROW)
1335     if (tmp->type == ARROW)
1336     { pick_up(op, tmp); if(0)fprintf(stderr,"ARROW\n"); continue; }
1337    
1338     /* all kinds of armor etc. */
1339     if(op->contr->mode & PU_ARMOUR)
1340     if (tmp->type == ARMOUR)
1341     { pick_up(op, tmp); if(0)fprintf(stderr,"ARMOUR\n"); continue; }
1342     if(op->contr->mode & PU_HELMET)
1343     if (tmp->type == HELMET)
1344     { pick_up(op, tmp); if(0)fprintf(stderr,"HELMET\n"); continue; }
1345     if(op->contr->mode & PU_SHIELD)
1346     if (tmp->type == SHIELD)
1347     { pick_up(op, tmp); if(0)fprintf(stderr,"SHIELD\n"); continue; }
1348     if(op->contr->mode & PU_BOOTS)
1349     if (tmp->type == BOOTS)
1350     { pick_up(op, tmp); if(0)fprintf(stderr,"BOOTS\n"); continue; }
1351     if(op->contr->mode & PU_GLOVES)
1352     if (tmp->type == GLOVES)
1353     { pick_up(op, tmp); if(0)fprintf(stderr,"GLOVES\n"); continue; }
1354     if(op->contr->mode & PU_CLOAK)
1355     if (tmp->type == CLOAK)
1356     { pick_up(op, tmp); if(0)fprintf(stderr,"GLOVES\n"); continue; }
1357    
1358     /* hoping to catch throwing daggers here */
1359     if(op->contr->mode & PU_MISSILEWEAPON)
1360     if(tmp->type == WEAPON && QUERY_FLAG(tmp, FLAG_IS_THROWN))
1361     { pick_up(op, tmp); if(0)fprintf(stderr,"MISSILEWEAPON\n"); continue; }
1362    
1363     /* careful: chairs and tables are weapons! */
1364     if(op->contr->mode & PU_ALLWEAPON)
1365     {
1366     if(tmp->type == WEAPON && tmp->name!=NULL)
1367     {
1368     if(strstr(tmp->name,"table")==NULL && strstr(tmp->arch->name,"table")==NULL &&
1369     strstr(tmp->name,"chair") && strstr(tmp->arch->name,"chair")==NULL)
1370     { pick_up(op, tmp); if(0)fprintf(stderr,"WEAPON\n"); continue; }
1371     }
1372     if(tmp->type == WEAPON && tmp->name==NULL)
1373     {
1374     if(strstr(tmp->arch->name,"table")==NULL &&
1375     strstr(tmp->arch->name,"chair")==NULL)
1376     { pick_up(op, tmp); if(0)fprintf(stderr,"WEAPON\n"); continue; }
1377     }
1378     }
1379    
1380     /* misc stuff that's useful */
1381     if(op->contr->mode & PU_KEY)
1382     if (tmp->type == KEY || tmp->type == SPECIAL_KEY)
1383     { pick_up(op, tmp); if(0)fprintf(stderr,"KEY\n"); continue; }
1384    
1385     /* any of the last 4 bits set means we use the ratio for value
1386     * pickups */
1387     if(op->contr->mode & PU_RATIO)
1388     {
1389     /* use value density to decide what else to grab */
1390     /* >=7 was >= op->contr->mode */
1391     /* >=7 is the old standard setting. Now we take the last 4 bits
1392     * and multiply them by 5, giving 0..15*5== 5..75 */
1393     wvratio=(op->contr->mode & PU_RATIO) * 5;
1394     if ((query_cost(tmp, op, F_TRUE)*100 / (tmp->weight * MAX(tmp->nrof, 1))) >= wvratio)
1395     {
1396     pick_up(op, tmp);
1397     #if 0
1398     fprintf(stderr,"HIGH WEIGHT/VALUE [");
1399     if(tmp->name!=NULL) {
1400     fprintf(stderr,"%s", tmp->name);
1401     }
1402     else fprintf(stderr,"%s",tmp->arch->name);
1403     fprintf(stderr,",%d] = ", tmp->type);
1404     fprintf(stderr,"%d\n",(int)(query_cost(tmp,op,F_TRUE)*100 / (tmp->weight * MAX(tmp->nrof,1))));
1405     #endif
1406     continue;
1407     }
1408     }
1409     } /* the new pickup model */
1410     }
1411     return ! stop;
1412     }
1413    
1414     /*
1415     * Find an arrow in the inventory and after that
1416     * in the right type container (quiver). Pointer to the
1417     * found object is returned.
1418     */
1419     object *find_arrow(object *op, const char *type)
1420     {
1421     object *tmp = NULL;
1422    
1423     for(op=op->inv; op; op=op->below)
1424     if(!tmp && op->type==CONTAINER && op->race==type &&
1425     QUERY_FLAG(op,FLAG_APPLIED))
1426     tmp = find_arrow (op, type);
1427     else if (op->type==ARROW && op->race==type)
1428     return op;
1429     return tmp;
1430     }
1431    
1432     /*
1433     * Similar to find_arrow, but looks for (roughly) the best arrow to use
1434     * against the target. A full test is not performed, simply a basic test
1435     * of resistances. The archer is making a quick guess at what he sees down
1436     * the hall. Failing that it does it's best to pick the highest plus arrow.
1437     */
1438    
1439     object *find_better_arrow(object *op, object *target, const char *type, int *better)
1440     {
1441     object *tmp = NULL, *arrow, *ntmp;
1442     int attacknum, attacktype, betterby=0, i;
1443    
1444     if (!type)
1445     return NULL;
1446    
1447     for (arrow=op->inv; arrow; arrow=arrow->below) {
1448     if (arrow->type==CONTAINER && arrow->race==type &&
1449     QUERY_FLAG(arrow, FLAG_APPLIED)) {
1450     i = 0;
1451     ntmp = find_better_arrow(arrow, target, type, &i);
1452     if (i > betterby) {
1453     tmp = ntmp;
1454     betterby = i;
1455     }
1456     } else if (arrow->type==ARROW && arrow->race==type) {
1457     /* allways prefer assasination/slaying */
1458     if (target->race != NULL && arrow->slaying != NULL &&
1459     strstr(arrow->slaying, target->race)) {
1460     if (arrow->attacktype & AT_DEATH) {
1461     *better = 100;
1462     return arrow;
1463     } else {
1464     tmp = arrow;
1465     betterby = (arrow->magic + arrow->stats.dam) * 2;
1466     }
1467     } else {
1468     for (attacknum=0; attacknum < NROFATTACKS; attacknum++) {
1469     attacktype = 1<<attacknum;
1470     if ((arrow->attacktype & attacktype) && (target->arch->clone.resist[attacknum]) < 0)
1471     if (((arrow->magic + arrow->stats.dam)*(100-target->arch->clone.resist[attacknum])/100) > betterby) {
1472     tmp = arrow;
1473     betterby = (arrow->magic + arrow->stats.dam)*(100-target->arch->clone.resist[attacknum])/100;
1474     }
1475     }
1476     if ((2 + arrow->magic + arrow->stats.dam) > betterby) {
1477     tmp = arrow;
1478     betterby = 2 + arrow->magic + arrow->stats.dam;
1479     }
1480     if (arrow->title && (1 + arrow->magic + arrow->stats.dam) > betterby) {
1481     tmp = arrow;
1482     betterby = 1 + arrow->magic + arrow->stats.dam;
1483     }
1484     }
1485     }
1486     }
1487     if (tmp == NULL && arrow == NULL)
1488     return find_arrow(op, type);
1489    
1490     *better = betterby;
1491     return tmp;
1492     }
1493    
1494     /* looks in a given direction, finds the first valid target, and calls
1495     * find_better_arrow to find a decent arrow to use.
1496     * op = the shooter
1497     * type = bow->race
1498     * dir = fire direction
1499     */
1500    
1501     object *pick_arrow_target(object *op, const char *type, int dir)
1502     {
1503     object *tmp = NULL;
1504     mapstruct *m;
1505     int i, mflags, found, number;
1506     sint16 x, y;
1507    
1508     if (op->map == NULL)
1509     return find_arrow(op, type);
1510    
1511     /* do a dex check */
1512     number = (die_roll(2, 40, op, PREFER_LOW)-2)/2;
1513     if (number > (op->stats.Dex + (op->chosen_skill?op->chosen_skill->level:op->level)))
1514     return find_arrow(op, type);
1515    
1516     m = op->map;
1517     x = op->x;
1518     y = op->y;
1519    
1520     /* find the first target */
1521     for (i=0, found=0; i<20; i++) {
1522     x += freearr_x[dir];
1523     y += freearr_y[dir];
1524     mflags = get_map_flags(m, &m, x, y, &x, &y);
1525     if (mflags & P_OUT_OF_MAP || mflags & P_BLOCKSVIEW) {
1526     tmp = NULL;
1527     break;
1528     } else if (GET_MAP_MOVE_BLOCK(m, x, y) == MOVE_FLY_LOW) {
1529     /* This block presumes arrows and the like are MOVE_FLY_SLOW -
1530     * perhaps a bad assumption.
1531     */
1532     tmp = NULL;
1533     break;
1534     }
1535     if (mflags & P_IS_ALIVE) {
1536     for (tmp = GET_MAP_OB(m, x, y); tmp; tmp=tmp->above)
1537     if (QUERY_FLAG(tmp, FLAG_ALIVE)) {
1538     found++;
1539     break;
1540     }
1541     if (found)
1542     break;
1543     }
1544     }
1545     if (tmp == NULL)
1546     return find_arrow(op, type);
1547    
1548     if (tmp->head)
1549     tmp = tmp->head;
1550    
1551     return find_better_arrow(op, tmp, type, &i);
1552     }
1553    
1554     /*
1555     * Creature fires a bow - op can be monster or player. Returns
1556     * 1 if bow was actually fired, 0 otherwise.
1557     * op is the object firing the bow.
1558     * part is for multipart creatures - the part firing the bow.
1559     * dir is the direction of fire.
1560     * wc_mod is any special modifier to give (used in special player fire modes)
1561     * sx, sy are coordinates to fire arrow from - also used in some of the special
1562     * player fire modes.
1563     */
1564     int fire_bow(object *op, object *part, object *arrow, int dir, int wc_mod,
1565     sint16 sx, sint16 sy)
1566     {
1567     object *left, *bow;
1568     tag_t left_tag, tag;
1569     int bowspeed, mflags;
1570     mapstruct *m;
1571    
1572     if (!dir) {
1573     new_draw_info(NDI_UNIQUE, 0, op, "You can't shoot yourself!");
1574     return 0;
1575     }
1576     if (op->type == PLAYER)
1577     bow=op->contr->ranges[range_bow];
1578     else {
1579     for(bow=op->inv; bow; bow=bow->below)
1580     /* Don't check for applied - monsters don't apply bows - in that way, they
1581     * don't need to switch back and forth between bows and weapons.
1582     */
1583     if(bow->type==BOW)
1584     break;
1585    
1586     if (!bow) {
1587     LOG (llevError, "Range: bow without activated bow (%s).\n", op->name);
1588     return 0;
1589     }
1590     }
1591     if( !bow->race || !bow->skill) {
1592     new_draw_info_format(NDI_UNIQUE, 0, op, "Your %s is broken.", bow->name);
1593     return 0;
1594     }
1595    
1596     bowspeed = bow->stats.sp + dex_bonus[op->stats.Dex];
1597    
1598     /* penalize ROF for bestarrow */
1599     if (op->type == PLAYER && op->contr->bowtype == bow_bestarrow)
1600     bowspeed -= dex_bonus[op->stats.Dex] + 5;
1601     if (bowspeed < 1)
1602     bowspeed = 1;
1603    
1604     if (arrow == NULL) {
1605     if ((arrow=find_arrow(op, bow->race)) == NULL) {
1606     if (op->type == PLAYER)
1607     new_draw_info_format(NDI_UNIQUE, 0, op,
1608     "You have no %s left.", bow->race);
1609     /* FLAG_READY_BOW will get reset if the monsters picks up some arrows */
1610     else
1611     CLEAR_FLAG(op, FLAG_READY_BOW);
1612     return 0;
1613     }
1614     }
1615     mflags = get_map_flags(op->map, &m, sx, sy, &sx, &sy);
1616     if (mflags & P_OUT_OF_MAP) {
1617     return 0;
1618     }
1619     if (GET_MAP_MOVE_BLOCK(m, sx, sy) == MOVE_FLY_LOW) {
1620     new_draw_info(NDI_UNIQUE, 0,op,"Something is in the way.");
1621     return 0;
1622     }
1623    
1624     /* this should not happen, but sometimes does */
1625     if (arrow->nrof==0) {
1626     remove_ob(arrow);
1627     free_object(arrow);
1628     return 0;
1629     }
1630    
1631     left = arrow; /* these are arrows left to the player */
1632     left_tag = left->count;
1633     arrow = get_split_ob(arrow, 1);
1634     if (arrow == NULL) {
1635     new_draw_info_format(NDI_UNIQUE, 0, op, "You have no %s left.",
1636     bow->race);
1637     return 0;
1638     }
1639     set_owner(arrow, op);
1640     if (arrow->skill) free_string(arrow->skill);
1641     arrow->skill = add_refcount(bow->skill);
1642    
1643     arrow->direction=dir;
1644     arrow->x = sx;
1645     arrow->y = sy;
1646    
1647     if (op->type == PLAYER) {
1648     op->speed_left = 0.01 - (float)FABS(op->speed) * 100 / bowspeed;
1649     fix_player(op);
1650     }
1651    
1652     SET_ANIMATION(arrow, arrow->direction);
1653     arrow->stats.sp = arrow->stats.wc; /* save original wc and dam */
1654     arrow->stats.hp = arrow->stats.dam;
1655     arrow->stats.grace = arrow->attacktype;
1656     if (arrow->slaying != NULL)
1657     arrow->spellarg = strdup_local(arrow->slaying);
1658    
1659     /* Note that this was different for monsters - they got their level
1660     * added to the damage. I think the strength bonus is more proper.
1661     */
1662    
1663     arrow->stats.dam += (QUERY_FLAG(bow, FLAG_NO_STRENGTH) ?
1664     0 : dam_bonus[op->stats.Str]) +
1665     bow->stats.dam + bow->magic + arrow->magic;
1666    
1667     /* update the speed */
1668     arrow->speed = (float)((QUERY_FLAG(bow, FLAG_NO_STRENGTH) ?
1669     0 : dam_bonus[op->stats.Str]) +
1670     bow->magic + arrow->magic) / 5.0 +
1671     (float)bow->stats.dam / 7.0;
1672    
1673     if (arrow->speed < 1.0)
1674     arrow->speed = 1.0;
1675     update_ob_speed(arrow);
1676     arrow->speed_left = 0;
1677    
1678     if (op->type == PLAYER) {
1679     arrow->stats.wc = 20 - bow->magic - arrow->magic -
1680     (op->chosen_skill?op->chosen_skill->level:op->level) -
1681     dex_bonus[op->stats.Dex] - thaco_bonus[op->stats.Str] -
1682     arrow->stats.wc - bow->stats.wc + wc_mod;
1683    
1684     arrow->level = op->chosen_skill?op->chosen_skill->level:op->level;
1685     } else {
1686     arrow->stats.wc= op->stats.wc - bow->magic - arrow->magic -
1687     arrow->stats.wc + wc_mod;
1688    
1689     arrow->level = op->level;
1690     }
1691     if (arrow->attacktype == AT_PHYSICAL)
1692     arrow->attacktype |= bow->attacktype;
1693     if (bow->slaying != NULL)
1694     arrow->slaying = add_string(bow->slaying);
1695    
1696     arrow->map = m;
1697     arrow->move_type = MOVE_FLY_LOW;
1698     arrow->move_on = MOVE_FLY_LOW | MOVE_WALK;
1699    
1700     play_sound_map(op->map, op->x, op->y, SOUND_FIRE_ARROW);
1701     tag = arrow->count;
1702     insert_ob_in_map(arrow, m, op, 0);
1703    
1704     if (!was_destroyed(arrow, tag))
1705     move_arrow(arrow);
1706    
1707     if (op->type == PLAYER) {
1708     if (was_destroyed (left, left_tag))
1709     esrv_del_item(op->contr, left_tag);
1710     else
1711     esrv_send_item(op, left);
1712     }
1713     return 1;
1714     }
1715    
1716     /* Special fire code for players - this takes into
1717     * account the special fire modes players can have
1718     * but monsters can't. Putting that code here
1719     * makes the fire_bow code much cleaner.
1720     * this function should only be called if 'op' is a player,
1721     * hence the function name.
1722     */
1723     int player_fire_bow(object *op, int dir)
1724     {
1725     int ret=0, wcmod=0;
1726    
1727     if (op->contr->bowtype == bow_bestarrow) {
1728     ret = fire_bow(op, op,
1729     pick_arrow_target(op, op->contr->ranges[range_bow]->race, dir),
1730     dir, 0, op->x, op->y);
1731     } else if (op->contr->bowtype >= bow_n && op->contr->bowtype <= bow_nw) {
1732     if (!similar_direction(dir, op->contr->bowtype - bow_n + 1))
1733     wcmod =-1;
1734     ret = fire_bow(op, op, NULL, op->contr->bowtype - bow_n + 1, wcmod,
1735     op->x, op->y);
1736     } else if (op->contr->bowtype == bow_threewide) {
1737     ret = fire_bow(op, op, NULL, dir, 0, op->x, op->y);
1738     ret |= fire_bow(op, op, NULL, dir, -5, op->x + freearr_x[absdir(dir+2)], op->y + freearr_y[absdir(dir+2)]);
1739     ret |= fire_bow(op, op, NULL, dir, -5, op->x + freearr_x[absdir(dir-2)], op->y + freearr_y[absdir(dir-2)]);
1740     } else if (op->contr->bowtype == bow_spreadshot) {
1741     ret |= fire_bow(op, op, NULL, dir, 0, op->x, op->y);
1742     ret |= fire_bow(op, op, NULL, absdir(dir-1), -5, op->x, op->y);
1743     ret |= fire_bow(op, op, NULL, absdir(dir+1), -5, op->x, op->y);
1744    
1745     } else {
1746     /* Simple case */
1747     ret = fire_bow(op, op, NULL, dir, 0, op->x, op->y);
1748     }
1749     return ret;
1750     }
1751    
1752    
1753     /* Fires a misc (wand/rod/horn) object in 'dir'.
1754     * Broken apart from 'fire' to keep it more readable.
1755     */
1756     void fire_misc_object(object *op, int dir)
1757     {
1758     object *item;
1759    
1760     if (!op->contr->ranges[range_misc]) {
1761     new_draw_info(NDI_UNIQUE, 0,op,"You have range item readied.");
1762     return;
1763     }
1764    
1765     item = op->contr->ranges[range_misc];
1766     if (!item->inv) {
1767     LOG(llevError,"Object %s lacks a spell\n", item->name);
1768     return;
1769     }
1770     if (item->type == WAND) {
1771     if(item->stats.food<=0) {
1772     play_sound_player_only(op->contr, SOUND_WAND_POOF,0,0);
1773     new_draw_info_format(NDI_UNIQUE, 0,op,"The %s goes poof.", query_base_name(item, 0));
1774     return;
1775     }
1776     } else if (item->type == ROD || item->type==HORN) {
1777     if(item->stats.hp<MAX(item->inv->stats.sp, item->inv->stats.grace)) {
1778     play_sound_player_only(op->contr, SOUND_WAND_POOF,0,0);
1779     if (item->type== ROD)
1780     new_draw_info_format(NDI_UNIQUE, 0,op,
1781     "The %s whines for a while, but nothing happens.", query_base_name(item,0));
1782     else
1783     new_draw_info_format(NDI_UNIQUE, 0,op,
1784     "The %s needs more time to charge.", query_base_name(item,0));
1785     return;
1786     }
1787     }
1788    
1789     if(cast_spell(op,item,dir,item->inv,NULL)) {
1790     SET_FLAG(op, FLAG_BEEN_APPLIED); /* You now know something about it */
1791     if (item->type == WAND) {
1792     if (!(--item->stats.food)) {
1793     object *tmp;
1794     if (item->arch) {
1795     CLEAR_FLAG(item, FLAG_ANIMATE);
1796     item->face = item->arch->clone.face;
1797     item->speed = 0;
1798     update_ob_speed(item);
1799     }
1800     if ((tmp=is_player_inv(item)))
1801     esrv_update_item(UPD_ANIM, tmp, item);
1802     }
1803     }
1804     else if (item->type == ROD || item->type==HORN) {
1805     drain_rod_charge(item);
1806     }
1807     }
1808     }
1809    
1810     /* Received a fire command for the player - go and do it.
1811     */
1812     void fire(object *op,int dir) {
1813     int spellcost=0;
1814    
1815     /* check for loss of invisiblity/hide */
1816     if (action_makes_visible(op)) make_visible(op);
1817    
1818     switch(op->contr->shoottype) {
1819     case range_none:
1820     return;
1821    
1822     case range_bow:
1823     player_fire_bow(op, dir);
1824     return;
1825    
1826     case range_magic: /* Casting spells */
1827     spellcost=(cast_spell(op,op,dir,op->contr->ranges[range_magic],op->contr->spellparam[0]?op->contr->spellparam:NULL));
1828     return;
1829    
1830     case range_misc:
1831     fire_misc_object(op, dir);
1832     return;
1833    
1834     case range_golem: /* Control summoned monsters from scrolls */
1835     if(op->contr->ranges[range_golem]==NULL ||
1836     op->contr->golem_count != op->contr->ranges[range_golem]->count) {
1837     op->contr->ranges[range_golem] = NULL;
1838     op->contr->shoottype=range_none;
1839     op->contr->golem_count = 0;
1840     }
1841     else
1842     control_golem(op->contr->ranges[range_golem], dir);
1843     return;
1844    
1845     case range_skill:
1846     if(!op->chosen_skill) {
1847     if(op->type==PLAYER)
1848     new_draw_info(NDI_UNIQUE, 0,op,"You have no applicable skill to use.");
1849     return;
1850     }
1851     (void) do_skill(op,op,op->chosen_skill,dir,NULL);
1852     return;
1853     case range_builder:
1854     apply_map_builder( op, dir );
1855     return;
1856     default:
1857     new_draw_info(NDI_UNIQUE, 0,op,"Illegal shoot type.");
1858     return;
1859     }
1860     }
1861    
1862    
1863    
1864     /* find_key
1865     * We try to find a key for the door as passed. If we find a key
1866     * and successfully use it, we return the key, otherwise NULL
1867     * This function merges both normal and locked door, since the logic
1868     * for both is the same - just the specific key is different.
1869     * pl is the player,
1870     * inv is the objects inventory to searched
1871     * door is the door we are trying to match against.
1872     * This function can be called recursively to search containers.
1873     */
1874    
1875     object * find_key(object *pl, object *container, object *door)
1876     {
1877     object *tmp,*key;
1878    
1879     /* Should not happen, but sanity checking is never bad */
1880     if (container->inv == NULL) return NULL;
1881    
1882     /* First, lets try to find a key in the top level inventory */
1883     for (tmp=container->inv; tmp!=NULL; tmp=tmp->below) {
1884     if (door->type==DOOR && tmp->type==KEY) break;
1885     /* For sanity, we should really check door type, but other stuff
1886     * (like containers) can be locked with special keys
1887     */
1888     if (tmp->slaying && tmp->type==SPECIAL_KEY &&
1889     tmp->slaying==door->slaying) break;
1890     }
1891     /* No key found - lets search inventories now */
1892     /* If we find and use a key in an inventory, return at that time.
1893     * otherwise, if we search all the inventories and still don't find
1894     * a key, return
1895     */
1896     if (!tmp) {
1897     for (tmp=container->inv; tmp!=NULL; tmp=tmp->below) {
1898     /* No reason to search empty containers */
1899     if (tmp->type==CONTAINER && tmp->inv) {
1900     if ((key=find_key(pl, tmp, door))!=NULL) return key;
1901     }
1902     }
1903     if (!tmp) return NULL;
1904     }
1905     /* We get down here if we have found a key. Now if its in a container,
1906     * see if we actually want to use it
1907     */
1908     if (pl!=container) {
1909     /* Only let players use keys in containers */
1910     if (!pl->contr) return NULL;
1911     /* cases where this fails:
1912     * If we only search the player inventory, return now since we
1913     * are not in the players inventory.
1914     * If the container is not active, return now since only active
1915     * containers can be used.
1916     * If we only search keyrings and the container does not have
1917     * a race/isn't a keyring.
1918     * No checking for all containers - to fall through past here,
1919     * inv must have been an container and must have been active.
1920     *
1921     * Change the color so that the message doesn't disappear with
1922     * all the others.
1923     */
1924     if (pl->contr->usekeys == key_inventory ||
1925     !QUERY_FLAG(container, FLAG_APPLIED) ||
1926     (pl->contr->usekeys == keyrings &&
1927     (!container->race || strcmp(container->race, "keys")))
1928     ) {
1929     new_draw_info_format(NDI_UNIQUE|NDI_BROWN, 0, pl,
1930     "The %s in your %s vibrates as you approach the door",
1931     query_name(tmp), query_name(container));
1932     return NULL;
1933     }
1934     }
1935     return tmp;
1936     }
1937    
1938     /* moved door processing out of move_player_attack.
1939     * returns 1 if player has opened the door with a key
1940     * such that the caller should not do anything more,
1941     * 0 otherwise
1942     */
1943     static int player_attack_door(object *op, object *door)
1944     {
1945    
1946     /* If its a door, try to find a use a key. If we do destroy the door,
1947     * might as well return immediately as there is nothing more to do -
1948     * otherwise, we fall through to the rest of the code.
1949     */
1950     object *key=find_key(op, op, door);
1951    
1952     /* IF we found a key, do some extra work */
1953     if (key) {
1954     object *container=key->env;
1955    
1956     play_sound_map(op->map, op->x, op->y, SOUND_OPEN_DOOR);
1957     if(action_makes_visible(op)) make_visible(op);
1958     if(door->inv &&(door->inv->type ==RUNE || door->inv->type ==TRAP)) spring_trap(door->inv,op);
1959     if (door->type == DOOR) {
1960     hit_player(door,9998,op,AT_PHYSICAL,1); /* Break through the door */
1961     }
1962     else if(door->type==LOCKED_DOOR) {
1963     new_draw_info_format(NDI_UNIQUE, NDI_BROWN, op,
1964     "You open the door with the %s", query_short_name(key));
1965     remove_door2(door); /* remove door without violence ;-) */
1966     }
1967     /* Do this after we print the message */
1968     decrease_ob(key); /* Use up one of the keys */
1969     /* Need to update the weight the container the key was in */
1970     if (container != op)
1971     esrv_update_item(UPD_WEIGHT, op, container);
1972     return 1; /* Nothing more to do below */
1973     } else if (door->type==LOCKED_DOOR) {
1974     /* Might as well return now - no other way to open this */
1975     new_draw_info(NDI_UNIQUE | NDI_NAVY, 0, op, door->msg);
1976     return 1;
1977     }
1978     return 0;
1979     }
1980    
1981     /* This function is just part of a breakup from move_player.
1982     * It should keep the code cleaner.
1983     * When this is called, the players direction has been updated
1984     * (taking into account confusion.) The player is also actually
1985     * going to try and move (not fire weapons).
1986     */
1987    
1988     void move_player_attack(object *op, int dir)
1989     {
1990     object *tmp, *mon;
1991     sint16 nx=freearr_x[dir]+op->x,ny=freearr_y[dir]+op->y;
1992     int on_battleground;
1993     mapstruct *m;
1994    
1995     on_battleground = op_on_battleground(op, NULL, NULL);
1996    
1997     /* If braced, or can't move to the square, and it is not out of the
1998     * map, attack it. Note order of if statement is important - don't
1999     * want to be calling move_ob if braced, because move_ob will move the
2000     * player. This is a pretty nasty hack, because if we could
2001     * move to some space, it then means that if we are braced, we should
2002     * do nothing at all. As it is, if we are braced, we go through
2003     * quite a bit of processing. However, it probably is less than what
2004     * move_ob uses.
2005     */
2006     if ((op->contr->braced || !move_ob(op,dir,op)) && !out_of_map(op->map,nx,ny)) {
2007     if (OUT_OF_REAL_MAP(op->map, nx, ny)) {
2008     m = get_map_from_coord(op->map, &nx, &ny);
2009     if (!m) return; /* Don't think this should happen */
2010     }
2011     else m =op->map;
2012    
2013     if ((tmp=get_map_ob(m,nx,ny))==NULL) {
2014     /* LOG(llevError,"player_move_attack: get_map_ob returns NULL, but player can not more there.\n");*/
2015     return;
2016     }
2017    
2018     mon = NULL;
2019     /* Go through all the objects, and find ones of interest. Only stop if
2020     * we find a monster - that is something we know we want to attack.
2021     * if its a door or barrel (can roll) see if there may be monsters
2022     * on the space
2023     */
2024     while (tmp!=NULL) {
2025     if (tmp == op) {
2026     tmp=tmp->above;
2027     continue;
2028     }
2029     if (QUERY_FLAG(tmp,FLAG_ALIVE)) {
2030     mon = tmp;
2031     break;
2032     }
2033     if (tmp->type==LOCKED_DOOR || QUERY_FLAG(tmp,FLAG_CAN_ROLL))
2034     mon = tmp;
2035     tmp=tmp->above;
2036     }
2037    
2038     if (mon==NULL) /* This happens anytime the player tries to move */
2039     return; /* into a wall */
2040    
2041     if(mon->head != NULL)
2042     mon = mon->head;
2043    
2044     if ((mon->type==DOOR && mon->stats.hp>=0) || (mon->type==LOCKED_DOOR))
2045     if (player_attack_door(op, mon)) return;
2046    
2047     /* The following deals with possibly attacking peaceful
2048     * or frienddly creatures. Basically, all players are considered
2049     * unaggressive. If the moving player has peaceful set, then the
2050     * object should be pushed instead of attacked. It is assumed that
2051     * if you are braced, you will not attack friends accidently,
2052     * and thus will not push them.
2053     */
2054    
2055     /* If the creature is a pet, push it even if the player is not
2056     * peaceful. Our assumption is the creature is a pet if the
2057     * player owns it and it is either friendly or unagressive.
2058     */
2059 root 1.2 if ((op->type==PLAYER)
2060     &&
2061     (
2062     (get_owner(mon) && get_owner(mon)->contr
2063     && same_party (get_owner(mon)->contr->party, op->contr->party))
2064     || get_owner(mon) == op
2065     )
2066     && (QUERY_FLAG(mon,FLAG_UNAGGRESSIVE) || QUERY_FLAG(mon, FLAG_FRIENDLY)))
2067 root 1.1 {
2068     /* If we're braced, we don't want to switch places with it */
2069     if (op->contr->braced) return;
2070     play_sound_map(op->map, op->x, op->y, SOUND_PUSH_PLAYER);
2071     (void) push_ob(mon,dir,op);
2072     if(op->contr->tmp_invis||op->hide) make_visible(op);
2073     return;
2074     }
2075    
2076     /* in certain circumstances, you shouldn't attack friendly
2077     * creatures. Note that if you are braced, you can't push
2078     * someone, but put it inside this loop so that you won't
2079     * attack them either.
2080     */
2081     if ((mon->type==PLAYER || mon->enemy != op) &&
2082     (mon->type==PLAYER || QUERY_FLAG(mon,FLAG_UNAGGRESSIVE) || QUERY_FLAG(mon, FLAG_FRIENDLY)) &&
2083     (op->contr->peaceful && !on_battleground)) {
2084     if (!op->contr->braced) {
2085     play_sound_map(op->map, op->x, op->y, SOUND_PUSH_PLAYER);
2086     (void) push_ob(mon,dir,op);
2087     } else {
2088     new_draw_info(0, 0,op,"You withhold your attack");
2089     }
2090     if(op->contr->tmp_invis||op->hide) make_visible(op);
2091     }
2092    
2093     /* If the object is a boulder or other rollable object, then
2094     * roll it if not braced. You can't roll it if you are braced.
2095     */
2096     else if(QUERY_FLAG(mon,FLAG_CAN_ROLL)&&(!op->contr->braced)) {
2097     recursive_roll(mon,dir,op);
2098     if(action_makes_visible(op)) make_visible(op);
2099     }
2100    
2101     /* Any generic living creature. Including things like doors.
2102     * Way it works is like this: First, it must have some hit points
2103     * and be living. Then, it must be one of the following:
2104     * 1) Not a player, 2) A player, but of a different party. Note
2105     * that party_number -1 is no party, so attacks can still happen.
2106     */
2107    
2108     else if ((mon->stats.hp>=0) && QUERY_FLAG(mon, FLAG_ALIVE) &&
2109     ((mon->type!=PLAYER || op->contr->party==NULL ||
2110     op->contr->party!=mon->contr->party))) {
2111    
2112     /* If the player hasn't hit something this tick, and does
2113     * so, give them speed boost based on weapon speed. Doing
2114     * it here is better than process_players2, which basically
2115     * incurred a 1 tick offset.
2116     */
2117     if (!op->contr->has_hit) {
2118     op->speed_left += op->speed / op->contr->weapon_sp;
2119    
2120     op->contr->has_hit = 1; /* The last action was to hit, so use weapon_sp */
2121     }
2122    
2123     skill_attack(mon, op, 0, NULL, NULL);
2124    
2125     /* If attacking another player, that player gets automatic
2126     * hitback, and doesn't loose luck either.
2127     * Disable hitback on the battleground or if the target is
2128     * the wiz.
2129     */
2130     if (mon->type == PLAYER && mon->stats.hp >= 0 && !mon->contr->has_hit &&
2131     !on_battleground && !QUERY_FLAG(mon, FLAG_WIZ)) {
2132     short luck = mon->stats.luck;
2133     mon->contr->has_hit = 1;
2134     skill_attack(op, mon, 0, NULL, NULL);
2135     mon->stats.luck = luck;
2136     }
2137     if(action_makes_visible(op)) make_visible(op);
2138     }
2139     } /* if player should attack something */
2140     }
2141    
2142     int move_player(object *op,int dir) {
2143     int pick;
2144    
2145     if(op->map == NULL || op->map->in_memory != MAP_IN_MEMORY)
2146     return 0;
2147    
2148     /* Sanity check: make sure dir is valid */
2149     if ( ( dir < 0 ) || ( dir >= 9 ) ) {
2150     LOG( llevError, "move_player: invalid direction %d\n", dir);
2151     return 0;
2152     }
2153    
2154     /* peterm: added following line */
2155     if(QUERY_FLAG(op,FLAG_CONFUSED) && dir)
2156     dir = absdir(dir + RANDOM()%3 + RANDOM()%3 - 2);
2157    
2158     op->facing = dir;
2159    
2160     if(op->hide) do_hidden_move(op);
2161    
2162     if(op->contr->fire_on) {
2163     fire(op,dir);
2164     }
2165     else move_player_attack(op,dir);
2166    
2167     pick = check_pick(op);
2168    
2169    
2170     /* Add special check for newcs players and fire on - this way, the
2171     * server can handle repeat firing.
2172     */
2173     if (op->contr->fire_on || (op->contr->run_on && pick!=0)) {
2174     op->direction = dir;
2175     } else {
2176     op->direction=0;
2177     }
2178     /* Update how the player looks. Use the facing, so direction may
2179     * get reset to zero. This allows for full animation capabilities
2180     * for players.
2181     */
2182     animate_object(op, op->facing);
2183     return 0;
2184     }
2185    
2186     /* This is similar to handle_player, below, but is only used by the
2187     * new client/server stuff.
2188     * This is sort of special, in that the new client/server actually uses
2189     * the new speed values for commands.
2190     *
2191     * Returns true if there are more actions we can do.
2192     */
2193     int handle_newcs_player(object *op)
2194     {
2195     if (op->contr->hidden) {
2196     op->invisible = 1000;
2197     /* the socket code flasehs the player visible/invisible
2198     * depending on the value if invisible, so we need to
2199     * alternate it here for it to work correctly.
2200     */
2201     if (pticks & 2) op->invisible--;
2202     }
2203     else if(op->invisible&&!(QUERY_FLAG(op,FLAG_MAKE_INVIS))) {
2204     op->invisible--;
2205     if(!op->invisible) {
2206     make_visible(op);
2207     new_draw_info(NDI_UNIQUE, 0, op, "Your invisibility spell runs out.");
2208     }
2209     }
2210    
2211     if (QUERY_FLAG(op, FLAG_SCARED)) {
2212     flee_player(op);
2213     /* If player is still scared, that is his action for this tick */
2214     if (QUERY_FLAG(op, FLAG_SCARED)) {
2215     op->speed_left--;
2216     return 0;
2217     }
2218     }
2219    
2220     /* I've been seeing crashes where the golem has been destroyed, but
2221     * the player object still points to the defunct golem. The code that
2222     * destroys the golem looks correct, and it doesn't always happen, so
2223     * put this in a a workaround to clean up the golem pointer.
2224     */
2225     if (op->contr->ranges[range_golem] &&
2226     ((op->contr->golem_count != op->contr->ranges[range_golem]->count) ||
2227     QUERY_FLAG(op->contr->ranges[range_golem], FLAG_REMOVED))) {
2228     op->contr->ranges[range_golem] = NULL;
2229     op->contr->golem_count = 0;
2230     }
2231    
2232     /* call this here - we also will call this in do_ericserver, but
2233     * the players time has been increased when doericserver has been
2234     * called, so we recheck it here.
2235     */
2236     HandleClient(&op->contr->socket, op->contr);
2237     if (op->speed_left<0) return 0;
2238    
2239     if(op->direction && (op->contr->run_on || op->contr->fire_on)) {
2240     /* All move commands take 1 tick, at least for now */
2241     op->speed_left--;
2242    
2243     /* Instead of all the stuff below, let move_player take care
2244     * of it. Also, some of the skill stuff is only put in
2245     * there, as well as the confusion stuff.
2246     */
2247     move_player(op, op->direction);
2248     if (op->speed_left>0) return 1;
2249     else return 0;
2250     }
2251     return 0;
2252     }
2253    
2254     int save_life(object *op) {
2255     object *tmp;
2256    
2257     if(!QUERY_FLAG(op,FLAG_LIFESAVE))
2258     return 0;
2259    
2260     for(tmp=op->inv;tmp!=NULL;tmp=tmp->below)
2261     if(QUERY_FLAG(tmp, FLAG_APPLIED)&&QUERY_FLAG(tmp,FLAG_LIFESAVE)) {
2262     play_sound_map(op->map, op->x, op->y, SOUND_OB_EVAPORATE);
2263     new_draw_info_format(NDI_UNIQUE, 0,op,
2264     "Your %s vibrates violently, then evaporates.",
2265     query_name(tmp));
2266     if (op->contr)
2267     esrv_del_item(op->contr, tmp->count);
2268     remove_ob(tmp);
2269     free_object(tmp);
2270     CLEAR_FLAG(op, FLAG_LIFESAVE);
2271     if(op->stats.hp<0)
2272     op->stats.hp = op->stats.maxhp;
2273     if(op->stats.food<0)
2274     op->stats.food = 999;
2275     fix_player(op);
2276     return 1;
2277     }
2278     LOG(llevError,"Error: LIFESAVE set without applied object.\n");
2279     CLEAR_FLAG(op, FLAG_LIFESAVE);
2280     enter_player_savebed(op); /* bring him home. */
2281     return 0;
2282     }
2283    
2284     /* This goes throws the inventory and removes unpaid objects, and puts them
2285     * back in the map (location and map determined by values of env). This
2286     * function will descend into containers. op is the object to start the search
2287     * from.
2288     */
2289     void remove_unpaid_objects(object *op, object *env)
2290     {
2291     object *next;
2292    
2293     while (op) {
2294     next=op->below; /* Make sure we have a good value, in case
2295     * we remove object 'op'
2296     */
2297     if (QUERY_FLAG(op, FLAG_UNPAID)) {
2298     remove_ob(op);
2299     op->x = env->x;
2300     op->y = env->y;
2301     if (env->type == PLAYER)
2302     esrv_del_item(env->contr, op->count);
2303     insert_ob_in_map(op, env->map, NULL,0);
2304     }
2305     else if (op->inv) remove_unpaid_objects(op->inv, env);
2306     op=next;
2307     }
2308     }
2309    
2310    
2311     /*
2312     * Returns pointer a static string containing gravestone text
2313     * Moved from apply.c to player.c - player.c is what
2314     * actually uses this function. player.c may not be quite the
2315     * best, a misc file for object actions is probably better,
2316     * but there isn't one in the server directory.
2317     */
2318     char *gravestone_text (object *op)
2319     {
2320     static char buf2[MAX_BUF];
2321     char buf[MAX_BUF];
2322     time_t now = time (NULL);
2323    
2324     strcpy (buf2, " R.I.P.\n\n");
2325     if (op->type == PLAYER)
2326     sprintf (buf, "%s the %s\n", op->name, op->contr->title);
2327     else
2328     sprintf (buf, "%s\n", op->name);
2329     strncat (buf2, " ", 20 - strlen (buf) / 2);
2330     strcat (buf2, buf);
2331     if (op->type == PLAYER)
2332     sprintf (buf, "who was in level %d when killed\n", op->level);
2333     else
2334     sprintf (buf, "who was in level %d when died.\n\n", op->level);
2335     strncat (buf2, " ", 20 - strlen (buf) / 2);
2336     strcat (buf2, buf);
2337     if (op->type == PLAYER) {
2338     sprintf (buf, "by %s.\n\n", op->contr->killer);
2339     strncat (buf2, " ", 21 - strlen (buf) / 2);
2340     strcat (buf2, buf);
2341     }
2342     strftime (buf, MAX_BUF, "%b %d %Y\n", localtime (&now));
2343     strncat (buf2, " ", 20 - strlen (buf) / 2);
2344     strcat (buf2, buf);
2345     return buf2;
2346     }
2347    
2348    
2349    
2350     void do_some_living(object *op) {
2351     int last_food=op->stats.food;
2352     int gen_hp, gen_sp, gen_grace;
2353     int over_hp, over_sp, over_grace;
2354     int i;
2355     int rate_hp = 1200;
2356     int rate_sp = 2500;
2357     int rate_grace = 2000;
2358     const int max_hp = 1;
2359     const int max_sp = 1;
2360     const int max_grace = 1;
2361    
2362     if (op->contr->outputs_sync) {
2363     for (i=0; i<NUM_OUTPUT_BUFS; i++)
2364     if (op->contr->outputs[i].buf!=NULL &&
2365     (op->contr->outputs[i].first_update+op->contr->outputs_sync)<pticks)
2366     flush_output_element(op, &op->contr->outputs[i]);
2367     }
2368    
2369     if(op->contr->state==ST_PLAYING) {
2370    
2371     /* these next three if clauses make it possible to SLOW DOWN
2372     hp/grace/spellpoint regeneration. */
2373     if(op->contr->gen_hp >= 0 )
2374     gen_hp=(op->contr->gen_hp+1)*op->stats.maxhp;
2375     else {
2376     gen_hp = op->stats.maxhp;
2377     rate_hp -= rate_hp/2 * op->contr->gen_hp;
2378     }
2379     if(op->contr->gen_sp >= 0 )
2380     gen_sp=(op->contr->gen_sp+1)*op->stats.maxsp;
2381     else {
2382     gen_sp = op->stats.maxsp;
2383     rate_sp -= rate_sp/2 * op->contr->gen_sp;
2384     }
2385     if(op->contr->gen_grace >= 0)
2386     gen_grace=(op->contr->gen_grace+1)*op->stats.maxgrace;
2387     else {
2388     gen_grace = op->stats.maxgrace;
2389     rate_grace -= rate_grace/2 * op->contr->gen_grace;
2390     }
2391    
2392     /* Regenerate Spell Points */
2393     if(op->contr->ranges[range_golem]==NULL && --op->last_sp<0) {
2394     gen_sp = gen_sp * 10 / (op->contr->gen_sp_armour < 10? 10 : op->contr->gen_sp_armour);
2395     if(op->stats.sp<op->stats.maxsp) {
2396     op->stats.sp++;
2397     /* dms do not consume food */
2398     if (!QUERY_FLAG(op,FLAG_WIZ)) {
2399     op->stats.food--;
2400     if(op->contr->digestion<0)
2401     op->stats.food+=op->contr->digestion;
2402     else if(op->contr->digestion>0 &&
2403     random_roll(0, op->contr->digestion, op, PREFER_HIGH))
2404     op->stats.food=last_food;
2405     }
2406     }
2407     if (max_sp>1) {
2408     over_sp = (gen_sp+10)/rate_sp;
2409     if (over_sp > 0) {
2410     if(op->stats.sp<op->stats.maxsp) {
2411     op->stats.sp += over_sp>max_sp ? max_sp : over_sp;
2412     if(random_roll(0, rate_sp-1, op, PREFER_LOW) > ((gen_sp+10)%rate_sp))
2413     op->stats.sp--;
2414     if(op->stats.sp>op->stats.maxsp)
2415     op->stats.sp=op->stats.maxsp;
2416     }
2417     op->last_sp=0;
2418     } else {
2419     op->last_sp=rate_sp/(gen_sp<20 ? 30 : gen_sp+10);
2420     }
2421     } else {
2422     op->last_sp=rate_sp/(gen_sp<20 ? 30 : gen_sp+10);
2423     }
2424     }
2425    
2426     /* Regenerate Grace */
2427     /* I altered this a little - maximum grace is ony achieved through prayer -b.t.*/
2428     if(--op->last_grace<0) {
2429     if(op->stats.grace<op->stats.maxgrace/2)
2430     op->stats.grace++; /* no penalty in food for regaining grace */
2431     if(max_grace>1) {
2432     over_grace = (gen_grace<20 ? 30 : gen_grace+10)/rate_grace;
2433     if (over_grace > 0) {
2434     op->stats.sp += over_grace
2435     + (random_roll(0, rate_grace-1, op, PREFER_HIGH) > ((gen_grace<20 ? 30 : gen_grace+10)%rate_grace))? -1 : 0;
2436     op->last_grace=0;
2437     } else {
2438     op->last_grace=rate_grace/(gen_grace<20 ? 30 : gen_grace+10);
2439     }
2440     } else {
2441     op->last_grace=rate_grace/(gen_grace<20 ? 30 : gen_grace+10);
2442     }
2443     /* wearing stuff doesn't detract from grace generation. */
2444     }
2445    
2446     /* Regenerate Hit Points */
2447     if(--op->last_heal<0) {
2448     if(op->stats.hp<op->stats.maxhp) {
2449     op->stats.hp++;
2450     /* dms do not consume food */
2451     if (!QUERY_FLAG(op,FLAG_WIZ)) {
2452     op->stats.food--;
2453     if(op->contr->digestion<0)
2454     op->stats.food+=op->contr->digestion;
2455     else if(op->contr->digestion>0 &&
2456     random_roll(0, op->contr->digestion, op, PREFER_HIGH))
2457     op->stats.food=last_food;
2458     }
2459     }
2460     if(max_hp>1) {
2461     over_hp = (gen_hp<20 ? 30 : gen_hp+10)/rate_hp;
2462     if (over_hp > 0) {
2463     op->stats.sp += over_hp
2464     + (RANDOM()%rate_hp > ((gen_hp<20 ? 30 : gen_hp+10)%rate_hp))? -1 : 0;
2465     op->last_heal=0;
2466     } else {
2467     op->last_heal=rate_hp/(gen_hp<20 ? 30 : gen_hp+10);
2468     }
2469     } else {
2470     op->last_heal=rate_hp/(gen_hp<20 ? 30 : gen_hp+10);
2471     }
2472     }
2473    
2474     /* Digestion */
2475     if(--op->last_eat<0) {
2476 root 1.2 int dg = op->contr->digestion>=0 && op->contr->digestion<2 ? 2 : op->contr->digestion;
2477     int bonus=dg>0?dg:0,
2478     penalty=dg<0?-dg:0;
2479 root 1.1 if(op->contr->gen_hp > 0)
2480     op->last_eat=25*(1+bonus)/(op->contr->gen_hp+penalty+1);
2481     else
2482     op->last_eat=25*(1+bonus)/(penalty +1);
2483     /* dms do not consume food */
2484     if (!QUERY_FLAG(op,FLAG_WIZ)) op->stats.food--;
2485     }
2486     }
2487    
2488     if(op->contr->state==ST_PLAYING&&op->stats.food<0&&op->stats.hp>=0) {
2489     object *tmp, *flesh=NULL;
2490    
2491     for(tmp=op->inv;tmp!=NULL;tmp=tmp->below) {
2492     if(!QUERY_FLAG(tmp, FLAG_UNPAID)) {
2493     if (tmp->type==FOOD || tmp->type==DRINK || tmp->type==POISON) {
2494     new_draw_info(NDI_UNIQUE, 0,op,"You blindly grab for a bite of food.");
2495     manual_apply(op,tmp,0);
2496     if(op->stats.food>=0||op->stats.hp<0)
2497     break;
2498     }
2499     else if (tmp->type==FLESH) flesh=tmp;
2500     } /* End if paid for object */
2501     } /* end of for loop */
2502     /* If player is still starving, it means they don't have any food, so
2503     * eat flesh instead.
2504     */
2505     if (op->stats.food<0 && op->stats.hp>=0 && flesh) {
2506     new_draw_info(NDI_UNIQUE, 0,op,"You blindly grab for a bite of food.");
2507     manual_apply(op,flesh,0);
2508     }
2509     } /* end if player is starving */
2510    
2511     while(op->stats.food<0&&op->stats.hp>0)
2512     op->stats.food++,op->stats.hp--;
2513    
2514     if (!op->contr->state&&!QUERY_FLAG(op,FLAG_WIZ)&&(op->stats.hp<0||op->stats.food<0))
2515     kill_player(op);
2516     }
2517    
2518    
2519    
2520     /* If the player should die (lack of hp, food, etc), we call this.
2521     * op is the player in jeopardy. If the player can not be saved (not
2522     * permadeath, no lifesave), this will take care of removing the player
2523     * file.
2524     */
2525     void kill_player(object *op)
2526     {
2527     char buf[MAX_BUF];
2528     int x,y,i;
2529     mapstruct *map; /* this is for resurrection */
2530     int z;
2531     int num_stats_lose;
2532     int lost_a_stat;
2533     int lose_this_stat;
2534     int this_stat;
2535     int will_kill_again;
2536     archetype *at;
2537     object *tmp;
2538    
2539     if(save_life(op))
2540     return;
2541    
2542    
2543     /* If player dies on BATTLEGROUND, no stat/exp loss! For Combat-Arenas
2544     * in cities ONLY!!! It is very important that this doesn't get abused.
2545     * Look at op_on_battleground() for more info --AndreasV
2546     */
2547     if (op_on_battleground(op, &x, &y)) {
2548     new_draw_info(NDI_UNIQUE | NDI_NAVY, 0,op,
2549     "You have been defeated in combat!");
2550     new_draw_info(NDI_UNIQUE | NDI_NAVY, 0,op,
2551     "Local medics have saved your life...");
2552    
2553     /* restore player */
2554     at = find_archetype("poisoning");
2555     tmp=present_arch_in_ob(at,op);
2556     if (tmp) {
2557     remove_ob(tmp);
2558     free_object(tmp);
2559     new_draw_info(NDI_UNIQUE, 0,op, "Your body feels cleansed");
2560     }
2561    
2562     at = find_archetype("confusion");
2563     tmp=present_arch_in_ob(at,op);
2564     if (tmp) {
2565     remove_ob(tmp);
2566     free_object(tmp);
2567     new_draw_info(NDI_UNIQUE, 0,tmp, "Your mind feels clearer");
2568     }
2569    
2570     cure_disease(op,0); /* remove any disease */
2571     op->stats.hp=op->stats.maxhp;
2572     if (op->stats.food<=0) op->stats.food=999;
2573    
2574     /* create a bodypart-trophy to make the winner happy */
2575     tmp=arch_to_object(find_archetype("finger"));
2576     if (tmp != NULL)
2577     {
2578     sprintf(buf,"%s's finger",op->name);
2579     tmp->name = add_string(buf);
2580     sprintf(buf," This finger has been cut off %s\n"
2581     " the %s, when he was defeated at\n level %d by %s.\n",
2582     op->name, op->contr->title, (int)(op->level),
2583     op->contr->killer);
2584     tmp->msg=add_string(buf);
2585     tmp->value=0, tmp->material=0, tmp->type=0;
2586     tmp->materialname = NULL;
2587     tmp->x = op->x, tmp->y = op->y;
2588     insert_ob_in_map(tmp,op->map,op,0);
2589     }
2590    
2591     /* teleport defeated player to new destination*/
2592     transfer_ob(op, x, y, 0, NULL);
2593     op->contr->braced=0;
2594     return;
2595     }
2596    
2597     /* Lauwenmark: Handle for plugin death event */
2598     if (execute_event(op, EVENT_DEATH,NULL,NULL,NULL,SCRIPT_FIX_ALL) != 0)
2599     return;
2600    
2601     /* Lauwenmark: Handle for the global death event */
2602     execute_global_event(EVENT_PLAYER_DEATH, op);
2603     if(op->stats.food<0) {
2604     if (op->contr->explore) {
2605     new_draw_info(NDI_UNIQUE, 0,op,"You would have starved, but you are");
2606     new_draw_info(NDI_UNIQUE, 0,op,"in explore mode, so...");
2607     op->stats.food=999;
2608     return;
2609     }
2610     sprintf(buf,"%s starved to death.",op->name);
2611     strcpy(op->contr->killer,"starvation");
2612     }
2613     else {
2614     if (op->contr->explore) {
2615     new_draw_info(NDI_UNIQUE, 0,op,"You would have died, but you are");
2616     new_draw_info(NDI_UNIQUE, 0,op,"in explore mode, so...");
2617     op->stats.hp=op->stats.maxhp;
2618     return;
2619     }
2620     sprintf(buf,"%s died.",op->name);
2621     }
2622     play_sound_player_only(op->contr, SOUND_PLAYER_DIES,0,0);
2623    
2624     /* save the map location for corpse, gravestone*/
2625     x=op->x;y=op->y;map=op->map;
2626    
2627    
2628     if (settings.not_permadeth == TRUE) {
2629     /* NOT_PERMADEATH code. This basically brings the character back to
2630     * life if they are dead - it takes some exp and a random stat.
2631     * See the config.h file for a little more in depth detail about this.
2632     */
2633    
2634     /* Basically two ways to go - remove a stat permanently, or just
2635     * make it depletion. This bunch of code deals with that aspect
2636     * of death.
2637     */
2638 root 1.2 #if 0
2639 root 1.1 if (settings.balanced_stat_loss) {
2640     /* If stat loss is permanent, lose one stat only. */
2641     /* Lower level chars don't lose as many stats because they suffer
2642     more if they do. */
2643     /* Higher level characters can afford things such as potions of
2644     restoration, or better, stat potions. So we slug them that
2645     little bit harder. */
2646     /* GD */
2647     if (settings.stat_loss_on_death)
2648     num_stats_lose = 1;
2649     else
2650     num_stats_lose = 1 + op->level/BALSL_NUMBER_LOSSES_RATIO;
2651     } else {
2652     num_stats_lose = 1;
2653     }
2654     lost_a_stat = 0;
2655    
2656     for (z=0; z<num_stats_lose; z++) {
2657     if (settings.stat_loss_on_death) {
2658     /* Pick a random stat and take a point off it. Tell the player
2659     * what he lost.
2660     */
2661     i = RANDOM() % 7;
2662     change_attr_value(&(op->stats), i,-1);
2663     check_stat_bounds(&(op->stats));
2664     change_attr_value(&(op->contr->orig_stats), i,-1);
2665     check_stat_bounds(&(op->contr->orig_stats));
2666     new_draw_info(NDI_UNIQUE, 0,op, lose_msg[i]);
2667     lost_a_stat = 1;
2668     } else {
2669     /* deplete a stat */
2670     archetype *deparch=find_archetype("depletion");
2671     object *dep;
2672    
2673     i = RANDOM() % 7;
2674     dep = present_arch_in_ob(deparch,op);
2675     if(!dep) {
2676     dep = arch_to_object(deparch);
2677     insert_ob_in_ob(dep, op);
2678     }
2679     lose_this_stat = 1;
2680     if (settings.balanced_stat_loss) {
2681     /* GD */
2682     /* Get the stat that we're about to deplete. */
2683     this_stat = get_attr_value(&(dep->stats), i);
2684     if (this_stat < 0) {
2685     int loss_chance = 1 + op->level/BALSL_LOSS_CHANCE_RATIO;
2686     int keep_chance = this_stat * this_stat;
2687     /* Yes, I am paranoid. Sue me. */
2688     if (keep_chance < 1)
2689     keep_chance = 1;
2690    
2691     /* There is a maximum depletion total per level. */
2692     if (this_stat < -1 - op->level/BALSL_MAX_LOSS_RATIO) {
2693     lose_this_stat = 0;
2694     /* Take loss chance vs keep chance to see if we
2695     retain the stat. */
2696     } else {
2697     if (random_roll(0, loss_chance + keep_chance-1,
2698     op, PREFER_LOW) < keep_chance)
2699     lose_this_stat = 0;
2700     /* LOG(llevDebug, "Determining stat loss. Stat: %d Keep: %d Lose: %d Result: %s.\n",
2701     this_stat, keep_chance, loss_chance,
2702     lose_this_stat?"LOSE":"KEEP"); */
2703     }
2704     }
2705     }
2706    
2707     if (lose_this_stat) {
2708     this_stat = get_attr_value(&(dep->stats), i);
2709     /* We could try to do something clever like find another
2710     * stat to reduce if this fails. But chances are, if
2711     * stats have been depleted to -50, all are pretty low
2712     * and should be roughly the same, so it shouldn't make a
2713     * difference.
2714     */
2715     if (this_stat>=-50) {
2716     change_attr_value(&(dep->stats), i, -1);
2717     SET_FLAG(dep, FLAG_APPLIED);
2718     new_draw_info(NDI_UNIQUE, 0,op, lose_msg[i]);
2719     fix_player(op);
2720     lost_a_stat = 1;
2721     }
2722     }
2723     }
2724     }
2725     /* If no stat lost, tell the player. */
2726     if (!lost_a_stat)
2727     {
2728     /* determine_god() seems to not work sometimes... why is this?
2729     Should I be using something else? GD */
2730     const char *god = determine_god(op);
2731     if (god && (strcmp(god, "none")))
2732     new_draw_info_format(NDI_UNIQUE, 0, op, "For a brief "
2733     "moment you feel the holy presence of %s protecting"
2734     " you.", god);
2735     else
2736     new_draw_info(NDI_UNIQUE, 0, op, "For a brief moment you"
2737     " feel a holy presence protecting you.");
2738     }
2739 root 1.2 #endif
2740     new_draw_info(NDI_UNIQUE, 0, op, "For a brief moment you"
2741     " feel a holy presence protecting you from losing yourself completely.");
2742 root 1.1
2743     /* Put a gravestone up where the character 'almost' died. List the
2744     * exp loss on the stone.
2745     */
2746     tmp=arch_to_object(find_archetype("gravestone"));
2747     sprintf(buf,"%s's gravestone",op->name);
2748     FREE_AND_COPY(tmp->name, buf);
2749     sprintf(buf,"%s's gravestones",op->name);
2750     FREE_AND_COPY(tmp->name_pl, buf);
2751     sprintf(buf,"RIP\nHere rests the hero %s the %s,\n"
2752     "who was killed\n"
2753     "by %s.\n",
2754     op->name, op->contr->title,
2755     op->contr->killer);
2756     tmp->msg = add_string(buf);
2757     tmp->x=op->x,tmp->y=op->y;
2758     insert_ob_in_map (tmp, op->map, NULL,0);
2759    
2760     /**************************************/
2761     /* */
2762     /* Subtract the experience points, */
2763     /* if we died cause of food, give us */
2764     /* food, and reset HP's... */
2765     /* */
2766     /**************************************/
2767    
2768     /* remove any poisoning and confusion the character may be suffering.*/
2769     /* restore player */
2770     at = find_archetype("poisoning");
2771     tmp=present_arch_in_ob(at,op);
2772     if (tmp) {
2773     remove_ob(tmp);
2774     free_object(tmp);
2775     new_draw_info(NDI_UNIQUE, 0,op, "Your body feels cleansed");
2776     }
2777    
2778     at = find_archetype("confusion");
2779     tmp=present_arch_in_ob(at,op);
2780     if (tmp) {
2781     remove_ob(tmp);
2782     free_object(tmp);
2783     new_draw_info(NDI_UNIQUE, 0,tmp, "Your mind feels clearer");
2784     }
2785     cure_disease(op,0); /* remove any disease */
2786    
2787     /*add_exp(op, (op->stats.exp * -0.20)); */
2788     apply_death_exp_penalty(op);
2789     if(op->stats.food < 100) op->stats.food = 900;
2790     op->stats.hp = op->stats.maxhp;
2791     op->stats.sp = MAX(op->stats.sp, op->stats.maxsp);
2792     op->stats.grace = MAX(op->stats.grace, op->stats.maxgrace);
2793    
2794     /*
2795     * Check to see if the player is in a shop. IF so, then check to see if
2796     * the player has any unpaid items. If so, remove them and put them back
2797     * in the map.
2798     */
2799    
2800     for (tmp= get_map_ob(op->map, op->x, op->y); tmp; tmp=tmp->above) {
2801     if (tmp->type == SHOP_FLOOR) {
2802     remove_unpaid_objects(op->inv, op);
2803     break;
2804     }
2805     }
2806    
2807    
2808     /****************************************/
2809     /* */
2810     /* Move player to his current respawn- */
2811     /* position (usually last savebed) */
2812     /* */
2813     /****************************************/
2814    
2815     enter_player_savebed(op);
2816    
2817     /* Save the player before inserting the force to reduce
2818     * chance of abuse.
2819     */
2820     op->contr->braced=0;
2821     save_player(op,1);
2822    
2823     /* it is possible that the player has blown something up
2824     * at his savebed location, and that can have long lasting
2825     * spell effects. So first see if there is a spell effect
2826     * on the space that might harm the player.
2827     */
2828     will_kill_again=0;
2829     for (tmp= get_map_ob(op->map, op->x, op->y); tmp; tmp=tmp->above) {
2830     if (tmp->type ==SPELL_EFFECT)
2831     will_kill_again|=tmp->attacktype;
2832     }
2833     if (will_kill_again) {
2834     object *force;
2835     int at;
2836    
2837     force=get_archetype(FORCE_NAME);
2838     /* 50 ticks should be enough time for the spell to abate */
2839     force->speed=0.1;
2840     force->speed_left=-5.0;
2841     SET_FLAG(force, FLAG_APPLIED);
2842     for (at=0; at<NROFATTACKS; at++) {
2843     if (will_kill_again & (1 << at))
2844     force->resist[at] = 100;
2845     }
2846     insert_ob_in_ob(force, op);
2847     fix_player(op);
2848    
2849     }
2850     /**************************************/
2851     /* */
2852     /* Repaint the characters inv, and */
2853     /* stats, and show a nasty message ;) */
2854     /* */
2855     /**************************************/
2856    
2857     new_draw_info(NDI_UNIQUE, 0,op,"YOU HAVE DIED.");
2858     return;
2859     } /* NOT_PERMADETH */
2860     else {
2861     /* If NOT_PERMADETH is set, then the rest of this is not reachable. This
2862     * should probably be embedded in an else statement.
2863     */
2864    
2865     op->contr->party=NULL;
2866     if (settings.set_title == TRUE)
2867     op->contr->own_title[0]='\0';
2868     new_draw_info(NDI_UNIQUE|NDI_ALL, 0,NULL, buf);
2869     check_score(op);
2870     if(op->contr->ranges[range_golem]!=NULL) {
2871     remove_friendly_object(op->contr->ranges[range_golem]);
2872     remove_ob(op->contr->ranges[range_golem]);
2873     free_object(op->contr->ranges[range_golem]);
2874     op->contr->ranges[range_golem]=NULL;
2875     op->contr->golem_count=0;
2876     }
2877     loot_object(op); /* Remove some of the items for good */
2878     remove_ob(op);
2879     op->direction=0;
2880    
2881     if(!QUERY_FLAG(op,FLAG_WAS_WIZ)&&op->stats.exp) {
2882     delete_character(op->name,0);
2883     if (settings.resurrection == TRUE) {
2884     /* save playerfile sans equipment when player dies
2885     ** then save it as player.pl.dead so that future resurrection
2886     ** type spells will work on them nicely
2887     */
2888     delete_character(op->name,0);
2889     op->stats.hp = op->stats.maxhp;
2890     op->stats.food = 999;
2891    
2892     /* set the location of where the person will reappear when */
2893     /* maybe resurrection code should fix map also */
2894     strcpy(op->contr->maplevel, settings.emergency_mapname);
2895     if(op->map!=NULL)
2896     op->map = NULL;
2897     op->x = settings.emergency_x;
2898     op->y = settings.emergency_y;
2899     save_player(op,0);
2900     op->map = map;
2901     /* please see resurrection.c: peterm */
2902     dead_player(op);
2903     } else {
2904     delete_character(op->name,1);
2905     }
2906     }
2907     play_again(op);
2908    
2909     /* peterm: added to create a corpse at deathsite. */
2910     tmp=arch_to_object(find_archetype("corpse_pl"));
2911     sprintf(buf,"%s", op->name);
2912     FREE_AND_COPY(tmp->name, buf);
2913     FREE_AND_COPY(tmp->name_pl, buf);
2914     tmp->level=op->level;
2915     tmp->x=x;tmp->y=y;
2916     if (tmp->msg)
2917     free_string(tmp->msg);
2918     tmp->msg = add_string (gravestone_text(op));
2919     SET_FLAG (tmp, FLAG_UNIQUE);
2920     insert_ob_in_map (tmp, map, NULL,0);
2921     }
2922     }
2923    
2924    
2925     void loot_object(object *op) { /* Grab and destroy some treasure */
2926     object *tmp,*tmp2,*next;
2927    
2928     if (op->container) { /* close open sack first */
2929     esrv_apply_container (op, op->container);
2930     }
2931    
2932     for(tmp=op->inv;tmp!=NULL;tmp=next) {
2933     next=tmp->below;
2934     if (tmp->type==EXPERIENCE || tmp->invisible) continue;
2935     remove_ob(tmp);
2936     tmp->x=op->x,tmp->y=op->y;
2937     if (tmp->type == CONTAINER) { /* empty container to ground */
2938     loot_object(tmp);
2939     }
2940     if(!QUERY_FLAG(tmp, FLAG_UNIQUE) && (QUERY_FLAG(tmp, FLAG_STARTEQUIP)
2941     || QUERY_FLAG(tmp,FLAG_NO_DROP) || !(RANDOM()%3))) {
2942     if(tmp->nrof>1) {
2943     tmp2=get_split_ob(tmp,1+RANDOM()%(tmp->nrof-1));
2944     free_object(tmp2);
2945     insert_ob_in_map(tmp,op->map,NULL,0);
2946     } else
2947     free_object(tmp);
2948     } else
2949     insert_ob_in_map(tmp,op->map,NULL,0);
2950     }
2951     }
2952    
2953     /*
2954     * fix_weight(): Check recursively the weight of all players, and fix
2955     * what needs to be fixed. Refresh windows and fix speed if anything
2956     * was changed.
2957     */
2958    
2959     void fix_weight(void) {
2960     player *pl;
2961     for (pl = first_player; pl != NULL; pl = pl->next) {
2962     int old = pl->ob->carrying, sum = sum_weight(pl->ob);
2963     if(old == sum)
2964     continue;
2965     fix_player(pl->ob);
2966     LOG(llevDebug,"Fixed inventory in %s (%d -> %d)\n",
2967     pl->ob->name, old, sum);
2968     }
2969     }
2970    
2971     void fix_luck(void) {
2972     player *pl;
2973     for (pl = first_player; pl != NULL; pl = pl->next)
2974     if (!pl->ob->contr->state)
2975     change_luck(pl->ob, 0);
2976     }
2977    
2978    
2979     /* cast_dust() - handles op throwing objects of type 'DUST'.
2980     * This is much simpler in the new spell code - we basically
2981     * just treat this as any other spell casting object.
2982     */
2983    
2984     void cast_dust (object *op, object *throw_ob, int dir) {
2985     object *skop, *spob;
2986    
2987     skop = find_skill_by_name(op, throw_ob->skill);
2988    
2989     /* casting POTION 'dusts' is really a use_magic_item skill */
2990     if(op->type==PLAYER && throw_ob->type==POTION && !skop) {
2991     LOG(llevError,"Player %s lacks critical skill use_magic_item!\n",
2992     op->name);
2993     return;
2994     }
2995     spob = throw_ob->inv;
2996     if (op->type==PLAYER && spob)
2997     new_draw_info_format(NDI_UNIQUE, 0,op,"You cast %s.",spob->name);
2998    
2999     cast_spell(op, throw_ob, dir, spob, NULL);
3000    
3001     if(!QUERY_FLAG(throw_ob,FLAG_REMOVED)) remove_ob(throw_ob);
3002     free_object(throw_ob);
3003     }
3004    
3005     void make_visible (object *op) {
3006     op->hide = 0;
3007     op->invisible = 0;
3008     if(op->type==PLAYER) {
3009     op->contr->tmp_invis = 0;
3010     if (op->contr->invis_race) FREE_AND_CLEAR_STR(op->contr->invis_race);
3011     }
3012     update_object(op,UP_OBJ_FACE);
3013     }
3014    
3015     int is_true_undead(object *op) {
3016     object *tmp=NULL;
3017    
3018     if(QUERY_FLAG(&op->arch->clone,FLAG_UNDEAD)) return 1;
3019    
3020     if(op->type==PLAYER)
3021     for(tmp=op->inv;tmp;tmp=tmp->below)
3022     if(tmp->type==EXPERIENCE && tmp->stats.Wis)
3023     if(QUERY_FLAG(tmp,FLAG_UNDEAD)) return 1;
3024     return 0;
3025     }
3026    
3027     /* look at the surrounding terrain to determine
3028     * the hideability of this object. Positive levels
3029     * indicate greater hideability.
3030     */
3031    
3032     int hideability(object *ob) {
3033     int i,level=0, mflag;
3034     sint16 x,y;
3035    
3036     if(!ob||!ob->map) return 0;
3037    
3038     /* so, on normal lighted maps, its hard to hide */
3039     level=ob->map->darkness - 2;
3040    
3041     /* this also picks up whether the object is glowing.
3042     * If you carry a light on a non-dark map, its not
3043     * as bad as carrying a light on a pitch dark map */
3044     if(has_carried_lights(ob)) level =- (10 + (2*ob->map->darkness));
3045    
3046     /* scan through all nearby squares for terrain to hide in */
3047     for(i=0,x=ob->x,y=ob->y;i<9;i++,x=ob->x+freearr_x[i],y=ob->y+freearr_y[i]) {
3048     mflag = get_map_flags(ob->map, NULL, x, y, NULL, NULL);
3049     if (mflag & P_OUT_OF_MAP) { continue; }
3050     if(mflag & P_BLOCKSVIEW) /* something to hide near! */
3051     level += 2;
3052     else /* open terrain! */
3053     level -= 1;
3054     }
3055    
3056     #if 0
3057     LOG(llevDebug,"hideability of %s is %d\n",ob->name,level);
3058     #endif
3059     return level;
3060     }
3061    
3062     /* For Hidden creatures - a chance of becoming 'unhidden'
3063     * every time they move - as we subtract off 'invisibility'
3064     * AND, for players, if they move into a ridiculously unhideable
3065     * spot (surrounded by clear terrain in broad daylight). -b.t.
3066     */
3067    
3068     void do_hidden_move (object *op) {
3069     int hide=0, num=random_roll(0, 19, op, PREFER_LOW);
3070     object *skop;
3071    
3072     if(!op || !op->map) return;
3073    
3074     skop = find_obj_by_type_subtype(op, SKILL, SK_HIDING);
3075    
3076     /* its *extremely* hard to run and sneak/hide at the same time! */
3077     if(op->type==PLAYER && op->contr->run_on) {
3078     if(!skop || num >= skop->level) {
3079     new_draw_info(NDI_UNIQUE,0,op,"You ran too much! You are no longer hidden!");
3080     make_visible(op);
3081     return;
3082     } else num += 20;
3083     }
3084     num += op->map->difficulty;
3085     hide = hideability(op); /* modify by terrain hidden level */
3086     num -= hide;
3087     if((op->type==PLAYER && hide<-10) || ((op->invisible-=num)<=0)) {
3088     make_visible(op);
3089     if(op->type==PLAYER) new_draw_info(NDI_UNIQUE, 0,op,
3090     "You moved out of hiding! You are visible!");
3091     }
3092     else if (op->type == PLAYER && skop) {
3093     change_exp(op, calc_skill_exp(op, NULL, skop), skop->skill, 0);
3094     }
3095     }
3096    
3097     /* determine if who is standing near a hostile creature. */
3098    
3099     int stand_near_hostile( object *who ) {
3100     object *tmp=NULL;
3101     int i,friendly=0,player=0, mflags;
3102     mapstruct *m;
3103     sint16 x,y;
3104    
3105     if(!who) return 0;
3106    
3107     if(who->type==PLAYER) player=1;
3108     else friendly = QUERY_FLAG(who,FLAG_FRIENDLY);
3109    
3110     /* search adjacent squares */
3111     for(i=1;i<9;i++) {
3112     x = who->x+freearr_x[i];
3113     y = who->y+freearr_y[i];
3114     m = who->map;
3115     mflags = get_map_flags(m, &m, x, y, &x, &y);
3116     /* space must be blocked if there is a monster. If not
3117     * blocked, don't need to check this space.
3118     */
3119     if (mflags & P_OUT_OF_MAP) continue;
3120     if (OB_TYPE_MOVE_BLOCK(who, GET_MAP_MOVE_BLOCK(m, x, y))) continue;
3121    
3122     for(tmp=get_map_ob(m,x,y);tmp;tmp=tmp->above) {
3123     if((player||friendly)
3124     &&QUERY_FLAG(tmp,FLAG_MONSTER)&&!QUERY_FLAG(tmp,FLAG_UNAGGRESSIVE))
3125     return 1;
3126     else if(tmp->type==PLAYER)
3127     {
3128     /*don't let a hidden DM prevent you from hiding*/
3129     if(!QUERY_FLAG(tmp, FLAG_WIZ) || tmp->contr->hidden == 0)
3130     return 1;
3131     }
3132     }
3133     }
3134     return 0;
3135     }
3136    
3137     /* check the player los field for viewability of the
3138     * object op. This function works fine for monsters,
3139     * but we dont worry if the object isnt the top one in
3140     * a pile (say a coin under a table would return "viewable"
3141     * by this routine). Another question, should we be
3142     * concerned with the direction the player is looking
3143     * in? Realistically, most of use cant see stuff behind
3144     * our backs...on the other hand, does the "facing" direction
3145     * imply the way your head, or body is facing? Its possible
3146     * for them to differ. Sigh, this fctn could get a bit more complex.
3147     * -b.t.
3148     * This function is now map tiling safe.
3149     */
3150    
3151     int player_can_view (object *pl,object *op) {
3152     rv_vector rv;
3153     int dx,dy;
3154    
3155     if(pl->type!=PLAYER) {
3156     LOG(llevError,"player_can_view() called for non-player object\n");
3157     return -1;
3158     }
3159     if (!pl || !op) return 0;
3160    
3161     if(op->head) { op = op->head; }
3162     get_rangevector(pl, op, &rv, 0x1);
3163    
3164     /* starting with the 'head' part, lets loop
3165     * through the object and find if it has any
3166     * part that is in the los array but isnt on
3167     * a blocked los square.
3168     * we use the archetype to figure out offsets.
3169     */
3170     while(op) {
3171     dx = rv.distance_x + op->arch->clone.x;
3172     dy = rv.distance_y + op->arch->clone.y;
3173    
3174     /* only the viewable area the player sees is updated by LOS
3175     * code, so we need to restrict ourselves to that range of values
3176     * for any meaningful values.
3177     */
3178     if (FABS(dx) <= (pl->contr->socket.mapx/2) &&
3179     FABS(dy) <= (pl->contr->socket.mapy/2) &&
3180     !pl->contr->blocked_los[dx + (pl->contr->socket.mapx/2)][dy+(pl->contr->socket.mapy/2)] )
3181     return 1;
3182     op = op->more;
3183     }
3184     return 0;
3185     }
3186    
3187     /* routine for both players and monsters. We call this when
3188     * there is a possibility for our action distrubing our hiding
3189     * place or invisiblity spell. Artefact invisiblity is not
3190     * effected by this. If we arent invisible to begin with, we
3191     * return 0.
3192     */
3193     int action_makes_visible (object *op) {
3194    
3195     if(op->invisible && QUERY_FLAG(op,FLAG_ALIVE)) {
3196     if(QUERY_FLAG(op,FLAG_MAKE_INVIS))
3197     return 0;
3198    
3199     if (op->contr && op->contr->tmp_invis == 0) return 0;
3200    
3201     /* If monsters, they should become visible */
3202     if(op->hide || !op->contr || (op->contr && op->contr->tmp_invis)) {
3203     new_draw_info_format(NDI_UNIQUE, 0,op,"You become %s!",op->hide?"unhidden":"visible");
3204     return 1;
3205     }
3206     }
3207     return 0;
3208     }
3209    
3210     /* op_on_battleground - checks if the given object op (usually
3211     * a player) is standing on a valid battleground-tile,
3212     * function returns TRUE/FALSE. If true x, y returns the battleground
3213     * -exit-coord. (and if x, y not NULL)
3214     * 19 March 2005 - josh@woosworld.net modifed to check if the battleground also has slaying, maxhp, and maxsp set
3215     * and if those are all set and the player has a marker that matches the slaying send them to a different x, y
3216     * Default is to do the same as before, so only people wanting to have different points need worry about this
3217     */
3218     int op_on_battleground (object *op, int *x, int *y) {
3219     object *tmp;
3220    
3221     /* A battleground-tile needs the following attributes to be valid:
3222     * is_floor 1 (has to be the FIRST floor beneath the player's feet),
3223     * name="battleground", no_pick 1, type=58 (type BATTLEGROUND)
3224     * and the exit-coordinates sp/hp must both be > 0.
3225     * => The intention here is to prevent abuse of the battleground-
3226     * feature (like pickable or hidden battleground tiles). */
3227     for (tmp=op->below; tmp!=NULL; tmp=tmp->below) {
3228     if (QUERY_FLAG (tmp, FLAG_IS_FLOOR)) {
3229     if (QUERY_FLAG (tmp, FLAG_NO_PICK) &&
3230     strcmp(tmp->name, "battleground")==0 &&
3231     tmp->type == BATTLEGROUND && EXIT_X(tmp) && EXIT_Y(tmp)) {
3232     /*before we assign the exit, check if this is a teambattle*/
3233     if ( EXIT_ALT_X(tmp) && EXIT_ALT_Y(tmp) && EXIT_PATH(tmp) ){
3234     object *invtmp;
3235     for(invtmp=op->inv; invtmp != NULL; invtmp=invtmp->below) {
3236     if(invtmp->type==FORCE && invtmp->slaying &&
3237     !strcmp(EXIT_PATH(tmp), invtmp->slaying)){
3238     if (x != NULL && y != NULL)
3239     *x=EXIT_ALT_X(tmp), *y=EXIT_ALT_Y(tmp);
3240     return 1;
3241     }
3242     }
3243     }
3244     if (x != NULL && y != NULL)
3245     *x=EXIT_X(tmp), *y=EXIT_Y(tmp);
3246     return 1;
3247     }
3248     }
3249     }
3250     /* If we got here, did not find a battleground */
3251     return 0;
3252     }
3253    
3254     /*
3255     * When a dragon-player gains a new stage of evolution,
3256     * he gets some treasure
3257     *
3258     * attributes:
3259     * object *who the dragon player
3260     * int atnr the attack-number of the ability focus
3261     * int level ability level
3262     */
3263     void dragon_ability_gain(object *who, int atnr, int level) {
3264     treasurelist *trlist = NULL; /* treasurelist */
3265     treasure *tr; /* treasure */
3266     object *tmp,*skop; /* tmp. object */
3267     object *item; /* treasure object */
3268     char buf[MAX_BUF]; /* tmp. string buffer */
3269     int i=0, j=0;
3270    
3271     /* get the appropriate treasurelist */
3272     if (atnr == ATNR_FIRE)
3273     trlist = find_treasurelist("dragon_ability_fire");
3274     else if (atnr == ATNR_COLD)
3275     trlist = find_treasurelist("dragon_ability_cold");
3276     else if (atnr == ATNR_ELECTRICITY)
3277     trlist = find_treasurelist("dragon_ability_elec");
3278     else if (atnr == ATNR_POISON)
3279     trlist = find_treasurelist("dragon_ability_poison");
3280    
3281     if (trlist == NULL || who->type != PLAYER)
3282     return;
3283    
3284     for (i=0, tr = trlist->items; tr != NULL && i<level-1;
3285     tr = tr->next, i++);
3286    
3287     if (tr == NULL || tr->item == NULL) {
3288     /* LOG(llevDebug, "-> no more treasure for %s\n", change_resist_msg[atnr]); */
3289     return;
3290     }
3291    
3292     /* everything seems okay - now bring on the gift: */
3293     item = &(tr->item->clone);
3294    
3295     if (item->type == SPELL) {
3296     if (check_spell_known (who, item->name))
3297     return;
3298    
3299     new_draw_info_format(NDI_UNIQUE|NDI_BLUE, 0, who, "You gained the ability of %s", item->name);
3300     do_learn_spell (who, item, 0);
3301     return;
3302     }
3303    
3304     /* grant direct spell */
3305     if (item->type == SPELLBOOK) {
3306     if (!item->inv) {
3307     LOG(llevDebug,"dragon_ability_gain: Broken spellbook %s\n",
3308     item->name);
3309     return;
3310     }
3311     if (check_spell_known (who, item->inv->name))
3312     return;
3313     if (item->invisible) {
3314     new_draw_info_format(NDI_UNIQUE|NDI_BLUE, 0, who, "You gained the ability of %s", item->inv->name);
3315     do_learn_spell (who, item->inv, 0);
3316     return;
3317     }
3318     }
3319     else if (item->type == SKILL_TOOL && item->invisible) {
3320     if (item->subtype == SK_CLAWING && (skop=find_skill_by_name(who, item->skill))!=NULL) {
3321    
3322     /* should this perhaps be (skop->attackyp & item->attacktype)!=item->attacktype ...
3323     * in this way, if the player is missing any of the attacktypes, he gets
3324     * them. As it is now, if the player has any that match the granted skill,
3325     * but not all of them, he gets nothing.
3326     */
3327     if (!(skop->attacktype & item->attacktype)) {
3328     /* Give new attacktype */
3329     skop->attacktype |= item->attacktype;
3330    
3331     /* always add physical if there's none */
3332     skop->attacktype |= AT_PHYSICAL;
3333    
3334     if (item->msg != NULL)
3335     new_draw_info(NDI_UNIQUE|NDI_BLUE, 0, who, item->msg);
3336    
3337     /* Give player new face */
3338     if (item->animation_id) {
3339     who->face = skop->face;
3340     who->animation_id = item->animation_id;
3341     who->anim_speed = item->anim_speed;
3342     who->last_anim = 0;
3343     who->state = 0;
3344     animate_object(who, who->direction);
3345     }
3346     }
3347     }
3348     }
3349     else if (item->type == FORCE) {
3350     /* forces in the treasurelist can alter the player's stats */
3351     object *skin;
3352     /* first get the dragon skin force */
3353     for (skin=who->inv; skin!=NULL && strcmp(skin->arch->name, "dragon_skin_force")!=0;
3354     skin=skin->below);
3355     if (skin == NULL) return;
3356    
3357     /* adding new spellpath attunements */
3358     if (item->path_attuned > 0 && !(skin->path_attuned & item->path_attuned)) {
3359     skin->path_attuned |= item->path_attuned; /* add attunement to skin */
3360    
3361     /* print message */
3362     sprintf(buf, "You feel attuned to ");
3363     for(i=0, j=0; i<NRSPELLPATHS; i++) {
3364     if(item->path_attuned & (1<<i)) {
3365     if (j)
3366     strcat(buf," and ");
3367     else
3368     j = 1;
3369     strcat(buf, spellpathnames[i]);
3370     }
3371     }
3372     strcat(buf,".");
3373     new_draw_info(NDI_UNIQUE|NDI_BLUE, 0, who, buf);
3374     }
3375    
3376     /* evtl. adding flags: */
3377     if(QUERY_FLAG(item, FLAG_XRAYS))
3378     SET_FLAG(skin, FLAG_XRAYS);
3379     if(QUERY_FLAG(item, FLAG_STEALTH))
3380     SET_FLAG(skin, FLAG_STEALTH);
3381     if(QUERY_FLAG(item, FLAG_SEE_IN_DARK))
3382     SET_FLAG(skin, FLAG_SEE_IN_DARK);
3383    
3384     /* print message if there is one */
3385     if (item->msg != NULL)
3386     new_draw_info(NDI_UNIQUE|NDI_BLUE, 0, who, item->msg);
3387     }
3388     else {
3389     /* generate misc. treasure */
3390     tmp = arch_to_object (tr->item);
3391     new_draw_info_format(NDI_UNIQUE|NDI_BLUE, 0, who, "You gained %s", query_short_name(tmp));
3392     tmp = insert_ob_in_ob (tmp, who);
3393     if (who->type == PLAYER)
3394     esrv_send_item(who, tmp);
3395     }
3396     }
3397    
3398     /**
3399     * Unready an object for a player. This function does nothing if the object was
3400     * not readied.
3401     */
3402     void player_unready_range_ob(player *pl, object *ob) {
3403     rangetype i;
3404    
3405     for (i = 0; i < range_size; i++) {
3406     if (pl->ranges[i] == ob) {
3407     pl->ranges[i] = NULL;
3408     if (pl->shoottype == i) {
3409     pl->shoottype = range_none;
3410     }
3411     }
3412     }
3413     }