Snek Obstacle

The Partridge Family were neither partridges nor a family. Discuss.
Post Reply
EpicCrisis
Posts: 2
Joined: January 18th, 2018, 2:28 pm

Snek Obstacle

Post by EpicCrisis » June 9th, 2018, 5:14 am

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.
Attachments
Stuff.zip
Obstacle and Game source.
(3.45 KiB) Downloaded 124 times

User avatar
Yumtard
Posts: 575
Joined: January 19th, 2017, 10:28 pm
Location: Idiot from northern Europe

Re: Snek Obstacle

Post by Yumtard » June 9th, 2018, 9:55 am

Yeah making a new one each time would work. You can do something like

.h

Code: Select all

std::vector<Obstacle*> __obstacles;
.cpp

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};
.cpp

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);
}

albinopapa
Posts: 4373
Joined: February 28th, 2013, 3:23 am
Location: Oklahoma, United States

Re: Snek Obstacle

Post by albinopapa » June 10th, 2018, 12:39 am

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.
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

Post Reply