Guest User

Untitled

a guest
May 20th, 2018
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.10 KB | None | 0 0
  1. package game.connect4.ui;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.util.Stack;
  7. import java.util.StringTokenizer;
  8. import game.*;
  9. import game.connect4.rep.Board;
  10. import game.connect4.rep.Column;
  11. import game.connect4.rep.Connect4Color;
  12. import game.connect4.rep.Connect4Move;
  13. import game.connect4.rep.Connect4RepresentationException;
  14.  
  15. /**
  16. * character based user interface for a connect 4 game.
  17. * To play a 100% manual connect 4 game, simply make an instance of this Class and execute the method 'playGame()'
  18. * To have a computer play against a human, connect a 'Connect4Playable' object to this instance.
  19. *
  20. * You can add your own connect4 computer to this interface by creating a class that implements the Connect4Playable
  21. * interface and connect an instance of your class a UIBoard instance.
  22. *
  23. * @author martin
  24. *
  25. */
  26. public class UIBoard {
  27.  
  28. private static final int EMPTY = 0;
  29. private static final int RED = 1;
  30. private static final int YELLOW = 2;
  31. private int board[];
  32. private int colorToMove;
  33. private Stack<Integer> moveStack;
  34. private Board playboard;
  35.  
  36. public UIBoard() {
  37. board = new int[42];
  38. newGame();
  39. }
  40.  
  41. /**
  42. * initializes the board.
  43. */
  44. private void newGame() {
  45.  
  46. //Initialiseer board
  47. try {
  48. playboard = new Board();
  49. playboard.playGame();
  50. } catch (Connect4RepresentationException e) {
  51. // TODO Auto-generated catch block
  52. e.printStackTrace();
  53. }
  54. for (int i = 0; i < 42; ++i) {
  55. board[i] = EMPTY;
  56. }
  57. colorToMove = YELLOW;
  58.  
  59. moveStack = new Stack<Integer>();
  60. moveStack.clear();
  61.  
  62. }
  63.  
  64. /**
  65. * Shows the commands that can be chosen by the user
  66. */
  67. private void showCommands() {
  68. System.out.println("COMMAND Action");
  69. System.out.println("===========================================================================");
  70. System.out.println("HELP, : Shows this screen");
  71. System.out.println("A-G : If possible, it executes a move in this column");
  72. System.out.println("TAKEBACK, T : Takes back a move");
  73. System.out.println("SHOW : Shows the board again");
  74. System.out.println("NEW : Starts an new game");
  75. System.out.println("QUIT : Quits the program");
  76. System.out.println("All other input will be ingored");
  77. System.out.println();
  78. }
  79.  
  80. /**
  81. * Displays the board on the screen,
  82. * It also shows the last column played, by indicating a '^' below the column
  83. * Furthermore it shows which color is to move.
  84. */
  85. private void showBoard() {
  86. for (int r = 5; r >= 0; --r) {
  87. for (int c = 0; c < 7; ++c) {
  88. int sq = r * 7 + c;
  89. if (board[sq] == YELLOW) {
  90. System.out.print(" X");
  91. } else if (board[sq] == RED) {
  92. System.out.print(" O");
  93. } else {
  94. System.out.print(" .");
  95. }
  96. }
  97. System.out.println();
  98. }
  99. System.out.println("--------------");
  100.  
  101. for (int c = 0; c < 7; ++c) {
  102. System.out.print(' ');
  103. System.out.print((char) ('A' + c));
  104. }
  105. System.out.println();
  106.  
  107. if (moveStack.isEmpty()) {
  108. System.out.println();
  109. } else {
  110. for (int c = 0; c < 7; ++c) {
  111. int columnPlayed = moveStack.peek().intValue() % 7;
  112. if (columnPlayed == c) {
  113. System.out.print(" ^");
  114. } else {
  115. System.out.print(" ");
  116. }
  117. }
  118. System.out.println();
  119. }
  120.  
  121. int val = valEndPosition();
  122. if (val == 0) {
  123. System.out.println("Endposition. Draw.");
  124. } else if (val == YELLOW) {
  125. System.out.println("Endposition. 'X' has won.");
  126. } else if (val == RED) {
  127. System.out.println("Endposition. 'O' has won.");
  128. } else if (colorToMove == YELLOW) {
  129. System.out.println("'X' to move");
  130. } else {
  131. System.out.println("'O' to move");
  132. }
  133. }
  134.  
  135. /**
  136. * Simply shows an error message 'msg' on the next line of the screen.
  137. * @param msg
  138. */
  139. private void showError(String msg) {
  140. System.err.println(msg);
  141. }
  142.  
  143. private void showPrompt() {
  144. System.out.print("> ");
  145. }
  146.  
  147. /**
  148. * This function waits until the user has entered his action.
  149. * An action can be some system setting or a column letter.
  150. */
  151. public void playGame() {
  152. try {
  153. boolean goOn = true;
  154. //Display Menu
  155. goOn = menu();
  156. if(goOn)showBoard();
  157. if(goOn)System.out.println("(Press '?' to get an overview of all commands)");
  158. while (goOn) {
  159. BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
  160.  
  161. StringTokenizer st;
  162. do {
  163. showPrompt();
  164. String s = userInput.readLine();
  165. st = new StringTokenizer(s);
  166. } while (!st.hasMoreTokens());
  167.  
  168. String tok = (st.nextToken()).toUpperCase();
  169. if (tok.equals("?") || tok.equals("HELP")) {
  170. showCommands();
  171. } else if (tok.length() == 1 && (tok.charAt(0) >= 'A' && tok.charAt(0) <= 'G')) {
  172. // Do human move
  173. char ch = tok.charAt(0);
  174. if (isEndPosition()) {
  175. showError("Endposition has been reached. No new move allowed");
  176. } else if (legalMove(ch)) {
  177. executeMove(lowestFreeSquare(ch));
  178. showBoard();
  179. if(!isEndPosition()){
  180. executeMove(lowestFreeSquare((char) (playboard.putHumanMove(ch- 'A')+'A')));
  181. showBoard();
  182. }
  183. //goOn = false; // Nu mag de compuiter :>
  184. } else {
  185. showError("Illegal Move. Column already filled up.");
  186. }
  187. } else if ((tok.equals("T") || tok.equals("TAKEBACK"))) {
  188. if (takeBackPossible()) {
  189. takeBackLastMove();
  190. showBoard();
  191. } else {
  192. showError("No takeback possible.");
  193. }
  194. } else if (tok.equals("SHOW")) {
  195. showBoard();
  196. } else if (tok.equals("NEW")) {
  197. newGame();
  198. showBoard();
  199. } else if (tok.equals("QUIT")) {
  200. goOn = false;
  201. } else {
  202. showError("Illegal command or command not allowed during search of computer");
  203. }
  204. }
  205.  
  206. AI();
  207. //System.out.println("End of Program");
  208. } catch (IOException e) {
  209. e.printStackTrace();
  210. }
  211. }
  212.  
  213. private void AI(){
  214. //playboard.doMove(, Connect4Color.YELLOW));
  215. //playGame();
  216. }
  217.  
  218. /**
  219. * Checks if square 'sq' is part of a one-color four-connected serie in direction 'dir'
  220. * @param sq
  221. * @param dir
  222. * @return true if it there is a four connection, false otherwise
  223. */
  224. private boolean connect4InDirection(int sq, int dir) {
  225. int sqCol = sq % 7;
  226. int sqRow = sq / 7;
  227. for (int l = 3; l >= 0; l--) {
  228. boolean insideBoard = true;
  229. //check if we get behind the edge of the board
  230. if ((dir == 1 || dir == 8) && (sqCol - l < 0 || sqCol + (3 - l) > 6)) {
  231. insideBoard = false;
  232. } else if ((dir == 6) && (sqCol + l > 6 || sqCol - (3 - l) < 0)) {
  233. insideBoard = false;
  234. } else if (dir != 1 && (sqRow - l < 0 || sqRow + (3 - l) > 5)) {
  235. insideBoard = false;
  236. }
  237.  
  238.  
  239. if (insideBoard) {
  240. int nb = sq - l * dir;
  241. boolean stillPossible = true;
  242. while (nb <= (sq + (3 - l) * dir) && stillPossible) {
  243. if (board[nb] == EMPTY || board[sq] != board[nb]) {
  244. stillPossible = false; //quit loop
  245. } else {
  246. nb += dir;
  247. }
  248. }
  249. if (stillPossible) {
  250. return true;
  251. }
  252. }
  253. }
  254.  
  255. return false;
  256. }
  257.  
  258. /**
  259. * Checks if the last move played has lead to an end position
  260. * @return -1 if no end position has been reached
  261. * value of RED or YELLOW if the last move has lead to a connection of 4 coins
  262. * 0 if all moves have been played and there is no winner
  263. */
  264. private int valEndPosition() {
  265. if (moveStack.size() < 7) {
  266. return -1;
  267. }
  268.  
  269. int sq = moveStack.peek().intValue();
  270.  
  271. if (connect4InDirection(sq, 1)) {
  272. return board[sq];
  273. }
  274. if (connect4InDirection(sq, 6)) {
  275. return board[sq];
  276. }
  277. if (connect4InDirection(sq, 7)) {
  278. return board[sq];
  279. }
  280. if (connect4InDirection(sq, 8)) {
  281. return board[sq];
  282. }
  283. if (moveStack.size() == 42) {
  284. return 0;
  285. }
  286.  
  287. return -1;
  288. }
  289.  
  290. /**
  291. * Checks if the last move played has lead to an end position
  292. * @return true if this square is part of a four connected serie or all 42 moves have been played
  293. * false otherwise
  294. */
  295. private boolean isEndPosition() {
  296. return (valEndPosition() >= 0);
  297. }
  298.  
  299. /**
  300. * Returns the lowest free square in a column (if available)
  301. * The columnChar must be between 'A' and 'G'
  302. * @param columnChar
  303. * @return if there is a free square in a column, it returns the index of that square
  304. * it returns -1 otherwise
  305. */
  306. private int lowestFreeSquare(char columnChar) {
  307. int columnNumber = columnChar - 'A';
  308. if (columnNumber >= 0 && columnNumber <= 6) {
  309. for (int i = columnNumber; i < 42; i += 7) {
  310. if (board[i] == EMPTY) {
  311. return i;
  312. }
  313. }
  314. }
  315. return -1;
  316. }
  317.  
  318. /**
  319. * Checks if the column represented by columnChar is a legal column and if it can be filled
  320. * @param columnChar - the column to be checked
  321. * @return true if it is a column that can be played, false otherwise
  322. */
  323. private boolean legalMove(char columnChar) {
  324. return (lowestFreeSquare(columnChar) > -1);
  325. }
  326.  
  327. /**
  328. * Returns the other color from the give color.
  329. * If the given color is not RED or YELLOW, it returns EMPTY
  330. * @param color
  331. * @return other color.
  332. */
  333. private int otherColor(int color) {
  334. if (color == YELLOW) {
  335. return RED;
  336. }
  337. if (color == RED) {
  338. return YELLOW;
  339. }
  340. return EMPTY;
  341. }
  342.  
  343. /**
  344. * Executes the move, given by the squareIndex 'sqIndex'
  345. * Will also calls the listener that a move has been played
  346. *
  347. * @param sqIndex
  348. */
  349.  
  350. public void executecomp(int col){
  351. lowestFreeSquare((char) (col +'A'));
  352. }
  353.  
  354.  
  355. private void executeMove(int sqIndex) {
  356. board[sqIndex] = colorToMove;
  357. //playboard.doMove(new Connect4Move(new Column(aColumnNr, sq0, sq1, sq2, sq3, sq4, sq5), colorToMove));
  358. colorToMove = otherColor(colorToMove);
  359. moveStack.add(new Integer(sqIndex));
  360.  
  361.  
  362. System.out.println();
  363. }
  364.  
  365. /**
  366. * Checks if it is possible to take back a move
  367. * @return true if you can take back a move,false otherwise
  368. */
  369. private boolean takeBackPossible() {
  370. return !moveStack.isEmpty();
  371. }
  372.  
  373. /**
  374. * Takes back the last move played.
  375. * Will also calls the listeners that the last move has been canceled
  376. */
  377. private void takeBackLastMove() {
  378. if (takeBackPossible()) {
  379. int sq = moveStack.pop().intValue();
  380. board[sq] = EMPTY;
  381. colorToMove = otherColor(colorToMove);
  382. }
  383. }
  384.  
  385. private boolean menu(){
  386. try{
  387. System.out.println("To run test case 1 press 1");
  388. System.out.println("To run test case 2 press 2");
  389. System.out.println("To play against AI press p");
  390. boolean menu = true;
  391. while(menu){
  392. BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
  393.  
  394. StringTokenizer st;
  395. do {
  396. showPrompt();
  397. String s = userInput.readLine();
  398. st = new StringTokenizer(s);
  399. } while (!st.hasMoreTokens());
  400.  
  401. String tok = (st.nextToken()).toUpperCase();
  402.  
  403. if(tok.equals("1")){
  404. return test1();
  405. }else if(tok.equals("2")){
  406. return test2();
  407. }else if(tok.equals("P")){
  408. menu = false;
  409. return true;
  410. }
  411. }
  412. }catch (IOException e) {
  413. e.printStackTrace();
  414. }
  415. return true;
  416. }
  417.  
  418. private boolean test1(){
  419. try{
  420. System.out.println("Run test 1 with how many ply?");
  421. boolean menu = true;
  422. while(menu){
  423. BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
  424.  
  425. StringTokenizer st;
  426. do {
  427. showPrompt();
  428. String s = userInput.readLine();
  429. st = new StringTokenizer(s);
  430. } while (!st.hasMoreTokens());
  431.  
  432. String tok = (st.nextToken()).toUpperCase();
  433.  
  434. int number = 0;
  435.  
  436. try{
  437. number = Integer.parseInt(tok);
  438. }catch(Exception exception){
  439. System.out.println(exception);
  440. }
  441.  
  442.  
  443. if(number >= 1 && number <= 99){
  444. playboard.runTest1(number);
  445. System.out.println("Program finished");
  446. return false;
  447. }else{
  448. System.out.println("Please enter a NUMBER");
  449. }
  450.  
  451. }
  452. }catch (IOException e) {
  453. e.printStackTrace();
  454. }
  455. return false;
  456. }
  457.  
  458. private boolean test2(){
  459. try{
  460. System.out.println("Run test 2 with how many ply?");
  461. boolean menu = true;
  462. while(menu){
  463. BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
  464.  
  465. StringTokenizer st;
  466. do {
  467. showPrompt();
  468. String s = userInput.readLine();
  469. st = new StringTokenizer(s);
  470. } while (!st.hasMoreTokens());
  471.  
  472. String tok = (st.nextToken()).toUpperCase();
  473.  
  474. int number = 0;
  475.  
  476. try{
  477. number = Integer.parseInt(tok);
  478. }catch(Exception exception){
  479. System.out.println(exception);
  480. }
  481.  
  482.  
  483. if(number >= 1 && number <= 99){
  484. playboard.runTest2(number);
  485. System.out.println("Program finished");
  486. return false;
  487. }else{
  488. System.out.println("Please enter a NUMBER");
  489. }
  490.  
  491. }
  492. }catch (IOException e) {
  493. e.printStackTrace();
  494. }
  495. return false;
  496. }
  497. }
Add Comment
Please, Sign In to add comment