以下是一个简单的实现示例:

import java.util.Scanner;

class Fish {
    private int size;

    public Fish(int size) {
        this.size = size;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public void eat(Fish otherFish) {
        if (this.size > otherFish.getSize()) {
            this.size += otherFish.getSize();
            System.out.println('You ate a fish! Your size is now ' + this.size);
        } else {
            System.out.println('You were eaten by a bigger fish! Game over.');
            System.exit(0);
        }
    }
}

public class FishGame {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the size of your fish: ");
        int userSize = scanner.nextInt();

        Fish userFish = new Fish(userSize);

        while (true) {
            System.out.print("Enter the size of the fish you want to eat (0 to quit): ");
            int fishSize = scanner.nextInt();

            if (fishSize == 0) {
                break;
            }

            Fish otherFish = new Fish((int) (Math.random() * (userSize + 10)));
            userFish.eat(otherFish);
        }

        System.out.println("Game over. Your final size is " + userFish.getSize());
    }
}

在这个程序中,Fish 类表示鱼,具有大小属性和吃鱼的方法。FishGame 类是游戏的主类,用于接收用户输入和进行游戏逻辑处理。在主方法中,首先要求用户输入自己鱼的大小,然后进入一个循环,用户可以输入想要吃的鱼的大小。程序会根据用户输入的大小生成一条随机大小的鱼,并调用用户鱼的 eat 方法进行判断是否能吃掉这条鱼。如果用户输入的大小为 0,表示退出游戏。当用户鱼被比自己大的鱼吃掉时,游戏结束,输出最终的用户鱼大小。

Java 大鱼吃小鱼游戏代码实现 - 完整教程

原文地址: https://www.cveoy.top/t/topic/pj8n 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录