SoFunction
Updated on 2025-03-02

javascript writing gluttonous snake game

The code is very simple, there are not many BBs here. Let’s take a look at the examples directly.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:///TR/xhtml1/DTD/">
<html xmlns="http:///1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312" />
<title>Untitled document</title>
</head>
<body>
<style>
*{
  margin:0;
  padding:0;
}
#wrap{
  position:relative;width:400px;height:400px;
  border:1px solid #ccc;
  margin:10px auto;
}
.snak, .snakBody{
  position:absolute;
  width:10px;height:10px;
  background:#666;
}
.food{
  position:absolute;width:10px;height:10px;
  background:#09F;display:block;
}
</style>
<div >
  
</div>
<script src="http://ftp152341.host180./%E6%89%93%E8%9C%9C%E8%9C%82/"></script>
<script>
var Snak, Food;;

Food = function(op){ //op is a zepto object  var food = $('<span class="food"></span>');
  ({ left : (((op[0].clientWidth-10)*())), top : (((op[0].clientHeight-10)*())) })
  ( food );
};
Snak = function(op){
   = ('div');
   = 'snak';
   = op;
};
 = function(){
  var _this = this, code;
  $(window).bind('keydown',function(e){
    clearInterval(_this.downTimer);
    code = ;
    _this.downTimer = setInterval(function(){
      var l = _this., t = _this.;
      switch( code ){
        case 37 :
          l = l - 5;
        break;
        case 38 : 
          t = t - 5;
        break;
        case 39 : 
          l = l + 5;
        break;
        case 40:
          t = t + 5;
        break;
      };
      if( (l<0) || (t<0) || (l>400) || (t>400)){()};
      _this. = l + 'px';
      _this. = t + 'px';
      var snakB = $('.snakBody');
      for(var i=-1; i>=0; i--){
        if(i == 0){
          snakB[0]. = l + 'px';
          snakB[0]. = t + 'px';
        }else{
          snakB[i]. = snakB[i-1].offsetLeft + 'px';
          snakB[i]. = snakB[i-1].offsetTop + 'px';
        };
      };
      if( pz(_this.obj,$('.food')[0]) ){
        $('.food').remove();
        new Food(wrap);
        $('<div class="snakBody"></div>').appendTo(wrap)
      };
    },30);
  }).bind('keyup',function(e){
  });
};
function pz(obj1,obj2){  
  var L1 = ;
  var T1 = ;
  var R1 = L1 + ;
  var B1 = T1 + ;
  
  var L2 = ;
  var T2 = ;
  var R2 = L2 + ;
  var B2 = T2 + ;
  if(L1 >= R2 || T1 >= B2 || R1 <= L2 || B1 <= T2){
    return false;
  }
  return true;
};
var wrap = $('#wrap'),snak = new Snak(food);
var food = new Food( wrap );
();
( $('<div class="snakBody"></div>') )[0].appendChild(  );
</script>
</body>
</html>

The above is the entire content of this article, I hope you like it.