/
Hand.java
112 lines (93 loc) · 2.95 KB
/
Hand.java
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
package com.skiwi.tcg.model.objects;
import com.skiwi.eventbus.EventBus;
import com.skiwi.eventbus.EventBusFactory;
import com.skiwi.eventbus.EventSender;
import com.skiwi.tcg.events.HandAddedEvent;
import com.skiwi.tcg.events.HandPlayedEvent;
import com.skiwi.tcg.events.HandSwappedEvent;
import com.skiwi.tcg.model.cards.Card;
import com.skiwi.tcg.utils.Arguments;
import com.skiwi.tcg.utils.States;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Spliterator;
import java.util.function.Consumer;
/**
*
* @author Frank van Heeswijk
*/
public class Hand extends AbstractCollection<Card> implements Collection<Card>, EventSender {
private EventBus eventBus = EventBusFactory.getVoidEventBus();
private final int capacity;
private final List<Card> list;
public Hand(final int capacity) {
this.capacity = Arguments.requirePositive(capacity, "capacity");
this.list = new ArrayList<>(capacity);
}
@Override
public void setEventBus(final EventBus eventBus) {
this.eventBus = (eventBus == null) ? EventBusFactory.getVoidEventBus() : eventBus;
}
public boolean isFull() {
return (list.size() == capacity);
}
@Override
public boolean add(final Card card) {
Objects.requireNonNull(card);
States.requireFalse(isFull(), "hand is full");
list.add(card);
eventBus.executeEvent(new HandAddedEvent(this, card));
return true;
}
public Card get(final int index) {
checkIndex(index);
return list.get(index);
}
public Card play(final int index) {
checkIndex(index);
Card result = list.remove(index);
eventBus.executeEvent(new HandPlayedEvent(this, index, result));
return result;
}
public void swap(final int indexOne, final int indexTwo) {
checkIndex(indexOne);
checkIndex(indexTwo);
Collections.swap(list, indexOne, indexTwo);
eventBus.executeEvent(new HandSwappedEvent(this, indexOne, indexTwo));
}
@Override
public String toString() {
return Hand.class.getSimpleName() + "(" + capacity + ", " + list + ")";
}
@Override
public Iterator<Card> iterator() {
return list.iterator();
}
@Override
public Spliterator<Card> spliterator() {
return list.spliterator();
}
@Override
public int size() {
return list.size();
}
@Override
public void forEach(final Consumer<? super Card> action) {
Objects.requireNonNull(action);
list.forEach(action);
}
public int getCapacity() {
return capacity;
}
public int getRemainingCapacity() {
return (capacity - size());
}
private void checkIndex(final int index) {
Arguments.requireIndexInRange(index, 0, size());
}
}