Skip to the content.

Java Console Games • 20 min read

Description

These console games show many elements from College Board's Units.

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;
import java.util.Random;

public class ConsoleGame {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

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

            int choice = scanner.nextInt();
            scanner.nextLine(); // Consume the newline character

            switch (choice) {
                case 1:
                    playRockPaperScissors(scanner);
                    break;
                case 2:
                    playHigherOrLower(scanner);
                    break;
                case 3:
                    playTicTacToe(scanner);
                    break;
                case 4:
                    System.out.println("Goodbye!");
                    scanner.close();
                    return;
                default:
                    System.out.println("Invalid choice. Please enter a valid option.");
            }
        }
    }

    private static void playRockPaperScissors(Scanner scanner) {
        String[] options = {"Rock", "Paper", "Scissors"};
        Random random = new Random();

        System.out.println("Rock, Paper, Scissors! Enter your choice (Rock/Paper/Scissors):");
        String userChoice = scanner.nextLine();
        int userIndex = -1;

        for (int i = 0; i < options.length; i++) {
            if (options[i].equalsIgnoreCase(userChoice)) {
                userIndex = i;
                break;
            }
        }

        if (userIndex == -1) {
            System.out.println("Invalid choice. Please enter Rock, Paper, or Scissors.");
            return;
        }

        int computerIndex = random.nextInt(3);

        System.out.println("Computer chose: " + options[computerIndex]);

        if (userIndex == computerIndex) {
            System.out.println("It's a tie!");
        } else if ((userIndex == 0 && computerIndex == 2) ||
                   (userIndex == 1 && computerIndex == 0) ||
                   (userIndex == 2 && computerIndex == 1)) {
            System.out.println("You win!");
        } else {
            System.out.println("Computer wins!");
        }
    }

    private static void playHigherOrLower(Scanner scanner) {
        // Higher or Lower game logic
        Random random = new Random();
        int targetNumber = random.nextInt(100) + 1;
        int attempts = 0;

        System.out.println("Welcome to Higher or Lower!");
        System.out.println("Try to guess the target number between 1 and 100.");

        while (true) {
            System.out.print("Enter your guess: ");
            int guess = scanner.nextInt();
            attempts++;

            if (guess == targetNumber) {
                System.out.println("Congratulations! You guessed the number " + targetNumber + " in " + attempts + " attempts.");
                break;
            } else if (guess < targetNumber) {
                System.out.println("Higher!");
            } else {
                System.out.println("Lower!");
            }
        }
    }

    private static void playTicTacToe(Scanner scanner) {
        // Tic Tac Toe game logic
        char[][] board = new char[3][3];
        initializeBoard(board);
        boolean isPlayer1 = true;
        boolean gameOver = false;
        int movesMade = 0;

        while (!gameOver) {
            printBoard(board);

            int row, col;
            char currentPlayerSymbol = isPlayer1 ? 'X' : 'O';
            System.out.println("Player " + (isPlayer1 ? "1 (X)" : "2 (O)") + ", enter your move (row and column): ");
            
            row = scanner.nextInt();
            col = scanner.nextInt();

            if (isValidMove(row, col, board)) {
                board[row][col] = currentPlayerSymbol;
                movesMade++;
                
                if (checkWin(board, currentPlayerSymbol)) {
                    printBoard(board);
                    System.out.println("Player " + (isPlayer1 ? "1 (X)" : "2 (O)") + " wins!");
                    gameOver = true;
                } else if (movesMade == 9) {
                    printBoard(board);
                    System.out.println("It's a draw!");
                    gameOver = true;
                } else {
                    isPlayer1 = !isPlayer1;
                }
            } else {
                System.out.println("Invalid move. Try again.");
            }
        }
    }

    private static void initializeBoard(char[][] board) {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                board[i][j] = ' ';
            }
        }
    }

    private static void printBoard(char[][] board) {
        System.out.println("-------------");
        for (int i = 0; i < 3; i++) {
            System.out.print("| ");
            for (int j = 0; j < 3; j++) {
                System.out.print(board[i][j] + " | ");
            }
            System.out.println("\n-------------");
        }
    }

    private static boolean isValidMove(int row, int col, char[][] board) {
        return row >= 0 && row < 3 && col >= 0 && col < 3 && board[row][col] == ' ';
    }

    private static boolean checkWin(char[][] board, char playerSymbol) {
        // Check rows, columns, and diagonals for a win
        for (int i = 0; i < 3; i++) {
            if ((board[i][0] == playerSymbol && board[i][1] == playerSymbol && board[i][2] == playerSymbol) ||
                (board[0][i] == playerSymbol && board[1][i] == playerSymbol && board[2][i] == playerSymbol)) {
                return true;
            }
        }
        
        return (board[0][0] == playerSymbol && board[1][1] == playerSymbol && board[2][2] == playerSymbol) ||
               (board[0][2] == playerSymbol && board[1][1] == playerSymbol && board[2][0] == playerSymbol);
    }
}
ConsoleGame.main(null);
___________________________
|~~~~~~~~~~~~~~~~~~~~~~~~~|
|          Menu!          |
|~~~~~~~~~~~~~~~~~~~~~~~~~|
| 4 - Exit                |
| 1 - Rock Paper Scissors |
| 2 - Higher or Lower     |
| 3 - Tic Tac Toe         |
|_________________________|   

Choose an option.

-------------
|   |   |   | 
-------------
|   |   |   | 
-------------
|   |   |   | 
-------------
Player 1 (X), enter your move (row and column): 
-------------
|   |   |   | 
-------------
|   | X |   | 
-------------
|   |   |   | 
-------------
Player 2 (O), enter your move (row and column): 
-------------
| O |   |   | 
-------------
|   | X |   | 
-------------
|   |   |   | 
-------------
Player 1 (X), enter your move (row and column): 
Invalid move. Try again.
-------------
| O |   |   | 
-------------
|   | X |   | 
-------------
|   |   |   | 
-------------
Player 1 (X), enter your move (row and column): 
-------------
| O |   |   | 
-------------
|   | X |   | 
-------------
|   |   | X | 
-------------
Player 2 (O), enter your move (row and column): 
-------------
| O |   |   | 
-------------
|   | X | O | 
-------------
|   |   | X | 
-------------
Player 1 (X), enter your move (row and column): 
-------------
| O | X |   | 
-------------
|   | X | O | 
-------------
|   |   | X | 
-------------
Player 2 (O), enter your move (row and column): 
Invalid move. Try again.
-------------
| O | X |   | 
-------------
|   | X | O | 
-------------
|   |   | X | 
-------------
Player 2 (O), enter your move (row and column): 
-------------
| O | X | O | 
-------------
|   | X | O | 
-------------
|   |   | X | 
-------------
Player 1 (X), enter your move (row and column): 
-------------
| O | X | O | 
-------------
|   | X | O | 
-------------
|   | X | X | 
-------------
Player 1 (X) wins!
___________________________
|~~~~~~~~~~~~~~~~~~~~~~~~~|
|          Menu!          |
|~~~~~~~~~~~~~~~~~~~~~~~~~|
| 4 - Exit                |
| 1 - Rock Paper Scissors |
| 2 - Higher or Lower     |
| 3 - Tic Tac Toe         |
|_________________________|   

Choose an option.

Goodbye!

Hacks

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

  • Make RPS, Tic-Tack-Toe, and Higher Lower into different cells and objects. Document each cell in Jupyter Notebooks.
  • 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. Try to color differently.
  • Look over 10 units for College Board AP Computer Science A. In your reorganized code blocks and comments identify the Units of Code Used.
  • Answer why you think this reorganization and AP indetification is important?