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 | /* IC 312 Fall 2015 * Project 2 starter code */ import java.util.*; import java.io.*; /** A two-player game pitting human vs computer - who will be victorious? */ public class TwoPlayers { private class ComputerPlayer extends Thread { public void run() { compWords = game.allWords(); } } public Board game; public ComputerPlayer computer; public volatile Queue<String> compWords = null; //TODO: Replace YourDataStructure below. public YourDataStructure myWords = new YourDataStructure(); public TwoPlayers() { game = new Board(); computer = new ComputerPlayer(); } public void goHuman(long endTime) throws IOException { BufferedReader input = new BufferedReader(System.console().reader()); PrintWriter output = System.console().writer(); while (true) { output.print("\u001b[2J\u001b[H"); // clears the screen output.println(game); output.print("Current words:"); for (String word : myWords.traverse()) { output.print(" " + word); } output.print("\n" + (endTime - System.currentTimeMillis())/1000 + " seconds remaining."); output.print("\n\nNext word? "); output.flush(); while (!input.ready() && System.currentTimeMillis() < endTime) { try { Thread.sleep(100); } catch (InterruptedException ee) { endTime = 0; } } if (System.currentTimeMillis() >= endTime) { output.println("TIME'S UP!"); break; } String nextWord = input.readLine().trim().toUpperCase(); myWords.insert(nextWord); } } public static void main(String[] args) { TwoPlayers play = new TwoPlayers(); try { play.computer.start(); play.goHuman(System.currentTimeMillis() + 60000); } catch (Exception e) { System.err.println("\n(game ended prematurely)"); } System.out.println("\n================== RESULTS =====================\n"); int myPoints = Board.countPoints(play.myWords.traverse()); System.out.println("You got " + myPoints + " points."); System.out.println("(note: these words were not checked for validity!)\n"); if (play.compWords == null) { System.out.println("\nWaiting for the computer to finish..."); try { play.computer.join(); } catch(InterruptedException ee) { } } int compPoints = Board.countPoints(play.compWords); System.out.println("The computer got " + compPoints + " points."); try { System.out.print("\n(let that sink in"); for (int ii=0; ii<30; ++ii) { Thread.sleep(100); System.out.print("."); } System.out.println(")"); } catch (InterruptedException ee) { } System.out.println("\nHere are the computer's words:"); int online = 0; for (String word : play.compWords) { if (online >= 8) { System.out.println(); online = 0; } System.out.print(word + " "); ++online; } System.out.println(); } } |