js贪吃蛇游戏实现思路和源码_javascript技巧

WBOY
Release: 2016-05-16 15:05:32
Original
3824 people have browsed it

本文实例为大家分享了js贪吃蛇游戏的相关代码,供大家参考,具体内容如下

    贪吃蛇小游戏  
  

贪吃蛇小游戏

New Game

score:0

Your browser doesn't support the canvas element.
Copy after login

效果图:

思路:

function newgame(){ 重置蛇和分数的数据; 清除interval; 初始化画布; 画一条蛇; 放置食物; 使用定时器(setInterval)使蛇移动(move函数); } function move(){ 根据方向改变蛇头下一格将要到达的位置; 判断游戏是否结束,以及显示结束的原因(包含输赢); 蛇移动一格(moveIn函数); } 对键盘的方向键作监控,当改变方向时,修改全局变量DIR的值(用于存储方向); function moveIn(){ 在蛇头的前一格增加一格作为新的蛇头,并将蛇头的坐标作为第一个元素加入到代表蛇的数组中; if(没吃到食物){ 删除一格蛇尾,在画布中做相应改变; } }
Copy after login

需要注意的是,如果需要在JS中设定canvas中的宽度和高度,和设置其他CSS属性略有不同。

CANVAS.width = MAXWIDTH;CANVAS.height = MAXHEIGHT;

小编还为大家准备了精彩的专题:javascript经典小游戏汇总

以上就是本文的全部内容,希望对大家学习javascript程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!