我应该做一个石头,床单和剪刀游戏的程序。它涉及来自 Math.random() 的人类游戏和计算机游戏。它实际上是有效的,但我必须在我喜欢玩的时候一次又一次地重新运行它。所以我决定让它无限,直到输入 4。
这里'它是如何工作的:
想玩?打败电脑!
- 结石
- 床单
- 剪
- 退出
意思是说当我输入 4 时它会退出,但只要输入 1、2 或 3,它就应该连续运行。我怎样才能做到这一点。这是我当前的代码。我知道错误是 while player != 4 的位置
import javax.swing.*;
public class StoneSheetShears
{
public static void main(String[] args)
{
String consoleStr;
int player = 0;
int[] numChoices = {1,2,3,4};
String[] strChoices = {"Stone", "Sheet", "Shears", "Quit"};
String playerChoice = "";
String compChoice = "";
int computer = (int)(Math.random() * 3);
String output = "";
while(true)
{
do
{
try
{
consoleStr = JOptionPane.showInputDialog("Beat the computer\n1. Rock\n2. Paper" +
"\n3. Scissors\n4. Quit ");
player = Integer.parseInt(consoleStr);
for(int x = 0; x <numChoices.length; x++)
{
if(player == numChoices[x])
{
playerChoice = strChoices[x];
}
}
for(int y = 0; y <numChoices.length; y++)
{
if(computer == numChoices[y])
{
compChoice = strChoices[y];
}
}
}
}while(player!=4)
catch (NumberFormatException err)
{
JOptionPane.showMessageDialog(null, "There is an error on entry",
"Error Message", JOptionPane.WARNING_MESSAGE);
continue;
}
break;
}
if (player == computer)
{
output = "Both are " + compChoice;
JOptionPane.showMessageDialog(null, output, "DRAW!", JOptionPane.INFORMATION_MESSAGE);
}
else if (player == 1)
{
if (computer == 2)
{
output = "Computer move is " + compChoice +
"\nYour move is " + playerChoice;
JOptionPane.showMessageDialog(null,output, "You Lose!",
JOptionPane.INFORMATION_MESSAGE);
}
else if (computer == 3)
{
output = "Computer move is " + compChoice +
"\nYour move is " + playerChoice;
JOptionPane.showMessageDialog(null,output, "You Win!",
JOptionPane.INFORMATION_MESSAGE);
}
}
else if (player == 2)
{
if (computer == 3)
{
output = "Computer move is " + compChoice +
"\nYour move is " + playerChoice;
JOptionPane.showMessageDialog(null,output, "You Lose!",
JOptionPane.INFORMATION_MESSAGE);
}
else if (computer == 1)
{
output = "Computer move is " + compChoice +
"\nYour move is " + playerChoice;
JOptionPane.showMessageDialog(null,output, "You Win!",
JOptionPane.INFORMATION_MESSAGE);
}
}
else if (player == 3)
{
if (computer == 1)
{
output = "Computer move is " + compChoice +
"\nYour move is " + playerChoice;
JOptionPane.showMessageDialog(null,output, "You Lose!",
JOptionPane.INFORMATION_MESSAGE);
}
else if (computer == 2)
{
output = "Computer move is " + compChoice +
"\nYour move is " + playerChoice;
JOptionPane.showMessageDialog(null,output, "You Win!",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
}
这基本上是一个游戏,其中石板和剪刀是选择。
- 人类玩家将从 1(石头)、2(薄片)、3(剪刀)、4(退出)中进行选择
- 电脑播放器是基于数学随机的。
我使用数组来定义人类玩家和计算机的动作。(数组是 Java 语法的一部分,不适合这样的描述。) - 如果两人的动作相同,那就是平局。
- 如果人类选择纸张,而电脑玩家是剪刀,显然电脑赢了。这同样适用于其他选择。
玩家将输入另一个数字 1 2 或 3。(这只是重复步骤 1,因此没有必要)。输入 4 即停止游戏,即按提示退出
我唯一的问题是如何让它连续工作,直到输入 4。