-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscripts.js
134 lines (121 loc) · 2.7 KB
/
scripts.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
const computeState = require('./computeState.js');
const padding = require('./padding.js')
const stateUpdate = require('./stateUpdate.js')
//初始化world
var world=new Array();
for(var i=0;i<20;i++)
{ world[i]=new Array();
for(var j=0;j<30;j++)
{
world[i][j]=0;
}
}
var canvas=document.getElementById("test-canvas");
var start=document.getElementById("start");
var stop=document.getElementById("stop");
var clear=document.getElementById("clear");
var speed=document.getElementById("speed");
var speedValue=speed.value;
var pause=false;
//初始化矩阵
var ctx=canvas.getContext('2d');
for(var i=0;i<=300;i++)
{
for(var j=0;j<=200;j++)
{
ctx.fillStyle = 'grey';
ctx.fillRect(i,j,9,9);
j+=9;
}
i+=9;
}
//点击矩阵时矩阵变色
canvas.addEventListener("click", function(event) {
p=getEventPosition(event);
var i=parseInt(p.x/10)*10;
var ii=parseInt(p.x/10);
var jj=parseInt(p.y/10);
var j=parseInt(p.y/10)*10;
ctx.fillStyle="blue";
ctx.fillRect(i,j,9,9);
world[jj][ii]=1;
});
//获取鼠标点击canvas的位置
function getEventPosition(ev){
var x, y;
if (ev.layerX || ev.layerX == 0) {
x = ev.layerX;
y = ev.layerY;
}
return {x: x, y: y};
}
//更新图像
function updateWorld(){
stateUpdate(world);
for(var i=0;i<20;i++){
for(var j=0;j<30;j++)
{
ctx.fillStyle = 'grey';
ctx.fillRect(j*10,i*10,9,9);
if(world[i][j]==1)
{
ctx.fillStyle="blue";
ctx.fillRect(j*10,i*10,9,9);
}
}
}
}
//获取speedValue的值
speed.addEventListener("click",function(){
speedValue=speed.value;
clearInterval(timer);
if (!pause)
startAutoPlay();
})
//自动更新
function startAutoPlay(){
speedValue=speed.value;
timer=setInterval(function(){
updateWorld();
},speedValue);
pause = false;
}
//停止更新
function stopAutoPlay(){
if(timer){
clearInterval(timer);
}
pause = true;
}
//点击start按钮后自动更新
function pageLoad(){
start.onclick=startAutoPlay;
}
//点击暂停后停止
function stopRun(){
stop.onclick=stopAutoPlay;
}
//点击清除按钮清除canvas上的图像
clear.addEventListener("click",function(){
for(var i=0;i<=300;i++)
{
for(var j=0;j<=200;j++)
{
ctx.fillStyle = 'grey';
ctx.fillRect(i,j,9,9);
j+=9;
}
i+=9;
}
//clear world
for(var i=0;i<20;i++)
{
world[i]=new Array();
for(var j=0;j<30;j++)
{
world[i][j]=0;
}
}
})
pageLoad();
stopRun();