class Snake{ Vec2 [] s;//snake body array int d,id;//direction and length int col;//snake color boolean alive; Snake(int id, int len, int col, int xStart, int yStart){ this.id = id; s = new Vec2[len]; this.col = col; alive = true; d = rand(4); for(int i = 0; i < s.length; i++){ s[i] = new Vec2(xStart, yStart); } game.world.setBot(id, xStart, yStart); move(); } void move(){ //shift values along one game.world.grid[s[0].x][s[0].y] = 0; for (int i = 1; i < s.length; i++){ s[i-1].x = s[i].x; s[i-1].y = s[i].y; } switch(d){ case 0: s[s.length-1].x++; break; case 1: s[s.length-1].y++; break; case 2: s[s.length-1].x--; break; case 3: s[s.length-1].y--; break; } game.world.setBot(id, s[s.length-1].x, s[s.length-1].y); //check for own body, walls and eggs if(s[s.length-1].x < game.wide && s[s.length-1].x > -1 && s[s.length-1].y < game.high && s[s.length-1].y > -1){ if(game.world.grid[s[s.length-1].x][s[s.length-1].y] == -1){ alive = false; } if(s[s.length-1].equals(game.world.target[0])){ Vec2 [] temp = new Vec2[rand(1,6) + s.length]; for(int i = s.length-1; i < temp.length; i++){ temp[i] = new Vec2(s[s.length-1].x, s[s.length-1].y); game.world.grid[s[s.length-1].x][s[s.length-1].y] = -1; } System.arraycopy(s, 0, temp, 0, s.length); s = temp; game.egg[0] = new Egg(0, 0); } if(s[s.length-1].equals(game.world.target[1])){ Vec2 [] temp = new Vec2[rand(7,15) + s.length]; for(int i = s.length-1; i < temp.length; i++){ temp[i] = new Vec2(s[s.length-1].x, s[s.length-1].y); game.world.grid[s[s.length-1].x][s[s.length-1].y] = -1; } System.arraycopy(s, 0, temp, 0, s.length); s = temp; game.egg[1] = new Egg(1, 0); game.world.setTarget(1, -1, -1); } game.world.grid[s[s.length-1].x][s[s.length-1].y] = -1; } else{ alive = false; } } void AI(){ int eggNum = 0; if(game.egg[1].timer > 0){ eggNum = 1; } game.world.findPath(id, eggNum, false); if(game.world.closedlist.size() > 1){ Vector pathway = game.world.logicalPath(id, eggNum); if(pathway.size() > 1){ Vec2 temp = (Vec2)pathway.get(pathway.size() - 2); if(temp.x == s[s.length-1].x + 1 && temp.y == s[s.length-1].y){ d = 0; } if(temp.x == s[s.length-1].x && temp.y == s[s.length-1].y + 1){ d = 1; } if(temp.x == s[s.length-1].x - 1 && temp.y == s[s.length-1].y){ d = 2; } if(temp.x == s[s.length-1].x && temp.y == s[s.length-1].y - 1){ d = 3; } } } } void draw(){ stroke(col); strokeWeight(8); beginShape(LINE_STRIP); for(int i = 0; i < s.length; i++){ vertex(4 + s[i].x*gridUnit, 4 + s[i].y*gridUnit); } endShape(); } }