C# 猜数字小游戏
来源:互联网 发布:linux 限制用户登录 编辑:程序博客网 时间:2024/06/14 15:37
不知道大家有没有玩过这个游戏,反正N多年前我在我爸爸的小灵通手机上玩过。正好不久前遇到关于这个游戏的代码练习题,自己写了一个。虽然写了出来但玩得明显没有以前好了。老了。。。
猜数字游戏具体要求:随机产生一个每位数互不相同的四位数,让用户来猜。用户输入一个四位数,与之进行比较,
如果有一个数字位置均相同,得到一个A,如果数字相同但位置不同得到一个B。如果猜对,则输出猜中。如果八次机会仍然没有猜中,游戏结束。比如产生的数字是1234,如果用用户输入3456,则显示0A2B,用户再输入5634,则显示2A0B......以此类推。
namespace OOPDAY01Practice { class Program { static void Main(string[] args) { GuessGame(); } Console.ReadKey(); } private static void GuessGame() { Random rdm = new Random(); int a, b, c, d; for (;;) {//随机产生互不相同的四个数字,组成一个四位数 a = rdm.Next(0, 10); b = rdm.Next(0, 10); c = rdm.Next(0, 10); d = rdm.Next(0, 10); if (a != b && a != c && a != d && b != c && b != d && c != d) break; } for (int k = 0; k < 8; k++) { Console.WriteLine("请输入一个四位数,还有{0}次机会", 8 - k); int input = int.Parse(Console.ReadLine()); int d1 = GetSingle(input), c1 = GetTens(input), b1 = GetHundreds(input), a1 = GetThousands(input); //判断,并输出结果 int Acount = 0, Bcount = 0; if (a1 == a) Acount++; else if (a1 == b || a1 == c || a1 == d) Bcount++; if (b1 == b) Acount++; else if (b1 == a || b1 == c || b1 == d) Bcount++; if (c1 == c) Acount++; else if (c1 == a || c1 == b || c1 == d) Bcount++; if (d1 == d) Acount++; else if (d1 == a || d1 == b || d1 == c) Bcount++; if (Acount == 4) { goto label;//如果完全数字以及位置完全相同,则跳出循环 } else Console.WriteLine("{0}A{1}B", Acount, Bcount); Console.WriteLine(); } Console.WriteLine("游戏结束,很遗憾没有猜中......答案是{0}{1}{2}{3}", a, b, c, d);//八次未猜中,游戏结束,并显示答案。 goto label2; label: Console.WriteLine("恭喜猜中!答案是{0}{1}{2}{3}", a, b, c, d);//猜中,显示答案。 label2: Console.ReadKey(); } //获取一个四位数的个位数 public static int GetSingle(int i) { return i % 10; } //获取一个四位数的十位数 public static int GetTens(int i) { return (i % 100) / 10; } //获取一个四位数的百位数 public static int GetHundreds(int i) { return (i%1000) / 100; } //获取一个四位数的千位数 public static int GetThousands(int i) { return (i - i % 1000) / 1000; }
}纯属交流。如有bug或者需要改进的地方,欢迎指出
阅读全文
1 0
- c#猜数字小游戏
- C#猜数字小游戏
- c#猜数字小游戏
- C# 猜数字小游戏
- 猜数字小游戏
- 猜数字小游戏
- 猜数字小游戏(MiniGUI)
- 猜数字小游戏
- 猜数字小游戏
- Flex:猜数字小游戏
- 猜数字的小游戏~
- 猜数字 小游戏
- 猜数字的小游戏
- shell猜数字小游戏
- 猜数字小游戏
- 猜数字小游戏
- 猜数字小游戏 v1
- 猜数字小游戏 v3
- POJ 2385 Apple Catching
- [SCOI2007] BZOJ 1072 排列perm
- IO系列
- php基本语句
- Sample Clock Based On UWP
- C# 猜数字小游戏
- pybitcointools源码分析之由私钥获取公钥
- Java的21个核心技术点,你知道吗?
- Android第一天
- 面试总结之守护进程,僵尸进程和孤儿进程
- 欢迎使用CSDN-markdown编辑器
- 搭建VUE脚手架的时候,fsevents报错问题;
- CSS3 linear-gradient实现三角形
- 对2017年8月26日(北京时间17日)梅威瑟和麦格雷戈跨界大战的预测