其他分享
首页 > 其他分享> > Canvas贪吃蛇小游戏

Canvas贪吃蛇小游戏

作者:互联网

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>贪吃蛇</title>
    <style>
        .wrap{
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
        .header{
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 900px;
            height: 50px;
        }
    </style>
</head>
<body>
    <div class="wrap">
        <div class="header">
            <p>
				<button id="start" type="button">开始游戏</button>
				<span>得分:</span><span class="score">0</span>分
			</p>
        </div>
        <div class="content">
            <canvas id="canvas" width="900" height="650" style="border:5px solid teal;"></canvas>
        </div>
        <div class="footer">
			<span>按键:</span>
			&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
		   1:小蛇加速 
		   &nbsp;&nbsp;&nbsp;&nbsp;
		   2:小蛇减速
		   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
           space-空格键 暂停/继续  
		   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
		   ↑ ↓ ← → 控制方向
        </div>
    </div>
	
	<img hidden="hidden" src="image/up.png" id="up">
	<img hidden="hidden" src="image/down.png" id="down">
	<img hidden="hidden" src="image/left.png" id="left">
	<img hidden="hidden" src="image/right.png" id="right">
	<img hidden="hidden" src="image/food.png" id="food">
	<img hidden="hidden" src="image/body.png" id="body">
	
    <script>
		
		/**
		 * 蛇-移动-吃食物
		 * 
		 * 获取贪吃蛇图片
		 * 
		 * 初始化参数
		 * 按键设置
		 * 食物随机
		 * 判断食物是否被吃
		 * 画 背景-蛇-食物
		 * 
		 */
		
		window.onload = function(){	
			
			// 获取图片
			var up = document.getElementById('up');
			var down = document.getElementById('down');
			var left = document.getElementById('left');
			var right = document.getElementById('right');
			var foods = document.getElementById('food');
			var body = document.getElementById('body');
		  
			var canvas = document.getElementById('canvas');
			var ctx = canvas.getContext("2d");

			var start_btn = document.getElementById('start');

			
			// 定义初始值
			var length;
			var snakeX = new Array(816);//蛇的X
			var snakeY = new Array(816);//蛇的Y
			var foodX;
			var foodY;
			var direction = "right";
			var score;
			var timeout;
			
			init();
			var time;
			
			
			function start(){
				// 定时
				time = setInterval(function(){
					getKey();
					eat();
					draw();
					die();
					move();
					document.getElementsByClassName('score')[0].innerHTML = score;
				},timeout)
			}
			// 初始化
			function init(){
				length = 3;
				snakeX[0] = 100;snakeY[0] = 100;
				snakeX[1] = 75;snakeY[1] = 100;
				snakeX[2] = 50;snakeY[2] = 100;
				Food();
				score = 0;
				timeout = 100;
			}
			
			// 移动
			function move(){
				for (var i = length-1; i > 0; i--) {
					snakeX[i]=snakeX[i-1];
					snakeY[i]=snakeY[i-1];
				}
				if (direction == "right"){
					snakeX[0] = snakeX[0]+25;
					if (snakeX[0]>850) snakeX[0] = 25;
				}else if (direction == "left"){
					snakeX[0] = snakeX[0]-25;
					if (snakeX[0]<25) snakeX[0] = 850;
				}else if (direction == "up"){
					snakeY[0] = snakeY[0]-25;
					if (snakeY[0]<25) snakeY[0] = 600;
				}else if (direction == "down"){
					snakeY[0] = snakeY[0]+25;
					if (snakeY[0]>600) snakeY[0] = 25;
				}
			}
			
			// 画图
			function draw(){
				ctx.fillStyle = "#333333"
				ctx.fillRect(25,25,850,600);
				// 食物
				ctx.drawImage(foods,foodX,foodY,25,25);
				//蛇的头通过方向变量来判断
				if (direction == "right"){ 
					ctx.drawImage(right,snakeX[0],snakeY[0],25,25);
				}else if (direction == "left"){
					ctx.drawImage(left,snakeX[0],snakeY[0],25,25);
				}else if (direction == "up"){
					ctx.drawImage(up,snakeX[0],snakeY[0],25,25);
				}else if (direction == "down"){
					ctx.drawImage(down,snakeX[0],snakeY[0],25,25);
				}
				// 身体
				for (var i = 1; i <length; i++) {
					ctx.drawImage(body,snakeX[i],snakeY[i],25,25);
				}
			}
			
			// 蛇吃到食物
			function eat(){
				if(foodX == snakeX[0]&&foodY == snakeY[0]){
					length++;
					score=score+10;
					Food();
				}
			}
			
			// 获取按键
			function getKey() {
				document.onkeydown=function(event){
					var e = event || window.event || arguments.callee.caller.arguments[0];
					if(e && e.keyCode==38){//上
						if (direction !== 'down')
						direction = 'up'
					}
					if(e && e.keyCode == 37){//左
						if (direction !== 'right')
						direction = 'left'
					}
					if(e && e.keyCode == 39){//右
						if (direction !== 'left')
						direction = 'right'
					}
					if(e && e.keyCode == 40){//下
						if (direction !== 'up')
						direction = 'down'
					}
					if(e && e.keyCode == 32){//空格
						confirm("游戏已暂停")
					}
					// 加速
					if(e && e.keyCode == 49){//1
						clearInterval(time)
						timeout-=10;
						time = setInterval(function(){
							getKey();
							eat();
							draw();
							die();
							move();
							document.getElementsByClassName('score')[0].innerHTML = score;
						},timeout)
					}
					// 减速
					if(e && e.keyCode == 50){//2
						clearInterval(time)
						timeout+=10;
						time = setInterval(function(){
							getKey();
							eat();
							draw();
							die();
							move();
							document.getElementsByClassName('score')[0].innerHTML = score;
						},timeout)
					}
				};
			}
			
			// 失败判定
			function die(){
				for (var i = 1; i < length; i++) {
					if(snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]){
						fail()
						alert("游戏失败")
						start_btn.removeAttribute("disabled")
					}
				}
			}
			
			//时间停止
			function fail(){
				clearInterval(time)
			}
			
			// 食物位置
			function Food(){
				foodX = 25+parseInt(Math.random() * 34) * 25;
				foodY = 25+parseInt(Math.random() * 24) * 25;
			}
			
			draw();
			
			// 点击开始
			start_btn.onclick = function(){
				init();
				start();
				start_btn.setAttribute("disabled",true)
			}
		}

    </script>
</body>
</html>

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

标签:25,Canvas,direction,snakeX,snakeY,小游戏,nbsp,贪吃蛇,var
来源: https://blog.csdn.net/weixin_48736541/article/details/117772843