如何检查用户输入是否与文本文件中的单词匹配?

时间:2020-11-08 23:11:42

标签: c# arrays dictionary unity3d user-input

using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Security.Cryptography.X509Certificates;
using UnityEngine;
using UnityEngine.UI;

public class LetterRandomiser : MonoBehaviour
{
    public char[] characters; 

    public Text textbox; 

    public InputField mainInputField;

    void Start() /*when the game starts*/
    {
        char c = characters[Random.Range(0,characters.Length)];
        textbox.text = c.ToString(); 
    }

    void Update()
    {
        string[] lines = System.IO.File.ReadAllLines(@"C:\Users\lluc\Downloads\words_alpha.txt");

        foreach (string x in lines)
        {
            if (Input.GetKeyDown(KeyCode.Return) 
                && mainInputField.text.Contains(textbox.text) == true
                && mainInputField.text.Contains(x) == true)
            {
                char c = characters[Random.Range(0, characters.Length)];
                textbox.text = c.ToString();
                mainInputField.text = "";
            }
            else if (Input.GetKeyDown(KeyCode.Return) 
                && mainInputField.text.Contains(textbox.text) == false
                && mainInputField.text.Contains(x) == false)
            {
                mainInputField.text = "";
            }
        }
    }
}

引用my game

没有错误,但是当我运行游戏时,它非常缓慢。我认为这是因为程序正在读取文本文件words_alpha.txt,其中包含所有英语单词。

但是,即使它很迟钝,当我输入一个完全随机的单词,该单词与文本文件中的任何单词都不匹配时,程序仍会接受该单词。

我的代码有问题...

我想要我的代码做什么?

  • 接受包含在输入框上方显示的随机生成字母的单词。 (有效)

  • 接受英语词典中的有效单词(在我的情况下,这是一个名为words_alpha.txt的文本文件的形式)。 (不起作用)

1 个答案:

答案 0 :(得分:1)

您应该从Start()方法而不是Update()读取文件,因为该文件只需要读取一次,而不是每一帧。这将消除延迟。

此外,您还在每个帧上循环浏览文件,这是不必要的。你应该移动

if (Input.GetKeyDown(KeyCode.Return))

foreach循环之外。并且您可能应该在该if语句中调用另一个函数。 Update()应该看起来更像是

void Update()
{
    if (Input.GetKeyDown(KeyCode.Return) &&
        mainInputField.text.Contains(textbox.text))
    {
        wordIsInFile(mainInputField.text);
        //Remaining code that you want to use
    }

    else
    {
        //whatever needs to be done in the else statement
    }
}

然后遍历数组的函数:

void wordIsInFile(string word)
{
    foreach (var item in lines)
    {
        if (word == item)
        {
            //Perform tasks on word
            //and whatever else
        }
    }
}

只需在string[] lines外部声明Start(),但在Start()中对其进行初始化,以确保它是一个全局变量。这样可以消除延迟,提高效率,因为除非按下KeyCode并且mainInputField包含一些字符串,否则您不会不断循环遍历数组。

相关问题