summaryrefslogtreecommitdiffstats
path: root/src/jrummikub/control/RoundControl.java
blob: a19a2ab2f84b4df5c7076fefa079802b502dc5bd (plain)
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
package jrummikub.control;

import static jrummikub.model.PlayerSettings.Type.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import jrummikub.control.turn.AIControl;
import jrummikub.control.turn.HumanTurnControl;
import jrummikub.control.turn.ITurnControl;
import jrummikub.control.turn.TurnControlFactory;
import jrummikub.control.turn.TurnMode;
import jrummikub.model.Hand;
import jrummikub.model.IHand;
import jrummikub.model.IPlayer;
import jrummikub.model.IRoundState;
import jrummikub.model.ITable;
import jrummikub.model.PlayerSettings;
import jrummikub.model.Position;
import jrummikub.model.Score;
import jrummikub.model.Stone;
import jrummikub.model.StoneSet;
import jrummikub.util.Connection;
import jrummikub.util.Event;
import jrummikub.util.Event1;
import jrummikub.util.IEvent;
import jrummikub.util.IEvent1;
import jrummikub.util.IListener;
import jrummikub.util.IListener1;
import jrummikub.util.Pair;
import jrummikub.view.IView;
import jrummikub.view.IView.BottomPanelType;

/**
 * Controller that manages a single round of rummikub
 */
public class RoundControl {
	private ITurnControl turnControl;
	protected IRoundState roundState;
	private IView view;
	private ITable clonedTable;
	IHand clonedHand;
	private Event restartRoundEvent = new Event();
	private Event1<IRoundState> roundStateUpdateEvent = new Event1<IRoundState>();
	private Event1<Score> endOfRoundEvent = new Event1<Score>();
	protected List<Connection> connections = new ArrayList<Connection>();
	private boolean roundFinished;
	private boolean lastTurnNotEnoughPoints;
	private boolean lastTurnMeldError;

	/**
	 * Create a new RoundControl using the given gameState and view
	 * 
	 * @param roundState
	 *          initial round state
	 * @param view
	 *          view used for user interaction
	 */
	public RoundControl(IRoundState roundState, IView view) {
		this.roundState = roundState;
		this.view = view;
	}

	public IEvent1<IRoundState> getRoundStateUpdateEvent() {
		return roundStateUpdateEvent;
	}

	/**
	 * End the round
	 * 
	 * @return endOfRoundEvent
	 */
	public IEvent1<Score> getEndOfRoundEvent() {
		return endOfRoundEvent;
	}

	/**
	 * Begin the round
	 */
	public void startRound() {
		deal();
		continueRound();
	}

	/**
	 * Continue a saved round after loading
	 */
	public void continueRound() {
		connections.add(view.getStartTurnEvent().add(new IListener() {
			@Override
			public void handle() {
				startTurn();
			}
		}));

		connections.add(view.getAcknowledgeInvalidEvent().add(new IListener() {
			@Override
			public void handle() {
				nextPlayer();
			}
		}));

		prepareTurn();
	}

	/**
	 * Abort round if a new one is started or a saved one is loaded
	 */
	public void abortRound() {
		removeListeners();
		if (turnControl != null) {
			turnControl.abortTurn();
			turnControl = null;
		}
	}

	private void prepareTurn() {
		boolean isHuman = roundState.getActivePlayer().getPlayerSettings()
				.getType() == HUMAN;
		boolean oneHuman = roundState.getGameSettings().oneHuman();

		clonedTable = (ITable) roundState.getTable().clone();
		clonedHand = (IHand) roundState.getActivePlayer().getHand().clone();

		if (isHuman) {
			view.setBottomPanel(oneHuman ? BottomPanelType.HUMAN_HAND_PANEL
					: BottomPanelType.START_TURN_PANEL);
		} else {
			view.setBottomPanel(BottomPanelType.NONHUMAN_HAND_PANEL);
		}

		view.getTablePanel().setStoneSets(clonedTable.clone());
		view.setCurrentPlayerName(roundState.getActivePlayer().getPlayerSettings()
				.getName());
		view.setCurrentPlayerColor(roundState.getActivePlayer().getPlayerSettings()
				.getColor());
		view.setCurrentPlayerHasLaidOut(roundState.getActivePlayer().getLaidOut());

		turnControl = createTurnControl(roundState.getActivePlayer()
				.getPlayerSettings());

		boolean isAI = (turnControl instanceof AIControl);

		if (isAI || (isHuman && oneHuman)) {
			startTurn();
		}
	}

	protected void startTurn() {
		boolean isHuman = roundState.getActivePlayer().getPlayerSettings()
				.getType() == HUMAN;

		TurnMode turnMode = TurnMode.NORMAL_TURN;

		if (roundState.getTurnNumber() < 1) {
			view.setStoneCollectionHidden(true);
			turnMode = TurnMode.INSPECT_ONLY;
			if (clonedHand.getIdenticalStoneCount() >= 3) {
				turnMode = TurnMode.MAY_REDEAL;
			}
		}

		if (isHuman) {
			view.getPlayerPanel().setEndTurnMode(turnMode);
		}

		turnControl.setup(new ITurnControl.TurnInfo(clonedTable, clonedHand,
				roundState.getActivePlayer().getLaidOut(), turnMode), roundState
				.getGameSettings(), view);
		turnControl.getEndOfTurnEvent().add(new IListener1<ITable>() {
			@Override
			public void handle(ITable newTable) {
				endOfTurn(newTable);
			}
		});
		turnControl.getRedealEvent().add(new IListener() {
			@Override
			public void handle() {
				redeal();
			}
		});
		addTurnControlListeners(turnControl);

		turnControl.startTurn();
	}

	/** Override this */
	protected void addTurnControlListeners(ITurnControl turnControl) {
	}

	protected ITurnControl createTurnControl(PlayerSettings playerSettings) {
		return TurnControlFactory.getFactory(playerSettings.getType()).create();
	}

	void deal() {
		for (int i = 0; i < roundState.getPlayerCount(); i++) {
			IHand hand = roundState.getNthNextPlayer(i).getHand();
			for (int j = 0; j < roundState.getGameSettings().getNumberOfStonesDealt(); j++) {
				hand.drop(roundState.getGameHeap().drawStone(), new Position(0, 0));
			}
		}
	}

	private boolean laidOutValidPoints() {
		List<StoneSet> newSets = tableSetDifference(roundState.getTable(),
				clonedTable);

		int totalValue = 0;
		for (StoneSet set : newSets) {
			totalValue += set.classify(roundState.getGameSettings()).getSecond();
		}

		return totalValue == 0
				|| totalValue >= roundState.getGameSettings().getInitialMeldThreshold();
	}

	private void endOfTurn(ITable newTable) {
		boolean wasHuman = (turnControl instanceof HumanTurnControl);
		boolean wasAI = (turnControl instanceof AIControl);

		turnControl = null;

		roundState.getActivePlayer().setHand(clonedHand);
		boolean goToNextPlayer = true;
		lastTurnNotEnoughPoints = false;
		lastTurnMeldError = false;
		if (roundState.getTurnNumber() >= 1) {
			goToNextPlayer = checkTurn(newTable);
		}
		if (goToNextPlayer || wasAI) {
			nextPlayer();
		} else {
			if (wasHuman) {
				view.setBottomPanel(BottomPanelType.INVALID_TURN_PANEL);
			}

			if (lastTurnNotEnoughPoints) {
				view.setInitialMeldError(roundState.getGameSettings()
						.getInitialMeldThreshold());
				view.setInvalidStoneSets(tableSetDifference(roundState.getTable(),
						newTable));
			} else if (lastTurnMeldError) {
				view.setInitialMeldFirstError();
				view.setInvalidStoneSets(touchedStoneSets(newTable));
			} else {
				view.setStoneCollectionHidden(true);
				view.setInvalidStoneSets(invalidStoneSets(newTable));
			}
		}
	}

	private List<StoneSet> invalidStoneSets(ITable newTable) {
		List<StoneSet> invalidSets = new ArrayList<StoneSet>();
		for (Pair<StoneSet, Position> set : newTable) {
			if (set.getFirst().isValid(roundState.getGameSettings())) {
				continue;
			}
			invalidSets.add(set.getFirst());
		}
		return invalidSets;
	}

	private List<StoneSet> touchedStoneSets(ITable newTable) {
		List<StoneSet> touchedSets = new ArrayList<StoneSet>();
		for (StoneSet set : tableSetDifference(roundState.getTable(), newTable)) {
			for (Stone stone : set) {
				if (!roundState.getActivePlayer().getHand().contains(stone)) {
					touchedSets.add(set);
					break;
				}
			}
		}

		return touchedSets;
	}

	private void nextPlayer() {
		view.setSelectedStones(Collections.<Stone> emptyList());
		view.setInvalidStoneSets(Collections.<StoneSet> emptyList());
		view.setStoneCollectionHidden(false);
		if (roundState.getLastPlayer() == null) {
			if (roundState.getGameHeap().getSize() == 0) {
				roundState.setLastPlayer(roundState.getNthNextPlayer(0));
				roundState.nextPlayer();
				roundState.nextTurn();
			} else {
				roundState.nextPlayer();
				roundState.nextTurn();
			}
		} else {
			if (roundState.getActivePlayer() == roundState.getLastPlayer()) {
				endOfRound();
			} else {
				roundState.nextPlayer();
				roundState.nextTurn();
			}
		}
		if (!roundFinished) {
			prepareTurn();
		}
	}

	private boolean checkTurn(ITable newTable) {
		if (!newTable.isValid()) {
			rejectMove(newTable);
			return false;
		}
		if (!roundState.getActivePlayer().getLaidOut()) {
			// Player touched forbidden stones
			if (!tableSetDifference(newTable, roundState.getTable()).isEmpty()) {
				rejectMove(newTable);
				lastTurnMeldError = true;
				return false;
			}
			if (!laidOutValidPoints()) {
				rejectMove(newTable);
				lastTurnNotEnoughPoints = true;
				return false;
			}
		}
		Set<Stone> tableDiff = tableDifference(roundState.getTable(), newTable);

		roundState.setTable(newTable);

		if (tableDiff.isEmpty()) {
			// Player hasn't made a move
			dealStone();
		} else {
			roundState.getActivePlayer().setLaidOut(true);
			if (roundState.getActivePlayer().getHand().getSize() == 0) {
				endOfRound();
			}
		}
		return true;
	}

	private void rejectMove(ITable newTable) {
		Set<Stone> tableDiff = tableDifference(roundState.getTable(), newTable);
		// deal penalty, reset
		roundState.getGameHeap().putBack(tableDiff);
		dealPenalty(tableDiff.size());

	}

	static Set<Stone> tableDifference(ITable oldTable, ITable newTable) {
		Set<Stone> ret = new HashSet<Stone>();

		for (Pair<StoneSet, Position> entry : newTable) {
			for (Stone stone : entry.getFirst()) {
				ret.add(stone);
			}
		}
		for (Pair<StoneSet, Position> entry : oldTable) {
			for (Stone stone : entry.getFirst()) {
				ret.remove(stone);
			}
		}
		return ret;
	}

	static List<StoneSet> tableSetDifference(ITable oldTable, ITable newTable) {
		List<StoneSet> ret = new ArrayList<StoneSet>();

		for (Pair<StoneSet, Position> entry : newTable) {
			ret.add(entry.getFirst());
		}
		for (Pair<StoneSet, Position> entry : oldTable) {
			ret.remove(entry.getFirst());
		}
		return ret;
	}

	void dealStones(int count) {
		IHand hand = roundState.getActivePlayer().getHand();
		int rowCount = hand.getRowCount();

		for (int i = 0; i < count; ++i) {
			if (hand.getFreeRowSpace(rowCount - 1) == 0) {
				rowCount++;
			}

			hand.drop(roundState.getGameHeap().drawStone(), new Position(
					Hand.WIDTH - 1, rowCount - 1));
		}
	}

	private void dealStone() {
		dealStones(1);
	}

	private void dealPenalty(int count) {
		dealStones(count + 3);
	}

	void endOfRound() {
		removeListeners();
		Score roundScore = score();
		endOfRoundEvent.emit(roundScore);
		roundFinished = true;
	}

	private void removeListeners() {
		for (Connection c : connections) {
			c.remove();
		}
	}

	private Score score() {
		List<Boolean> winners = new ArrayList<Boolean>();
		List<Integer> points = new ArrayList<Integer>();

		boolean foundRegularWinner = false;
		int winnerPlayerNumber = 0;
		Pair<Integer, Integer> bestScore = new Pair<Integer, Integer>(
				Integer.MIN_VALUE, Integer.MAX_VALUE);
		int pointSum = 0;
		for (int i = 0; i < roundState.getPlayerCount(); i++) {
			IPlayer player = roundState.getNthPlayer(i);
			IHand playerHand = player.getHand();
			boolean isWinner = playerHand.getSize() == 0;
			winners.add(isWinner);
			if (isWinner) {
				foundRegularWinner = true;
				winnerPlayerNumber = i;
			}
			int stonePoints = 0;

			if (!player.getLaidOut()) {
				stonePoints = playerHand.isInitialMeldPossible(roundState
						.getGameSettings()) ? 200 : 100;
			} else {
				stonePoints = playerHand.getStonePoints(roundState.getGameSettings());
			}

			bestScore = updateBestScore(bestScore, -stonePoints, playerHand.getSize());

			points.add(-stonePoints);
			pointSum += stonePoints;
		}

		if (foundRegularWinner) {
			points.set(winnerPlayerNumber, pointSum);
		} else {
			for (int i = 0; i < roundState.getPlayerCount(); i++) {
				if (bestScore.equals(new Pair<Integer, Integer>(points.get(i),
						roundState.getNthPlayer(i).getHand().getSize()))) {
					winners.set(i, true);
				}
			}
		}
		return new Score(winners, points);
	}

	private static Pair<Integer, Integer> updateBestScore(
			Pair<Integer, Integer> bestScore, int stonePoints, int size) {
		if (bestScore.getFirst() == stonePoints) {
			return new Pair<Integer, Integer>(stonePoints, Math.min(
					bestScore.getSecond(), size));
		} else if (bestScore.getFirst() < stonePoints) {
			return new Pair<Integer, Integer>(stonePoints, size);
		}
		return bestScore;
	}

	/**
	 * Emitted when the round is aborted and needs to be restarted
	 * 
	 * @return the event
	 */
	public IEvent getRestartRoundEvent() {
		return restartRoundEvent;
	}

	private void redeal() {
		turnControl = null;
		for (Connection c : new ArrayList<Connection>(connections)) {
			c.remove();
		}
		restartRoundEvent.emit();
	}
}