import java.util.Random;
import java.lang.Math;
import java.lang.String;
public class GameOfNim
{
private int min,max;
private int turn;
private int firstturn;
private int stupid;
private int smart;
private int computer;
private int user;
private int first;
private int pile;
public GameOfNim(int min, int max ){
pile=(int)(Math.random()*max+min);
smart=(int)(Math.random()*100);
stupid=(int)(Math.random()*100);
System.out.println("Pile size is "+pile);
firstturn=(int)(Math.random()*100 + 1);
computer=0;
user=1;
if(firstturn>50)
{
firstturn=user;
}
else
{
firstturn=computer;
}
firstturn=turn;
}
public void play()
{
if(smart>50)
{
System.out.println("Computer is playing smart");
}
else
{
System.out.println("Computer is playing stupid");
}
if(firstturn==user)
{
System.out.println("You go first");
}
else
{
System.out.println("Computer goes first");
}
turn = firstturn;
while(pile-1>0)
{
if(turn==user)
{
String take = "How many marbles do you want to take away?";
System.out.println(take);
int take2 = Integer.parseInt(take);
while(take2>(int)(pile/2))
{
System.out.println("Only take away half or less from the pile");
take = "How many marbles do you want to take away?";
take2= Integer.parseInt(take);
}
pile= pile-take2;
System.out.println("There are "+pile+" marbles left");
turn=computer;
}
else
{
if(smart>50)
{
pile -= smartTake();
}
else
{
pile -= stupidTake();
}
turn = user;
}
}
}
private int smartTake()
{
int x = (int)(Math.random())*2-1;
int sMarbles= (int)Math.pow(2,x);
while (sMarbles > (.5 * pile) || sMarbles==0)
{
x = (int)(Math.random())*2-1;
sMarbles = (int)Math.pow(2,x);
}
System.out.println("The computer took away " + sMarbles +" marbles");
return sMarbles;
}
private int stupidTake(){
int stMarbles = pile/2;
while (stMarbles > (.5*pile) || pile==0)
{
stMarbles = pile/2;
}
System.out.println("The Computer took away " + stMarbles +" marbles");
return stMarbles;
}
}
这是我的nim类游戏
public class Project5
{
public static void main(String args[])
{
String k = "yes";
String str;
Scanner console = new Scanner(System.in);
System.out.print("Enter the minimum number of marbles in your pile: ");
int min = console.nextInt();
System.out.print("Enter the maximum number of marbles in your pile: ");
int max= console.nextInt();
GameOfNim game = new GameOfNim(min, max);
game.play();
System.out.println( " Thank you and good bye!");
}
}
这是我的驱动程序类
由于某些原因每次我运行它它一直到它说“计算机先行”然后没有其他事情发生。我假设它陷入了一个循环,但我似乎无法找出原因。任何帮助将不胜感激