java猜拳_Java:猜拳游戏

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();

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值