21xrx.com
2024-11-22 06:48:19 Friday
登录
文章检索 我的文章 写文章
探索Java世界中的好玩代码
2023-06-12 00:42:06 深夜i     --     --
Java游戏 “二十四点”游戏 Java实现

Java作为一种强大、稳定、高效的编程语言,除了被广泛应用于企业级应用开发、桌面应用程序的编写和手机软件开发等诸多领域之外,你可能还不知道,Java也有许多好玩的代码。这些好玩的代码可能帮助你更好地理解Java语言的特性,也能带给你极佳的开发体验。

下面,我们就来一起探索一些好玩的Java代码案例。

1. 使用Java实现“二十四点”游戏

代码示例:


import java.util.Random;

import java.util.Scanner;

public class TwentyFourPointGame {

  public static boolean play() {

    Scanner input = new Scanner(System.in);

    Random random = new Random();

    int[] arr = new int[4];

    char[] op = new char[3];

    for (int i = 0; i < arr.length; i++) {

      arr[i] = random.nextInt(9) + 1;

    }

    for (int i = 0; i < op.length; i++) {

      int temp = random.nextInt(4) + 1;

      switch (temp) {

        case 1:

          op[i] = '+';

          break;

        case 2:

          op[i] = '-';

          break;

        case 3:

          op[i] = '*';

          break;

        case 4:

          op[i] = '/';

          break;

      }

    }

    System.out.println("请算出下列四个数的运算结果(用括号括起来)");

    System.out.println(arr[0] + " " + op[0] + " " + arr[1] + " " + op[1] + " " +

        arr[2] + " " + op[2] + " " + arr[3]);

    String result = input.nextLine();

    double answer = 0;

    try {

      answer = Double.parseDouble(result);

    } catch (NumberFormatException e)

      return false;

    

    double value = compute(arr, op);

    double delta = Math.abs(answer - value);

    if (delta < 0.0001) {

      System.out.println("Congratulations! You got it!");

      return true;

    } else {

      System.out.println("Oops! The correct answer is " + value);

      return false;

    }

  }

  public static double compute(int[] arr, char[] op) {

    double res = arr[0];

    for (int i = 0; i < op.length; i++) {

      switch (op[i]) {

        case '+':

          res += arr[i + 1];

          break;

        case '-':

          res -= arr[i + 1];

          break;

        case '*':

          res *= arr[i + 1];

          break;

        case '/':

          res /= arr[i + 1];

          break;

      }

    }

    return res;

  }

  public static void main(String[] args) {

    while (true) {

      if (play())

        break;

      

    }

  }

}

这是一个用Java语言实现的“二十四点”游戏。运行程序后,程序会先随机生成四个1-9之间的整数,以及三个运算符(分别为加、减、乘、除)。玩家需要根据给出的四个数和三个运算符,算出一个运算结果,并在命令行输入。

如果玩家输入的结果与预期结果一致,则程序会提示答对了;如果不一致,则会提示正确答案。

这个程序不仅能提升玩家运算能力,还能增加Java语言的练习经验和代码实现能力。

2. 使用Java打印出指定格式的数字三角形

代码示例:


import java.util.Scanner;

public class PrintNumberTriangle {

  public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    System.out.println("请输入要打印的数字三角形的行数:");

    int numRows = scanner.nextInt();

    for (int i = 1; i <= numRows; i++) {

      for (int j = i; j < numRows; j++) {

        System.out.print(" ");

      }

      for (int j = 1; j <= 2 * i - 1; j++) {

        System.out.print(i);

      }

      System.out.println();

    }

  }

}

这是一个使用Java语言实现的打印数字三角形的程序。运行程序后,程序会提示用户输入要打印的数字三角形的行数。输入行数后,程序就会自动生成一个数字三角形,如下所示:


请输入要打印的数字三角形的行数:

5

  1

  222

 33333

4444444

555555555

通过这个程序,我们不仅能加深对Java语言循环结构的理解,还能培养代码实现能力和数学思维能力。

关键词:Java打印数字三角形、循环结构、Java实现

3. 使用Java制作命令行版“扫雷”游戏

代码示例:


import java.util.Scanner;

public class MineSweeper {

  private static final int EASY_MODE = 8;

  private static final int MEDIUM_MODE = 12;

  private static final int HARD_MODE = 16;

  private static final int MINE_NUM_EASY = 10;

  private static final int MINE_NUM_MEDIUM = 20;

  private static final int MINE_NUM_HARD = 30;

  private static final int UNKNOWN = -1;

  private static final int MINE = -2;

  private static final int OPENED = -3;

  private int[][] board;

  private boolean[][] opened;

  private int mode;

  private int mineNum;

  private int currentMineNum;

  private boolean gameOver;

  public MineSweeper() {

    this.board = new int[HARD_MODE][HARD_MODE];

    this.opened = new boolean[HARD_MODE][HARD_MODE];

    this.mode = EASY_MODE;

    this.mineNum = MINE_NUM_EASY;

    this.currentMineNum = this.mineNum;

    this.gameOver = false;

  }

  public void run() {

    Scanner scanner = new Scanner(System.in);

    while (!gameOver) {

      System.out.println("当前地图:");

      printBoard();

      System.out.println("请选择操作:");

      System.out.println("1. 打开方块");

      System.out.println("2. 标记地雷");

      int option = scanner.nextInt();

      System.out.println("请选择坐标(格式为:行 列):");

      int row = scanner.nextInt();

      int col = scanner.nextInt();

      switch (option) {

        case 1:

          if (opened[row][col]) {

            System.out.println("该方块已打开,请重新选择操作。");

            break;

          }

          if (board[row][col] == MINE) {

            System.out.println("Game over,您踩到地雷了!");

            gameOver = true;

          } else {

            open(row, col);

            checkWin();

          }

          break;

        case 2:

          mark(row, col);

          break;

        default:

          System.out.println("选项不存在,请重新选择。");

      }

    }

    System.out.println("游戏结束。");

  }

  private void printBoard() {

    for (int i = 0; i < mode; i++) {

      for (int j = 0; j < mode; j++) {

        int cell = UNKNOWN;

        if (opened[i][j]) {

          cell = board[i][j];

        }

        if (cell == UNKNOWN) {

          System.out.print("● ");

        } else if (cell == MINE) {

          System.out.print("✹ ");

        } else if (cell == OPENED) {

          System.out.print(" ");

        } else {

          System.out.print(cell + " ");

        }

      }

      System.out.println();

    }

  }

  private void generateMines() {

    currentMineNum = mineNum;

    while (currentMineNum > 0) {

      int row = (int) (Math.random() * mode);

      int col = (int) (Math.random() * mode);

      if (board[row][col] != MINE) {

        board[row][col] = MINE;

        currentMineNum--;

      }

    }

  }

  private void mark(int row, int col) {

    if (opened[row][col]) {

      System.out.println("该方块已打开,无法标记。");

      return;

    }

    if (board[row][col] == MINE) {

      currentMineNum++;

      board[row][col] = UNKNOWN;

      System.out.println("取消标记成功。");

    } else {

      if (currentMineNum == 0) {

        System.out.println("已经标记了所有的地雷,无法再标记。");

        return;

      }

      currentMineNum--;

      board[row][col] = MINE;

      System.out.println("标记成功。");

    }

  }

  private void open(int row, int col) {

    if (opened[row][col])

      return;

    

    opened[row][col] = true;

    int val = getCellValue(row, col);

    if (val == 0) {

      openNeighborhood(row, col);

    } else {

      board[row][col] = val;

    }

  }

  private void openNeighborhood(int row, int col) {

    int[] rowOff = new int[] -1;

    int[] colOff = new int[] 1;

    for (int i = 0; i < rowOff.length; i++) {

      int r = row + rowOff[i];

      int c = col + colOff[i];

      if (isValidCell(r, c) && !opened[r][c]) {

        open(r, c);

      }

    }

  }

  private int getCellValue(int row, int col) {

    if (board[row][col] == MINE)

      return MINE;

    

    int cnt = 0;

    int[] rowOff = new int[] 0;

    int[] colOff = new int[]0;

    for (int i = 0; i < rowOff.length; i++) {

      int r = row + rowOff[i];

      int c = col + colOff[i];

      if (isValidCell(r, c) && board[r][c] == MINE) {

        cnt++;

      }

    }

    return cnt;

  }

  private boolean isValidCell(int row, int col)

    return row >= 0 && row < mode && col >= 0 && col < mode;

  

  private void checkWin() {

    boolean win = true;

    for (int i = 0; i < mode && win; i++) {

      for (int j = 0; j < mode && win; j++) {

        if (!opened[i][j] && board[i][j] != MINE)

          win = false;

        

      }

    }

    if (win) {

      System.out.println("Congratulations! You win!");

      gameOver = true;

    }

  }

  public static void main(String[] args) {

    MineSweeper game = new MineSweeper();

    game.generateMines();

    game.run();

  }

}

这是一个使用Java语言实现的命令行版“扫雷”游戏。该程序将地图分为三个大小不同的难度等级(分别为简单、普通、困难),并在地图中随机生成一定数量的地雷。运行程序后,用户可以通过命令行选择行和列来操作。

该程序不仅能提升Java语言的练习经验和代码实现能力,还能增强逻辑思维和空间思维能力。

关键词:Java命令行、扫雷游戏、Java实现

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章