Skip to content

Instantly share code, notes, and snippets.

@Nekodigi
Created August 25, 2022 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nekodigi/dcde3cd88c4ecb7b179927adb598a8d4 to your computer and use it in GitHub Desktop.
Save Nekodigi/dcde3cd88c4ecb7b179927adb598a8d4 to your computer and use it in GitHub Desktop.
//snake game
//make with queue
int cellSize = 25;
int wN, hN;//horizontal number of cell, vertical number of cell
ArrayList<PVector> history = new ArrayList<PVector>();//history of snake position
ArrayList<PVector> apples = new ArrayList<PVector>();
PVector dir = new PVector(1, 0);
int speed = 10;
int score = 0;
void setup(){
size(500, 500);
wN = width/cellSize;
hN = height/cellSize;
history.add(new PVector(wN/2, hN/2));
for(int i=0; i<3; i++)apples.add(new PVector((int)random(wN), (int)random(hN)));
}
void draw(){
background(0);
if(frameCount%(60/speed)==0)move();
show();
}
void move(){
PVector prevHead = history.get(history.size()-1);
PVector newHead = PVector.add(prevHead, dir);
boolean flag = false;//when hit apple
for(int i=apples.size()-1; i>=0; i--){
PVector apple = apples.get(i);
if(newHead.dist(apple) == 0){
apples.remove(i);
apples.add(new PVector((int)random(wN), (int)random(hN)));
score++;
flag = true;
}
}
for(PVector pos : history){
if(newHead.dist(pos) == 0){
stop();
}
}
newHead = new PVector(newHead.x < 0 ? newHead.x+wN : newHead.x%wN, newHead.y < 0 ? newHead.y+hN : newHead.y%hN);
history.add(newHead);
//println(history.get(1).x);
if(!flag){
history.remove(0);
}
}
void show(){
fill(255);
textSize(cellSize);
textAlign(LEFT,TOP);
text("Score:"+score, 0, 0);
fill(255, 0, 0);
for(PVector apple : apples){
ellipseMode(CORNER);
ellipse(apple.x*cellSize, apple.y*cellSize, cellSize, cellSize);
}
for(int i=0; i<history.size(); i++){
PVector pos = history.get(i);
int r = 0;
fill(0, 255*(i/2+history.size()/2+1)/history.size(), 0);
rect(pos.x*cellSize, pos.y*cellSize, cellSize, cellSize, r, r, r, r);
}
noStroke();
}
void keyPressed(){
if((key == 'w' || keyCode == UP)&& dir.dist(new PVector(0, 1))!=0){
dir = new PVector(0, -1);
}
if((key == 's' || keyCode == DOWN)&& dir.dist(new PVector(0, -1))!=0){
dir = new PVector(0, 1);
}
if((key == 'a' || keyCode == LEFT)&& dir.dist(new PVector(1, 0))!=0){
dir = new PVector(-1, 0);
}
if((key == 'd' || keyCode == RIGHT)&& dir.dist(new PVector(-1, 0))!=0){
dir = new PVector(1, 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment