[ create a new paste ] login | about

Link: http://codepad.org/klgZCMgU    [ raw code | fork ]

mavenman - PHP, pasted on Jan 18:
<?php

/** 
 * @param String $strStartingSquare – The knight’s current square in algebraic notation (e4) 
 * @return array – list of all valid squares the knight can move to in algebraic notation 
 */ 
function getValidKnightSquares($strStartingSquare) {
  //Chess Board coords using algebraic notation
  $files=range('a','h');
  $ranks=range(1,8);
  
  //direction both vertical and horizontal
  $signs=array(-1,1);
  
  //Range of Knight Movement
  //When file=1, rank=2 squares
  //When file=2, rank=1 squares
  $moves=array(1=>2,2=>1);

  //keys of Starting Square
  $f=array_search($strStartingSquare[0],$files);
  $r=array_search($strStartingSquare[1],$ranks);
  
  //valid move results
  $results=array();
  
  //Walk valid movements
  foreach($moves as $a=>$b){
    //walk each sign for files
    foreach($signs as $c){
      //walk each sign for ranks
      foreach($signs as $d){
        //Get move based on starting pos for file/rank + sign*movement
        $m=$files[$f+($a*$c)].$ranks[$r+($b*$d)];
        //check if move has valid length
        if(strlen($m)==2)
          $results[]=$m;
      }
    }
  }
  
  return $results;
}


Create a new paste based on this one


Comments: