var changdu = 5;//蛇的起始长度var fangxiang = 'right';//初始运行方向var xStart = 100; //蛇的起始横坐标var yStart = 250; //蛇的起始纵坐标var diff = 10;//每一段的长度var X = [];//蛇的每一段横坐标var Y = [];//蛇的每一段纵坐标var D_x = 300;//随机点的横坐标var D_y = 300;//随机点的纵坐标function setup() { createCanvas(500, 500); frameRate(5);//刷新率 stroke(255); strokeWeight(10); for (var i = 0; i < changdu; i++) {//产生点的坐标放到数组里面 X.push(xStart + (i * diff)); Y.push(yStart); }}function draw() { background(0); for (var i = 0; i < changdu - 1; i++) { line(X[i], Y[i], X[i + 1], Y[i + 1]);//画直线 } gaibian();//控制运动 suijiD();//产生随机点}function suijiD() { point(D_x, D_y); if (X[X.length - 1] === D_x && Y[Y.length - 1] === D_y) { X.unshift(X[0]);//unshift(a)方法将a插入数组的头部 Y.unshift(Y[0]); changdu++; //random(a,b)产生a到b之间的浮点型随机数 //floor()数据取整 D_x = floor(random(10, (width - 100) / 10)) * 10; D_y = floor(random(10, (height - 100) / 10)) * 10; }}function gaibian() { for (var i = 0; i < changdu - 1; i++) { X[i] = X[i + 1]; Y[i] = Y[i + 1]; } switch (fangxiang) { case 'right': X[changdu - 1] = X[changdu - 2] + diff; Y[changdu - 1] = Y[changdu - 2]; break; case 'up': X[changdu - 1] = X[changdu - 2]; Y[changdu - 1] = Y[changdu - 2] - diff; break; case 'left': X[changdu - 1] = X[changdu - 2] - diff; Y[changdu - 1] = Y[changdu - 2]; break; case 'down': X[changdu - 1] = X[changdu - 2]; Y[changdu - 1] = Y[changdu - 2] + diff; break; }}function keyPressed() { switch (keyCode) { case 74: if (fangxiang != 'right') { fangxiang = 'left'; } break; case 76: if (fangxiang != 'left') { fangxiang = 'right'; } break; case 73: if (fangxiang != 'down') { fangxiang = 'up'; } break; case 75: if (fangxiang != 'up') { fangxiang = 'down'; } break; }}