昔、どっかの雑誌で迷路探索というのがあって、
探索はいらないのでシンプルに迷路だけを表示できるように、
不要な部分を消してみました、これはもっとスリム化できますでしょうか?
(単純に2D迷路だけを表示するために不必要な部分は他にありますか?)
他にも要らなさそうな部分をいろいろ消してみたんですが、迷路が表示されなくなりました。
いろいろ迷路を描く方法はあると思いますが、
これは1と0だけで迷路を表現できて
迷路デザインも自由にできて、一番効率よく描けるので
気に入っています。
何か助言あればお願いします。
JavaScript
1 2<!DOCTYPE; HTML> 3<html lang="ja"> 4<head> 5 <meta charset="UTF-8"/> 6 <title>MAZE</title> 7 <style>canvas{ background-color:#00FFFF;}</style> 8</head> 9<body> 10<canvas width="480" height="360" id="canvas"></canvas> 11 12<script type="text/javascript"> 13var canvas = document.getElementById("canvas"); 14var context = canvas.getContext("2d"); 15 16var maze = 17 [[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], 18 [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], 19 [1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1], 20 [1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1], 21 [1,0,1,0,0,0,0,0,0,0,0,0,0,1,1,1], 22 [1,0,1,0,1,1,1,0,1,1,1,1,0,1,1,1], 23 [1,0,1,0,1,1,1,0,1,1,1,1,0,1,1,1], 24 [1,0,1,0,1,1,1,0,1,1,1,1,0,1,1,1], 25 [1,0,1,0,1,1,1,0,1,1,1,1,0,1,1,1], 26 [1,0,1,0,1,1,1,1,1,1,1,1,0,1,1,1], 27 [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], 28 [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]; 29 30 31var queue = new Array(); 32var route = new Array(12); 33 34for(var i=0; i<12; i++){ 35 route[i] = new Array(16); 36} 37 38var WALKED = 99; 39var isGoal = false; 40 41var startPos = {x:1,y:1}, goalPos = {x:13,y:9}; 42queue.push({x:startPos.x,y:startPos.y}); 43 44 45var mazeDraw=function(){ 46 for(y=0; y<12; y++){ 47 for(x=0; x<16; x++){ 48 49 if(maze[y][x] == 1) { 50 context.fillStyle = "rgb(150,200,100)"; 51 context.fillRect(x*30, y*30, 30, 30); 52 } 53 if(maze[y][x] == WALKED){ 54 context.fillStyle = "rgb(80,100,150)"; 55 context.fillRect(x*30, y*30,30,30); 56 } 57 } 58} 59context.fillStyle = "rgb(100,100,200)"; 60context.fillRect(startPos.x*30, startPos.y*30,30,30); 61context.fillStyle = "rgb(255,255,0)"; 62context.fillRect(goalPos.x*30, goalPos.y*30,30,30); 63} 64 65 66var BFS = function(){ 67 var pos =queue.shift(); 68 var x = Pos.x; 69 var y = Pos.y; 70 71 72if(x==goalPos.x && y == goalPos.y){ 73 context.fillStyle="rgb(150,150,0)"; 74 for(;;){ 75 pos=route[y][x]; 76 if(pos.px==startPos.x && pos.py==startPos.y){ 77 break; 78 } 79 context.fillRect(Pos.px*30, Pos.py*30, 30, 30); 80 x = Pos.px; 81 y = Pos.py; 82 83 } 84 alert("goal"); 85 isGoal=true; 86 return; 87} 88 if(maze[y-1][x] == 0){ 89 queue.push({x:x,y:y-1}); 90 route[y-1][x] = {px:x,py:y}; 91 maze[y-1][x] = WALKED; 92 } 93 if(maze[y+1][x] == 0){ 94 queue.push({x:x,y:y+1}); 95 route[y+1][x] = {px:x,py:y}; 96 maze[y+1][x] = WALKED; 97 } 98 if(maze[y][x-1] == 0){ 99 queue.push({x:x-1,y:y}); 100 route[y][x-1] = {px:x,py:y}; 101 maze[y][x-1] = WALKED; 102 } 103 if(maze[y][x+1] == 0){ 104 queue.push({x:x+1,y:y}); 105 route[y][x+1] = {px:x,py:y}; 106 maze[y][x+1] = WALKED; 107 } 108 109return; 110 111 } 112 113window.onload= mazeDraw ; 114 115var walk = function(){ 116 if(!isGoal){ 117mazeDraw(); 118BFS(); 119} 120} 121 122</script> 123</body> 124</html> 125 126
回答1件
あなたの回答
tips
プレビュー