Your Ad Here

Posted By

shyno on 02/10/12


Tagged

php logic vacas toros


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

eludnasud


Logic


 / Published in: PHP
 

Cows and Bulls logic game

  1. <?php
  2. class itergame {
  3. private $hidenum;
  4. public $turn;
  5.  
  6. function __construct($number = "") {
  7. $this->turn = 0;
  8. if($number != "") {
  9. $this->hidenum = $number;
  10. } else {
  11. $this->Generate();
  12. }
  13. }
  14.  
  15. public function Generate() {
  16. $temp = "";
  17. for($i=0; $i<4; $i++) {
  18. do
  19. {
  20. $k = mt_rand(1,9);
  21. }
  22. while( substr_count($temp,$k) > 0 );
  23. $temp .= $k;
  24. $this->hidenum = $temp;
  25. }
  26. }
  27.  
  28. public function Eval_n($num) {
  29. $r = 0; $b = 0;
  30. $nh = str_split($this->hidenum);
  31. if( NumValid($num) ) {
  32. for($i=0; $i < 4; $i++) {
  33. if( IsThere($num, $nh[$i]))
  34. $r++;
  35. if( InPos($num, $nh[$i], $i) )
  36. $b++;
  37.  
  38. $r -= $b;
  39. }
  40. $result = $r." ".$b;
  41. $this->turn++;
  42. } else {
  43. $result = "";
  44. }
  45.  
  46. return $result;
  47. }
  48.  
  49. private function NumValid($num) {
  50. $vof = 1;
  51. $arr = str_split($num);
  52. for($i=0; $i < 4; $i++) {
  53. if($arr[$i] < 1 || $arr[$i] > 9) {
  54. $vof = 0;
  55. echo "Número Ilegal, cifra fuera de rango\n";
  56. }
  57. }
  58. for($i=0; $i < 4; $i++) {
  59. if( substr_count($num, $arr[$i]) > 1 ) {
  60. $vof = 0;
  61. echo "Número Ilegal, tiene cifras repetidas\n";
  62. }
  63. }
  64.  
  65. return $vof;
  66. }
  67.  
  68. private function InPos($cad, $n, $ind) {
  69. $arr = str_split($cad);
  70. $vof = ($arr[$ind] == $n);
  71. return $vof;
  72. }
  73.  
  74. private function IsThere($cad, $n) {
  75. $vof = (substr_count($cad, $n) > 0);
  76. return $vof;
  77. }
  78.  
  79. }
  80.  
  81. ?>

Report this snippet  

You need to login to post a comment.