/**
* 計算機類
*/
public class Computer {
private String name; // 計算機姓名
private int WinTimes; // 計算機贏得次數
/**
* 構造器
*
* @param name
* 計算機的姓名
*/
public Computer(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public int getWinTimes() {
return this.WinTimes;
}
public void setWinTimes(int winTimes) {
this.WinTimes = winTimes;
}
/**
* 計算機出拳的方法
*/
public int showFist() {
return (int) (Math.random() * 3 + 1);
}
}
package com.accp;
import java.util.Scanner;
/**
* 玩家類
*/
public class Player {
private String name; // 玩家姓名
private int WinTimes; // 玩家贏的次數
/**
* 構造器
*
* @param name
* 玩家的姓名
*/
public Player(String name) {
this.name = name;
}
public int getWinTimes() {
return this.WinTimes;
}
public String getName() {
return this.name;
}
public void setWinTimes(int winTimes) {
this.WinTimes = winTimes;
}
/**
* 人出拳的方法
*/
public int showFist() {
int fist;
Scanner sc = new Scanner(System.in);
do {
System.out.println("請出拳:1--剪刀 2--石頭 3--布");
System.out.println("請選擇: ");
fist = sc.nextInt();
} while (fist < 1 || fist > 3);
return fist;
}
}
package com.accp;
import java.util.Scanner;
/**
* 遊戲類
*/
public class Game {
private Computer computer;
private Player player;
private int counter;
public Game(Computer computer, Player player) {
this.computer = computer;
this.player = player;
}
// 顯示結果和獲勝的次數
public void showReult() {
System.out.println("======比賽結果======");
System.out.println("共比賽了" + counter + "回合");
System.out.println(player.getName() + "贏了" + player.getWinTimes() + "次");
System.out.println(computer.getName() + "贏了" + computer.getWinTimes()
+ "次");
System.out.println("平局 :"
+ (counter - player.getWinTimes() - computer.getWinTimes()));
}
/**
* 是否繼續的方法
*/
public void start() {
Scanner sc = new Scanner(System.in);
String s = " ";
do {
play();
System.out.println("\n要繼續嗎?(輸入yes繼續)");
s = sc.nextLine();
counter++;
} while (s.substring(0, 1).equalsIgnoreCase("y"));
}
/**
* 判斷輸贏的方法
*/
public void play() {
int cf = computer.showFist();
int pf = player.showFist();
String[] hj = { "剪刀", "石頭", "布" };
System.out.println(computer.getName() + "出了" + hj[cf - 1]);
System.out.println(player.getName() + "出了" + hj[pf - 1]);
if (cf == pf) {
System.out.println("平局!!");
} else if (pf == 1 && cf == 3 || pf == 2 && cf == 1 || pf == 3
&& cf == 2) {
System.out.println(player.getName() + "贏了!!");
player.setWinTimes(player.getWinTimes() + 1);
}
else {
System.out.println(computer.getName() + "贏了!!");
computer.setWinTimes(computer.getWinTimes() + 1);
}
}
}
package com.accp;
/**
* 運行遊戲
*/
public class RunGame {
public static void main(String[] args) {
Player p = new Player("曹操");
Computer c = new Computer("劉備");
Game ch = new Game(c, p);
ch.start();
ch.showReult();
}
}