package game;
import java.util.Scanner;
public class Person {
String name;
int score;
public Person() {
}
public Person(int score) {
this.score = score;
}
// 1. 石头 2. 剪刀 3. 布
int play() {
System.out.println("请出拳:(1石头2剪刀3布)");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
switch (num) {
case 1: {
System.out.println(this.name + "出拳:石头") ;
break;
}
case 2: {
System.out.println(this.name + "出拳:剪刀");
break;
}
default:
System.out.println(this.name + "出拳:布");
break;
}
return num;
}
}
package game;
import java.util.Random;
public class Computer {
String name;
int score;
// 构造方法
public Computer() { // 默认构造方法
}
public Computer (int score) {
this.score = score;
}
// 出拳
int play() {
Random rand = new Random();
// 1. 石头 2. 剪刀 3.布
int num = rand.nextInt(3)+1;
switch (num) {
case 1: {
System.out.println(this.name + "出拳:石头") ;
break;
}
case 2: {
System.out.println(this.name + "出拳:剪刀");
break;
}
default:
System.out.println(this.name + "出拳:布");
break;
}
return num;
}
}
package game;
import java.util.Scanner;
public class Memu {
Computer computer;
Person p;
// 构造方法
public Memu() {
this.init();
}
// 初始化游戏
void init() {
// 创建机器对象
this.computer = new Computer(0);
System.out.println("请输入电脑的名字:");
Scanner sc = new Scanner(System.in);
this.computer.name = sc.next();
// 创建一个人对象
this.p = new Person(0);
System.out.println("请输入你的名字:");
this.p.name = sc.next();
}
// 开始游戏
void start() {
// 人先出拳
int pNum = this.p.play();
// 机器出拳
int cNum = this.computer.play();
// 计算分数
this.calculate(pNum, cNum);
System.out.println("游戏是否结束(exit)");
Scanner sc = new Scanner(System.in);
if ("exit".equals(sc.next())) {
// 展示结果
this.show();
return;
} else {
start();
}
}
// 计算分数 num : 人出拳的值 num1 机器出拳的值
void calculate( int num, int num1) {
if (num == num1) { // 平局
System.out.println("平局");
return;
}
if ((num == 1 && num1 == 2) || (num == 2 && num1 == 3) ||
(num==3&&num1==1)) { // 人胜利
System.out.println("人胜利");
this.p.score++;
} else { // 机器胜利
System.out.println("机器胜利");
this.computer.score++;
}
}
// 展示结果
void show() {
System.out.println(this.p.name + "得分:" + this.p.score);
System.out.println(this.computer.name + "得分:" +
this.computer.score);
}
}
package game;
public class Test {
public static void main(String[] args) {
Memu memu = new Memu();
memu.start();
}
}
网友评论