用java写面向对象程序之奥比岛游戏的代码
时间: 2023-12-08 07:05:41 浏览: 158
好的,以下是一个简单的用 Java 写的面向对象程序设计的奥比岛游戏代码示例,供您参考:
```
import java.util.ArrayList;
import java.util.Scanner;
public class ObiIsland {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 创建游戏对象
Game game = new Game();
// 添加玩家
System.out.print("请输入玩家数量:");
int playerCount = scanner.nextInt();
scanner.nextLine(); // 读取换行符
for (int i = 0; i < playerCount; i++) {
System.out.print("请输入玩家 " + (i + 1) + " 的名字:");
String name = scanner.nextLine();
Player player = new Player(name);
game.addPlayer(player);
}
// 开始游戏
game.startGame();
}
}
class Game {
private ArrayList<Player> players;
private Player currentPlayer;
private Map map;
public Game() {
players = new ArrayList<>();
map = new Map();
}
public void addPlayer(Player player) {
players.add(player);
}
public void startGame() {
// 随机选择第一个玩家
currentPlayer = players.get((int) (Math.random() * players.size()));
// 游戏循环
while (!map.isGameOver()) {
// 当前玩家进行操作
currentPlayer.move(map);
// 切换到下一个玩家
currentPlayer = getNextPlayer();
}
// 游戏结束,统计得分
int highScore = 0;
Player winner = null;
for (Player player : players) {
int score = player.getScore();
System.out.println(player.getName() + " 的得分是 " + score);
if (score > highScore) {
highScore = score;
winner = player;
}
}
System.out.println("游戏结束,胜利者是 " + winner.getName());
}
private Player getNextPlayer() {
int currentIndex = players.indexOf(currentPlayer);
int nextIndex = (currentIndex + 1) % players.size();
return players.get(nextIndex);
}
}
class Map {
private int[] treasures;
private boolean gameOver;
public Map() {
treasures = new int[]{5, 10, 15, 20};
gameOver = false;
}
public int getTreasure(int index) {
return treasures[index];
}
public void removeTreasure(int index) {
treasures[index] = 0;
if (isGameOver()) {
gameOver = true;
}
}
public boolean isGameOver() {
for (int treasure : treasures) {
if (treasure > 0) {
return false;
}
}
return true;
}
}
class Player {
private String name;
private int score;
public Player(String name) {
this.name = name;
score = 0;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
public void move(Map map) {
Scanner scanner = new Scanner(System.in);
System.out.println(name + " 的分数是 " + score);
System.out.print("请输入要挖掘的宝藏编号(1-4):");
int index = scanner.nextInt() - 1;
if (index < 0 || index >= map.getTreasures().length) {
System.out.println("宝藏编号无效!");
return;
}
int treasure = map.getTreasure(index);
if (treasure == 0) {
System.out.println("该宝藏已被挖掘!");
return;
}
score += treasure;
map.removeTreasure(index);
System.out.println(name + " 挖掘了宝藏,获得了 " + treasure + " 分!");
}
}
```
这个代码示例演示了一个简单的奥比岛游戏,包含了游戏逻辑、地图状态和玩家操作等部分。你可以根据自己的需求和游戏规则进行修改和扩展。
阅读全文