一個簡單的貪喫蛇小遊戲

js小遊戲 一條簡單的貪喫蛇

代碼複製可用

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>貪喫蛇</title>
		<style>
			body{
				display: flex;
				height: 100vh;
				margin: 0;
				padding: 0;
				justify-content: center;
				align-items: center;
			}
		</style>
	</head>
	<body>
		<canvas id="can" width="400" height="400" style="background: #000;">對不起,你的瀏覽器不支持!</canvas>
	<script>
		var snake=[41,40],
			direction=1,
			food=43,
			n,
			box=document.getElementById("can").getContext("2d");
			
		function draw(seat,color){
			box.fillStyle=color;
			box.fillRect(seat%20*20+1,~~(seat/20)*20+1,18,18);
		}
			document.onkeydown = function(evt){
				direction=snake[1]-snake[0]==(n=[-1,-20,1,20][(evt||event).keyCode-37]||direction)?direction:n;
			}
			!function(){
				snake.unshift(n=snake[0]+direction);
				if(snake.indexOf(n,1)>0||n<0||n>399||direction==1&&n%20==0||direction==-1&&n%20==19){
				alert("game over!");	
				}
				draw(n,"lime");
				if(n==food){
					while(snake.indexOf(food=~~(Math.random()*400))>0);
					draw(food,"yellow");
				}else{
					draw(snake.pop(),"black");
				}
				setTimeout(arguments.callee,150);
			}();
			
			
			
			
			
			
			
			
			
	</script>	
	</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章