簡體   English   中英

如何檢查用戶輸入是否與文本文件中的單詞匹配?

[英]How to check whether user input matches with a word from a text file?

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 = "";
            }
        }
    }
}

參考我的游戲

沒有錯誤,但是當我運行游戲時,它非常滯后。 我認為這是因為程序正在讀取包含所有英文單詞的文本文件 words_alpha.txt。

然而,即使它是滯后的,當我輸入一個與文本文件中的任何詞都不匹配的完全隨機的詞時,程序仍然會接受該詞。

我的代碼有問題...

我想讓我的代碼做什么?

  • 接受包含輸入框上方顯示的隨機生成字母的單詞。 (有效)

  • 接受英語詞典中的有效單詞(在我的例子中,這是一個名為 words_alpha.txt 的文本文件形式)。 (這不起作用)

您應該從Start()方法而不是Update() Start()方法讀取文件,因為文件只需要讀取一次,而不是每幀。 這將消除滯后。

此外,您還在不必要的每一幀上循環瀏覽文件。 你應該搬家

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
        }
    }
}

只需在Start()之外聲明string[] lines ,但在Start()對其進行初始化,以確保它是一個全局變量。 這將消除延遲,並提高效率,因為除非按下KeyCode並且mainInputField包含一些字符串,否則您不會不斷循環遍歷數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM