C#实现简单打字小游戏攻略
思路分析
实现打字游戏需要以下步骤:
- 随机生成单词:从一个单词列表中选择一个单词,或者生成一个随机单词;
- 显示单词并记录开始时间;
- 接收用户输入并计算打字速度;
- 将结果显示出来;
示例1:从单词列表中选择一个单词
- 首先定义一个单词列表:
string[] words = { "hello", "world", "welcome", "programming", "language" };
- 在游戏开始时,从单词列表中随机选择一个单词:
Random random = new Random();
string word = words[random.Next(0, words.Length)];
- 显示所选单词并记录开始时间:
Console.WriteLine("Type the word: " + word);
DateTime startTime = DateTime.Now;
- 接收用户输入并计算打字速度:
string input = Console.ReadLine();
TimeSpan duration = DateTime.Now - startTime;
double seconds = duration.TotalSeconds;
int speed = (int)(((double)word.Length / seconds) * 60);
- 最后将结果显示出来:
Console.WriteLine("You typed {0} characters in {1:0.00} seconds. Your speed is {2} characters per minute.", word.Length, seconds, speed);
示例2:生成随机单词
- 生成随机单词需要一个随机字符生成器:
Random random = new Random();
string chars = "abcdefghijklmnopqrstuvwxyz";
- 然后从随机字符生成器中随机选择字符,构建一个随机单词:
int length = 5;
string word = "";
for (int i = 0; i < length; i++)
{
int index = random.Next(0, chars.Length);
word += chars[index];
}
- 显示随机单词并记录开始时间:
Console.WriteLine("Type the word: " + word);
DateTime startTime = DateTime.Now;
-
接收用户输入并计算打字速度,方法同示例1。
-
最后将结果显示出来,方法同示例1。
完整代码
using System;
namespace TypingGame
{
class Program
{
static void Main(string[] args)
{
// sample 1: from word list
string[] words = { "hello", "world", "welcome", "programming", "language" };
Random random = new Random();
string word = words[random.Next(0, words.Length)];
Console.WriteLine("Type the word: " + word);
DateTime startTime = DateTime.Now;
string input = Console.ReadLine();
TimeSpan duration = DateTime.Now - startTime;
double seconds = duration.TotalSeconds;
int speed = (int)(((double)word.Length / seconds) * 60);
Console.WriteLine("You typed {0} characters in {1:0.00} seconds. Your speed is {2} characters per minute.", word.Length, seconds, speed);
// sample 2: generate random word
string chars = "abcdefghijklmnopqrstuvwxyz";
int length = 5;
word = "";
for (int i = 0; i < length; i++)
{
int index = random.Next(0, chars.Length);
word += chars[index];
}
Console.WriteLine("Type the word: " + word);
startTime = DateTime.Now;
input = Console.ReadLine();
duration = DateTime.Now - startTime;
seconds = duration.TotalSeconds;
speed = (int)(((double)word.Length / seconds) * 60);
Console.WriteLine("You typed {0} characters in {1:0.00} seconds. Your speed is {2} characters per minute.", word.Length, seconds, speed);
}
}
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#实现简单打字小游戏 - Python技术站