您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。