-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathSnakeLadder.java
More file actions
80 lines (66 loc) · 2.66 KB
/
SnakeLadder.java
File metadata and controls
80 lines (66 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
public class SnakeLadder {
final static int WINNING_POSITION = 100;
static Map<Integer, Integer> snakes = new HashMap<>();
static Map<Integer, Integer> ladders = new HashMap<>();
static {
// Setting up snakes
snakes.put(99, 54);
snakes.put(70, 55);
snakes.put(52, 42);
snakes.put(25, 2);
snakes.put(95, 72);
// Setting up ladders
ladders.put(6, 25);
ladders.put(11, 40);
ladders.put(60, 85);
ladders.put(46, 90);
ladders.put(17, 69);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int player1Position = 0;
int player2Position = 0;
boolean isPlayer1Turn = true;
System.out.println("Welcome to Snake and Ladder Game!");
while (player1Position < WINNING_POSITION && player2Position < WINNING_POSITION) {
System.out.println((isPlayer1Turn ? "Player 1" : "Player 2") + "'s turn. Press Enter to roll the dice...");
scanner.nextLine();
int diceValue = random.nextInt(6) + 1;
System.out.println("Rolled a " + diceValue);
if (isPlayer1Turn) {
player1Position = movePlayer(player1Position, diceValue);
System.out.println("Player 1 is at position: " + player1Position);
} else {
player2Position = movePlayer(player2Position, diceValue);
System.out.println("Player 2 is at position: " + player2Position);
}
if (player1Position == WINNING_POSITION) {
System.out.println("Player 1 wins!");
break;
} else if (player2Position == WINNING_POSITION) {
System.out.println("Player 2 wins!");
break;
}
isPlayer1Turn = !isPlayer1Turn; // Switch turns
}
scanner.close();
}
private static int movePlayer(int playerPosition, int diceValue) {
playerPosition += diceValue;
if (playerPosition > WINNING_POSITION) {
playerPosition -= diceValue; // Cannot move beyond the winning position
} else if (snakes.containsKey(playerPosition)) {
System.out.println("Oh no! Bitten by a snake!");
playerPosition = snakes.get(playerPosition);
} else if (ladders.containsKey(playerPosition)) {
System.out.println("Yay! Climbing a ladder!");
playerPosition = ladders.get(playerPosition);
}
return playerPosition;
}
}