欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用js实现贪食蛇游戏

程序员文章站 2022-07-13 08:28:50
...

1、游戏说明

 

 

1) 用户可自定义贪食蛇行走速度(数字越大速度越快)及阻挡物个数(随机生成)。

2) 按“回车键”或“开始游戏”按钮开始游戏。

3) 按“方向键”控制贪食蛇行走方向。

4) 按“空格”或“开始/暂停游戏”按钮开始/暂停游戏。

 

2、效果图


使用js实现贪食蛇游戏
 
3、html页面

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>贪食蛇</title>
<link href="css/snake.css" rel="stylesheet"  />
<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="js/snake.js"></script>
</head>

<body>
<div class="operate">
	<div id="start">
        贪食蛇速度:
        <select id="speed" style="width:100px;">
        	<option value="10" >1</option>
        	<option value="8" >2</option>
        	<option value="6" selected="selected" >3</option>
        	<option value="4" >4</option>
        	<option value="2" >5</option>
        </select>
        <br /><br />
        阻挡物个数:<input type="text" value="5" id="wall" style="width:100px;" />
        <br /><br />
        <input type="button" onclick="startGame();" value="开始游戏" />
    </div>
    <div id="restart" style="display:none;">
		<input type="button" id="pause" onclick="pauseGame();" value="暂停游戏" />
		<input type="button" onclick="restartGame();" value="重新开始" />
    </div>
    <div id="result"></div>
    <div class="tip">
   		<hr />
    	<ul>
        	<li><div class="tip_color" style="background:red;"></div><span class="tip_font">蛇头</span></li>
        	<li><div class="tip_color" style="background:green;"></div><span class="tip_font">蛇体</span></li>
        	<li><div class="tip_color" style="background:#660000;"></div><span class="tip_font">食物</span></li>
        	<li><div class="tip_color" style="background:#6699FF;"></div><span class="tip_font">阻挡物</span></li>
            <br /><br />
        	<li><span class="tip_short"><b>游戏操作说明:</b></span></li>
        	<li><span class="tip_short">1.用户可自定义贪食蛇行走速度(数字越大速度越快)及阻挡物个数(随机生成)。</span></li>
        	<li><span class="tip_short">2.按“回车键”或“开始游戏”按钮开始游戏。</span></li>
        	<li><span class="tip_short">3.按“方向键”控制贪食蛇行走方向。</span></li>
            <li><span class="tip_short">4.按“空格”或“开始/暂停游戏”按钮开始/暂停游戏。</span></li>
        </ul>
    </div>
</div>
</body>
</html>

 
4、js

 

// 游戏名称:贪食蛇
// 作者:Sailqi
// 版本:1.0
// 日期:2011-09-22

var ground_rows = 60;//场地行数
var ground_columns = 60;//场地列数
var ground_width = 600;//场地宽度
var ground_height = 600;//场地高度

var x_step = ground_width / ground_columns;
var y_step = ground_height / ground_rows;

var points = new Array();//各点坐标数组
var snake = new Array();//贪食蛇各点数据
var refreshTimer = 200;//贪食蛇速度

var snakeHeadColor = "red";//蛇头颜色
var snakeColor = "green";//贪食蛇颜色
var foodColor = "#660000";//食物颜色
var wallColor = "#6699FF";//墙壁颜色

var groundObj;//场地JQuery对象

//行走方向 1左 2上 3右 4下
var direction = 3;
var pre_direction = direction;

var isStart = false;
var isPause = false;

//方块信息对象
function point(row, column, id, type){
	this.row = row;
	this.column = column;
	this.id = id;
	this.type = type;//1空方块,2墙,3蛇体,4食物
}

$(document).ready(function(){
	document.onkeydown = keydown;
	init();
});

//开始游戏
function startGame(){
	
	//生成食物
	groundObj.append(createRandomBlock(4));
	
	//生成初始化贪食蛇
	var snakeP;
	snakeP = points[1][1];
	snakeP.type = 3;
	snake.push(snakeP);
	groundObj.append(createBlock(snakeP));
	
	//速度
	refreshTimer = parseInt($("#speed").val()) * 50;
	//阻挡物
	var wallNum = parseInt($("#wall").val());
	for(k = 0; k < wallNum; k++){
		groundObj.append(createRandomBlock(2));
	}
	
	isStart = true;
	
	$("#start").hide();
	$("#restart").show();
	
	timer();
}

//重新开始
function restartGame(){
	location.reload();
}
//暂停/继续游戏
function pauseGame(){
	isPause = !isPause;
	if(isPause){
		$("#pause").val("继续游戏");
	} else{
		$("#pause").val("暂停游戏");
	}
}

//初始化数据、界面
function init(){
	$("body").append('<div id="ground" style="width:' + ground_width + 'px;height:' + ground_height + 'px;"></div>');
	groundObj = $("#ground");
	
	//场地各点坐标
	var max_x = ground_columns + 1;
	var max_y = ground_rows + 1;
	for(i = 0; i <= max_x; i++){
		points[i] = new Array();
		for(j = 0; j <= max_y; j++){
			if( i == 0 || i == max_x || j == 0 || j == max_y){//四周围墙
				points[i][j] = new point(i, j, "point" + i + "_" + j, 2);
				groundObj.append(createBlock(points[i][j]));
			} else{
				points[i][j] = new point(i, j, "point" + i + "_" + j, 1);
			}
		}
	}
	
}

//创建实际方块
//p 方块信息
function createBlock(p){
	var blockColor = "";
	if(p.type == 2){//墙壁
		blockColor = wallColor;
	} else if(p.type == 3){//蛇体
		blockColor = snakeColor;
	} else if(p.type == 4){//食物
		blockColor = foodColor;
	}
	var left = x_step * (p.column - 1);
	var top = y_step * (p.row - 1);
	var blockHtml = '<div id="' + p.id 
					+ '" style="width:' + x_step + 'px;'
					+ 'height:' + y_step + 'px;'
					+ 'background:' + blockColor  + ';'
					+ 'left:' + left + 'px;'
					+ 'top:' + top + 'px;'
					+ '"></div>';
	return blockHtml;
}

//随机生成方块
function createRandomBlock(type){
	var i = Math.floor(Math.random() * ground_columns + 1);
	var j = Math.floor(Math.random() * ground_rows + 1);
	var pt = points[i][j];
	//判断该位置是否已被占用
	if(pt.type != 1)
		return createRandomBlock(type);
	pt.type = type;
	return createBlock(pt);
}

//获取前进方向方块信息
function getBlock(){
	var current = snake[snake.length-1];
	var next;
	var row = 0, column = 0;
	switch(direction){
		case 1://左
			row = current.row;
			column = current.column - 1;
			break;
		case 2://上
			row = current.row - 1;
			column = current.column;
			break;
		case 3://右
			row = current.row;
			column = current.column + 1;
			break;
		case 4://下
			row = current.row + 1;
			column = current.column;
			break;
		default:
			return;
	}
	next = points[row][column];
	return next;
}

//蛇头颜色替换
function changeColor(){
	var snakeLength = snake.length;
	if(snakeLength > 1){
		$("#" + snake[snake.length-2].id).get(0).style.background = snakeColor;
	}
	$("#" + snake[snake.length-1].id).get(0).style.background = snakeHeadColor;
}

//刷新贪食蛇长度、位置
function refreshSnake(next){
	switch(next.type){
		//前面是空方块
		case 1:
			//移除尾部方块
			var tail = snake.shift();
			tail.type = 1;
			$("#" + tail.id).remove();
			//新增头部方块
			next.type = 3;
			snake.push(next);
			groundObj.append(createBlock( next));
			changeColor();
			break;	
		//前面是墙
		case 2:
			isStart = false;
			break;
		//前面是蛇本身
		case 3:
			if(Math.abs(direction - pre_direction) == 2){
				direction = pre_direction;
				break;
			}
			isStart = false;
			break;
		//前面是食物
		case 4:
			//移除食物方块
			$("#" + next.id).remove();
			//新增头部方块
			next.type = 3;
			snake.push(next);
			groundObj.append(createBlock(next));
			//重新生成食物
			groundObj.append(createRandomBlock(4));
			changeColor();
			break;	
	}
}

function showResult(){
	var score = snake.length;
	var result = "游戏结束!<br />您的成绩为:" + snake.length + "分。<br />";
	if(score < 6) result +="等级:差";
	else if(score >= 6 && score < 15) result += "等级:及格";
	else if(score >= 15 && score < 30) result += "等级:良好";
	else if(score >= 30 && score < 40) result += "等级:优秀";
	else if(score >= 40 && score < 50) result += "等级:牛人";
	else if(score >= 50 && score < 60) result += "等级:神人";
	else if(score >=60 && score < 70) result += "等级:立地成佛";
	else if(score >=70) result += "等级:无人能及";
	$("#result").html(result);
}
//定时器
function timer(){
	if(!isPause){
		if(isStart){
			refreshSnake(getBlock());
		} else{
			showResult();
			return;
		}
	}
	setTimeout("timer();", refreshTimer);
}

//监听键盘(方向键)
function keydown(evt)
{
	var evt = evt || event;
	var currKey = evt.keyCode || evt.which || evt.charCode;
	if(currKey == 13 || currKey == 32 || (currKey > 36 && currKey < 41))
	{
		pre_direction = direction;
		switch(currKey)
		{
			//回车键
			case 13:
				if(!isStart){
					startGame();
				}
				break;
			//空格键
			case 32:
				isPause = !isPause;
				break;
			//左方向键
			case 37:
				direction = 1;
				break;
			//上方向键
			case 38:
				direction = 2;
				break;
			//右方向键
			case 39:
				direction = 3;
				break;
			//下方向键
			case 40:
				direction = 4;
				break;
			//其它
			default:
				break;
		};
	}
}


5、css

@charset "utf-8";
/* CSS Document */
div{
	position: absolute;
}
/*场地*/
#ground{
	margin-left: 200px;
	margin-top: 50px;
}

.operate{
	width: 300px;
	height: 600px;
	margin-left: 900px;
	margin-top: 40px;
	border: 1px solid #6699FF;
	padding: 10px 10px 10px 10px;
}
/*用户自定义、控制面板*/
#start, #restart{
	margin-top:20px;
	margin-left: 20px;
}

/*结果显示*/
#result{
	margin-top:100px;
 	color: #FF0000;
	font-size: 20px;
	font-weight: bold;
	text-align: center;
	width:280px;
	height: 100px;
}
/*游戏说明*/
.tip{
	margin-top:200px;
}

.tip ul, .til ul li{
	list-style: none;
	margin-top: 30px;
	padding-left: 20px;
	width:280px;
}
/*方块*/
.tip_color{
	width:15px;
	height:15px;
}

/*方块颜色说明*/
.tip_font{
	width:50px;
	margin-left: 30px;
	overflow: scroll;
}

/*快捷键*/
.tip_short{
	height:20px;
	line-height: 23px;
}

/*水平线*/
hr{
	color: #6699FF;
}

 

6、源代码已打包,见附件Snake.zip。

 

相关标签: js 贪食蛇