...
Her er fullstendig kode for Memory-klassen og en oppdatert MemoryProgram-klasse:
Code Block | ||||
---|---|---|---|---|
| ||||
public class Memory<T> {
private List<T> possibleItems;
private List<T> expectedItems;
private int acceptedCount;
public Memory(Collection<T> possibleItems) {
this.possibleItems = new ArrayList<>(possibleItems);
expectedItems = new ArrayList<T>();
acceptedCount = 0;
}
public Memory(T... possibleItems) {
this(Arrays.asList(possibleItems));
}
public T nextItem() {
int index = (int) (Math.random() * possibleItems.size()); // generate random index
T nextItem = possibleItems.get(index); // look up value
expectedItems.add(nextItem); // add to sequence
acceptedCount = 0; // reset accepted counter
return nextItem; // return new item
}
public Collection<T> nextItems(int count) {
Collection<T> items = new ArrayList<T>();
while (count > 0) {
items.add(nextItem());
}
return items;
}
public int getItemCount() {
return expectedItems.size();
}
public int getItemsLeft() {
return expectedItems.size() - acceptedCount;
}
public Boolean acceptItem(T item) {
// is acceptItem called after sequence is completed
if (acceptedCount >= expectedItems.size()) {
return false;
}
// is the number input by the user correct
if (! expectedItems.get(acceptedCount).equals(item)) {
// if they are not the same, we indicate this by returning false object
return Boolean.FALSE;
}
acceptedCount++; // correct number, so increment counter
// is this the last number
if (acceptedCount == expectedItems.size()) {
// return true object
return Boolean.TRUE;
}
// otherwise return null, indicating correct value, but not finished
return null;
}
}
public class MemoryProgram {
private void run() {
Scanner scanner = new Scanner(System.in);
do {
Memory<Integer> memory = new Memory<Integer>(1, 2, 3, 4, 5, 6, 7, 8, 9);
while (true) {
int nextItem = memory.nextItem();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
System.out.println("Next item is " + nextItem);
System.out.println("Please input " + memory.getItemCount() + " items");
Boolean result = null;
do {
int nextInt = scanner.nextInt();
result = memory.acceptItem(nextInt);
} while (result == null);
if (result == Boolean.FALSE) {
System.out.println("Wrong, game over");
break;
}
}
System.out.println("Another game (true/false)?");
} while (scanner.nextBoolean());
scanner.close();
}
public static void main(String[] args) {
new MemoryProgram().run();
}
} |
Her har vi lagt til to ekstra metoder i Memory, for å gjøre klassen litt mer fleksibel og enklere å bruke:
...