import java.util.Scanner;
/**
* 猜拳游戏
*
* @author Administrator
*
*/
public class Main {
// 接收键盘输入
private Scanner s = new Scanner(System.in);
//定义全局常量和全局变量,类里各方法都能用到
// 剪刀
public static final int SCISSORS = 1;
// 石头
public static final int STONE = 2;
// 布
public static final int CLOTH = 3;
// 您胜利了,您出的是石头,电脑出的是剪刀
// 这里有3个是变数,所以声明三个变量
// 默认值输了
private String gameResult = "输了";
private String personText = "石头";
private String computerText = "石头";
/**
* 游戏开始
*/
private void startGame() {
System.out.println("猜拳游戏开始");
System.out.println("请出拳:(1.剪刀 2.石头 3.布)【输入数字为准】");
}
/**
* 玩游戏
*/
private void playGame() {
// 不包含3所以要加1,如2.9变为整数位2,2+1=3
int computer = (int) (Math.random() * 3 + 1);
// 会进入阻塞状态
int person = s.nextInt();
//&&的优先级比||高,所以不用加()
if (person == SCISSORS && computer == CLOTH
|| person == STONE && computer == SCISSORS
|| person == CLOTH && computer == STONE) {
gameResult = "胜利了";
} else if (person == computer) {
gameResult = "和局了";
}
// 用if一起判断也行,如if(person == SCISSORS || computer== SCISSORS)
switch (person) {
case SCISSORS:
personText = "剪刀";
break;
case CLOTH:
personText = "布";
}
switch (computer) {
case SCISSORS:
computerText = "剪刀";
break;
case CLOTH:
computerText = "布";
}
}
/**
* 游戏结束
*/
private void endGame() {
System.out.println("您" + gameResult + ",您出的是" + personText + ",电脑出的是"
+ computerText);
}
public static void main(String[] args) {
Main main = new Main();
main.startGame();
main.playGame();
main.endGame();
}
}
java猜拳游戏
最新推荐文章于 2023-03-05 15:51:16 发布