Jump to content

Cleaner/Shorter code?


godsent

Recommended Posts

Maybe some of you know this game, that two persons pick one of the (paper, scissors, well)

and winner determined in this way:

 

paper > well

paper < scissors

 

scissors > paper

scissors < well

 

well > scissors

well < paper

 

 

And i generate winner like this:

 

		

		$person1 = "Tom";
		$person2 = "Mike";

		//Same answer
		if ($person1_choose == $person2_choose)
		{
			$winner = "none.";
		}

		//paper vs scissors
		if ($person1_choose == "paper" && $person2_choose == "scissorsr")
		{
			$winner = $person2;
		}
		if ($person1_choose == "scissorsr" && $person2_choose == "paper")
		{
			$winner = $person1;
		}

		//paper vc well
		if ($person1_choose == "paper" && $person2_choose == "well")
		{
			$winner = $person1;
		}
		if ($person1_choose == "well" && $person2_choose == "paper")
		{
			$winner = $person2;
		}

		//scissorsr vs well
		if ($person1_choose == "scissorsr" && $person2_choose == "well")
		{
			$winner = $person2;
		}
		if ($person1_choose == "well" && $person2_choose == "scissorsr")
		{
			$winner = $person1;
		}

		echo $winner;

 

If you have any ideas please post. :)

Link to comment
https://forums.phpfreaks.com/topic/187696-cleanershorter-code/
Share on other sites

How about something like...

 

    $beats = array('paper'=>'rock','scissors'=>'paper', 'rock'=>'scissors');
    
    $player1 = $_POST['player1'];
    $player2 = $_POST['player2'];
    
    if($player1 == $player2) {
        echo "Tie";
    } elseif($beats[$player1] == $player2) {
        echo "Player 1 Wins";
    } else {
        echo "Player 2 Wins";
    }

Link to comment
https://forums.phpfreaks.com/topic/187696-cleanershorter-code/#findComment-990903
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.