主程序
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("请用户输入猜拳局数:");
Scanner input = new Scanner(System.in);
int count = input.nextInt();
System.out.println("猜拳规则为:"+count+"局"+(count/2+1)+"胜");
Judge j = new Judge();
j.judging(count);
input.close();
}
}
人猜拳设置程序
import java.util.Scanner;
public class Human {
private String person;
private int a;
public Human() {
super();
// TODO Auto-generated constructor stub
}
public Human(String person) {
super();
this.person = person;
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public String getPerson() {
return person;
}
public void setPerson(String person) {
this.person = person;
}
public void Initialize() {
System.out.println("-----------------");
Scanner input = new Scanner(System.in);
System.out.println("请用户输入猜拳(1代表剪刀,2代表石头,3代表布):");
setA(input.nextInt());
while(getA()!=1&&getA()!=2&&getA()!=3) {
System.out.println("你的输入有误,请重新输入:");
setA(input.nextInt());
}
switch(getA()) {
case 1:person="剪刀";
break;
case 2:person="石头";
break;
case 3:person="布";
break;
}
}
电脑随机猜拳
public class Machine {
private String computer;
private int b;
public Machine() {
super();
// TODO Auto-generated constructor stub
}
public Machine(String computer, int b) {
super();
this.computer = computer;
this.b = b;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
public String getComputer() {
return computer;
}
public void setComputer(String computer) {
this.computer = computer;
}
public void random() {
setB((int)(Math.random()*3+1));
//Math.random():生成大于等于0.0、小于1.0的double型随机数。
switch(getB()) {
case 1:computer="剪刀";
break;
case 2:computer="石头";
break;
case 3:computer="布";
break;
}
}
}
判断胜负程序
public class Judge {
private int person_num;
private int computer_num;
static int person_win_count;
static int computer_win_count;
static int count;
public void judging(int counts) {
Human human = new Human ();
Machine machine = new Machine();
//a为总局数,a/2+1为胜局数
while((count<counts)&&(person_win_count<(counts/2+1))&&(computer_win_count<(counts/2+1))) {
human.Initialize();
machine.random();
person_num = human.getA();
computer_num = machine.getB();
//判断输赢
/**
* 用户胜:用户出1,电脑出3
* 用户出2,电脑出1
* 用户出3,电脑出2
*/
if((person_num==1&&computer_num==3)||(person_num==2&&computer_num==1)||(person_num==3&&computer_num==2)) {
person_win_count++;
System.out.print("你出的是"+human.getPerson()+",电脑出的是:"+machine.getComputer());
System.out.println(".\t恭喜你赢了");
}
else if(person_num==computer_num) {
System.out.print("你出的是"+human.getPerson()+",电脑出的是:"+machine.getComputer());
System.out.println(".\t打成平手");
}
else {
computer_win_count++;
System.out.print("你出的是"+human.getPerson()+",电脑出的是:"+machine.getComputer());
System.out.println(".\t很遗憾,你输了");
}
count++;
System.out.println("猜拳局数为:"+count+",当前的比分:\t用户:电脑="+person_win_count+":"+computer_win_count);
}
System.out.println("最终的比分:\t用户:电脑 = "+person_win_count+":"+computer_win_count);
}
}