如何解决如何在 love2d 中创建一个可以输入数据进行计算的文本框类?
如何制作一个文本框,以便在 love2d 中输入数字来计算?
解决方法
步骤:
- (可选)捕捉鼠标/触摸位置
- 将输入存储在字符串变量中
- 清理输入,确保没有意外字符
- 计算结果,使用
load(str)
然后执行()
- 打印结果
捕获鼠标是可选的,仅当您的应用具有多个功能时才需要。如果它是仅计算您输入的内容的一次性应用程序,则无需第一步。但是,如果屏幕上还有其他可选择的位置,您将需要一种方法来确定用户是否需要该输入区域。有一些 GUI 库可以帮助解决这个问题,或者您可以简单地测试它是否在预期的屏幕 x,y 区域内。
function love.load()
fontsize = 16
fontname = "font.ttf"
font = love.graphics.newFont( fontname,fontsize )
input_x_min = 20
input_x_max = 400
input_y_min = 20
input_y_max = input_y_min +fontsize *2
allowed_chars = "1234567890()+-*/"
love.keyboard.setTextInput( false )
input_text = "result=" -- for storing input
result = nil -- empty placeholder for now
output_x = 20
output_y = 40
output_limit = 400
end
function love.update(dt)
local x,y = love.mouse.getPosition()
-- could also capture mouseclicks here,and/or get touch events
if x >= input_x_min and x <= input_x_max
and y >= input_y_min and y <= input_y_max then
love.keyboard.setTextInput( true )
else
love.keyboard.setTextInput( false )
input_text = "result=" -- no longer selected,reset input
end
end
function love.textinput(t)
for i = 1,#allowed_chars do -- sanitize input
if allowed_chars :sub(i,i) == t then -- if char is allowed
input_text = input_text ..t -- append what was typed
generate_result,err = load( input_text ) -- "result=3+(2*2)"
if err then print( err )
else generate_result() -- function() return result=3+(2*2) end
end
end
end
end
function love.draw()
love.graphics.printf( input_text,output_x,output_y,input_limit )
love.graphics.printf( result,output_limit )
end
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。