@matfah/

Player FR 2007

Java

No description

fork
loading
Files
  • Main.java
  • GameDriver.java
  • GameState.java
  • Player.java
  • RandomPlayer.java
Main.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
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
import java.util.*;
import java.io.*;
import java.lang.reflect.*;

public class Main {
  
  public static void main(String[] args) {
    
    testRandomPlayer();
    
    for(int i = 0; i < 10; i++)
      testPlay();
    
    System.out.println("Passed all tests!");
  }
  
  public static void testRandomPlayer() {
    
    checkAllInstanceVariablesArePrivate(RandomPlayer.class);
    
    Constructor<RandomPlayer> constructor = null;
    try {
      constructor = RandomPlayer.class.getDeclaredConstructor(String.class);
    }
    catch(Exception e) {
      System.out.println("Your RandomPlayer class does not have a 1 parameter String constructor!");
      System.exit(0);
    }
    
    RandomPlayer player = null;
    try {
      player = constructor.newInstance("Bob");
    }
    catch(Exception e) {
      System.out.println("Error trying to construct a RandomPlayer object!");
      System.exit(0);
    }
    
    try {
      Field name = Player.class.getDeclaredField("name");
      name.setAccessible(true);
      String result = (String)name.get(player);
      if(name == null || !result.equals("Bob")) {
        System.out.println("RandomPlayer Constructor does not properly call superclass constructor!");
        System.exit(0);
      }
    }
    catch(Exception e) {
      System.out.println("Did you change the Player class...?!?!");
      System.exit(0);
    }
    
    Method getNextMove = null;
    Method getNameChild = null;
    try {
     getNextMove = RandomPlayer.class.getDeclaredMethod("getNextMove", GameState.class);
    }
    catch(Exception e) {
      System.out.println("RandomPlayer class does not override getNextMove");
      System.exit(0);
    }
    
    try {
     getNameChild = RandomPlayer.class.getDeclaredMethod("getName");
     if(getNameChild != null) {
       System.out.println("You shouldn't be overriding getName() in RandomPlayer...");
       System.exit(0);
     }
    }
    catch(Exception e) {
      //this is okay!  we don't want RandomPlayer to override getName
    }
    
    
    if(!Player.class.isAssignableFrom(RandomPlayer.class)) {
      System.out.println("Your RandomPlayer class is not a subclass of Player!");
      System.exit(0);
    }
    
    GameState emptyState = new GameState() {
      public boolean isGameOver() { return false; }
      public Player getWinner() { return null; }
      public Player getCurrentPlayer() { return null; }
      public ArrayList<String> getCurrentMoves() { 
        ArrayList<String>list = new ArrayList<String>();
        return list;
      }
      public void makeMove(String move) {}
      public String toString() { return ""; }
    };
    
    GameState state = new GameState() {
      public boolean isGameOver() { return false; }
      public Player getWinner() { return null; }
      public Player getCurrentPlayer() { return null; }
      public ArrayList<String> getCurrentMoves() { 
        ArrayList<String>list = new ArrayList<String>();
        list.add("A"); list.add("B"); list.add("C"); list.add("D");
        return list;
      }
      public void makeMove(String move) {}
      public String toString() { return ""; }
    };
    
    try {
      String result = (String)getNextMove.invoke(player, emptyState);
      if(result == null || !result.equals("no move")) {
        System.out.println("Result of calling getNextMove() from a RandomPlayer object is wrong!");
        System.exit(0);
      }
    }
    catch(Exception e) {
      System.out.println("Error calling getNextMove() from a RandomPlayer object!");
      System.exit(0);
    }
    
    try {
      
      //I use run testing to see if there is any randomness going on
      //http://www.itl.nist.gov/div898/handbook/eda/section3/eda35d.htm
      
      String allData = "";
      
      for(int i = 0; i < 10000; i++) {
        String result = (String)getNextMove.invoke(player, state);
        if(result == null || (!result.equals("A") && !result.equals("B") && !result.equals("C") && !result.equals("D"))) {
          System.out.println("Result of calling getNextMove() from a RandomPlayer object is wrong!");
          System.exit(0);
        }
        
        allData += result;
      }
      
      //now we want to see if the data is 
      for(int length = 1; length <= 5; length++) {

        ArrayList<String> list = new ArrayList<String>();
        stringsOfLength(length, new String[]{"A", "B", "C", "D"}, "", list);
        
        ArrayList<Integer> counts = new ArrayList<Integer>();
        for(String s: list)
          counts.add(occurences(allData, s));
          
        int total = 0;
        for(int i = 0; i < counts.size(); i++) {
          total += counts.get(i);
        }
        
        double average = total / (double)counts.size();
        for(int count: counts) {
          if(Math.abs(average - count) > 0.4 *average) {
            System.out.println("I could be wrong... but your RandomPlayer doesn't seem very random...");
            System.exit(0);
          }
        }
      }
    }
    catch(Exception e) {
      System.out.println("Error calling getNextMove() from a RandomPlayer object!");
      System.exit(0);
    }

  }

  public static void stringsOfLength(int len, String[] options, String soFar, ArrayList<String> place) {
    
    if(len == 0) {
      place.add(soFar);
      return;
    }
    
    for(int i = 0; i < options.length; i++) {
      if(options[i] != null) {
        String temp = options[i];
        options[i] = null;
        stringsOfLength(len-1, options, temp + soFar, place);
        options[i] = temp;
      }
    }
  }
  
  public static int occurences(String text, String substring) {
    
    int count = 0;
    int pos = 0;
    
    while((pos = text.indexOf(substring, pos)) != -1) {
      count++;
      pos += substring.length();
    }
    
    return count;
  }
  
  public static void checkAllInstanceVariablesArePrivate(Class c) {
    Field[] fields = c.getDeclaredFields();
    for(Field f: fields) {
      if((f.getModifiers() & Modifier.PRIVATE) != Modifier.PRIVATE)
      {
        System.out.println("Not all fields of " + c.getName() + " are private!");
        System.exit(0);
      }
    }
  }
  
  //https://stackoverflow.com/questions/8708342/redirect-console-output-to-string-in-java
  public static void testPlay() {
    
    int seed = (int)(Math.random()*100);
    Random random = new Random(seed);
    Random random2 = new Random(seed);
    
    String[] names = {"Alice", "Bob", "Chris", "Daniel", "Erin", "Fran", "Gina", "Helen"};
    
    String playerA = names[(int)(Math.random()*names.length)];
    String playerB = names[(int)(Math.random()*names.length)];
    
    Guts g1 = new Guts(random, new FahrenbacherPlayer(playerA), new FahrenbacherPlayer(playerB));
    Guts g2 = new Guts(random2, new FahrenbacherPlayer(playerA), new FahrenbacherPlayer(playerB));
    GameDriver driver = new GameDriver(g1);
    String output = getOutput(new Runnable() {
      public void run() {
        driver.play();
      }
    });
  
    ArrayList<String> answer = new ArrayList<String>();
    
    answer.add(g2.toString());
    
    while(!g2.isGameOver()) {
      Player current = g2.getCurrentPlayer();
      String name = current.getName();
      String move = current.getNextMove(g2);
      
      answer.add(name);
      answer.add(move);
      
      g2.makeMove(move);
    }
    
    Player winner = g2.getWinner();
    if(winner == null) {
      answer.add("Game ends in a draw");
    }
    else {
      answer.add(winner.getName());
      answer.add("wins");
    }
    
    int pos = 0;
    for(String s : answer) {
      int newPos = output.indexOf(s, pos);
      
      if(newPos == -1) {
        System.out.println("Expected part of output not found from play() method");
        System.exit(0);
      }
      
      pos = newPos + s.length();
    }
  }
  
  public static String getOutput(Runnable r) {
    // Create a stream to hold the output
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);
    
    // IMPORTANT: Save the old System.out!
    PrintStream old = System.out;
    // Tell Java to use your special stream
    System.setOut(ps);
    
    // Print some output: goes to your special stream
    r.run();
    
    // Put things back
    System.out.flush();
    System.setOut(old);
    
    // Show what happened
    return baos.toString();
  }
  
}

//Modified version of the game of Guts (Piggy Sixes)
class Guts implements GameState {
  
  private int[] scores = new int[2];
  private int[] unbanked = new int[2];
  private int turn;
  private Player[] players;
  private Random random;
  
  public Guts(Random r, Player... p) {
    players = p;
    random = r;
    turn = random.nextInt(2);
  }
  
  public boolean isGameOver() {
    
    //we're going to call this a tie
    if(scores[0] > 0 && scores[1] > 0 && scores[0] == scores[1])
      return true;
    
    return scores[0] >= 100 || scores[1] >= 100;  
  }
  
  public Player getWinner() {
    if(scores[0] > 0 && scores[1] > 0 && scores[0] == scores[1]) return null;
    else if(scores[0] >= 100) return players[0];
    else if(scores[1] >= 100) return players[1];
    else return null;
  }
  
  public Player getCurrentPlayer() {
    return players[turn];
  }
  
  public ArrayList<String> getCurrentMoves() {
    ArrayList<String> moves = new ArrayList<String>();
    
    //if you are too far ahead, we won't let you roll anymore!
    if(scores[turn] > 2 * scores[1- turn]) {
      
    }
    else {
      moves.add("roll");
      moves.add("bank");
    }
    
    return moves;
  }
  
  public void makeMove(String move) {
    if(move.equals("roll")) {
      int rollA = (int)(random.nextInt(6)) + 1;
      int rollB = (int)(random.nextInt(6)) + 1;
      
      if(rollA == 6 && rollB == 6) {
        scores[turn] = 0;
        unbanked[turn] = 0;
        turn = 1 - turn;
      }
      else if(rollA == 6 || rollB == 6) {
        unbanked[turn] = 0;
        turn = 1 - turn;
      }
      else {
        scores[turn] += rollA + rollB;
      }
    }  
    else if(move.equals("bank")){ //bank
      scores[turn] += unbanked[turn];
      unbanked[turn] = 0;
      turn = 1 - turn;
    }
    else { //no move
      turn = 1 - turn;
      
    }
  }
  
  public String toString() {
    return  "Player 0: " + scores[0] + " " + unbanked[0] + ", " +
            "Player 1: " + scores[1] + " " + unbanked[1] + ", " + 
            "It is Player " + turn + "'s turn";
  }
}

class FahrenbacherPlayer extends Player {
  
  int count = 0;
  
  public FahrenbacherPlayer(String aName) { 
    super(aName);
  }
  
  public String getNextMove(GameState state) { 
    count++;
    
    ArrayList<String> list = state.getCurrentMoves();
    if(list.size() == 0)
      return "no move";
    else if(count % 2 == 1)
      return list.get(0); //roll
    else
      return list.get(1); //bank
  }
}