猜数字游戏类C#源代码(封装改进版)

来源:互联网 发布:武汉软件职业工程学院 编辑:程序博客网 时间:2024/04/29 23:59
猜数游戏:随机生成一个整数(范围:[100-999]),请用户从键盘上输入数据猜想设值的数是什么,告诉用户是猜大了还是小了。10次以内猜对,用户获胜。否则,告诉用户设置的数据是什么。有源代码下载。
using System;using System.Collections.Generic;namespace Keleyi.Com.Game{/// /// 猜数字游戏类 www.keleyi.com/// class KeleyiNumberGuess{string _gameNote;public string GameNote{get { return _gameNote; }}string _tips;public string Tips{get { return _tips; }}int _gameResult;public int GameResult{get { return _gameResult; }}int _theNumber;int _guessedTimes;int _maxTimes = 10;int _minNumber = 100, _maxNumber = 999;public int MaxNumber{get { return _maxNumber; }}public int MinNumber{get { return _minNumber; }}public KeleyiNumberGuess(){Init();}public void ReStart(){Init();}private void Init(){_gameResult = 0;_guessedTimes = 0;Random random_keleyi_com = new Random();_theNumber = random_keleyi_com.Next(_minNumber, _maxNumber);_gameNote = "柯乐义请您玩猜数字游戏。\r\n后台已经随机生成了一个" + _minNumber.ToString()+ "到" + _maxNumber.ToString() + "之间的数字。\r\n如果您能在" + _maxTimes.ToString()+ "次之内猜出这个数字,则游戏成功,否则失败。\r\n请开始吧。";}public int Guess(int n){_guessedTimes++;if (_guessedTimes > _maxTimes){_gameResult = -1;_tips = "您已经猜多于"+_maxNumber.ToString()+"了";return -2;}if (n == _theNumber){_tips = "恭喜您猜对了!您刚才猜的数字是" + n.ToString() + "。您共猜了" + _guessedTimes.ToString() + "次。";_gameResult = 1;return 0;}else if (n > _theNumber){_tips = "您刚才猜的数字是" + n.ToString() + ",该数字大了。您已经猜了" + _guessedTimes.ToString() + "次。";if (_guessedTimes >= _maxTimes){_tips = "游戏失败。要猜的数字是:" + _theNumber.ToString() + "。" + _tips;_gameResult = -1;}return 1;}else{_tips = "您刚才猜的数字是" + n.ToString() + ",该数字小了。您已经猜了" + _guessedTimes.ToString() + "次。";if (_guessedTimes >= _maxTimes){_tips = "游戏失败。要猜的数字是:"+_theNumber.ToString()+"。" + _tips;_gameResult = -1;}return -1;}}}}




实例源代码下载 点击download下载


本文转载自柯乐义http://www.keleyi.com/dev/a10d692967436351.htm
原创粉丝点击