ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/server/player.c
Revision: 1.1.1.3 (vendor branch)
Committed: Wed Mar 15 14:05:37 2006 UTC (18 years, 3 months ago) by elmex
Content type: text/plain
Branch: UPSTREAM
CVS Tags: UPSTREAM_2006_03_15
Changes since 1.1.1.2: +2 -1 lines
Log Message:
cvs -z9 -d:ext:elmex@cvs.schmorp.de:/schmorpforge import cf.schmorp.de UPSTREAM UPSTREAM_2006_03_15

File Contents

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