原本要继续研究塔防游戏,但发现寻路算法搞不定,其实算法压根看不懂,看的头晕,炮塔自动追踪移动物体也搞不定,塔防项目得延迟了。所以,就搞了另外一个游戏,键盘打字母游戏,老样子,因为初学javascript,代码比较乱,见谅。
游戏难点:
1.字母初始化
2.一个字母消失后,自动补充一个
3.字母运动
想必大家也看出来了,游戏比较简单,直接开始js部分。
字母类
//字母类
function Word(){
this.x=[];
this.y=[];
this.aLive=[];
this.spd=[];
this.larr=[];//绘制所需数组
this.color=[];
this.xColor;//选择颜色
this.letters=[];//字母集合数组
}
Word.prototype.sum=5;//屏幕中最多有50个字母
Word.prototype.init=function(){
this.letters=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
this.color=['yellow','red','blue','green'];
for(var i=0;i600){
this.y[i]=0;
}
if(i>=1){
if(this.y[i]-this.y[i-1]<30){
this.y[i]=this.y[i-1]+41;
}
}
var arrL=this.letters[Math.floor(Math.random()*48)];//随机排序
this.larr.push(arrL);
this.spd[i]=Math.random()*0.017+0.003;//速度区间在[0.01-0.015)
}
}
Word.prototype.draw=function(){
for(var i=0;i600){
this.y[i]=0;
}
this.larr.splice(i,1,this.letters[Math.floor(Math.random()*48)]);//删除数组对应字母,并在原位置插入,确保顺序
this.aLive[i]=true;//字母重新生成
}
上面类属性基本上都是采用数组方式,为什么呢?因为字母有多个,多个物体运动必须有多个物体坐标,速度等,字母触碰边界消失,按键触发消失,以上代码有详细注释,不多说了。
接下来就是游戏必不可少的鼠标事件,按键事件
//按键事件
keysDown={};//保存按键事件
window.addEventListener('keydown',function(e){
keysDown[e.keyCode]=true;
e=event||window.event;
for(var i=0;i708&&mx<730&&my>120&&my<130){
canvas.style.cursor='pointer';
ctx.fillText('黄色',708,130);
}
else if(mx>748&&mx<770&&my>120&&my<130){
canvas.style.cursor='pointer';
ctx.fillText('红色',748,130);
}
else if(mx>708&&mx<730&&my>160&&my<170){
canvas.style.cursor='pointer';
ctx.fillText('蓝色',708,170);
}
else if(mx>748&&mx<770&&my>160&&my<170){
canvas.style.cursor='pointer';
ctx.fillText('绿色',748,170);
}
else{
canvas.style.cursor='default';
ctx.beginPath();
//设置字体样式
ctx.font = "12px Courier New";
//设置字体填充颜色
ctx.fillStyle ='blue';
//从坐标点(50,50)开始绘制文字
ctx.fillText('请选择字母颜色',708,100);
ctx.fillText('黄色',708,130);
ctx.fillText('红色',748,130);
ctx.fillText('蓝色',708,170);
ctx.fillText('绿色',748,170);
ctx.closePath();
}
ctx.restore();
},false);
//鼠标点击
window.addEventListener('click',function(e){
if(e.offSetX||e.layerX){//兼容性写法
//三元运算符
mx=e.offSetX==undefined?e.layerX:e.offSetX;
my=e.offSetY==undefined?e.layerY:e.layerY;
}
if(mx>708&&mx<730&&my>120&&my<130){
xColor=0;
}
else if(mx>748&&mx<770&&my>120&&my<130){
xColor=1;
}
else if(mx>708&&mx<730&&my>160&&my<170){
xColor=2;
}
else if(mx>748&&mx<770&&my>160&&my<170){
xColor=3;
}
},false);
采用addEventListener事件绑定,这样做好处就是响应更加紧凑,而且可以实现(玩家)斜着运动,这里用来绑定鼠标移动,鼠标点击,键盘事件。鼠标移动事件主要是为了字母颜色选择时候,字体变色(类似鼠标经过效果),鼠标点击事件就是增加响应颜色属性,改变字母颜色。键盘事件主要用到String.fromCharCode(e.keyCode)返回按键字符串,当然是大写的,所以判断时候,要将画布上字母进行大写转换word.larr[i].toLocaleUpperCase(),否则小写字母,不会消失。
字母绘制,文本绘制
//设置字体样式
ctx.font = "12px Courier New";
//设置字体填充颜色
ctx.fillStyle ='blue';
//从坐标点(50,50)开始绘制文字
ctx.fillText('请选择字母颜色',708,100);
接下来的不过就是不断循环刷新画布,让字母运动,这里不再多说,感觉我也说不清楚。大家有兴趣可以去 慕课网 找 爱心鱼游戏视频教程看看,里面有专门讲解。