mardi 22 juillet 2008

99 bottles of beer

Ca y est je suis enfin de retour sur mon blog pour un post de la plus haute importance...

Il y a quelques jours, un collègue (un certain Shaoken : http://weblog.shaoken.be) m'a parlé d'un site http://www.99-bottles-of-beer.net/ qui propose de réaliser un programme permettant d'afficher les paroles de la chanson "99 bottles of beer".

J'ai trouvé ça marrant..... et j'ai pris ça comme un défis :) Alors je me suis mis à le faire en PHP. Voici le résultat :

/**
* Class used to display 99 bottles of beer lyrics
*
*/
Class Song
{
/**
* Line break string
*
*/
const LINE_BREAK = '
';


/**
* Number of bottles on the wall
*
* @var integer
*/
private $bottlesCounter;

/**
* Constructor
*
* @param integer $nbBottles
*/
public function __construct($nbBottles = 99)
{
$this -> bottlesCounter = intval($nbBottles);
}

/**
* Return number of bottles on the wall
*
* @return integer
*/
public function getBottlesCounter()
{
return $this -> bottlesCounter;
}

/**
* Remove a bottle
*
*/
public function removeBottle()
{
$this -> bottlesCounter--;
}

/**
* Return '1 bottle' or 'xxx bottles' depending on bottlesCounter
*
* @return string
*/
public function getBottlesString()
{
if ($this -> bottlesCounter > 1)
return ($this -> bottlesCounter . ' bottles');
else
return '1 bottle';
}

/**
* Return a verse depending on number of bottles on the wall
*
* @return string
*/
public function getVerse()
{
$string = '';
switch ($this -> bottlesCounter)
{
case 1: $string .= $this -> getBottlesString() . ' of beer on the wall, ' .
$this -> getBottlesString() . ' of beer.' . self::LINE_BREAK;
$this -> removeBottle();
$string .= 'Take one down and pass it around, no more bottles of beer on the wall.'
. self::LINE_BREAK . self::LINE_BREAK;
break;

case 0: $string .= 'No more bottles of beer on the wall, no more bottles of beer.' . self::LINE_BREAK;
$this -> removeBottle();
$string .= 'Go to the store and buy some more, 99 bottles of beer on the wall.';
break;

default: $string .= $this -> getBottlesString() . ' of beer on the wall, ' .
$this -> getBottlesString() . ' of beer.' . self::LINE_BREAK;

$this -> removeBottle();

$string .= 'Take one down and pass it around, '
. $this -> getBottlesString() . ' of beer on the wall.'
. self::LINE_BREAK . self::LINE_BREAK;
break;
}

return $string;
}

/**
* Display song lyrics
*
*/
public function sing()
{
while ($this -> getBottlesCounter() >= 0)
{
echo $this -> getVerse();
}
}
}

//the song object
$song = new Song();

//Sing 99 Bottles of Beer
$song -> sing();

Et comme je sais que ce code va être très mal affiché, je vous le propose en téléchargement (et gratuit en plus ! ! ! :) => http://www.acolson.net/files/bottles.rar

Pour une petite démo, rendez-vous ici => http://www.acolson.net/files/bottles.php et non ce n'est pas du texte "hard codé" :-)

Si vous avez des remarques, n'hésitez pas...


Aucun commentaire: