【发布时间】:2021-05-04 11:59:29
【问题描述】:
我正在做一个学校项目。这是一个瓷砖移动游戏,我将屏幕上的瓷砖从瓷砖矢量数组中取出。
我正在尝试打乱瓷砖并将它们放入另一个名为 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 是右下角的图块,我不想更改它的位置,因为没有必要。
感谢您的帮助。
塔马斯
【问题讨论】:
-
试试
assert(this->tiles.size() == 16); -
什么是断言?
-
我应该把它放到for循环里面还是外面?
-
#include <cassert>和循环前的断言以确认图块实际上包含 16 个元素。
标签: c++ arrays sorting vector sfml