This article describes the Java-implemented scissors stone cloth game. Share it for your reference, as follows:
ChoiceAnswer.java
public class ChoiceAnswer { String texts[] = { "Stone", "Scissors", "Cloth" }; int value; // 【1】Stone/t【2】Scissors/t【3】Cloth String getText() { return texts[value - 1]; } ChoiceAnswer(int value) { this.value = value; } /** * Return 0 means draw, return 1 means winning, return -1 means losing*/ int compTo(ChoiceAnswer c) { if (value == c.value) { return 0; } if (value + 1 == c.value || (value == 3 && c.value == 1)) { return 1; } return -1; }}Game.java
import java.util.Scanner;public class Game { void p(String s) { System.out.println(s); } void showWelcome() { p("Welcome・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・� userChoice > 3) { p("You entered incorrectly! Please re-enter!"); userChoice = Integer.parseInt(sc.nextLine()); } return new ChoiceAnswer(userChoice); } ChoiceAnswer getComputerChoice() { int computerChoice = (int) ((Math.random() * 3) + 1); return new ChoiceAnswer(computerChoice); } void showResult(ChoiceAnswer userChoice, ChoiceAnswer computerChoice) { int result = userChoice.compTo(computerChoice); if (result == 0) { System.out.println("Get, both you and the computer chose: " + userChoice.getText()); } else if (result == 1) { System.out.println("Congratulations, you won! You selected: " + userChoice.getText() + "; Computer selected: " + computerChoice.getText()); } else { System.out.println("Sorry, you lost! You selected: " + userChoice.getText() + "; Computer selected: " + computerChoice.getText()); } } void start() { showWelcome(); ChoiceAnswer userChoice = getUserChoice(); ChoiceAnswer computerChoice = getComputerChoice(); showResult(userChoice, computerChoice); } public static void main(String a[]) { System.out.println("Wulin.com test result:"); new Game().start(); }}Running results:
For more information about Java algorithms, readers who are interested in this site can view the topics: "Java Data Structure and Algorithm Tutorial", "Summary of Java Operation DOM Node Tips", "Summary of Java File and Directory Operation Tips" and "Summary of Java Cache Operation Tips"
I hope this article will be helpful to everyone's Java programming.