gpt4 book ai didi

使用随机数的 Java 游戏

转载 作者:行者123 更新时间:2023-11-30 06:58:13 25 4
gpt4 key购买 nike

我有一个java程序,计算机将决定哪个玩家先走,并选择随机数从数组中删除。当玩家移除数字时,数组将会减少。所有这些都将使用随机完成。但是当我运行我的代码时,它不是我期望的那样。我可以知道我哪里出错了吗?

这是我的代码:

[类(class)]

public class StickBag {

private int numOfSticks;

public StickBag(int numOfSticks)
{
this.numOfSticks = numOfSticks;
}

public int getNumOfSticks() {
return numOfSticks;
}

public void setNumOfSticks(int numOfSticks) {
this.numOfSticks = numOfSticks;
}

public int remove(int n)
{
numOfSticks = numOfSticks - n;
return numOfSticks;
}
}

[主要]

public class StickGameApp {

public static void main(String[] args) {

StickBag s1 = new StickBag(25);

System.out.println("Welcome to the game of sticks!");
System.out.println("There are initially " + s1.getNumOfSticks() + " sticks on the board.");

int minP = 1;
int maxP = 2;
int randP;

int minN = 1;
int maxN = 10;
int randNum;

randP = minP + (int)(Math.random()*(maxP));
randNum = minN + (int)(Math.random()*(maxN));

for (int i=0; i<10; i++)
{
if(s1.getNumOfSticks() > randNum)
{
System.out.println("Computer player " + randP + " choose " + randNum + " sticks ");
s1.remove(randNum);
}
else
{
System.out.println("Computer player " + randP + " wants to choose " + randNum + " sticks but is unable to.");
System.out.println("Computer player " + randP + " loses ");
}
}

}
}

当我运行代码时,它显示如下:

<小时/>

欢迎来到棍子游戏!

板上最初有 25 根木棍。

电脑玩家2选择6棒

电脑玩家2选择6棒

电脑玩家2选择6棒

电脑玩家2选择6棒

计算机玩家 2 想要选择 6 根棍子,但无法选择。电脑玩家2输了

计算机玩家 2 想要选择 6 根棍子,但无法选择。电脑玩家2输了

计算机玩家 2 想要选择 6 根棍子,但无法选择。电脑玩家2输了

计算机玩家 2 想要选择 6 根棍子,但无法选择。电脑玩家2输了

计算机玩家 2 想要选择 6 根棍子,但无法选择。电脑玩家2输了

计算机玩家 2 想要选择 6 根棍子,但无法选择。电脑玩家2输了

<小时/>

但我希望它像这样显示:

<小时/>

欢迎来到棍子游戏!

板上最初有 25 根木棍。

计算机玩家 1 选择 5 根棍子。

计算机玩家 2 选择 7 根棍子。

计算机玩家 1 选择 7 根棍子。

计算机玩家 2 想要选择 7 根棍子,但无法选择。

电脑玩家2,你输了。

<小时/>

我可以知道我哪里出错了吗?

最佳答案

你的错误只是你把玩家和计算机的随机数生成器randPrandNum放在运行游戏的for循环之前,这样随机数选择就会被执行只有一次。

你的代码应该是:

for (int i=0; i<10; i++)
{
randP = minP + (int)(Math.random()*(maxP));
randNum = minN + (int)(Math.random()*(maxN));
if(s1.getNumOfSticks() > randNum)
{
System.out.println("Computer player " + randP + " choose " + randNum + " sticks ");
s1.remove(randNum);
}
else
{
System.out.println("Computer player " + randP + " wants to choose " + randNum + " sticks but is unable to.");
System.out.println("Computer player " + randP + " loses ");
}
}

}

关于使用随机数的 Java 游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41422749/

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