-
Notifications
You must be signed in to change notification settings - Fork 507
Expand file tree
/
Copy pathGame.java
More file actions
63 lines (52 loc) · 1.53 KB
/
Game.java
File metadata and controls
63 lines (52 loc) · 1.53 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
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Game {
private List<Player> players;
private Board board;
private Player winner;
private Random random;
public Game(Board board) {
this.players = new ArrayList<>();
this.board = board;
this.winner = null;
this.random = new Random();
}
public void addPlayer(Player player) {
players.add(player);
}
public void setSnakes(List<int[]> snakes) {
for (int[] snake : snakes) {
board.addSnake(snake[0], snake[1]);
}
}
public void setLadders(List<int[]> ladders) {
for (int[] ladder : ladders) {
board.addSnake(ladder[0], ladder[1]);
}
}
public int rollDice() {
return random.nextInt(6) + 1;
}
public void play() {
int currentPlayerIndex = 0;
while (winner == null) {
Player player = players.get(currentPlayerIndex);
int diceValue = rollDice();
int initialPosition = player.getPosition();
int newPosition = initialPosition + diceValue;
if (newPosition <= board.getSize()) {
newPosition = board.getNewPosition(newPosition);
player.setPosition(newPosition);
}
System.out.printf("%s rolled a %d and moved from %d to %d%n", player, diceValue, initialPosition,
player.getPosition());
if (player.getPosition() == board.getSize()) {
winner = player;
System.out.printf("%s wins the game.%n", player);
break;
}
currentPlayerIndex = (currentPlayerIndex + 1) % players.size();
}
}
}