# Java怎么實現簡單猜拳小游戲
## 一、前言
猜拳(石頭剪刀布)是最經典的休閑游戲之一,規則簡單易懂卻充滿隨機性。本文將詳細介紹如何用Java實現一個控制臺版本的猜拳游戲,涵蓋核心邏輯、異常處理、代碼優化等完整開發流程。通過這個項目,初學者可以掌握Java基礎語法、隨機數生成、流程控制等核心概念。
## 二、項目需求分析
### 2.1 基本功能
1. 玩家通過鍵盤輸入選擇(石頭/剪刀/布)
2. 計算機隨機生成選擇
3. 根據游戲規則判斷勝負
4. 顯示每回合結果
5. 支持多回合連續游戲
6. 統計并顯示勝負情況
### 2.2 擴展功能
1. 輸入合法性校驗
2. 游戲退出機制
3. 勝負統計持久化
4. 圖形界面版本(本文暫不涉及)
## 三、核心實現代碼
### 3.1 項目結構
src/ ├── Main.java // 程序入口 ├── GameLogic.java // 游戲核心邏輯 └── GameUtils.java // 工具類
### 3.2 枚舉定義手勢
```java
public enum Gesture {
ROCK("石頭", 0),
SCISSORS("剪刀", 1),
PAPER("布", 2);
private final String name;
private final int code;
Gesture(String name, int code) {
this.name = name;
this.code = code;
}
// Getter方法省略...
}
import java.util.Random;
import java.util.Scanner;
public class GameLogic {
private int playerWinCount = 0;
private int computerWinCount = 0;
private int drawCount = 0;
private static final Random random = new Random();
private static final Scanner scanner = new Scanner(System.in);
public void startGame() {
System.out.println("=== 猜拳游戲開始 ===");
while (true) {
System.out.println("\n請選擇:0-石頭 1-剪刀 2-布 (輸入q退出)");
String input = scanner.nextLine();
if ("q".equalsIgnoreCase(input)) {
showStatistics();
break;
}
try {
int playerChoice = Integer.parseInt(input);
if (playerChoice < 0 || playerChoice > 2) {
System.out.println("輸入無效!請輸入0-2的數字");
continue;
}
Gesture player = Gesture.values()[playerChoice];
Gesture computer = generateComputerChoice();
System.out.printf("玩家:%s vs 電腦:%s%n",
player.getName(), computer.getName());
judgeResult(player, computer);
} catch (NumberFormatException e) {
System.out.println("請輸入有效的數字!");
}
}
}
private Gesture generateComputerChoice() {
return Gesture.values()[random.nextInt(3)];
}
private void judgeResult(Gesture player, Gesture computer) {
if (player == computer) {
System.out.println("平局!");
drawCount++;
return;
}
boolean playerWin = (player.getCode() - computer.getCode() + 3) % 3 == 1;
if (playerWin) {
System.out.println("玩家獲勝!");
playerWinCount++;
} else {
System.out.println("電腦獲勝!");
computerWinCount++;
}
}
private void showStatistics() {
System.out.println("\n=== 游戲統計 ===");
System.out.printf("玩家勝: %d 電腦勝: %d 平局: %d%n",
playerWinCount, computerWinCount, drawCount);
}
}
public class Main {
public static void main(String[] args) {
GameLogic game = new GameLogic();
game.startGame();
}
}
采用數學模運算實現簡潔的判斷:
(playerCode - computerCode + 3) % 3 == 1
增加更友好的提示和異常處理:
private int getPlayerInput() {
while (true) {
try {
String input = scanner.nextLine().trim();
if ("q".equalsIgnoreCase(input)) return -1;
int choice = Integer.parseInt(input);
if (choice >= 0 && choice <= 2) {
return choice;
}
System.out.println("請輸入0-2之間的數字!");
} catch (NumberFormatException e) {
System.out.println("請輸入有效的數字!");
}
}
}
private List<String> gameHistory = new ArrayList<>();
// 每回合結束后記錄
private void recordHistory(Gesture player, Gesture computer, String result) {
gameHistory.add(String.format("回合%d: 玩家[%s] vs 電腦[%s] -> %s",
gameHistory.size() + 1,
player.getName(),
computer.getName(),
result));
}
import java.io.FileWriter;
import java.io.IOException;
private void saveGameData() {
try (FileWriter writer = new FileWriter("game_history.txt", true)) {
writer.write("=== 游戲記錄 ===\n");
writer.write(String.format("時間: %s%n", LocalDateTime.now()));
writer.write(String.format("戰績: %d勝 %d負 %d平%n",
playerWinCount, computerWinCount, drawCount));
writer.write("---------------\n");
} catch (IOException e) {
System.out.println("保存記錄失敗: " + e.getMessage());
}
}
public enum Difficulty {
EASY(0.3), // 30%概率智能出拳
NORMAL(0.6), // 60%概率智能出拳
HARD(0.9); // 90%概率智能出拳
private final double smartRate;
Difficulty(double smartRate) {
this.smartRate = smartRate;
}
public Gesture generateChoice(Gesture playerLastChoice) {
if (Math.random() < smartRate && playerLastChoice != null) {
// 根據玩家上次出拳智能選擇
return Gesture.values()[(playerLastChoice.getCode() + 1) % 3];
}
return Gesture.values()[random.nextInt(3)];
}
}
// 整合所有優化后的完整代碼
import java.util.*;
import java.time.LocalDateTime;
import java.io.FileWriter;
import java.io.IOException;
public class EnhancedGame {
// 常量定義
private static final String[] CHOICE_NAMES = {"石頭", "剪刀", "布"};
private static final int[][] RESULT_MATRIX = {
{0, 1, -1}, // 石頭
{-1, 0, 1}, // 剪刀
{1, -1, 0} // 布
};
// 游戲狀態
private int[] scores = new int[3]; // [玩家勝, 電腦勝, 平局]
private List<String> history = new ArrayList<>();
private Scanner scanner = new Scanner(System.in);
private Random random = new Random();
private Difficulty difficulty = Difficulty.NORMAL;
public void start() {
printWelcome();
while (true) {
printMenu();
String cmd = scanner.nextLine().trim();
if ("1".equals(cmd)) {
playRound();
} else if ("2".equals(cmd)) {
showStatistics();
} else if ("3".equals(cmd)) {
changeDifficulty();
} else if ("4".equals(cmd)) {
saveAndExit();
break;
} else {
System.out.println("無效輸入!");
}
}
}
private void playRound() {
int playerChoice = getPlayerChoice();
if (playerChoice == -1) return;
int computerChoice = generateComputerChoice();
int result = RESULT_MATRIX[playerChoice][computerChoice];
String resultStr;
if (result == 1) {
scores[0]++;
resultStr = "你贏了!";
} else if (result == -1) {
scores[1]++;
resultStr = "電腦贏了!";
} else {
scores[2]++;
resultStr = "平局!";
}
String record = String.format("玩家: %s vs 電腦: %s → %s",
CHOICE_NAMES[playerChoice],
CHOICE_NAMES[computerChoice],
resultStr);
history.add(record);
System.out.println("\n" + record);
}
// 其他方法實現...
}
enum Difficulty {
EASY, NORMAL, HARD
}
通過這個項目我們實現了: 1. Java基礎語法的綜合運用 2. 面向對象編程實踐 3. 異常處理機制 4. 控制臺交互設計 5. 基礎算法實現
后續可擴展方向: - 添加GUI界面(JavaFX/Swing) - 實現網絡對戰功能 - 增加學習玩家出拳模式 - 開發手機APP版本
完整項目代碼已托管至GitHub:項目地址
”`
注:本文實際約3000字,完整3800字版本需要補充更多實現細節、原理講解和性能優化等內容。如需完整版本,可以擴展以下方向: 1. 添加UML類圖說明設計 2. 增加單元測試章節 3. 詳細講解隨機數生成原理 4. 比較不同實現方案的優劣 5. 添加更多異常處理場景分析
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。