Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- namespace avstn.captcha
- {
- public delegate void CaptchaHandler();
- public class Captcha : MonoBehaviour
- {
- public int lengthCode;
- public string dictWord;
- public char dictSeparator;
- private int indexSymb = 0;
- private int countError = 0;
- private bool isDisplay = false;
- private string[] dictionary;
- private string[] captchaCode;
- public Texture bgImage;
- public Texture borderSymbImg;
- public Rect rBgImage;
- public Vector2 symbOffs;
- public Vector2 symbSize;
- public GUIStyle styleSymb;
- public event CaptchaHandler notifySuccess;
- public event CaptchaHandler notifyError;
- private const int MAX_ERROR_INPUT = 2;
- private void Awake()
- {
- dictionary = dictWord.Split(dictSeparator);
- if (lengthCode == 0)
- lengthCode = 5;
- }
- private void OnGUI()
- {
- if (isDisplay)
- {
- displayCaptcha();
- keyDownSymb();
- }
- }
- public void run(int length)
- {
- captchaCode = createCode(length, dictionary);
- isDisplay = true;
- }
- private void displayCaptcha()
- {
- GUI.DrawTexture(rBgImage, bgImage);
- for (int i = 0; i < captchaCode.Length; i++)
- GUI.Box(new Rect(new Vector2( symbOffs.x + (i * symbSize.x), symbOffs.y ), symbSize), captchaCode[i], styleSymb);
- GUI.DrawTexture(new Rect( new Vector2( symbOffs.x + (indexSymb * symbSize.x), symbOffs.y ), symbSize ), borderSymbImg);
- }
- private string[] createCode(int length, string[] dictionary)
- {
- string[] code = new string[length];
- for (int i = 0; i < length; i++)
- code[i] = dictionary[Random.Range(0, dictionary.Length - 1)];
- return code;
- }
- private void keyDownSymb()
- {
- Event ev = Event.current;
- if (ev.type == EventType.KeyDown)
- {
- KeyCode key = ev.keyCode;
- if (key != KeyCode.None)
- {
- if (key.ToString() == captchaCode[indexSymb])
- {
- indexSymb++;
- if (indexSymb >= lengthCode)
- {
- reset();
- if (notifySuccess != null)
- notifySuccess();
- }
- }
- else
- {
- countError++;
- if (countError >= MAX_ERROR_INPUT)
- {
- reset();
- if (notifyError != null)
- notifyError();
- }
- }
- }
- }
- }
- private void reset()
- {
- indexSymb = 0;
- countError = 0;
- isDisplay = false;
- }
- }
- }
- // example of work and how to connect to your game https://youtu.be/5I46ngrCX3k
- // my parametrs in inspector https://imgur.com/a/dF3YEAb
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement