|
| 1 | +import java.util.Scanner; |
| 2 | +import java.util.Random; |
| 3 | + |
| 4 | +public class ludo { |
| 5 | + |
| 6 | + public static void main(String[] args) { |
| 7 | + |
| 8 | + Scanner scanner = new Scanner(System.in); |
| 9 | + Random random = new Random(); |
| 10 | + |
| 11 | + System.out.print("Enter number of players (2-4): "); |
| 12 | + int numPlayers = scanner.nextInt(); |
| 13 | + |
| 14 | + if (numPlayers < 2 || numPlayers > 4) { |
| 15 | + System.out.println("Invalid number of players. Please restart and enter 2 to 4 players."); |
| 16 | + scanner.close(); |
| 17 | + return; |
| 18 | + } |
| 19 | + |
| 20 | + System.out.println("\nStarting Ludo game with " + numPlayers + " players!"); |
| 21 | + System.out.println("First player to reach position 30 wins.\n"); |
| 22 | + |
| 23 | + int[] positions = new int[numPlayers]; |
| 24 | + |
| 25 | + boolean gameOver = false; |
| 26 | + int currentPlayer = 0; |
| 27 | + |
| 28 | + while (!gameOver) { |
| 29 | + |
| 30 | + System.out.println("Player " + (currentPlayer + 1) + "'s turn"); |
| 31 | + System.out.print("Press 1 to roll the dice: "); |
| 32 | + int choice = scanner.nextInt(); |
| 33 | + |
| 34 | + if (choice != 1) { |
| 35 | + System.out.println("Invalid input. Turn skipped.\n"); |
| 36 | + } else { |
| 37 | + int dice = random.nextInt(6) + 1; |
| 38 | + System.out.println("Dice rolled: " + dice); |
| 39 | + |
| 40 | + positions[currentPlayer] += dice; |
| 41 | + |
| 42 | + if (positions[currentPlayer] > 30) { |
| 43 | + positions[currentPlayer] = 30; |
| 44 | + } |
| 45 | + |
| 46 | + System.out.println("Player " + (currentPlayer + 1) + |
| 47 | + " position: " + positions[currentPlayer]); |
| 48 | + |
| 49 | + if (positions[currentPlayer] == 30) { |
| 50 | + System.out.println("\n🎉 Player " + (currentPlayer + 1) + " WINS THE GAME! 🎉"); |
| 51 | + gameOver = true; |
| 52 | + break; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + System.out.println(); |
| 57 | + |
| 58 | + currentPlayer = (currentPlayer + 1) % numPlayers; |
| 59 | + } |
| 60 | + |
| 61 | + scanner.close(); |
| 62 | + } |
| 63 | +} |
0 commit comments