Saturday, 20 February 2016

Another day another challenge

Over the month I have been working on Java OCA, now scoring in the 60% after a month in the high 40 low 50s, I need to break into the 80% range before I can book the exam. 

Started to learn to touch type as one of those things I have always wanted to get around to, typing club helps. 

Talking to the developers at work about interviews, quick as you can tic tac toe, best I can do in about 30 minutes, error I noticed afterwards is it works from top left as is 0,0. 

 package com.company;

import java.util.Arrays;
import java.util.Scanner;

public class TicTacToe {
    public char[][] board;

    public TicTacToe() {
        board = new char[3][3];
        for (char[] row: board) {
            for (int i = 0; i < row.length; i++) {
                row[i] = ' ';
            }
        }
        startGame();
    }

    public void printBoard() {
        for (char[] row : board) {
            for (char letter :row) {
                System.out.print("[ " + letter + " ]" );
            }
            System.out.println();
        }
    }

    public boolean placeValue(int col, int row, char letter) {
        if (board[row][col] != ' ') {
            System.out.println("Space taken");
            return false;
        } else {
            board[row][col] = letter;
            return true;
        }
    }

    public boolean isGameWon() {

        //horizontal
        for (char[] row: board) {
            if(row[0] != ' ') {
                if (row[0] == row[1] && row[1] == row[2])
                    return true;
            }
        }

        //vertical
        for (int i = 0; i < 3; i++) {
            if (board[0][i] != ' ' && board[0][i] == board[1][i] && 

            board[1][i] == board[2][i])
                return true;
        }
        //diagonal
        if (board[0][0] != ' ' && board[1][1] == board[0][0] &&              board[1][1] == board[2][2]) return true;
        if (board[2][2] != ' ' && board[1][1] == board[0][0] && 

        board[1][1] == board[2][2]) return true;

        return false;
    }

    public void startGame() {
        String inputText = "";
        Scanner reader = new Scanner(System.in);
        printBoard();
        while (
                Arrays.asList(board).contains(' ')
                || !isGameWon()
                ) {
            System.out.println("Enter co ords and char 0 0 A: ");
            inputText = reader.nextLine().trim();
            placeValue(Integer.parseInt(String.valueOf(inputText.charAt(0))),
                    Integer.parseInt(String.valueOf(inputText.charAt(2))),
                    inputText.charAt(4));
            printBoard();
        }
        if(isGameWon()) {
            System.out.println("You Win!");
        } else {
            System.out.println("Draw!");
        }

    }
}

No comments:

Post a Comment