老师给的源代码如下,共以后复习参考:
电脑:
import java.util.Random;
public class Computer {
private String name;
private int score;
public Computer(String name){
this.name = name;
score = 0;
}
public String fistComputer(){
Random random = new Random();
int num = random.nextInt(3);
String fist;
if(num == 0){
fist = "石头";
}else if(num == 1){
fist ="剪刀";
}else{
fist = "布";
}
return fist;
}
public void addScore(int score){
this.score += score;
}
public String getName(){
return name;
}
public int getScore(){
return score;
}
}
人手动输入石头剪刀布
import java.util.Scanner;
public class People {
private String name;
private int score;
public People(String name){
this.name = name;
score = 0;
}
public String fistPeople(){
System.out.println("石头 剪刀 布");
System.out.println("Jamie出:");
Scanner scanner = new Scanner(System.in);
String fist = scanner.next();
return fist;
}
public void addScore(int score){
this.score += score;
}
public String getName(){
return name;
}
public int getScore(){
return score;
}
}
游戏规则
import java.util.Scanner;
public class Game {
private Computer computer;
private People people;
public Game(){
people = new People("Jamie");
computer= new Computer("lisi");
}
public void judge(String fistPeople,String fistComputer){
if(fistPeople.equals("石头") &&fistComputer.equals("剪刀") ||
fistPeople.equals("剪刀")&&fistComputer.equals("布") ||
fistPeople.equals("布")&&fistComputer.equals("石头") ){
System.out.println(people.getName() + "胜利");
people.addScore(1);
}else if(fistPeople.equals(fistComputer)){
System.out.println("平局!不得分");
}else{
System.out.println(computer.getName() + "胜利!");
computer.addScore(1);
}
}
private void judgeThree(){
if(people.getScore() == computer.getScore()){
System.out.println("平局啦");
System.out.println(people.getName()+":"+computer.getName()+
"="+people.getScore()+":"+computer.getScore());
}else if(people.getScore() > computer.getScore()){
System.out.println(people.getName() + "胜利!");
System.out.println(people.getName()+":"+computer.getName()+
"="+people.getScore()+":"+computer.getScore());
}else{
System.out.println(computer.getName() + "胜利!");
System.out.println(people.getName()+":"+computer.getName()+
"="+people.getScore()+":"+computer.getScore());
}
}
public void start(){
boolean flag = true;
while(flag){
System.out.println("游戏开始!");
Scanner scanner = new Scanner(System.in);
int count = 0;
while(count<3){
System.out.println("请出拳!");
String fistPeople = people.fistPeople();
String fistComputer = computer.fistComputer();
System.out.println("对方出:"+fistComputer);
judge(fistPeople,fistComputer);
count++;
}
judgeThree();
System.out.println("是否继续游戏:是,否");
String string = scanner.next();
if(string.equals("否")){
flag = false;
}
}
}
}
测试方法
public class main {
public static void main(String[] args) {
Game game = new Game();
game.start();
}
}