Skip to content

Commit ee6f4ac

Browse files
Snake and Ladder game
1 parent 0f77f88 commit ee6f4ac

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

Snake_and_Ladder.java

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import java.util.*;
2+
3+
public class Snake_and_Ladder {
4+
5+
public static void main(String[] args) {
6+
7+
Scanner sc = new Scanner(System.in);
8+
Random dice = new Random();
9+
10+
System.out.println("Welcome to Snake and Ladder Game");
11+
System.out.print("Enter number of players: ");
12+
int numPlayers = sc.nextInt();
13+
sc.nextLine();
14+
15+
String[] players = new String[numPlayers];
16+
int[] position = new int[numPlayers];
17+
18+
for (int i = 0; i < numPlayers; i++) {
19+
System.out.print("Enter name of player " + (i + 1) + ": ");
20+
players[i] = sc.nextLine();
21+
position[i] = 0;
22+
}
23+
24+
HashMap<Integer, Integer> board = new HashMap<>();
25+
board.put(99, 54);
26+
board.put(70, 55);
27+
board.put(52, 42);
28+
board.put(25, 2);
29+
30+
board.put(6, 25);
31+
board.put(11, 40);
32+
board.put(60, 85);
33+
board.put(46, 90);
34+
35+
System.out.println("\n Game starts with players: " + Arrays.toString(players));
36+
37+
boolean gameOver = false;
38+
39+
while (!gameOver) {
40+
for (int i = 0; i < numPlayers; i++) {
41+
42+
System.out.println("\n" + players[i] + "'s turn. Press Enter to roll dice");
43+
sc.nextLine();
44+
45+
int roll = dice.nextInt(6) + 1;
46+
System.out.println(" Rolled: " + roll);
47+
48+
position[i] += roll;
49+
50+
if (position[i] > 100) {
51+
position[i] -= roll;
52+
System.out.println("Move exceeds 100. Stay at " + position[i]);
53+
}
54+
55+
if (board.containsKey(position[i])) {
56+
int newPos = board.get(position[i]);
57+
if (newPos > position[i])
58+
System.out.println("Ladder! Climb up to " + newPos);
59+
else
60+
System.out.println("Snake! Slide down to " + newPos);
61+
62+
position[i] = newPos;
63+
}
64+
65+
System.out.println(players[i] + " is at position " + position[i]);
66+
67+
if (position[i] == 100) {
68+
System.out.println("\n" + players[i] + " WINS THE GAME! 🏆");
69+
gameOver = true;
70+
break;
71+
}
72+
}
73+
}
74+
75+
sc.close();
76+
}
77+
}

0 commit comments

Comments
 (0)