import java.util.Scanner;
import java.util.Random;
class Tom {
//属性:结果(0; 1; 2)、胜利次数
int result;
int wins;
//胜利则 wins 加 1
public void winGame() {
wins += 1;
}
//输入结果(0; 1; 2), 并返回
public int getResult() {
System.out.println("请输入0(石头)、1(剪刀)、2(布)");
Scanner scanner = new Scanner(System.in);
int result = scanner.nextInt();
return result;
}
//打印赢得次数
public void showWins() {
System.out.println("Tom赢了" + wins + "局");
}
}
class Machine {
int result;
// 返回机器结果
public int showResult() {
Random random = new Random();
result = random.nextInt(3);
System.out.println("机器输出" + result);
return result;
}
}
class Game {
Tom tom;
Machine machine;
int round;
// 传入Tom对象、machine对象、局数
public void gameStart(Tom tom, Machine machine, int round) {
for(int i = 1; i <= round; i++) {
System.out.println("===开始第" + i + "场游戏===");
int tomResult = tom.getResult();
int machineResult = machine.showResult();
gameRule(tom, tomResult, machineResult);
}
}
// 传入tom和机器结果判断输赢并记录
public void gameRule(Tom tom, int tomResult, int machineResult) {
if((tomResult == 0 && machineResult == 1) ||
(tomResult == 1 && machineResult == 2) ||
(tomResult == 2 && machineResult == 0)) {
tom.winGame();
}
}
}
public class pra34 {
public static void main(String args[]) {
int round = 4;
Tom tom = new Tom();
Machine machine = new Machine();
Game game = new Game();
game.gameStart(tom, machine, round);
tom.showWins();
}
}
石头剪刀布的JAVA代码
最新推荐文章于 2024-08-01 15:05:06 发布