用html js制作迷宫,JavaScript生成随机迷宫详解

本篇教程介绍了JavaScript生成随机迷宫详解,希望阅读本篇文章以后大家有所收获,帮助大家对JavaScript的理解更加深入。

<

#先看生成随机迷宫的代码吧↓

生成随机迷宫v1.0

7     

8     

生成随机迷宫v1.0

9     刷新

10 

11 

12 

13 var width = 1600;

14 var height = 800;

15 var cellWidth = 40;

16 var canvas = document.getElementById("myCan1");

17 var cxt = canvas.getContext("2d");

18 // 初始化canvas容器

19 function initCanvas() {

20     canvas.width = width;

21     canvas.height = height;

22     canvas.style = "border-radius: 15px";

23     canvas.style.border = "1px solid #3b3b3b";

24 };

25 initCanvas();

26 // 初始化画布

27 function initContext(cxt) {

28     cxt.lineCap="round";

29     cxt.lineJoin="round";

30     cxt.lineWidth = 1;

31 }

32 initContext(cxt);

33 // 开始画迷宫

34 function drawMaze(cxt) {

35     drawSingleBox(8, 0, 0, cxt);

36 };

37 /*setInterval(function(){

38     cxt.clearRect(0, 0, width, height);

39     drawMaze(cxt);

40 }, 50);*/

41 drawMaze(cxt);

42 // 递归画单元格

43 function drawSingleBox(option, posX, posY, cxt){

44     //cxt.strokeStyle = getColor();

45     switch(option){

46     case 0:

47         cxt.beginPath();

48         cxt.moveTo(posX, posY);

49         cxt.lineTo(posX + cellWidth, posY);

50         cxt.stroke();

51         break;

52     case 1:

53         cxt.beginPath();

54         cxt.moveTo(posX + cellWidth, posY);

55         cxt.lineTo(posX + cellWidth, posY + cellWidth);

56         cxt.stroke();

57         break;

58     case 2:

59         cxt.beginPath();

60         cxt.moveTo(posX, posY + cellWidth);

61         cxt.lineTo(posX + cellWidth, posY + cellWidth);

62         cxt.stroke();

63         break;

64     case 3:

65         cxt.beginPath();

66         cxt.moveTo(posX, posY);

67         cxt.lineTo(posX, posY + cellWidth);

68         cxt.stroke();

69         break;

70     }

71     if(posX >= width - cellWidth && posY >= height - cellWidth) {

72         return;

73     } else {

74         posX += cellWidth;

75         if(posX >= width){

76             posX = 0;

77             posY += cellWidth;

78         }

79         drawSingleBox(Math.floor(Math.random()*4), posX, posY, cxt);

80     }

81 }

82 // 随机出任意颜色

83 function getColor(){

84     var colorElements = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f";

85     var colorArray = colorElements.split(",");

86     var color ="#";

87     for(var i =0;i<6;i++){

88         color+=colorArray[Math.floor(Math.random()*16)];

89     }

90     return color;

91 }

92 

93 

生成随机迷宫

#去掉代码注释,神奇的一幕出现了,自己看看吧

1 setInterval(function(){

2     cxt.clearRect(0, 0, width, height);

3     drawMaze(cxt);

4 }, 50);

去掉此段代码的注释

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标WEB前端JavaScript频道!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值