Jump to content

brainf*ck interpreter in php

- - - - -

  • Please log in to reply
1 reply to this topic

#1
__ak

__ak

    Newbie

  • Members
  • PipPip
  • 24 posts
Hi,
Been trying to make an brainfuck interpreter in PHP.
I got stuck at making nested loops, so looked through the web and read numerous examples written in C, Perl etc.
A lot of them used a stack to keep track of pointer placement when starting loop, and then pop/shift it off when loop is done. So that's the solution I choose.

AND IT WORKED!
... for a while.

It took programs like the classic hello world:
>+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.[-]

>++++++++[<++++>-] <.>+++++++++++[<++++++++>-]<-.--------.+++

.------.--------.[-]>++++++++[<++++>- ]<+.[-]++++++++++.

and two I've made myself:

//Prints 99-00 with leading zero

+++++[>+++++++++++<-]>++ //Counter for first digit

>+++++[>+++++++++++<-]>++ //Counter for second digit

>++++++++++[>++++++++++[<<<<.>>.->>-]<<<<->>++++++++++>-] //Loop and print

//Prints 9-0

+++++[>+++++++++++<-]>++

>++++++++++[<.->-]

But when trying to interpret the 99-bottles-of-beer.net example i get a bunch of rubbish - but some of the lines are correct.
Then at some points i starts to break out of my predefined cells, and i get:
PHP Notice:  Undefined offset: 50001 in /var/www/bfint.php on line 32

...

PHP Notice:  Undefined offset: 50051 in /var/www/bfint.php on line 32

etc.

Here's the source, bfint.php

#!/usr/bin/php -q

<?php

$f = fopen($_SERVER['argv'][1], 'r')	;

$p = 0; 

$d = $c = $l = array();


//Reading the file, byte by byte and putting into data array

while(($b = fgets($f,2))!==false)

	 $d[] = $b;


//Predefining cells

for($t=0;$t<=50000;$t++)

	$c[] = 0;


$loops = count($d);


for($i=0; $i<$loops; $i++) {

	switch($d[$i]) {

		case '>':

			$p++;

		break;

		case '<':

			$p--;

		break;

		case '+':

			$c[$p]++;

		break;

		case '-':

			$c[$p]--;

		break;

		case '.':

			fputs(STDOUT, chr($c[$p]));

		break;

		case ',':

			$c[$p] = ord(fgets(STDIN, 2));

		break;

		case '[':

			array_unshift($l, $i);

		break;

		case ']':

			($c[$p]>0) ? $i=$l[0] : array_shift($l) ;

		break;

	}

}

fputs(STDOUT, "\n");

fclose($f);

exit(0);

?>



#2
__ak

__ak

    Newbie

  • Members
  • PipPip
  • 24 posts
Here the source of full output
99 bottles of beer on the wall, 99 bottles of beer. Take one down and pass it f - Pastebin.com




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users