首页 > 代码库 > 小游戏●两人对战
小游戏●两人对战
利用结构体编写的两人对战小游戏,代码及简要分析如下
1 public struct Fighter 2 { 3 public string name; 4 public int blood; 5 public int attack; 6 public int defense; 7 public int hit; 8 public int hide; 9 }10 11 12 static void Main(string[] arge)13 {14 15 //定义一组对手16 Fighter f1 = new Fighter();17 Fighter f2 = new Fighter();18 Console.Write("第一位:");19 f1.name = Console.ReadLine();20 Console.Write("第二位:");21 f2.name = Console.ReadLine();22 23 24 //利用名字的前两个字,创建随机数生成器25 int r1 = (int)Convert.ToChar(f1.name.Substring(0, 1)) + (int)Convert.ToChar(f1.name.Substring(1, 1));26 int r2 = (int)Convert.ToChar(f2.name.Substring(0, 1)) + (int)Convert.ToChar(f2.name.Substring(1, 1));27 Random rand1 = new Random(r1);28 Random rand2 = new Random(r2);29 30 f1.blood = 100; //对战双方初始血量都为10031 f2.blood = 100;32 33 for (int i = 1; (f1.blood > 0 && f2.blood > 0); i++)34 {35 //利用各自创建的随机数生成器赋值攻击力、防御力、命中、躲避36 System.Threading.Thread.Sleep(2000);37 f1.attack = rand1.Next(30);38 f1.defense = rand1.Next(10);39 f1.hit = rand1.Next(100);40 f1.hide = rand1.Next(100);41 42 f2.attack = rand2.Next(30);43 f2.defense = rand2.Next(10);44 f2.hit = rand2.Next(100);45 f2.hide = rand2.Next(100);46 47 if (f1.hit <= 95 && f2.hide <= 95) //都设95%命中,5%躲避,判断是否命中48 {49 Console.WriteLine(f1.name + "发起攻击……");50 if (f1.attack > f2.defense) //判断2号本次防御力是否高于1号攻击力51 {52 f2.blood = f2.blood - f1.attack + f2.defense;53 Console.WriteLine("{0}被打掉了{1}血!", f2.name, (f1.attack - f2.defense));54 }55 else56 Console.WriteLine(f2.name + "挡住了攻击!");57 if (f2.blood <= 0) //假如2号血量掉到0,游戏结束58 {59 break;60 }61 }62 else if (f1.hit <= 95 && f2.hide > 95) //判断1号攻击未失误时,2号是否躲避63 {64 Console.WriteLine(f2.name + "躲开了攻击!");65 }66 else67 Console.WriteLine(f1.name + "攻击失误!");68 69 if (f2.hit <= 95 && f1.hide <= 95) //都设95%命中,5%躲避70 {71 Console.WriteLine(f2.name + "发起攻击……");72 if (f2.attack > f1.defense)73 {74 f1.blood = f1.blood - f2.attack + f1.defense;75 Console.WriteLine("{0}被打掉了{1}血!", f1.name, (f2.attack - f1.defense));76 }77 else78 Console.WriteLine(f1.name + "挡住了攻击!");79 if (f1.blood <= 0)80 {81 break;82 }83 }84 else if (f2.hit <= 95 && f1.hide > 95)85 {86 Console.WriteLine(f1.name + "躲开了攻击!");87 }88 else89 Console.WriteLine(f1.name + "攻击失误!");90 Console.WriteLine("{0}剩余血量{1},{2}剩余血量{3}", //每回合结束,显示双方剩余血量91 f1.name, (f1.blood <= 0 ? 0 : f1.blood),92 f2.name, (f2.blood <= 0 ? 0 : f2.blood) + "\n");93 94 }95 Console.WriteLine("{0}剩余血量{1},{2}剩余血量{3}", //游戏结束,显示双方剩余血量96 f1.name, (f1.blood <= 0 ? 0 : f1.blood),97 f2.name, (f2.blood <= 0 ? 0 : f2.blood));98 99 }
执行过程截图
小游戏●两人对战
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。