You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
97 lines
2.8 KiB
97 lines
2.8 KiB
package main
|
|
|
|
import (
|
|
"github.com/veandco/go-sdl2/sdl"
|
|
"strings"
|
|
)
|
|
|
|
var charWidth int32
|
|
var charHeight int32
|
|
|
|
var printables string
|
|
|
|
func Init() {
|
|
tmp, _, _ := font.SizeUTF8("W")
|
|
charWidth = int32(tmp)
|
|
charHeight = int32(font.Height())
|
|
printables = "abcdefghijklmnopqrstuvwxyz1234567890"
|
|
}
|
|
|
|
type keyField struct {
|
|
charLen int
|
|
passwd string
|
|
onSuccess func()
|
|
onFailure func(bool)
|
|
enteredChar []string
|
|
bkTimer int
|
|
}
|
|
|
|
func createKeyField(passwd string, onSuccess func(), onFailure func(bool)) *keyField {
|
|
charLen := len(passwd)
|
|
fld := keyField{charLen, passwd, onSuccess, onFailure, []string{}, 0}
|
|
RegisterKeypressHandler(fld.keyListener)
|
|
return &fld
|
|
}
|
|
|
|
func (k *keyField) Blit(renderer *sdl.Renderer) {
|
|
if k.bkTimer / 10 % 2 == 0 {
|
|
blockSize := charWidth + 30
|
|
width := int32(k.charLen) * (blockSize)
|
|
height := charHeight + 5 + 3
|
|
leftREF := 1920 / 2 - width / 2
|
|
topREF := 1080 - height - 80
|
|
fieldRect := &sdl.Rect{leftREF, topREF, width, height}
|
|
|
|
fieldSurface, _ := sdl.CreateRGBSurface(0, width, height, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000)
|
|
defer fieldSurface.Free()
|
|
|
|
for i := 0; i < len(k.enteredChar); i++ {
|
|
char, e := font.RenderUTF8Blended(k.enteredChar[i], sdl.Color{20, 20, 0, 255})
|
|
if e == nil {
|
|
pos := &sdl.Rect{int32(i + 1) * blockSize - blockSize / 2 - char.W / 2, 0, char.W, char.H}
|
|
char.Blit(nil, fieldSurface, pos)
|
|
defer char.Free()
|
|
}
|
|
}
|
|
|
|
texture, _ := renderer.CreateTextureFromSurface(fieldSurface)
|
|
defer texture.Destroy()
|
|
renderer.Copy(texture, nil, fieldRect)
|
|
|
|
renderer.SetDrawColor(20, 20, 0, 255)
|
|
for i := 0; i < k.charLen; i++ {
|
|
renderer.DrawLine(leftREF + 15 + (int32(i) * (blockSize)), topREF + height - 1, leftREF + int32(i + 1) * (blockSize) - 15, topREF + height - 1)
|
|
}
|
|
}
|
|
if k.bkTimer > 0 {
|
|
k.bkTimer--
|
|
}
|
|
}
|
|
|
|
func (k *keyField) Blink() {
|
|
k.bkTimer = 40
|
|
}
|
|
|
|
func (k *keyField) keyListener(scancode sdl.Scancode) {
|
|
key := strings.ToLower(sdl.GetKeyName(sdl.GetKeyFromScancode(scancode)))
|
|
key = strings.ToLower(key)
|
|
if strings.Contains(printables, key) {
|
|
if len(k.enteredChar) < k.charLen {
|
|
k.enteredChar = append(k.enteredChar, key)
|
|
} else {
|
|
k.enteredChar = shiftLeft(k.enteredChar, key)
|
|
}
|
|
} else if scancode == sdl.SCANCODE_BACKSPACE {
|
|
if len(k.enteredChar) > 0 {
|
|
k.enteredChar = k.enteredChar[:len(k.enteredChar) - 1]
|
|
}
|
|
} else if scancode == sdl.SCANCODE_RETURN {
|
|
if strings.Join(k.enteredChar, "") == k.passwd {
|
|
k.onSuccess()
|
|
} else {
|
|
k.Blink()
|
|
}
|
|
}
|
|
|
|
}
|