Home > other >  Probably a simple question about a c loop
Probably a simple question about a c loop

Time:11-04

I would like to start off by thanking everybody that attempts to help give me guidance through this issue. I am creating a snake clone to give myself real problems and situations. I have gotten through a lot on my own but unfortunately I have felt like I hit a brick wall and don't want to waste anymore time not understanding something that is probably really simple.

My issue is with the tail of the snake. When I create a block of the snakes tail I want that block to take the position of the pervious block that was created. This is because as of right now the first block follows the head which is not in the same class. The head is referred to as the playerObj in the code. I created a for loop because I thought that would be the best way to get this done and I excluded the first block of tail from the for loop.

for (int i = 1; i < snakeSize; i  )

    int previousTail = i - 1;
            
            
    //std::cout << "CURRENT TAIL X: " << CurTailPosX << " Y: " << CurTailPosY << std::endl;
             

    // This is the where the issue happens - ONLY TAIL 0 POS IS TRACKED AND ALL OTHERS GET UPDATED TO ITS POS
            
            
    growTail.snakeArray[i][0] = growTail.snakeArray[previousTail][0];
    growTail.snakeArray[i][1] = growTail.snakeArray[previousTail][1];


    std::cout << "Last Tail Pos X: " << growTail.snakeArray[previousTail][0] << " Y: " << growTail.snakeArray[previousTail][1] << std::endl;
            

Currently what is happening is all of the tails that get created end up just becoming the first tail blocks position so they all appear as one block which of course is the first tail block. I am sure this is very simple and again sorry for that but I am learning after-all.

If that's not enough information you can check out this paste bin link that will have the whole file you can look through (https://pastebin.com/zSJCVJ9F). Thanks again for reading this far in and dealing with me lol...

CodePudding user response:

What the posted code is doing is basically the following

for (size_t i = 1; i < a.size(); i  )
{                                        // Given a container, e.g. {1, 2, 3, 4}
     a[i] = a[i - 1];                    // the result would be     {1, 1, 1, 1}
}                   

You should traverse the container in the opposite direction to preserve its values other than the last one.

Given the task, I'd suggest to implement a circular buffer or use std::deque:

The complexity (efficiency) of common operations on deques is as follows:

Random access - constant O(1)
Insertion or removal of elements at the end or beginning - constant O(1)

  • Related