Java入门超简单程序Treasure Hunting

Treasure Hunting 

The goal of this assignment is to write a program, TreasureHunting, that plays the game of finding a treasure that is located in the 10-by-10 grid.

The player has 10 chances to guess its location. The location of the treasure is by selecting two random integers between 1 and 10. After the user enters a guess, if the guess does not match the true location, the program gives the user two tips. The first tip is approximately how far the guess is from the true location: whether the distance between the guess and the true location is very small, reasonably small, or not. The second tip is offered the second round on, and is whether the distance is smaller than the previous round. After showing these tips, the program shows a diagram that presents the location of the present guess and the previous guess.

Since many variables are involved in the program, the program shall use eight global int variables:

   static int trueX, trueY;
   static int prevX, prevY;
   static int nowX, nowY
   static int prevDistance, nowDistance;

The variables trueX and trueY are for storing the locations of the treasure. The variables prevX and prevY are for storing the guesses from the previous round. The variables nowX and nowY are for storing the guesses in the previous round. The variables prevDistance and nowDistance are for storing the previous and the present distances of the guesses from the true location.

The action that the program performs is in the following steps:

1. Call a method, openingMessage(), to print the rules of the program.

2. Call a method, initialize(), to select random locations for the treasure.

3. Execute a for-loop that iterates over the range 1 to 10 with the iteration variable, say i, with the following series of action:

(a)  Print the value of round.

(b)  Optionally, print the location of the treasure (so as to make sure that the program is working).

(c)  Call a method, receiveGuess(), to receive a guess from the user.

(d)  If the value of nowDistance is equal to 0, terminate the loop immediately by calling

break.

(e)  Call a method, checkDistance(), to give the first tip.

(f) If the value of round is greater than or equal to 2, call a method, advise(). Before the end of the program, report the true location.

The method openingMessage

For openingMessage, the program explains the rule of the game as follows:

#######################################################
# A treasure has been hidden at a location in a 10x10 #
# gird. Guess where it is. You have 10 chances.       #
#######################################################

The method initialize

For initialize, the program sets -1 to nowX and nowY,assigns a random integer between 1 and 10 to trueX, assigns another random integer between 1 and 10 to trueY, and assign a large value, say 20, to nowDistance.

The program reports the round in the following manner:

---- Round M ----
where M is the round. The program prints the location of the treasure in the format: X,Y

The method receiveGuess

In receiveGuess, before receiving the new guess, the program needs to update the “previous” values with the “present” values. Then it receives two guesses, one for X and the other for Y. After that, the program updates the distance. The distance between the true location and the guessed location is in the Manhattan distance, which is the sum of the absolute distance on the x-axis and the absolute distance on the y-axis.

The method show

This method uses a double for-loop to print the locations of the present and the previous guesses.

Here is an example of an output generated by the method:

.......... 10
.......... 9
.......... 8
...P...... 7
.......... 6
.....@.... 5
.......... 4
.......... 3
.......... 2
.......... 1
@ = current, P = previous

The numbers appearing at the end of the lines are the y-coordinates. The character P represents the previous location. The character @ represents the current location. The period . represents the rest. The external for-loop generates the value for y going down from 10 to 1 and the internal for-loop generates the value for x going up from 1 to 10. In the body of the internal loop, the method checks whether the combination of x and y is equal to the combination of nowX and nowY, and if so, print "@"; otherwise, the method checks whether the combination of x and y is equal to the combination of prevX and prevY, and if so, print "P"; otherwise, it prints ".". After completing the internal for-loop, the method prints one whitespace and the value of y. After completing the external for-loop, the method prints the line that says "@ = current, P = previous".

The method checkDistance

The method computes the Manhattan distance between nowX, nowY and trueX, trueY, which is as the sum of the absolute difference between nowX and trueX and the absolute difference between nowY and trueY. It uses int constants CLOSE and FAR. Their values are set to 3 and 6. After calculating the value of the Manhattan distance, the method prints a statement according to its value:

  • 0: "You have found the treasure!"
  • 1, 2, 3: "The distance is no more than 3."
  • 4, 5, 6: "The distance is no more than 6."
  • 7 or higher: "The distance is more than 6."

The method advise

The method computes the difference of the two distance values. Depending on the sign of this

difference, the method prints the following: • 0: "The same distance"

  • 1 or higher: "You are farther."
  • −1 or smaller: "You are closer."

Execution Examples

In this example, the user does not find it.

 
#######################################################
# A treasure has been hidden at a location in a 10x10 #
# gird. Guess where it is. You have 10 chances.       #
#######################################################
---- Round 1 ----
4,8
Enter your guess for X, Y: 3 5 The distance is no more than 6
..........10 

..........9 

..........8

..........7 

..........6 

..@.......5

..........4

..........3 

..........2 

..........1
@ = current, P = previous

---- Round 2 ----
4,8
Enter your guess for X, Y: 5 9 The distance is no more than 3. You are closer.
..........10 
....@.....9 
..........8 
..........7 
..........6 
..P.......5 
..........4 
..........3 
..........2 
..........1
@ = current, P = previous

---- Round 3 ----
4,8
Enter your guess for X, Y: 6 5 The distance is no more than 6. You are farther.
..........10 
....P.....9
..........8 
..........7 
..........6 
.....@....5
..........4 
..........3 
..........2 
..........1
@ = current, P = previous

---- Round 4 ----
4,8
Enter your guess for X, Y: 4 8
You have found the treasure!
The treasure was at (4,8).

Solution:


import java.util.Random;
import java.util.Scanner;

public class Game {

    static int trueX, trueY;
    static int prevX, prevY;
    static int nowX, nowY;
    static int prevDistance, nowDistance;

    public static void openingMessage() {
        String message = "#######################################################\n" +
                "# A treasure has been hidden at a location in a 10x10 #\n" +
                "# gird. Guess where it is. You have 10 chances.       #\n" +
                "#######################################################";
        System.out.println(message);

    }

    public static void initialize() {

        nowX = -1;
        nowY = -1;
        Random random = new Random();
        trueX = random.nextInt(9) + 1;
        trueY = random.nextInt(9) + 1;
        //trueX = 4;
        //trueY = 8;
        nowDistance = 20;
    }

    public static void receiveGuess() {
        prevX = nowX;
        prevY = nowY;
        prevDistance = nowDistance;

        Scanner scanner = new Scanner(System.in);
        nowX = scanner.nextInt();
        nowY = scanner.nextInt();
        nowDistance = Math.abs(nowX - trueX) + Math.abs(nowY - trueY);

    }

    public static void main(String[] args) {

        openingMessage();
        initialize();

        for (int m = 1; m <= 10; m++) {
            System.out.println();
            System.out.println("---- Round " + m + " ----");
            System.out.println(trueX + "," + trueY);
            System.out.print("Enter your guess for X, Y:");
            receiveGuess();
            checkDistance();
            if (nowDistance == 0) {
                break;
            }
            if (m >= 2) {
                advise();
            }
            show();
        }
        System.out.println("The treasure was at (" + trueX + "," + trueY + ").");
    }

    public static void show() {

        for (int y = 10; y >= 1; y--) {

            for (int x = 1; x <= 10; x++) {
                if (x == nowX && y == nowY) {
                    System.out.print("@");
                } else if (x == prevX && y == prevY) {
                    System.out.print("P");
                } else {
                    System.out.print(".");
                }

            }
            System.out.println(y);

        }
        System.out.println("@ = current, P = previous");
    }

    public static void advise() {
        if (nowDistance < prevDistance) {
            System.out.println("You are closer.");
        } else if (nowDistance > prevDistance) {
            System.out.println("You are farther.");
        } else {
            System.out.println("The same distance");
        }
    }

    public static void checkDistance() {
        if (nowDistance == 0) {
            System.out.println("You have found the treasure!");
        } else if (nowDistance >= 1 && nowDistance <= 3) {
            System.out.println("The distance is no more than 3.");
        } else if (nowDistance >= 4 && nowDistance <= 6) {
            System.out.println("The distance is no more than 6.");
        } else {
            System.out.println("The distance is more than 6.");
        }

    }

}

好的,以下是一个简单的用 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 + " 分!"); } } ``` 这个代码示例演示了一个简单的奥比岛游戏,包含了游戏逻辑、地图状态和玩家操作等部分。你可以根据自己的需求和游戏规则进行修改和扩展。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

康雨城

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值