网页版贪吃蛇(HTML 5)

 (文字描述太繁琐了, 贪吃蛇算法很经典不多说, 那个伪播放器,不值一提。)

源码: 网页版贪吃蛇 【http://files.cnblogs.com/crystalplus/%E4%B8%A4%E4%B8%AA%E7%BD%91%E9%A1%B5%E6%A0%B7%E4%BE%8B(%E6%97%A0%E9%9F%B3%E4%B9%90%E7%89%88).7z】

显示截图:

//file : mian.css	
body
			{
			
				margin:0px;
				margin-top:20px;
				padding: 0px;
				background-color: gray; 
	
	
			}
			#base
			{
				width:1240px;
				margin-top:20px;
				padding-top: 20px;
				margin: 5px auto;
				padding: 20px;
				border:5px silver  groove;
				position:relative;
				
				box-shadow: 10px 10px 5px #888888;
				border-radius:20px;

				background-color:white;
	
			}
			
			
			#wow
			{
			
				width: 1000px;
				height:350px;
				float:left;
				position:relative;
				
				margin:15px;
				margin-left: 50px;
				padding:15px;
								
			}
			#c{
				
				background:fuchsia url('./def.jpg') no-repeat;
				background-position: -50px;
				margin: 5px;
				float:left;
				border-radius:25px;

				
					
			}
			
			#cav_con
			{
				background-color:black;
				border:15px black  solid;
				
				box-shadow: 10px 10px 5px black;
				border-radius:30px;
			}
			#mycanvas
			{
				background:white  no-repeat url('../images/bg.jpg');
				margin-top: 6px;
				float:left;
				border-radius:25px;


				
			}
			#content{
				background: fuchsia url('../images/slider.jpg') no-repeat;
				float:left;
			   width:336px;
				height:340px;
				
				margin: 10px;
				margin-left: 50px;
				color:fuchsia;
				font-family: Arial, Helvetica, sans-serif;
				font-weight: bold;
				border-radius: 25px;
				box-shadow: 10px 10px 5px black;


						}
			 #content p
			 {
			 	color:white; 
			 	padding:5px;
			 	font: bold 20px Tahoma;
				color: skyBlue;	
				}
			 
			#musicplay{
	
					position:relative;
					float:right;
					text-align:left;
					//margin-top:10px;
					top:0px;
					right:250px;
					}
			#support
			{
				clear:left;
	
			}
			
			footer{
				width:1220px;
				margin: 0px auto;
				padding:10px;
				margin-top:20px;
				border-top: 2px  teal groove;
				font-size:small;
				border-radius:10px;
				background: #EAEAEA;
				color: black;
				font-weight:bold;
				}

			span:hover
				{
					margin:5px;
					color:Skyblue;
					//font-size: 16px;}

  

// file: index.html
<!DOCTYPE html>
<html lang="en">
	<head>
		<title>Just test</title>
		<link type="text/css" href="css/main.css" rel="stylesheet">
			<script src="style/modernizr-1.6.min.js"></script>
		
		<script>
		
		window.addEventListener("load", eventWindowLoaded, false);
		function eventWindowLoaded()
		{

			canvasApp();
		
		}
		
		function canvasSupport()
		{
			return Modernizr.canvas;
		}
		
		function canvasApp()
		{
			if(!canvasSupport())
			{	
			
				return;
			}
			else
			{
			
				var thecanvas = document.getElementById("mycanvas");
				var context = thecanvas.getContext('2d');
			}
			const GAME_STARTED = 1;
			const DOT_SIZE = 10;
			var dots = 3;
			var apple;
			
			var left = false;
			var right = true;
			var up = false;
			var down = false;
			var inGame = true;
			
			var keyPressList = [];
			
			var dotArray ;//= new Array();
			var head = new Image();
			head.src = "./images/head.png";
			var dot = new Image();
			dot.src = "./images/dot.png";
			
			var app = new Image();
			app.src = "./images/apple.png";
			
			var apple = new Apple(80, 50);
			
			initDots();
			
			paint();
			
			
			
			//const FRAME_RATE = 20;
			//var intervalTime = 1000 / FRAME_RATE;
			setInterval(repaint, 180);

						
			document.οnkeydοwn=function(e){
		
			e=e?e:window.event;
			//ConsoleLog.log(e.keyCode + "down");
			keyPressList[e.keyCode]=true;
		}
	
			document.οnkeyup=function(e){
			//document.body.οnkeyup=function(e){
				e=e?e:window.event;
				//ConsoleLog.log(e.keyCode + "up");
				keyPressList[e.keyCode]=false;
		};
		
			
			
		 function checkKeys() {
		
		//check keys
		
				if (keyPressList[38]==true && !down){
					left = false;
					right = false;
					up = true;
					}
			
				if (keyPressList[40]==true && !up){
					left = false;
					right = false;
					down = true;
				  }

		
				if (keyPressList[37] == true && !right) {
					left = true;
					up = false;
					down = false;  
				
				}
		
				if (keyPressList[39] == true && !left) {
					right = true;
					up = false;
					down = false; 
				}
			}
			
			
			function Dot(x1, y1)
			{
				this.PointX = x1;
				this.PointY = y1;
				this.getX = getPointX;
				this.getY = getPointY;
				this.setX = setPointX;
				this.setY = setPointY;

			}
			
			function getPointX()
			{
					return this.PointX;
			}
			
			function getPointY()
			{
					return this.PointY;
			}
			
			function setPointX(e)
			{
					this.PointX += e;
			}
			
			function setPointY(e)
			{
					this.PointY += e;
			}



			
			
			function initDots()
			{
			 dotArray = new Array();
				for(var z = 0; z < dots; z++)
				{
					dotArray.push(new Dot((50 - z * 10), 50));
					
					
				}
				
				apple.localApple();
				
			}
			
			
			
			function Apple(x, y)
			{
			
					this.x = x;
					this.y = y;
					this.localApple = LocalApple;
					this.getx = function(){ return this.x};
					this.gety = function() {return this.y};
			
			}
			
			function checkApple()
			{
				if(dotArray[0].getX() == apple.getx() && dotArray[0].getY() == apple.gety())
				{
				  dots++;
				  dotArray.push(new Dot(0, 0));
				  apple.localApple();
				  
				}
			}
			
			function LocalApple()
			{
				var rx = Math.round(Math.random() * 49);
				this.x =  rx * DOT_SIZE;
				
				var ry = Math.round(Math.random() * 31);
				this.y = ry * DOT_SIZE;
			}
			
			function checkCollision()
			{
				for(var z = dots  ; z > 0; z--)
				{	
					if((z > 4) && (dotArray[0] == dotArray[z] ))
					{
						inGame = false;
					}	
				}
				
				var px = dotArray[0].getX();
				var py = dotArray[0].getY();

				if( py == thecanvas.height)
					{
					 	inGame = false;

					}
				if( py == 0)
				{
					inGame = false;
				}
				
				if( px  == thecanvas.width)
					{
					 	inGame = false;

					}
				if( px == 0)
				{
					inGame = false;
				}

				
			}
			
			function move()
			{
			
				for(var q = dots -1; q > 0; q--)
				{
					dotArray[q ].PointX = dotArray[q -1 ].getX();	
					dotArray[q ].PointY = dotArray[q -1].getY();	
					//dotArray[q] = dotArray[q ];
										
				}
				
				if(left)
				{
					dotArray[0].PointX -= DOT_SIZE;
				}
				
				if(right)
				{
					dotArray[0].PointX += DOT_SIZE;//
					//dotArray[0].setX(DOT_SIZE);
					
				}
				
				if(up)
				{
					dotArray[0].PointY -= DOT_SIZE;
				}
				
				if(down)
				{
					dotArray[0].PointY += DOT_SIZE;
				}


			}
			
			function restart()
			{
				if (keyPressList[32]==true){
	    
						inGame = true;
						left = false;
						right = true;
						up = false;
						down = false; 

						dots = 3;
						delete dotArray;
						initDots();
						
		
					}
			
			}
			
			function gameOver()
			{
				//context.clearRect(0, 0, thecanvas.width, thecanvas.height);

				context.fillStyle = 'aqua';
				context.font = '30px _sans';
				context.textBaseline = 'top';
				context.fillText ("Game Over!", 150, 130); 
				context.fillText ("Press Space  key to restart!", 80, 160); 

				
			}
			
			function paint()
			{			
				context.clearRect(0, 0, thecanvas.width, thecanvas.height);
					
				  if (inGame) {
            
				  context.drawImage(app, apple.x, apple.y);
			      context.save();	
					 
          			 for (var e = 0; e < dots; e++) {
						 if (e == 0)
						 {
						  context.drawImage(head, dotArray[e].PointX, dotArray[e].PointY);
						}
						else
					   {
                			context.drawImage(dot, dotArray[e].PointX, dotArray[e].PointY);
                		}
				}
				context.restore();
          		  
				} else {
           		 gameOver();
        			}
			}
			
				
			function repaint()
			{
			 	if(inGame)
			 	{
			 		
			 		checkApple();
			 		move();
           	 	checkCollision();
           	 	//apple.localApple();	
           	 	checkKeys();
				
				}
				else
				{
					restart();				
				}
						
				 paint();
				
			}
			
			function drawScreen()
			{
					context.clearRect(0, 0, thecanvas.width, thecanvas.height);
					context.drawImage(head, x, y);
					context.drawImage(dot, x, y - 10);
					if(x == 0 || x == thecanvas.width )
					{
							Xstep =  -Xstep;
					}
					if(y == 0 || y == thecanvas.height)
					{
							Ystep = -Ystep;
					
					}
					
					
					x -= Xstep;
					y -= Ystep;  
					
			}
			//setInterval(drawScreen, 200);
				
		}	
		</script>
	</head>

	<body>
		<div id="base">
		<header >
			<h3 style="color:Skyblue;">: - )The Html Games!!! Snake</h3>
			<aside id="musicplay">
			<audio id="uu" autoplay="autoplay" preload="metadata" autobuffer  οnended="MusicPlayer()"  controls=""  >
				<source src="./music/music.mp3"></source>
				<source src="./music/music.ogg"></source>
			</audio>
			</aside>
			<script>

			function supportedAudioFormat(audio) {
			var returnExtension = "";
		
			 if (audio.canPlayType("audio/mp3") == "probably" || audio.canPlayType("audio/mp3") == "maybe") {
				 returnExtension = ".mp3";
				 
			 }
			else if (audio.canPlayType("audio/ogg") =="probably" || audio.canPlayType("audio/ogg") == "maybe") {
				returnExtension = ".ogg";
					
			}
			return returnExtension;
	
			}
	    	var count_one = 1;
	    	var con = document.getElementById("uu");
	    	con.volume = 0.36;
			//	con.controls="controls";
			var Mnames = new Array();
		    Mnames.push("music");
			Mnames[1] = "sanyue";
		    //Mnames[2] = "Sunshine Girl";
			//	Mnames.push("old boy");
			var where = "./music/";
		
			var audioType = supportedAudioFormat(con);

  	    	function MusicPlayer()
	    	{
				if(con.ended)
				{
					con.src= where + Mnames[count_one] + audioType;
					con.play();
				
				}

				if(count_one != Mnames.length - 1)
				{
				  count_one++;
				}
				else
				{
				count_one = 0;
				}
					
	     	}

			</script>

		</header>
		<div id="wow">
			<div id ="cav_con" style="float:left;">
			<canvas id="mycanvas" width="500px" height="320px" >
			Your browser does not support Html 5
			</canvas>
			</div>
			<div id="content"   >
				
			 <p > This is a Demo and Expression</p>
			 <p> ToRight : Right Array Key </p>

            

			<p>Fire :  Space Key</p>

			<P>ToLeft : Left Array Key </p>
			</div>
			
				
			
		</div>

		<!--<p id="support" οnclick="support_html()">Click me :- D, check whether your browser supports Html 5</p>-->
		
		<div id="support">
			<footer><span class="copyright"> 2011 Made By Thomas.</span></footer>
		
		</div>
		
	</div>
	
</body>
</html>

  

转载于:https://www.cnblogs.com/crystalplus/archive/2011/11/26/2264178.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的贪吃蛇游戏的 HTML 代码,你可以在浏览器中打开并运行它: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>贪吃蛇游戏</title> <style> canvas { border: 1px solid black; } </style> </head> <body> <canvas id="gameCanvas" width="400" height="400"></canvas> <script> let canvas = document.getElementById('gameCanvas'); let ctx = canvas.getContext('2d'); let snake = [{x: 10, y: 10}]; let food = {x: 5, y: 5}; let direction = 'right'; function update() { // 更新贪吃蛇的位置 let head = {x: snake[0].x, y: snake[0].y}; switch (direction) { case 'left': head.x--; break; case 'right': head.x++; break; case 'up': head.y--; break; case 'down': head.y++; break; } snake.unshift(head); // 检测是否吃到食物 if (head.x === food.x && head.y === food.y) { food.x = Math.floor(Math.random() * 20); food.y = Math.floor(Math.random() * 20); } else { snake.pop(); } // 检测游戏是否结束 if (head.x < 0 || head.x >= 20 || head.y < 0 || head.y >= 20) { gameOver(); } for (let i = 1; i < snake.length; i++) { if (head.x === snake[i].x && head.y === snake[i].y) { gameOver(); } } } function draw() { // 绘制背景 ctx.fillStyle = 'white'; ctx.fillRect(0, 0, canvas.width, canvas.height); // 绘制贪吃蛇 ctx.fillStyle = 'green'; for (let i = 0; i < snake.length; i++) { ctx.fillRect(snake[i].x * 20, snake[i].y * 20, 20, 20); } // 绘制食物 ctx.fillStyle = 'red'; ctx.fillRect(food.x * 20, food.y * 20, 20, 20); } function gameOver() { clearInterval(gameLoop); alert('游戏结束!'); } function gameLoop() { update(); draw(); } document.addEventListener('keydown', event => { switch (event.keyCode) { case 37: // left arrow if (direction !== 'right') { direction = 'left'; } break; case 38: // up arrow if (direction !== 'down') { direction = 'up'; } break; case 39: // right arrow if (direction !== 'left') { direction = 'right'; } break; case 40: // down arrow if (direction !== 'up') { direction = 'down'; } break; } }); let gameLoop = setInterval(() => { gameLoop(); }, 100); </script> </body> </html> ``` 这个代码创建了一个 400x400 的画布,用于绘制贪吃蛇游戏。它定义了一个 `canvas` 元素、一个 `gameLoop` 函数和一些变量,以及一些用于更新和绘制游戏状态的函数。它还通过 `setInterval` 函数每 100 毫秒调用一次 `gameLoop` 函数来运行游戏。 你可以将这个代码复制到一个文本编辑器中,并将文件保存为 `.html` 格式,然后在浏览器中打开它,就可以玩贪吃蛇游戏了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值