Home
Time Box
Calculator
Snake
Blogs
Hacks

Java Console hacks • 33 min read

Description

hacks for the java console lesson


Java Console Hacks

Documented code H and L

public void horl(){

    // Inital Rules Print Staments
    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 is used similar to input() in python
    Scanner scHL = new Scanner(System.in);
    int randomG = (int) (Math.random() * 8) + 1; // This makes the random number
    int guess = scHL.nextInt();

    // Game Logic seeing if you guessed higher or lower
    // For loop only giving you three geusses
    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();
    }

    //End of game Print plus close();
    System.out.println("Game over.");
    scHL.close();
}

RPS

public void rps(){
    // Intial Rule Staments
    System.out.println("Rock Paper Scissors");
    System.out.println("Type r for rock, p for paper, or s for scissors");

    // Scaner + other vars
    Scanner scRPS = new Scanner(System.in);
    String userChoice = scRPS.nextLine().toLowerCase();
    Boolean quit = false;
    int random = (int) (Math.random() * 3);

    // Uses a while loop to Make game logic
    // It has the same game logic could be improved
    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();
}

Java Game TTT more simpflied

import java.util.Random;
import java.util.Scanner;

public class TicTacToe {
    public static void main(String[] args) {
        System.out.println("Tic Tac Toe");
        Scanner scanner = new Scanner(System.in);
        String[] board = {"1", "2", "3", "4", "5", "6", "7", "8", "9"};
        boolean quit = false;

        int choice = getPlayerChoice(scanner);

        String player = "X";
        String player2 = (choice == 1) ? "O" : "Computer";

        while (!quit) {
            printBoard(board);
            int move;
            if (player.equals("X") || choice == 1) {
                move = getPlayerMove(scanner, board, player);
            } else {
                move = getComputerMove(board);
            }
            updateBoard(board, move, player);
            if (checkWin(board, player)) {
                printBoard(board);
                System.out.println("Player " + player + " wins!");
                quit = true;
            } else if (isBoardFull(board)) {
                printBoard(board);
                System.out.println("It's a tie!");
                quit = true;
            } else {
                player = (player.equals("X")) ? player2 : "X";
            }
        }

        scanner.close();
    }

    public static int getPlayerChoice(Scanner scanner) {
        System.out.println("Do you want to play against a friend or the computer?");
        System.out.println("Type 1 for friend, 2 for computer");
        return scanner.nextInt();
    }

    public static void printBoard(String[] board) {
        for (int i = 0; i < 9; i += 3) {
            String cell1 = board[i].equals("Computer") ? "O" : board[i];
            String cell2 = board[i + 1].equals("Computer") ? "O" : board[i + 1];
            String cell3 = board[i + 2].equals("Computer") ? "O" : board[i + 2];
            System.out.println(cell1 + " | " + cell2 + " | " + cell3);
        }
    }
    

    public static int getPlayerMove(Scanner scanner, String[] board, String player) {
        int move;
        while (true) {
            System.out.println("Player " + player + "'s turn (" + player + ")");
            move = scanner.nextInt();
            if (move < 1 || move > 9 || !board[move - 1].equals(String.valueOf(move))) {
                System.out.println("Invalid move. Try again.");
            } else {
                break;
            }
        }
        return move;
    }

    public static void updateBoard(String[] board, int move, String player) {
        board[move - 1] = player;
    }

    public static boolean checkWin(String[] board, String player) {
        int[][] winConditions = {
                {0, 1, 2}, {3, 4, 5}, {6, 7, 8},
                {0, 3, 6}, {1, 4, 7}, {2, 5, 8},
                {0, 4, 8}, {2, 4, 6}
        };

        for (int[] condition : winConditions) {
            if (board[condition[0]].equals(player) &&
                    board[condition[1]].equals(player) &&
                    board[condition[2]].equals(player)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isBoardFull(String[] board) {
        for (String cell : board) {
            if (!cell.equals("X") && !cell.equals("O")) {
                return false;
            }
        }
        return true;
    }

    public static int getComputerMove(String[] board) {
        Random random = new Random();
        int move;
        do {
            move = random.nextInt(9) + 1;
        } while (!board[move - 1].equals(String.valueOf(move)));
        return move;
    }
}

TicTacToe.main(null);

Tic Tac Toe
Do you want to play against a friend or the computer?
Type 1 for friend, 2 for computer
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
Player X's turn (X)
X | 2 | 3
4 | 5 | 6
7 | 8 | 9
Player O's turn (O)
X | 2 | 3
4 | O | 6
7 | 8 | 9
Player X's turn (X)
X | X | 3
4 | O | 6
7 | 8 | 9
Player O's turn (O)
X | X | 3
O | O | 6
7 | 8 | 9
Player X's turn (X)
X | X | X
O | O | 6
7 | 8 | 9
Player X wins!

Things that I changed in the code

  1. Modular Design and Functions: In the second code, the logic is divided into separate functions, each responsible for a specific task. This makes the code more organized, readable, and maintainable. Functions like getPlayerChoice, printBoard, getPlayerMove, updateBoard, checkWin, isBoardFull, and getComputerMove handle individual tasks. This modular approach improves code clarity and encourages code reuse.

  2. Win Condition Handling: The second code employs a more concise and efficient approach for checking win conditions. It uses a predefined 2D array winConditions to represent all possible winning combinations on the Tic Tac Toe board. This eliminates the need for multiple explicit if-else statements for checking each win condition individually, as seen in the first code. The second code’s approach enhances code maintainability and readability.

  3. Improved Computer Move Generation: In the second code, the computer’s move generation logic is more refined. It uses a Random object to generate random moves, but it ensures that the generated move corresponds to an available spot on the board. This guarantees that the computer doesn’t make an invalid move or overwrite existing moves. In the first code, the computer’s move generation using Math.random() is prone to generating invalid moves, which is avoided in the second code.

Simplfied game plus new colors

import java.util.Scanner;
import java.util.Random;

public class ConsoleGame {
    private Scanner scanner = new Scanner(System.in);
    private Random random = new Random();

    public ConsoleGame() {
        displayMenu();
    }

    public static final String ANSI_RESET = "\u001B[0m";
    public static final String ANSI_CYAN = "\u001B[36m";
    public static final String ANSI_PURPLE = "\u001B[35m";

    private void displayMenu() {
        System.out.println(ANSI_CYAN + "_______________________");
        System.out.println("|" + ANSI_PURPLE + "~~~~~~~~~~~~~~~~~~~~" + ANSI_CYAN + "|");
        System.out.println("|" + ANSI_PURPLE + "                 Menu!                " + ANSI_CYAN + "|");
        System.out.println("|" + ANSI_PURPLE + "~~~~~~~~~~~~~~~~~~~~" + ANSI_CYAN + "|");
        System.out.println("| 0 - Exit                              |");
        System.out.println("| 1 - Rock Paper Scissors    |");
        System.out.println("| 2 - Higher or Lower          |");
        System.out.println("| 3 - Tic Tac Toe                 |");
        System.out.println("|_____________________|" + ANSI_RESET);
        System.out.println(ANSI_CYAN + "Choose an option." + ANSI_RESET);

        int choice = -1;
        while (choice < 0 || choice > 3) {
            if (scanner.hasNextInt()) {
                choice = scanner.nextInt();
            } else {
                scanner.next(); // Clear invalid input
                System.out.println("Invalid choice. Please enter a valid option.");
            }
        }
        performAction(choice);
    }

    private void performAction(int selection) {
        switch (selection) {
            case 0:
                System.out.println("Goodbye, World!");
                break;
            case 1:
                playRPS();
                break;
            case 2:
                playHigherOrLower();
                break;
            case 3:
                playTicTacToe();
                break;
            default:
                System.out.println("Unexpected choice, try again.");
        }

        if (selection != 0) {
            displayMenu();
        } else {
            scanner.close();
        }
    }

    private void playHigherOrLower() {
        System.out.println("Higher or Lower");
        System.out.println("You have three guesses to guess the number I am thinking of between 1-8.");
        int randomG = random.nextInt(8) + 1;
        playNumberGuessing(randomG, 3);
        System.out.println("Game over.");
    }

    private void playNumberGuessing(int targetNumber, int remainingGuesses) {
        if (remainingGuesses == 0) {
            System.out.println("Out of guesses!");
            return;
        }

        int guess = scanner.nextInt();
        if (guess == targetNumber) {
            System.out.println("You win!");
        } else if (guess > targetNumber) {
            System.out.println("The number is lower");
            playNumberGuessing(targetNumber, remainingGuesses - 1);
        } else {
            System.out.println("The number is higher");
            playNumberGuessing(targetNumber, remainingGuesses - 1);
        }
    }

    private void playRPS() {
        System.out.println("Rock Paper Scissors");
        System.out.println("Type r for rock, p for paper, or s for scissors");
        String[] choices = {"rock", "paper", "scissors"};
        int userChoiceIndex = getUserChoiceIndex();

        int computerChoiceIndex = random.nextInt(3);
        String computerChoice = choices[computerChoiceIndex];

        String userChoice = choices[userChoiceIndex];
        System.out.println("You chose " + userChoice + "\nThe computer chose " + computerChoice);

        if (userChoiceIndex == computerChoiceIndex) {
            System.out.println("It's a tie!");
        } else if ((userChoiceIndex == 0 && computerChoiceIndex == 2) ||
                (userChoiceIndex == 1 && computerChoiceIndex == 0) ||
                (userChoiceIndex == 2 && computerChoiceIndex == 1)) {
            System.out.println("You win!");
        } else {
            System.out.println("You lose!");
        }
    }

    private int getUserChoiceIndex() {
        String userChoice = scanner.next().toLowerCase();
        switch (userChoice) {
            case "r":
                return 0;
            case "p":
                return 1;
            case "s":
                return 2;
            default:
                System.out.println("Invalid input, try again");
                return getUserChoiceIndex();
        }
    }

    private void playTicTacToe() {
        System.out.println("Tic Tac Toe");
        String[] board = {"1", "2", "3", "4", "5", "6", "7", "8", "9"};
        boolean quit = false;

        int choice = getPlayerChoice(scanner);

        String player = "X";
        String player2 = (choice == 1) ? "O" : "Computer";

        while (!quit) {
            printBoard(board);

            int move;
            if (player.equals("X") || choice == 1) {
                move = getPlayerMove(scanner, board, player);
            } else {
                move = getComputerMove(board);
            }

            updateBoard(board, move, player);

            if (checkWin(board, player)) {
                printBoard(board);
                System.out.println("Player " + player + " wins!");
                quit = true;
            } else if (isBoardFull(board)) {
                printBoard(board);
                System.out.println("It's a tie!");
                quit = true;
            } else {
                player = (player.equals("X")) ? player2 : "X";
            }
        }

        displayMenu(); // Return to the menu after the game
    }

    private int getPlayerChoice(Scanner scanner) {
        System.out.println("Choose your player (1 for X, 2 for O/Computer):");
        while (true) {
            if (scanner.hasNextInt()) {
                int choice = scanner.nextInt();
                if (choice == 1 || choice == 2) {
                    return choice;
                } else {
                    System.out.println("Invalid choice. Please enter 1 or 2.");
                }
            } else {
                scanner.next(); // Clear invalid input
                System.out.println("Invalid choice. Please enter 1 or 2.");
            }
        }
    }

    private int getPlayerMove(Scanner scanner, String[] board, String player) {
        // ... (Getting player's move)
        return 0; // Replace with the actual move
    }

    private int getComputerMove(String[] board) {
        // ... (Getting computer's move)
        return 0; // Replace with the actual move
    }

    private void updateBoard(String[] board, int move, String player) {
        // ... (Updating the board)
    }

    private boolean checkWin(String[] board, String player) {
        // ... (Checking for a win)
        return false; // Replace with the actual logic
    }

    private boolean isBoardFull(String[] board) {
        // ... (Checking if the board is full)
        return false; // Replace with the actual logic
    }

    private void printBoard(String[] board) {
        // ... (Printing the board)
    }

    public static void main(String[] args) {
        new ConsoleGame();
    }
}

ConsoleGame.main(null);
_______________________
|~~~~~~~~~~~~~~~~~~~~|
|                 Menu!                |
|~~~~~~~~~~~~~~~~~~~~|
| 0 - Exit                              |
| 1 - Rock Paper Scissors    |
| 2 - Higher or Lower          |
| 3 - Tic Tac Toe                 |
|_____________________|
Choose an option.


Higher or Lower
You have three guesses to guess the number I am thinking of between 1-8.
The number is higher
The number is higher
You win!
Game over.
_______________________
|~~~~~~~~~~~~~~~~~~~~|
|                 Menu!                |
|~~~~~~~~~~~~~~~~~~~~|
| 0 - Exit                              |
| 1 - Rock Paper Scissors    |
| 2 - Higher or Lower          |
| 3 - Tic Tac Toe                 |
|_____________________|
Choose an option.
Invalid choice. Please enter a valid option.
Goodbye, World!

AP Units Used in the code