猜字谜小游戏编程

简介: 新建一个类 using System; namespace 猜数字小游戏 {      public class Play     {          public void play()          {              Random r = new Random();              int i = r.

新建一个类

using System;

namespace 猜数字小游戏
{
     public class Play
    {
         public void play()
         {
             Random r = new Random();
             int i = r.Next(0, 100);
             int j;
             int n = 1;
             Flag:
             Console.WriteLine("请猜猜它是多少[温馨提示:0-100之间]:");
             do
             {
                 j = int.Parse(Console.ReadLine());
                 if (j == i)
                 {
                     Console.WriteLine("恭喜你在第{0}次猜对了", n);
                     Console.WriteLine("还想在试一次吗?确定(Y),退出(N):");
                     char k;
                     k = Convert.ToChar(Console.ReadLine().ToUpper()); //转化成大写字母
                     if (k == 'Y')
                     {
                         Console.Clear();
                         goto Flag; //利用了一个Goto语句
                     }
                     else
                     {
                         Console.Clear();
                         Console.WriteLine("-------------------------------------");
                         Console.WriteLine("            欢迎您再次使用!         ");
                         Console.WriteLine("-------------------------------------");
                         break;
                     }
                 }
                 else
                 {
                     if (j > i)
                     {
                         Console.WriteLine("第{0}次,猜大了", n);
                         Console.WriteLine("再试试:");
                     }
                     else
                     {
                         Console.WriteLine("第{0}次,猜小了", n);
                         Console.WriteLine("再试试:");
                     }
                 }
                 n++;
             } while (j != i);
         }
    }
}
然后创建主程序

using System;

namespace 猜数字小游戏
{
    class Program
    {
        static void Main(string[] args)
        {
            Random rd = new Random();
            Console.BackgroundColor=(System.ConsoleColor.Red);//生成随机背景颜色
            Console.ForegroundColor = (System.ConsoleColor)rd.Next(9,15);//生成随机文字颜色
            Play p=new Play();
            p.play();
        }
       
    }
}

 

相关文章