练习 - 完成创建可重用方法的挑战
代码挑战将强化所学知识,有助于在继续操作之前增强自信。
此挑战的重点是修改代码,使其可重复使用,并且可随时执行。
算命
你正在帮助开发一个大型多玩家角色扮演游戏。 每个玩家都有一个运气统计数据,可能会影响他们找到稀有宝藏的几率。 每天,玩家可以与游戏内的算命师交谈,算命师会揭示其运气统计数据是高、低还是一般。
游戏当前具有生成玩家时运的代码,但无法重复使用。 你的任务是创建一个可随时调用的 tellFortune 方法,并将现有逻辑替换为对该方法的调用。
在此挑战中,你将获得一些起始代码。 必须决定如何创建和调用 tellFortune 方法。
代码挑战:创建可重用的方法
在开始的代码中,有一个泛型文本数组,后跟“好”、“坏”和“一般”文本数组。 根据 luck 的值,选择其中一个数组与泛型文本一起显示。
你的挑战是创建一个可重用的方法,随时打印玩家的时运。 该方法应包含提供的代码中已存在的逻辑。
确保在 Visual Studio Code 中打开了一个空的 Program.cs 文件。
如有必要,请打开 Visual Studio Code,然后完成以下步骤,以在编辑器中准备 Program.cs 文件:
在“文件”菜单中,选择“打开文件夹”。
使用“打开文件夹”对话框导航到 CsharpProjects 文件夹,然后打开。
在 Visual Studio Code 的“资源管理器”窗格中,选择“Program.cs”。
在 Visual Studio Code 的“选择”菜单上,选择“全选”,然后按 Delete 键。
复制以下代码并将其粘贴到编辑器中:
Random random = new Random(); int luck = random.Next(100); string[] text = {"You have much to", "Today is a day to", "Whatever work you do", "This is an ideal time to"}; string[] good = {"look forward to.", "try new things!", "is likely to succeed.", "accomplish your dreams!"}; string[] bad = {"fear.", "avoid major decisions.", "may have unexpected outcomes.", "re-evaluate your life."}; string[] neutral = {"appreciate.", "enjoy time with friends.", "should align with your values.", "get in tune with nature."}; Console.WriteLine("A fortune teller whispers the following words:"); string[] fortune = (luck > 75 ? good : (luck < 25 ? bad : neutral)); for (int i = 0; i < 4; i++) { Console.Write($"{text[i]} {fortune[i]} "); }更新代码以使用方法来显示时运。
使用学到的有关创建和调用方法的知识来完成更新。
通过更改
luck的值并再次调用方法来测试代码。验证代码生成以下消息之一:
A fortune teller whispers the following words: You have much to look forward to. Today is a day to try new things! Whatever work you do is likely to succeed. This is an ideal time to accomplish your dreams!A fortune teller whispers the following words: You have much to appreciate. Today is a day to enjoy time with friends. Whatever work you do should align with your values. This is an ideal time to get in tune with nature.A fortune teller whispers the following words: You have much to fear. Today is a day to avoid major decisions. Whatever work you do may have unexpected outcomes. This is an ideal time to re-evaluate your life.
无论是遇到问题而需要查看解决方案,还是成功完成操作,都请继续查看此挑战的一种解决方案。