⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 rspgame.java

📁 Java经典例程 从外国一大学计算机教授出版物下载的代码 经典
💻 JAVA
字号:
import java.io.*;
import javagently.*;
import java.util.Random;

class RSPGame {

  /* The RSP Game class      by J M Bishop Aug 1996
   * ------------------      Java 1.1  Dec 1997
   *                         updated June 2000
   * offers four methods:
   * startGame, getmyChoice, getyourChoice and Winner.
   * getyourChoice returns a character so
   * that we can stop if it was a Q.
   * Illustrates typed methods, switches, loops, Math.random
   * and private members
   */


  private int mychoice;
  private char yourchoice; // R S P
  private Random dice;
  private Stream in = new Stream(System.in);

  void startGame () throws IOException {
    System.out.println("Let's play RSP");
    System.out.println("To show I'm not cheating, start me off by"+
      " giving me a number.");
    dice = new Random(in.readInt());
  }

  void winner () {
    // In the calls to report, the first parameter is my choice.
    // The second one is the choice that I could beat.
    // The third one is the choice that would beat me.

    switch (mychoice) {
      case 0 : report ('R','S','P'); break;
      case 1 : report ('S','P','R'); break;
      case 2 : report ('P','R','S'); break;
    }
  }

  void makemyChoice () {
    // nextInt returns an integer in its full range.
    // We have to reduce it to 0, 1, 2
    mychoice = Math.abs(dice.nextInt()) % 3;
  }

  char getyourChoice () throws IOException {
    do {
      System.out.print("Your choice of R S P or Q to stop ?");
      yourchoice = Character.toUpperCase(
           in.readString().charAt(0));
    }  while (yourchoice !='R' && yourchoice != 'S'
              && yourchoice != 'P' && yourchoice != 'Q');
    if (yourchoice != 'Q') {
      System.out.print("You drew "+yourchoice+" and ");
    }
    return yourchoice;
  }

  private void report (char me, char Iwin, char youWin) {
    System.out.println("I drew a " + me);
    if (yourchoice == Iwin) {
      System.out.println("I win");
    } else
    if (yourchoice == youWin) {
      System.out.println("You win");
    }
    else {
      System.out.println("It's a draw");
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -