java版 石头剪刀布游戏制作
电脑:
import java.util.Random;
public class Computer {
String name;
double score;
//构造方法
public Computer(double score){
this.score = score;
}
public Computer () {
}
int play(){
Random rand = new Random();
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;
}
}
人:
import java.util.Scanner;
public class Person {
String name;
double score;
// 构造方法
public Person() {
}
public Person(double score) {
this.score = score;
}
// 方法 玩
int play() {
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;
}
}
菜单类:
import java.util.Scanner;
public class Menu {
Computer computer;
Person person;
// 初始化方法
void init() {
computer = new Computer(0);
System.out.println("请输入电脑名:");
Scanner scanner = new Scanner(System.in);
computer.name = scanner.next();
person = new Person(0);
System.out.println("请输入玩家姓名:");
person.name = scanner.next();
}
// 开始游戏
void start() {
System.out.println("请出拳(1 石头 2 剪刀 3 布子)");
int PNum = person.play();
int cNum = computer.play();
cal(PNum, cNum);
System.out.println("是否退出(exit)");
Scanner sc = new Scanner(System.in);
String str = sc.next();
System.out.println("退出成功");
if ("exit".equals(str)) {
System.out.println(this.person.name + "得分为:" + this.person.score);
System.out.println(this.computer.name + "得分为:"
+ this.computer.score);
return;
} else {
start();
}
}
void cal(int num, int num1) {
if (num == num1) {
System.out.println("平局");
}
if ((num == 1 && num1 == 3) || (num == 1 && num1 == 3)
|| (num == 1 && num1 == 3)) {
System.out.println(this.person.name + "赢");
person.score++;
} else {
System.out.println(this.computer.name + "赢");
computer.score++;
}
}
}
测试类:(调用方法)
public class Test {
public static void main(String[] args) {
Menu menu = new Menu();
menu.init();
menu.start();
}
}