使用java设计一个游戏,电脑和人玩剪刀石头布游戏,并且能显示游戏结果,比如人出了石头,电脑出了剪子, 则显示人赢了,否则显示电脑赢了,或者平局。比赛次数至少为5次,将每一局的游戏结果写入 result.txt文件。
时间: 2024-02-18 17:06:17 浏览: 51
用Java写的小游戏——剪刀石头布.zip
很高兴能够为您提供代码,这是一个基于面向对象编程的实现方案。
首先,我们需要定义一个手势类,它包含三个常量:剪刀、石头和布。我们还可以添加一个方法来将手势表示为字符串,以便显示游戏结果。
```java
public class Gesture {
public static final int SCISSORS = 0;
public static final int ROCK = 1;
public static final int PAPER = 2;
private int value;
public Gesture(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public String toString() {
switch (value) {
case SCISSORS:
return "scissors";
case ROCK:
return "rock";
case PAPER:
return "paper";
default:
return "";
}
}
}
```
接下来,我们需要定义一个游戏类,它包含玩家和电脑的手势,以及比较手势的方法。
```java
public class Game {
private Gesture playerGesture;
private Gesture computerGesture;
public void setPlayerGesture(Gesture gesture) {
this.playerGesture = gesture;
}
public void setComputerGesture(Gesture gesture) {
this.computerGesture = gesture;
}
public String compareGestures() {
if (playerGesture.getValue() == computerGesture.getValue()) {
return "Draw!";
} else if ((playerGesture.getValue() == Gesture.SCISSORS && computerGesture.getValue() == Gesture.PAPER)
|| (playerGesture.getValue() == Gesture.ROCK && computerGesture.getValue() == Gesture.SCISSORS)
|| (playerGesture.getValue() == Gesture.PAPER && computerGesture.getValue() == Gesture.ROCK)) {
return "You win!";
} else {
return "Computer wins!";
}
}
}
```
然后,我们需要编写一个主程序来实现游戏的流程。在每一轮游戏中,先让玩家输入手势,再获取电脑的手势并进行比较,最后输出游戏结果并将它写入 result.txt 文件。
```java
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Game game = new Game();
int playerScore = 0;
int computerScore = 0;
try {
PrintWriter writer = new PrintWriter("result.txt");
for (int i = 1; i <= 5; i++) {
System.out.println("Round " + i + ":");
System.out.print("Your gesture (0 for scissors, 1 for rock, 2 for paper): ");
int playerGestureValue = scanner.nextInt();
Gesture playerGesture = new Gesture(playerGestureValue);
game.setPlayerGesture(playerGesture);
Gesture computerGesture = new Gesture((int) (Math.random() * 3));
game.setComputerGesture(computerGesture);
String result = game.compareGestures();
System.out.println("You: " + playerGesture);
System.out.println("Computer: " + computerGesture);
System.out.println(result);
writer.println("Round " + i + ":");
writer.println("You: " + playerGesture);
writer.println("Computer: " + computerGesture);
writer.println(result);
if (result.equals("You win!")) {
playerScore++;
} else if (result.equals("Computer wins!")) {
computerScore++;
}
}
writer.println("Final score:");
writer.println("You: " + playerScore);
writer.println("Computer: " + computerScore);
writer.close();
} catch (FileNotFoundException e) {
System.out.println("Failed to write result to file: " + e.getMessage());
}
}
```
这就是一个基本的剪刀石头布游戏的实现,它可以记录每一局的游戏结果并将它们写入 result.txt 文件。您可以根据需要进行修改和扩展,例如增加更多的手势、增加计时器等等。
阅读全文