Ejemplo n.º 1
0
/*
 * domaze:
 *	Draw the maze on this level.
 */
do_maze()
{
	reg int least;
	reg struct room *rp;
	reg struct linked_list *item;
	reg struct object *obj;
	int cnt;
	bool treas;
	coord tp;

	for (rp = rooms; rp < &rooms[MAXROOMS]; rp++) {
		rp->r_flags = ISGONE;		/* kill all rooms */
		rp->r_fires = NULL;		/* no fires */
	}
	rp = &rooms[0];				/* point to only room */
	rp->r_flags = ISDARK;			/* mazes always dark */
	rp->r_pos.x = 0;			/* room fills whole screen */
	rp->r_pos.y = 1;
	rp->r_max.x = cols - 1;
	rp->r_max.y = lines - 3;
	draw_maze();				/* put maze into window */
	/*
	 * add some gold to make it worth looking for 
	 */
	item = spec_item(GOLD, NULL, NULL, NULL);
	obj = OBJPTR(item);
	obj->o_count *= (rnd(5) + 5);		/* add in one large hunk */
	attach(lvl_obj, item);
	cnt = 0;
	do {
	    rnd_pos(rp, &tp);
	} until (mvinch(tp.y, tp.x) == FLOOR || cnt++ > 5000);
	mvaddch(tp.y, tp.x, GOLD);
	obj->o_pos = tp;
	/*
	 * add in some food to make sure he has enough
	 */
	item = spec_item(FOOD, NULL, NULL, NULL);
	obj = OBJPTR(item);
	attach(lvl_obj, item);
	do {
	    rnd_pos(rp, &tp);
	} until (mvinch(tp.y, tp.x) == FLOOR || cnt++ > 5000);
	mvaddch(tp.y, tp.x, FOOD);
	obj->o_pos = tp;
	if (rnd(100) < 40) {			/* treasure type maze */
		treas = TRUE;
		least = 10;
		debug("treasure maze");
	}
	else {					/* normal maze level */
		least = 5;
		treas = FALSE;
	}
	genmonsters(least, treas);
}
Ejemplo n.º 2
0
void Moc::parseFunctionArguments(FunctionDef *def)
{
    Q_UNUSED(def);
    while (hasNext()) {
        ArgumentDef  arg;
        arg.type = parseType();
        if (arg.type.name == "void")
            break;
        if (test(IDENTIFIER))
            arg.name = lexem();
        while (test(LBRACK)) {
            arg.rightType += lexemUntil(RBRACK);
        }
        if (test(CONST) || test(VOLATILE)) {
            arg.rightType += ' ';
            arg.rightType += lexem();
        }
        arg.normalizedType = normalizeType(arg.type.name + ' ' + arg.rightType);
        arg.typeNameForCast = normalizeType(noRef(arg.type.name) + "(*)" + arg.rightType);
        if (test(EQ))
            arg.isDefault = true;
        def->arguments += arg;
        if (!until(COMMA))
            break;
    }
}
Ejemplo n.º 3
0
bool Moc::parseEnum(EnumDef *def)
{
    bool isTypdefEnum = false; // typedef enum { ... } Foo;

    if (test(IDENTIFIER)) {
        def->name = lexem();
    } else {
        if (lookup(-1) != TYPEDEF)
            return false; // anonymous enum
        isTypdefEnum = true;
    }
    if (!test(LBRACE))
        return false;
    do {
        if (lookup() == RBRACE) // accept trailing comma
            break;
        next(IDENTIFIER);
        def->values += lexem();
    } while (test(EQ) ? until(COMMA) : test(COMMA));
    next(RBRACE);
    if (isTypdefEnum) {
        if (!test(IDENTIFIER))
            return false;
        def->name = lexem();
    }
    return true;
}
Ejemplo n.º 4
0
void Moc::parseSlots(ClassDef *def, FunctionDef::Access access)
{
    next(COLON);
    while (inClass(def) && hasNext()) {
        switch (next()) {
        case PUBLIC:
        case PROTECTED:
        case PRIVATE:
        case Q_SIGNALS_TOKEN:
        case Q_SLOTS_TOKEN:
            prev();
            return;
        case SEMIC:
            continue;
        case FRIEND:
            until(SEMIC);
            continue;
        case USING:
            error("'using' directive not supported in 'slots' section");
        default:
            prev();
        }

        FunctionDef funcDef;
        funcDef.access = access;
        if (!parseFunction(&funcDef))
            continue;
        def->slotList += funcDef;
        while (funcDef.arguments.size() > 0 && funcDef.arguments.last().isDefault) {
            funcDef.wasCloned = true;
            funcDef.arguments.removeLast();
            def->slotList += funcDef;
        }
    }
}
Ejemplo n.º 5
0
/**
*
* Copy a file to the standard output
*
**/
void copyfile(FILE *file)
{
  int c;

  until ((c = fgetc(file)) == EOF)
    putchar(c);
}
Ejemplo n.º 6
0
char *
linebuf_prev (LINEBUF *buffer, DESCR *descr, const char *curline)
{
    ASSERT (buffer);
    ASSERT (descr);
    ASSERT (curline);

    if (curline == buffer-> tail)
        return (NULL);                  /*  We're at the start               */
    else
      {
        /*  We're pointing to the byte after the line's null byte            */
        buffer_dec (curline);           /*  Bump down to null                */
        ASSERT (*curline == '\0');

        do
          {
            buffer_dec (curline);       /*  And now look for previous null   */
            if (*curline == '\0')
              {
                buffer_inc (curline);   /*  Bump up to start of string       */
                break;
              }
          }
        until (curline == buffer-> tail);

        get_line (buffer, descr, curline);
        return ((char *) curline);
      }
}
Ejemplo n.º 7
0
bool ConnectionContext::get(boost::shared_ptr<SessionContext> ssn, boost::shared_ptr<ReceiverContext> lnk, qpid::messaging::Message& message, qpid::messaging::Duration timeout)
{
    qpid::sys::AbsTime until(convert(timeout));
    while (true) {
        qpid::sys::ScopedLock<qpid::sys::Monitor> l(lock);
        pn_delivery_t* current = pn_link_current((pn_link_t*) lnk->receiver);
        QPID_LOG(debug, "In ConnectionContext::get(), current=" << current);
        if (current) {
            qpid::messaging::MessageImpl& impl = MessageImplAccess::get(message);
            boost::shared_ptr<EncodedMessage> encoded(new EncodedMessage(pn_delivery_pending(current)));
            ssize_t read = pn_link_recv(lnk->receiver, encoded->getData(), encoded->getSize());
            if (read < 0) throw qpid::messaging::MessagingException("Failed to read message");
            encoded->trim((size_t) read);
            QPID_LOG(debug, "Received message of " << encoded->getSize() << " bytes: ");
            encoded->init(impl);
            impl.setEncoded(encoded);
            impl.setInternalId(ssn->record(current));
            pn_link_advance(lnk->receiver);
            return true;
        } else if (until > qpid::sys::now()) {
            wait();
        } else {
            return false;
        }
    }
    return false;
}
Ejemplo n.º 8
0
int mollweide(mapx_class *current, double lat, double lon,
	      double *x, double *y)
{
  double dlon;
  double phi, lam, theta, delta;
  double sin_theta, cos_theta, psi, epsilon=1e-6;
  int it, maxit=10;
  
  dlon = lon - current->lon0;
  NORMALIZE(dlon);
  
  phi = RADIANS (lat);
  lam = RADIANS (dlon);
  
  delta = 0.0;
  theta = phi;
  sin_theta = sin(theta);
  cos_theta = cos(theta);
  if (fabs(cos_theta) > epsilon)
  { psi = PI*sin(phi);
    it = 0;
    repeat
    { delta = -(theta + sin_theta - psi) / (1 + cos_theta);
      theta += delta;
      sin_theta = sin(theta);
      cos_theta = cos(theta);
      if (++it >= maxit) break;
    } until (fabs(delta) <= epsilon);
    theta /= 2.0;
    sin_theta = sin(theta);
    cos_theta = cos(theta);
  }
Ejemplo n.º 9
0
/**
*
* _help(debug);
*
* Display help file.
*
**/
PUBLIC void _help(DEBUG *debug, char *topic)
{
    DISPLAY *display = debug->display;
#ifndef BUG
    int  proc_id;
#endif

    dstart(display);
    if (topic == NULL)
    {
        if ((proc_id = vfork()) == 0)
        {
            dup2(fileno(display->filein), 0);
            dup2(fileno(display->fileout), 1);
            dup2(fileno(display->fileout), 2);
            execlp("more", "more", "/helios/etc/debug.hlp", NULL);
            perror("more");
            _exit(1);
        }
#ifndef BUG
        {
            int t_state,terror;
            do
            {
                terror = wait(&t_state);
            }
            until((terror == proc_id) || (terror == -1));

        }
#endif
    }
    else
    {
Ejemplo n.º 10
0
do_passages()
{
    register struct rdes *r1, *r2;
    register int i, j;
    register int roomcount;

    /*
     * reinitialize room graph description
     */
    for (r1 = rdes; r1 < &rdes[MAXROOMS]; r1++)
    {
	for (j = 0; j < MAXROOMS; j++)
	    r1->isconn[j] = FALSE;
	r1->ingraph = FALSE;
    }

    /*
     * starting with one room, connect it to a random adjacent room and
     * then pick a new room to start with.
     */
    roomcount = 1;
    r1 = &rdes[rnd(MAXROOMS)];
    r1->ingraph = TRUE;
    do
    {
	/*
	 * find a room to connect with
	 */
	j = 0;
	for (i = 0; i < MAXROOMS; i++)
	    if (r1->conn[i] && !rdes[i].ingraph && rnd(++j) == 0)
		r2 = &rdes[i];
	/*
	 * if no adjacent rooms are outside the graph, pick a new room
	 * to look from
	 */
	if (j == 0)
	{
	    do
		r1 = &rdes[rnd(MAXROOMS)];
	    until (r1->ingraph);
	}
	/*
	 * otherwise, connect new room to the graph, and draw a tunnel
	 * to it
	 */
	else
	{
	    r2->ingraph = TRUE;
	    i = r1 - rdes;
	    j = r2 - rdes;
	    conn(i, j);
	    r1->isconn[j] = TRUE;
	    r2->isconn[i] = TRUE;
	    roomcount++;
	}
    } while (roomcount < MAXROOMS);
Ejemplo n.º 11
0
int main () {
  int numbers[]={10,20,30,40,50};
  MyIterator from(numbers);
  MyIterator until(numbers+5);
  for (MyIterator it=from; it!=until; it++)
    std::cout << *it << ' ';
  std::cout << '\n';

  return 0;
}
Ejemplo n.º 12
0
void Moc::parseSignals(ClassDef *def)
{
    int defaultRevision = -1;
    if (test(Q_REVISION_TOKEN)) {
        next(LPAREN);
        QByteArray revision = lexemUntil(RPAREN);
        revision.remove(0, 1);
        revision.chop(1);
        bool ok = false;
        defaultRevision = revision.toInt(&ok);
        if (!ok || defaultRevision < 0)
            error("Invalid revision");
    }

    next(COLON);
    while (inClass(def) && hasNext()) {
        switch (next()) {
        case PUBLIC:
        case PROTECTED:
        case PRIVATE:
        case Q_SIGNALS_TOKEN:
        case Q_SLOTS_TOKEN:
            prev();
            return;
        case SEMIC:
            continue;
        case FRIEND:
            until(SEMIC);
            continue;
        case USING:
            error("'using' directive not supported in 'signals' section");
        default:
            prev();
        }
        FunctionDef funcDef;
        funcDef.access = FunctionDef::Protected;
        parseFunction(&funcDef);
        if (funcDef.isVirtual)
            warning("Signals cannot be declared virtual");
        if (funcDef.inlineCode)
            error("Not a signal declaration");
        if (funcDef.revision > 0) {
            ++def->revisionedMethods;
        } else if (defaultRevision != -1) {
            funcDef.revision = defaultRevision;
            ++def->revisionedMethods;
        }
        def->signalList += funcDef;
        while (funcDef.arguments.size() > 0 && funcDef.arguments.last().isDefault) {
            funcDef.wasCloned = true;
            funcDef.arguments.removeLast();
            def->signalList += funcDef;
        }
    }
}
Ejemplo n.º 13
0
int test_iterator_1()
{
	// std::iterator: 迭代器基类
	int numbers[] = { 10, 20, 30, 40, 50 };
	MyIterator from(numbers);
	MyIterator until(numbers + 5);
	for (MyIterator it = from; it != until; it++)
		std::cout << *it << ' ';
	std::cout << '\n';

	return 0;
}
Ejemplo n.º 14
0
Archivo: gram.c Proyecto: joequant/iraf
/* LISTALLHELP -- Starting at curpack, list out all packages and their tasks
 * in a circular fashion until get back to curpack. this is like the search
 * path works.  Label the current package in some way.  Serves ?? directive.
 * TODO: this should be optimized once a nice form is settled on.
 */
void 
listallhelp (int show_invis)
{
	register struct package *pkp;

	pkp = curpack;
	do {
		oprintf ("    %s:\n", pkp->pk_name);
		listhelp (pkp, show_invis);
		if ((pkp = pkp->pk_npk) == NULL)
			pkp = reference (package, pachead);
	} until (pkp == curpack);
}
Ejemplo n.º 15
0
/*** Parse a while statement ***/
While* Parser::parseWhile()
{
	if(!hasTokens() || peekToken().getType() != T_WHILE)
		ParserSyntaxException(getToken(), "Expected \"while\" command!");
	Token tok = getToken();

	// Store the condition
	std::auto_ptr<Object> cond(parseExpression());

	if(!hasTokens() || peekToken().getType() != T_DO)
		ParserSyntaxException(getToken(), "Expected \"do\" command!");
	getToken();

	// Parse any newlines
	while(hasTokens() && peekToken().getType() == T_EOL)
		getToken();

	// Add commands until "od" or "until" is found
	std::auto_ptr<NodeList> whileStmts(new NodeList());
	while(hasTokens() && !(peekToken().getType() == T_OD || peekToken().getType() == T_UNTIL))
	{
		whileStmts->pushNode(parseStatement());
		parseSeparation();
	}

	std::auto_ptr<While> result(new While());
	result->setLineNumber(tok.getLineNumber());
	result->setColumnNumber(tok.getColumnNumber());

	if(hasTokens() && peekToken().getType() == T_OD)
	{
		getToken();
		result->setCondition(cond.release());
		result->setStatements(whileStmts.release());
		return result.release();
	}

	if(hasTokens() && peekToken().getType() == T_UNTIL)
	{
		getToken();
		std::auto_ptr<Object> until(parseExpression());
		result->setCondition(cond.release());
		result->setStatements(whileStmts.release());
		result->setUntilCondition(until.release());
		return result.release();
	}

	throw ParserSyntaxException(getToken(), "Expected \"od\" or \"until\" command!");
	return 0;
}
Ejemplo n.º 16
0
Archivo: moc.cpp Proyecto: Fale/qtmoko
QByteArray Moc::lexemUntil(Token target)
{
    int from = index;
    until(target);
    QByteArray s;
    while (from <= index) {
        QByteArray n = symbols.at(from++-1).lexem();
        if (s.size() && n.size()
            && is_ident_char(s.at(s.size()-1))
            && is_ident_char(n.at(0)))
            s += ' ';
        s += n;
    }
    return s;
}
Ejemplo n.º 17
0
Archivo: dt.c Proyecto: pkuwwt/Detri
Dt_input_scan *dt_input_scan (const char data_path[])
     /* ... scans the ASCII input file data_path for the fields in the return
        structure (see dt.h file).  See also dt_input_load() which actually
        loads the data and sets the has_weights field if necessary. */
     /* NOTE: The returned address, which points to the return structure,
              is a constant.  DO NOT FREE() IT and consider the fields
              of the structure as read-only. */
{
  static Dt_input_scan data;
  FILE *inp = basic_fopen (data_path, "r");
  char *r;
  ;
  /* default values */
  data.name = STRDUP (data_path);
  data.title = NULL;
  data.lines = 0;
  data.n = 0;
  data.scale = 1.0;     /* ie, no scaling */
  data.fix_w = 0;    
  data.fix_a = 0;
  data.decimals = 10;  /* ie, int coordinates */
  data.has_weights = 0;  /* ie, unknown; see dt_input_load() */
  ;
  /* scan the file */
  print ("Scanning ASCII file \"%s\" ... ",
         If (basic_fopen_zpath, basic_fopen_zpath, data_path));
  flush ();
  while ((r = basic_cb_getline (inp)))
    {
      data.lines ++;
      if (basic_strip (r) AND (r[0] != '#'))
        { /* a data line: <x> <y> <z> */
          data.n ++;
        }
      else if (is_command (&data, r, "title", 5))
        { /* # title: %s */
          r = basic_strip (index (r, 'e') + 1);
          if (r)
            {
              int i = -1;
              data.title = STRDUP (r);
              do { i ++; } until (data.title[i] == '\n');
              data.title[i] = 0;
            }
        }
      else if (is_command (&data, r, "scale", 5))
Ejemplo n.º 18
0
Archivo: init.c Proyecto: kioy/TA-Demo2
/*
 * init_colors:
 *	Initialize the potion color scheme for this time
 */
void
init_colors(void)
{
    int i, j;
    int used[NCOLORS];

    for (i = 0; i < NCOLORS; i++)
        used[i] = FALSE;
    for (i = 0; i < MAXPOTIONS; i++)
    {
        do
            j = rnd(NCOLORS);
        until (!used[j]);
        used[j] = TRUE;
        p_colors[i] = rainbow[j];
    }
}
Ejemplo n.º 19
0
/**
*
* _edit(debug, loc):
*
* Invoke an editor.
*
**/
PUBLIC void _edit(DEBUG *debug, LOCATION loc)
{
    DISPLAY *display = debug->display;
    char *editor;
    char lineopt[20];
#ifndef BUG
    int  proc_id;
#endif
    (void)sprintf(lineopt, "-g%d", loc.line);
    if ((editor = getvar(debug->env.Envv, "EDITOR")) == NULL) editor = "emacs";
    /* ACE: The name stored with the source should be the full name, thus
            eliminating the need to fiddle the current directory.
    */

#ifdef OLDCODE
    chdir(debug->env.Objv[0]->Name);
#endif
    /*
    -- crf : 12/08/91 - clean up use of Environment Objv
    */
    chdir(debug->env.Objv[OV_Cdir]->Name);

    dstart(display);
    if ((proc_id = vfork()) == 0)
    {
        dup2(fileno(display->filein), 0);
        dup2(fileno(display->fileout), 1);
        dup2(fileno(display->fileout), 2);
        execlp(editor, editor, lineopt, getsource(loc.module)->name, NULL);
        perror(editor);
        _exit(1);
    }
#ifndef BUG
    {
        int t_state,terror;
        do
        {
            terror = wait(&t_state);
        }
        until((terror == proc_id) || (terror == -1));

    }
#endif
    dend(display, FALSE);

}
Ejemplo n.º 20
0
Archivo: init.c Proyecto: kioy/TA-Demo2
/*
 * init_stones:
 *	Initialize the ring stone setting scheme for this time
 */
void
init_stones(void)
{
    int used[NSTONES];
    int i, j;

    for (i = 0; i < NSTONES; i++)
        used[i] = FALSE;
    for (i = 0; i < MAXRINGS; i++)
    {
        do
            j = rnd(NSTONES);
        until (!used[j]);
        used[j] = TRUE;
        r_stones[i] = stones[j].st_name;
        ring_info[i].oi_worth += stones[j].st_value;
    }
}
Ejemplo n.º 21
0
/**
*
* _shell(debug, cmdline);
*
* Execute a shell.
*
**/
PUBLIC void _shell(DEBUG *debug, char *cmdline)
{
    DISPLAY *display = debug->display;
    char *shell;
#ifndef BUG
    int  proc_id;
#endif
    if ((shell = getvar(debug->env.Envv, "SHELL")) == NULL) shell = "shell";

#ifdef OLDCODE
    chdir(debug->env.Objv[0]->Name);
#endif
    /*
    -- crf : 12/08/91 - clean up use of Environment Objv
    */
    chdir(debug->env.Objv[OV_Cdir]->Name);

    dstart(display);
    if ((proc_id = vfork()) == 0)
    {
        dup2(fileno(display->filein), 0);
        dup2(fileno(display->fileout), 1);
        dup2(fileno(display->fileout), 2);
        if (cmdline == NULL) execlp(shell, shell, NULL);
        else execlp(shell, shell, "-fc", cmdline, NULL);
        perror(shell);
        _exit(1);
    }

#ifndef BUG
    {
        int t_state,terror;
        do
        {
            terror = wait(&t_state);
        }
        until((terror == proc_id) || (terror == -1));

    }
#endif
    dend(display, cmdline != NULL);
}
Ejemplo n.º 22
0
void Procedure::parseBody(bool allowNative) {
    if(nextToken()->value[0] == E_RADIO){
        const Token *t = consumeToken(IDENTIFIER);
        if(!allowNative){
            compilerError(t, "Native code is not allowed in this context.");
        }
        native = true;
        return;
    }
    
    const Token *token = consumeToken(IDENTIFIER);
    
    if (token->value[0] != E_GRAPES){
        ecCharToCharStack(token->value[0], c);
        compilerError(token, "Expected 🍇 but found %s instead.", c);
    }
    
    firstToken = currentToken;
    
    int d = 0;
    while ((token = until(E_WATERMELON, E_GRAPES, &d)) != nullptr);
}
Ejemplo n.º 23
0
int test_iterator_20()
{
	// std::reverse_iterator: 反向迭代器
	std::vector<int> myvector;
	for (int i = 0; i<10; i++) myvector.push_back(i);

	typedef std::vector<int>::iterator iter_type;
							      // ? 0 1 2 3 4 5 6 7 8 9 ?
	iter_type from(myvector.begin());                     //   ^
							      //         ------>
	iter_type until(myvector.end());                      //                       ^
							      //
	std::reverse_iterator<iter_type> rev_until(from);     // ^
							      //         <------
	std::reverse_iterator<iter_type> rev_from(until);     //                     ^

	std::cout << "myvector:";
	while (rev_from != rev_until)
		std::cout << ' ' << *rev_from++; // 9 8 7 6 5 4 3 2 1 0
	std::cout << '\n';

	return 0;
}
Ejemplo n.º 24
0
Archivo: exec.c Proyecto: geechee/iraf
/* RUN -- Run the code beginning at pc until we run an EXEC instruction of
 *   something other than a builtin command or END instruction.
 *   The EXEC instruction means that a new task is being started and we should
 *   return to the parser in the main "parse/run" loop in main.  If, however,
 *   the exec was for a builtin (or procedure, someday) then no parsing is to
 *   be done and we just continue on with the current code.
 * Note that execing the bye builtin is not a special case since it does a
 *   restor() which resets the pc to the instruction immediately following the
 *   exec IN THE PARENT task and we continue on with it.
 * Increment pc after each "fetch" cycle and before the "exec" cycle.
 *   If any if the instructions fail, they will call error(). this will do
 *   a longjmp(errenv,1), causing setjmp to return (in main) and an
 *   immediate retreat to the most recent terminaltask with unwind().
 */
void
run (void)
{
	register struct codeentry *cp;
	register int opcode;

	if (cltrace)
	    eprintf ("\t----- task %s -----\n",
		currentask->t_ltp->lt_lname);

	do {
	    cp = coderef (pc);
	    opcode = cp->c_opcode;
	    if (cltrace)
		d_instr (stderr, "\t", pc);
	    if (cldebug)
		eprintf ("run: pc = %d, opcode = %d\n", pc, opcode);
	    pc += cp->c_length;
	    (*opcodetbl[opcode]) (&cp->c_args);

	} until ((opcode == EXEC && !(newtask->t_flags & T_BUILTIN)) ||
		  opcode == END || alldone);
}
Ejemplo n.º 25
0
void Moc::parseSignals(ClassDef *def)
{
    next(COLON);
    while (inClass(def) && hasNext()) {
        switch (next()) {
        case PUBLIC:
        case PROTECTED:
        case PRIVATE:
        case Q_SIGNALS_TOKEN:
        case Q_SLOTS_TOKEN:
            prev();
            return;
        case SEMIC:
            continue;
        case FRIEND:
            until(SEMIC);
            continue;
        case USING:
            error("'using' directive not supported in 'signals' section");
        default:
            prev();
        }
        FunctionDef funcDef;
        funcDef.access = FunctionDef::Protected;
        parseFunction(&funcDef);
        if (funcDef.isVirtual)
            warning("Signals cannot be declared virtual");
        if (funcDef.inlineCode)
            error("Not a signal declaration");
        def->signalList += funcDef;
        while (funcDef.arguments.size() > 0 && funcDef.arguments.last().isDefault) {
            funcDef.wasCloned = true;
            funcDef.arguments.removeLast();
            def->signalList += funcDef;
        }
    }
}
Ejemplo n.º 26
0
int main()
{
	int numbers[]={10,20,30,40,50};
	MyIterator from(numbers);
	MyIterator until(numbers+5);
	for (MyIterator it=from; it!=until; it++)
		std::cout << *it << ' ';
	std::cout << '\n';

	// F*****g the Question 5 in http://blog.csdn.net/fengbingyang/article/details/8764931
	// refer to http://programmers.stackexchange.com/questions/153386/why-is-x-x-undefined
	int x=10;
	x = x++;
	from = from++;
	printf("int++: %d, iter++: %d\n",x,*from);

	std::vector<int> vc1(numbers, numbers+5);
	std::vector<int> vc2(vc1.begin(), vc1.end());

	std::vector<int> v(vc1);
	auto mid1 = my_reverse(v.begin(), v.end());
	for (int n : v)
		std::cout << n << ' ';
	std::cout << "Mid: " << mid1 <<'\n';

	std::list<int> l(numbers, numbers+5);
	auto mid2 = my_reverse(l.begin(), l.end());
	for (auto n : l)
		std::cout << n << ' ';
	std::cout << "Mid: " << mid2<< '\n';

	//    std::istreambuf_iterator<char> i1(std::cin), i2;
	//    my_reverse(i1, i2); // compilation error

	return 0;
}
Ejemplo n.º 27
0
buy_it()
{
        reg int wh;
        struct linked_list *item = NULL;
        struct object *obj = NULL;
        int wasfood = FALSE;

        if (purse <= 0) {
            msg("You have no money.");
            return;
        }
        if (curprice < 0) {             /* if not yet priced */
            wh = price_it();
            if (!wh)                    /* nothing to price */
                return;
            msg("Do you want to buy it? ");
            do {
                wh = wgetch(cw);
                if (wh == ESC || wh == 'n') {
                    msg("");
                    return;
                }
            } until(wh == 'y');
        }
Ejemplo n.º 28
0
/*
 * buy_it:
 *	Buy the item on which the hero stands
 */
int buy_it()
{
  int wh;

  if (purse <= 0) {
    msg("You have no money.");
    return 0;
  }
  if (curprice < 0) { /* if not yet priced */
    wh = price_it();
    if (!wh) /* nothing to price */
      return 0;
    msg("Do you want to buy it? ");
    do {
      wh = readchar();
      if (isupper(wh))
        wh = tolower(wh);
      if (wh == ESCAPE || wh == 'n') {
        msg("");
        return 0;
      }
    }
    until(wh == 'y');
  }
Ejemplo n.º 29
0
void GameStateManager::cleanup()
{
	//unwind state stack in reverse
	typedef std::vector<State*>::iterator iter_type;
	iter_type from(gameStates.begin());
	iter_type until(gameStates.end());  
	std::reverse_iterator<iter_type> rev_until(from);
	std::reverse_iterator<iter_type> rev_from(until);                    
	while (rev_from != rev_until)
	{
		delete *rev_from++;
	}
	

	for (auto& state : hangingStates)
	{
		delete state;
		state = nullptr;
	}

	//remove all state pointers
	gameStates.clear();
	hangingStates.clear();
}
Ejemplo n.º 30
0
void Preprocessor::preprocess(const QByteArray &filename, Symbols &preprocessed)
{
    currentFilenames.push(filename);
    preprocessed.reserve(preprocessed.size() + symbols.size());
    while (hasNext()) {
        Token token = next();

        switch (token) {
        case PP_INCLUDE:
        {
            int lineNum = symbol().lineNum;
            QByteArray include;
            bool local = false;
            if (test(PP_STRING_LITERAL)) {
                local = lexem().startsWith('\"');
                include = unquotedLexem();
            } else
                continue;
            until(PP_NEWLINE);

            // #### stringery
            QFileInfo fi;
            if (local)
                fi.setFile(QFileInfo(QString::fromLocal8Bit(filename)).dir(), QString::fromLocal8Bit(include));
            for (int j = 0; j < Preprocessor::includes.size() && !fi.exists(); ++j) {
                const IncludePath &p = Preprocessor::includes.at(j);
                if (p.isFrameworkPath) {
                    const int slashPos = include.indexOf('/');
                    if (slashPos == -1)
                        continue;
                    QByteArray frameworkCandidate = include.left(slashPos);
                    frameworkCandidate.append(".framework/Headers/");
                    fi.setFile(QString::fromLocal8Bit(QByteArray(p.path + '/' + frameworkCandidate)), QString::fromLocal8Bit(include.mid(slashPos + 1)));
                } else {
                    fi.setFile(QString::fromLocal8Bit(p.path), QString::fromLocal8Bit(include));
                }
                // try again, maybe there's a file later in the include paths with the same name
                // (186067)
                if (fi.isDir()) {
                    fi = QFileInfo();
                    continue;
                }
            }

            if (!fi.exists() || fi.isDir())
                continue;
            include = fi.canonicalFilePath().toLocal8Bit();

            if (Preprocessor::preprocessedIncludes.contains(include))
                continue;
            Preprocessor::preprocessedIncludes.insert(include);

            QFile file(QString::fromLocal8Bit(include));
            if (!file.open(QFile::ReadOnly))
                continue;

            QByteArray input = file.readAll();
            file.close();
            if (input.isEmpty())
                continue;

            Symbols saveSymbols = symbols;
            int saveIndex = index;

            // phase 1: get rid of backslash-newlines
            input = cleaned(input);

            // phase 2: tokenize for the preprocessor
            symbols = tokenize(input);
            input.clear();

            index = 0;

            // phase 3: preprocess conditions and substitute macros
            preprocessed += Symbol(0, MOC_INCLUDE_BEGIN, include);
            preprocess(include, preprocessed);
            preprocessed += Symbol(lineNum, MOC_INCLUDE_END, include);

            symbols = saveSymbols;
            index = saveIndex;
            continue;
        }
        case PP_DEFINE:
        {
            next(IDENTIFIER);
            QByteArray name = lexem();
            int start = index;
            until(PP_NEWLINE);
            Macro macro;
            macro.symbols.reserve(index - start - 1);
            for (int i = start; i < index - 1; ++i)
                macro.symbols += symbols.at(i);
            macros.insert(name, macro);
            continue;
        }
        case PP_UNDEF: {
            next(IDENTIFIER);
            QByteArray name = lexem();
            until(PP_NEWLINE);
            macros.remove(name);
            continue;
        }
        case PP_IDENTIFIER:
        {
//             if (macros.contains(symbol()))
//                 ;
        }
            // we _could_ easily substitute macros by the following
            // four lines, but we choose not to.
            /*
            if (macros.contains(sym.lexem())) {
                preprocessed += substitute(macros, symbols, i);
                continue;
            }
            */
            break;
        case PP_HASH:
            until(PP_NEWLINE);
            continue; // skip unknown preprocessor statement
        case PP_IFDEF:
        case PP_IFNDEF:
        case PP_IF:
            while (!evaluateCondition()) {
                if (!skipBranch())
                    break;
                if (test(PP_ELIF)) {
                } else {
                    until(PP_NEWLINE);
                    break;
                }
            }
            continue;
        case PP_ELIF:
        case PP_ELSE:
            skipUntilEndif();
            // fall through
        case PP_ENDIF:
            until(PP_NEWLINE);
            continue;
        case SIGNALS:
        case SLOTS: {
            Symbol sym = symbol();
            if (macros.contains("QT_NO_KEYWORDS"))
                sym.token = IDENTIFIER;
            else
                sym.token = (token == SIGNALS ? Q_SIGNALS_TOKEN : Q_SLOTS_TOKEN);
            preprocessed += sym;
        } continue;
        default:
            break;
        }
        preprocessed += symbol();
    }

    currentFilenames.pop();
}