Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package game.connect4.ui;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.Stack;
- import java.util.StringTokenizer;
- import game.*;
- import game.connect4.rep.Board;
- import game.connect4.rep.Column;
- import game.connect4.rep.Connect4Color;
- import game.connect4.rep.Connect4Move;
- import game.connect4.rep.Connect4RepresentationException;
- /**
- * character based user interface for a connect 4 game.
- * To play a 100% manual connect 4 game, simply make an instance of this Class and execute the method 'playGame()'
- * To have a computer play against a human, connect a 'Connect4Playable' object to this instance.
- *
- * You can add your own connect4 computer to this interface by creating a class that implements the Connect4Playable
- * interface and connect an instance of your class a UIBoard instance.
- *
- * @author martin
- *
- */
- public class UIBoard {
- private static final int EMPTY = 0;
- private static final int RED = 1;
- private static final int YELLOW = 2;
- private int board[];
- private int colorToMove;
- private Stack<Integer> moveStack;
- private Board playboard;
- public UIBoard() {
- board = new int[42];
- newGame();
- }
- /**
- * initializes the board.
- */
- private void newGame() {
- //Initialiseer board
- try {
- playboard = new Board();
- playboard.playGame();
- } catch (Connect4RepresentationException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- for (int i = 0; i < 42; ++i) {
- board[i] = EMPTY;
- }
- colorToMove = YELLOW;
- moveStack = new Stack<Integer>();
- moveStack.clear();
- }
- /**
- * Shows the commands that can be chosen by the user
- */
- private void showCommands() {
- System.out.println("COMMAND Action");
- System.out.println("===========================================================================");
- System.out.println("HELP, : Shows this screen");
- System.out.println("A-G : If possible, it executes a move in this column");
- System.out.println("TAKEBACK, T : Takes back a move");
- System.out.println("SHOW : Shows the board again");
- System.out.println("NEW : Starts an new game");
- System.out.println("QUIT : Quits the program");
- System.out.println("All other input will be ingored");
- System.out.println();
- }
- /**
- * Displays the board on the screen,
- * It also shows the last column played, by indicating a '^' below the column
- * Furthermore it shows which color is to move.
- */
- private void showBoard() {
- for (int r = 5; r >= 0; --r) {
- for (int c = 0; c < 7; ++c) {
- int sq = r * 7 + c;
- if (board[sq] == YELLOW) {
- System.out.print(" X");
- } else if (board[sq] == RED) {
- System.out.print(" O");
- } else {
- System.out.print(" .");
- }
- }
- System.out.println();
- }
- System.out.println("--------------");
- for (int c = 0; c < 7; ++c) {
- System.out.print(' ');
- System.out.print((char) ('A' + c));
- }
- System.out.println();
- if (moveStack.isEmpty()) {
- System.out.println();
- } else {
- for (int c = 0; c < 7; ++c) {
- int columnPlayed = moveStack.peek().intValue() % 7;
- if (columnPlayed == c) {
- System.out.print(" ^");
- } else {
- System.out.print(" ");
- }
- }
- System.out.println();
- }
- int val = valEndPosition();
- if (val == 0) {
- System.out.println("Endposition. Draw.");
- } else if (val == YELLOW) {
- System.out.println("Endposition. 'X' has won.");
- } else if (val == RED) {
- System.out.println("Endposition. 'O' has won.");
- } else if (colorToMove == YELLOW) {
- System.out.println("'X' to move");
- } else {
- System.out.println("'O' to move");
- }
- }
- /**
- * Simply shows an error message 'msg' on the next line of the screen.
- * @param msg
- */
- private void showError(String msg) {
- System.err.println(msg);
- }
- private void showPrompt() {
- System.out.print("> ");
- }
- /**
- * This function waits until the user has entered his action.
- * An action can be some system setting or a column letter.
- */
- public void playGame() {
- try {
- boolean goOn = true;
- //Display Menu
- goOn = menu();
- if(goOn)showBoard();
- if(goOn)System.out.println("(Press '?' to get an overview of all commands)");
- while (goOn) {
- BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
- StringTokenizer st;
- do {
- showPrompt();
- String s = userInput.readLine();
- st = new StringTokenizer(s);
- } while (!st.hasMoreTokens());
- String tok = (st.nextToken()).toUpperCase();
- if (tok.equals("?") || tok.equals("HELP")) {
- showCommands();
- } else if (tok.length() == 1 && (tok.charAt(0) >= 'A' && tok.charAt(0) <= 'G')) {
- // Do human move
- char ch = tok.charAt(0);
- if (isEndPosition()) {
- showError("Endposition has been reached. No new move allowed");
- } else if (legalMove(ch)) {
- executeMove(lowestFreeSquare(ch));
- showBoard();
- if(!isEndPosition()){
- executeMove(lowestFreeSquare((char) (playboard.putHumanMove(ch- 'A')+'A')));
- showBoard();
- }
- //goOn = false; // Nu mag de compuiter :>
- } else {
- showError("Illegal Move. Column already filled up.");
- }
- } else if ((tok.equals("T") || tok.equals("TAKEBACK"))) {
- if (takeBackPossible()) {
- takeBackLastMove();
- showBoard();
- } else {
- showError("No takeback possible.");
- }
- } else if (tok.equals("SHOW")) {
- showBoard();
- } else if (tok.equals("NEW")) {
- newGame();
- showBoard();
- } else if (tok.equals("QUIT")) {
- goOn = false;
- } else {
- showError("Illegal command or command not allowed during search of computer");
- }
- }
- AI();
- //System.out.println("End of Program");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- private void AI(){
- //playboard.doMove(, Connect4Color.YELLOW));
- //playGame();
- }
- /**
- * Checks if square 'sq' is part of a one-color four-connected serie in direction 'dir'
- * @param sq
- * @param dir
- * @return true if it there is a four connection, false otherwise
- */
- private boolean connect4InDirection(int sq, int dir) {
- int sqCol = sq % 7;
- int sqRow = sq / 7;
- for (int l = 3; l >= 0; l--) {
- boolean insideBoard = true;
- //check if we get behind the edge of the board
- if ((dir == 1 || dir == 8) && (sqCol - l < 0 || sqCol + (3 - l) > 6)) {
- insideBoard = false;
- } else if ((dir == 6) && (sqCol + l > 6 || sqCol - (3 - l) < 0)) {
- insideBoard = false;
- } else if (dir != 1 && (sqRow - l < 0 || sqRow + (3 - l) > 5)) {
- insideBoard = false;
- }
- if (insideBoard) {
- int nb = sq - l * dir;
- boolean stillPossible = true;
- while (nb <= (sq + (3 - l) * dir) && stillPossible) {
- if (board[nb] == EMPTY || board[sq] != board[nb]) {
- stillPossible = false; //quit loop
- } else {
- nb += dir;
- }
- }
- if (stillPossible) {
- return true;
- }
- }
- }
- return false;
- }
- /**
- * Checks if the last move played has lead to an end position
- * @return -1 if no end position has been reached
- * value of RED or YELLOW if the last move has lead to a connection of 4 coins
- * 0 if all moves have been played and there is no winner
- */
- private int valEndPosition() {
- if (moveStack.size() < 7) {
- return -1;
- }
- int sq = moveStack.peek().intValue();
- if (connect4InDirection(sq, 1)) {
- return board[sq];
- }
- if (connect4InDirection(sq, 6)) {
- return board[sq];
- }
- if (connect4InDirection(sq, 7)) {
- return board[sq];
- }
- if (connect4InDirection(sq, 8)) {
- return board[sq];
- }
- if (moveStack.size() == 42) {
- return 0;
- }
- return -1;
- }
- /**
- * Checks if the last move played has lead to an end position
- * @return true if this square is part of a four connected serie or all 42 moves have been played
- * false otherwise
- */
- private boolean isEndPosition() {
- return (valEndPosition() >= 0);
- }
- /**
- * Returns the lowest free square in a column (if available)
- * The columnChar must be between 'A' and 'G'
- * @param columnChar
- * @return if there is a free square in a column, it returns the index of that square
- * it returns -1 otherwise
- */
- private int lowestFreeSquare(char columnChar) {
- int columnNumber = columnChar - 'A';
- if (columnNumber >= 0 && columnNumber <= 6) {
- for (int i = columnNumber; i < 42; i += 7) {
- if (board[i] == EMPTY) {
- return i;
- }
- }
- }
- return -1;
- }
- /**
- * Checks if the column represented by columnChar is a legal column and if it can be filled
- * @param columnChar - the column to be checked
- * @return true if it is a column that can be played, false otherwise
- */
- private boolean legalMove(char columnChar) {
- return (lowestFreeSquare(columnChar) > -1);
- }
- /**
- * Returns the other color from the give color.
- * If the given color is not RED or YELLOW, it returns EMPTY
- * @param color
- * @return other color.
- */
- private int otherColor(int color) {
- if (color == YELLOW) {
- return RED;
- }
- if (color == RED) {
- return YELLOW;
- }
- return EMPTY;
- }
- /**
- * Executes the move, given by the squareIndex 'sqIndex'
- * Will also calls the listener that a move has been played
- *
- * @param sqIndex
- */
- public void executecomp(int col){
- lowestFreeSquare((char) (col +'A'));
- }
- private void executeMove(int sqIndex) {
- board[sqIndex] = colorToMove;
- //playboard.doMove(new Connect4Move(new Column(aColumnNr, sq0, sq1, sq2, sq3, sq4, sq5), colorToMove));
- colorToMove = otherColor(colorToMove);
- moveStack.add(new Integer(sqIndex));
- System.out.println();
- }
- /**
- * Checks if it is possible to take back a move
- * @return true if you can take back a move,false otherwise
- */
- private boolean takeBackPossible() {
- return !moveStack.isEmpty();
- }
- /**
- * Takes back the last move played.
- * Will also calls the listeners that the last move has been canceled
- */
- private void takeBackLastMove() {
- if (takeBackPossible()) {
- int sq = moveStack.pop().intValue();
- board[sq] = EMPTY;
- colorToMove = otherColor(colorToMove);
- }
- }
- private boolean menu(){
- try{
- System.out.println("To run test case 1 press 1");
- System.out.println("To run test case 2 press 2");
- System.out.println("To play against AI press p");
- boolean menu = true;
- while(menu){
- BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
- StringTokenizer st;
- do {
- showPrompt();
- String s = userInput.readLine();
- st = new StringTokenizer(s);
- } while (!st.hasMoreTokens());
- String tok = (st.nextToken()).toUpperCase();
- if(tok.equals("1")){
- return test1();
- }else if(tok.equals("2")){
- return test2();
- }else if(tok.equals("P")){
- menu = false;
- return true;
- }
- }
- }catch (IOException e) {
- e.printStackTrace();
- }
- return true;
- }
- private boolean test1(){
- try{
- System.out.println("Run test 1 with how many ply?");
- boolean menu = true;
- while(menu){
- BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
- StringTokenizer st;
- do {
- showPrompt();
- String s = userInput.readLine();
- st = new StringTokenizer(s);
- } while (!st.hasMoreTokens());
- String tok = (st.nextToken()).toUpperCase();
- int number = 0;
- try{
- number = Integer.parseInt(tok);
- }catch(Exception exception){
- System.out.println(exception);
- }
- if(number >= 1 && number <= 99){
- playboard.runTest1(number);
- System.out.println("Program finished");
- return false;
- }else{
- System.out.println("Please enter a NUMBER");
- }
- }
- }catch (IOException e) {
- e.printStackTrace();
- }
- return false;
- }
- private boolean test2(){
- try{
- System.out.println("Run test 2 with how many ply?");
- boolean menu = true;
- while(menu){
- BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
- StringTokenizer st;
- do {
- showPrompt();
- String s = userInput.readLine();
- st = new StringTokenizer(s);
- } while (!st.hasMoreTokens());
- String tok = (st.nextToken()).toUpperCase();
- int number = 0;
- try{
- number = Integer.parseInt(tok);
- }catch(Exception exception){
- System.out.println(exception);
- }
- if(number >= 1 && number <= 99){
- playboard.runTest2(number);
- System.out.println("Program finished");
- return false;
- }else{
- System.out.println("Please enter a NUMBER");
- }
- }
- }catch (IOException e) {
- e.printStackTrace();
- }
- return false;
- }
- }
Add Comment
Please, Sign In to add comment