所以我今天的任务是使用方法做一个石头纸剪刀游戏。我的代码的第一个问题是,我需要它来询问用户是否要再次玩。 (y或n)另外,我需要实现得分,如果用户获胜,则得1分,如果失败,则为-1,并且每次他们再次玩都将该得分添加到总得分。关于如何实现这个的任何想法?或者我需要更改为我的代码。另外,我是一个新手,对于丑陋的格式感到抱歉,并随时批评每一个小细节,因此我不能吸收所有可能的信息。岩纸剪刀简单的java使用方法
public static void main(String[] args){
boolean tie = true;
do{
String computer = computerChoice();
String user = userChoice();
tie = (computer.compareTo(user) == 0);
determineWinner(computer, user);
}while(tie);
}
public static String computerChoice(){
Random rand = new Random();
int cinput = rand.nextInt(3)+ 1;
String computer = "thing";
if (cinput == 1)
computer = "Rock";
if (cinput == 2)
computer = "Paper";
if (cinput == 3)
computer = "Scissors";
return computer;
}
public static String userChoice(){
Scanner sc = new Scanner (System.in);
String user = "default";
do{
System.out.println("choose your weapon(Paper,Scissors or Rock)");
user = sc.nextLine();
}
while (isValidChoice (user) == false);
return user;
}
public static boolean isValidChoice(String choice){
boolean status;
if (choice.compareTo("Rock")== 0)
status = true;
else if (choice.compareTo("Paper")== 0)
status = true;
else if (choice.compareTo("Scissors")== 0)
status = true;
else{
status = false;
System.out.println("Error! Make sure you are capitalizing your choices");
}
return status;
}
public static boolean determineWinner(String computer, String user){
System.out.println (" Computer Choice: " + computer);
System.out.println ("Your Choice : " + user);
if (computer.compareTo("Rock") == 0 && user.compareTo ("Scissors") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Scissors")== 0 && user.compareTo("Paper") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Paper") == 0 && user.compareTo("Rock") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Rock") == 0 && user.compareTo("Paper") == 0)
System.out.println (" You win!!");
if (computer.compareTo("Scissors") == 0 && user.compareTo("Rock") == 0)
System.out.println (" You win!!");
if (computer.compareTo("Paper") == 0 && user.compareTo("Scissors") == 0)
System.out.println (" You win!!");
else if (computer.compareTo(user) == 0){
System.out.println(" Tie! the game must be played again.");
return false;
}
return true;
}
}
,我的教授给我们作为一个例子输出为:
Choose your weapon!
1. Paper
2. Scissors
3. Rock
5
Choose your weapon!
1. Paper
2. Scissors
3. Rock
1
You chose paper!
I choose rock!
I have been vanquished!
We have matched wits 1 times, and your score is 1
Do you want to play again (y or n)? y
Choose your weapon!
1. Paper
2. Scissors
3. Rock
1
You chose paper!
I choose paper!
We are equally matched. You are a worthy adversary.
We have matched wits 2 times, and your score is 1
Do you want to play again (y or n)? n
你知道怎么反复要求一个“武器”,但不知道怎么反复要求再玩一次? –
使用.equals()可以更好地检查响应 – WIR3D
@ScottHunter,所以我只需制作另一种方法并让它们再次播放? – Progamminnoob