首页 > 代码库 > 人机猜拳小游戏

人机猜拳小游戏

朋友做的小案例,结构很清晰

void Main(){    Game gmr = new Game();    gmr.Init();    gmr.Playing();    gmr.ShowResult();    Console.WriteLine ("程序结束");}//玩家类class Player{    //玩家昵称    public string Name { get; set; }    //积分    public int Score { get; set; }        //出拳方法    public int ShowFist()    {        Console.WriteLine ("请出拳!1.石头 2.剪刀 3.布");        int fist = Convert.ToInt32(Console.ReadLine());        return fist;    }}//电脑类class Computer{    //电脑积分    public int Score { get; set; }    //出拳方法    public int ShowFist()    {        Random rdm = new Random();        int fist = rdm.Next(1,4);        return fist;    }}class Game{    //玩家    Player player;    //电脑    Computer computer;    //主界面    public void Init()    {        Console.WriteLine ("******************************");        Console.WriteLine ("*****欢迎进入人机猜拳游戏*****");        Console.WriteLine ("******************************");        player = new Player();        computer = new Computer();        Console.WriteLine ("请输入昵称:");        player.Name = Console.ReadLine();        Console.WriteLine ("准备好了吗?游戏开始...");    }        //积分计算    public void CalcScore(int person,int cptr)    {        int result = person- cptr;        if (result==0)        {            Console.WriteLine ("哈~和局");        }else if (result==-1 || result == 2)        {            Console.WriteLine ("^_^你赢了!!加一分!");            player.Score+=1;        }else{            Console.WriteLine ("-_-!电脑赢咯~~");            computer.Score+=1;        }    }        public void Trans(string obj,int fist)    {        string result = obj+" 出拳:";        switch (fist)        {            case 1:                result+="石头";                break;            case 2:                result+="剪刀";                break;            case 3:                result+="";                break;        }        Console.WriteLine (result);    }        public void Playing()    {        string answer = string.Empty;        do{            int playFist = player.ShowFist();            Trans(player.Name,playFist);            int cptrFist = computer.ShowFist();            Trans("电脑",cptrFist);            CalcScore(playFist,cptrFist);            Console.WriteLine ("再来?(y/n)");            answer = Console.ReadLine();        }while(answer == "y");    }        public void ShowResult()    {        Console.WriteLine ("最终比分:");        Console.WriteLine ("您的分数:{0}",player.Score);        Console.WriteLine ("电脑分数:{0}",computer.Score);        int result = player.Score - computer.Score;        if (result > 0)        {            Console.WriteLine ("幸运之神太眷顾你了吧!!");        }else if(result == 0)        {            Console.WriteLine ("呀,不相上下哦~真是强劲的对手呢!");        }else        {            Console.WriteLine ("不服气吗?欢迎再来挑战哦~");        }    }}

 

人机猜拳小游戏