我是php的新手,一直在努力让我的石头,纸,剪刀游戏正常工作!我知道我要做什么,但是我无法弄错地方了……它可以在石头上工作,但对于纸和剪刀我却有两个输出!新手出来...谢谢! 附言:我知道这样做有很多巧妙的方法!
<?php
// user enters a value R P or S - NEED TO RETURN A COUPLE OF
TIMES AFTER, not sure why?
echo "What do you select - R for rock, P for paper or S for
scissors?\n";
$input=
$R = stream_get_line(STDIN, 1, "\n");
$P = stream_get_line(STDIN, 1, "\n");
$S = stream_get_line(STDIN, 1, "\n");
//program converts the value into Rock, Paper or Scissors
switch ($input) {
case 'R' :
case 'r':
echo $R = "You selected Rock\n" ;
break;
case 'P' :
case 'p':
echo $P = "You selected Paper\n" ;
break;
case 'S' :
case 's':
echo $S = "You selected Scissors\n" ;
break;
}
//computer generates a random value 0,1,2 & converts to R P or S
echo "\nComputer is now making its selection....\n";
//$options = ('Rock=0, Paper=1, Scissors=2');
$output = (rand(0,2) );
echo $output;
if ($output== 0)
{
echo "\nComputer Selected Rock\n"; //goto Rock;
}
elseif ($output==1)
{
echo "\nComputer Selected Paper\n"; //goto Paper;
}
elseif ($output==2)
{
echo "\nComputer Selected Scissors\n"; //goto Scissors;
}
//compare user and computers choise
Rock:
if ($R && $output===0)//.($P && $output==1),($S && $output==2))
{
echo "\nITS A DRAW";
}
elseif ($R && $output===1)//.($P && $output==2).($S &&
$output==0))
{
echo "\nCOMPUTER WINS";
}
elseif ($R && $output===2)//.($P && $output==0).($S &&
$output==1))
{
echo "\nYOU WIN";
}
Paper:
if ($P && $output===1)
{
echo "\nITS A DRAW";
}
elseif ($P && $output===2)
{
echo "\nCOMPUTER WINS";
}
elseif ($P && $output===0)
{
echo "\nYOU WIN";
}
Scissors:
if ($S && $output===2)
{
echo "\nITS A DRAW";
}
elseif ($S && $output===0)
{
echo "\nCOMPUTER WINS";
}
elseif ($S && $output===1)
{
echo "\nYOU WIN";
}
答案 0 :(得分:1)
首先应将$ R,$ P和$ S初始化为false。然后将用户输入1x读入$ input。 其余脚本似乎没问题。
<?php
$R = $P = $S = false;
$input= stream_get_line(STDIN, 1, "\n");
答案 1 :(得分:0)
// user enters a value R P or S - NEED TO RETURN A COUPLE OF TIMES AFTER, not sure why?
因为
$input=
$R = stream_get_line(STDIN, 1, "\n");
$P = stream_get_line(STDIN, 1, "\n");
$S = stream_get_line(STDIN, 1, "\n");
您要呼叫stream_get_line()
三次,因此脚本需要三行输入。
此外,我不确定是否打算这样做,但是由于$input = $R = stream_get_line()
将第一个用户输入存储在$R
中并且 $input
。
我建议只做$input = stream_get_line()
,不要做其他事情。
然后在您的开关/机箱中进行例如echo $R = "...";
,然后再做if ($R && ...)
。
不建议将字符串评估为布尔值。
我会推荐类似的东西
$R = $P = $S = false; // initialize all variables to false
switch ($input)
{
case "R":
$R = true; // set selected variable to true
echo "You have selected Rock\n";
break;
// ...
}
最后,您似乎正在使用跳转标记来注释您的代码。
Rock:
if ( ...
尽管这还没有引起任何问题(但是),但出于文档目的滥用语言功能通常被认为是不好的风格。
这些应该成为注释:
// Rock
if ( ...