gpt4 book ai didi

java - Nim 循环游戏

转载 作者:行者123 更新时间:2023-12-03 23:14:18 24 4
gpt4 key购买 nike

所以,我必须制作一个 Nim 风格的 Java 游戏......我已经成功制作了大部分游戏......我只是有几个问题让我感到困惑:

问题 1:程序执行得很好,甚至运行了一次,但在执行一次代码后,程序就退出了......我需要帮助看看它为什么会那样(我是否使用了错误的循环?)

问题二:为什么程序总是选择电脑处于所谓的“智能模式”?

任何帮助将不胜感激。谢谢你们:D

这是我的代码:

import java.util.*;
public class GameOfNim
{
public static void main (String [] args)
{
Scanner in = new Scanner (System.in);
Random num = new Random ();
int numberLeft = num.nextInt(101-10) + 10;
int computerMode = num.nextInt(1);
int subtraction = numberLeft;
boolean turn = num.nextBoolean();

System.out.println ("The number you start out with is: " + numberLeft);

if (computerMode == 0)
{
System.out.println ("The computer is in smart mode");
}
if (computerMode == 1)
{
System.out.println ("The computer is in dumb mode");
}

while (numberLeft > 1)
{
if (turn == true)
{
System.out.println ("It is your turn...");
System.out.printf ("Please enter the number you wish to take from the pile (Remember it has to be less than " + numberLeft/2 + "): ");
subtraction = in.nextInt();
numberLeft -=subtraction;
System.out.println ("The number left is " + numberLeft);
turn = false;
}
if (turn ==false)
{
System.out.println ("It is the computer's turn...");
if (computerMode == 0)
{
numberLeft = smartComputer(numberLeft);
System.out.println ("The number left is " + numberLeft);
}

if (computerMode == 1)
{
numberLeft -= num.nextInt(numberLeft/2);
System.out.println ("The number left is " + numberLeft);
}
turn = true;
return;
}
}

if (numberLeft <= 1)
{
if (turn = false)
{
System.out.println ("You Win!");
}
else
{
System.out.println ("You're horrible...you lost to a computer.");
}
}
}

public static int smartComputer (int num)
{
int power = 2;
while (power < num)
{
power *=2;
}
power /= 2;
num = power-1;
return num;
}
}

最佳答案

Random.nextInt(int n) 将返回一个介于 0 和 n 之间的整数值。由于您已按如下方式计算 computerMode:

int computerMode = num.nextInt(1);

computerMode 将始终返回 0。

如果计算机只能处于两种模式,也许您可​​以改用 nextBoolean?

关于java - Nim 循环游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20340166/

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