作者 主题: 100行代码小游戏系列 之 贪吃蛇  (阅读 4154 次)

vinjn

  • SuperManager
  • Hero Member
  • *****
  • 帖子: 586
100行代码小游戏系列 之 贪吃蛇
« 于: 八月 15, 2011, 05:48:47 下午 »
在线运行的地址,需要支持html5的浏览器
http://vinjn.sinaapp.com/SnakeEater.html


程序代码
/* 
[][][][][][][][][][][][][][][]Snake5
use UP/DOWN/LEFT/RIGHT to control your snake
vinjn.z@gmail.com
*/

float s = 8;//default moving speed of snake
float r = s*1.5;//the size
ArrayList snake = new ArrayList();
PVector food = new PVector();
PVector vel = new PVector(s,0);

void newFood()
{
food = new PVector(random(width), random(height));
}

void setup()
{
//some boring setup
size(400, 400);
smooth();
frameRate(30);
rectMode(CENTER);

snake.add(new PVector(width/2, height/2));//the first one is the HEAD
snake.add(new PVector());//body 1
snake.add(new PVector());//body 2
newFood();
}

void draw()
{
background(200);
//[update & draw snake's head]
PVector head = (PVector)snake.get(0);
head.add(vel);
if (head.x > width) head.x -= width;
else if (head.x < 0) head.x += width;
if (head.y > height) head.y -= height;
else if (head.y < 0) head.y += height;

fill(color(200,0,0));stroke(0);strokeWeight(3);
ellipse(head.x, head.y, r*1.5,r*1.5);

//[update & draw snake's bodies]
for (int i=snake.size()-1;i>0;i--)
{
PVector cur = (PVector)snake.get(i);
fill(color(100));noStroke();
ellipse(cur.x, cur.y, r,r);
noFill();stroke(0);strokeWeight(1);
ellipse(cur.x, cur.y, r*1.3,r*1.3);

//make latter ones follow previous ones
PVector prev = (PVector)snake.get(i-1);
cur.x = prev.x;
cur.y = prev.y;
}
if (head.dist(food) < r)//if near enough, EAT the food
{
snake.add(new PVector(head.x, head.y));//Yummy!!
newFood();//giv me more food!!
}
else
{//just draw the food
fill(color(0,122,200));noStroke();
rect(food.x, food.y, r,r);
noFill();stroke(0);strokeWeight(1);
rect(food.x, food.y, r*1.3,r*1.3);
}
}

void keyReleased() {
if (key == CODED) {
if (vel.x == 0)
{
if (keyCode == LEFT)
vel = new PVector(-s,0);
else if (keyCode == RIGHT)
vel = new PVector(s,0);
}
if (vel.y == 0)
{
if (keyCode == UP)
vel = new PVector(0,-s);
else if (keyCode == DOWN)
vel = new PVector(0,s);
}
}
}
« 最后编辑时间: 一月 01, 2012, 03:15:11 下午 作者 vinjn »

Tags: