kivaari icon

Untitled

kivaari | PRO | 01/06/17 09:45:22 PM UTC | 0 ⭐ | 303 👁️ | Never ⏰ | []
C++ |

16.26 KB

|

None

|

0 👍

/

0 👎

package go;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
 
 
/**
 *
 * @author Chris
 */
public class Go_ConsoleIO implements Go_IO {
    
    
    int size=0;
    Board myboard;
    InputStreamReader input = new InputStreamReader(System.in);
    OutputStreamWriter output = new OutputStreamWriter(System.out);
    
    // Singleton
    
    private static Go_ConsoleIO instance = null;
    
    private Go_ConsoleIO() {
        
    }
    
    public static Go_ConsoleIO getInstance() {
        if (instance == null) {
            instance = new Go_ConsoleIO();
        }
        return instance;
    }
 
    @Override
    public void setBoard(Board b){
        myboard=b;
    }
 
    @Override
    public void printTurn(int turn){
        try {
            printTurn(turn , output);
        } catch (IOException ex) {
            Logger.getLogger(Go_ConsoleIO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void printTurn(int turn, OutputStreamWriter outputstream) throws IOException{
        BufferedWriter writer = new BufferedWriter(outputstream);
        clear();
        writer.newLine();
        writer.write("------ TURN "+turn+ " ------");
        writer.flush();
    }
 
    @Override
    public void printCapturedStones(int p1stones, int p2stones){
        try {
            printCapturedStones(p1stones, p2stones,output);
        } catch (IOException ex) {
            Logger.getLogger(Go_ConsoleIO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void printCapturedStones(int p1stones, int p2stones, OutputStreamWriter outputstream) throws IOException {
        BufferedWriter writer = new BufferedWriter(outputstream);
        writer.newLine();
        writer.write("--- CAPTURED STONES ---");
        writer.newLine();
        writer.write("Black: "+p1stones+"    White: "+p2stones);
        writer.newLine();
        writer.flush();
    }
 
    @Override
    public void printBoard(){
        try {
            printBoard(output);
        } catch (IOException ex) {
            Logger.getLogger(Go_ConsoleIO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void printBoard(OutputStreamWriter outputstream) throws IOException{
    
        BufferedWriter writer = new BufferedWriter(outputstream);
        String str;
        writer.newLine();
        size=myboard.getDimension();
        writer.write("   ");
        for(int i=65; i<(size+65);i++){
            char b = (char) i;
            str=" "+b+" ";
            writer.write(str);
        }
 
        writer.newLine();
        for(int y = size - 1; y >= 0 ; y--) {
            writer.write(y + 1 + "| ");
 
            for(int x = y * size; x < size * y + size; x++) {
                String stone;
                if (myboard.getStone(x).getColor() == 1) {
                    stone = "B";
                }
                else if (myboard.getStone(x).getColor() == 2) {
                    stone = "W";
                }
                else {
                    stone = " ";
                }
 
                // System.out.print("["+myboard.getStone(x).getColor()+"]");
                str="["+stone+"]";
                writer.write(str);
                
 
            }
 
            writer.newLine();        
        }
 
        writer.newLine();
        writer.flush();
    /*for(int i=0; i<size;i++){
        System.out.println(" "+(i+1)+" ");
        for(int y=i; y<size;y++){
            System.out.print("("+myboard.getStone(i+(y*size)).getColor()+")");      //TODO beautify this
            //TODO unsicher, ob try/catch noch n?tig zwecks theoretisch m?glichem myboard=null
        }
    }*/
    }
        
    @Override
    public int getPlayerInput (int id){
        try { 
            return(getPlayerInput(id, input, output));
        } catch (IOException ex) {
            Logger.getLogger(Go_ConsoleIO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return -9999;
    }
    public int getPlayerInput (int id, InputStreamReader inputstream, OutputStreamWriter outputstream) throws IOException {
        BufferedReader reader = new BufferedReader(inputstream);
        BufferedWriter writer = new BufferedWriter(outputstream);
        size = myboard.getDimension();
        String yourmove = "";
        if (id == 1) {
            yourmove = "Black";
        }
        else if (id == 2) {
            yourmove = "White";
        }
        int input = -1;
        int x = 0;
        int y = 0;
        while(input<0){
            writer.newLine();
            writer.write("Available commands: 'undo', 'surrender', 'pass' or an existing coordinate (for example: A1)");
            writer.newLine();
            writer.write("Your move (" + yourmove + "): ");
            writer.flush();
            String inputstring = reader.readLine();
            // undo
            if(inputstring.equals("undo")) return -1;
            // pass
            if(inputstring.equals("pass")) return -2;
            // surrender
            if(inputstring.equals("surr") || inputstring.equals("surrender")) return -3;
            
            if (inputstring.length() != 2) {
                writer.newLine();
                writer.write("Please enter a valid coordinate (for example: A1)!");
            }
            else {
                char first = inputstring.charAt(0);
                char second = inputstring.charAt(1);
                
                if (Character.isLetter(first) && Character.isDigit(second)) {
                    x = (int) first;
                    y = (int) second;
                    
                    if (x >= 97) {
                        x = x - 97;
                    }
                    else {
                        x = x - 65;
                    }
                    
                    y = y - 49;
                    
                    if ((x >= 0 && x < size) && (y >= 0 && y < size)) {
                        input = x + (y * size);
                    }
                    else {
                        writer.write("Please enter a valid coordinate (for example: A1)!");
                    }
                }
                else {
                    writer.write("Please enter a valid coordinate (for example: A1)!");
                }
            } 
                    
            /* char[] c = inputstring.toCharArray();
            for(int i=0; i<c.length ; i++){
                if(c[i]!=' '){
                    if(x<=0){
                        if(Character.isLetter(c[i])){
                        
                    
                            x = c[i] -0;
                            if(x>=97) x=x-32; 
                            x=x-65;
                        }   
                    }
                    else{
                    int num1 = c[i]-49;
                        if(num1<9 &&num1>-1){
                        if(y<=0) y=num1;
                        else y=y*10+num1;
                        }
                    }
                } 
            
            }
            if(x<=size && y<=size) input=x+(size*y);
            if(input<0){
                System.out.println("The position you entered could not get matched:");
            
            } */
            
        }
 
        return input;
    }
    
    @Override
   public int getMenu(){
       int r=-1; 
        try {
            r=getMenu(input, output);
        } catch (IOException ex) {
            Logger.getLogger(Go_ConsoleIO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return r;
    }
    public int getMenu(InputStreamReader inputstream, OutputStreamWriter outputstream) throws IOException {
        BufferedReader reader = new BufferedReader(inputstream);
        BufferedWriter writer = new BufferedWriter(outputstream);
        int r=0;
        clear();
        writer.newLine();
        writer.write("----- MAIN MENU -----");
        writer.newLine();
        writer.write("1: Start the game");
        writer.newLine();
        writer.write("2: Configure game settings");
        writer.newLine();
        writer.write("Select an option: ");
        writer.flush();
        while(r==0){
            int num = Integer.parseInt(reader.readLine());
            if (num==1 || num==2) r=num;
            else {
                writer.write("Not a valid selection, please try again: ");
                writer.flush();
            }
            
            }
        return r;
    }
    
    @Override
    public int getDimension() {
        int r=-1;
        while(r==-1){
            try {
                r=getDimension(input, output);
            } catch (IOException ex) {
                Logger.getLogger(Go_ConsoleIO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return r;
    }
    public int getDimension(InputStreamReader inputstream, OutputStreamWriter outputstream) throws IOException {
        BufferedReader reader = new BufferedReader(inputstream);
        BufferedWriter writer = new BufferedWriter(outputstream);
        clear();
        writer.newLine();
        writer.write("----- CONFIGURATION -----");
        int r=0;
        writer.newLine();
        writer.write("Choose the size of the board (must be 9, 13 or 19): ");
        writer.flush();
        while(r!=9 || r!=13 || r!=19) {
          r=Integer.parseInt(reader.readLine());
          if (r!=9 && r!=13 && r!=19) {
              writer.newLine();
              writer.write("Not a valid board size, please choose 9, 13 and 19: ");
              writer.flush();
          }
        }
        setSize(r);
        return r;
    }
    
    @Override
    public int getPlayer(int i){
        int r=-1;
        while(r==-1){
            try {
                r=getPlayer(i,input,output);
            } catch (IOException ex) {
                Logger.getLogger(Go_ConsoleIO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return r;
    }
    
    public int getPlayer(int i,InputStreamReader inputstream, OutputStreamWriter outputstream) throws IOException {
        BufferedReader reader = new BufferedReader(inputstream);
        BufferedWriter writer = new BufferedWriter(outputstream);
        // clear();
        int r=0;
        writer.newLine();
        writer.write("Enter '1' if you want the player to be human controlled, else enter '2'");
        writer.flush();
        if(i==1)writer.write("Player 1 (Black): ");
        else if(i==2)writer.write("Player 2 (White): ");
        writer.flush();
        while(r<1 || r>2){
            r=Integer.parseInt(reader.readLine());
            if(r<1||r>2) {
                writer.newLine();
                writer.write("Not a valid choice, enter '1' for human or '2' for AI: ");
                writer.flush();
            }
        }
        return r;
    }
    
    public void printUndoError(){
        System.out.println("Undo not allowed at this point!");
    }
    
    private void clear(){
        System.out.print("\033[H\033[2J");
    }
    
 /*   private int getInput(){
        int num;
        Scanner input = new Scanner(System.in);
        try{
            num= input.nextInt();
           
        }
        catch(InputMismatchException ex){
           System.out.println("Incorrect input: an integer is required");
           return -1;
        }
        return num;        
    }*/
    
    private void setSize(int s){
        size=s;
    }
 
    @Override
    public void printForfeitMessage(int loser){
        try {
            printForfeitMessage(loser, input, output);
        } catch (IOException ex) {
            Logger.getLogger(Go_ConsoleIO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void printForfeitMessage(int loser,InputStreamReader inputstream, OutputStreamWriter outputstream) throws IOException {
        BufferedReader reader = new BufferedReader(inputstream);
        BufferedWriter writer = new BufferedWriter(outputstream);
        System.out.println("");
        switch(loser){
           case 1: 
               writer.newLine();
               writer.write("----- WHITE WON THE GAME VIA FORFEIT -----");
               writer.flush();
               break;
           
           case 2:
               writer.newLine();
               writer.write("----- BLACK WON THE GAME VIA FORFEIT -----");
               writer.flush();
               break;
       
       }
        
        System.out.println("Thanks for playing!");
           
    }
 
    @Override
    public void printEndGameMessage(double p1score, double p2score){
        //printEndGameMessage()
    }
    public void printEndGameMessage(double p1score, double p2score, OutputStreamWriter outputstream) {
        BufferedWriter writer = new BufferedWriter(outputstream);
        System.out.println("----- GAME HAS ENDED -----");
        
        System.out.println();
        System.out.println("Final score (captured stones + komi): BLACK " + p1score + " - " + p2score + " WHITE");
        System.out.println("Thanks for playing. You can now calculate the winner!");
        System.out.println();
        
    }
 
    @Override
    public void printBackToMenuMessage() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Press ENTER once you are ready to return to the main menu... ");
        scanner.nextLine();
    }
 
    @Override
    public void printNoMoreValidPlaysMessage(int player){
        try {
            printNoMoreValidPlaysMessage(player,output);
        } catch (IOException ex) {
            Logger.getLogger(Go_ConsoleIO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void printNoMoreValidPlaysMessage(int player, OutputStreamWriter outputstream) throws IOException {
        BufferedWriter writer = new BufferedWriter(outputstream);
        Scanner scanner = new Scanner(System.in);
        writer.newLine();
        switch(player) {
            case(1):
               
                writer.write("Black has no more valid plays left.");
                writer.flush();
                break;
            
            case(2):
                
                writer.write("White has no more valid plays left.");
                break;
        }
        writer.write("Press ENTER to confirm... ");
        writer.flush();
        scanner.nextLine();
    }
 
    @Override
    public void printNotValidTurnMessage() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("You can't place a stone on this field! Press ENTER to confirm...");
        scanner.nextLine();
        
    }
 
    @Override
    public int getStartingPlayer(){
        int r=-1;
        while(r==-1){
            try {
                r=getStartingPlayer(input,output);
            } catch (IOException ex) {
                Logger.getLogger(Go_ConsoleIO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return r;
    }
    public int getStartingPlayer(InputStreamReader inputstream, OutputStreamWriter outputstream) throws IOException {
        BufferedReader reader = new BufferedReader(inputstream);
        BufferedWriter writer = new BufferedWriter(outputstream);
        writer.newLine();
        writer.write("Who should start the game? (Enter 'human' or 'AI'): ");
        writer.flush();
        boolean run = true;
        
        while (run) {
            String inputstring = reader.readLine();
            
            if (inputstring.equals("human") || inputstring.equals("Human")) {
                return 1;
            }
            else if (inputstring.equals("ai") || inputstring.equals("AI")) {
                return 2;
            }
            else {
                writer.newLine();
                writer.write("Invalid command, please try again: ");
                writer.flush();
            }
        }
        return 0;
    }
}

Comments