We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello,
I'm quite new to programming and we have to create the game Snake with processing for School. But the snake is always 2 parts long no matter how big the snake size variable is. I hope you can help me out. (ignore the german names :P)
//Variables
int swidth = 20; //snake width
int sheight = 20; //snake height
int xpos = 200; //Snake position
int ypos = 200;
int dir = 0; //direction: 0 = up, 1 = right, 2 = down, 3 = left
int slength = 5; //snake length
//Arrays
int[] xSchlange = new int[50]; //X Position Snake
int[] ySchlange = new int[50]; //Y Position Snake
void setup(){
size(400,400);
frameRate(8);
background(255);
stroke(0);
zeichneGitter(); //draw grid
xSchlange[0] = xpos;
ySchlange[0] = ypos;
}
void draw(){
zeichneGitter();
steuerung();
schlangeZeichnen();
fill(0);
}
void zeichneGitter(){ //draw grid
background(255);
stroke(0);
for(int i = 0; i < 20; i++){ //X lines
line(0, i*20, 400, i*20);
}
for(int i = 0; i < 20; i++){ //Y lines
line(i*20, 0, i*20, 400);
}
}
void steuerung(){ //controls
if(dir == 0){
ySchlange[0] = ySchlange[0] - 20;
}else if(dir == 1){
xSchlange[0] = xSchlange[0] + 20;
}else if(dir == 2){
ySchlange[0] = ySchlange[0] + 20;
}else if(dir == 3){
xSchlange[0] = xSchlange[0] - 20;
}
}
void schlangeZeichnen(){ //draw snake
for(int i = 0; i <= slength; i++){
rect(xSchlange[i], ySchlange[i], swidth, sheight);
}
for(int i = 0; i <= slength; i++){
xSchlange[i + 1] = xSchlange[i];
ySchlange[i + 1] = ySchlange[i];
}
}
void keyPressed(){
if(key == 'W' || key == 'w'){ //WASD controls
dir = 0;
}else if(key == 'S' || key == 's'){
dir = 2;
}else if(key == 'A' || key == 'a'){
dir = 3;
}else if(key == 'D' || key == 'd'){
dir = 1;
}
}
Answers
Instead of making the snake longer, you should focus in working on the snake in the grid. Then, you could add the extra code. The trick is to shuffle the positions of the body of the array by one "backwards" and then update the head.
Please also study for loops... your conditions were wrong which leads to bugs in your programs.
also check in the reference: rectMode()
Kf