http://zetcode.com/javascript/snake/
int dots = 3;
boolean leftDirection = false;
boolean rightDirection = true;
boolean upDirection = false;
boolean downDirection = false;
int apple_x;
int apple_y;
int [] x = new int[100];
int [] y = new int[100];
void set_table()
{
background(0, 0, 0);
for (int i = 0 ; i < 10; i++)
{
for (int j = 0 ; j < 10; j++)
{
fill(255, 255, 255);
rect(i*50, j*50, 50, 50);
}
}
}
void doDrawing(){
fill(0, 122,0);
rect(apple_x,apple_y,50,50);
for (int z = 0; z < dots; z++) {
if (z == 0){
fill(255, 0, 0);
rect(x[z],y[z],50,50);
}
else
{
fill(122, 122,122);
rect(x[z],y[z],50,50);
}
}
}
void move_1() {
for (int z = dots; z > 0; z--) {
x[z] = x[(z - 1)];
y[z] = y[(z - 1)];
}
if (leftDirection) {
x[0] -= 50;
}
if (rightDirection) {
x[0] += 50;
}
if (upDirection) {
y[0] -= 50;
}
if (downDirection) {
y[0] += 50;
}
}
void setup()
{
frameRate(15);
size(700, 700);
for (int z = 0; z < dots; z++) {
x[z] = z * 50;
y[z] = 50;
}
int r = (int)random(0,9);
apple_x = r * 50;
r = (int)random(0, 9);
apple_y = r * 50;
}
void checkApple() {
if ((x[0] == apple_x) && (y[0] == apple_y)) {
dots++;
int r = (int)random(0,9);
apple_x = r * 50;
r = (int)random(0,9);
apple_y = r * 50;
}
}
void draw()
{
set_table();
checkApple();
move_1();
doDrawing();
}
void keyPressed() {
if ((keyCode == LEFT) && (!rightDirection)) {
leftDirection = true;
upDirection = false;
downDirection = false;
}
if ((keyCode == RIGHT) && (!leftDirection)) {
rightDirection = true;
upDirection = false;
downDirection = false;
}
if ((keyCode == UP) && (!downDirection)) {
upDirection = true;
rightDirection = false;
leftDirection = false;
}
if ((keyCode == DOWN) && (!upDirection)) {
downDirection = true;
rightDirection = false;
leftDirection = false;
}
}
|