I'm looking for some feedback on my first program. It's a small game you play with matches.
It's a two-player game, where the players take turns picking matches (1, 2 or 3) and cannot pick the same number of matches as the other player: if player one picks 2 matches, player two will have to pick either 1 or 3 matches. The player who cannot pick anymore matches loses the game, which means there are two end scenarios : when there are no more matches, or there is 1 but the other player picked 1 during the previous round.
Is there a more efficient way to do something (performance-wise or with less code to write)? Can I improve the overall presentation/organization of the code? (am I unaware of a convention?) Any advice or criticism is very welcome.
import java.util.Scanner ;
public class JeuDeNim2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in) ;
int totalMatches ;
do {
System.out.println("How many matches do you want to play with? "
+ "(from 6 to 60)") ;
totalMatches = sc.nextInt() ;
}
while (totalMatches < 6 || totalMatches > 60) ;
int matchesThisTurn ;
int matchesPreviousTurn = 0 ;
int round = 0 ;
int player = 0 ;
int previousPlayer ;
while (true) {
round++ ;
previousPlayer = player ;
player = round % 2 ;
if (player == 0) {
player = 2 ;
}
while (true) {
if (totalMatches == 1) {
System.out.println("There is only one match left on "
+ "the table") ;
} else {
System.out.println("There are " + totalMatches
+ " matches on the table") ;
}
if (round == 1 || round == 2) {
System.out.println("Player " + player + ": How many "
+ "matches do you want to pick? (1, 2 or 3)") ;
} else {
System.out.println("Player " + player + ": How many "
+ "matches do you want to pick this turn?") ;
}
matchesThisTurn = sc.nextInt() ;
if (matchesThisTurn < 1 || matchesThisTurn > 3) {
System.out.println("Wrong entry: you have to pick 1, 2 "
+ "or 3 matches") ;
continue ;
}
if (matchesThisTurn == matchesPreviousTurn) {
System.out.println("You cannot pick the same number of "
+ "matches as Player " + previousPlayer) ;
continue ;
}
if (totalMatches == 1 && matchesThisTurn > totalMatches) {
System.out.println("You cannot pick " + matchesThisTurn
+ " matches: there is only one match left") ;
continue ;
}
if (matchesThisTurn > totalMatches) {
System.out.println("You cannot pick " + matchesThisTurn
+ " matches: there are only " + totalMatches
+ " matches left") ;
continue ;
}
break ;
}
totalMatches -= matchesThisTurn ;
matchesPreviousTurn = matchesThisTurn ;
if (totalMatches == 0) {
System.out.println("*** There are no more matches! ***") ;
break ;
}
if (totalMatches == 1 && matchesThisTurn == 1) {
System.out.println("*** There is only one match left, but "
+ "Player " + player + " already took one! ***") ;
break ;
}
}
System.out.println("*** The game is over! Player " + player
+ " Wins! ***") ;
}
}