Yo wasup my dudes, I've just finished the snek tutorials and homework and want to try adding obstacles that spawn randomly.
I reused the goal codes for the obstacle and made the snek die when touching it, but when I try to randomly spawn the obstacle, it will reuse the same obstacle for the spawning.
Currently the code is using a newLoc for the same cell everytime, so what do I need to know to make it a different obstacle everytime?
Should I be using an array and increment that changes the current obstacle index for each time it spawns? I can't seem to find a good way to fit it into the current code.
Snek Obstacle
-
- Posts: 2
- Joined: January 18th, 2018, 2:28 pm
Snek Obstacle
- Attachments
-
- Stuff.zip
- Obstacle and Game source.
- (3.45 KiB) Downloaded 124 times
Re: Snek Obstacle
Yeah making a new one each time would work. You can do something like
.h
.cpp
or use an array if you want a max amount of obstacles
.h
.cpp
.h
Code: Select all
std::vector<Obstacle*> __obstacles;
Code: Select all
if (obstacleSpawnCounter > obstacleSpawnPeriod)
{
obstacleSpawnCounter = 0;
_obstacles.emplace_back(new Obstacle(rng, brd, snek));
}
//draw
std::vector<Obstacle*>::iterator it = _obstacles.begin();
for (; it != _obstacles.end(); ++it)
it->Draw(brd);
or use an array if you want a max amount of obstacles
.h
Code: Select all
static constexpr int MAX_OBSTACLES = 100;
int _num_obstacles = 0;
Obstacle* _obstacles[MAX_OBSTACLES] = {nullptr};
Code: Select all
if (obstacleSpawnCounter > obstacleSpawnPeriod)
{
obstacleSpawnCounter = 0;
if (_num_obstacles < MAX_OBSTACLES)
{
_num_obstacles++;
_obstacles[_num_obstacles] = new Obstacle(rng, brd, snek);
}
//draw
for (size_t i = 0; i < _num_obstacles; i++)
_obstacles[i]->Draw(brd);
}
-
- Posts: 4373
- Joined: February 28th, 2013, 3:23 am
- Location: Oklahoma, United States
Re: Snek Obstacle
May I make a suggestion about using vector or arrays? Yumtard has probably gotten used to C# or something lol, just kidding. Instead of an std::vector<Obstacle*> why not just std::vector<Obstacle>?
Instead of C style arrays, use std::array<Obstacle, MAX_OBSTACLES>
Instead of using iterators and a for loop, use the range based for loop
for( auto& obstacle : obstacles )
{
obstacle.Draw( gfx );
}
If you do need to have an array of Obstacle*, you should consider using std::vector<std::unique_ptr<Obstacle>> instead.
Instead of C style arrays, use std::array<Obstacle, MAX_OBSTACLES>
Instead of using iterators and a for loop, use the range based for loop
for( auto& obstacle : obstacles )
{
obstacle.Draw( gfx );
}
If you do need to have an array of Obstacle*, you should consider using std::vector<std::unique_ptr<Obstacle>> instead.
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com