gpt4 book ai didi

java - 使用枚举来决定打印哪些文本的迷宫游戏

转载 作者:行者123 更新时间:2023-12-02 01:13:35 25 4
gpt4 key购买 nike

我正在制作一个迷宫游戏。我想做的是当用户撞到墙上时根据随机数打印不同的消息。该数字由随机数生成器生成。为此,我使用枚举,因为我认为它会更容易,但我遇到了问题。 GameManager 类获取用户的所有输入并决定如何处理它们。当我调用 textcard.cardtype.WALL 的打印语句时,它返回 null,我不知道为什么。我很确定我的问题与我的 getCard 方法有关。我试图在类里面归还该文本卡,但我不确定我是否做对了。下面是我的枚举和 wall 方法。

import java.util.Random;
public class TextCard
{
// instance variables - replace the example below with your own
private String text;//text in the card
private int number;
private TextCard text1;
public enum CardType{
WALL, TRAP
}
/**
* Constructor for objects of class TextCard
*/
//messages that will appear throughout the game
public TextCard(CardType cardType)
{
if(cardType == (CardType.WALL)){
wallCard();
}

}
public String wallCard(){
Random rnd = new Random();
number = rnd.nextInt(100) + 1;
if(number < 20){
return ("wall1");
}
if(20 < number && number > 40){
return ("wall2");
}
if(40 < number && number > 60){
return ("wall3");
}
if(60 < number && number > 80){
return ("wall4");
}
else{
return ("wall5");
}
}
public TextCard getCard(){
return text1;
}

}

游戏管理器中的方法调用

System.out.println(new TextCard(TextCard.CardType.WALL).getCard());

最佳答案

System.out.println(new TextCard(TextCard.CardType.WALL).wallCard());

我不知道为什么你想要一个方法来返回对象本身,你已经有了。我假设您想调用您的方法来获取随机字符串。

此外,您可以将 wallCard 方法设为静态,这样您就不需要在打印后立即删除的 TextCard 的新实例

public static String wallCard(){

这将像这样使用

System.out.println(TextCard.wallCard());

为了解释您发布的代码有什么问题,您在构造函数中调用 wallCard() ,它返回随机字符串,但您不存储它。 getCard() 方法尚不清楚,但看起来您在打印中如何调用它,您希望它返回随机字符串。如果您只想重复使用 1 个随机字符串,则需要使用文本字符串变量。所以在构造函数中,执行以下操作

text = wallCard(); 

然后在 getCard() 中,返回文本。它需要返回一个字符串。

关于java - 使用枚举来决定打印哪些文本的迷宫游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59000483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com