ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/server/player.c
Revision: 1.6
Committed: Wed Feb 22 18:53:56 2006 UTC (18 years, 3 months ago) by elmex
Content type: text/plain
Branch: MAIN
Changes since 1.5: +47 -16 lines
Log Message:
UPSTREAM_2006-02-22 merge

File Contents

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