Java Kernel for Jupyter Notebooks.

[Install Java kernel readme}(https://github.com/SpencerPark/IJava). Java will require an independent kernel in Jupyter Notebooks. The instruction performed by the Teacher follows, but look to readme if you have troubles.

(base) id:~$ wget https://github.com/SpencerPark/IJava/releases/download/v1.3.0/ijava-1.3.0.zip  # download IJava kernel as zip
(base) id:~$ unzip ijava-1.3.0.zip # unzip downloaded IJava kernel
(base) id:~$ python install.py --user # install IJava kernel
(base) id:~$ jupyter kernelspec list # list kernels
Available kernels:
  java          /home/shay/.local/share/jupyter/kernels/java
  python3       /home/shay/.local/share/jupyter/kernels/python3

Console Game Menu

College Boards Units #1, #3, and #4 and Free Response Methods and Control Structures are built into these labs. Of course, these games are very popular in beginning programming. They are here for reference, as they were shared by a student.

import java.util.Scanner; //library for user input
import java.lang.Math; //library for random numbers

public class ConsoleGame {
    public final String DEFAULT = "\u001B[0m";  // Default Terminal Color
    
    public ConsoleGame() {
        Scanner sc = new Scanner(System.in);  // using Java Scanner Object
        
        boolean quit = false;
        while (!quit) {
            this.menuString();  // print Menu
            try {
                int choice = sc.nextInt();  // using method from Java Scanner Object
                System.out.print("" + choice + ": ");
                quit = this.action(choice);  // take action
            } catch (Exception e) {
                sc.nextLine(); // error: clear buffer
                System.out.println(e + ": Not a number, try again.");
            }
            
        }
        sc.close();
    }

    public void menuString(){
        String menuText = ""
                + "\u001B[35m___________________________\n"  
                + "|~~~~~~~~~~~~~~~~~~~~~~~~~|\n"
                + "|\u001B[0m          Menu!          \u001B[35m|\n"
                + "|~~~~~~~~~~~~~~~~~~~~~~~~~|\n"
                + "| 0 - Exit                |\n"    
                + "| 1 - Rock Paper Scissors |\n"
                + "| 2 - Higher or Lower     |\n"
                + "| 3 - Tic Tac Toe         |\n"
                + "|_________________________|   \u001B[0m\n"
                + "\n"
                + "Choose an option.\n"
                ;
        System.out.println(menuText);
    }

    private boolean action(int selection) {
        boolean quit = false;
        switch (selection) {  // Switch or Switch/Case is Control Flow statement and is used to evaluate the user selection
            case 0:
                System.out.print("Goodbye, World!"); 
                quit = true; 
                break;
            case 1:
                rps();
                break;
            case 2:
                horl();
                break;
            case 3:
                ticTacToe();
                break;
                    
            default:
                //Prints error message from console
                System.out.print("Unexpected choice, try again.");
        }
        System.out.println(DEFAULT);  // make sure to reset color and provide new line
        return quit;
    }

    public void horl(){
        System.out.println("Higher or Lower");
        System.out.println("You have three guesses to guess the number I am thinking of between 1-8.");
        System.out.println("If you guess the number correctly, you win!");
        Scanner scHL = new Scanner(System.in);
        int randomG = (int) (Math.random() * 8) + 1;
        int guess = scHL.nextInt();
        for(int i = 3; i > 0; i--){
            if(guess == randomG){
                System.out.println("You win!");
                break;
            }
            else if(guess > randomG){
                System.out.println("The number is lower");
            }
            else if(guess < randomG){
                System.out.println("The number is higher");
            }
            guess = scHL.nextInt();
        }
        System.out.println("Game over.");
        scHL.close();
    }
                                                     
    public void rps(){
        System.out.println("Rock Paper Scissors");
        System.out.println("Type r for rock, p for paper, or s for scissors");
        Scanner scRPS = new Scanner(System.in);
        String userChoice = scRPS.nextLine().toLowerCase();
        Boolean quit = false;
        int random = (int) (Math.random() * 3);
        while(quit == false){
            if(userChoice.equals("r")){
                if(random == 1){
                    System.out.println("You chose rock \nThe computer chose paper \nYou lose!");
                }
                else if(random == 2){
                    System.out.println("You chose rock \nThe computer chose scissors \nYou win!");
                }
                else{
                    System.out.println("You chose rock \nThe computer chose rock \nIt's a tie!");
                }
                quit = true;
            }
            else if(userChoice.equals("p")){
                if(random == 1){
                    System.out.println("You chose paper \nThe computer chose paper \nIt's a tie!");
                }
                else if(random == 2){
                    System.out.println("You chose paper \nThe computer chose scissors \nYou lose!");
                }
                else{
                    System.out.println("You chose paper \nThe computer chose rock \nYou win!");
                }
                quit = true;

            }
            else if(userChoice.equals("s")){
                if(random == 1){
                    System.out.println("You chose scissors \nThe computer chose paper \nYou win!");
                }
                else if(random == 2){
                    System.out.println("You chose scissors \nThe computer chose scissors \nIt's a tie!");
                }
                else{
                    System.out.println("You chose scissors \nThe computer chose rock \nYou lose!");
                }
                quit = true;

            }
            else{
                System.out.println("Invalid input, try again");
                userChoice = scRPS.nextLine();
            }            
        }
        scRPS.close();
    }
    
    public void ticTacToe(){
        System.out.println("Tic Tac Toe");
        Scanner scTTT = new Scanner(System.in);
        String[] board = {"1", "2", "3", "4", "5", "6", "7", "8", "9"};
        String player = "X";
        String player2 = "O";
        int turn = 0;
        Boolean quit = false;
        System.out.println("Do you want to play against a friend or the computer?");
        System.out.println("Type 1 for friend, 2 for computer");
        int choice = scTTT.nextInt();
        //make tic tac toe using player1 and player2
        if(choice == 1){                
            System.out.println("Type the number of the square you want to place your piece in");
            while(quit == false){
                System.out.println("Player 1's turn (X)");
                System.out.println(board[0] + " | " + board[1] + " | " + board[2]);
                System.out.println(board[3] + " | " + board[4] + " | " + board[5]);
                System.out.println(board[6] + " | " + board[7] + " | " + board[8]);
                int move = scTTT.nextInt();
                if(board[move - 1].equals("X") || board[move - 1].equals("O")){
                    System.out.println("That square is already taken, try again");
                }
                else{
                    board[move - 1] = player;
                    turn++;
                    if(board[0].equals("X") && board[1].equals("X") && board[2].equals("X")){
                        System.out.println("Player 1 wins!");
                        quit = true;
                    }
                    else if(board[3].equals("X") && board[4].equals("X") && board[5].equals("X")){
                        System.out.println("Player 1 wins!");
                        quit = true;
                    }
                    else if(board[6].equals("X") && board[7].equals("X") && board[8].equals("X")){
                        System.out.println("Player 1 wins!");
                        quit = true;
                    }
                    else if(board[0].equals("X") && board[3].equals("X") && board[6].equals("X")){
                        System.out.println("Player 1 wins!");
                        quit = true;
                    }
                    else if(board[1].equals("X") && board[4].equals("X") && board[7].equals("X")){
                        System.out.println("Player 1 wins!");
                        quit = true;
                    }
                    else if(board[2].equals("X") && board[5].equals("X") && board[8].equals("X")){
                        System.out.println("Player 1 wins!");
                        quit = true;
                    }
                    else if(board[0].equals("X") && board[4].equals("X") && board[8].equals("X")){
                        System.out.println("Player 1 wins!");
                        quit = true;
                    }
                    else if(board[2].equals("X") && board[4].equals("X") && board[6].equals("X")){
                        System.out.println("Player 1 wins!");
                        quit = true;
                    }
                    else if(turn == 9){
                        System.out.println("It's a tie!");
                        quit = true;
                    }
                    else{
                        System.out.println("Player 2's turn (O)");
                        System.out.println(board[0] + " | " + board[1] + " | " + board[2]);
                        System.out.println(board[3] + " | " + board[4] + " | " + board[5]);
                        System.out.println(board[6] + " | " + board[7] + " | " + board[8]);
                        int move2 = scTTT.nextInt();
                        if(board[move2 - 1].equals("X") || board[move2 - 1].equals("O")){
                            System.out.println("That square is already taken, try again");
                        }
                        else{
                            board[move2 - 1] = player2;
                            turn++;
                            if(board[0].equals("O") && board[1].equals("O") && board[2].equals("O")){
                                System.out.println("Player 2 wins!");
                                quit = true;
                            }
                            else if(board[3].equals("O") && board[4].equals("O") && board[5].equals("O")){
                                System.out.println("Player 2 wins!");
                                quit = true;
                            }
                            else if(board[6].equals("O") && board[7].equals("O") && board[8].equals("O")){
                                System.out.println("Player 2 wins!");
                                quit = true;
                            }
                            else if(board[0].equals("O") && board[3].equals("O") && board[6].equals("O")){
                                System.out.println("Player 2 wins!");
                                quit = true;
                            }
                            else if(board[1].equals("O") && board[4].equals("O") && board[7].equals("O")){
                                System.out.println("Player 2 wins!");
                                quit = true;
                            }
                            else if(board[2].equals("O") && board[5].equals("O") && board[8].equals("O")){
                                System.out.println("Player 2 wins!");
                                quit = true;
                            }
                        }
                    }
                }
            }
        }
        if(choice == 2){
            String computer = "O";
            System.out.println("Type the number of the square you want to place your piece in");
            while(quit == false){
                System.out.println("Player 1's turn (X)");
                System.out.println(board[0] + " | " + board[1] + " | " + board[2]);
                System.out.println(board[3] + " | " + board[4] + " | " + board[5]);
                System.out.println(board[6] + " | " + board[7] + " | " + board[8]);
                int move = scTTT.nextInt();
                if(board[move - 1].equals("X") || board[move - 1].equals("O")){
                    System.out.println("That square is already taken, try again");
                }
                else{
                    board[move - 1] = player;
                    turn++;
                    if(board[0].equals("X") && board[1].equals("X") && board[2].equals("X")){
                        System.out.println("Player 1 wins!");
                        quit = true;
                    }
                    else if(board[3].equals("X") && board[4].equals("X") && board[5].equals("X")){
                        System.out.println("Player 1 wins!");
                        quit = true;
                    }
                    else if(board[6].equals("X") && board[7].equals("X") && board[8].equals("X")){
                        System.out.println("Player 1 wins!");
                        quit = true;
                    }
                    else if(board[0].equals("X") && board[3].equals("X") && board[6].equals("X")){
                        System.out.println("Player 1 wins!");
                        quit = true;
                    }
                    else if(board[1].equals("X") && board[4].equals("X") && board[7].equals("X")){
                        System.out.println("Player 1 wins!");
                        quit = true;
                    }
                    else if(board[2].equals("X") && board[5].equals("X") && board[8].equals("X")){
                        System.out.println("Player 1 wins!");
                        quit = true;
                    }
                    else if(board[0].equals("X") && board[4].equals("X") && board[8].equals("X")){
                        System.out.println("Player 1 wins!");
                        quit = true;
                    }
                    else if(board[2].equals("X") && board[4].equals("X") && board[6].equals("X")){
                        System.out.println("Player 1 wins!");
                        quit = true;
                    }
                    else if(turn == 9){
                        System.out.println("It's a tie!");
                        quit = true;
                    }
                    else{
                        System.out.println("Computer's turn (O)");
                        System.out.println(board[0] + " | " + board[1] + " | " + board[2]);
                        System.out.println(board[3] + " | " + board[4] + " | " + board[5]);
                        System.out.println(board[6] + " | " + board[7] + " | " + board[8]);
                        int move2 = (int)(Math.random() * 9) + 1;
                        if(board[move2 - 1].equals("X") || board[move2 - 1].equals("O")){
                            System.out.println("That square is already taken, try again");
                        }
                        else{
                            board[move2 - 1] = computer;
                            turn++;
                            if(board[0].equals("O") && board[1].equals("O") && board[2].equals("O")){
                                System.out.println("Computer wins!");
                                quit = true;
                            }
                            else if(board[3].equals("O") && board[4].equals("O") && board[5].equals("O")){
                                System.out.println("Computer wins!");
                                quit = true;
                            }
                            else if(board[6].equals("O") && board[7].equals("O") && board[8].equals("O")){
                                System.out.println("Computer wins!");
                                quit = true;
                            }
                            else if(board[0].equals("O") && board[3].equals("O") && board[6].equals("O")){
                                System.out.println("Computer wins!");
                                quit = true;
                            }
                            else if(board[1].equals("O") && board[4].equals("O") && board[7].equals("O")){
                                System.out.println("Computer wins!");
                                quit = true;
                            }
                            else if(board[2].equals("O") && board[5].equals("O") && board[8].equals("O")){
                                System.out.println("Computer wins!");
                                quit = true;
                            }
                        }
                    }
                }
            }
          
    }
        scTTT.close();
    }

    static public void main(String[] args)  {  
        new ConsoleGame(); // starting Menu object
    }


}
ConsoleGame.main(null);

Hacks

To start the year, I want you to consider a simple Java console game or improve on the games listed.

  • Make RPS, Tic-Tack-Toe, and Higher Lower into different objects. Answer why you think this is important?

Making them different objects is important for a bunch of reasons, including ease of testing, modularity, encapsulation (and private class variables that are relevant to the given game), and the scalability of this games console.

  • Simplify logic, particularly T-T-T. What could you do to make this more simple? Java has HashMap (like Python Dictionary), Arrays (fixed size), ArraLists (Dynamic Size).
  • Run the menu using recursion versus while loop.

For my hacks, I improved all of these games’ functionality and made them their own separate objects. I then made a separate object that would run each of the games when selected. I also did the recursion thing.

Rock Paper Scissors

I optimized the win-lose-tie system with a single array in a separate rpsWinCheck function and created an option to play again using a while loop.

import java.util.Random;

public class RockPaperScissors {
    // win check method; returns "win", "lose" or "tie"
    private String rpsWinCheck(int playerChoice, int computerChoice) {
        // array representing win conditions
        String[][] outcomeArray = {
            {"tie", "lose", "win"},
            {"win", "tie", "lose"},
            {"lose", "win", "tie"}
        };
        // selecting outcome
        String outcome = outcomeArray[playerChoice][computerChoice];
        // return the outcome as a string
        return outcome;
    }

    // main game start method
    public static void main(String[] args) {
        // used for game text
        String[] choices = {"rock", "paper", "scissors"};
        // new random object
        Random random = new Random();
        // random rps selection
        int compChoice = random.nextInt(3);

        // user stuff yo yo yo
        Scanner rpsInput = new Scanner(System.in);  // create a Scanner object
        try {
            boolean playing = true;
            while (playing) {
                System.out.println("It's Rock Paper Scissors time! What do you choose? (Input an integer option below.)\n\t1. Rock\n\t2. Paper\n\t3. Scissors");
                String rpsSelection = rpsInput.nextLine();
                int pChoice = Integer.parseInt(rpsSelection) - 1; String result = rpsWinCheck(pChoice, compChoice);
                System.out.println("You chose " + choices[pChoice] + " and the opponent chose " + choices[compChoice] + ", so you " + result + "!");
                System.out.println("Would you like to play again? (Input 'y' or 'n', please.)");
                String playAgain = rpsInput.nextLine();
                if ("n".equals(playAgain)) {playing = false;}
            }
            rpsInput.close();
            return;
        } catch (Exception e) {
            System.out.println("You had three clearly-defined options to pick from, and you failed. How shameful.");
            return;
        } finally {rpsInput.close();}
    }
}

Higher or Lower

Once again, I added a “Play Again” option after the round. I made it more efficient.

public class HigherOrLower {
    private static boolean horlWinCheck(int playerChoice, int computerChoice) {
        String result = "DIFFERENT"; //if, for some reason, the comparison doesn't work
        if (playerChoice > 10 || playerChoice < 1) {
            System.out.println("Please guess a number between 1 and 10.");
            return false;
        }
        if (playerChoice == computerChoice) {
            System.out.println("Congratulations! You've successfully guessed the number!");
            return true;
        } else {
            if (playerChoice > computerChoice) {result = "LOWER";} else {result = "HIGHER";}
            System.out.println("The opponent's number is " + result + " than your guess.");
            return false;
        }
    }
    public static void main(String[] args) {
        // new random object
        Random random = new Random();
        // user stuff yo yo yo
        Scanner horlInput = new Scanner(System.in);  // create a Scanner object
        try {
            boolean playing = true;
            while (playing) {
                // random rps selection
                int compChoice = random.nextInt(10) + 1;
                // resetting to the first turn
                int turn = 1;
                System.out.println("Your opponent has chosen a number. You have 3 tries to guess it!");
                while (turn < 4) {
                    System.out.println("TURN " + Integer.toString(turn) + ": Guess a number between 1 and 10.");
                    String horlSelection = horlInput.nextLine();
                    if (horlWinCheck(Integer.parseInt(horlSelection), compChoice)) {
                        turn = 4;
                    } else {
                        if (turn == 3) {
                            System.out.println("Oh no! You weren't able to guess the number.");
                        }
                        turn += 1;
                    }
                }
                // play again?
                System.out.println("Would you like to play again? (Input 'y' or 'n', please.)\n");
                String playAgain = horlInput.nextLine();
                if ("n".equals(playAgain)) {playing = false;}
            }
            horlInput.close();
            return;
        } catch (Exception e) {
            System.out.println("You literally just pick a number from 1 to 10. It's so easy. I'm disappointed in you.");
            return;
        } finally {horlInput.close();}
    }
}

Tic-Tac-Toe

Rather than replay functionality, I mainly optimized this game by making the AI more efficient (and actually functional) and I made the checks for wins clearer.

public class TicTacToe {
    // ttt player input for "X" and "O"
    public static String[][] tttMakeMove(String xoro, int gridIndex, String[][] boardData) {
        int converterCheck = 1;
        outerloop:
        for (int j = 0; j < 3; j++) {
            for (int k = 0; k < 3; k++) {
                if (converterCheck == gridIndex) {
                    boardData[j][k] = xoro;
                    break outerloop;
                }
                converterCheck++;
                if (converterCheck == 10) {
                    System.out.println("Invalid input.");
                }
            }
        }
        return boardData;
    }

    // win check function
    public static boolean tttWinCheck(String[][] board) {
        // check rows and columns
        for (int i = 0; i < 3; i++) {
            if (board[i][0].equals(board[i][1]) && board[i][1].equals(board[i][2])) {
                System.out.println("Three in a row! " + board[i][0] + " player wins.");
                return true; // row win
            }
            if (board[0][i].equals(board[1][i]) && board[1][i].equals(board[2][i])) {
                System.out.println("Three in a row! " + board[0][i] + " player wins.");
                return true; // column win
            }
        }
        // Check diagonals
        if (board[0][0].equals(board[1][1]) && board[1][1].equals(board[2][2])) {
            System.out.println("Three in a row! " + board[0][0] + " player wins.");
                return true; // top-left-to-right diagonal win
        }
        if (board[0][2].equals(board[1][1]) && board[1][1].equals(board[2][0])) {
            System.out.println("Three in a row! " + board[0][2] + " player wins.");
            return true; // top-right-to-left diagonal win
        }
        // test for tie
        int tieTest = 0;
        for (int j = 0; j < 3; j++) {
            for (int k = 0; k < 3; k++) {
                if ("X".equals(board[j][k]) || "O".equals(board[j][k])) {tieTest++;}
            }
        }
        if (tieTest >= 9) {
            System.out.println("It's a tie! Nobody wins.");
            return true; // tie ending
        }
        return false; // no win
    }

    // main game run
    public static void main(String[] args) {
        Scanner tttInput = new Scanner(System.in);  // create a Scanner object
        try {
            Random random = new Random(); //create random object
            boolean compGame = true;
            // player chooses mode
            System.out.println("Welcome to Tic-Tac-Toe! Please choose a mode.\n\t1. Player vs. Player\n\t2. Player vs. Computer");
            String modeChoice = tttInput.nextLine();
            if ("1".equals(modeChoice)) {compGame = false;}
            // create board with numbers
            String[][] board = {
                {"1", "2", "3"},
                {"4", "5", "6"},
                {"7", "8", "9"}
            };
            // repeat game loop while active
            boolean playing = true;
            while (playing) {
                for (int i = 0; i < 3; i++) {
                    System.out.println(board[i][0] + " | " + board[i][1] + " | " + board[i][2]);
                }
                System.out.println("Where would you like to place an X?");
                String tttSelection1 = tttInput.nextLine();
                int gridValue = Integer.parseInt(tttSelection1);
                board = tttMakeMove("X", gridValue, board);
                if (tttWinCheck(board)) {return;}
                if (compGame) {
                    boolean compChoosing = true;
                    while (compChoosing) {
                        int compChoiceRow = random.nextInt(3);
                        int compChoiceColumn = random.nextInt(3);
                        if (!("X".equals(board[compChoiceRow][compChoiceColumn])) && !("O".equals(board[compChoiceRow][compChoiceColumn]))) {
                            board[compChoiceRow][compChoiceColumn] = "O";
                            compChoosing = false;
                        }
                    }
                } else {
                    for (int i = 0; i < 3; i++) {
                        System.out.println(board[i][0] + " | " + board[i][1] + " | " + board[i][2]);
                    }
                    System.out.println("Other player, where would you like to place an O?");
                    String tttSelection2 = tttInput.nextLine();
                    int gridValue2 = Integer.parseInt(tttSelection2);
                    board = tttMakeMove("O", gridValue2, board);
                }
                if (tttWinCheck(board)) {return;}
            }
        } catch (Exception e) {
            System.out.println("You have a specific set of numerical choices and you messed it up. Wow.");
            return;
        } finally {tttInput.close();}
    }
}

Recursive Console Games Object

I created a new ConsoleGames object that allows for game selection and works recursively rather than with a while loop.

public class ConsoleGames {
    public static void main(String[] args) {
        Scanner consoleInput = new Scanner(System.in);
        playGames(consoleInput);
        consoleInput.close();
    }

    // the play games fun thing
    private static void playGames(Scanner consoleInput) {
        String menu = ""
                + "\u001B[31m____________________________\n"
                + "\u001B[31m|\t\t\u001B[35mGames Menu\t\t\t\u001B[31m|\n"
                + "\u001B[31m|\t\u001B[35m1. Rock Paper Scissors\t\t\u001B[31m|\n"
                + "\u001B[31m|\t\u001B[35m2. Higher or Lower\t\t\t\u001B[31m|\n"
                + "\u001B[31m|\t\u001B[35m3. Tic-Tac-Toe\t\t\t\t\u001B[31m|\n"
                + "\u001B[31m|\t\u001B[35m4. Exit\t\t\t\t\t\u001B[31m|\n"
                + "\u001B[31m____________________________\n"
                + "\n\u001B[37mChoose one of the games to play.";
        System.out.println(menu);

        String gameChoice = consoleInput.nextLine();

        switch (gameChoice) {
            case "1":
                RockPaperScissors.main(null);
                break;
            case "2":
                HigherOrLower.main(null);
                break;
            case "3":
                TicTacToe.main(null);
                break;
            case "4":
                System.out.println("Goodbye, World!");
                return; // terminate
            default:
                System.out.println("Invalid input. Try again.");
                break;
        }

        // RECURSION
        playGames(consoleInput);
    }
}

ConsoleGames.main(null);