简体   繁体   中英

Adding tail to snake game [c++ sfml]

I want to move the snake's tail by filling the gap it creates each time the head moves:
. o oox
.ooo x
. oo o x
So basically the last element moves into the gap. I can get the position of gap and create a tail there but as soon as I have more than 1 tail object it doesn't work correct. I believe it creates the new tail object on the same position as other tails, so the gap. Tail = rep

For tail

    //If tail exists
    if(imamoRep)
    {
            rep[repCount-1].setPosition(gap);

            temp[0] = rep[repCount-1]; //Remember last element
            for(int i=1;i<repCount;i++)
            {
                rep[i] = rep[i-1];
            }
            rep[0]=temp[0];   //assign last element to first
    }

Drawing

for(int i=0; i<repCount; i++)
    {
        window.draw(rep[i]);
    }

I'm guessing I did something wrong with arrays, the last element should become first and all others should move to left, so there's a new last tail. I created 100 tail elements in the beggining so I only need to draw them correctly. If I remove the tail code except the first line that sets position then I get this result: 在此处输入图片说明

Tails are left behind, because only the position of last element changes, otherwise as said before all tails are on the same position. I would really appriciate help.

You almost had it. Think of what this loop is doing to your positions:

for(int i = 1; i < repCount; ++i)
{
    rep[i] = rep[i - 1];
}

Starting at i=1 it'll assign rep[1] the value of rep[0] . Next for i=2 it'll assign rep[2] the value of rep[1] which was overwritten with rep[0] on the previous iteration. And so on...

What you need to do is invert the loop writing the element at i+1 before writing the element at i :

for(int i = repCount - 1; i > 0; --i)
{
    rep[i] = rep[i - 1];
}

Note that std::copy_backward generically implements this behaviour. Ie you can rewrite the loop above as:

if(repCount > 0)
{
    // Assuming rep is a std::vector using std::vector::begin
    std::copy_backward(rep.begin(), rep.begin() + repCount - 1, rep.begin() + repCount);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM