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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
|
package jrummikub.ai;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import jrummikub.model.GameSettings;
import jrummikub.model.Stone;
import jrummikub.model.StoneColor;
import jrummikub.model.StoneSet;
import jrummikub.util.Pair;
/**
* Logic behind the ai turns
*/
public class TurnLogic {
private GameSettings settings;
private int stoneCount;
private List<Stone> inputStones;
private StoneColor maxColor;
private StoneColor minColor;
private ArrayList<StoneColor> stoneColors;
private volatile State bestState;
private ArrayList<State> stack = new ArrayList<State>();
private State top;
private volatile boolean abort = false;
private volatile boolean autoAbort = false;
private int neededPoints = 0;
private double neededScore = 0;
@SuppressWarnings("serial")
private static class Contradiction extends Throwable {
}
private class State {
ArrayList<StoneState> stones = new ArrayList<StoneState>();
HashSet<Integer> changedStones = new HashSet<Integer>();
ArrayList<Integer> jokerIDs = new ArrayList<Integer>();
public State() {
}
public State(State state) {
for (StoneState stone : state.stones) {
stones.add(new StoneState(stone));
}
jokerIDs = state.jokerIDs;
}
public void add(StoneState stone) {
stones.add(stone);
changedStones.add(stones.size() - 1);
if (stone.joker) {
jokerIDs.add(stone.id);
}
}
public void updateStones() throws Contradiction {
checkJokers();
for (int i : changedStones) {
stones.get(i).checkState();
}
checkScoreAndPoints();
while (!changedStones.isEmpty()) {
updateStonesStep();
checkScoreAndPoints();
}
}
public void updateStonesStep() throws Contradiction {
HashSet<Integer> newChangedStones = new HashSet<Integer>();
for (int i = 0; i < stoneCount; i++) {
StoneState stone = stones.get(i);
if (stone.isInterested(changedStones)) {
if (stone.update(changedStones)) {
newChangedStones.add(i);
}
}
}
changedStones = newChangedStones;
}
public boolean isSolved() {
for (StoneState stone : stones) {
if (!stone.isSolved()) {
return false;
}
}
return true;
}
public void checkJokers() throws Contradiction {
for (int i = 0; i < jokerIDs.size(); i++) {
StoneState left = stones.get(jokerIDs.get(i));
HashSet<Integer> leftLeftGroup = new HashSet<Integer>(left.leftGroup);
HashSet<Integer> leftLeftRun = new HashSet<Integer>(left.leftRun);
leftLeftGroup.remove(null);
leftLeftRun.remove(null);
int runID, groupID;
if (leftLeftGroup.isEmpty()) {
groupID = -1;
} else {
groupID = Collections.min(leftLeftGroup);
}
if (leftLeftRun.isEmpty()) {
runID = -1;
} else {
runID = Collections.min(leftLeftRun);
}
for (int j = i + 1; j < jokerIDs.size(); j++) {
StoneState right = stones.get(jokerIDs.get(j));
if (right.leftGroup.remove(groupID)) {
changedStones.add(jokerIDs.get(j));
}
if (right.leftRun.remove(runID)) {
changedStones.add(jokerIDs.get(j));
}
}
}
}
public void checkScoreAndPoints() throws Contradiction {
if (getPoints() < neededPoints) {
throw new Contradiction();
}
if (getScore() <= neededScore) {
throw new Contradiction();
}
}
public int getPoints() {
int sum = 0;
for (StoneState stone : stones) {
if (stone.onTable != Boolean.FALSE) {
sum += stone.getPoints();
}
}
return sum;
}
public double getScore() {
double sum = 0;
for (StoneState stone : stones) {
if (stone.onTable != Boolean.FALSE) {
sum += stone.getScore();
}
}
return sum;
}
}
private class StoneState {
int id;
boolean joker;
Integer value;
StoneColor color;
Boolean onTable;
boolean fromTable;
HashSet<Integer> leftRun;
HashSet<Integer> rightRun;
HashSet<Integer> leftGroup;
HashSet<Integer> rightGroup;
public StoneState(int id, Stone stone, boolean table) {
this.id = id;
joker = stone.isJoker();
if (!joker) {
this.value = stone.getValue();
this.color = stone.getColor();
}
onTable = table ? true : null;
fromTable = table;
leftRun = makeFullSet();
rightRun = makeFullSet();
leftGroup = makeFullSet();
rightGroup = makeFullSet();
}
public StoneState(StoneState stone) {
this.id = stone.id;
this.joker = stone.joker;
this.value = stone.value;
this.color = stone.color;
this.onTable = stone.onTable;
this.fromTable = stone.fromTable;
this.leftRun = new HashSet<Integer>(stone.leftRun);
this.rightRun = new HashSet<Integer>(stone.rightRun);
this.leftGroup = new HashSet<Integer>(stone.leftGroup);
this.rightGroup = new HashSet<Integer>(stone.rightGroup);
}
private HashSet<Integer> makeFullSet() {
HashSet<Integer> set = new HashSet<Integer>();
for (int i = 0; i < stoneCount; i++) {
if (i != id) {
set.add(i);
}
}
set.add(null);
return set;
}
public boolean isInterested(HashSet<Integer> changes) {
return !(Collections.disjoint(changes, leftRun)
&& Collections.disjoint(changes, rightRun)
&& Collections.disjoint(changes, leftGroup) && Collections.disjoint(
changes, rightGroup));
}
public <T extends Comparable<T>> boolean lessThan(T a, T b) {
return a == null || b == null || a.compareTo(b) < 0;
}
public <T> boolean same(T a, T b) {
return a == null || b == null || a.equals(b);
}
public boolean step(Integer a, Integer b) {
return a == null || b == null || (int) a == b - 1;
}
public boolean cycleStep(Integer a, Integer b) {
return a == null || b == null || (int) a == b - 1
|| a == settings.getHighestValue() && b == 1;
}
public boolean groupNeighbor(StoneState other) {
if (isNullSet(leftGroup) && isNullSet(other.rightGroup)) {
return false;
}
if (other.color == minColor || color == maxColor) {
return false;
}
return lessThan(color, other.color) && same(value, other.value);
}
public boolean runNeighbor(StoneState other) {
if (isNullSet(leftRun) && isNullSet(other.rightRun)) {
return false;
}
if (!same(color, other.color)) {
return false;
}
if (settings.isNoLimits()) {
return cycleStep(value, other.value);
} else {
if (((Integer) 1).equals(other.value)
|| ((Integer) settings.getHighestValue()).equals(value)) {
return false;
}
return step(value, other.value);
}
}
public boolean update(HashSet<Integer> changes) throws Contradiction {
boolean changed = false;
changed |= updateRightRuns(changes);
changed |= updateLeftRuns(changes);
changed |= updateRightGroups(changes);
changed |= updateLeftGroups(changes);
changed |= checkState();
return changed;
}
public boolean updateRightRuns(HashSet<Integer> changes)
throws Contradiction {
boolean changed = false;
HashSet<Integer> relevantChanges = new HashSet<Integer>(leftRun);
relevantChanges.retainAll(changes);
for (int i : relevantChanges) {
StoneState other = top.stones.get(i);
if (!other.runNeighbor(this) || !other.rightRun.contains(id)) {
leftRun.remove(i);
changed = true;
} else if (other.rightRun.size() == 1 && other.onTable == Boolean.TRUE) {
changed |= leftRun.retainAll(Arrays.asList(i));
changed |= onTable != Boolean.TRUE;
onTable = true;
break;
}
}
return changed;
}
public boolean updateLeftRuns(HashSet<Integer> changes)
throws Contradiction {
boolean changed = false;
HashSet<Integer> relevantChanges = new HashSet<Integer>(rightRun);
relevantChanges.retainAll(changes);
for (int i : relevantChanges) {
StoneState other = top.stones.get(i);
if (!this.runNeighbor(other) || !other.leftRun.contains(id)) {
rightRun.remove(i);
changed = true;
} else if (other.leftRun.size() == 1 && other.onTable == Boolean.TRUE) {
changed |= rightRun.retainAll(Arrays.asList(i));
changed |= onTable != Boolean.TRUE;
onTable = true;
break;
}
}
return changed;
}
public boolean updateRightGroups(HashSet<Integer> changes)
throws Contradiction {
boolean changed = false;
HashSet<Integer> relevantChanges = new HashSet<Integer>(leftGroup);
relevantChanges.retainAll(changes);
for (int i : relevantChanges) {
StoneState other = top.stones.get(i);
if (!other.groupNeighbor(this) || !other.rightGroup.contains(id)) {
leftGroup.remove(i);
changed = true;
} else if (other.rightGroup.size() == 1
&& other.onTable == Boolean.TRUE) {
changed |= leftGroup.retainAll(Arrays.asList(i));
changed |= onTable != Boolean.TRUE;
onTable = true;
break;
}
}
return changed;
}
public boolean updateLeftGroups(HashSet<Integer> changes)
throws Contradiction {
boolean changed = false;
HashSet<Integer> relevantChanges = new HashSet<Integer>(leftGroup);
relevantChanges = new HashSet<Integer>(rightGroup);
relevantChanges.retainAll(changes);
for (int i : relevantChanges) {
StoneState other = top.stones.get(i);
if (!this.groupNeighbor(other) || !other.leftGroup.contains(id)) {
rightGroup.remove(i);
changed = true;
} else if (other.leftGroup.size() == 1 && other.onTable == Boolean.TRUE) {
changed |= rightGroup.retainAll(Arrays.asList(i));
changed |= onTable != Boolean.TRUE;
onTable = true;
break;
}
}
return changed;
}
public boolean checkState() throws Contradiction {
boolean changed = false;
if (onTable == Boolean.FALSE) {
if (leftRun.size() + rightRun.size() + leftGroup.size()
+ rightGroup.size() != 0) {
leftRun.clear();
rightRun.clear();
leftGroup.clear();
rightGroup.clear();
return true;
}
return false;
}
changed |= checkSetTypeKnown();
changed |= checkLonelyStone();
changed |= checkNeighborStoneNeeded();
changed |= checkStoneCanBeOnTable();
checkGroupRunExclusive();
changed |= checkJoker();
return changed;
}
private boolean checkSetTypeKnown() {
boolean changed = false;
if (!(leftGroup.contains(null) || rightGroup.contains(null))) {
changed |= leftRun.retainAll(Arrays.asList((Integer) null))
| rightRun.retainAll(Arrays.asList((Integer) null));
}
if (!(leftRun.contains(null) || rightRun.contains(null))) {
changed |= leftGroup.retainAll(Arrays.asList((Integer) null))
| rightGroup.retainAll(Arrays.asList((Integer) null));
}
return changed;
}
private boolean checkLonelyStone() {
boolean changed = false;
@SuppressWarnings("unchecked")
List<HashSet<Integer>> sets = Arrays.<HashSet<Integer>> asList(leftGroup,
rightGroup, leftRun, rightRun, leftGroup, rightGroup, leftRun);
for (int i = 0; i < 4; i++) {
if (isNullSet(sets.get(i)) && isNullSet(sets.get(i + 1))
&& isNullSet(sets.get(i + 2))) {
changed |= sets.get(i + 3).remove(null);
}
}
return changed;
}
private boolean checkNeighborStoneNeeded() {
boolean changed = false;
if (isSingleNonNullSet(leftRun)
&& isNullSet(top.stones.get(leftRun.iterator().next()).leftRun)) {
changed |= rightRun.remove(null);
}
if (isSingleNonNullSet(rightRun)
&& isNullSet(top.stones.get(rightRun.iterator().next()).rightRun)) {
changed |= leftRun.remove(null);
}
if (isSingleNonNullSet(leftGroup)
&& isNullSet(top.stones.get(leftGroup.iterator().next()).leftGroup)) {
changed |= rightGroup.remove(null);
}
if (isSingleNonNullSet(rightGroup)
&& isNullSet(top.stones.get(rightGroup.iterator().next()).rightGroup)) {
changed |= leftGroup.remove(null);
}
return changed;
}
private boolean checkStoneCanBeOnTable() throws Contradiction {
boolean changed = false;
if (leftGroup.isEmpty() || rightGroup.isEmpty() || leftRun.isEmpty()
|| rightRun.isEmpty()) {
if (onTable == Boolean.TRUE) {
throw new Contradiction();
}
if (onTable == null) {
onTable = false;
leftRun.clear();
rightRun.clear();
leftGroup.clear();
rightGroup.clear();
changed = true;
}
}
return changed;
}
private void checkGroupRunExclusive() throws Contradiction {
if ((isSingleNonNullSet(leftGroup) || isSingleNonNullSet(rightGroup))
&& (isSingleNonNullSet(leftRun) || isSingleNonNullSet(rightRun))) {
throw new Contradiction();
}
}
private boolean checkJoker() {
return false;
}
public boolean isSolved() {
if (onTable == Boolean.FALSE) {
return true;
}
if (onTable == null || color == null || value == null) {
return false;
}
if (leftRun.size() > 1 || rightRun.size() > 1 || leftGroup.size() > 1
|| rightGroup.size() > 1) {
return false;
}
return true;
}
public double getScore() {
if (fromTable) {
return 0;
}
return 1;
}
public double getPoints() {
if (fromTable) {
return 0;
}
if (value == null)
return (double) settings.getHighestValue();
else
return (double) value;
}
}
private static boolean isNullSet(HashSet<Integer> i) {
return i.size() == 1 && i.contains(null);
}
private static boolean isSingleNonNullSet(HashSet<Integer> i) {
return i.size() == 1 && !i.contains(null);
}
/**
* Creates new turn logic
*
* @param settings
* the game settings
* @param tableStones
* all stones on the table
* @param handStones
* all stones on the hand
*/
public TurnLogic(GameSettings settings, Collection<Stone> tableStones,
Collection<Stone> handStones) {
this.settings = settings;
stoneCount = tableStones.size() + handStones.size();
maxColor = Collections.max(settings.getStoneColors());
minColor = Collections.min(settings.getStoneColors());
stoneColors = new ArrayList<StoneColor>(settings.getStoneColors());
Collections.sort(stoneColors);
top = new State();
stack.add(top);
ArrayList<Pair<Stone, Boolean>> sortedStones = new ArrayList<Pair<Stone, Boolean>>();
inputStones = new ArrayList<Stone>();
for (Stone stone : tableStones) {
sortedStones.add(new Pair<Stone, Boolean>(stone, true));
}
for (Stone stone : handStones) {
sortedStones.add(new Pair<Stone, Boolean>(stone, false));
}
Collections.sort(sortedStones, new Comparator<Pair<Stone, Boolean>>() {
@Override
public int compare(Pair<Stone, Boolean> o1, Pair<Stone, Boolean> o2) {
int cmp;
cmp = ((Boolean) o1.getFirst().isJoker()).compareTo(o2.getFirst()
.isJoker());
if (cmp != 0) {
return -cmp;
}
cmp = (o1.getFirst().getColor()).compareTo(o2.getFirst().getColor());
if (cmp != 0) {
return cmp;
}
cmp = ((Integer) o1.getFirst().getValue()).compareTo(o2.getFirst()
.getValue());
return cmp;
}
});
int i = 0;
for (Pair<Stone, Boolean> pair : sortedStones) {
top.add(new StoneState(i++, pair.getFirst(), pair.getSecond()));
inputStones.add(pair.getFirst());
}
}
/**
* Include initial meld threshold into turn logic
*/
public void needIntialMeldThreshold() {
neededPoints = settings.getInitialMeldThreshold();
}
private void pop() {
stack.remove(stack.size() - 1);
if (!stack.isEmpty()) {
top = stack.get(stack.size() - 1);
}
}
private void replace() {
stack.remove(stack.size() - 1);
}
private void pushes(State... states) {
for (State state : states) {
stack.add(state);
}
}
private void done() {
top = stack.get(stack.size() - 1);
}
/**
* Aborts currently running solve call
*/
public void abort() {
abort = true;
}
/**
* Get the found stones and create output sets
*
* @return output sets to put on table
*/
public List<StoneSet> getResult() {
State result = bestState;
if (result == null) {
return null;
}
ArrayList<StoneSet> outputSets = new ArrayList<StoneSet>();
for (int i = 0; i < stoneCount; i++) {
StoneState stone = result.stones.get(i);
if (isNullSet(stone.leftRun) && isNullSet(stone.leftGroup)) {
ArrayList<Stone> setStones = new ArrayList<Stone>();
while (true) {
setStones.add(inputStones.get(stone.id));
if (isNullSet(stone.rightRun) && isNullSet(stone.rightGroup)) {
break;
}
Integer rightRunID = stone.rightRun.iterator().next();
Integer rightGroupID = stone.rightGroup.iterator().next();
stone = result.stones.get(rightRunID == null ? rightGroupID
: rightRunID);
}
outputSets.add(new StoneSet(setStones));
}
}
return outputSets;
}
/**
* Solves next state on stack while not aborted
*
* @return solved
*/
public boolean solve() {
if (top.isSolved()) {
pop();
}
while (stack.size() != 0) {
if (abort) {
return false;
}
try {
top.updateStones();
if (top.isSolved()) {
bestState = top;
return true;
}
branch();
done();
} catch (Contradiction c) {
pop();
}
}
return false;
}
/**
* Optimizes the solution found as long as stopped from control
*
* @return score of found solution
*/
public double optimize() {
while (!autoAbort && solve()) {
neededScore = top.getScore();
}
return neededScore;
}
private void branch() throws Contradiction {
for (int i = 0; i < stoneCount; i++) {
StoneState stone = top.stones.get(i);
if (stone.onTable == null) {
replace();
branchOnHand(i);
return;
}
if (stone.leftRun.size() > 1) {
replace();
branchLeftRun(i, stone);
return;
}
if (stone.rightRun.size() > 1) {
replace();
branchRightRun(i, stone);
return;
}
if (stone.leftGroup.size() > 1) {
replace();
branchLeftGroup(i, stone);
return;
}
if (stone.rightGroup.size() > 1) {
replace();
branchRightGroup(i, stone);
return;
}
if (stone.color == null) {
replace();
branchColor(i);
return;
}
if (stone.value == null) {
replace();
branchValue(i);
return;
}
}
// This should never happen
throw new Error("Internal AI error");
}
private void branchValue(int i) {
for (int value = 1; value <= settings.getHighestValue(); value++) {
State newState = new State(top);
newState.stones.get(i).value = value;
newState.changedStones.add(i);
pushes(newState);
}
}
private void branchColor(int i) {
for (StoneColor color : stoneColors) {
State newState = new State(top);
newState.stones.get(i).color = color;
newState.changedStones.add(i);
pushes(newState);
}
}
private void branchRightGroup(int i, StoneState stone) {
for (Integer id : stone.rightGroup) {
State newState = new State(top);
newState.stones.get(i).rightGroup.clear();
newState.stones.get(i).rightGroup.add(id);
newState.changedStones.add(i);
pushes(newState);
}
}
private void branchLeftGroup(int i, StoneState stone) {
for (Integer id : stone.leftGroup) {
State newState = new State(top);
newState.stones.get(i).leftGroup.clear();
newState.stones.get(i).leftGroup.add(id);
newState.changedStones.add(i);
pushes(newState);
}
}
private void branchRightRun(int i, StoneState stone) {
for (Integer id : stone.rightRun) {
State newState = new State(top);
newState.stones.get(i).rightRun.clear();
newState.stones.get(i).rightRun.add(id);
newState.changedStones.add(i);
pushes(newState);
}
}
private void branchLeftRun(int i, StoneState stone) {
for (Integer id : stone.leftRun) {
State newState = new State(top);
newState.stones.get(i).leftRun.clear();
newState.stones.get(i).leftRun.add(id);
newState.changedStones.add(i);
pushes(newState);
}
}
private void branchOnHand(int i) {
State newState = new State(top);
newState.stones.get(i).onTable = false;
newState.changedStones.add(i);
State altState = new State(top);
altState.stones.get(i).onTable = true;
altState.changedStones.add(i);
pushes(altState, newState);
}
/**
* Abort as soon as a solution is found
*/
public void autoAbort() {
if (bestState != null) {
abort = true;
}
autoAbort = true;
}
}
|