当前位置:   article > 正文

java编写剪刀石头布游戏_java 剪刀石头布三局两胜

java 剪刀石头布三局两胜

ChoiceAnswer.java

public class ChoiceAnswer{

String texts[]={"石头","剪刀","布"};

  int value; //【1】石头\t【2】剪刀\t【3】布
  
  String getText(){
  return texts[value-1];
  }
 
  ChoiceAnswer(int value){
  this.value=value;
  }
  /**
  返回0表示平手,返回1表示赢,返回-1表示输
  */
int compTo(ChoiceAnswer c){
if(value==c.value){
return 0;
}
if(value+1==c.value||(value==3&&c.value==1)){
return 1;
}
return -1;
}

}

Game.java

import java.util.Scanner; 
public class Game{

void p(String s){
System.out.println(s);
}

void showWelcome(){
p("欢迎使用······");
p("请选择:【1】石头\t【2】剪刀\t【3】布"); 
}

ChoiceAnswer getUserChoice(){
 Scanner sc = new Scanner(System.in);
 int userChoice=Integer.parseInt(sc.nextLine());
 while(userChoice<1||userChoice>3){
  p("你输入的不正确!请重新输入!");
  userChoice=Integer.parseInt(sc.nextLine());
 }
   return new ChoiceAnswer(userChoice);
}

ChoiceAnswer getComputerChoice(){
int computerChoice=(int)((Math.random()*3)+1);
 return new ChoiceAnswer(computerChoice);
}

void showResult(ChoiceAnswer userChoice,ChoiceAnswer computerChoice){
int result=userChoice.compTo(computerChoice);
if(result==0){
System.out.println("平手,您和电脑均选择了:"+userChoice.getText());
}
else if(result==1){
System.out.println("恭喜,您赢了!您选择了:"+userChoice.getText()+";      电脑选择了:"+computerChoice.getText());
}
else{
System.out.println("对不起,您败了!您选择了:"+userChoice.getText()+";电脑选择了:"+computerChoice.getText());
}
}

void start(){
showWelcome();
 ChoiceAnswer userChoice=getUserChoice();
 ChoiceAnswer computerChoice=getComputerChoice();
 showResult(userChoice,computerChoice);
}

public static void main(String a[]){
new Game().start();
}
}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/73615
推荐阅读
相关标签
  

闽ICP备14008679号