《代码本色：用编程模拟自然系统》是一本好书，一定要读一读。用编程模拟自然，是我一直以来都想做的事，也是我编程的热情所在。无奈自己的数学和物理知识越剩越少，所以心有余而力不足。现在这本书来了，学完这本书一定可以让自己过够瘾。

``````<!doctype html>
<html>
<title>random walker</title>
<meta charset="utf-8" />
<meta name="author" content="JollyWing(jiqingwu@gmail.com)"/>
<meta name="create" content="2014-12-16 Tue"/>
<style type="text/css">
#screen {border:1px solid #000;}
</style>
<script>
var x = 100;
var y = 100;
var xspeed = 11;
var yspeed = 10;
var timeOut;
var scr, width, height, context;

function initScr(){
scr = document.getElementById('screen');
width = scr.width;
height = scr.height;
context = scr.getContext('2d');
context.strokeStyle="red";
}

function walk(){

x = x + xspeed;
y = y + yspeed;

if(x > width - 2 || x < 2){
xspeed = xspeed * -1;
}
if(y > height - 2 || y < 2){
yspeed = yspeed * -1;
}

console.log(x + ',' + y);

context.arc(x, y, 2, 0, 2*Math.PI);
context.stroke();

timeOut = setTimeout('walk()', 200);
}

function stopWalk(){
clearTimeout(timeOut);
}
</script>
<p>
<canvas id="screen" width="640" height="480"></canvas>
</p>
<input type="button" value='Start' onclick='walk()'/>
<input type="button" value='Stop' onclick='stopWalk()' />
</body>
</html>
``````

``````<!doctype html>
<html>
<title>random walker</title>
<meta charset="utf-8" />
<meta name="author" content="JollyWing(jiqingwu@gmail.com)"/>
<meta name="create" content="2014-12-16 Tue"/>
<style type="text/css">
#screen {border:1px solid #000;}
</style>
<script>
var sprite = {
x:100,
y:100,
xspeed:11,
yspeed:10,
move:function(canvasWidth, canvasHeight){
this.x = this.x + this.xspeed;
this.y = this.y + this.yspeed;

this.xspeed = this.xspeed * -1;
}
this.yspeed = this.yspeed * -1;
}

},
draw:function(context){
context.stroke();
}
};

var timeOut;
var scr, width, height, context;

function initScr(){
scr = document.getElementById('screen');
width = scr.width;
height = scr.height;
context = scr.getContext('2d');
context.strokeStyle="red";
}

function walk(){
sprite.move(width, height);

sprite.draw(context);

timeOut = setTimeout('walk()', 200);
}

function stopWalk(){
clearTimeout(timeOut);
}
</script>