Reputation: 107
My assignment:
The game of Stix – similar to a game played on "Survivor, Thailand" some time ago – in a simplified version somehow looks like this:
It is played by two players (in Survivor it were more than two, but here we just deal with two). A number of sticks (like matches) are placed on a table. The first player takes 1, 2 or 3 sticks away, provided that there that many on the table. Then the second player takes 1, 2 or 3 sticks away (if possible), and so on. Whoever takes the last stick, loses.
This is my class:
public class StixBoard
{
public int number;
public StixBoard(int number)
{
this.number = number;
}
public int getNumStix()
{
return number;
}
public boolean takeStix(int number)
{
int take = 0;
while(take != number && number <= 3 && number > 0)
{
number = this.number - take;
take++;
}
if(this.number >= 1 && this.number <= 3)
{
number = number - this.number;
System.out.println("Number of sticks on board:" + number);
return(true);
}
else
System.out.println("Illegeal Move");
return(false);
}
public boolean isGameOver()
{
if(number >=1)
{
return(true);
}
else
return false;
}
public String toString()
{
return(getNumStix() + " Stix Remaining.");
}
}
This is my tester:
public class StixGame
{
public static void main(String[] args)
{
StixBoard game1 = new StixBoard(6);
System.out.println(game1.getNumStix());
System.out.println(game1.takeStix(1));
System.out.println(game1.getNumStix());
}
}
I cant seem to shy away from this output:
6
Illegeal Move
false
6
Upvotes: 0
Views: 73
Reputation: 32343
You use the variable number
way too many times, this will make your code extremely confusing... Using an IDE to rename the variable in your class to totalStix
, the problems become instantly obvious.
takeStix
method shouldn't need a while loop. All that's happening is one player is taking stix away, right? So remove that code.take
, because that's what you're taking away.You're left with the following code (with a few other minor tweaks):
public class StixBoard
{
public int totalStix;
public StixBoard(int number)
{
this.totalStix = number;
}
public int getNumStix()
{
return totalStix;
}
public boolean takeStix(int take)
{
if(take >= 1 && take <= 3)
{
totalStix -= take;
System.out.println("Number of sticks on board:" + totalStix);
return true;
}
System.out.println("Illegeal Move");
return false ;
}
public boolean isGameOver()
{
if(totalStix >=1)
{
return(true);
}
else
return false;
}
public String toString()
{
return(getNumStix() + " Stix Remaining.");
}
}
Upvotes: 1