编程语言
首页 > 编程语言> > JAVA 猜拳游戏

JAVA 猜拳游戏

作者:互联网

JAVA 猜拳游戏

题目:通过控制台方式实现一个人机对战的猜拳游戏

用户通过输入(0.石头子 1.剪刀 2.布),机器随机生成(0.石头子 1.剪刀 2.布)

要求:

  1. 能打印玩家的对局信息,胜利的次数,平局次数,和平局次数
package HomeWorkExercise;

import java.util.Iterator;
import java.util.Random;
import java.util.Scanner;

public class Homework14 {
	public static void main(String args[]) {
		String name = "小杨";
		Game game = new Game(name);
		
		//进行10次猜拳
		for(int i = 1 ; i <= 5 ; i++) {
			
			game.play();
			System.out.println();
		}
		
		//打印情况
		game.getInfo();
		
	}
}


/*
 * 思路
 * 0 石头 1剪刀 2布
 * 1.电脑端:生成一个随机数 并返回,0~2
 * 2.玩家:用户输入,0~2,超出范围提示输入错误,并重新输入
 * 3.进行猜拳游戏
 *   进行枚举
 *   电脑端 0 
 *   	玩家出2 算赢,0算平局,1算输
 *   电脑端 1
 *   	玩家出0 算赢,1算平局,2算输
 *   电脑端 2
 *   	玩家出1 算赢,2算平局,0算输
 */
class Game{
	String name;
	int win = 0;
	int fail = 0;
	int draw = 0;
	
	//构造器
	public Game(String name) {
		this.name = name;
	}
	
	//生成电脑出的数 
	public int computer() {
		Random r1 = new Random();
		return r1.nextInt(2);
	}
	
	//获取玩家出的数
	public int player() {
		Scanner sc = new Scanner(System.in);
		int input;
		//从键盘获取一个数 0~2
		while(true) {
			System.out.print("请输入一个数(0~2):");
			input = sc.nextInt();
			if(input >=0 && input <=2) {
				break;
			}else{
				System.out.println("输入有误,请输入0~2这三个数");
			}
		}
		return input;
	}
	
	//开始游戏
	public void play() {
		int computer = this.computer(); 
		int player = this.player();
		
	
		//电脑出石头
		if(computer == 0 ) {
			System.out.println("电脑:石头");
			if(player == 2) {
				System.out.println("您:布");
				System.out.println("胜利");
				this.win++;
			}else if(player == 0) {
				System.out.println("您:石头");
				System.out.println("平局");
				this.draw++;
			}else {
				System.out.println("您:剪刀");
				System.out.println("失败");
				this.fail++;
			}
		}
		
		//电脑出剪刀
		if(computer == 1 ) {
			System.out.println("电脑:剪刀");
			if(player == 0) {
				System.out.println("您:石头");
				System.out.println("胜利");
				this.win++;
			}else if(player == 1) {
				System.out.println("您:剪刀");
				System.out.println("平局");
				this.draw++;
			}else {
				System.out.println("您:布");
				System.out.println("失败");
				this.fail++;
			}
		}
		
		//电脑出布
		if(computer == 2 ) {
			System.out.println("电脑:布");
			if(player == 1) {
				System.out.println("您:剪刀");
				System.out.println("胜利");
				this.win++;
			}else if(player == 2) {
				System.out.println("您:布");
				System.out.println("平局");
				this.draw++;
			}else {
				System.out.println("您:石头");
				System.out.println("失败");
				this.fail++;
			}
		}
	}
	
	//获得输赢次数
	public void getInfo() {
		System.out.println("玩家:"+this.name);
		System.out.println("输赢次数如下");
		System.out.println("胜利\t平局\t失败");
		System.out.println(this.win+"\t" + this.draw +"\t" + this.fail +"\t");
	}

}

标签:JAVA,猜拳,java,util,String,Game,import,游戏
来源: https://www.cnblogs.com/DL50/p/15838554.html