コード例 #1
0
ファイル: subdiv.cpp プロジェクト: THTBSE/Stability
// Compute the butterfly stencil
static point butterfly(TriMesh *mesh, int f1, int f2,
		       int v0, int v1, int v2, int v3)
{
	point p = 0.5f * (mesh->vertices[v1] + mesh->vertices[v2]) +
		  0.125f * (mesh->vertices[v0] + mesh->vertices[v3]);
	p -= 0.0625f * (opposite(mesh, f1, v1) + opposite(mesh, f1, v2) +
			opposite(mesh, f2, v1) + opposite(mesh, f2, v2));
	return p;
}
コード例 #2
0
void FuncSet4::changeTurnTobeProved()
{
    QTextCodec *TradChineseCodec = QTextCodec::codecForName("Big5-ETen");
    turnTobeProved = opposite(turnTobeProved);
    turnTobeProvedButton->setText( TradChineseCodec->toUnicode(
                    (turnTobeProved==BLACK) ? "黑方" : "白方" ) );
}
コード例 #3
0
ファイル: move_gen.cpp プロジェクト: YurkoFlisk/checkers
void MoveGenEnglish::_find_deep_capture_queen(MoveList& moves, Move& move, int8_t row, int8_t column, bool(&captured)[8][8]) const
{
	static constexpr int d_row[4] = { 1, 1, -1, -1 }, d_column[4] = { 1, -1, 1, -1 };
	for (size_t dir = 0; dir < 4; ++dir)
	{
		// In english checkers we can jump only over adjacent pieces
		const int r1 = row + d_row[dir], c1 = column + d_column[dir], r2 = r1 + d_row[dir], c2 = c1 + d_column[dir];
		if (r2 < 0 || c2 < 0 || r2 > 7 || c2 > 7 || board[r2][c2].get_type() != PT_EMPTY
			|| board[r1][c1].get_colour() != opposite(TURN) || captured[r1][c1])
			continue;
		move.add_step(Position(r2, c2)); // Correct capture-move
		move.add_capture(std::make_pair(Position(r1, c1), board[r1][c1]));
		const size_t old = moves.size();
		captured[r1][c1] = true; // For preventing 'recapturing' piece at (r1; c1) in moves produced by recursive call to this function(next 4 lines)
		_find_deep_capture_queen<TURN>(moves, move, r2, c2, captured);
		if (old == moves.size()) // If in recursive call we haven't found any move, then 'move' is a final capture and is one of possible captures
		{
			move.set_become(Piece(TURN == WHITE ? WHITE_QUEEN : BLACK_QUEEN));
			moves.emplace(move);
		}
		captured[r1][c1] = false; // For correct work on next cycles we should clear changes to 'captured' and 'move' variables
		move.pop_step();
		move.pop_capture();
	}
}
コード例 #4
0
void buildTreeWidgetItem(pnsNode *node, QTreeWidgetItem *rootItem)
{
    if(rootItem==NULL) err(false, "buildTreeWidget(): treeWidget shouldn't be NULL");
    if(node==NULL) err(false, "buildTreeWidget(): node shouldn't be NULL");

    QString str;
    str.sprintf("%s (%d,%d) [%d,%d] ",
                (( (opposite(node->turn))==BLACK )?"BLACK":"WHITE"),
                node->x, node->y, node->pn, node->dn);/*
                (node->pn >= PNS_INFINITY)?"INF":QString::number(node->pn),
                (node->dn >= PNS_INFINITY)?"INF":QString::number(node->dn) );*/
    rootItem->setText(0, str);

    QTreeWidgetItem *tItem;
    if(node->actualChildren.size()!=0) rootItem->setExpanded(true);
    for(int i=node->actualChildren.size()-1; i>=0; i--){
        tItem = new QTreeWidgetItem(rootItem);
        buildTreeWidgetItem(node->actualChildren[i], tItem);
    }
    if( node->virtualChildren.size()!=0 ){
        tItem = new QTreeWidgetItem(rootItem);
        str.sprintf("other unspanned %d nodes", node->virtualChildren.size());
        tItem->setText(0, str);

        QTreeWidgetItem *xItem = new QTreeWidgetItem(tItem);
        QString tmp;
        str.clear();
        for(int i=node->virtualChildren.size()-1; i>=0; i--){
            tmp.sprintf("(%d,%d) ", node->virtualChildren[i].first, node->virtualChildren[i].second);
            str.append(tmp);
        }
        xItem->setText(0, str);
    }
}
コード例 #5
0
void dtNavMesh::connectExtLinks(dtMeshTile* tile, dtMeshTile* target, int side)
{
	if (!tile) return;
	
	// Connect border links.
	for (int i = 0; i < tile->header->polyCount; ++i)
	{
		dtPoly* poly = &tile->polys[i];

		// Create new links.
		unsigned short m = DT_EXT_LINK | (unsigned short)side;
		const int nv = poly->vertCount;
		for (int j = 0; j < nv; ++j)
		{
			// Skip edges which do not point to the right side.
			if (poly->neis[j] != m) continue;
			
			// Create new links
			const float* va = &tile->verts[poly->verts[j]*3];
			const float* vb = &tile->verts[poly->verts[(j+1) % nv]*3];
			dtPolyRef nei[4];
			float neia[4*2];
			int nnei = findConnectingPolys(va,vb, target, opposite(side), nei,neia,4);
			for (int k = 0; k < nnei; ++k)
			{
				unsigned int idx = allocLink(tile);
				if (idx != DT_NULL_LINK)
				{
					dtLink* link = &tile->links[idx];
					link->ref = nei[k];
					link->edge = (unsigned char)j;
					link->side = (unsigned char)side;
					
					link->next = poly->firstLink;
					poly->firstLink = idx;

					// Compress portal limits to a byte value.
					if (side == 0 || side == 4)
					{
						float tmin = (neia[k*2+0]-va[2]) / (vb[2]-va[2]);
						float tmax = (neia[k*2+1]-va[2]) / (vb[2]-va[2]);
						if (tmin > tmax)
							dtSwap(tmin,tmax);
						link->bmin = (unsigned char)(dtClamp(tmin, 0.0f, 1.0f)*255.0f);
						link->bmax = (unsigned char)(dtClamp(tmax, 0.0f, 1.0f)*255.0f);
					}
					else if (side == 2 || side == 6)
					{
						float tmin = (neia[k*2+0]-va[0]) / (vb[0]-va[0]);
						float tmax = (neia[k*2+1]-va[0]) / (vb[0]-va[0]);
						if (tmin > tmax)
							dtSwap(tmin,tmax);
						link->bmin = (unsigned char)(dtClamp(tmin, 0.0f, 1.0f)*255.0f);
						link->bmax = (unsigned char)(dtClamp(tmax, 0.0f, 1.0f)*255.0f);
					}
				}
			}
		}
	}
}
コード例 #6
0
ファイル: move_gen.cpp プロジェクト: YurkoFlisk/checkers
void MoveGenEnglish::_find_deep_capture(MoveList& moves, Move& move, int8_t row, int8_t column) const
{
	static constexpr int d_row = (TURN == WHITE ? 1 : -1), d_column[2] = { 1, -1 };
	const int r1 = row + d_row, r2 = r1 + d_row;
	if (r2 < 0 || r2 > 7)
		return;
	for (size_t dir = 0; dir < 2; ++dir)
	{
		const int c1 = column + d_column[dir], c2 = c1 + d_column[dir];
		if (c2 < 0 || c2 > 7 || board[r2][c2].get_type() != PT_EMPTY
			|| board[r1][c1].get_colour() != opposite(TURN))
			continue;
		move.add_step(Position(r2, c2)); // Correct capture-move
		move.add_capture(std::make_pair(Position(r1, c1), board[r1][c1]));
		const size_t old = moves.size();
		if (TURN == WHITE ? (r2 == 7) : (r2 == 0)) // We can become queen at this move
		{
			move.set_become(Piece(TURN == WHITE ? WHITE_QUEEN : BLACK_QUEEN)); // In english checkers move is stopped when piece becomes queen
			moves.emplace(move);
		}
		else
		{
			_find_deep_capture<TURN>(moves, move, r2, c2);
			if (old == moves.size()) // If in recursive call we haven't found any move, then 'move' is a final capture and is one of possible captures
			{
				move.set_become(Piece(TURN == WHITE ? WHITE_SIMPLE : BLACK_SIMPLE));
				moves.emplace(move);
			}
		}
		move.pop_step();
		move.pop_capture();
	}
}
コード例 #7
0
ファイル: dfs-maze.cpp プロジェクト: ftk/XXLDDRace
void fill_maze(int x, int y, int lenght = 0)
{
  cell& cur = maze[x][y];
  cur.visited = true;
  if(lenght > endlen)
  {
    endx = x;
    endy = y;
    endlen = lenght;
  }
  for(int i = 0; i < 30; i++) // all directions in random order
  {
    direction dir = random_dir();
    int cx = x, cy = y; // neightbor
    if(!offset(dir, cx, cy))
      continue;
    cell& n = maze[cx][cy];
    if(n.visited)
      continue;
    
    // make path
    cur.break_wall(dir);
    n.break_wall(opposite(dir));
    
    
    // recursion
    fill_maze(cx, cy, lenght + 1);
  }
}
コード例 #8
0
ファイル: term.c プロジェクト: kg6zgj/asterisk-1.8-current
char *term_color(char *outbuf, const char *inbuf, int fgcolor, int bgcolor, int maxout)
{
    int attr = 0;

    if (!vt100compat) {
        ast_copy_string(outbuf, inbuf, maxout);
        return outbuf;
    }
    if (!fgcolor) {
        ast_copy_string(outbuf, inbuf, maxout);
        return outbuf;
    }

    if (fgcolor & 128) {
        attr = ast_opt_light_background ? 0 : ATTR_BRIGHT;
        fgcolor &= ~128;
    }

    if (bgcolor) {
        bgcolor &= ~128;
    }

    if (ast_opt_light_background) {
        fgcolor = opposite(fgcolor);
    }

    if (ast_opt_force_black_background) {
        snprintf(outbuf, maxout, "%c[%d;%d;%dm%s%c[%d;%dm", ESC, attr, fgcolor, bgcolor + 10, inbuf, ESC, COLOR_WHITE, COLOR_BLACK + 10);
    } else {
        snprintf(outbuf, maxout, "%c[%d;%dm%s%c[0m", ESC, attr, fgcolor, inbuf, ESC);
    }
    return outbuf;
}
コード例 #9
0
ファイル: snake.cpp プロジェクト: BartAdv/grasssnake
Snake::Snake(Point head, Dir dir, int length)
  : head(head)
{
  auto d = opposite(dir);
  for(int i = 0; i < length-1; i++)
    segments.push_back(d);
}
コード例 #10
0
// Opposite of a vector
ComplexVector operator-(const ComplexVector& first)
{
	ComplexVector opposite(first.n);
	for(int i=0; i<first.n; i++)
		opposite.v[i] = -first.v[i];
	return (opposite);
}
コード例 #11
0
ファイル: polygon2d.cpp プロジェクト: Amy1014/shape-packing
 static inline Sign point_is_in_half_plane(
     const vec2& p, const vec2& q1, const vec2& q2,
     bool invert
 ) {
     Sign result = orient(q1, q2, p) ;
     if(invert) {
         result = opposite(result) ;
     }
     return result ;
 }
コード例 #12
0
ファイル: SFMLMap.cpp プロジェクト: HurricaN/TD
void SFMLMap::flipCollAndCol(position where, int direction)
{
	flipColl(where,direction);
	bool c = getColl(where,direction);
	Color col= Color::Green;
	if(!c)
		col = Color::Red;
	grille.setCircleCol(where, direction, col);
	if(direction != TOURABLE)
		grille.setCircleCol(where+basic_dep[direction], opposite(direction), col);
}
コード例 #13
0
ファイル: term.c プロジェクト: kg6zgj/asterisk-1.8-current
static void check_fgcolor(int *fgcolor, int *attr)
{
    if (*fgcolor & 128) {
        *attr = ast_opt_light_background ? 0 : ATTR_BRIGHT;
        *fgcolor &= ~128;
    }

    if (ast_opt_light_background) {
        *fgcolor = opposite(*fgcolor);
    }
}
コード例 #14
0
ファイル: opposite.c プロジェクト: niki-lafee/dfh
int main() {

	stu *head;

	head = creat();
	print (head);
	opposite (head);
	print (head);

	return 0;

}
コード例 #15
0
ファイル: agent.cpp プロジェクト: aijunbai/reversi
char Agent::do_msg(char *msg)
{
	char reply = 0;
	switch(*msg){
		case BOARD_DESCRIPTION:
			reply = NO_NEED_TO_SEND;
			update(msg); break;
		case ACTION:
			reply = NEED_TO_SEND;
			act(msg); break;
		case WAIT:
			reply = NO_NEED_TO_SEND;
			puts(">>>> wait for one time"); break;
		case ONE_MORE_TIME:
			reply = NEED_TO_SEND;
			times_left(1, msg); break;
		case TWO_TIMES_LEFT:
			reply = NEED_TO_SEND;
			times_left(2, msg); break;
		case THREE_TIMES_LEFT:
			reply = NEED_TO_SEND;
			times_left(3,  msg); break;
		case RL_BLACK:
			reply = NO_NEED_TO_SEND; puts(">>>> I'm the Black");
			role = RL_BLACK; opp_role = opposite(role); break;
		case RL_WHITE:
			reply = NO_NEED_TO_SEND; puts(">>>> I'm the White");
			role = RL_WHITE; opp_role = opposite(role); break;
		case YOU_WIN:
			reply = FINISHED;
			puts(">>>> I win"); break;
		case YOU_LOSE:
			reply = FINISHED;
			puts(">>>> I lose"); break;
		case YOU_TIE:
			reply = FINISHED;
			puts(">>> We tie"); break;
	}
	return reply;
}
コード例 #16
0
/*
  returns number of bytes consumed
*/
int QtTelnetPrivate::parseIAC(const QByteArray &data)
{
    if (data.isEmpty())
        return 0;

    Q_ASSERT(uchar(data.at(0)) == Common::IAC);

    if (data.size() >= 3 && isOperation(data[1])) { // IAC, Operation, Option
        const uchar operation = data[1];
        const uchar option = data[2];
        if (operation == Common::WONT && option == Common::Logout) {
            q->close();
            return 3;
        }
        if (operation == Common::DONT && option == Common::Authentication) {
            if (loginp.isEmpty() && passp.isEmpty())
                emit q->loggedIn();
            nullauth = true;
        }
        if (replyNeeded(operation, option)) {
            bool allowed = allowOption(operation, option);
            sendCommand(opposite(operation, allowed), option);
            setMode(operation, option);
        }
        return 3;
    }
    if (data.size() >= 2 && isCommand(data[1])) { // IAC Command
        return 2;
    }

    QByteArray suboption = getSubOption(data);
    if (suboption.isEmpty())
        return 0;

    // IAC SB Operation SubOption [...] IAC SE
    switch (suboption[0]) {
    case Common::Authentication:
        parseSubAuth(suboption);
        break;
    case Common::TerminalType:
        parseSubTT(suboption);
        break;
    case Common::NAWS:
        parseSubNAWS(data);
        break;
    default:
        qWarning("QtTelnetPrivate::parseIAC: unknown suboption %d",
                 quint8(suboption.at(0)));
        break;
    }
    return suboption.size() + 4;
}
コード例 #17
0
ファイル: Hash.cpp プロジェクト: myluoxz/cgal
void test_edge_hash_and_null(const P& p)
{
  typedef boost::graph_traits<P> GT;
  typedef typename GT::halfedge_descriptor halfedge_descriptor;
  typedef typename GT::vertex_descriptor vertex_descriptor;
  typedef typename GT::face_descriptor face_descriptor;

  BOOST_FOREACH(halfedge_descriptor h, halfedges(p))
  {
    assert(
      hash_value( edge(h,p) ) ==
      hash_value( edge(opposite(h,p),p) ) );
  }
コード例 #18
0
ファイル: incident_vertices.cpp プロジェクト: 2php/cgal
OutputIterator
adjacent_vertices_V1(const Polyhedron& g,
                     vertex_descriptor vd,
                     OutputIterator out)
{
  typename GraphTraits::halfedge_descriptor hb = halfedge(vd,g), done(hb);
  do {
        *out++ = source(hb,g);
        hb = opposite(next(hb,g),g);
  } while(hb!= done);

  return out;
}
コード例 #19
0
static std::vector<SimpleEdge_3> getEdges(Polyhedron_3 P,
		std::map<int, int> &map)
{
	DEBUG_START;
	std::vector<bool> visited(P.size_of_halfedges());
	for (unsigned i = 0 ; i < visited.size(); ++i)
		visited[i] = false;
	std::cout << "getEdges: number of halfedges: " << P.size_of_halfedges()
		<< std::endl;

	std::vector<SimpleEdge_3> edges;
	P.initialize_indices();
	CGAL::Origin origin;

	for (auto &i : map)
		i.second = UNINITIALIZED_MAP_VALUE;

	for (auto I = P.halfedges_begin(), E = P.halfedges_end(); I != E; ++I)
	{
		if (visited[I->id])
			continue;
		SimpleEdge_3 edge;
		edge.A = I->vertex()->point() - origin;
		edge.B = I->opposite()->vertex()->point() - origin;
		edge.iForward = I->facet()->id;
		edge.iBackward = I->opposite()->facet()->id;
		// FIXME: Remember indices of planes, not planes themselves,
		// and fix structure for this.
		map[I->id] = map[I->opposite()->id] = edges.size();
		edges.push_back(edge);
		visited[I->id] = visited[I->opposite()->id] = true;
	}
	std::cout << "getEdges: number of edges: " << edges.size() << std::endl;
	ASSERT(edges.size() * 2 == P.size_of_halfedges());

	DEBUG_END;
	return edges;
}
コード例 #20
0
ファイル: GrafoNew (1).cpp プロジェクト: Jejugo/Graph-2
//Funcao que calcula o caminho minimo de um vertice a outro
int dijkstra(grafo *g, mapa m, int v, int v2){
    filaP *Q = NULL;
    int distance[100];      //vértice que armazena as distancias
    int parent[100];        //vertice que armazena os pais de cada vertice

    int i=1;
    while (i <= m.indiceVert){
        if (pegaVertRef(m, i) != NULL){
            if (i == v) {
                distance[i-1] = 0; //inicializa o vetor de distancias com 0 para o vertice inicial e INF para os demais
                parent[i-1] = 0;   //inicializa o vetor parent com 0 para o vertice inicial e INF para os demais
            } else {
                distance[i-1] = INF;
                parent[i-1] = INF;
            }
            Q = insertFilaP(Q, i, distance[i-1]);       //insere o vertice na fila de prioridades
        }
        i++;
    }

    int k = 0;
    while (k<g->nvertices){                     //para cada vertice
        int uI = retornaFilaP(Q);               //retorna o primeiro vertice da fila
        Q = removeFilaP(Q);                     //remove o vertice u da fila
        vertice *uR = pegaVertRef(m, uI);       //pega a referencia do vertice u
        incidencia *i = uR->lista;              //lista de incidencias do vertice u
        while (i != NULL){                      //para cada aresta da lista de incidencias do vertice u
            aresta *e = i->aresta;
            vertice *zR = opposite(g, uR, e);   //pega o vértice z oposto a u pela aresta e
            int zI = pegaVertInd(m, zR);        //pega o indentificador do vertice z
            if (distance[zI-1] > (distance[uI-1] + e->conteudo)){   //se z.distance > u.distance + e.weight
                distance[zI-1] = (distance[uI-1] + e->conteudo);    //z.distance = u.distance + e.weight
                parent[zI-1] = uI;                                  //z.parent = u
                if (Q != NULL){
                    Q = replaceKeyFilaP(Q, zI, distance[zI-1]);     //substitui a chave do vertice z na fila
                }
            }
            i = i->prox;    //vai para a proxima incidencia
        }
        k++;
    }

    //printf("%d\n", distance[v2-1]);
    //imprimeDijkstra(v, v2, parent, 0);
    return distance[v2-1];
}
コード例 #21
0
ファイル: frame.cpp プロジェクト: yannicklm/plee-the-bear
std::size_t ptb::frame::find_nearest_control
( const CurrentValue1& current_value_1, const OtherValue1& other_value_1,
  const CurrentValue2& current_value_2, const OtherValue2& other_value_2,
  bool reversed ) const
{
  if ( m_current_control == m_controls.size() )
    return 0;

  double min_1( std::numeric_limits<double>::max() );
  double min_2( std::numeric_limits<double>::max() );
  double opposite_1( std::numeric_limits<double>::max() );
  double opposite_2( std::numeric_limits<double>::max() );
  std::size_t result(m_current_control);
  std::size_t opposite(m_current_control);
  const bear::gui::visual_component* current = m_controls[m_current_control];

  for ( std::size_t i=0; i!=m_controls.size(); ++i )
    if ( i != m_current_control )
      {
        const double d1
          (std::abs(current_value_1(*current)-other_value_1(*m_controls[i])));
        double d2(current_value_2(*current) - other_value_2(*m_controls[i]));
        if ( reversed )
          d2 = -d2;

        if ( (d2 > 0) && ( (d1 < min_1)||( (d1 == min_1) && (d2 < min_2) ) ) )
            {
              min_1 = d1;
              min_2 = d2;
              result = i;
            }

        if ( (d2 < 0) &&
             ( (d2 < opposite_2)||((d2 == opposite_2) && (d1 < opposite_1)) ) )
          {
            opposite_1 = d1;
            opposite_2 = d2;
            opposite = i;
          }
      }

  if ( (m_current_control == result) && (m_current_control != opposite) )
    result = opposite;

  return result;
} // frame::find_nearest_control()
コード例 #22
0
void int_to_string(int integer, char *string, unsigned int base) {
	int i = 0, tmp;
	if (integer < 0) {												// Se è un numero negativo...
		integer = opposite(integer);								// ... ne calcoliamo l'opposto
		string[i] = '-';											// ... il primo carattere della stringa è -
		i++;														// ... aumentiamo il contatore della posizione nella stringa perché il primo carattere della stringa è dedicato al -
	}

	while (integer != 0) {											// Formula di conversione di un numero a una base b
		tmp = integer % base;

		// Per passare da un int a un char dobbiamo aggiungere 48, ma lo facciamo dopo il controllo sul resto, in modo da verificare la base

		if (tmp >= 10 && tmp < 36) {								// Se il resto è maggiore di 10 ma minore di 36, la base è > 10, quindi dobbiamo usare le lettere maiuscole
			tmp += 7;												// ... quindi aggiungiamo 7
		} 
		else if (tmp >= 36) {										// ... ma se il resto è maggiore di 36, la base è > 36, quindi dobbiamo usare le lettere minuscole
			tmp += 13;												// ... quindi aggiungiamo 13
		}

		tmp += 48;													// Per passare da un int a un char dobbiamo aggiungere 48

		string[i] = tmp;											// Salviamo il char nella stringa
		integer /= base;

		i++;														// Aumentiamo il contatore per passare al carattere successivo della stringa
	}

	if (string[0] == '-' && debug == 0) {
		printf("-");
	}

	i--;															// Dobbiamo diminuire di una unità i perché viene aumentata una volta inserito l'ultimo carattere per come è costruito il while
	
	if (debug == 0) {												// Se non siamo in debug mode stampa i risultati
		while (i+1 != 0) {											// Partiamo dall'ultimo carattere inserito stampiamo la stringa
			if (string[i] != '-') {
				printf("%c", string[i]);
			}
			i--;
		}

		printf("\n");
	}
}
コード例 #23
0
ファイル: Manifold_2.C プロジェクト: xyuan/IMPACT
/// Return the dihedral angle at the edge. If the edge is a border edge,
/// then return pi. Note that this must be called after update_bd_normals
/// has been called.
double Halfedge::dihedral_angle() const {
  const double pi=3.14159265358979;
  if ( is_physical_border()) return pi;

  Halfedge hopp = opposite();
  if ( hopp.is_physical_border()) return pi;

  Vector_3<Real> normals[2] = { normal(), hopp.normal() };

  double cos_a = normals[0]*normals[1] 
    / std::sqrt( (normals[0]*normals[0])*(normals[1]*normals[1]));

  // Resolve roundoff error
  if ( cos_a>1) cos_a=1;
  if ( cos_a<-1) cos_a=-1;

  return std::acos( cos_a);
}
コード例 #24
0
ファイル: expand.c プロジェクト: kkaempf/core
/**
 * Check if #str contains one and only one variable expansion of #vtype kind
 * (it's usually either '$' or '@'). It can contain nested expansions which
 * are not checked properly. Examples:
 *     true:  "$(whatever)", "${whatever}", "$(blah$(blue))"
 *     false: "$(blah)blue", "blah$(blue)", "$(blah)$(blue)", "$(blah}"
 */
bool IsNakedVar(const char *str, char vtype)
{
    size_t len = strlen(str);
    char last  = len > 0 ? str[len-1] : 0;

    if (len < 3
        || str[0] != vtype
        || (str[1] != '(' && str[1] != '{')
        || last != opposite(str[1]))
    {
        return false;
    }

    /* TODO check if nesting happens correctly? Is it needed? */
    size_t count = 0;
    for (const char *sp = str; *sp != '\0'; sp++)
    {
        switch (*sp)
        {
        case '(':
        case '{':
            count++;
            break;
        case ')':
        case '}':
            count--;

            /* Make sure the end of the variable is the last character. */
            if (count == 0 && sp[1] != '\0')
            {
                return false;
            }

            break;
        }
    }

    if (count != 0)
    {
        return false;
    }

    return true;
}
コード例 #25
0
void printTreePnDn(pnsNode *node, Paper *paper)
{
    if(paper == NULL) return;
/*    safePrint(paper, " %d,%d/%d,%d/%d ", node->x, node->y, node->pn, node->dn, opposite(node->turn));
    safePrint(paper, "(");
    for(uint i=0;i<node->virtualChildren.size();i++)
        safePrint(paper, "/%d,%d/ ", node->virtualChildren[i].first, node->virtualChildren[i].second);
    for(uint i=0;i<node->actualChildren.size();i++)
        printTreePnDn(node->actualChildren[i], paper);
    safePrint(paper, ")");*/

    qDebug(" %d,%d/%d,%d/%d ", node->x, node->y, node->pn, node->dn, opposite(node->turn));
    qDebug("(");
    for(uint i=0;i<node->virtualChildren.size();i++)
        qDebug("/%d,%d/ ", node->virtualChildren[i].first, node->virtualChildren[i].second);
    for(uint i=0;i<node->actualChildren.size();i++)
        printTreePnDn(node->actualChildren[i], paper);
    qDebug(")");
}
コード例 #26
0
ファイル: test_graph_traits.cpp プロジェクト: efifogel/cgal
void test_halfedge_around_vertex_iterator(const Graph& g)
{
  CGAL_GRAPH_TRAITS_MEMBERS(Graph);
  vertex_iterator vit, vend;
  for(boost::tie(vit, vend) = vertices(g); vit != vend; ++vit) {
    halfedge_around_target_iterator havit, havend;
    for(boost::tie(havit, havend) = CGAL::halfedges_around_target(halfedge(*vit, g), g); 
        havit != havend; ++havit) {
      assert(target(*havit, g) == *vit);

      // check if we are really moving clockwise
      halfedge_around_target_iterator step = boost::next(havit);
      if(step != havend) {
        halfedge_descriptor stepd = *step;
        assert(stepd == opposite(next(*havit, g), g));
      }
    }
  }
}
コード例 #27
0
std::pair<double, double> Alan_Turing_AI::score_board(const Board& board, Color perspective, const Game_Result& move_result) const
{
    if(move_result.game_has_ended())
    {
        if(move_result.winner() == perspective)
        {
            return {1000.0, 1000.0};
        }
        else if(move_result.winner() == opposite(perspective))
        {
            return {-1000.0, -1000.0};
        }
        else
        {
            return {0.0, 0.0};
        }
    }

    return std::make_pair(material_value(board, perspective), position_play_value(board, perspective));
}
コード例 #28
0
/**
@brief		print a RES_ACK

Prints a snapshot of the status of the @b @@dev circular queue when AP sends or
receives an RES_ACK.

@param mld	the pointer to a mem_link_device instance
@param mst	the pointer to a mem_snapshot instance
@param dev	the pointer to a mem_ipc_device instance (IPC_FMT, etc.)
@param dir	the direction of communication (TX or RX)

@remark		When a RES_ACK is sent, the status of the RXQ in @b @@dev must
		be shown. On the contrary, the status of the TXQ in @b @@dev
		must be shown When a RES_ACK is received.
*/
void print_res_ack(struct mem_link_device *mld, struct mem_snapshot *mst,
		   struct mem_ipc_device *dev, enum direction dir)
{
#ifdef DEBUG_MODEM_IF_FLOW_CTRL
	struct link_device *ld = &mld->link_dev;
	struct modem_ctl *mc = ld->mc;
	enum dev_format id = dev->id;
	enum direction opp_dir = opposite(dir);	/* opposite direction */
	unsigned int qsize = get_size(cq(dev, opp_dir));
	unsigned int in = mst->head[id][opp_dir];
	unsigned int out = mst->tail[id][opp_dir];
	unsigned int usage = circ_get_usage(qsize, in, out);
	unsigned int space = circ_get_space(qsize, in, out);

	mif_info("RES_ACK: %s%s%s: %s_%s.%d "
		"{in:%u out:%u usage:%u space:%u}\n",
		ld->name, arrow(dir), mc->name, dev->name, q_dir(opp_dir),
		dev->req_ack_cnt[opp_dir], in, out, usage, space);
#endif
}
コード例 #29
0
ファイル: move_gen.cpp プロジェクト: YurkoFlisk/checkers
void MoveGenDefault::_find_deep_capture_queen(MoveList& moves, Move& move, int8_t row, int8_t column, bool(&captured)[8][8]) const
{
	static constexpr int d_row[4] = { 1, 1, -1, -1 }, d_column[4] = { 1, -1, 1, -1 };
	for (size_t dir = 0; dir < 4; ++dir)
	{
		bool capture_found = false;
		int r1 = row + d_row[dir], c1 = column + d_column[dir];
		for (; r1 < 7 && c1 < 7 && r1 > 0 && c1 > 0 && board[r1][c1].get_colour() != TURN &&
			!captured[r1][c1]; r1 += d_row[dir], c1 += d_column[dir])
			if (board[r1][c1].get_colour() == opposite(TURN))
			{
				capture_found = true;
				break;
			}
		if (!capture_found)
			continue;
		captured[r1][c1] = true;
		const int old = moves.size();
		for (int r2 = r1 + d_row[dir], c2 = c1 + d_column[dir]; r2 < 8 && c2 < 8 && r2 >= 0 && c2 >= 0 &&
			board[r2][c2].get_type() == PT_EMPTY; r2 += d_row[dir], c2 += d_column[dir])
		{
			move.add_step(Position(r2, c2));
			move.add_capture(std::make_pair(Position(r1, c1), board[r1][c1]));
			_find_deep_capture_queen<TURN>(moves, move, r2, c2, captured);
			move.pop_step();
			move.pop_capture();
		}
		if (old == moves.size()) // If in recursive calls we haven't found any move, then any move is a final capture in this direction and is one of possible captures
			for (int r2 = r1 + d_row[dir], c2 = c1 + d_column[dir]; r2 < 8 && c2 < 8 && r2 >= 0 && c2 >= 0 &&
				board[r2][c2].get_type() == PT_EMPTY; r2 += d_row[dir], c2 += d_column[dir])
			{
				move.add_step(Position(r2, c2));
				move.add_capture(std::make_pair(Position(r1, c1), board[r1][c1]));
				move.set_become(Piece(TURN == WHITE ? WHITE_QUEEN : BLACK_QUEEN));
				moves.emplace(move);
				move.pop_step();
				move.pop_capture();
			}
		captured[r1][c1] = false;
	}
}
コード例 #30
0
list<Direction> _302901087_C::convertFromMapPointsDistancesToDirectionsList(const Point& point, map<Point, int> map)
{
	list<Direction> res;
	Point curr = point;
	int distance = map[curr];
	while (distance > 0)
	{
		for (Direction d : directions)
		{
			Point tmp = curr.neighbour(d);
			if (map.find(tmp)!=map.end() && map[tmp] == distance - 1)
			{
				res.push_back(opposite(d));
				curr = tmp;
				distance--;
				break;
			}
		}
	}
	return res;
}