summaryrefslogtreecommitdiffstats
path: root/src/jrummikub/control/turn/AIControl.java
blob: 9ce162f1c4bb757ca8426dc9c26c2d490e52d5e9 (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
package jrummikub.control.turn;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.SwingUtilities;
import javax.swing.Timer;

import jrummikub.ai.TurnLogic;
import jrummikub.model.Position;
import jrummikub.model.Stone;
import jrummikub.model.StoneSet;
import jrummikub.util.Pair;

/**
 * Base class for AI players
 * 
 */
public class AIControl extends AbstractTurnControl {
	private TurnLogic logic;
	/**
	 * Does the AI control currently use an internal timer
	 */
	public static boolean useBackgroundThread = true;
	long startTime;

	private boolean isPaused = false;
	private boolean turnDone = false;
	private boolean readyToEmit = false;
	private boolean aborted = false;

	@Override
	protected void doStartTurn() {
		timer.startTimer();
		startTime = System.currentTimeMillis();
		compute();
	}

	@Override
	protected void timeOut() {
		executeTurn();
	}

	@Override
	protected void pauseTurn() {
		super.pauseTurn();
		isPaused = true;
	}

	@Override
	protected void resumeTurn() {
		super.resumeTurn();
		isPaused = false;
		if (readyToEmit) {
			emitEndOfTurn();
		}
	}

	@Override
	protected void cleanUp() {
		if (logic != null)
			logic.abort();
		turnDone = true;
		super.cleanUp();
	}

	@Override
	public void abortTurn() {
		aborted = true;
		super.abortTurn();
	}

	private void compute() {
		switch (turnInfo.getTurnMode()) {
		case MAY_REDEAL:
			endTurn();
			break;
		case INSPECT_ONLY:
			endTurn();
			break;
		case NORMAL_TURN:
			turn();
			break;
		}
	}

	private void turn() {
		List<Stone> tableStones = new ArrayList<Stone>();
		List<Stone> handStones = new ArrayList<Stone>();

		addHandStones(handStones);

		addTableStones(tableStones);

		logic = new TurnLogic(settings, tableStones, handStones);

		if (!turnInfo.getLaidOut()) {
			logic.needIntialMeldThreshold();
		}
		if (useBackgroundThread) {

			startTimers();

			Thread computeThread = new Thread(new Runnable() {
				@Override
				public void run() {
					logic.optimize();
					SwingUtilities.invokeLater(new Runnable() {
						@Override
						public void run() {
							executeTurn();
						}
					});
				}
			});
			computeThread.start();
		} else {
			logic.optimize();
			executeTurn();
		}

	}

	private void startTimers() {
		Timer timer = new Timer(10000, new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				logic.autoAbort();
			}
		});
		timer.setRepeats(false);
		timer.start();

		timer = new Timer((int) (turnInfo.getRoundState().getGameSettings()
				.getTotalTime() * 1000 * (0.5 + 0.25 * Math.random())),
				new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						executeTurn();
					}
				});
		timer.setRepeats(false);
		timer.start();
	}

	private void addHandStones(List<Stone> handStones) {
		for (Pair<Stone, Position> entry : turnInfo.getHand()) {
			handStones.add(entry.getFirst());
		}
	}

	private void addTableStones(List<Stone> tableStones) {
		if (turnInfo.getLaidOut()) {
			for (Pair<StoneSet, Position> entry : turnInfo.getTable()) {
				for (Stone stone : entry.getFirst()) {
					tableStones.add(stone);
				}
			}
		}
	}

	private void executeTurn() {
		if (turnDone) {
			return;
		}

		List<StoneSet> result = logic.getResult();

		if (result != null) {

			if (turnInfo.getLaidOut()) {
				doNotMoveExistingSets(result);
			}

			for (StoneSet set : result) {
				turnInfo.getTable().drop(
						set,
						new Position(10 * (Math.random() * 2 - 1),
								5 * (Math.random() * 2 - 1)));
				for (Stone stone : set) {
					turnInfo.getHand().pickUp(stone);
				}
			}
		}

		endTurn();
	}

	private void doNotMoveExistingSets(List<StoneSet> result) {

		outerLoop: for (Iterator<Pair<StoneSet, Position>> it = turnInfo.getTable()
				.iterator(); it.hasNext();) {
			Pair<StoneSet, Position> pair = it.next();
			setSearch: for (Iterator<StoneSet> it2 = result.iterator(); it2.hasNext();) {
				StoneSet set = it2.next();
				if (set.getSize() != pair.getFirst().getSize()) {
					continue;
				}
				for (int i = 0; i < set.getSize(); i++) {
					if (set.get(i) != pair.getFirst().get(i)) {
						continue setSearch;
					}
				}
				it2.remove();
				continue outerLoop;
			}
			it.remove();
		}
	}

	private void endTurn() {
		turnDone = true;

		long turnLength = System.currentTimeMillis() - startTime;

		if (useBackgroundThread) {
			Timer timer = new Timer(Math.max(0,
					(int) (1000 + Math.random() * 2000 - turnLength)),
					new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent event) {
							emitEndOfTurn();
						}
					});
			timer.setRepeats(false);
			timer.start();
		} else {
			emitEndOfTurn();
		}

	}

	private void emitEndOfTurn() {
		readyToEmit = true;
		if (isPaused || aborted) {
			return;
		}
		cleanUp();
		endOfTurnEvent.emit(turnInfo.getRoundState(), checkTurn());
	}

	/**
	 * Get the factory for the base AI control
	 * 
	 * @return the factory
	 */
	static public TurnControlFactory getFactory() {
		return new TurnControlFactory() {
			@Override
			public ITurnControl create() {
				return new AIControl();
			}
		};
	}

}