0

i have a snake game project but now i need to find a way to make the tail follow the head, and i already make the head first,but i still confuse on how to make the tail follow the head, i know that i have to make the tail follow the previous coordinate of the head, but i can't find a way to do it

here's my code

#include <stdio.h> #include <stdlib.h> #include <conio.h> int side; char map[20][20]; int z=5,c=5; //the starting position of the head int p=0; void snake(char map[20][20],int ,int ) { if(p==0) { p++; for(int x=0;x<side;x++) { map[z][c]='X'; printf("%s\n",map[x]); } } int hc,hb,t,r,j,u,i; hc=getch(); hb=getch(); if(hb==72)//up { z--; } else if(hb==77)//right { c++; } else if(hb==80)//down { z++; } else if(hb==75)//left { c--; } map[z][c]='X'; system("CLS"); } void square(){ int x,y; for(x=0;x<side;x++){ for(y=0;y<side;y++){ if(x==0||x==side-1||y==0||y==side-1){ map[x][y]='X'; } else{ map[x][y]=' '; } } } snake(map,x,y); } void print(){ for(int x=0;x<side;x++){ printf("%s\n",map[x]); } } int main() { printf("Input the large = "); scanf("%d",&side); fflush(stdin); system("CLS"); while(true) { square(); print(); } getchar(); } 

1 Answer 1

4

In most such games, you don't actually have to make the tail follow the head -- you just add a new X at the front to extend the head one step and remove the last X at the tail to shorten it one step. That simplifies the problem to just needing to know what the past coordinates were, which you need anyway in order to keep the snake from crossing itself.

Sign up to request clarification or add additional context in comments.

2 Comments

but my project require that the tail must follow the head, so can you give me some advice for that ?
The tail will follow the head. Or more accurately, will follow the body, which follows the path the head has already traced. If the tail is a different graphic from the rest of the body, then things get a bit more complicated and you have to actually repaint the next-to-last position with the new glyph. But it's still essentially the same solution. Unless this is a different game than the one I think you're describing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.