[Vectors] pushing coordinates in a vector

Hi,

I'm creating a snake like game for the console. As you know: when the snake eats food he becomes longer. I'm trying to push the coordinates of the player into a vector. The instances of "AANHANGSEL" (the body of the snake) need to use these coordinates in order to follow the player. Needless to say: I'm doing it completely wrong and i can't find a solution :(

I'm saving [0] & [1] of the vector in an integer and use them for the first instance.

Note: The code doesn't yet create more than 1 instance.. And the instance is already visible when the game starts ("O").

Here's the code, Just search for the word "VECTOR" to find the most important parts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#include <iostream>
#include <cstdlib>
#include <ctime> 
#include <vector>
#include <string>
using namespace std;

//Aanmaken van classes
class VOEDSEL    
{              
 public:
    int x;
    int y;

    VOEDSEL(int x, int y)        // Init-constructor.
        {
        this->x = y;
        this->y = x;
        }
};

class AANHANGSEL
{
	public:
	int x;
	int y;
	
	AANHANGSEL(int x,int y)		// Init-constuctor
	{
		this->x = y;
		this->y = x;
	}
};

class SPELER
{
	public:
	int x;
	int y;
	
	SPELER(int x,int y)			// Init-constructor.
	{
		this->x = y;
		this->y = x;
	}
};



int main() // Hoofdprogramma.
{
	int lengte = 0;
	int tijdelijkeAanhangselCoordinaat[2];

	//VECTOR
	vector<int> aanhangselVector (0);
	vector<int>::iterator Iter; 
	
	//Random getal voor spawnende objecten
	const int   veldgrootte = 15;
	int randomSpawn[4];
	srand((unsigned)time(NULL)); 
	
	//String aanmaken voor de controls
	string		wasd1234;
	
	//Iteratie voor het aanmaken van random getallen
	for (int i=0; i<4; i++)
	{	
		int getal = rand();
		randomSpawn[i] = getal % (veldgrootte-1);
	}
	
    //VECTOR
	SPELER		speler1(7,7);	//Speler 1 positie
	VOEDSEL     rondje(randomSpawn[0],randomSpawn[1]);   
    VOEDSEL     kruisje(randomSpawn[2],randomSpawn[3]);
	AANHANGSEL	aanhangsel1(tijdelijkeAanhangselCoordinaat[0],tijdelijkeAanhangselCoordinaat[1]);
    
	
	loop:
		system("CLS");
		//Maak het veld aan		
		for (int x=0; x<veldgrootte; x++)
        {
			for (int y=0; y<veldgrootte; y++)
            {
				if		((rondje.x == x) && (rondje.y == y))
                cout << "o ";
				else if ((kruisje.x == x) && (kruisje.y == y))
                cout << "x ";
				else if ((speler1.x == x) && (speler1.y == y))
				cout << "€ ";
				else if ((aanhangsel1.x == x) && (aanhangsel1.y == y))
				cout << "O ";
				else
                cout << ". ";
            }
			cout << endl;
        }
		
		//Controls
		cout << tijdelijkeAanhangselCoordinaat[0] << " & " << tijdelijkeAanhangselCoordinaat[1] << " Vectors: " << aanhangselVector[0] <<" & " << aanhangselVector[1] << endl;
		cout << "WASD om te bewegen: ";
		cin  >> wasd1234;
		cout << "De lengte van de vector is " << aanhangselVector.size() << endl;
	
		if ((wasd1234 == "w") && (speler1.x >0))
		{
			speler1.x -=1;
		}
		else if ((wasd1234 == "s") && (speler1.x < (veldgrootte-1)))
		{
			speler1.x +=1;
		}
		else if ((wasd1234 == "a") && (speler1.y > 0))
		{
			speler1.y -=1;
		}
		else if ((wasd1234 == "d") && (speler1.y < (veldgrootte-1)))
		{
			speler1.y +=1;
		}
		
		//SAVING THE COORDINATES IN A VECTOR
//		aanhangselVector.resize(0);
		aanhangselVector.push_back(speler1.x);
		aanhangselVector.push_back(speler1.y);
				// integers aanmaken met coordinaten voor aanhangsels
			tijdelijkeAanhangselCoordinaat[0] = aanhangselVector[0];
			tijdelijkeAanhangselCoordinaat[1] = aanhangselVector[1];
		
		//Collition detection & volgen voedsel
		if ((speler1.x == rondje.x) && (speler1.y == rondje.y))
		{		
			lengte += 2;
		}	
		

	goto loop;
	

    return 0;
}
I've made some modifications to the code below. (I translated everything into English. It's easier for me to work with that way. You really might want to consider that when you post on a site that's in English.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#include <iostream>
#include <cstdlib>
#include <ctime> 
#include <vector>
#include <string>
using namespace std;

//Produce classes
class FOOD    
{              
 public:
    int x;
    int y;

    FOOD(int x, int y)        // Init-constructor.
        {
        this->x = y;
        this->y = x;
        }
};

class APPENDIX
{
	public:
	int x;
	int y;
	
	APPENDIX(int x,int y)		// Init-constuctor
	{
		this->x = y;
		this->y = x;
	}
};

class PLAYER
{
	public:
	int x;
	int y;
	
	PLAYER(int x,int y)			// Init-constructor.
	{
		this->x = y;
		this->y = x;
	}
};



int main() // HEAD PROGRAM.
{
	int length = 0;
	int temporaryAppendixCoordinate[2]= {0,0};  // You need to initialize this with some values so that you're not trying to use it un-initialized the first time through the loop.


	//VECTOR                                               I don't see why you need this vector, so I commented it out.
	//vector<int> appendixVector (2);   In the event that you're stuck on using this, you need to initialize it with a space, or you'll end up accessing a random memory point outside the vector the first time your loop executes.
	//vector<int>::iterator Iter; 
	
	//Random number for spawning objects
	const int   fieldsize = 15;
	int randomSpawn[4];
	srand((unsigned)time(NULL)); 
	
	//String produced for controls
	string	wasd1234;
	
	//Iterator for producing random numbers
	for (int i=0; i<4; i++)
	{	
		srand((unsigned)time(NULL));
		int number = rand();
		randomSpawn[i] = (number % (fieldsize-1));
	}
	
    //VECTOR
	PLAYER	player1(7,7);	//player 1 position
	FOOD     rondje(randomSpawn[0],randomSpawn[1]);   
    FOOD     kruisje(randomSpawn[2],randomSpawn[3]);
	APPENDIX  appendix1(temporaryAppendixCoordinate[0],temporaryAppendixCoordinate[1]);
    
// I changed this to an infinite loop that breaks when the player is caught by the snake.  I don't like goto statements!!!
 for(bool i=true;i==true;)
 {
		system("CLS");
		//Produce the field		
		for (int x=0; x<fieldsize; x++)
        {
			for (int y=0; y<fieldsize; y++)
            {
				if		((rondje.x == x) && (rondje.y == y))
                cout << "o ";
				else if ((kruisje.x == x) && (kruisje.y == y))
                cout << "x ";
				else if ((player1.x == x) && (player1.y == y))
				cout << "? ";
				else if ((appendix1.x == x) && (appendix1.y == y))
				cout << "O ";
				else
                cout << ". ";
            }
			cout << endl;
        }
		
	//Controls
//Again, I commented out everything here that uses that vector, because I'm not sure what purpose it really serves.
//cout << temporaryAppendixCoordinate[0] << " & " << temporaryAppendixCoordinate[1] << " Vectors: " <<appendixVector[0] <<" & " << appendixVector[1] << endl;
		cout << "WASD to move: ";
		cin  >> wasd1234;
		/*cout << "The length of the vector is" << appendixVector.size() << endl;*/
	
		if ((wasd1234 == "w") && (player1.x >0))
		{
			player1.x -=1;
		}
		else if ((wasd1234 == "s") && (player1.x < (fieldsize-1)))
		{
			player1.x +=1;
		}
		else if ((wasd1234 == "a") && (player1.y > 0))
		{
			player1.y -=1;
		}
		else if ((wasd1234 == "d") && (player1.y < (fieldsize-1)))
		{
			player1.y +=1;
		}

// Here's where the snake follows the player.  (It's a little relentless, and since it checks both the x and the y, and allows a move on both, the snake moves faster than the player.  If you want to fix that, just put in a statement to have it move on one axis or the other (x or y), and not both.
		if (player1.x>appendix1.x)
		{
			appendix1.x +=1;
		}
		else if (player1.x<appendix1.x)
		{
			appendix1.x -=1;
		}

		if (player1.y>appendix1.y)
		{
			appendix1.y +=1;
		}
		else if (player1.y<appendix1.y)
		{
			appendix1.y -=1;
		}
		
		if (player1.x==appendix1.x && player1.y==appendix1.y)
		{
			cout<<"YOU LOSE!"<<endl;
			break;
		}
		//SAVING THE COORDINATES IN A VECTOR
		//appendixVector.resize(0);
		//appendixVector.push_back(player1.x);
		//appendixVector.push_back(player1.y);

// integers producing coordinates for appendices
			//temporaryAppendixCoordinate[0] = appendixVector[0];
			//temporaryAppendixCoordinate[1] = appendixVector[1];
		
		//Collision detection and follow food??  This currently doesn't do anything.  And why is it trying to detect collision between the player and the food?  I thought the snake was the one that was supposed to eat the food and grow longer.
		if ((player1.x == rondje.x) && (player1.y == rondje.y))
		{		
			length += 2;
		}	
	}
	

    return 0;
}


Hope this helps.
Thank you so much for replying!

Oh this is epic :). I was looking at the chances you made to my code and I was surprised. You actually made a different game :). It's my fault for explaining the game badly.

The game I was trying to make is the classic snake game you would play on your old Nokia cellphone. You, the player, control the snake. When you "eat" the food your snake will become larger. The appendix will follow the player like a snake does. That's why i needed the vector. To store the locations of the "head" of the snake so that the appendix could use these coordinates when the head moves to a different place. Every time the player(head) eats food the snake will become larger.

I hope you can help me with this problem.
Oh. In that case, give me a little while to take another look, and I'll see what I can come up with.
Sure thing. Thanks.
Bump. I'm kinda running out of time :D
Here's what I have so far. I've been really busy lately, so I haven't had very much time to work on this. I couldn't really work it out very well with your previous code, so I've pretty much re-coded it from scratch. It still needs logic to limit the snake to the edge of the field, and to detect when the snake runs into itself. (You'll also want to add logic to prevent it from turning back on itself.) Also, the food still needs to be randomized. (The code you had before won't work. It needs to be random, but still limit it to always appear somewhere on the field.) I plan to continue working on it, but with how hectic it has been around here lately, I can't guarantee it will be complete anytime soon. Anyway, this should be a good start for you.

PS: The code is too long for one post, so I've pasted half here, and the other half will be pasted below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
//This is a snake game.  The snake is a vector that moves around the board according to the commands input by the player.  If it
//encounters food, the snake grows, and the food is moved to a new location.  If the snake runs into itself, the game ends.

#include <iostream>
#include <vector>
#include <ctime>
using namespace std;

//The food class is simply a small integer array representing it's x and y coordinates. It has the field as a friend class to allow
//the field to read it's location, and access it's change location function.
class Food
{              
 public:
        friend class Field;
    Food(int a, int b)
        {
         foodarr[0]=a;
         foodarr[1]=b;
        }
//The change location function is called by the field whenever the player intersects food.  It just changes the x and y coordinates
//of the food to make it jump to a new location.
    void Changelocation(int x, int y)
    {
       foodarr[0] = x;
       foodarr[1] = y;
    }
 private:
     int foodarr[2];
};

//The player is the snake, and moves around the field eating food, and growing larger.  Once again, the Field is a friend class to
//allow it to access the players location data, and the Eat method, when the player comes into contact with food.
class Player
{
  public: 
      friend class Field;
// The constructor initializes the starting location of the player(a and b), and loads them into the body of the player. (The vector)
//it also initializes the bool value istherefood (who's purpose is explained later) to false.
      Player(int a, int b)
      {
        playervector.push_back(b);
        playervector.push_back(a);
        istherefood = false;
      }
//Move described below where defined.
      void Move(char movechar);
//Eat is called by the field when the player intersects food. It changes the bool value istherefood to true.  The purpose of this
//bool value is explained below in the Move function explanation.
      void Eat()
      {
           istherefood = true;
      }
//Defined for use during creation of code.
      void Showvector(); 
  private:
          vector<int>playervector;
          vector<int>::iterator i;
          bool istherefood;
};
      
void Player::Showvector()
      {
           for(vector<int>::iterator i = playervector.begin(); i != playervector.end(); i++)
           {
             cout<<*i<<endl;
           }
      }

//This is the function that moves the player around the board. It does so by recieving a character input from the user: w,a,s, or d.
//It then translates this into movement by: reading the value of the first two elements of the vector representing the player
//(which correspond to the x and y coordinates of the head); it then alters them appropriately (subtract 1 from the x coordinate
//to move left, etc.) then pushes the new values onto the front end of the vector.  Finally, it checks the bool value istherefood
//to determine whether the last move made intersected with food.  If no food was intersected on the last move (istherefood == false)
//then it pops the back two numbers off the vector, thus preventing the vector (the player) from growing in length.  If there was
//food intersected on the last move (istherefood ==true) then it doesn't pop the values off the back of the array, and it re-sets
//istherefood to false.
void Player::Move(char movechar)
{
     if (movechar=='a')
     {
        i = playervector.begin();
        playervector.insert(i,playervector[1]-1);
        i = playervector.begin();
        playervector.insert(i,playervector[1]);
        if(istherefood==false)
        {
        playervector.pop_back();
        playervector.pop_back();
        }
        else
        {
            istherefood = false;
        }
     }     

     else if (movechar=='d')
     {
        i = playervector.begin();
        playervector.insert(i,playervector[1]+1);
        i = playervector.begin();
        playervector.insert(i,playervector[1]);
        if(istherefood==false)
        {
        playervector.pop_back();
        playervector.pop_back();
        }
        else
        {
            istherefood = false;
        }
     }
     else if (movechar=='w')
     {
        i = playervector.begin();
        playervector.insert(i,playervector[1]);
        i = playervector.begin();
        playervector.insert(i,playervector[1]-1);
        if(istherefood==false)
        {
        playervector.pop_back();
        playervector.pop_back();
        }
        else
        {
            istherefood = false;
        }
     }
          else if (movechar=='s')
     {
        i = playervector.begin();
        playervector.insert(i,playervector[1]);
        i = playervector.begin();
        playervector.insert(i,playervector[1]+1);
        if(istherefood==false)
        {
        playervector.pop_back();
        playervector.pop_back();
        }
        else
        {
            istherefood = false;
        }
     }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//This value sets the size of the field
int const fieldsize = 15;

//The field class represents the playing area, the body of which is represented by a two dimensional charachter array.
//It has datamembers corresponding to the player, and the food, so that it can access and compare data from both.
class Field
{
  public:
      //The constructor just passes the instances of the food and the player to the field as references.
 	  Field(Player & theplayer, Food & thefood)
 	  :_player(theplayer),_food(thefood)
 	  {}
 	  //The field Filler is responsible for populating the field with the appropriate charachters based on the coordinates passed
 	  //in by the player, and the food.  It is also responsible for detecting intersections between the player and the food, and
 	  //then passing notification back to the player via the Eat() function (so the player knows to grow, and to the food via the 
 	  //Changelocation() function.
 	  void Fieldfiller()
 	  {
        //Fill the field with field charachters corresponding to the un-occuppied spaces.
        for (int zerofiller = 0; zerofiller<fieldsize; zerofiller++)
        {
            for (int zerofiller2 = 0; zerofiller2<fieldsize; zerofiller2++)
            {
                fieldarr[zerofiller][zerofiller2] = '-';
            }
        }
        // Overwrite the empty spaces in the location corresponding to the location of the food.
           fieldarr[_food.foodarr[1]-1][_food.foodarr[0]-1] =4;

        
        //Overwrite the empty spaces corresponding to the location of the player. 
        //If food is already there, use the player eat function to toggle a bool for the snake to grow, and the food Changelocation
        //function to re-locate the food.
        
        //Start by iterating through the x coordinates of the player vector
        for(int count =0; count<_player.playervector.size(); count +=2)
        {
                //If that location on the field contains a 4 (ie: it contains food) overwrite it, and activate the Eat and 
                //Changelocation functions.
                if(fieldarr[_player.playervector[count]-1][_player.playervector[count+1]-1]==4)
                {
                   fieldarr[_player.playervector[count]-1][_player.playervector[count+1]-1]= 1;
                   _player.Eat();
                   _food.Changelocation(13,13);
                }
                //If there isn't any food there, just overwrite it.
                else
                {
                fieldarr[_player.playervector[count]-1][_player.playervector[count+1]-1]=1;
                }
        }
       }
       //Standard printing for a two dimensional array.
       void Field_displayer()
       {
        for (int display = 0; display<fieldsize; display++)
        {
            for (int display2 = 0; display2<fieldsize; display2++)
            {
                cout<<fieldarr[display][display2];
            }
            cout<<endl;
        }
       }
  private:
         Player & _player;
         char fieldarr[fieldsize][fieldsize];
         int x, y;
         Food & _food;
};


        

int main()
{
    Player myplayer(5,7);
    Food thefood(3,5);
    Field thefield(myplayer,thefood);
    thefield.Fieldfiller();
    for (int g = 100; g>0; g--)
    {
        //clear the screen
        system ("CLS");
        //display the current field
        thefield.Field_displayer();
        cout<<endl;
        //prompt for input
        cout<<"wasd to move:";
        char movingchar;
        cin>>movingchar;
        myplayer.Move(movingchar);
        thefield.Fieldfiller();
    }
        
        
        
    system ("pause");
}      


If you need any more help, let me know and I'll try to get back to you. Good luck!
Last edited on
I compiled this, after eating the second piece of food, no more appears, and the snake grows everytime it moves a step.
I know that. Note how the code:

1
2
3
4
5
6
7
8
   //If that location on the field contains a 4 (ie: it contains food) overwrite it, and activate the Eat and 
                //Changelocation functions.
                if(fieldarr[_player.playervector[count]-1][_player.playervector[count+1]-1]==4)
                {
                   fieldarr[_player.playervector[count]-1][_player.playervector[count+1]-1]= 1;
                   _player.Eat();
                   _food.Changelocation(13,13);
                }


Feeds the same location to the Changelocation code every time. (At 13,13) As I said above, it still needs a function added to randomize the food. (It's incomplete. I only posted it because BMH said he was running out of time.) That's why no other food seems to appear and the snake seems to keep on growing. The food is actually still at 13,13; and since part of the snake still occupies that space, it continues to grow. Once the food is randomized, that issue will go away. (The food needs to have random numbers generated that will always appear somewhere on the board, and never where the snake currently occupies. I haven't had a chance to write that yet.)

Regards,

gzero
To randomize the food:
_food.Changelocation(rand() % 15 + 1,rand() % 15 + 1);


Also, I found the game more fun, if you make it so it is only spaces, instead of lines for the fieald.
For example,
instead of:
fieldarr[zerofiller][zerofiller2] = '-';(line 157)
put:
fieldarr[zerofiller][zerofiller2] = ' ';
Last edited on
Oh, that seems to work well. I haven't messed with the rand() function before, so I didn't know that you could use the % operator to set a limit on the value. It still may need something added to prevent it from being generated in a space occupied by the snake though. It may not be a big deal while the snake is relatively small, but it will become more problematic as the snake grows. (Eventually, the code will be modified so it utilizes an infinite loop so the game won't end until you run into yourself. and a good player will be able to get rather large.)
Oh, yeah, I forgot about that. What you could do is:
[code
then to check to see if it is the same as the player:
[code]
//If that location on the field contains a 4 (ie: it contains food) overwrite it, and activate the Eat and
//Changelocation functions.
if(fieldarr[_player.playervector[count]-1][_player.playervector[count+1]-1]==4)
{
fieldarr[_player.playervector[count]-1][_player.playervector[count+1]-1]= 1;
_player.Eat();
int x,y;
for(;;){
x = rand() % 15 + 1;
y = rand() % 15 + 1;
if(x != *player's x variable(whaterever it is)*
|| y != *player's y variable(whaterever it is)*) {break;}
}
_food.Changelocation(x,y);
}
[/code]
[/code]
Last edited on
Holy shit :D. You actually redid the whole thing. Your a great help. The only problem is that I can't grasp it all. It's too complex for someone who has just a few hours of experience dealing with C++ :).

Could you explain to me how you created the vector that makes it possible for the snake to grow? I tried to figure it out, but I'm not advanced enough to understand your code completely.

Oh and a little note: I'm using Xcode 3 to compile your code and this is what i get in the console:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[Session started at 2008-03-23 00:00:47 +0100.]
sh: CLS: command not found
---------------
---------------
---------------
--------------
---------------
--------------
---------------
---------------
---------------
---------------
---------------
---------------
---------------
---------------

wasd to move:

I can only move up or down (white space moves).
Hmm... not really sure why you would only be able to move up or down. I can't see why it should be any different. The coding for all the moves is the same, save the fact that they modify either the x or the y coordinates. I can't say I'm at all familiar with Xcode 3.

As for explaining how the code allows the snake to grow, it's actually far less complicated than it looks. The key to how the snake grows is in the way that this vector is implemented and the way it moves about the board. The first thing that you need to know is that the vector uses consecutive spots in it's index to represent the x and y values. So playervector[0] represents the x coordinate of the head, playervector[1] represents the y value of the head, playervector[2] represents the x value of the first segment of the body, etc...
I think the easiest way to explain the rest is to show you how the code runs in snippets. Try running this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> playervector(2);
    vector<int>::iterator i;
    //initialize the x and y values to 4 and 8 respectively
    playervector[0]=4;
    playervector[1]= 8;
    
    //now run the first portion of the Move code that modifies the vector.
    i = playervector.begin();
    playervector.insert(i,playervector[1]-1);
    i = playervector.begin();
    playervector.insert(i,playervector[1]);
    //now show the current contents of thevector
     for(vector<int>::iterator i = playervector.begin(); i != playervector.end(); i++)
           {
             cout<<*i<<endl;
           }
    system ("pause");
}


Notice that the vector now contains both the original coordinates, (4,8) on the back end, and the coordinates for a downward move (4,7) on the front. But doesn't that make mean the vector, and thus our snake just grew in length? Right you are. We need to prevent it from growing if it hasn't encountered any food. Hence the next portion of the code is added. Addbool istherefood = false; in at the beginning of main, then add the following directly before the iterator which displays the contents of the vector:

1
2
3
4
5
6
7
8
9
if(istherefood==false)
        {
        playervector.pop_back();
        playervector.pop_back();
        }
        else
        {
            istherefood = false;
        }


Notice how now we're left with only the coordinate of the new location of the head. That's because we used the pop_back() function twice to break off the last two numbers off. Now try changing the value of istherefood to true. Now we're leaving those numbers on, to allow it to grow, and then toggling the istherefood value back to false (after all, we only want the vector to grow once each time it runs into food). So all we need now is something to tell us if we've run into food or not and toggle istherefood to true or false. In the snake program that's being handled by the Fieldfiller function. By writing in the location of the food onto the field first, and then checking the values as we write in the snake, we can see whether the player and the food have intersected, and toggle the switch.

I hope that's clear. By the way, I'm still working on making a few more modifications to this, so keep checking back for updates.


thanks for the explanation.

I got a question about for loops:
1
2
3
4
5
for (int i=0;i<8;i++)
{
	else if	((food[+i].x == x) && (food[+i].y == y))
    cout << "+" << food[+i].stunErbij << " ";
}

food0, food1 etc. till foosd7 are instances. I need to use the cout on all of them without having to write this piece of code 8 times. The problem is: I'm not doing it the right way :). Whheelp :D
Last edited on
Topic archived. No new replies allowed.