A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 冯佩 中级黑马   /  2013-1-19 01:57  /  2354 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

编写一个关于石头,剪刀,布的猜拳小游戏,力求代码简单优化。

评分

参与人数 1技术分 +1 收起 理由
Rancho_Gump + 1 赞一个!

查看全部评分

3 个回复

倒序浏览
本帖最后由 唐晓 于 2013-1-19 09:01 编辑

/*电脑随机出的石头剪子布*/
public class Computer {
                private String fist;
        public String getFist() {
                return fist;
        }

        public void setFist(String fist) {
                this.fist = fist;
        }
  
    //1 2 3   剪刀 石头 布
    public int ShowFist()
    {
        int result = -1;
        Random r=new Random();
      
                result= (int)(Math.random()*2+1);
               

        switch (result)
        {
            case 1:
                fist = "剪刀";
                break;
            case 2:
                fist = "石头";
                break;
            case 3:
                fist = "布";
                break;
        }

        return result;
    }
}


/*你自己的出拳*/
public class Player {
               private String fist;
              public String getFist() {
                return fist;
        }
        public void setFist(String fist) {
                this.fist = fist;
        }
    public int ShowFist(String fist)
    {
        this.fist = fist;
        int result = -1;
        if (fist == "剪刀")
        {
            result = 1;
        }
        else if(fist == "石头")
        {
            result = 2;
        }
        else if(fist == "布")
        {
            result = 3;
        }
        return result;
    }
}


/*判断输赢*/
public class Choose {
         public String Check(int player, int pc)
     {
         String result = "";
         int tmp = player - pc;
         if (tmp == 0)
         {
             result = "平手";
         }
         else if (tmp == 1 || tmp == -2)
         {
             result = "YOU WIN!";
         }
         else
         {
             result = "YOU LOST!";
         }
         return result;
     }
}


主程序运行:异常没处理,这里全部都抛出去了。
public static void main(String[] args) throws Exception{
                // TODO Auto-generated method stub
                System.out.println("请输入石头剪子或者布:");
                //创建输入流
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  
                String line = null;  
                //读取一行数据
                   line=br.readLine();
                   Check(line);
        }
         private static void Check(String fist)
     {
         Player player = new Player();
         player.ShowFist(fist);
         Computer pc = new Computer();
         pc.ShowFist();
         Choose j = new Choose();
         //判断输赢
       System.out.println("你出的是:"+player.getFist()+"----电脑出的是:"+pc.getFist()+"-----"+j.Check(player.ShowFist(fist), pc.ShowFist()));
         
     }

评分

参与人数 1技术分 +1 收起 理由
Rancho_Gump + 1 赞一个!

查看全部评分

回复 使用道具 举报
分析这个游戏包含三个类,玩家类,电脑类,游戏类
玩家类出1-3为石头,布剪刀,而电脑则用1-3随机数
的产生来确定出什么,游戏类将两个对象的结果进行
对比,在控制台输出结果即可
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马