带瓦片的洗牌向量数组



我正在做一个学校的项目。这是一款移动贴图的游戏,我将屏幕上的贴图从贴图向量数组中取出。

我试图洗牌,并把它们放入另一个矢量数组称为shuffledTiles,然后在屏幕上显示它们,但我写的代码只工作与一个瓷砖。谁能告诉我我做错了什么吗?我是一个初级程序员。

这是我的洗牌代码:

void Game::ShuffleTiles()
{
/* THIS FUNCTION IS TO CHOOSE A RANDOM TILE FROM THE TILES VECTOR STORAGE, TAKE ITS POSITION AND PUT IT INTO A NEW ARRAY CALLED SHUFFLED TILES, SET ITS POSITION TO THE 
POSITION SAVED INTO A TEMPORARY VECTOR2F variable */
// take items from 0 to 15 ->> 16 items
for (int i = 0; i < this->tiles.size(); i++)
{
// setting the random seed by time to make sure different random number is given every time 
srand(unsigned(time(NULL)));
// Vector2f variable for storing the position of the random selected tile
sf::Vector2f randTilePosXY;
// integer for the random number between 0 and 16
int randomNumber = rand() % this->tiles.size();
// console out to see which random number is selected
std::cout << "Random Number: " << randomNumber << std::endl;
// taking the randomly selected tile's position and saving it into the Vector2f variable
randTilePosXY == this->tiles[randomNumber].getPosition();
//Showing the random tile's X and Y positions
std::cout << "Random Number X and Y: " << std::stringstream(randTilePosXY) << std::endl;
// putting the randomly selected tile to the end of the new shuffledTiles vector array
this->shuffledTiles.push_back(this->tiles[randomNumber]);
// setting the position of item in the shuffledTiles vector storage under the index number
this->shuffledTiles[i].setPosition(sf::Vector2f(randTilePosXY));

}

我想用下面的代码来显示它们:

for (auto& s : this->shuffledTiles)
{
this->window->draw(s);
this->window->draw(emptyTile);
}

emptyTile是位于右下角的一个tile,我不想改变它的位置,因为它不是必需的。

谢谢你的帮助。

答摩

我认为你认为你的代码做了一件事,而事实上,它根本没有做你认为它做的事。你所做的基本上是:

// Step 1. Pick a tile from the existing set of tiles randomly.
int randomNumber = rand() % this->tiles.size();
// Step 2. Remember the randomly chosen tile's position
randTilePosXY == this->tiles[randomNumber].getPosition();
// Step 3. Copy the randomly chosen tile into a separate vector.
// THIS WILL COPY ALL INFORMATION OF THE TILE, INCLUDING ITS POSITION!
this->shuffledTiles.push_back(this->tiles[randomNumber]);
// Step 4. Copy AGAIN the POSITION INFORMATION.
// THIS STEP IS COMPLETELY USELESS AS YOU JUST OVERWRITE THE POSITION WITH THE SAME POSITION.
this->shuffledTiles[i].setPosition(sf::Vector2f(randTilePosXY));

你的洗牌"向量只不过是完全相同的信息,只是顺序不同。下面是发生的事情:

vector<tile> tiles = {{0, 0}, {1, 1}, {2, 2}}; // Three tiles at different positions.
// "Shuffle" the tiles...
shuffledTiles = {{1, 1}, {2, 2}, {0, 0}};

你在这里洗了什么?无论您是打印tiles还是shuffledTiles,您是否可以看到结果将是完全相同的?

编辑:作为题外话,这行代码:srand(unsigned(time(NULL)));应该在整个程序中只出现一次。把它放在main函数的顶部。随机生成器只需要播种一次。

这是现在的样子。

我完全不明白你在解释什么,对不起。

这就是我想要实现的,但是每次程序加载时位置不同

打乱瓷砖