Can anybody help with this basic function excercise

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
irishjoe
Forum Newbie
Posts: 2
Joined: Tue Jul 28, 2009 12:57 pm
Location: Cork

Can anybody help with this basic function excercise

Post by irishjoe »

Hi,

I am trying to figure out how to write a function (or combination of functions) that will perform the same action as this code

Code: Select all

$bet = $_GET['bet'];
 
if ( ( $bet == 'even' && ( rand(1, 6) + rand(1, 6) ) % 2 == 0 ) || 
     ( $bet == 'odd'  && ( rand(1, 6) + rand(1, 6) ) % 2 != 0 ) )
{
    echo '<p>You win!</p>';
}
else
{
    echo '<p>You lose!</p>';
}
   
Basially $bet contains the term "even" or "odd". The aim is to select even or odd on a form, and if the sum of the two dice is odd or even (depending on what you selected), you win.

I have tired a few different things that didnt work and I'm sure its a fairly simple function.
Any help or suggestions will be greatly appreciated :)

Thanks very much.
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Can anybody help with this basic function excercise

Post by prometheuzz »

Something like this:

Code: Select all

function win_or_lose($bet) {
  $even = (rand(1, 6) + rand(1, 6))%2 == 0;
  if($bet == 'even') {
    return $even ? "Win" : "Lose";
  }
  else {
    return $even ? "Lose" : "Win";
  }
}
?
User avatar
andyhoneycutt
Forum Contributor
Posts: 468
Joined: Wed Aug 27, 2008 10:02 am
Location: Idaho Falls

Re: Can anybody help with this basic function excercise

Post by andyhoneycutt »

Would this work for ya? Returns true or false based on is odd and they bet odd, is even and they bet even.

Code: Select all

function bet($x)
{
  return ($x == "odd") ? (rand(1, 6) + rand(1, 6) ) % 2 != 0) : (rand(1, 6) + rand(1, 6) ) % 2 == 0);
}
irishjoe
Forum Newbie
Posts: 2
Joined: Tue Jul 28, 2009 12:57 pm
Location: Cork

Re: Can anybody help with this basic function excercise

Post by irishjoe »

Thanks for the replies! Both helped alot.
Exactly what I was looking for
:D
Post Reply