Ejemplo n.º 1
0
void cmd_load(char *s)
{
    FILE *in;
    move m;
    char *filename;

    filename = (s[1] == 0) ? "bce.saved" : ++s;

    in = fopen(filename, "r");

    if (!in)
    {
	printf("error opening saved game: %s\n", filename);
	return;
    }

    initialize();

    computer[0] = 0;
    computer[1] = 0;
    
    while(!feof(in))
    {
	fscanf(in, "%u", &m);
	if (feof(in)) break;
	domove(m);
/*  	printf("Move: %s\n", movestring(m)); */
    }
    
    printf("- Board Loaded -\n");
    printboard();
    countmaterial();
    
    fclose(in);
}
Ejemplo n.º 2
0
Archivo: play.c Proyecto: BR903/cgames
/* Redo the last undone move.
 */
int redomove(void)
{
    if (!state.redo.count)
	return FALSE;
    domove(state.redo.list[--state.redo.count]);
    return TRUE;
}
Ejemplo n.º 3
0
void
nextglenda(void)
{
	int min =1000, next, dir, nextdir = 0, count = 0;
	Point p = findglenda();

	calc();
	calc();
	calc();

	grid[p.x][p.y] = 1000;
	
	for(dir = NE; dir <= NW; dir++) {
		next = checknext(dir, p.x, p.y);
		if(next < min) {
			min = next;
			nextdir = dir;
			++count;
		} else if(next == min) {
			nextdir = (nrand(++count) == 0)?dir:nextdir;
		}
	}
	if(min < 100)
		domove(nextdir, p.x, p.y);
	else
		finished = Won;

	if(eqpt(findglenda(), Pt(-1, -1)))
		finished = Lost;
}
Ejemplo n.º 4
0
Archivo: play.c Proyecto: BR903/cgames
/* Check a move for validity in the current state. If it is valid, it
 * is applied via domove(), otherwise return FALSE. If the move is
 * equivalent to an undo or a redo, then use that instead; otherwise,
 * the redo list is reset.
 */
int newmove(yx delta)
{
    dyx	move;
    int	b;
    yx	j;

    j = state.player + delta;
    if (state.map[j] & WALL)
	return FALSE;
    if (state.undo.count) {
	move = state.undo.list[state.undo.count - 1];
	if (!move.box && move.yx == -delta)
	    return undomove();
    }

    b = state.map[j] & BOX ? TRUE : FALSE;
    if (b && state.map[j + delta] & (BOX | WALL))
	return FALSE;
    if (state.redo.count) {
	move = state.redo.list[state.redo.count - 1];
	if (move.box == b && move.yx == delta)
	    return redomove();
    }

    move.yx = delta;
    move.box = b;
    domove(move);
    state.redo.count = 0;
    return TRUE;
}
Ejemplo n.º 5
0
int main() {

    char board[3][3];
    int i,j, result;
    int turn = 0; // Set the current turn to player X

    init(board);
  
    // Play until the game is over.
    while (status(board) == UNFINISHED) {

        // Execute a turn and change who's move it is.
        domove(board, getplayer(turn));
        turn = (turn+1)%2;
    }

    result = status(board);
  
    printf("\nHere is the final board:\n");
    printboard(board);

    // Output the appropriate message for each possible outcome.
    if (result == WINX)
        printf("Congrats team X, you won!\n");
    else if (result == WINO)
        printf("Congrats team O, you won!\n");
    else
        printf("Good job to both teams, the outcome is a tie!\n");

  system("PAUSE");
  return 0;
}
Ejemplo n.º 6
0
int
ab(int lvl, int mark, int lb, int d)
{
	int di, pos, ans, dir, s;

	s = score(&hist[hno], mark) - lvl;
	if (lvl <= 0)
		return s;
	if (s <= -WINL || s >= WINL)
		return s;

	ans = lb;
	for (di = 0; di < 4; di++) {
		dir = dirs[di];
		for (pos = 0; pos < bsize; pos++) {
			domove(dir, pos, mark);
			s = -ab(lvl-1, OTHER(mark), -d, -ans);
			if (s > ans)
				ans = s;
			undomove();
			if (ans >= d)
				goto end;
		}
	}
end:
	return ans;
}
Ejemplo n.º 7
0
int computermove (void) {
  int move, bestmove, rank, bestrank, c, r, check;
  int saveboard[14];

  for (c=0; c < 14; c++) saveboard[c] = board[c];
  bestrank = -99;
  for (move = 7; move <= 12; move++)
    if (board[move]) {
      rank = 0;
      domove(move, 13);
      for (c = 0; c < 5; c++)
        if (board[c]) {
          r = 0; check = board[c] + c;
          while (check > 14) { check -= 14; r = -1;}
          if ((!board[check]) && (check !=6) && (check != 13))
          r-=board[12 - check]; rank =(r < rank) ?  r : rank;
        }
      rank += board[13] - board[6];
      if (turn < 9) {
        check = memory[memory[0]] * 6 + move - 7;
        for (c = 1; c < memory[0]; c++)
          if (check == (int) ((float) memory[c] / pow (6, (7 - turn))))
            rank -= 2;
      }
      for (c=0; c < 14; c++) board[c] = saveboard[c];
      if (rank >= bestrank) {bestrank = rank; bestmove  = move;}
    }
  remember (bestmove);
  printf("Computer moves %d", (bestmove - 6));
  return (bestmove);
}
Ejemplo n.º 8
0
int main() {
  
    int gameover = 0; // used to check if the game is over or not
  
    char uncovered_board[SIDE][SIDE]; // board that stores the location of all
                                      // the bombs and numbers of adjacent bombs.

    char current_board[SIDE][SIDE]; // stores the current board as it should be
                                    // printed out.

    int totalmoves; // stores the total moves left for the user before they win.

    int i,j;
    int x,y;

    int listbombs[NUMBOMBS][2]; // stores (x,y) coordinates of all bombs.
  
    srand(time(0)); // Seed the random number generator.

    // Initialize the current board.
    for (i=0;i<SIDE;i++) {
        for (j=0;j<SIDE;j++) {
            current_board[i][j] = '_';
            uncovered_board[i][j] = '_';
        }
    }

    // Randomly choose where the bombs will go.
    getbombs(listbombs);
  
    // Place the bombs onto the board.
    for (i=0;i<NUMBOMBS;i++) 
        uncovered_board[listbombs[i][0]][listbombs[i][1]]='*';
  
    totalmoves = SIDE*SIDE - NUMBOMBS;

    // Continue playing until the game ends.
    while (!gameover) {
        
        // Get a move from the user.
        printf("Here is the board : \n");
        printboard(current_board);
        getmove(&x,&y);
        printf("at 7 1 when get move is %c\n", current_board[7][1]);
    
        // Execute that move.
        gameover = domove(current_board,uncovered_board,listbombs,x,y,&totalmoves);

        // Check if they have won.
        if ((!gameover) && (totalmoves==0)) {
            printf("Great! You win!!!\n");
            gameover = 1;
        }
    }
  
    system("PAUSE");
    return 0;
  
}
Ejemplo n.º 9
0
void
computemove(char *dirp, int *posp, int mark)
{
	int pos, di, high, lvl, s, i, j, bdir = 0, bpos = 0;
	int dir;
	struct move *mp, *np, *tmp;
	
	mp = moves;
	for (di = 0; di < 4; di++) {
		dir = dirs[di];
		for (pos = 0; pos < bsize; pos++) {
			mp->dir = dir;
			mp->pos = pos;
			mp++;
		}
	}

	mp = moves; np = nmoves;
	for (lvl = 3; lvl < MAXLVL; lvl++) {
		high = -INF;
		for (i = 0; i < bsize4; i++) {
			domove(mp[i].dir, mp[i].pos, mark);
			s = -ab(lvl, OTHER(mark), -INF, -high);
			if (s > high) {
				high = s;
				bdir = mp[i].dir;
				bpos = mp[i].pos;
				if (WINNER(high)) {
					goto done;
				}
			}
			undomove();

			/* sort the move into np */
			for (j = i; j > 0; j--) {
				if (np[j-1].score >= s)
					break;
				np[j] = np[j-1];
			}
			np[j].dir = mp[i].dir;
			np[j].pos = mp[i].pos;
			np[j].score = s;

		}
		*dirp = bdir;
		*posp = bpos;

		DPRINTF(("lvl=%d nscore=%d, high=%d\n", lvl, nscore, high));
		nscore = 0;
		tmp = mp;
		mp = np;
		np = tmp;
	}
done:
	*dirp = bdir;
	*posp = bpos;
	DPRINTF(("high=%d\n", high));
}
Ejemplo n.º 10
0
void go_northwest(void) {
   string usermsg, othermsg;

   usermsg = "You trust in your faith and step out onto the near invisible " +
      "bridge."; 
   $othermsg = this_player()->query_Name() + walks across a faintly " +
      "glowing bridge.";
   XXX domove(DIR + "/rooms/south/sshore26.c",usermsg, othermsg);
}
Ejemplo n.º 11
0
void playgame (void) {
  int c, numpl;

  for (c = 0; c < 13; c++) board[c] = 3;
  board[6] = board [13] = memory[memory[0]] = numpl = 0;
  do {
    printf ("\nHow many players (1 - 2) ? ");
    scanf ("%d", &numpl);
    if (numpl < 1 || numpl > 2) {
      printf ("Please input either 1 or 2.\n");
      numpl = 0;
    }
  } while (!numpl);
  turn = 0;
  do {
    drawboard ();
    if (domove (playermove (0), 6))
      if (!endgame()) {
        drawboard ();
        printf ("Again.\n");
        domove (playermove (0), 6);
      }
    drawboard ();
    if  (!endgame ()) {
      if (domove ((numpl - 1) ? playermove (1) : computermove (), 13))
        if (!endgame()) {
          drawboard ();
          printf ("Again.\n");
          domove ((numpl - 1) ? playermove (1) : computermove (), 13);
        }
      printf("\n");
    }
  } while (!endgame ());
  drawboard ();
  printf ("\nGame Over.\n");
  c = board[6]-board[13];
  if (c < 0) printf ("%s by %d points.\n",
    (numpl - 1) ? "Player 2 wins" : "I win", (-c));
  else {
    if (!(numpl - 1) && memory[0] < 50) memory[0]++;
    if (c == 0) printf ("Drawn game.\n");
    else printf ("Player 1 wins by %d points.\n", c);
  }
}
Ejemplo n.º 12
0
// Pre-conditions: Both character arrays are squre 2D arrays with each
//                 dimension of size SIZE, the first dimension of the 
//                 list of bombs array should be of size NUMBOMBS,
//                 row and column must represent the row and column of
//                 the player's move, and totalmoves must equal how many
//                 more squares the user must uncover before winning.
// Post-conditions: The procedure will execute a single move in the game
//                  and make the necessary changes to the auxiliary
//                  data structures to ensure the game runs properly following
//                  the move.
int domove(char board[][SIDE], char realboard[][SIDE],
            int listbombs[][2], int row, int column, int *totalmoves) {


    int i, j, num;
  
    // Take care of the case that the user loses.
    if (realboard[row][column]=='*') {
    
        board[row][column]='*';
        for (i=0;i<NUMBOMBS;i++) 
            board[listbombs[i][0]][listbombs[i][1]]='*';
    
        printboard(board);
        printf("Sorry, you lose!\n");
        return 1;
    }
    
    // Take care of the case that the user chooses a square already chosen.
    else if (board[row][column]!='_') {
    
        printf("That square as already been cleared, try again!\n");
        return 0;
    }
  
    // Execute a normal non-losing move.
    else {
 
        // Calculate the number of adjacent bombs, and place this number on
        // the regular board.
        num = numberbombs(row, column, listbombs);
        (*totalmoves)--;
        
        // Cast is to make sure we store a character in the array.
        board[row][column]=(char)(num+'0');

        // If there are no adjacent bombs, we can recursively clear.
        if (num == 0) {
                
            // Loop through all adjacent indexes to the current square.    
            for (i=-1;i<2;i++) {
	            for (j=-1;j<2;j++) {
	  
	                // We only want to clear this new square IF it hasn't
	                // previously been cleared, so check that first.
	                if (valid(row+i,column+j) && (board[row+i][column+j]=='_'))
	                    domove(board, realboard, listbombs, row+i, column+j, totalmoves);
	            }
            }
	      
        } // end-if num==0

        return 0;
        
    } // end else
}
Ejemplo n.º 13
0
void showmoves(c)
{
    move_and_score *restore_sp = move_sp;
    
    genmoves(c);
    
    while (move_sp>restore_sp)
    {
	move m;
	m = popmove();
	domove(m);
	printboard();
	undomove();
    }
}
Ejemplo n.º 14
0
void automovedown(void) {
  if (shape_buf != SHPBUF_EMPTY) {
    if (trycreateshape() == 0) {
      createshape();
    } else {
      gameover();
      g_movbuf.shape = -1;
      g_ghost.shape = -1;
    }
    return;
  }

  if (trymove(MOVE_DOWN) == 0) {
    domove(MOVE_DOWN);
  } else {
    steadyall();
  }
}
Ejemplo n.º 15
0
Archivo: play.c Proyecto: BR903/cgames
/* Print to stdout a series of images of the map as the moves of a
 * user's solution are applied.
 */
int displaygamesolution(void)
{
    dyx		lastmove = { 0 };
    dyx	       *move;
    int		i;

    if (!state.redo.count)
	return FALSE;
    move = state.redo.list + state.redo.count;
    for (i = 0 ; i < state.redo.count ; ++i) {
	--move;
	if (move->yx != lastmove.yx || move->box != lastmove.box) {
	    lastmove = *move;
	    outputmapstate();
	}
	domove(*move);
    }
    outputmapstate();
    return TRUE;
}
Ejemplo n.º 16
0
Archivo: play.c Proyecto: BR903/cgames
/* Print to stdout a series of images of the map as the moves of a
 * user's solution are applied.
 */
int displaygamesolution(void)
{
    action     *move;
    int		lastid = -1;
    int		i;

    if (!state.redo.count)
	return FALSE;
    move = state.redo.list + state.redo.count;
    for (i = 0 ; i < state.redo.count ; ++i) {
	--move;
	if (move->id != lastid) {
	    lastid = move->id;
	    outputmapstate();
	}
	domove(*move);
    }
    outputmapstate();
    return TRUE;
}
Ejemplo n.º 17
0
Archivo: play.c Proyecto: BR903/cgames
/* Check a move for validity in the current state. If it is valid, it
 * is applied via domove(), otherwise return FALSE. If the move is
 * equivalent to an undo or a redo, then use that instead; otherwise,
 * the redo list is reset.
 */
int newmove(int dir)
{
    action	move;

    if (!state.currblock || !canmove(state.currblock, dir))
	return FALSE;
    if (state.undo.count) {
	move = state.undo.list[state.undo.count - 1];
	if (move.id == state.currblock && move.dir == backwards(dir)
				       && !move.door)
	    return undomove();
    }
    if (state.redo.count) {
	move = state.redo.list[state.redo.count - 1];
	if (move.id == state.currblock && move.dir == dir)
	    return redomove();
    }
    domove(makeaction(state.currblock, dir));
    state.redo.count = 0;
    return TRUE;
}
Ejemplo n.º 18
0
int
main(int argc, char **argv)
{
	int i, mark, pos, delay;
	char dir;

	hmax = 50;
	hist = malloc(hmax * sizeof(struct config));
	memset(&hist[0], 0, sizeof (struct config));

	for (i = 1; i <= bsize; i++)
		sumsize += AMP(i);

	if (argc == 1)
		delay = 28;
	else
		delay = atoi(argv[1]);
	DPRINTF(("delay=%d\n", delay));

#if 0
	scanf("%d\n", &mark);
	if (mark != bsize) exit(1);
#endif

	for (mark = X; scanf("%c%d\n", &dir, &pos) == 2; mark = OTHER(mark)) {
		domove(dir, pos-1, mark);
	}

	signal(SIGALRM, timeout);
	alarm(delay);

	computemove(&bestdir, &bestpos, mark);

	DPRINTF(("done\n"));
	timeout();
	exit(0);
}
Ejemplo n.º 19
0
void
moveloop()
{
#ifdef MICRO
	char ch;
	int abort_lev;
#endif
	int moverate = 0;
	boolean didmove = 0;

	/* Note:  these initializers don't do anything except guarantee that
		we're linked properly.
	*/
	decl_init();
	monst_init();
	monstr_init();	/* monster strengths */
	objects_init();

	(void) encumber_msg(); /* in case they auto-picked up something */

	for(;;) {
#ifdef CLIPPING
		cliparound(u.ux, u.uy);
#endif
#if defined(MAC_MPW32) && !defined(MODEL_FAR)
		UnloadAllSegments();  /* Marks non-resident segments as purgeable */
#endif
		get_nh_event();

		didmove = flags.move;
		if(flags.move) {	/* actual time passed */
#ifdef POLYSELF
		    int oldmtimedone;
#endif
		    int wtcap;

		    if (u.utotype) deferred_goto();
		    wtcap = encumber_msg();
#ifdef POLYSELF
		    oldmtimedone = u.mtimedone;
#endif

#ifdef SOUNDS
		    dosounds();
#endif

		    if(moverate <= 0) {
			/* calculate how much time passed. */
			int moveamt = 0;
			if(Fast & ~INTRINSIC) moveamt = 6;
			else if(Fast) moveamt = 8;
			else moveamt = 12;

			switch(wtcap) {
			case UNENCUMBERED: break;
			case SLT_ENCUMBER: moveamt = (moveamt * 4) / 3; break;
			case MOD_ENCUMBER: moveamt *= 2; break;
			case HVY_ENCUMBER: moveamt *= 4; break;
			default: moveamt *= 12; break;
			}
			moverate += moveamt;
			settrack();
		    }

		    if(moverate > 0) {
			movemon();
			/* a monster may have levteleported player -dlc */
			if (u.utotype) deferred_goto();
			if(!rn2(u.uevent.udemigod ? 25 :
				(depth(&u.uz) >
				 depth(&stronghold_level))
				? 50 : 70))
			    (void) makemon((struct permonst *)0, 0, 0);
			++monstermoves;
			remove_cadavers(&fobj);
			remove_cadavers(&invent);
			moverate -= 12;
		    }
		    if(Glib) glibr();
		    nh_timeout();
		    ++moves;
		    if (u.ublesscnt)  u.ublesscnt--;
		    if(flags.time) flags.botl = 1;
		    /* One possible result of prayer is healing.  Whether or
		     * not you get healed depends on your current hit points.
		     * If you are allowed to regenerate during the prayer, the
		     * end-of-prayer calculation messes up on this.
		     */
		    if (u.uinvulnerable)
			;
		    else
#ifdef POLYSELF
		    if (u.mtimedone && u.mh < u.mhmax) {
			if (u.mh < 1) {
			    rehumanize();
			    moverate = 0;
			} else if (Regeneration ||
				 (wtcap < MOD_ENCUMBER && !(moves%20))) {
			    flags.botl = 1;
			    u.mh++;
			}
		    } else
#endif
		    if(u.uhp < u.uhpmax) {
			if(u.ulevel > 9) {
			    int heal;

			    if(HRegeneration ||
			       (!(moves%3) &&
				(wtcap < MOD_ENCUMBER || !flags.mv))) {
				flags.botl = 1;
				if (ACURR(A_CON) <= 12) heal = 1;
				else heal = rnd((int) ACURR(A_CON)-12);
				if (heal > u.ulevel-9) heal = u.ulevel-9;
				u.uhp += heal;
				if(u.uhp > u.uhpmax)
				    u.uhp = u.uhpmax;
			    }
			} else if(HRegeneration ||
				  ((wtcap < MOD_ENCUMBER || !flags.mv) &&
				   (!(moves%((MAXULEV+12)/(u.ulevel+2)+1))))) {
			    flags.botl = 1;
			    u.uhp++;
			}
		    }

		    if (wtcap > MOD_ENCUMBER && flags.mv) {
			if(!(wtcap < EXT_ENCUMBER ? moves%30 : moves%10)) {
			    if(u.uhp > 1) {
				u.uhp--;
			    } else {
				pline("You pass out from exertion!");
				exercise(A_CON, FALSE);
				nomul(-10);
				u.usleep = 1;
			    }
			}
		    }

		    if ((u.uen < u.uenmax) &&
			((wtcap < MOD_ENCUMBER &&
			  (!(moves%((MAXULEV + 1 - u.ulevel) *
				    (pl_character[0] == 'W' ? 3 : 4) / 2))))
			 || Energy_regeneration)) {
			u.uen +=
			    rn1((int)(ACURR(A_WIS) + ACURR(A_INT)) / 10 + 1,1);
			if (u.uen > u.uenmax)  u.uen = u.uenmax;
			flags.botl = 1;
		    }

		    if(!u.uinvulnerable) {
			if(Teleportation && !rn2(85)) {
#ifdef REDO		    /* clear doagain keystrokes */
			    pushch(0);
			    savech(0);
#endif
			    tele();
			}
#ifdef POLYSELF
			if(Polymorph && !rn2(100)) {
			    if (multi >= 0) {
				if (occupation)
				    stop_occupation();
				else
				    nomul(0);
			    }
			    polyself();
			    moverate = 0;
			} else if (u.ulycn >= 0 && !rn2(80 - (20 * night()))) {
			    if (multi >= 0) {
				if (occupation)
				    stop_occupation();
				else
				    nomul(0);
			    }
			    you_were();
			    moverate = 0;
			}
#endif
		    }

		    if(Searching && multi >= 0) (void) dosearch0(1);
		    do_storms();
		    hatch_eggs();
		    burn_lamps();
		    gethungry();
		    exerchk();
		    invault();
		    amulet();
		    if (!rn2(40+(int)(ACURR(A_DEX)*3))) 
			u_wipe_engr(rnd(3));
		    if (u.uevent.udemigod && !u.uinvulnerable) {
			if (u.udg_cnt) u.udg_cnt--;
			if (!u.udg_cnt) {
			    intervene();
			    u.udg_cnt = rn1(200, 50);
			}
		    }
		    restore_attrib();
		    /* underwater and waterlevel vision are done here */
		    if (Is_waterlevel(&u.uz))
			movebubbles();
		    else if (Underwater)
			under_water(0);

#ifdef POLYSELF
		    if ((oldmtimedone && !u.mtimedone) ||
			(!oldmtimedone && u.mtimedone)) moverate = 0;
#endif
		}
		if(multi < 0) {
			if(!++multi){
				pline("%s",nomovemsg ? nomovemsg :
					(const char *)"You can move again.");
				nomovemsg = 0;
				u.usleep = 0;
				if(afternmv) (*afternmv)();
				afternmv = 0;
			}
		}

		find_ac();
		if(!flags.mv || Blind) {
		    /* redo monsters if hallu or wearing a helm of telepathy */
		    if (Hallucination ||
			(HTelepat & (WORN_HELMET|WORN_AMUL|W_ART)))
			see_monsters();

		    /* redo objects if hallucinating */
		    if (Hallucination) see_objects();

		    /* update swallowed display */
		    if (Hallucination && u.uswallow) swallowed(0);

		    if (vision_full_recalc) vision_recalc(0);	/* vision! */
		}
		if(flags.botl || flags.botlx) bot();

		flags.move = 1;

		if(multi >= 0 && occupation) {
#ifdef MICRO
			abort_lev = 0;
			if (kbhit()) {
				if ((ch = Getchar()) == ABORT)
					abort_lev++;
# ifdef REDO
				else
					pushch(ch);
# endif /* REDO */
			}
			if (!abort_lev && (*occupation)() == 0)
#else
			if ((*occupation)() == 0)
#endif
				occupation = 0;
			if(
#ifdef MICRO
			   abort_lev ||
#endif
			   monster_nearby()) {
				stop_occupation();
				reset_eat();
			}
#ifdef MICRO
			if (!(++occtime % 7))
				display_nhwindow(WIN_MAP, FALSE);
#endif
			continue;
		}

		if((u.uhave.amulet || Clairvoyant) && !In_endgame(&u.uz) &&
						!(moves%15) && !rn2(2))
			do_vicinity_map();

		if(u.utrap && u.utraptype == TT_LAVA) {
		    if(!is_lava(u.ux,u.uy))
			u.utrap = 0;
		    else {
			u.utrap -= 1<<8;
			if(u.utrap < 1<<8) {
			    killer_format = KILLED_BY;
			    killer = "molten lava";
			    You("sink below the surface and suffocate.");
			    done(DROWNING); /*whatever*/
			} else if(didmove && !u.umoved) {
			    Norep("You sink deeper into the lava.");
			    u.utrap += rnd(4);
			}
		    }
		}

		u.umoved = FALSE;
		if(!didmove || moverate <= 0) {
		    if(multi > 0) {
			lookaround();
			if(!multi) {	/* lookaround may clear multi */
				flags.move = 0;
				continue;
			}
			if(flags.mv) {
				if(multi < COLNO && !--multi)
					flags.mv = flags.run = 0;
				domove();
			} else {
				--multi;
				rhack(save_cm);
			}
		    } else if(multi == 0) {
#ifdef MAIL
			ckmailstatus();
#endif
			rhack(NULL);
		    }
		}
		if (vision_full_recalc) vision_recalc(0);	/* vision! */
		if(multi && multi%7 == 0)
			display_nhwindow(WIN_MAP, FALSE);
	}
}
Ejemplo n.º 20
0
/* returns -1 for stalemate or winner's color */
int playchess()
{
    int use_pondering = 0;
    
    printboard_and_time();
     
    for (;;)
    {
	long starttime, endtime;
	move m;
	int g;

	g = gameoverp(tomove());

	if (g)
	{
	    switch (g)
	    {
		case END_CHECKMATE:
		    if (tomove() == BLACK)
		    {
			return end(WHITE, "white mates");
		    }
		    else
		    {
			return end(BLACK, "black mates");
		    }
		case END_STALEMATE:
		    return end(-1, "stalemate");
		case NON_MATERIAL:
		    return end(-1, "insufficient material");
		case REP_DRAW:
		    if (!robo_mode)
		    {
			printf("drawable position\n");
		    }
		    if (computer[WHITE]||computer[BLACK])
		    {
			if (robo_mode)
			    tellics("draw\n");
			return end(-1, "draw by repetition of moves");
		    }
		    break;
	    }
	}
    
	starttime = get_ms();
	
	if (computer[tomove()])
	{
	    m = bce();

	    if ((m!=dummymove)&&(validmove(m)==1))
	    {
		printf("move %s\n", movestring(m));
	    }
	    else
	    {
		if (robo_mode)
		{
		    tellics("mailmoves\n");
		    tellics(
			"message madhacker valid? = %d, move = %s, wouldbeincheckp() = %d, wouldbeinfullcheckp() = %d, pv = %s\n",
			validmove(m),
			movestring(m),
			wouldbeincheckp(m),
			wouldbeincheckfullp(m),
			thoughts);
		    tellics("abort\n");
		}
		else
		{
		    printf("BCE returned invalid move: %s\n", movestring(m));
		    printf("valid? = %d\n", validmove(m));

		    fprintf(stdout, "random seed = %ld\n", seed);
		    fprintf(stdout, "hash = %lld\n", board->hash);
		    fprintf(stdout, "draw? = %d g = %d\n",
			    draw_by_rep(), g);
		    computer[1] = computer[0] = 0;
		}
	    }
	    use_pondering = 1;
	}
	else 
	{
	    if ((ponder_mode && computer[opp(tomove())])&&
		use_pondering)
	    {
		ponder();
		use_pondering = 0;
	    }
	    
	    m = usermove();
	    use_pondering = 0;
	}
    
	endtime = get_ms();
	chessclock[tomove()] -= (endtime-starttime);
	chessclock[tomove()] += clockinc;
    
	if (m)
	{
	    domove(m);
	    update_state(m);
	    printboard_and_time();
	}
    }
}
Ejemplo n.º 21
0
int
main(int ac, char *av[])
{
	bool	restore;

	/* Revoke setgid privileges */
	setgid(getgid());

	if (strcmp(av[0], "a.out") == 0) {
		outf = fopen("q", "w");
		setbuf(outf, NULL);
		Debug = TRUE;
	}
	restore = FALSE;
	switch (ac) {
	  case 2:
		rest_f(av[1]);
		restore = TRUE;
	  case 1:
		break;
	  default:
		usage();
		/* NOTREACHED */
	}
	Play = PLAYER;
	initscr();
	delwin(stdscr);
	stdscr = Board = newwin(BOARD_Y, BOARD_X, 0, 0);
	Score = newwin(SCORE_Y, SCORE_X, 0, 40);
	Miles = newwin(MILES_Y, MILES_X, 17, 0);
#ifdef attron
	idlok(Board, TRUE);
	idlok(Score, TRUE);
	idlok(Miles, TRUE);
#endif
	leaveok(Score, TRUE);
	leaveok(Miles, TRUE);
	clearok(curscr, TRUE);
	srandomdev();
	cbreak();
	noecho();
	signal(SIGINT, rub);
	for (;;) {
		if (!restore || (Player[PLAYER].total >= 5000
		    || Player[COMP].total >= 5000)) {
			if (Player[COMP].total < Player[PLAYER].total)
				Player[PLAYER].games++;
			else if (Player[COMP].total > Player[PLAYER].total)
				Player[COMP].games++;
			Player[COMP].total = 0;
			Player[PLAYER].total = 0;
		}
		do {
			if (!restore)
				Handstart = Play = other(Handstart);
			if (!restore || On_exit) {
				shuffle();
				init();
			}
			newboard();
			if (restore)
				mvwaddstr(Score, ERR_Y, ERR_X, Initstr);
			prboard();
			do {
				domove();
				if (Finished)
					newscore();
				prboard();
			} while (!Finished);
			check_more();
			restore = On_exit = FALSE;
		} while (Player[COMP].total < 5000
		    && Player[PLAYER].total < 5000);
	}
}
Ejemplo n.º 22
0
short play() {

   short c;
   short ret;
   short undolock = 1;		/* locked for undo */

   showscreen();
   tmpsave();
   ret = 0;
   while( ret == 0) {
      	switch( (c = getch())) {
	 	case 'q':    /* quit the game 					*/
	              ret = E_ENDGAME; 
	              break;
	 	case 's':    /* save the games					*/
		      if( (ret = savegame()) == 0)
			 ret = E_SAVED;
		      break;
	 	case '?':    /* show the help file				*/
		      showhelp();
		      showscreen();
		      break;
	 	case CNTL_R: /* refresh the screen 				*/
		      clear();
		      showscreen();
		      break;
	 	case 'c':    /* temporary save					*/
		      tmpsave();
		      break;
	 	case CNTL_U: /* reset to temporary save 			*/
		      tmpreset();
		      undolock = 1;
		      showscreen();
		      break;
	 	case 'U':    /* undo this level 				*/
		      moves = pushes = 0;
		      if( (ret = readscreen()) == 0) {
		         showscreen();
			 undolock = 1;
		      }
		      break;
	 	case 'u':    /* undo last move 				*/
		      if( ! undolock) {
		         undomove();
		         undolock = 1;
		      }
		      break;
	 	case 'k':    /* up 						*/
	 	case 'K':    /* run up 					*/
	 	case CNTL_K: /* run up, stop before object 			*/
	 	case 'j':    /* down 						*/
	 	case 'J':    /* run down 					*/
	 	case CNTL_J: /* run down, stop before object 			*/
	 	case 'l':    /* right 						*/
	 	case 'L':    /* run right 					*/
	 	case CNTL_L: /* run right, stop before object 			*/
	 	case 'h':    /* left 						*/
	 	case 'H':    /* run left 					*/
	 	case CNTL_H: /* run left, stop before object 			*/
		      do {
		         if( (action = testmove( c)) != 0) {
				    lastaction = action;
		            lastppos.x = ppos.x; lastppos.y = ppos.y;
		            lppc = map[ppos.x][ppos.y];
		            lasttpos1.x = tpos1.x; lasttpos1.y = tpos1.y; 
		            ltp1c = map[tpos1.x][tpos1.y];
		            lasttpos2.x = tpos2.x; lasttpos2.y = tpos2.y; 
		            ltp2c = map[tpos2.x][tpos2.y];
		            domove( lastaction); 
		            undolock = 0;
		         }
		      } while( (action != 0) && (! islower( c))
			      && (packets != savepack));
		      break;
	 	default:     helpmessage(); break;
     }
     if( (ret == 0) && (packets == savepack)) {
		 scorelevel = level;
		 scoremoves = moves;
		 scorepushes = pushes;
		 break;
     }
   }
   return( ret);
}
Ejemplo n.º 23
0
Archivo: learn.c Proyecto: cwbowron/BCE
void save_leaf(move *pv, int n, int value, int hashed)
{
#ifndef LEARNING
    return;
#else
    int s_ply = ply;
    int searched_value = -1;
    int stored_board_value = -1;

    
    if (tomove() != WHITE)
	value = -value;

    stored.search_results[stored.index] = value;

    /* first check our stored position */
    if (stored.boards[stored.index]->piececount[0]>0)
    {
	chessboard *temp_board = board;

	board = stored.boards[stored.index];
	countmaterial();
	
	stored_board_value = eval_for_white();

	board = temp_board;
	countmaterial();

	if (((stored_board_value > (value - EVAL_INTERVAL)) &&
	    (stored_board_value < (value + EVAL_INTERVAL))) ||
	    (value > WIN - 50) ||
	    (value < LOSE + 50))
	{
	    stored.usable[stored.index] = 1;
	    stored.actual[stored.index] = stored_board_value;
	    printf("STORING: qsearch board = %d\n", stored_board_value);
	}
    }

    /* then check to see if our value is the same as our last search */
    if (!stored.usable[stored.index])
    {
	if ((stored.search_results[stored.index] ==
	     stored.search_results[stored.index-1]))
	{
	    memcpy(stored.boards[stored.index], stored.boards[stored.index-1],
		   sizeof(chessboard));
	    stored.usable[stored.index] = 1;
	    stored.actual[stored.index] = stored.actual[stored.index]-1;
	    printf("STORING: previous board = %d\n",
		   stored.search_results[stored.index-1]);
	}
    }

    /* lastly check to see if our pv leads to a correct board eval */
    if (!stored.usable[stored.index])
    {
	int i;
	
	printf("pv: ");
	for (i=0;i<n;i++)
	{
	    if (pv[i] == dummymove)
		break;

	    domove(pv[i]);
	    printf("%s ", movestring(pv[i]));
	}
	printf("\n");
    
	searched_value = eval_for_white();
	
	if ((searched_value > value - EVAL_INTERVAL)&&
	    (searched_value < value + EVAL_INTERVAL))
	{
	    memcpy(stored.boards[stored.index], board, sizeof(chessboard));
	    stored.usable[stored.index] = 1;
	    stored.actual[stored.index] = searched_value;
	    printf("STORING: pv board = %d\n", searched_value);
	}
	else
	{
	    printf("!usable: stored_position %d, "
		   "searched %d, previous %d, stored %d\n",
		   stored_board_value, searched_value,
		   stored.search_results[stored.index-1], value);
	}
	
	while (ply>s_ply)
	    undomove();
    }
    
#endif
    
}
Ejemplo n.º 24
0
int
main (int argc, char **argv)
{
	int     i,l;		/* non-descript indices */
	char    c;		/* non-descript character storage */

	if (pledge("stdio rpath wpath cpath tty exec", NULL) == -1)
		err(1, "pledge");

	signal(SIGINT, getout);	/* trap interrupts */

	/* use whole screen for text */
	begscr = 0;

	getarg(argc, argv);

	initcurses();

	/* check if restored game and save flag for later */
	if ((rfl = rflag)) {
		if (pledge("stdio rpath wpath cpath tty", NULL) == -1)
			err(1, "pledge");

		wrboard();	/* print board */
		/* if new game, pretend to be a non-restored game */
		if (cturn == 0)
			rflag = 0;
	} else {
		rscore = wscore = 0;	/* zero score */

		if (aflag) {	/* print rules */
			addstr(rules);
			if (yorn(0)) {
				endwin();
				execl(TEACH, "teachgammon", (char *)NULL);

				err(1, "%s", noteach);
			} else {/* if not rules, then instructions */
				addstr(need);
				if (yorn(0)) {	/* print instructions */
					clear();
					text(instruct);
				}
			}
		}

		if (pledge("stdio rpath wpath cpath tty", NULL) == -1)
			err(1, "pledge");

		init();		/* initialize board */

		if (pnum == 2) {/* ask for color(s) */
			printw("\n%s", askcol);
			while (pnum == 2) {
				c = readc();
				switch (c) {

				case 'R':	/* red */
					pnum = -1;
					break;

				case 'W':	/* white */
					pnum = 1;
					break;

				case 'B':	/* both */
					pnum = 0;
					break;

				case 'P':	/* Control the dice */
					iroll = 1;
					addstr("\nDice controlled!\n");
					addstr(askcol);
					break;

				default:	/* error */
					beep();
				}
			}
		}

		wrboard();		/* print board */

		move(18, 0);
	}
	/* limit text to bottom of screen */
	begscr = 17;

	for (;;)  {			/* begin game! */
		/* initial roll if needed */
		if ((!rflag) || raflag)
			roll();

		/* perform ritual of first roll */
		if (!rflag) {
			move(17, 0);
			while (D0 == D1)	/* no doubles */
				roll();

			/* print rolls */
			printw("%s%d%s%d", rollr, D0, rollw, D1);

			/* winner goes first */
			if (D0 > D1) {
				addstr(rstart);
				cturn = 1;
			} else {
				addstr(wstart);
				cturn = -1;
			}
		}
		/* initialize variables according to whose turn it is */

		if (cturn == 1) {	/* red */
			home = 25;
			bar = 0;
			inptr = &in[1];
			inopp = &in[0];
			offptr = &off[1];
			offopp = &off[0];
			Colorptr = &color[1];
			colorptr = &color[3];
			colen = 3;
		} else {		/* white */
			home = 0;
			bar = 25;
			inptr = &in[0];
			inopp = &in[1];
			offptr = &off[0];
			offopp = &off[1];
			Colorptr = &color[0];
			colorptr = &color[2];
			colen = 5;
		}

		/* do first move (special case) */
		if (!(rflag && raflag)) {
			if (cturn == pnum)	/* computer's move */
				domove(0);
			else {	/* player's move */
				mvlim = movallow();
				/* reprint roll */
				move(cturn == -1 ? 18 : 19, 0);
				proll();
				getmove();	/* get player's move */
			}
		}
		move(17, 0);
		clrtoeol();
		begscr = 18;
		/* no longer any difference between normal and recovered game. */
		rflag = 0;

		/* move as long as it's someone's turn */
		while (cturn == 1 || cturn == -1) {

			/* board maintainence */
			moveplayers();	/* fix board */

			/* do computer's move */
			if (cturn == pnum) {
				domove(1);

				/* see if double refused */
				if (cturn == -2 || cturn == 2)
					break;

				/* check for winning move */
				if (*offopp == 15) {
					cturn *= -2;
					break;
				}
				continue;

			}
			/* (player's move) */

			/* clean screen if safe */
			if (hflag) {
				move(20, 0);
				clrtobot();
				hflag = 1;
			}
			/* if allowed, give him a chance to double */
			if (dflag && dlast != cturn && gvalue < 64) {
				move(cturn == -1 ? 18: 19, 0);
				addstr(*Colorptr);
				c = readc();

				/* character cases */
				switch (c) {

				case 'R':		/* reprint board */
					wrboard();
					break;

				case 'S':		/* save game */
					raflag = 1;
					save(1);
					break;

				case 'Q':		/* quit */
					quit();
					break;

				case 'D':		/* double */
					dble();
					break;

				case ' ':		/* roll */
				case '\n':
					roll();
					printw(" rolls %d %d.  ", D0, D1);

					/* see if he can move */
					if ((mvlim = movallow()) == 0) {

						/* can't move */
						printw("%s%s%s", toobad1, *colorptr, unable);
						if (pnum) {
							moveplayers();
							sleep(MVPAUSE);
						}
						nexturn();
						break;
					}

					getmove();

					/* okay to clean screen */
					hflag = 1;
					break;

				default:		/* invalid character */

					/* print help message */
					move(20, 0);
					text(helpm);
					move(cturn == -1 ? 18 : 19, 0);

					/* don't erase */
					hflag = 0;
				}
			} else {/* couldn't double */

				/* print roll */
				roll();
				move(cturn == -1 ? 18: 19, 0);
				proll();

				/* can he move? */
				if ((mvlim = movallow()) == 0) {

					/* he can't */
					printw("%s%s%s", toobad2, *colorptr, cantmv);
					moveplayers();
					sleep(MVPAUSE);
					nexturn();
					continue;
				}

				getmove();
			}
		}

		/* don't worry about who won if quit */
		if (cturn == 0)
			break;

		/* fix cturn = winner */
		cturn /= -2;

		/* final board pos. */
		moveplayers();

		/* backgammon? */
		mflag = 0;
		l = bar + 7 * cturn;
		for (i = bar; i != l; i += cturn)
			if (board[i] * cturn)
				mflag++;

		/* compute game value */
		move(20, 0);
		if (*offopp == 15) {
			if (mflag) {
				addstr(bgammon);
				gvalue *= 3;
			}
			else if (*offptr <= 0) {
				addstr(gammon);
				gvalue *= 2;
			}
		}
		/* report situation */
		if (cturn == -1) {
			addstr("Red wins ");
			rscore += gvalue;
		} else {
			addstr("White wins ");
			wscore += gvalue;
		}
		printw("%d point%s.\n", gvalue, (gvalue > 1) ? "s":"");

		/* write score */
		wrscore();

		/* see if he wants another game */
		addstr(again);
		if ((i = yorn('S')) == 0)
			break;

		init();
		if (i == 2) {
			addstr("  Save.\n");
			cturn = 0;
			save(0);
		}
		/* yes, reset game */
		wrboard();
	}

	/* give him a chance to save if game was recovered */
	if (rfl && cturn) {
		addstr(svpromt);
		if (yorn(0)) {
			/* re-initialize for recovery */
			init();
			cturn = 0;
			save(0);
		}
	}
	/* leave peacefully */
	getout(0);
	/* NOT REACHED */
}
Ejemplo n.º 25
0
void
moveloop()
{
#if defined(MICRO) || defined(WIN32)
    char ch;
    int abort_lev;
#endif
    int moveamt = 0, wtcap = 0, change = 0;
    boolean didmove = FALSE, monscanmove = FALSE;

    flags.moonphase = phase_of_the_moon();
    if(flags.moonphase == FULL_MOON) {
	You("are lucky!  Full moon tonight.");
	change_luck(1);
    } else if(flags.moonphase == NEW_MOON) {
	pline("Be careful!  New moon tonight.");
    }
    flags.friday13 = friday_13th();
    if (flags.friday13) {
	pline("Watch out!  Bad things can happen on Friday the 13th.");
	change_luck(-1);
    }

    initrack();


    /* Note:  these initializers don't do anything except guarantee that
	    we're linked properly.
    */
    decl_init();
    monst_init();
    monstr_init();	/* monster strengths */
    objects_init();

    commands_init();

    (void) encumber_msg(); /* in case they auto-picked up something */

    u.uz0.dlevel = u.uz.dlevel;
    youmonst.movement = NORMAL_SPEED;	/* give the hero some movement points */

    for(;;) {
	get_nh_event();
#ifdef POSITIONBAR
	do_positionbar();
#endif

	didmove = flags.move;
	if(didmove) {
	    /* actual time passed */
	    youmonst.movement -= NORMAL_SPEED;

	    do { /* hero can't move this turn loop */
		wtcap = encumber_msg();

		flags.mon_moving = TRUE;
		do {
		    monscanmove = movemon();
		    if (youmonst.movement >= NORMAL_SPEED)
		    {
		        curmonst = &youmonst;
			break;	/* it's now your turn */
		    }
		} while (monscanmove);
		flags.mon_moving = FALSE;

		if (!monscanmove && youmonst.movement < NORMAL_SPEED) {
		    /* both you and the monsters are out of steam this round */
		    /* set up for a new turn */
		    struct monst *mtmp;
		    mcalcdistress();	/* adjust monsters' trap, blind, etc */

		    /* reallocate movement rations to monsters */
		    for (mtmp = fmon; mtmp; mtmp = mtmp->nmon)
			mtmp->movement += mcalcmove(mtmp);

		    if(!rn2(u.uevent.udemigod ? 25 :
			    (depth(&u.uz) > depth(&stronghold_level)) ? 50 : 70))
			(void) makemon((struct permonst *)0, 0, 0, NO_MM_FLAGS);

		    /* calculate how much time passed. */
#ifdef STEED
		    if (u.usteed && u.umoved) {
			/* your speed doesn't augment steed's speed */
			moveamt = mcalcmove(u.usteed);
		    } else
#endif
		    {
			moveamt = youmonst.data->mmove;

			if (Very_fast) {	/* speed boots or potion */
			    /* average movement is 1.67 times normal */
			    moveamt += NORMAL_SPEED / 2;
			    if (rn2(3) == 0) moveamt += NORMAL_SPEED / 2;
			} else if (Fast) {
			    /* average movement is 1.33 times normal */
			    if (rn2(3) != 0) moveamt += NORMAL_SPEED / 2;
			}
		    }

		    switch (wtcap) {
			case UNENCUMBERED: break;
			case SLT_ENCUMBER: moveamt -= (moveamt / 4); break;
			case MOD_ENCUMBER: moveamt -= (moveamt / 2); break;
			case HVY_ENCUMBER: moveamt -= ((moveamt * 3) / 4); break;
			case EXT_ENCUMBER: moveamt -= ((moveamt * 7) / 8); break;
			default: break;
		    }

		    youmonst.movement += moveamt;
		    if (youmonst.movement < 0) youmonst.movement = 0;
		    settrack();

		    monstermoves++;
		    moves++;

		    /********************************/
		    /* once-per-turn things go here */
		    /********************************/

		    if (flags.bypasses) clear_bypasses();
		    if(Glib) glibr();
		    nh_timeout();
		    run_regions();

		    if (u.ublesscnt)  u.ublesscnt--;
		    if(flags.time && !flags.run)
			flags.botl = 1;

		    /* One possible result of prayer is healing.  Whether or
		     * not you get healed depends on your current hit points.
		     * If you are allowed to regenerate during the prayer, the
		     * end-of-prayer calculation messes up on this.
		     * Another possible result is rehumanization, which requires
		     * that encumbrance and movement rate be recalculated.
		     */
		    if (u.uinvulnerable) {
			/* for the moment at least, you're in tiptop shape */
			wtcap = UNENCUMBERED;
		    } else if (Upolyd && youmonst.data->mlet == S_EEL &&
		               !is_pool(u.ux,u.uy) && !Is_waterlevel(&u.uz) &&
			       !(u.uswallow &&
			         u.ustuck->data == &mons[PM_WATER_ELEMENTAL])) {
			if (u.mh > 1) {
			    u.mh--;
			    flags.botl = 1;
			} else if (u.mh < 1)
			    killer_format = KILLED_BY_AN,
			    rehumanize("inability to breathe air");
		    } else if (Upolyd && u.mh < u.mhmax) {
			if (u.mh < 1)
			    rehumanize(0);
			else if (Regeneration ||
				    (wtcap < MOD_ENCUMBER && !(moves%20))) {
			    flags.botl = 1;
			    u.mh++;
			}
		    } else if (u.uhp < u.uhpmax &&
			 (wtcap < MOD_ENCUMBER || !u.umoved || Regeneration)) {
			if (u.ulevel > 9 && !(moves % 3)) {
			    int heal, Con = (int) ACURR(A_CON);

			    if (Con <= 12) {
				heal = 1;
			    } else {
				heal = rnd(Con);
				if (heal > u.ulevel-9) heal = u.ulevel-9;
			    }
			    flags.botl = 1;
			    u.uhp += heal;
			    if(u.uhp > u.uhpmax)
				u.uhp = u.uhpmax;
			} else if (Regeneration ||
			     (u.ulevel <= 9 &&
			      !(moves % ((MAXULEV+12) / (u.ulevel+2) + 1)))) {
			    flags.botl = 1;
			    u.uhp++;
			}
		    }

		    /* moving around while encumbered is hard work */
		    if (wtcap > MOD_ENCUMBER && u.umoved) {
			if(!(wtcap < EXT_ENCUMBER ? moves%30 : moves%10)) {
			    if (Upolyd && u.mh > 1) {
				u.mh--;
			    } else if (!Upolyd && u.uhp > 1) {
				u.uhp--;
			    } else {
				You("pass out from exertion!");
				exercise(A_CON, FALSE);
				fall_asleep(-10, FALSE);
			    }
			}
		    }

		    if ((u.uen < u.uenmax) &&
			((wtcap < MOD_ENCUMBER &&
			  (!(moves%((MAXULEV + 8 - u.ulevel) *
				    (Role_if(PM_WIZARD) ? 3 : 4) / 6))))
			 || Energy_regeneration)) {
			u.uen += rn1((int)(ACURR(A_WIS) + ACURR(A_INT)) / 15 + 1,1);
			if (u.uen > u.uenmax)  u.uen = u.uenmax;
			flags.botl = 1;
		    }

		    if(!u.uinvulnerable) {
			if(Teleportation && !rn2(85)) {
			    xchar old_ux = u.ux, old_uy = u.uy;
			    tele();
			    if (u.ux != old_ux || u.uy != old_uy) {
				if (!next_to_u()) {
				    check_leash(old_ux, old_uy);
				}
#ifdef REDO
				/* clear doagain keystrokes */
				pushch(0);
				savech(0);
#endif
			    }
			}
			/* delayed change may not be valid anymore */
			if ((change == 1 && !Polymorph) ||
			    (change == 2 && u.ulycn == NON_PM))
			    change = 0;
			if(Polymorph && !rn2(100))
			    change = 1;
			else if (u.ulycn >= LOW_PM && !Upolyd &&
				 !rn2(80 - (20 * night())))
			    change = 2;
			if (change && !Unchanging) {
			    if (multi >= 0) {
				if (occupation)
				    stop_occupation();
				else
				    nomul(0);
				if (change == 1) polyself(FALSE);
				else you_were();
				change = 0;
			    }
			}
	
			if(u.utrap && u.utraptype == TT_LAVA) {
			    if(!is_lava(u.ux,u.uy))
				u.utrap = 0;
			    else if (!u.uinvulnerable) {
				u.utrap -= 1<<8;
				if(u.utrap < 1<<8) {
				    killer_format = KILLED_BY;
				    killer = "molten lava";
				    You("sink below the surface and die.");
				    done(DISSOLVED);
				} else if(didmove && !u.umoved) {
				    Norep("You sink deeper into the lava.");
				    u.utrap += rnd(4);
				}
			    }
			}
		    }

		    if(Searching && multi >= 0) (void) dosearch0(1);
		    dosounds();
		    /* hack - make sure damage from storms is not blamed
		       on the player */
		    flags.mon_moving = TRUE;
		    do_storms();
		    flags.mon_moving = FALSE;
		    gethungry();
		    age_spells();
		    exerchk();
		    invault();
		    if (u.uhave.amulet) amulet();
		    if (!rn2(40+(int)(ACURR(A_DEX)*3)))
			u_wipe_engr(rnd(3));
		    if (u.uevent.udemigod && !u.uinvulnerable) {
			if (u.udg_cnt) u.udg_cnt--;
			if (!u.udg_cnt) {
			    intervene();
			    u.udg_cnt = rn1(200, 50);
			}
		    }
		    restore_attrib();
		    /* underwater and waterlevel vision are done here */
		    if (Is_waterlevel(&u.uz))
			movebubbles();
		    else if (Underwater)
			under_water(0);
		    /* vision while buried done here */
		    else if (u.uburied) under_ground(0);

		    /* when immobile, count is in turns */
		    if(multi < 0) {
			if (++multi == 0) {	/* finished yet? */
			    unmul((char *)0);
			    /* if unmul caused a level change, take it now */
			    if (u.utotype) deferred_goto();
			}
		    }
		}
	    } while (youmonst.movement<NORMAL_SPEED); /* hero can't move loop */

	    /******************************************/
	    /* once-per-hero-took-time things go here */
	    /******************************************/
            curmonst = &youmonst;

	} /* actual time passed */

	/****************************************/
	/* once-per-player-input things go here */
	/****************************************/

	find_ac();
	if(!flags.mv || Blind) {
	    /* redo monsters if hallu or wearing a helm of telepathy */
	    if (HHallucination &&
	       !Halluc_resistance) {	/* update screen randomly */
	    /*
		see_monsters();
		see_objects();
		see_traps();
		if (u.uswallow) swallowed(0);
	    */
                if (u.uswallow) {
            	    swallowed(1);
                } else if (Underwater && !Is_waterlevel(&u.uz)) {
            	    under_water(1);
                } else if (u.uburied) {
            	    under_ground(1);
                } else {
		    register int x, y;
		    register struct rm *lev;

                    vision_recalc(2);

                    /*clear_nhwindow(WIN_MAP);*/
                    clear_glyph_buffer();
                
                    for (x = 1; x < COLNO; x++) {
                	lev = &levl[x][0];
                	for (y = 0; y < ROWNO; y++, lev++)
                	    if (lev->glyph != cmap_to_glyph(S_stone))
                		show_glyph(x,y,lev->glyph);
                    }
                
                    vision_recalc(0);
                
                    see_monsters();
    		}
	    } else if (Unblind_telepat) {
		see_monsters();
	    } else if (Warning || Warn_of_mon)
	     	see_monsters();

	    if (vision_full_recalc) vision_recalc(0);	/* vision! */
	}

#ifdef REALTIME_ON_BOTL
        if(iflags.showrealtime) {
            /* Update the bottom line if the number of minutes has
             * changed */
            if(get_realtime() / 60 != realtime_data.last_displayed_time / 60)
                flags.botl = 1;
        }
#endif
  
	if(flags.botl || flags.botlx) bot();

	flags.move = 1;

	if(multi >= 0 && occupation) {
#if defined(MICRO) || defined(WIN32)
	    abort_lev = 0;
	    if (kbhit()) {
		if ((ch = Getchar()) == ABORT)
		    abort_lev++;
# ifdef REDO
		else
		    pushch(ch);
# endif /* REDO */
	    }
	    if (!abort_lev && (*occupation)() == 0)
#else
	    if ((*occupation)() == 0)
#endif
		occupation = 0;
	    if(
#if defined(MICRO) || defined(WIN32)
		   abort_lev ||
#endif
		   monster_nearby()) {
		stop_occupation();
		reset_eat();
	    }
#if defined(MICRO) || defined(WIN32)
	    if (!(++occtime % 7))
		display_nhwindow(WIN_MAP, FALSE);
#endif
	    continue;
	}

	if ((u.uhave.amulet || Clairvoyant) &&
	    !In_endgame(&u.uz) && !BClairvoyant &&
	    !(moves % 15) && !rn2(2))
		do_vicinity_map();


#ifdef WIZARD
	if (iflags.sanity_check)
	    sanity_check();
#endif

#ifdef CLIPPING
	/* just before rhack */
	cliparound(u.ux, u.uy);
#endif

	u.umoved = FALSE;

	if (multi > 0) {
	    lookaround();
	    if (!multi) {
		/* lookaround may clear multi */
		flags.move = 0;
		if (flags.time) flags.botl = 1;
		continue;
	    }
	    if (flags.mv) {
		if(multi < COLNO && !--multi)
		    flags.travel = iflags.travel1 = flags.mv = flags.run = 0;
		domove();
	    } else {
		--multi;
		rhack(save_cm);
	    }
	} else if (multi == 0) {
#ifdef MAIL
	    ckmailstatus();
#endif
	    rhack((char *)0);
	}
	if (u.utotype)		/* change dungeon level */
	    deferred_goto();	/* after rhack() */
	/* !flags.move here: multiple movement command stopped */
	else if (flags.time && (!flags.move || !flags.mv))
	    flags.botl = 1;

	if (vision_full_recalc) vision_recalc(0);	/* vision! */
	/* when running in non-tport mode, this gets done through domove() */
	if ((!flags.run || iflags.runmode == RUN_TPORT) &&
		(multi && (!flags.travel ? !(multi % 7) : !(moves % 7L)))) {
	    if (flags.time && flags.run) flags.botl = 1;
	    display_nhwindow(WIN_MAP, FALSE);
	}
    }
}
Ejemplo n.º 26
0
int play() {

   short c;
   short ret;
   short testmove();
   short undolock = 1;         /* locked for undo */

#if ATARIST			/* Mess up keyboard to make cursor keys work */
KEY_TABLES *kbt;
KEY_TABLES old_kbt;
int i;

	kbt = Keytbl(-1, -1, -1);
	old_kbt = *kbt;

	for (i = 0; i < 128; i++) {
		unshifted[i] = kbt->unshifted[i];
		shifted[i] = kbt->shifted[i];
	}

	unshifted[0x48] = 'k';	/* Up */
	unshifted[0x50] = 'j';	/* Down */
	unshifted[0x4b] = 'h';	/* Left */
	unshifted[0x4d] = 'l';	/* Right */
	unshifted[0x61] = 'u';	/* Undo */
	unshifted[0x62] = '?';	/* Help */

	shifted[0x48] = '\013';	/* Up ^K */
	shifted[0x50] = '\012';	/* Down ^J */
	shifted[0x4b] = '\010';	/* Left ^H */
	shifted[0x4d] = '\014';	/* Right ^L */
	shifted[0x61] = 'q';	/* Undo */

	Keytbl(unshifted, shifted, -1);
#endif

   showscreen();
   tmpsave();
   ret = 0;
   while( ret == 0) {
      switch( (c = get_char())) {
        case 'q':    /* quit the game                                  */
				ret = E_ENDGAME;
				break;
        case 's':    /* save the games                                 */
                     if( (ret = savegame()) == 0)
                        ret = E_SAVED;
                     break;
        case '?':    /* show the help file                             */
                     showhelp();
                     showscreen();
                     break;
        case CNTL_R: /* refresh the screen                             */
                     clear();
                     showscreen();
                     break;
        case 'c':    /* temporary save                                 */
                     tmpsave();
                     break;
        case CNTL_U: /* reset to temporary save                        */
                     tmpreset();
                     undolock = 1;
                     showscreen();
                     break;
        case 'U':    /* undo this level                                */
                     moves = pushes = 0;
                     if( (ret = readscreen()) == 0) {
                        showscreen();
                        undolock = 1;
                     }
                     break;
        case 'u':    /* undo last move                                 */
                     if(state_num > 0) {
                        undomove();
                        undolock = 0;	/*1*/
                     }
                     break;
        case 'k':    /* up                                             */
        case 'K':    /* run up                                         */
        case CNTL_K: /* run up, stop before object                     */
        case 'j':    /* down                                           */
        case 'J':    /* run down                                       */
        case CNTL_J: /* run down, stop before object                   */
        case 'l':    /* right                                          */
        case 'L':    /* run right                                      */
        case CNTL_L: /* run right, stop before object                  */
        case 'h':    /* left                                           */
        case 'H':    /* run left                                       */
        case CNTL_H: /* run left, stop before object                   */
                     do {
                        if( (action = testmove( c)) != 0) {
						soko_state *s;
							s = &state[state_num];

                        	s->action = action;
							s->ppos = ppos;
                        	s->lppc = map[ppos.x][ppos.y];
							s->tpos1 = tpos1;
                        	s->ltp1c = map[tpos1.x][tpos1.y];
							s->tpos2 = tpos2;
                        	s->ltp2c = map[tpos2.x][tpos2.y];
                           domove( s->action);
                           undolock = 0;
						   state_num++;
                        }
                     } while( (action != 0) && (! islower( c))
                             && (packets != savepack));
                     break;
        default:     helpmessage(); break;
      }
      if( (ret == 0) && (packets == savepack)) {
        scorelevel = level;
        scoremoves = moves;
        scorepushes = pushes;
        break;
      }
   }
#if ATARIST
	kbt = Keytbl(-1, -1, -1);
	kbt->unshifted = old_kbt.unshifted;
	kbt->shifted = old_kbt.shifted;
/*	Keytbl(old_kbt.unshifted, old_kbt.shifted, old_kbt.capslock);*/
#endif
	return ret;
}
Ejemplo n.º 27
0
LRESULT CALLBACK EditProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam){

    char bstr[MAX_PATH];
    char *p,c;
    int i,k,n,o,r,f;
    POINT pt;
    struct edvars *ev;

    r = 0;

    //if (domove(GetParent(hwnd),message,wParam,lParam)) return 0;

    switch (message) {
    case WM_COPYDATA:
        if (0x4F4E4242 == ((PCOPYDATASTRUCT)lParam)->dwData)
        {
            char buff[MAX_PATH];
            int line_nr;
            const char *file = (const char*)((PCOPYDATASTRUCT)lParam)->lpData;
            getfile(buff, file, &line_nr);
            set_currentdir(buff);
            LoadFile(buff);
            if (line_nr) {
                ed_cmd(EK_GOTOLINE,line_nr-1);
                //ed_cmd(EK_MARK,lpos,imin(lpos+1,nextline(lpos,1)));
            }

            r = TRUE;
            goto p0r;
        }

        return bbn_receive_data(hwnd, lParam);

    default:
        if (bb_broadcast_msg == message && message)
        {
            if (bb_register(hwnd) && bb_getstyle(hwnd))
               goto reconfig1;
            return 0;
        }
        break;

    case BB_RECONFIGURE:
        if (bb_getstyle(hwnd))
            goto reconfig1;
        return 0;


    reconfig1:
        bb_close_dlg();
        makedlgfont();

    reconfig:
        zy0 = title_h + FRM-1;
        setsize(hwnd);
        new_back();
        InvalidateRect(hwnd, NULL, FALSE);
        return 0;

    case BB_SETSTYLESTRUCT:
    {
        StyleStruct *d = (StyleStruct *)wParam;
        StyleStruct *s = (StyleStruct *)lParam;
        memset(d, 0, sizeof *d);
        memcpy(d, s, sizeof *d);
        break;
    }

    case BB_SETSTYLE:
    {
        char *d = (char *)wParam;
        char *s = (char *)lParam;
        strcpy(d, s);
        break;
    }

    case WM_CREATE:
        zy0 = title_h + FRM-1;
        setsize(ewnd=hwnd);
        dragC  = LoadCursor(hInst,MAKEINTRESOURCE(101));
        dragCp = LoadCursor(hInst,MAKEINTRESOURCE(102));
        pointC = hCurs = LoadCursor(NULL,IDC_ARROW);
        init_edit(hwnd);
        DragAcceptFiles(hwnd,TRUE);
        if (false == bb_register(hwnd) || false == bb_getstyle(hwnd))
            readstyle(defstyle);
        goto reconfig1;


    case WM_DROPFILES: {
        POINT pt;
        HDROP hDrop = (HDROP)wParam; int n,f;
        ev=edp;
        f=0;

        GetCursorPos(&pt);
        if (GetAsyncKeyState(VK_CONTROL)<0) f=1;
        if (GetAsyncKeyState(VK_SHIFT)<0)   f=2;
        if (f) ScreenToClient(hwnd,&pt);

        for (i=-1, k=0; i<k; i++)
        {
            n=DragQueryFile (hDrop, i, p=bstr, 255);
            if (i<0)
            {
                k=n;
            }
            else
            if (f==0)
            {
                LoadFile(p);
            }
            else
            if (f==2)
            {
                if (readstyle(p))
                {
                    CopyFile(p, defstyle, FALSE);
                }
                break;
            }
            else
            {
                if (i == 0 && -1 == getmoupos(pt.x ,pt.y))
                    break;

                ed_cmd(EK_SETVAR);
                ed_cmd(EK_INSERT, p);
                ed_cmd(KEY_RET);
            }
        }
        DragFinish(hDrop);
        SetForegroundWindow(hwnd);
        if (f==0) goto showf;
        if (f==2) goto reconfig1;
        goto p0;
        }

    case WM_QUERYENDSESSION:
        return (1 == QueryDiscard(hwnd,1));

    case WM_ENDSESSION:
    {
        //void savecfg(void); savecfg();
        return 0;
    }

    case WM_DESTROY:
        exit_edit();
        DragAcceptFiles(hwnd,FALSE);
        bb_unregister(hwnd);
        PostQuitMessage(0);
        return 0 ;


    case WM_ACTIVATE:
        i=LOWORD(wParam);
        if (i==WA_ACTIVE)
            clickflag=0;

        return 0;

    case WM_ACTIVATEAPP:
        if (wParam) {
            clickflag=2;
        }
        return 0;

    case WM_LBUTTONDOWN:
    case WM_RBUTTONDOWN:
        if (alt_f) alt_f=2;

    case WM_MOUSEMOVE:
#if 0
    {
        static int wm;
        i = (short)HIWORD(lParam)/2;
        n = wm;
        wm = i;
        wParam = MAKELPARAM(0,(n-i)*30);
        goto mwhl;

    }
#endif
    case WM_LBUTTONDBLCLK:
    case WM_LBUTTONUP:
    case WM_RBUTTONUP:
    case WM_MBUTTONUP:
    case WM_MBUTTONDOWN:

        if (drag==0 && domove (hwnd, message, wParam, lParam))
            return 0;

        do_mouse(hwnd, wParam, lParam, message);

        if (message==WM_MOUSEMOVE && 0==(wParam & (MK_LBUTTON | MK_RBUTTON)))
            return 0;

        goto p0;

    case WM_TIMER:

        if (wParam==2) {
            resetmsg(hwnd);
            goto p0;
        }

        if (wParam==4) {
            mousewheelaccu=0;
        t0:
            KillTimer(hwnd, wParam);
            return 0;
        }

        GetCursorPos(&pt);
        ScreenToClient(hwnd,&pt);
        o=getmoupos(pt.x ,pt.y);
        if (o!=tcmd) {
            settimer(hwnd, o, SCROLL_INTERVAL);
            return 0;
        }

        if (tcmd==0) goto t0;
        c=ltup; ltup=0;
        ed_cmd(tcmd);
        ed_cmd(tcmd);
        upd=1;
        ltup=c;
        k=GetAsyncKeyState(VK_SHIFT)&0x8000;
        domarking(k!=0 || (0==moumrk && 0==drag));
        goto p0;


    case WM_SIZE:
        if (SIZE_MINIMIZED == wParam)
            return 0;

        if (edp) upd=1;
        ed_cmd(EK_SIZE);
        new_back();

    case WM_MOVE:
        setsize(hwnd);
        goto p0;

/*
   case WM_WINDOWPOSCHANGED:
        ewx0 = ((LPWINDOWPOS) lParam)->x;
        ewy0 = ((LPWINDOWPOS) lParam)->y;
        ewxl = ((LPWINDOWPOS) lParam)->cx;
        ewyl = ((LPWINDOWPOS) lParam)->cy;
        cfg_f |= 1;
        break; //process wm_move/wm_size

    case WM_WINDOWPOSCHANGING:
        SnapWindowToEdge((WINDOWPOS*)lParam, 10, 0);
        setsize(hwnd);
        return 0;
*/

    case WM_VSCROLL:
        vscroll(wParam);
        goto p0;

    case WM_HSCROLL:
        hscroll(wParam);
        goto p0;

    case WM_SETFOCUS:
        k_alt = 0>GetAsyncKeyState(VK_MENU);
        k_shft= 0>GetAsyncKeyState(VK_SHIFT);
        k_ctrl= 0>GetAsyncKeyState(VK_CONTROL);
        CreateCaret(hwnd,NULL,My_CaretSize,zy);
        caret=1;
        checkftime(hwnd);
        goto f1;

    case WM_KILLFOCUS:
        DestroyCaret();
        caret=0;
    f1:
        if (edp) upd=1;
        goto p0;

p0:
        r=0;
p0r:
        set_update(hwnd);
        return r;


    case WM_ERASEBKGND:
        return 1;

    case WM_PAINT:
        paint_window (hwnd);
        return 0;


    case WM_COMMAND:
        switch (LOWORD(wParam)) {

        case CMD_HELP:
#if 0
            bbnote_help();
            return 0;
#else
            if (fileexist(set_my_path(bstr, "bbnote.txt")))
                LoadFile(bstr);
            else if (fileexist(set_my_path(bstr, "docs/bbnote.txt")))
                LoadFile(bstr);
            goto p0;
#endif


        case CMD_EXIT:
            goto quit;

        case CMD_MENU_2:
        filemenu:
            if (ed0)
            {
                struct edvars *e = ed0;
                struct strl   *s = NULL;
                while (e)
                {
                    char temp[MAX_PATH];
                    sprintf(temp, "&%s", fname(e->sfilename));
                    appendstr(&s, temp);
                    e = e->next;
                }
                bb_file_menu (hwnd, lParam, s);
            }
            return 0;

        case CMD_MENU_1:
            bb_menu(hwnd, lParam);
            return 0;

        case CMD_COLOR:
            goto reconfig;

        case CMD_UPD:
            settitle();
            if (edp) upd=1;
            goto p0;


        case CMD_ZOOM:
    zoom:
            ShowWindow(hwnd, IsZoomed(hwnd) ? SW_SHOWNORMAL : SW_MAXIMIZE);
            return 0;

        case CMD_SEARCH:
        search:
            if (edp) bb_search_dialog(hwnd);
            return 0;

        case CMD_CLOSE:
        closefile:
            if (edp)
            {
                if (1 != QueryDiscard_1(hwnd, 1)) goto p0;
                if (ed0->next==NULL)
                {
                    extern HWND mwnd;
                    SendMessage(mwnd, WM_KEYDOWN, VK_ESCAPE, 0);
                    //DestroyWindow(mwnd);
                }
                CloseFile();
            }
            goto p0;

        case CMD_OPEN:
        openfile:
            ev=edp;
            DoFileOpenSave(hwnd, 0);
showf:
            if (ev==NULL || ev->next)
            {
                edp = ev ? ev->next : ed0;
                settitle();
            }
            goto p0;

        case CMD_RELOAD:
        reload:
            if (edp) f_reload(1);
            goto p0;


        case CMD_LIST:
            lParam = 2;
            goto filemenu;

        case CMD_NEW:
        newfile:
            NewFile();
            goto p0;

        case CMD_SAVE:
        savefile:
            if (edp) DoFileOpenSave(hwnd, 2);
            goto p0;

        case CMD_SAVEAS:
            if (edp!=NULL) DoFileOpenSave(hwnd, 1);
            break;

        case CMD_SAVEALL:
        //saveall:
            return QueryDiscard(hwnd, 0);

        case CMD_UNDO:
            ed_cmd(KEY_C_Z);
            goto p0;

        case CMD_REDO:
            ed_cmd(KEY_CS_Z);
            goto p0;

        case CMD_ABOUT:
            oyncan_msgbox(
              VERSION_STRING
              "\n"
              "\nediting with style"
              "\n04/2003 by grischka"
              "\n"
              "\[email protected]"
              , NULL, 1);
              return 0;


        case CMD_OPTIONS:
            goto config;

        case CMD_INFO:
            resetmsg(hwnd);
            p=(char*)lParam;
            if (p[0]==1) p++;
            else infoflg=1,infotimer=SetTimer(hwnd,2,666,NULL);
            strcpy(infomsg,p);
            if (edp) upd=1;
            goto p0;


        case CMD_FILECHG:
        {
            struct edvars *p=edp;
            edp=(struct edvars*)lParam;
            settitle();
            set_update(hwnd);
            f_reload(0);
            edp=p;
            settitle();
            goto p0;
        }

        default:
            i = LOWORD(wParam);
            if (i>=CMD_FILE && i< CMD_FILE_M)
            {
                struct edvars *p=ed0;
                i-=CMD_FILE;
                for (;i && p!=NULL; p=p->next,i--);
                if (p) {
                    //edp = p; settitle();
                    insfile(p);
                    goto p0;
                }
                return 0;
            }
            break;

        }
        break;

quit:
    if (1 == QueryDiscard(hwnd, 1))
        DestroyWindow(hwnd);
    return 0;

    case WM_SYSKEYDOWN:
        f=3; goto k1;

    case WM_SYSKEYUP:
        f=2; goto k1;

    case WM_KEYUP:
        if (wParam==VK_CONTROL && drag==3)  setdragc(2);
        f=0; goto k1;

    case WM_KEYDOWN:
        if (wParam==VK_CONTROL && drag==2)  setdragc(3);
        if (wParam==VK_SCROLL) { scroll_lock^=1; goto p0; }

        f=1; k1:

        n=LOWORD(wParam);

#if 0
        sprintf(bstr,"key %d  stat %d",n,f);
        if (n!=VK_MENU) MessageBox(NULL, bstr, "", MB_OK|MB_TOPMOST|MB_SETFOREGROUND);
#endif
        n=trans_keys(n, f);
        //if (0==n) goto p0;
        if (0==n) return 0;

        if (n>=2110 && n<=2117) {
        vmark=k_alt!=0;
        domarking(1);
        ed_cmd(n-100);
        domarking(1);
        goto p0;
        }

        switch (n) {

        case KEY_F8: return 0;
        case KEY_A_RIGHT:
        case KEY_F6:   nextfile(); goto p0;
        case KEY_A_LEFT:
        case KEY_C_F6: prevfile(); goto p0;

        case KEY_F10:  goto zoom;
        case KEY_F3:
        case KEY_C_F:  goto search;
        case KEY_C_F4: goto closefile;
        case KEY_C_O:  goto openfile;
        //case KEY_A_F3: goto reload;
        case KEY_C_N:  goto newfile;
        case KEY_C_L:  lParam = 0; goto filemenu;

        case KEY_F4:
            QueryDiscard(hwnd, 0);
            bb_reconfig();
            return 0;

        case KEY_S_F4:
            if (IDOK == oyncan_msgbox("Do you want to write all files?", "", 1+8))
                QueryDiscard(hwnd, 4);
            return 0;


        case KEY_C_S:  goto savefile;
        case KEY_A_F4: goto quit;

        case KEY_A_F2:
config:
            n = tabs;
            bb_config_dialog(hwnd);
            if (n!=tabs) goto reload;
            return 0;

        case KEY_ESC:
            if (drag==0) goto quit;
            dragmove=0;
            do_mouse(hwnd, 0,0,WM_LBUTTONUP);
            goto p0;

        case KEY_UP:
        case KEY_DOWN:
            if (scroll_lock) n+=200;
            goto defkey;

        case KEY_LEFT:
        case KEY_RIGHT:
            if (scroll_lock) n=(n^1)+204;
            goto defkey;
        }

    defkey:
        domarking(0);
        ed_cmd(n);
        i=n;
        if (i!=KEY_C_A
         && i!=KEY_C_U
         && i!=KEY_C_7
         && i!=KEY_C_8
         && i!=KEY_C_9
         && i!=KEY_C_0
         && i!=KEY_TAB
         && i!=KEY_S_TAB
         )
            unmark();
        goto p0;


    case WM_MOUSEWHEEL:
        i = mousewheelaccu + mousewheelfac * (short)HIWORD(wParam);
        while (i < -300)
            ed_cmd(KEY_C_DOWN), i+=600;
        while (i >  300)
            ed_cmd(KEY_C_UP),   i-=600;

        mousewheelaccu=i;
        unmark();
        SetTimer(hwnd, 4, 200, NULL);
        goto p0;


    case WM_NCPAINT:
        return 0;


    case WM_CHAR:
        n = LOWORD(wParam);
        if (n<32||n==127) return 0;

        resetmsg(hwnd);
        ed_cmd(EK_CHAR, n);
        goto p0;



    case CMD_GOTOLINE:
        ed_cmd(EK_GOTOLINE,wParam-1);
        ed_cmd(EK_MARK,lpos,imin(lpos+1,nextline(lpos,1)));
        lmf=2;
        goto p0;

    case CMD_LOADFILE:
        r=LoadFile((char*)wParam);
        goto p0r;

    case CMD_NSEARCH:
        resetmsg(hwnd);
        if (wParam&8) {
            ed_cmd(EK_REPLACE,(char *)lParam);
            if (wParam&1)
               ed_cmd(EK_GOTO,fpos+strlen((char*)lParam));
            goto p0;
        }
        unmark();
        if (wParam!=0) {
            struct sea *s=(struct sea *)lParam;
            struct edvars *ev0;

            for (ev0=edp;;) {
                r=ed_search(s);
                if (r || 0==(s->sf&128)) break;
                s->sf &= ~4;
                if (s->sf & 1) {
                    if (edp->next==NULL) break;
                    nextfile();
                    s->from=0;
                    continue;
                }
                if (s->sf & 2) {
                    if (edp==ed0) break;
                    prevfile();
                    s->from=flen;
                    continue;
                }}
            if (r<=0) {
                edp=ev0;
                settitle();
            } else {
               ed_cmd(KEY_HOME);
               ed_cmd(EK_MARK,s->a,s->e);
               ed_cmd(EK_GOTO,s->a);
            }
        }
        goto p0r;

    }
    return DefWindowProc (hwnd, message, wParam, lParam) ;
}
Ejemplo n.º 28
0
int
main(int argc, char *argv[])
{
	int fd;
#ifdef CHDIR
	char *dir;
#endif

	hname = argv[0];
	hackpid = getpid();

#ifdef CHDIR                    /* otherwise no chdir() */
	/*
	 * See if we must change directory to the playground.
	 * (Perhaps hack runs suid and playground is inaccessible
	 *  for the player.)
	 * The environment variable HACKDIR is overridden by a
	 *  -d command line option (must be the first option given)
	 */

	dir = getenv("HACKDIR");
	if (argc > 1 && !strncmp(argv[1], "-d", 2)) {
		argc--;
		argv++;
		dir = argv[0] + 2;
		if (*dir == '=' || *dir == ':')
			dir++;
		if (!*dir && argc > 1) {
			argc--;
			argv++;
			dir = argv[0];
		}
		if (!*dir)
			error("Flag -d must be followed by a directory name.");
	}
#endif

	/*
	 * Who am i? Algorithm: 1. Use name as specified in HACKOPTIONS
	 *			2. Use $USER or $LOGNAME	(if 1. fails)
	 *			3. Use getlogin()		(if 2. fails)
	 * The resulting name is overridden by command line options.
	 * If everything fails, or if the resulting name is some generic
	 * account like "games", "play", "player", "hack" then eventually
	 * we'll ask him.
	 * Note that we trust him here; it is possible to play under
	 * somebody else's name.
	 */
	{
		char *s;

		initoptions();
		if (!*plname && (s = getenv("USER")))
			strncpy(plname, s, sizeof(plname) - 1);
		if (!*plname && (s = getenv("LOGNAME")))
			strncpy(plname, s, sizeof(plname) - 1);
		if (!*plname && (s = getlogin()))
			strncpy(plname, s, sizeof(plname) - 1);
	}

	/*
	 * Now we know the directory containing 'record' and
	 * may do a prscore().
	 */
	if (argc > 1 && !strncmp(argv[1], "-s", 2)) {
#ifdef CHDIR
		chdirx(dir, 0);
#endif
		prscore(argc, argv);
		exit(0);
	}

	/*
	 * It seems he really wants to play.
	 * Remember tty modes, to be restored on exit.
	 */
	gettty();
	setbuf(stdout, obuf);
	umask(007);
	setrandom();
	startup();
	cls();
	u.uhp = 1;		/* prevent RIP on early quits */
	u.ux = FAR;		/* prevent nscr() */
	signal(SIGHUP, hangup);

	/*
	 * Find the creation date of this game,
	 * so as to avoid restoring outdated savefiles.
	 */
	gethdate(hname);

	/*
	 * We cannot do chdir earlier, otherwise gethdate will fail.
	 */
#ifdef CHDIR
	chdirx(dir, 1);
#endif

	/*
	 * Process options.
	 */
	while (argc > 1 && argv[1][0] == '-') {
		argv++;
		argc--;
		switch (argv[0][1]) {
#ifdef WIZARD
		case 'D':
			wizard = TRUE;
			break;
#endif
#ifdef NEWS
		case 'n':
			flags.nonews = TRUE;
			break;
#endif
		case 'u':
			if (argv[0][2])
				strncpy(plname, argv[0] + 2, sizeof(plname) - 1);
			else if (argc > 1) {
				argc--;
				argv++;
				strncpy(plname, argv[0], sizeof(plname) - 1);
			} else
				printf("Player name expected after -u\n");
			break;
		default:
			/* allow -T for Tourist, etc. */
			strncpy(pl_character, argv[0] + 1,
			    sizeof(pl_character) - 1);
		}
	}

	if (argc > 1)
		locknum = atoi(argv[1]);
#ifdef MAX_NR_OF_PLAYERS
	if (!locknum || locknum > MAX_NR_OF_PLAYERS)
		locknum = MAX_NR_OF_PLAYERS;
#endif
#ifdef DEF_PAGER
	if (!(catmore = getenv("HACKPAGER")) && !(catmore = getenv("PAGER")))
		catmore = DEF_PAGER;
#endif
#ifdef MAIL
	getmailstatus();
#endif
#ifdef WIZARD
	if (wizard)
		strcpy(plname, "wizard");
	else
#endif
	if (!*plname || !strncmp(plname, "player", 4)
	    || !strncmp(plname, "games", 4))
		askname();
	plnamesuffix();		/* strip suffix from name; calls askname() */
				/* again if suffix was whole name */
				/* accepts any suffix */
#ifdef WIZARD
	if (!wizard) {
#endif
		/*
		 * check for multiple games under the same name
		 * (if !locknum) or check max nr of players (otherwise)
		 */
		signal(SIGQUIT, SIG_IGN);
		signal(SIGINT, SIG_IGN);
		if (!locknum)
			strcpy(lock, plname);
		getlock();	/* sets lock if locknum != 0 */
#ifdef WIZARD
	} else {
		char *sfoo;
		strcpy(lock, plname);
		if ((sfoo = getenv("MAGIC")))
			while (*sfoo) {
				switch (*sfoo++) {
				case 'n':
					srandom(*sfoo++);
					break;
				}
			}
		if ((sfoo = getenv("GENOCIDED")) != NULL) {
			if (*sfoo == '!') {
				struct permonst *pm = mons;
				char *gp = genocided;

				while (pm < mons + CMNUM + 2) {
					if (!strchr(sfoo, pm->mlet))
						*gp++ = pm->mlet;
					pm++;
				}
				*gp = 0;
			} else
				strncpy(genocided, sfoo, sizeof(genocided) - 1);
			strcpy(fut_geno, genocided);
		}
	}
#endif
	setftty();
	sprintf(SAVEF, "save/%d%s", getuid(), plname);
	regularize(SAVEF + 5);	/* avoid . or / in name */
	if ((fd = open(SAVEF, O_RDONLY)) >= 0 &&
	    (uptodate(fd) || unlink(SAVEF) == 666)) {
		signal(SIGINT, done1);
		pline("Restoring old save file...");
		fflush(stdout);
		if (!dorecover(fd))
			goto not_recovered;
		pline("Hello %s, welcome to %s!", plname, gamename);
		flags.move = 0;
	} else {
not_recovered:
		fobj = fcobj = invent = 0;
		fmon = fallen_down = 0;
		ftrap = 0;
		fgold = 0;
		flags.ident = 1;
		init_objects();
		u_init();

		signal(SIGINT, done1);
		mklev();
		u.ux = xupstair;
		u.uy = yupstair;
		inshop();
		setsee();
		flags.botlx = 1;
		makedog();
		{
			struct monst *mtmp;
			if ((mtmp = m_at(u.ux, u.uy)) != NULL)
				mnexto(mtmp);	/* riv05!a3 */
		}
		seemons();
#ifdef NEWS
		if (flags.nonews || !readnews())
			/* after reading news we did docrt() already */
#endif
			docrt();

		/* give welcome message before pickup messages */
		pline("Hello %s, welcome to %s!", plname, gamename);

		pickup(1);
		read_engr_at(u.ux, u.uy);
		flags.move = 1;
	}

	flags.moonphase = phase_of_the_moon();
	if (flags.moonphase == FULL_MOON) {
		pline("You are lucky! Full moon tonight.");
		u.uluck++;
	} else if (flags.moonphase == NEW_MOON)
		pline("Be careful! New moon tonight.");

	initrack();

	for (;;) {
		if (flags.move) {	/* actual time passed */
			settrack();

			if (moves % 2 == 0 ||
			    (!(Fast & ~INTRINSIC) && (!Fast || rn2(3)))) {
				movemon();
				if (!rn2(70))
					makemon(NULL, 0, 0);
			}
			if (Glib)
				glibr();
			p_timeout();
			++moves;
			if (flags.time)
				flags.botl = 1;
			if (u.uhp < 1) {
				pline("You die...");
				done("died");
			}
			if (u.uhp * 10 < u.uhpmax && moves - wailmsg > 50) {
				wailmsg = moves;
				if (u.uhp == 1)
					pline("You hear the wailing of the Banshee...");
				else
					pline("You hear the howling of the CwnAnnwn...");
			}
			if (u.uhp < u.uhpmax) {
				if (u.ulevel > 9) {
					if (Regeneration || !(moves % 3)) {
						flags.botl = 1;
						u.uhp += rnd((int)u.ulevel - 9);
						if (u.uhp > u.uhpmax)
							u.uhp = u.uhpmax;
					}
				} else if (Regeneration ||
				    (!(moves % (22 - u.ulevel * 2)))) {
					flags.botl = 1;
					u.uhp++;
				}
			}
			if (Teleportation && !rn2(85))
				tele();
			if (Searching && multi >= 0)
				dosearch();
			gethungry();
			invault();
			amulet();
		}
		if (multi < 0) {
			if (!++multi) {
				pline("%s", nomovemsg ? nomovemsg :
				      "You can move again.");
				nomovemsg = 0;
				if (afternmv)
					(*afternmv)();
				afternmv = NULL;
			}
		}
		find_ac();
#ifndef QUEST
		if (!flags.mv || Blind)
#endif
		{
			seeobjs();
			seemons();
			nscr();
		}
		if (flags.botl || flags.botlx)
			bot();

		flags.move = 1;

		if (multi >= 0 && occupation) {
			if (monster_nearby())
				stop_occupation();
			else if ((*occupation)() == 0)
				occupation = NULL;
			continue;
		}

		if (multi > 0) {
#ifdef QUEST
			if (flags.run >= 4)
				finddir();
#endif
			lookaround();
			if (!multi) {	/* lookaround may clear multi */
				flags.move = 0;
				continue;
			}
			if (flags.mv) {
				if (multi < COLNO && !--multi)
					flags.mv = flags.run = 0;
				domove();
			} else {
				--multi;
				rhack(save_cm);
			}
		} else if (multi == 0) {
#ifdef MAIL
			ckmailstatus();
#endif
			rhack(NULL);
		}
		if (multi && multi % 7 == 0)
			fflush(stdout);
	}
}
Ejemplo n.º 29
0
Archivo: files.c Proyecto: AMDmi3/zsh
static int
bin_ln(char *nam, char **args, Options ops, int func)
{
    MoveFunc movefn;
    int flags, have_dir, err = 0;
    char **a, *ptr, *rp, *buf;
    struct stat st;
    size_t blen;


    if(func == BIN_MV) {
	movefn = (MoveFunc) rename;
	flags = OPT_ISSET(ops,'f') ? 0 : MV_ASKNW;
	flags |= MV_ATOMIC;
    } else {
	flags = OPT_ISSET(ops,'f') ? MV_FORCE : 0;
#ifdef HAVE_LSTAT
	if(OPT_ISSET(ops,'h') || OPT_ISSET(ops,'n'))
	    flags |= MV_NOCHASETARGET;
	if(OPT_ISSET(ops,'s'))
	    movefn = (MoveFunc) symlink;
	else
#endif
	{
	    movefn = (MoveFunc) link;
	    if(!OPT_ISSET(ops,'d'))
		flags |= MV_NODIRS;
	}
    }
    if(OPT_ISSET(ops,'i') && !OPT_ISSET(ops,'f'))
	flags |= MV_INTERACTIVE;
    for(a = args; a[1]; a++) ;
    if(a != args) {
	rp = unmeta(*a);
	if(rp && !stat(rp, &st) && S_ISDIR(st.st_mode)) {
	    have_dir = 1;
	    if((flags & MV_NOCHASETARGET)
	      && !lstat(rp, &st) && S_ISLNK(st.st_mode)) {
		/*
		 * So we have "ln -h" with the target being a symlink pointing
		 * to a directory; if there are multiple sources but the target
		 * is a symlink, then it's an error as we're not following
		 * symlinks; if OTOH there's just one source, then we need to
		 * either fail EEXIST or if "-f" given then remove the target.
		 */
		if(a > args+1) {
		    errno = ENOTDIR;
		    zwarnnam(nam, "%s: %e", *a, errno);
		    return 1;
		}
		if(flags & MV_FORCE) {
		    unlink(rp);
		    have_dir = 0;
		} else {
		    errno = EEXIST;
		    zwarnnam(nam, "%s: %e", *a, errno);
		    return 1;
		}
	    }
	    /* Normal case, target is a directory, chase into it */
	    if (have_dir)
		goto havedir;
	}
    }
    if(a > args+1) {
	zwarnnam(nam, "last of many arguments must be a directory");
	return 1;
    }
    if(!args[1]) {
	ptr = strrchr(args[0], '/');
	if(ptr)
	    args[1] = ptr+1;
	else
	    args[1] = args[0];
    }
    return domove(nam, movefn, args[0], args[1], flags);
 havedir:
    buf = ztrdup(*a);
    *a = NULL;
    buf = appstr(buf, "/");
    blen = strlen(buf);
    for(; *args; args++) {

	ptr = strrchr(*args, '/');
	if(ptr)
	    ptr++;
	else
	    ptr = *args;

	buf[blen] = 0;
	buf = appstr(buf, ptr);
	err |= domove(nam, movefn, *args, buf, flags);
    }
    zsfree(buf);
    return err;
}
Ejemplo n.º 30
0
void
rhack(const char *cmd)
{
	const struct func_tab *tlist = cmdlist;
	boolean         firsttime = FALSE;
	int res;

	if (!cmd) {
		firsttime = TRUE;
		flags.nopick = 0;
		cmd = parse();
	}
	if (!*cmd || (*cmd & 0377) == 0377 ||
	    (flags.no_rest_on_space && *cmd == ' ')) {
		sound_bell();
		flags.move = 0;
		return;		/* probably we just had an interrupt */
	}
	if (movecmd(*cmd)) {
walk:
		if (multi)
			flags.mv = 1;
		domove();
		return;
	}
	if (movecmd(lowc(*cmd))) {
		flags.run = 1;
rush:
		if (firsttime) {
			if (!multi)
				multi = COLNO;
			u.last_str_turn = 0;
		}
		flags.mv = 1;
#ifdef QUEST
		if (flags.run >= 4)
			finddir();
		if (firsttime) {
			u.ux0 = u.ux + u.dx;
			u.uy0 = u.uy + u.dy;
		}
#endif	/* QUEST */
		domove();
		return;
	}
	if ((*cmd == 'f' && movecmd(cmd[1])) || movecmd(unctrl(*cmd))) {
		flags.run = 2;
		goto rush;
	}
	if (*cmd == 'F' && movecmd(lowc(cmd[1]))) {
		flags.run = 3;
		goto rush;
	}
	if (*cmd == 'm' && movecmd(cmd[1])) {
		flags.run = 0;
		flags.nopick = 1;
		goto walk;
	}
	if (*cmd == 'M' && movecmd(lowc(cmd[1]))) {
		flags.run = 1;
		flags.nopick = 1;
		goto rush;
	}
#ifdef QUEST
	if (*cmd == cmd[1] && (*cmd == 'f' || *cmd == 'F')) {
		flags.run = 4;
		if (*cmd == 'F')
			flags.run += 2;
		if (cmd[2] == '-')
			flags.run += 1;
		goto rush;
	}
#endif	/* QUEST */
	while (tlist->f_char) {
		if (*cmd == tlist->f_char) {
			res = (*(tlist->f_funct)) ();
			if (!res) {
				flags.move = 0;
				multi = 0;
			}
			return;
		}
		tlist++;
	}
	{
		char            expcmd[10];
		char  *cp = expcmd;
		while (*cmd && cp - expcmd < (int)sizeof(expcmd) - 2) {
			if (*cmd >= 040 && *cmd < 0177)
				*cp++ = *cmd++;
			else {
				*cp++ = '^';
				*cp++ = *cmd++ ^ 0100;
			}
		}
		*cp++ = 0;
		pline("Unknown command '%s'.", expcmd);
	}
	multi = flags.move = 0;
}