当前位置: 代码迷 >> Web前端 >> 假日写了双人玩的贪吃蛇,纯新手, 欢迎大家拍砖
  详细解决方案

假日写了双人玩的贪吃蛇,纯新手, 欢迎大家拍砖

热度:753   发布时间:2012-10-29 10:03:53.0
假期写了双人玩的贪吃蛇,纯新手, 欢迎大家拍砖
近期学习js,假期无事,参照网上的代码写了个双人玩的贪吃蛇。
对网上的代码作了些改造,具体如下:
1,把m*n的二维数组变成m*n一维数组,映射关系为:
   A[r]------>a[i][j];
   i = r%m;
   j = (r-r%m)/m;
   j<n;
2,对随机数的获取作了些改造,
3,蛇尾总是第一个加入的元素,

代码编写仓促,也没写注释,望各位见谅

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>snake</title>

<script type='text/javascript' >
	(function(){
    if (!window.Snake) 
        window.Snake = {};
    Snake = function(container, name){
        this.container = container;
        this.name = '_' + name + '_';
        this.dir = 0;
        this.testDir = 0;
        this.head = -1;
        this.run = 0;
		this.speed=300;
		this.count={};
        
        if (typeof Snake.prototype._init == 'undefined') {
            Snake.prototype.control = function(n){
                if (Math.abs(this.testDir) == Math.abs(n)) 
                    return;
                this.dir = n;
            };
            Snake.prototype.move = function(){
                if (this.container.win) {
                    clearInterval(this.run);
                    return;
                }
                var _left = this.head % this.container.width;
                var _top = (this.head - this.head % this.container.width) / this.container.width;
                this.dir % this.container.width == 0 ? _top += this.dir / this.container.width : _left += this.dir;
                
                if (_left < 0 || _left >= this.container.width || _top < 0 || _top >= this.container.height || (this.container.all[this.head + this.dir] && this.container.all[this.head + this.dir].indexOf(this.name) != -1)) {
                    this.container.win = true;
					alert(this.name+'   lose ~_~');
					
                    return;
                }
                
                if (!this.container.all[this.head + this.dir]) {
                    this.container.all[this.head + this.dir] = this.name;
                    var _div = this.getDivByClass(this.name)[0];
                    this.container.all[parseInt(_div.style.left) / 20 + parseInt(_div.style.top) / 20 * this.container.width] = this.container.all[parseInt(_div.style.left) / 20 + parseInt(_div.style.top) / 20 * this.container.width].replace(this.name, '');
                    _div.style.left = _left * 20 + 'px';
                    _div.style.top = _top * 20 + 'px';
                    this.container.div.appendChild(_div);
                }
                else 
                    if (this.head + this.dir == this.container.food) {
                        var _div = this.getDivByClass(this.container.foodClass)[0];
                        _div.className = this.name;
                        this.container.div.appendChild(_div);
                        this.container.createFood();
                        this.container.all[this.head + this.dir] = this.name;
                        
                    }
                    else {
                    
                        var _str = this.container.all[this.head + this.dir];
                        var _divs = this.getDivByClass(_str);
                        var _div = _divs[0];
                        if (_divs.length > 1 && parseInt(_div.style.left) / 20 + parseInt(_div.style.top) / 20 * this.container.width == this.head + this.dir) {
                            this.container.all[this.head + this.dir] = this.name;
                            _div.className = this.name;
                            this.container.div.appendChild(_div);
                            
                            
                            
                        }
                        else {
                            this.container.all[this.head + this.dir] += this.name;
                            var _div = this.getDivByClass(this.name)[0];
							this.container.all[parseInt(_div.style.left) / 20 + parseInt(_div.style.top) / 20 * this.container.width] = this.container.all[parseInt(_div.style.left) / 20 + parseInt(_div.style.top) / 20 * this.container.width].replace(this.name, '');
                            _div.style.left = _left * 20 + 'px';
                            _div.style.top = _top * 20 + 'px';
						    this.container.div.appendChild(_div);
                        }
                        
                    }
				var lth=this.getDivByClass(this.name).length
				if(lth>=this.container.bet){
					this.container.win=true;
					alert(this.name+' win ^-^');
				}
				this.count.innerHTML=this.name+':  '+lth.toString();
                this.head += this.dir;
                this.testDir = this.dir;
                
            };
            
            Snake.prototype.getDivByClass = function(name){
                var _divs = this.container.div.getElementsByTagName('DIV');
                var _result = [];
                for (var i = 0; i < _divs.length; i++) {
                    if (_divs[i].className == name) 
                        _result.push(_divs[i]);
                }
                return _result;
            };
            
			Snake.prototype.acc=function(n){
				return this.speed+n>50? this.speed+n:this.speed;
			}
            Snake.prototype.init = function(){
                this.head = this.container.getRandom();
                this.container.all[this.head] = this.name;
                var _left = this.head % this.container.width * 20 + 'px';
                var _top = (this.head - this.head % this.container.width) / this.container.width * 20 + 'px';
                var _div = document.createElement('DIV');
                _div.className = this.name;
                _div.style.left = _left;
                _div.style.top = _top;
				this.count=document.createElement('P');
				this.count.innerHTML=this.name+':  1';
				this.container.counts.push(this.count);
                this.container.div.appendChild(_div);
                
            }
        }
        Snake.prototype._init = true;
        
    }
    if (!window.Container) 
        window.Container = {};
    Container = function(width, height, foodClass, bet){
        this.width = width;
        this.height = height;
        this.food = -1;
        this.foodClass = '_' + foodClass + '_';
        this.bet = bet;
        this.win = false;
        this.all = [];
		this.counts=[];
        var _div = document.createElement('DIV');
        _div.className = 'container';
        //_div.style.position = 'absolute';
        _div.style.width = this.width * 20 + 'px';
        _div.style.height = this.height * 20 + 'px';
        this.div = _div;
        this.getRandom = function(){
            var _remain = [];
            for (var i = 0; i < width * height; i++) {
                if (this.all[i]) 
                    continue;
                _remain.push(i);
            }
            var _index = Math.floor(Math.random() * _remain.length);
            return _remain[_index];
        }
        this.createFood = function(){
            var _food = this.getRandom();
            this.food = _food;
            this.all[_food] = this.foodClass;
            var _fDiv = document.createElement('DIV');
            _fDiv.className = this.foodClass;
            var _left = _food % this.width * 20 + 'px';
            var _top = (_food - _food % this.width) / this.width * 20 + 'px';
            _fDiv.style.left = _left;
            _fDiv.style.top = _top;
            this.div.appendChild(_fDiv);
        }
        
    }
    
})();

var container = new Container(30, 30, 'food', 20);
var snakeA = new Snake(container, 'snakeA');
var snakeB = new Snake(container, 'snakeB');
function game(){

    container.createFood();
    snakeA.init();
    snakeB.init();
    
    function allcontrol(e){
        e = e || window.event;
        var n = e.keyCode;
        
        switch (n) {
            case 37:
                snakeA.control(-1);
                break;
            case 38:
                snakeA.control(-container.width);
                break;
            case 39:
                snakeA.control(1);
                break;
            case 40:
                snakeA.control(container.width);
                break;
            case 65:
                snakeB.control(-1);
                break;
            case 87:
                snakeB.control(-container.width);
                break;
            case 68:
                snakeB.control(1);
                break;
            case 83:
                snakeB.control(container.width);
                break;
			case 96:
				if(snakeA.run){
					clearInterval(snakeA.run);
					snakeA.speed=snakeA.acc(-50);
					snakeA.run=setInterval('snakeA.move()',snakeA.acc(-50));
									}
				break;
			case 110:
				if(snakeA.run){
					clearInterval(snakeA.run);
					snakeA.speed=snakeA.acc(20);
					snakeA.run=setInterval('snakeA.move()',snakeA.acc(50));
					}
				break;
			case 71:
				if(snakeB.run){
					clearInterval(snakeB.run);
					snakeB.speed=snakeB.acc(-20);
					snakeB.run=setInterval('snakeB.move()',snakeB.acc(-50));
					}
				break;
			case 72:
				if(snakeB.run){
					clearInterval(snakeB.run);
					snakeB.speed=snakeB.acc(20);
					snakeB.run=setInterval('snakeB.move()',snakeB.acc(50));
					}
				break;
                
        }
        if (!snakeA.run && snakeA.dir) 
            snakeA.run = setInterval('snakeA.move()', 300);
        if (!snakeB.run && snakeB.dir) 
            snakeB.run = setInterval('snakeB.move()', 300);
    }
	var _wrap=document.createElement('DIV');
    _wrap.appendChild(container.counts[1]);
    _wrap.appendChild(container.div);
	_wrap.appendChild(container.counts[0]);
	document.body.appendChild(_wrap);
	var des=document.createElement('DIV');
	des.style.clear='both';
	des.style.position='relative';
	des.style.padding='20px';
	des.innerHTML='snakeA:键盘上↑↓←→代表方向控制,小键盘上0加速,.减速<br/>snakeB:键盘上A W S D代表方向控制,键盘上G加速,H减速<br/>两条蛇可以相互吃掉对方尾部,先吃到20个食物为赢';
	document.body.appendChild(des);
    if (document.addEventListener) {
        document.addEventListener('keydown', allcontrol, false);
    }
    else 
        if (document.attachEvent) {
            document.attachEvent('onkeydown', allcontrol);
        }
    
}

window.onload = game;

	
</script>
<style type='text/css'>
	p{
		float:left;
		margin:10px;
		padding:20px;
		font-weight:bolder;
		border:1px solid #000;
		text-align:center;
		vertical-align:text-bottom;;
	}
	.container{
		position:relative;
		float:left;
		margin:10px;
		padding:0;
		border:1px solid #000;
	}
	._snakeA_{
		position:absolute;
		margin:0;
		padding:0;
		width:20px;
		height:20px;
		border:1px solid #ccc;
		background-color:red;
	}
	._food_{
		position:absolute;
		margin:0;
		padding:0;
		width:20px;
		height:20px;
		border:1px solid #ccc;
		background-color:green;
	}
	._snakeB_{
		position:absolute;
		margin:0;
		padding:0;
		width:20px;
		height:20px;
		border:1px solid #ccc;
		background-color:#2E2E2E;
	}
	
	
</style>
<script type='text/javascript'>

	
</script>
</head>
<body >


</body>
</html>
  相关解决方案