Пример #1
0
BOOL Board::canmove(int ipiece, int x, int y)
{
	if (x == 0 && y == 0) { return FALSE; }
	CRect candrect = piece(ipiece)->mPieceRect;
	candrect.OffsetRect(x,y);
	CRect intersection;
	// 1st check if moved piece is still on the board
	if (intersection.IntersectRect(mBoardRect, candrect)) {
		if (intersection != candrect) {
			return FALSE;
		}
	} else {
		return FALSE;
	}

	// now see if it's moving to a free space

	int i;
	for(i = 0 ; i < numpieces(); i++) {
		if (i != ipiece) {
			CRect prect = piece(i)->mPieceRect;
			BOOL r = intersection.IntersectRect(candrect, prect);
			if (r != 0) {
				return FALSE;
			}
		}
	}
	return TRUE;
}
Пример #2
0
std::string Move::algebraic() const {
    std::string temp;
    if (!data) {
        return "0000"; }
    temp += (from() & 7) + 'a';
    temp += (from() >> 3) + '1';
    temp += (to() & 7) + 'a';
    temp += (to() >> 3) + '1';
    if (isSpecial()) {
        if ((piece() & 7) < Pawn) {
            temp += " RBQN"[piece() & 7]; } }
    return temp; }
Пример #3
0
 void setPiece(const size_t& begin,const size_t& end,ulong p) 
 {
  CALL("setPiece(const size_t& begin,const size_t& end,ulong p)");
  (base &= (inversePieceMask[begin][end])) |= (p << (sizeInBits() - end - 1)); 
  
  ASSERT(piece(begin,end) == p);
 };
Пример #4
0
void VTKWriter::initializeOutput(int numParticles) {

	vtkFile = new VTKFile_t("UnstructuredGrid");

	// per point, we add type, position, velocity and force
	PointData pointData;
	DataArray_t mass(type::Float32, "mass", 1);
	DataArray_t velocity(type::Float32, "velocity", 3);
	DataArray_t forces(type::Float32, "force", 3);
	DataArray_t type(type::Int32, "type", 1);
	pointData.DataArray().push_back(mass);
	pointData.DataArray().push_back(velocity);
    pointData.DataArray().push_back(forces);
    pointData.DataArray().push_back(type);

	CellData cellData; // we don't have cell data => leave it empty

	// 3 coordinates
	Points points;
	DataArray_t pointCoordinates(type::Float32, "points", 3);
	points.DataArray().push_back(pointCoordinates);

	Cells cells; // we don't have cells, => leave it empty
	// for some reasons, we have to add a dummy entry for paraview
	DataArray_t cells_data(type::Float32, "types", 0);
	cells.DataArray().push_back(cells_data);

	PieceUnstructuredGrid_t piece(pointData, cellData, points, cells, numParticles, 0);
	UnstructuredGrid_t unstructuredGrid(piece);
	vtkFile->UnstructuredGrid(unstructuredGrid);
}
Пример #5
0
//ピースの取得
void select(int max)
{   
	int num,
		i,
		j,
		k,
		total;
	ifs>>num;
	stone piece(num);


	for(k=0;k<num;k++)
	{		
		for(i=0;i<8;i++)
		{
			for(j=0;j<8;j++)
			ifs>>piece[k].block[i][j];
			if(piece[k].block[i][j]=='1'){
				piece[k].zk++; 
				total++;
			}
			if(total==max)
			break;
			else if(total>max){
				total-=piece[k].zk;
			}

		}
	}


	
}
Пример #6
0
double evalBoard1(State *state)
{
    int x,y;
    double rval = 0.0;
    evals++;
    for(x=0;x<8;x++)
    for(y=0;y<8;y++)
    {
        if(x%2 != y%2 && !empty(state->board[y][x])) {
            if(king(state->board[y][x])) { /* King */
                if(((state->board[y][x] & White) && !player1) ||
                   (!(state->board[y][x] & White) && player1) )
                    rval+=2.0;
                else rval-=2.0;
            } 
            else if(piece(state->board[y][x])) { /* Piece */
                if(((state->board[y][x] & White) && !player1) ||
                   (!(state->board[y][x] & White) && player1) )
                    rval+=1.0;
                else rval-=1.0;
            }
        }    
    }
    //PrintBoard(state->board);
    //fprintf(stderr,"Value = %g\n",rval);
    return rval;
}
Пример #7
0
void UnimplementedOpcode::setFullDescription(RLMachine& machine) {
    ostringstream oss;
    oss << "Undefined: " << name_;

#ifndef NDEBUG
    if (has_parameters_) {
        bool first = true;
        oss << "(";
        for (std::vector<std::string>::const_iterator it = parameters_.begin();
                it != parameters_.end(); ++it) {
            if (!first) {
                oss << ", ";
            }
            first = false;

            // Take the binary stuff and try to get usefull, printable values.
            const char* start = it->c_str();
            try {
                boost::scoped_ptr<libReallive::ExpressionPiece> piece(
                    libReallive::get_complex_param(start));
                oss << piece->getDebugValue(machine);
            } catch (libReallive::Error& e) {
                // Any error throw here is a parse error.
                oss << "{RAW : " << libReallive::parsableToPrintableString(*it) << "}";
            }
        }
        oss << ")";
    }
#endif

    description = oss.str();
}
Пример #8
0
void test_strings() {
  {
    auto hello = w_string::build("hello");
    ok(hello == w_string("hello"), "hello");
    ok(hello.size() == 5, "there are 5 chars in hello");
    ok(!strcmp("hello", hello.c_str()),
       "looks nul terminated `%s` %" PRIu32,
       hello.c_str(),
       strlen_uint32(hello.c_str()));
  }

  {
    w_string_piece piece("hello");
    ok(piece.size() == 5, "piece has 5 char size");
    auto hello = w_string::build(piece);
    ok(hello.size() == 5, "hello has 5 char size");
    ok(!strcmp("hello", hello.c_str()), "looks nul terminated");
  }

  {
    char foo[] = "foo";
    auto str = w_string::build(foo);
    ok(str.size() == 3, "foo has 3 char size");
    ok(!strcmp("foo", foo), "foo matches");
  }
}
Пример #9
0
static w_string parse_suffix(const json_ref& ele) {
  if (!ele.isString()) {
    throw QueryParseError("'suffix' must be a string or an array of strings");
  }

  auto str = json_to_w_string(ele);

  return str.piece().asLowerCase(str.type());
}
Пример #10
0
void StringTrimRight(std::string* str, const StringPiece& trim_value)
{
    StringPiece piece(*str);
    size_t end_pos = piece.find_last_not_of(trim_value);
    if (end_pos != std::string::npos) {
        *str = str->substr(0, end_pos + 1);
    } else {
        str->clear();
    }
}
Пример #11
0
void StringTrimLeft(std::string* str, const StringPiece& trim_value)
{
    StringPiece piece(*str);
    size_t start_pos = piece.find_first_not_of(trim_value);
    if (start_pos != std::string::npos) {
        *str = str->substr(start_pos);
    } else {
        str->clear();
    }
}
Пример #12
0
QString CrazyhouseBoard::sanMoveString(const Move& move)
{
	Piece piece(pieceAt(move.sourceSquare()));
	QVarLengthArray<int> squares;

	normalizePieces(piece, squares);
	QString str(WesternBoard::sanMoveString(move));
	restorePieces(piece, squares);

	return str;
}
Пример #13
0
static void DoStringTrim(StringType* str, const StringPiece& trim_value)
{
    StringPiece piece(*str);
    size_t start_pos = piece.find_first_not_of(trim_value);
    size_t end_pos = piece.find_last_not_of(trim_value);
    if (start_pos == std::string::npos)
    {
        str->clear();
        return;
    }
    *str = str->substr(start_pos, end_pos - start_pos + 1);
}
Пример #14
0
void Board::move(int ipiece, int x, int y)
{
	if (x > 0) x = 1;
	if (x < 0) x = -1;
	if (y > 0) y = 1;
	if (y < 0) y = -1;

	if (canmove(ipiece, (x * pper()) + pborder(), (y*pper())+pborder())
		|| mWon)
		piece(ipiece)->mov(x,y);

}
Пример #15
0
std::string Move::string() const {
    std::string temp;
    if (!data) {
        return "null"; }
    temp += (const char*[]) {"","R","B","Q","N","","K" }[piece() & 7];
    temp += (from() & 7) + 'a';
    temp += (from() >> 3) + '1';
    temp += capture() ? 'x' : '-';
    temp += (to() & 7) + 'a';
    temp += (to() >> 3) + '1';
    if (isSpecial()) {
        if ((piece() & 7) < Pawn) {
            temp += " RBQN"[piece() & 7];
            temp = temp.substr(1); }
        else if ((piece() & 7) == King) {
            if ((to() & 7) == 6)
                return "O-O";
            else
                return "O-O-O"; }
        else
            temp += " ep"; }
    return temp; }
Пример #16
0
ErrorStack NumaNodeMemory::initialize_log_buffers_memory() {
  uint64_t size_per_core_ = static_cast<uint64_t>(engine_->get_options().log_.log_buffer_kb_) << 10;
  uint64_t private_total = (cores_ * size_per_core_);
  LOG(INFO) << "Initializing log_buffer_memory_. total_size=" << private_total;
  CHECK_ERROR(allocate_huge_numa_memory(private_total, &log_buffer_memory_));
  LOG(INFO) << "log_buffer_memory_ allocated. addr=" << log_buffer_memory_.get_block();
  for (auto ordinal = 0; ordinal < cores_; ++ordinal) {
    AlignedMemorySlice piece(&log_buffer_memory_, size_per_core_ * ordinal, size_per_core_);
    LOG(INFO) << "log_buffer_piece[" << ordinal << "] addr=" << piece.get_block();
    log_buffer_memory_pieces_.push_back(piece);
  }

  return kRetOk;
}
Пример #17
0
vector<shared_ptr<Piece>> MapConfigReader::getPiecesFromEtage(pugi::xml_node etageNode) const
{
    vector<shared_ptr<Piece>> pieces;

    pugi::xml_node piecesNodes = etageNode.child("Pieces");

    for (pugi::xml_node pieceNode = piecesNodes.first_child(); pieceNode; pieceNode = pieceNode.next_sibling())
    {
        int nbAccessEtageSup = pieceNode.attribute("nbAccessEtageSup").as_int();
        Architecture archi = getArchitectureFromNode(pieceNode);
        Piece piece(archi, nbAccessEtageSup);
        pieces.push_back(std::make_shared<Piece>(piece));
    }

    return pieces;
}
void Player::read(const QJsonObject &json)
{

    ID = json["id"].toInt();
    name = json["id"].toString();
    active_player_pieces = json["active-player-pieces"].toInt();
    is_bot = json["is-bot"].toInt();
    start_move = json["start-move"].toInt();
    finish_move = json["finish_move"].toInt();

    QJsonArray pieces_array = json["pieces"].toArray();
    for (int i = 0; i < 4; i++)
    {
        QJsonObject pieceObject = pieces_array[i].toObject();
        Piece piece(i,this->ID);
        piece.read(pieceObject);
        piece_list[i] = new Piece(piece);
    }
}
Пример #19
0
/* Determines all of the legal moves possible for a given state */
int FindLegalMoves(struct State *state)
{
    int x, y, i;
    char move[12], board[8][8];

    memset(move,0,12*sizeof(char));
    jumpptr = numLegalMoves = 0;
    memcpy(board,state->board,64*sizeof(char));

    /* Loop through the board array, determining legal moves/jumps for each piece */
    for(i=1; i<=32; ++i)
    {
        NumberToXY(i, &x, &y);

        if(color(board[y][x]) == state->player && !empty(board[y][x])) 
        {
            if(king(board[y][x])) { /* King */
                move[0] = number(board[y][x])+1;
                FindKingJump(state->player,board,move,1,x,y);
                if(!jumpptr) FindKingMoves(board,x,y);
            } 
            else if(piece(board[y][x])) { /* Piece */
                move[0] = number(board[y][x])+1;
                FindJump(state->player,board,move,1,x,y);
                if(!jumpptr) FindMoves(state->player,board,x,y);    
            }
        }    
    }
    if(jumpptr) {
        for(x=0; x<jumpptr; x++) 
            for(y=0; y<12; y++) 
                state->movelist[x][y] = jumplist[x][y];
        state->numLegalMoves = jumpptr;
    } 
    else {
        for(x=0; x<numLegalMoves; x++) 
            for(y=0; y<12; y++) 
                state->movelist[x][y] = movelist[x][y];
        state->numLegalMoves = numLegalMoves;
    }
    return (jumpptr+numLegalMoves);
}
Пример #20
0
Move CrazyhouseBoard::moveFromSanString(const QString& str)
{
	if (str.isEmpty())
		return Move();

	Piece piece(pieceFromSymbol(str.at(0)));
	if (piece.isValid())
	{
		piece.setSide(sideToMove());
		QVarLengthArray<int> squares;

		normalizePieces(piece, squares);
		Move move(WesternBoard::moveFromSanString(str));
		restorePieces(piece, squares);

		return move;
	}

	return WesternBoard::moveFromSanString(str);
}
Пример #21
0
void VTKWriter::initializeOutput(int numParticles) {
	vtkFile = new VTKFile_t("UnstructuredGrid");

	// per point, we add mass, velocity, force, type and stress
	// and in DEBUG mode the id of the molecules
	PointData pointData;
	DataArray_t mass(type::Float32, "mass", 1);
	DataArray_t velocity(type::Float32, "velocity", 3);
	DataArray_t forces(type::Float32, "force", 3);
	DataArray_t type(type::Int32, "type", 1);
	DataArray_t stress(type::Float32, "stress", 1);
	DataArray_t flag(type::Int32, "flag", 1);
	pointData.DataArray().push_back(mass);
	pointData.DataArray().push_back(velocity);
    pointData.DataArray().push_back(forces);
    pointData.DataArray().push_back(type);
    pointData.DataArray().push_back(stress);
    pointData.DataArray().push_back(flag);

#ifdef DEBUG
    DataArray_t id(type::Int32, "id", 1);
    pointData.DataArray().push_back(id);
#endif

	CellData cellData; // we don't have cell data => leave it empty

	// 3 coordinates
	Points points;
	DataArray_t pointCoordinates(type::Float32, "points", 3);
	points.DataArray().push_back(pointCoordinates);

	Cells cells; // we don't have cells, => leave it empty
	// for some reasons, we have to add a dummy entry for paraview
	DataArray_t cells_data(type::Float32, "types", 0);
	cells.DataArray().push_back(cells_data);

	PieceUnstructuredGrid_t piece(pointData, cellData, points, cells, numParticles, 0);
	UnstructuredGrid_t unstructuredGrid(piece);
	vtkFile->UnstructuredGrid(unstructuredGrid);
}
Пример #22
0
void VideoBuffer::add_piece(int index, boost::shared_array<char> data, int size)
				throw(Exception) {
	if (index >= 0 && index < ((int) m_pieces.size()) && data && size > 0) {
		boost::shared_ptr<Piece> piece(new Piece(index, data, size));
		bool is_next_piece;

		{
			boost::lock_guard<boost::mutex> lock(m_mutex);
			m_pieces[index] = piece;

			is_next_piece = (index == m_next_piece_index);
		}

		if (is_next_piece) {
			m_condition.notify_all();
		}

	} else {
		throw Exception("Invalid piece: " +
				boost::lexical_cast<std::string>(index) + ", " +
				boost::lexical_cast<std::string>(int(data.get())) + ", " +
				boost::lexical_cast<std::string>(size));
	}
}
Пример #23
0
double evalBoard2(State *currBoard)
{
    int y,x;
    double score=0.0;

    evals++;
    for(y=0; y<8; y++)
    for(x=0; x<8; x++)
    {
         if(king(currBoard->board[y][x]))
         {
             //if(color(currBoard->board[y][x]) == White) score += 2.0;
             if(currBoard->board[y][x] & White) score += 2.0;
             else score -= 2.0;
         }
         else if(piece(currBoard->board[y][x]))
         {
             if(currBoard->board[y][x] & White) score += 1.0;
             else score -= 1.0;
         }
    }

    return currBoard->player==1 ? -score : score;
}
Пример #24
0
void Game::play()
{
	long maxp = gameSettings->getMaxp();
	long maxl = gameSettings->getMaxl();
	long maxg = gameSettings->getMaxg();
	int level = gameSettings->getLevel();
	int preview = gameSettings->getPreview();
	int stat = gameSettings->getStat();
	int size = gameSettings->getSize();
	int sliding = gameSettings->getSliding();
	int delay = gameSettings->getDelay();
	int animate = gameSettings->getAnimate();
	int exit = gameSettings->getExit();
	int pieceStartX = gameSettings->getPieceStartX();
	int frameRateDelay = gameSettings->getFrameRateDelay();
	int nextPiece = 0;
	int viewBoard = gameSettings->getViewBoard();
	int stepMode = gameSettings->getStepMode();
	milisec1 = GetTickCount();
	milisec2 = GetTickCount();
	seconds = time(NULL);

	if (strlen(gameSettings->getWgameFilename()) != 0)
	{
		if (wGameFile.open(gameSettings->getWgameFilename()))
		{
			cout << "Could not open the file  \"" << gameSettings->getWgameFilename() << "\"" << endl;

			return;
		}
	}

	if (strlen(gameSettings->getRgameFilename()) != 0)
	{
		if (rGameFile.open(gameSettings->getRgameFilename()))
		{
			cout << "Could not open the file  \"" << gameSettings->getRgameFilename() << "\"" << endl;

			return;
		}
	}

	if (strlen(gameSettings->getWhtmlFilename()) != 0)
	{
		wHtml.open(gameSettings->getWhtmlFilename());

		if (!wHtml.good())
		{
			cout << "Could not open the file  \"" << gameSettings->getWhtmlFilename() << "\"" << endl;

			return;
		}
	}

  board = new Board(gameSettings->getWidth(), gameSettings->getHeight(), sliding, pieceStartX);

	Piece setStaticInitializersPiece(board, 1, sliding, 1);

	Player *player = new Player(board);

	Random random = Random(gameSettings->getSeed());
	GameInfo gameInfo(maxCntblockstat);

  writeTmpFile(board);

	double equity = player->evaluate();
	double maxDiff = 0;

	int pieces[10];

	if (preview > 1)
		pieces[0] = random.getRandomP();

	pieces[1] = 0;
	pieces[2] = 0;
	pieces[3] = 0;
	pieces[4] = 0;
	pieces[5] = 0;
	pieces[6] = 0;
	pieces[7] = 0;
	pieces[8] = 0;
	pieces[9] = 0;

	if (wGameFile.isOpen())
	{
		// 1. Version of the file
		wGameFile.writeShort(1);													// # Version (short)
		
		// 2. Header
		wGameFile.writeShort(DATA_HEADER);								// # Type of block
		wGameFile.writeShort(1);													// # Version
		wGameFile.writeShort(gameSettings->getWidth());		// # Width (short)
		wGameFile.writeShort(gameSettings->getHeight());	// # Height (short)
		wGameFile.writeInt(gameSettings->getSeed());			// # Seed (int)
		wGameFile.writeByte(gameSettings->getLevel());		// # Level (byte)
		wGameFile.writeByte(gameSettings->getPreview());	// # Preview (byte)
		wGameFile.writeByte(pieces[0]);      							// # Piece (byte)
	}

	while ((maxg==0 && maxl==0 && maxp==0) || 
		     ((maxg > 0 && games < maxg) ||
		      (maxl > 0 && totalLines < maxl) ||
				  (maxp > 0 && totalPieces < maxp)))
	{
		if (exit == 1 || gameSettings->getExit() == 1)
			break;

		//-------------------------------------------
		if (stepMode != gameSettings->getStepMode()) {
			stepMode = gameSettings->getStepMode();
			initTime();
		}
		
		if (level != gameSettings->getLevel()) {
			level = gameSettings->getLevel();
			initTime();
		}

		if (sliding != gameSettings->getSliding())
		{
			sliding = gameSettings->getSliding();
			board->setSliding(sliding);
			initTime();
		}

		if (preview != gameSettings->getPreview())
		{
			preview = gameSettings->getPreview();

			if (preview == 1)
				pieces[1] = 0;
			else
			{
				if (nextPiece == 0)
					nextPiece = pieces[1] = random.getRandomP();
				else
					pieces[1] = nextPiece;
			}

			initTime();
		}

		if (animate != gameSettings->getAnimate()) {
			animate = gameSettings->getAnimate();
			initTime();
		}

		if (delay != gameSettings->getDelay()) {
			delay = gameSettings->getDelay();
			initTime();
		}

		if (frameRateDelay != gameSettings->getFrameRateDelay()) {
			frameRateDelay = gameSettings->getFrameRateDelay();
			initTime();
		}

		if (viewBoard != gameSettings->getViewBoard()) {
			viewBoard = gameSettings->getViewBoard();
			initTime();
		}

		while (gameSettings->isPause())
			::Sleep(10);

		if (board->getWidth() != gameSettings->getWidth())
		{
			delete board;
			pieceStartX = gameSettings->getPieceStartX();
			board = new Board(gameSettings->getWidth(), gameSettings->getHeight(), sliding, pieceStartX);
			Piece setStaticInitializersPiece(board, 1, sliding, 1);			
		}
		//-------------------------------------------

		if (preview > 1)
			nextPiece = pieces[1] = random.getRandomP();
		else
			pieces[0] = random.getRandomP();

		if (wGameFile.isOpen())
			wGameFile.writeByte(pieces[1]);									// # Piece

		Piece bestPiece(board, pieces[0]);


		gameObserverList.notify(board, 
														&gameInfo, 
														pieces[0], 
														pieces[1], 
														1, 
														milisec1,
														milisec2,
														cntblockstat, 
														games,
														cntPieces,
														cntLines,
														totalMoves,
														totalSlided,
														totalLines,
														totalLines2,
														totalPieces,
														totalPieces2,
														minLines,
														maxLines,
														linesPerGame);


		if (!animate)
			::Sleep(delay*10);

		int playAgain;
		Move *bestMove;
		MoveList *moveList;

		do
		{
			playAgain = 0;
			gameSettings->setIsThinking();

			if (animate != gameSettings->getAnimate()) {
				animate = gameSettings->getAnimate();
				initTime();
			}

			bestMove = player->play(pieces, level, preview, animate, &gameObserverList);

			if (bestMove > 0)
				bestPiece.set(bestMove->getV(), bestMove->getX(), bestMove->getY(), bestMove->getClearedLines());

			gameSettings->setIsNotThinking();

			moveList = board->getMoveList(level);

			gameObserverList.notify(moveList);

			while (gameSettings->isStepModeOn() && gameSettings->isStepWait())
			{
				if (level != gameSettings->getLevel()) {
					level = gameSettings->getLevel();
					initTime();
					playAgain = 1;
					break;
				}

				if (preview != gameSettings->getPreview())
				{
					preview = gameSettings->getPreview();

					if (preview == 1)
						pieces[1] = 0;
					else
					{
						if (nextPiece == 0)
							nextPiece = pieces[1] = random.getRandomP();
						else
							pieces[1] = nextPiece;
					}

					initTime();
					playAgain = 1;

					gameObserverList.notify(board, 
																	&gameInfo, 
																	pieces[0], 
																	pieces[1], 
																	1, 
																	milisec1,
																	milisec2,
																	cntblockstat, 
																	games,
																	cntPieces,
																	cntLines,
																	totalMoves,
																	totalSlided,
																	totalLines,
																	totalLines2,
																	totalPieces,
																	totalPieces2,
																	minLines,
																	maxLines,
																	linesPerGame);



					break;
				}

				if (sliding != gameSettings->getSliding() && bestMove > 0)
				{
					sliding = gameSettings->getSliding();
					board->setSliding(sliding);

					initTime();
					playAgain = 1;
					break;
				}

				::Sleep(10);
			}
		} while (playAgain);

		if (gameSettings->isStepModeOn())
			gameSettings->setStepWait();

		if (!animate && bestMove > 0)
		{
			bestPiece.setPiece();

			if (bestPiece.getClearedLines() > 0)
				board->clearLines(bestPiece.getY(), bestPiece.getHeight());
		}

		Move *move;
		int index = 0;

		int length = moveList->getLength();

		totalMoves += length;

		if (animate && bestMove > 0)
		{
			// Animate the moves.
			MovePath *movePath = board->getMovePath(level);
			MovePathStep *s = movePath->getPath(bestMove->getV(), bestMove->getX(), bestMove->getY());

			int skipFirst = 0;

			int prevy = -1;

			while (s > 0)
			{
				//----
				// Calculate the number of steps for the current line (y value).
				MovePathStep *s1 = s;
				int y1 = s1->y;
				int cnt;

				if (prevy != y1)
				{
					cnt = 0;

					while (s1 > 0 && s1->y == y1) {
						cnt++;
						s1 = s1->next;
					}
					prevy = y1;
				}
				//----
				
				if (animate != gameSettings->getAnimate())
					break;

				if (delay != gameSettings->getDelay())
					delay = gameSettings->getDelay();

				int v = s->v;
				int x = s->x;
				int y = s->y;

				Piece piece(board, bestPiece.getP());
				piece.setPiece(v, x, y);

				if (skipFirst)
					gameObserverList.notify(board, 
																	&gameInfo, 
																	pieces[0], 
																	pieces[1], 
																	0, 
																	milisec1,
																	milisec2,
																	cntblockstat, 
																	games,
																	cntPieces,
																	cntLines,
																	totalMoves,
																	totalSlided,
																	totalLines,
																	totalLines2,
																	totalPieces,
																	totalPieces2,
																	minLines,
																	maxLines,
																	linesPerGame);

				if (gameSettings->isSlidingOn())
					::Sleep((double)delay / cnt);
				else
					::Sleep((double)delay);

				piece.clearPiece();
				skipFirst = 1;
				s = s->next;

				while (gameSettings->isPause())
					::Sleep(10);
			}

			bestPiece.setPiece();

			if (bestPiece.getClearedLines() > 0)
			{
				int clearedLinesBits = board->getClearedLines(bestPiece.getY(), bestPiece.getHeight());

				for (int n=0; n<4; n++)
				{
					board->flashLines(bestPiece.getY(), bestPiece.getHeight(), clearedLinesBits);
					
					if (n<3)
					{
						gameObserverList.notify(board, 
																		&gameInfo, 
																		pieces[0], 
																		pieces[1], 
																		0, 
																		milisec1,
																		milisec2,
																		cntblockstat, 
																		games,
																		cntPieces,
																		cntLines,
																		totalMoves,
																		totalSlided,
																		totalLines,
																		totalLines2,
																		totalPieces,
																		totalPieces2,
																		minLines,
																		maxLines,
																		linesPerGame);

						if (delay > 0)
						{
							if (delay >= 50)
								::Sleep(150);
							else
								::Sleep(150-(50-delay)*2);
						}
					}
				}

				board->clearLines(bestPiece.getY(), bestPiece.getHeight());
			}
		}

		cntPieces++;
		totalPieces++;
		
		if (bestMove > 0)
			totalSlided += bestMove->isSlided();

		// Log the moves
		if (wGameFile.isOpen())
		{
			wGameFile.writeShort(length);											// # Number of legal moves.
			wGameFile.writeByte(bestPiece.getV());						// # V
			wGameFile.writeShort(bestPiece.getX());						// # X
			wGameFile.writeShort(bestPiece.getY());						// # Y

			move = moveList->getFirstMove();

			while (move != 0)
			{																									// Move:
				wGameFile.writeByte(move->getV());							// # V
				wGameFile.writeShort(move->getX());							// # X
				wGameFile.writeShort(move->getY());							// # Y

				for (int i=preview; i<=level; i++)							// Equity (e.g):
					wGameFile.writeFloat(move->getEquity(i));			// L2, L3, L4

				move = moveList->getNextMove();
			}
		}

		if (preview > 1)
			pieces[0] = pieces[1];

  	int clearedLines = bestPiece.getClearedLines();

  	if (bestMove == 0) 
		{
  		games++;
  		
			linesPerGame = totalLines/games;
		}
		else
		{
			cntLines += clearedLines;
			totalLines += clearedLines;

			cntBlock += 4 - clearedLines * board->getWidth();

			if (DEBUG == 0)
			{
				int xxx = cntBlock/4;
				if (xxx < maxCntblockstat)
					cntblockstat[xxx]++;
			}
		}

  	if (cntLines > maxLines)
  		maxLines = cntLines;

		if (bestMove == 0)
		{
  		if (cntLines < minLines || minLines==-1)
  			minLines = cntLines;
			
			cntBlock = 0;
			cntPieces = 0;
  		cntLines = 0;
		  board->clear();
			pieces[0] = random.getRandomP();
		}
	}

	delete board;
	delete player;

	if (wGameFile.isOpen())
	{
		wGameFile.writeByte(END_PIECE);				// # Piece
		wGameFile.close();
	}

	if (rGameFile.isOpen() && strlen(gameSettings->getWhtmlFilename()) > 0)
	{
		readGame(maxp, size);
		rGameFile.close();
	}

	gameSettings->setExit(2);
}
Error EditorTextureImportPlugin::import2(const String& p_path, const Ref<ResourceImportMetadata>& p_from,EditorExportPlatform::ImageCompression p_compr, bool p_external){



	ERR_FAIL_COND_V(p_from->get_source_count()==0,ERR_INVALID_PARAMETER);

	Ref<ResourceImportMetadata> from=p_from;

	Ref<ImageTexture> texture;
	Vector<Ref<AtlasTexture> > atlases;
	bool atlas = from->get_option("atlas");
	bool large = from->get_option("large");

	int flags=from->get_option("flags");
	int format=from->get_option("format");
	float quality=from->get_option("quality");

	uint32_t tex_flags=0;

	if (flags&EditorTextureImportPlugin::IMAGE_FLAG_REPEAT)
		tex_flags|=Texture::FLAG_REPEAT;
	if (flags&EditorTextureImportPlugin::IMAGE_FLAG_FILTER)
		tex_flags|=Texture::FLAG_FILTER;
	if (!(flags&EditorTextureImportPlugin::IMAGE_FLAG_NO_MIPMAPS))
		tex_flags|=Texture::FLAG_MIPMAPS;
	if (flags&EditorTextureImportPlugin::IMAGE_FLAG_CONVERT_TO_LINEAR)
		tex_flags|=Texture::FLAG_CONVERT_TO_LINEAR;
	if (flags&EditorTextureImportPlugin::IMAGE_FLAG_USE_ANISOTROPY)
		tex_flags|=Texture::FLAG_ANISOTROPIC_FILTER;

	print_line("path: "+p_path+" flags: "+itos(tex_flags));
	float shrink=1;
	if (from->has_option("shrink"))
		shrink=from->get_option("shrink");

	if (large) {
		ERR_FAIL_COND_V(from->get_source_count()!=1,ERR_INVALID_PARAMETER);

		String src_path = EditorImportPlugin::expand_source_path(from->get_source_path(0));


		int cell_size=from->get_option("large_cell_size");
		ERR_FAIL_COND_V(cell_size<128 || cell_size>16384,ERR_CANT_OPEN);

		EditorProgress pg("ltex","Import Large Texture",3);

		pg.step("Load Source Image",0);
		Image img;
		Error err = ImageLoader::load_image(src_path,&img);
		if (err) {
			return err;
		}

		pg.step("Slicing",1);

		Map<Vector2,Image> pieces;
		for(int i=0;i<img.get_width();i+=cell_size) {
			int w = MIN(img.get_width()-i,cell_size);
			for(int j=0;j<img.get_height();j+=cell_size) {
				int h = MIN(img.get_height()-j,cell_size);

				Image piece(w,h,0,img.get_format());
				piece.blit_rect(img,Rect2(i,j,w,h),Point2(0,0));
				if (!piece.is_invisible()) {
					pieces[Vector2(i,j)]=piece;
					//print_line("ADDING PIECE AT "+Vector2(i,j));
				}
			}
		}

		Ref<LargeTexture> existing;
		if (ResourceCache::has(p_path)) {
			existing = ResourceCache::get(p_path);
		}

		if (existing.is_valid()) {
			existing->clear();
		} else {
			existing = Ref<LargeTexture>(memnew( LargeTexture ));
		}

		existing->set_size(Size2(img.get_width(),img.get_height()));
		pg.step("Inserting",2);

		for (Map<Vector2,Image>::Element *E=pieces.front();E;E=E->next()) {

			Ref<ImageTexture> imgtex = Ref<ImageTexture>( memnew( ImageTexture ) );
			imgtex->create_from_image(E->get(),tex_flags);
			_process_texture_data(imgtex,format,quality,flags,p_compr,tex_flags,shrink);
			existing->add_piece(E->key(),imgtex);
		}

		if (!p_external) {
			from->set_editor(get_name());
			existing->set_path(p_path);
			existing->set_import_metadata(from);
		}
		pg.step("Saving",3);

		err = ResourceSaver::save(p_path,existing);
		if (err!=OK) {
			EditorNode::add_io_error("Couldn't save large texture: "+p_path);
			return err;
		}

		return OK;


	} else if (atlas) {

		//prepare atlas!
		Vector< Image > sources;
		Vector< Image > tsources;
		bool alpha=false;
		bool crop = from->get_option("crop");

		EditorProgress ep("make_atlas","Build Atlas For: "+p_path.get_file(),from->get_source_count()+3);

		print_line("sources: "+itos(from->get_source_count()));

		for(int i=0;i<from->get_source_count();i++) {

			String path = EditorImportPlugin::expand_source_path(from->get_source_path(i));
			String md5 = FileAccess::get_md5(path);
			from->set_source_md5(i,FileAccess::get_md5(path));
			ep.step("Loading Image: "+path,i);
			print_line("source path: "+path+" md5 "+md5);
			Image src;
			Error err = ImageLoader::load_image(path,&src);
			if (err) {
				EditorNode::add_io_error("Couldn't load image: "+path);
				return err;
			}

			if (src.detect_alpha())
				alpha=true;

			tsources.push_back(src);
		}
		ep.step("Converting Images",sources.size());

		int base_index=0;


		Map<uint64_t,int> source_md5;
		Map<int,List<int> > source_map;

		for(int i=0;i<tsources.size();i++) {

			Image src = tsources[i];

			if (alpha) {
				src.convert(Image::FORMAT_RGBA);
			} else {
				src.convert(Image::FORMAT_RGB);
			}

			DVector<uint8_t> data = src.get_data();
			MD5_CTX md5;
			DVector<uint8_t>::Read r=data.read();
			MD5Init(&md5);
			int len=data.size();
			for(int j=0;j<len;j++) {
				uint8_t b = r[j];
				b>>=2; //to aid in comparing
				MD5Update(&md5,(unsigned char*)&b,1);
			}
			MD5Final(&md5);
			uint64_t *cmp = (uint64_t*)md5.digest; //less bits, but still useful for this

			tsources[i]=Image(); //clear

			if (source_md5.has(*cmp)) {
				int sidx=source_md5[*cmp];
				source_map[sidx].push_back(i);
				print_line("REUSING "+from->get_source_path(i));

			} else {
				int sidx=sources.size();
				source_md5[*cmp]=sidx;
				sources.push_back(src);
				List<int> sm;
				sm.push_back(i);
				source_map[sidx]=sm;

			}


		}

		//texturepacker is not really good for optimizing, so..
		//will at some point likely replace with my own
		//first, will find the nearest to a square packing
		int border=1;

		Vector<Size2i> src_sizes;
		Vector<Rect2> crops;

		ep.step("Cropping Images",sources.size()+1);

		for(int j=0;j<sources.size();j++) {

			Size2i s;
			if (crop) {
				Rect2 crop = sources[j].get_used_rect();
				print_line("CROP: "+crop);
				s=crop.size;
				crops.push_back(crop);
			} else {

				s=Size2i(sources[j].get_width(),sources[j].get_height());
			}
			s+=Size2i(border*2,border*2);
			src_sizes.push_back(s); //add a line to constraint width
		}

		Vector<Point2i> dst_positions;
		Size2i dst_size;
		EditorAtlas::fit(src_sizes,dst_positions,dst_size);

		print_line("size that workeD: "+itos(dst_size.width)+","+itos(dst_size.height));

		ep.step("Blitting Images",sources.size()+2);

		bool blit_to_po2=tex_flags&Texture::FLAG_MIPMAPS;
		int atlas_w=dst_size.width;
		int atlas_h=dst_size.height;
		if (blit_to_po2) {
			atlas_w=nearest_power_of_2(dst_size.width);
			atlas_h=nearest_power_of_2(dst_size.height);
		}
		Image atlas;
		atlas.create(atlas_w,atlas_h,0,alpha?Image::FORMAT_RGBA:Image::FORMAT_RGB);


		atlases.resize(from->get_source_count());

		for(int i=0;i<sources.size();i++) {

			int x=dst_positions[i].x;
			int y=dst_positions[i].y;

			Size2 sz = Size2(sources[i].get_width(),sources[i].get_height());

			Rect2 region;
			Rect2 margin;

			if (crop && sz!=crops[i].size) {
				Rect2 rect = crops[i];
				rect.size=sz-rect.size;
				region=Rect2(x+border,y+border,crops[i].size.width,crops[i].size.height);
				margin=rect;
				atlas.blit_rect(sources[i],crops[i],Point2(x+border,y+border));
			} else {
				region=Rect2(x+border,y+border,sz.x,sz.y);
				atlas.blit_rect(sources[i],Rect2(0,0,sources[i].get_width(),sources[i].get_height()),Point2(x+border,y+border));
			}

			ERR_CONTINUE( !source_map.has(i) );
			for (List<int>::Element *E=source_map[i].front();E;E=E->next()) {

				String apath = p_path.get_base_dir().plus_file(from->get_source_path(E->get()).get_file().basename()+".atex");

				Ref<AtlasTexture> at;

				if (ResourceCache::has(apath)) {
					at = Ref<AtlasTexture>( ResourceCache::get(apath)->cast_to<AtlasTexture>() );
				} else {

					at = Ref<AtlasTexture>( memnew( AtlasTexture ) );
				}
				at->set_region(region);
				at->set_margin(margin);
				at->set_path(apath);
				atlases[E->get()]=at;
				print_line("Atlas Tex: "+apath);
			}
		}
		if (ResourceCache::has(p_path)) {
			texture = Ref<ImageTexture> ( ResourceCache::get(p_path)->cast_to<ImageTexture>() );
		} else {
			texture = Ref<ImageTexture>( memnew( ImageTexture ) );
		}
		texture->create_from_image(atlas,tex_flags);

	} else {
Пример #26
0
void Game::readGame(int maxp, int size)
{
	int cntmove = 1;
	int cntPiece = 0;

	// 1. Version of the file
	short version = rGameFile.readShort();	// # Version (short)

	// 2. Header
	short typeOfData = rGameFile.readShort();	// # DATA_HEADER
	rGameFile.readShort();										// # Header version

	short width = rGameFile.readShort();		// # Width (short)
	short height = rGameFile.readShort();		// # Height (short)
	int seed = rGameFile.readInt();					// # Seed (int)
	int level = rGameFile.readByte();				// # Level (byte)
	int preview = rGameFile.readByte();			// # Preview (byte)
	int piece1 = rGameFile.readByte();      // # Piece1 (byte)
	int piece2 = rGameFile.readByte();      // # Piece2 (byte)

	Board board(width, height, 0, 0);
	Board htmlBoard(width+8, height+5, 0, 0);
	Piece dummy(&board, piece1);					// Initialize static members for width x height.
	MoveList *moveList = board.getMoveList(level);

	htmlBoard.copyWithWalls(&board, preview-1);

	wHtml << "<html>\n"
		    << "<head>\n"
				<< "  <title>Test.</title>\n"
				<< "</head>\n"
				<< "<body>\n"
				<< "  <table border=1>\n";

	while (piece2 != END_PIECE)
	{
		Piece htmlPiece1(&htmlBoard, piece1);
		Piece htmlPiece2(&htmlBoard, piece2);
		htmlPiece1.setPiece(0, 10, 1, width);

		if (level > 1)
			htmlPiece2.setPiece(0, 1, 1, width);
		
		Piece piece(&board, piece1);

		int length = rGameFile.readShort();		// # Number of legal moves.
		int pieceV = rGameFile.readByte();		// # V
		int pieceX = rGameFile.readShort();		// # X
		int pieceY = rGameFile.readShort();		// # Y

		moveList->init(level, preview, board.getMaxEquity());

		if (length == 0)
			break;


		wHtml << "    <tr>\n"
					<< "      <td>\n"
					<< "        <table border=0 cellspacing=0 cellpadding=0>\n"
					<< "        <!-- Board -->\n";

		// 1. Board
		for (int y=0; y<height+5; y++)
		{
			wHtml	<< "          <tr><td>";

			for (int x=0; x<width+8; x++)
			{
				int p = htmlBoard.get(x, y);
				char c = Piece::getHtmlChar(p);

				if (width == 10 && y==height+3)
				{
					if (x==6)
						wHtml << "<IMG src=img/Wdigits.gif height=" << size << ">";
					else if (x >=7 && x<=width+6)
						continue;
				}

				wHtml << "<IMG src=img/" << c << ".gif height=" << size << " width=" << size << ">";
			}

			wHtml	<< "</td></tr>\n";
		}

		wHtml	<< "        </table>\n"
					<< "      </td>\n";


		// 2. Equity list header
		wHtml	<< "      <td>\n"
					<< "        <table border=0>\n"
					<< "        <!-- Equity list -->\n"
					<< "          <tr>\n"
					<< "            <td colspan=2 align=left><font face=Arial size=1>"
					<< cntmove << ".&nbsp;"
					<< Piece::getChar(piece1) << Piece::getChar(piece2)
					<< "</font></td>\n"
					<< "          </tr>\n"
					<< "          <tr>\n"
					<< "            <td align=right><font face=Arial size=1>&nbsp;</font></td>\n"
					<< "            <td align=right><font face=Arial size=1>vx</font></td>\n";

		for (int i=level; i>=preview; i--)
			wHtml << "            <td align=right><font face=Arial size=1>&nbsp;&nbsp;Level&nbsp;"
						<< i << "</font></td>\n";
					
		wHtml << "          </tr>\n";

		while (length-- > 0)
		{
			int v = rGameFile.readByte();				// # V
			int x = rGameFile.readShort();			// # X
			int y = rGameFile.readShort();			// # Y

			Move *move = moveList->getMove();
			moveList->add(v, x, y);

			for (int i=preview; i<=level; i++)	// Equity (e.g):
			{
				double equity = rGameFile.readFloat();		// L2, L3, L4

				move->setEquity(i, equity);
			}
		}

		moveList->sort();

		int movecnt = 0;
		Move *move = moveList->getFirstMove();

		int first[MAX_LEVELS+1];
		float bestEquity[MAX_LEVELS+1];

		if (move != 0)
		{
			for (int i=preview; i<=level; i++)
			{
				first[i] = 1;
				bestEquity[i] = (float)moveList->getBestEquity(i);
			}
		}

		// 2. Equity list list
		while (move != 0)
		{
			movecnt++;

			if (movecnt > height/2)
				break;

			int v = move->getV();
			int x = move->getX();
			int y = move->getY();

			wHtml << "          <tr>\n"
				    << "            <td align=right><font face=Arial size=1>"
						<< movecnt << ".</font></td>\n"
						<< "            <td align=right><font face=Arial size=1>"
						<< v << x << "</font></td>\n";

			for (int i=level; i>=preview; i--)	// Equity (e.g):
			{
				char equityBuf[20];
				float equity = move->getEquity(i);

				if (equity == 0)
					strcpy(equityBuf, "-");
				else
				{
					if (equity == bestEquity[i] && first[i])
					{
						first[i] = 0;
						sprintf(equityBuf, "%.3f", equity);
					}
					else
						sprintf(equityBuf, "+%.3f", equity-bestEquity[i]);
				}

				wHtml << "            <td align=right><font face=Arial size=1>" << equityBuf << "</font></td>\n";
			}

			wHtml << "          </tr>\n";

			move = moveList->getNextMove();
		}

		wHtml	<< "        </table>\n"
		    	<< "      </td>\n"
		    	<< "    </tr>\n";

		piece.setPiece(pieceV, pieceX, pieceY);
		
		board.clearLines(pieceY, piece.getHeight());
		htmlBoard.copyWithWalls(&board, preview-1);

		piece1 = piece2;
		piece2 = rGameFile.readByte();				// # Piece (byte)
		cntmove++;

		if (maxp > 0 && cntmove >= maxp)
			break;
	}

	wHtml	<< "  </table>\n"
				<< "</body>\n"
				<< "</html>\n";
}
Пример #27
0
static int branch(void) {
  int p;
  p=empty;
  while(!(sym==SYM_END||(sym==SYM_CHR&&(val=='|'||val==')')))) p=group(p,piece());
  return p;
}
Пример #28
0
 bool XQ::set_fen(string const &fen)
 {
     clear();
     uint idx = 0UL, len = (uint)fen.size();
     uint y = 9UL, x = 0UL;
     while (idx < len)
     {
         sint32 c = fen[idx++];
         uint32 type = char_type(c);
         if (type != InvaildPiece)
         {
             if (y >= 10UL || x >= 9UL)
             {
                 //error
                 clear();
                 return false;
             }
             uint32 begin = type_begin(type);
             uint32 end = type_end(type);
             while (end >= begin)
             {
                 if (piece(begin) == InvaildCoordinate)
                 {
                     break;
                 }
                 ++begin;
             }
             if (begin > end)
             {
                 //error
                 clear();
                 return false;
             }
             uint32 sq = xy_coordinate(x++, y);
             m_coordinates[sq] = static_cast<uint8>(begin);
             m_pieces[begin] = static_cast<uint8>(sq);
         }
         else if (c == ' ')
         {
             if (y || x != 9UL || (idx == len))
             {
                 //error
                 clear();
                 return false;
             }
             c = fen[idx];
             m_player = ((c == 'b') ? Black : Red);
             for (int i = 0; i < 32; i++)
             {
                 uint32 sq = piece(i);
                 if (sq != InvaildCoordinate)
                 {
                     if (!(coordinate_flag(sq) & piece_flag(i)))
                     {
                         //error
                         clear();
                         return false;
                     }
                     m_bitmap.setbit(sq);
                 }
             }
             //ok
             return true;
         }
         else if (c == '/')
         {
             if (!y || x != 9UL)
             {
                 //error
                 clear();
                 return false;
             }
             --y;
             x = 0UL;
         }
         else if (c >= '1' && c <= '9')
         {
             x += c - '0';
         }
         else
         {
             //error
             clear();
             return false;
         }
     }
     //error
     clear();
     return false;
 }