Java——猜拳游戏

package homework;

import java.util.Random;
import java.util.Scanner;

public class Homework14 {
    public static void main(String[] args) {
        Tom tom = new Tom();
        System.out.println("进入猜拳游戏,请输入(0~石头),(1~剪子),(2~布)");
        System.out.println("玩家输入:");
        //玩家输入
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        tom.setTomGuessNum(num);
        //电脑输入
        tom.computerNum();
        //判断输赢
        System.out.println(tom.vsComputer());
    }
}
class Tom{
    int tomGuessNum;    //玩家出拳
    int comGuessNum;    //电脑出拳

    public int getTomGuessNum(){
        return tomGuessNum;
    }
    public int getComGuessNum(){
        return comGuessNum;
    }
    //电脑随机数0~2,返回结果
    public int computerNum(){
        Random r = new Random();
        this.comGuessNum = r.nextInt(3);
        return comGuessNum;
    }
    //玩家猜拳
    public void setTomGuessNum(int tomGuessNum){
        if (tomGuessNum > 2 || tomGuessNum < 0){
            throw new IllegalArgumentException("数字输入错误!");
        }
        this.tomGuessNum = tomGuessNum;
    }


    public String panDuan_comGuessNum(int comGuessNum){
        String num = "";
        if (comGuessNum == 0){
            num = "石头";
        }else if (comGuessNum == 1){
            num = "剪子";
        }else if (comGuessNum == 2){
            num = "布";
        }
        return num;
    }
    public String panDuan_tomGuessNum(int tomGuessNum){
        String num = "";
        if (tomGuessNum == 0){
            num = "石头";
        }else if (tomGuessNum == 1){
            num = "剪子";
        }else if (tomGuessNum == 2){
            num = "布";
        }
        return num;
    }

    //判断输赢
    public String vsComputer(){
        String num_tom = panDuan_tomGuessNum(tomGuessNum);
        String num_com = panDuan_comGuessNum(comGuessNum);
        if (tomGuessNum == 0 && comGuessNum == 1){
            return "你赢了! \n玩家:石头\t电脑:剪子" ;
        }else if (tomGuessNum == 1 && comGuessNum == 2){
            return "你赢了! \n玩家:剪子\t电脑:布";
        }else if (tomGuessNum == 2 && comGuessNum == 0){
            return "你赢了! \n玩家:布\t电脑:石头";
        }else if (tomGuessNum == comGuessNum){
            return "平手\n玩家:" + num_tom + "\t电脑:" + num_com;
        }else{
            return "你输了!\n玩家:" + num_tom + "\t电脑:" + num_com;
        }
    }

}

posted @ 2023-05-16 00:53  Hello_world_名字被取了  Views(29)  Comments(0Edit  收藏  举报