Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 691c3adb37 | |||
| ae97703bb4 | |||
| e8ca768e87 | |||
| 9a908e89ae | |||
| 3109844765 | |||
| 6b864a2d9b |
+11
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"$schema": "https://raw.githubusercontent.com/sumneko/vscode-lua/master/setting/schema.json",
|
||||
"runtime.version": "LuaJIT",
|
||||
"diagnostics.globals": [
|
||||
"love"
|
||||
],
|
||||
"workspace.library": [
|
||||
"${3rd}/love2d/library"
|
||||
],
|
||||
"workspace.checkThirdParty": false
|
||||
}
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"recommendations":
|
||||
["tomblind.local-lua-debugger-vscode",
|
||||
"sumneko.lua",]
|
||||
}
|
||||
Vendored
+28
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"type": "lua-local",
|
||||
"request": "launch",
|
||||
"name": "Debug",
|
||||
"program": {
|
||||
"command": "love"
|
||||
},
|
||||
"args": [
|
||||
".",
|
||||
"debug"
|
||||
],
|
||||
},
|
||||
{
|
||||
"type": "lua-local",
|
||||
"request": "launch",
|
||||
"name": "Release",
|
||||
"program": {
|
||||
"command": "love"
|
||||
},
|
||||
"args": [
|
||||
".",
|
||||
],
|
||||
},
|
||||
]
|
||||
}
|
||||
Vendored
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"label": "Build with LÖVE-Build",
|
||||
"type": "shell",
|
||||
"command": "love-build", // Path to Love-build
|
||||
"args": [".main.lua"],
|
||||
"group": "build",
|
||||
}
|
||||
]
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 57 KiB |
@@ -0,0 +1,17 @@
|
||||
return {
|
||||
-- basic settings:
|
||||
name = 'Jeopardy', -- name of the game for your executable
|
||||
developer = 'Ryan Ward', -- dev name used in metadata of the file
|
||||
output = 'bin', -- output location for your game, defaults to $SAVE_DIRECTORY
|
||||
version = '1.0.4', -- 'version' of your game, used to name the folder in output
|
||||
love = '11.5', -- version of LÖVE to use, must match github releases
|
||||
ignore = {'bin', 'love', 'server_test', '.gitignore', '.gitmodules', 'build.lua', 'login_dialog.yaml', 'package.bat', 'README.md'}, -- folders/files to ignore in your project
|
||||
icon = 'assets/icon.png', -- 256x256px PNG icon for game, will be converted for you
|
||||
|
||||
-- optional settings:
|
||||
use32bit = false, -- set true to build windows 32-bit as well as 64-bit
|
||||
identifier = 'net.ddns.epicknex.jeopardy', -- macos team identifier, defaults to game.developer.name
|
||||
libs = {},
|
||||
hooks = {},
|
||||
platforms = {'windows', --[['macos', 'linux', 'steamdeck']]} -- set if you only want to build for a specific platform
|
||||
}
|
||||
+1
-1
Submodule gui updated: fa06733747...27995af07f
@@ -1,59 +0,0 @@
|
||||
# login_dialog.yaml
|
||||
type: frame
|
||||
x: 0
|
||||
y: 0
|
||||
scale-size: [0.4, 0.25]
|
||||
scale-pos: [0.3, 0.2]
|
||||
color: "#1e1e2e"
|
||||
border-color: "#4a4a6a"
|
||||
roundness: 12
|
||||
|
||||
children:
|
||||
- type: label
|
||||
text: "Sign In"
|
||||
x: 0
|
||||
y: 20
|
||||
scale-size: [1.0, 0.0]
|
||||
h: 48
|
||||
align: center
|
||||
font: 28
|
||||
text-color: "#cdd6f4"
|
||||
|
||||
- type: textbox
|
||||
x: 30
|
||||
y: 90
|
||||
scale-size: [0.85, 0.0]
|
||||
h: 36
|
||||
text: ""
|
||||
color: "#313244"
|
||||
border-color: "#6c7086"
|
||||
text-color: "#cdd6f4"
|
||||
font: 14
|
||||
on-return: "focusPassword"
|
||||
|
||||
- type: textbox
|
||||
x: 30
|
||||
y: 140
|
||||
scale-size: [0.85, 0.0]
|
||||
h: 36
|
||||
text: ""
|
||||
color: "#313244"
|
||||
border-color: "#6c7086"
|
||||
text-color: "#cdd6f4"
|
||||
font: 14
|
||||
on-return: "submitLogin"
|
||||
|
||||
- type: button
|
||||
text: "Log In"
|
||||
align: "center"
|
||||
fit-font: true
|
||||
x: 30
|
||||
y: 200
|
||||
scale-size: [0.2, 0.0]
|
||||
h: 40
|
||||
color: "#89b4fa"
|
||||
text-color: "#1e1e2e"
|
||||
roundness: 8
|
||||
on-pressed: "submitLogin"
|
||||
on-enter: "highlightButton"
|
||||
on-exit: "unhighlightButton"
|
||||
@@ -1,6 +1,26 @@
|
||||
multi, thread = require("multi"):init({priority=true})
|
||||
local logger = require("utils/logger")
|
||||
local lovehandler = require("utils/love_file_handler")
|
||||
local zip = require("utils/zip")
|
||||
|
||||
local multi, thread = require("multi"):init({priority=true})
|
||||
multi.setClock(require("socket").gettime) -- When on linux os.clock doesn't reture actual seconds the program has elapsed for
|
||||
GLOBAL, THREAD = require("multi.integration.loveManager"):init()
|
||||
local GLOBAL, THREAD = require("multi.integration.loveManager"):init()
|
||||
|
||||
local fileHandler, logCtrl = lovehandler.new("logs/jeopardy.log", {
|
||||
max_size = 512 * 1024, -- rotate at 512 KB
|
||||
max_files = 3,
|
||||
buffered = false, -- write every line immediately (safest for games)
|
||||
})
|
||||
|
||||
lovehandler.auto_flush_on_quit(logCtrl)
|
||||
|
||||
log = logger.new("jeopardy", {
|
||||
level = logger.LEVELS.INFO,
|
||||
handlers = {
|
||||
logger.handlers.ConsoleHandler({ colours = true }),
|
||||
fileHandler,
|
||||
},
|
||||
})
|
||||
|
||||
local gui = require("gui")
|
||||
local color = require("gui.core.color")
|
||||
@@ -15,6 +35,12 @@ color.indexColor("title_font","#b16d24")
|
||||
color.indexColor("question_bg","#363ac8")
|
||||
color.indexColor("tile_font","#ffffff")
|
||||
color.indexColor("header_font","#fef6eeda")
|
||||
color.indexColor("correct", "#52b11b")
|
||||
color.indexColor("skip", "#5d5d5d")
|
||||
color.indexColor("wrong", "#bd2626")
|
||||
color.indexColor("shaderColA","rgb01(0.10, 0.12, 0.38)")
|
||||
color.indexColor("shaderColB","rgb01(0.20, 0.22, 0.58)")
|
||||
color.indexColor("shaderColC","rgb01(0.55, 0.58, 0.78)")
|
||||
|
||||
require("gui.addons")
|
||||
|
||||
@@ -23,25 +49,51 @@ gui:setHotKey({"f11"})(function()
|
||||
love.window.setFullscreen(not fullscreen, "desktop")
|
||||
end)
|
||||
|
||||
local loadLog = log:child("load")
|
||||
local old = multi.error
|
||||
|
||||
multi.error = function(...)
|
||||
old(...)
|
||||
os.exit()
|
||||
multi.error = function(self, err)
|
||||
loadLog:error("Error: %s", err)
|
||||
loadLog:error(debug.traceback())
|
||||
love.quit()
|
||||
end
|
||||
|
||||
function readFileData(path)
|
||||
return io.open(path,"r"):read("*a")
|
||||
end
|
||||
|
||||
function love.load()
|
||||
-- local z = zip.new()
|
||||
-- z:add("main.lua",readFileData("main.lua"))
|
||||
-- z:add("package.bat",readFileData("package.bat"))
|
||||
-- local data = z:build()
|
||||
-- local file = io.open("test.zip","wb")
|
||||
-- file:write(data)
|
||||
-- file:close()
|
||||
|
||||
loadLog:info("Starting Jeopardy Game")
|
||||
loadLog:debug("Setting game identity to jeopardy")
|
||||
for i,v in ipairs(color.listColors(showAllColors)) do
|
||||
loadLog:debug("Indexed color %s",v)
|
||||
end
|
||||
love.filesystem.setIdentity("jeopardy")
|
||||
loadLog:trace("Creating save directory")
|
||||
success = love.filesystem.createDirectory("")
|
||||
if not success then
|
||||
loadLog:fatal("Unable to create save directory")
|
||||
love.quit()
|
||||
end
|
||||
loadLog:trace("Creating save directory")
|
||||
gui:cacheImage({"assets/images/checked.png","assets/images/unchecked.png","assets/images/speaker.png"})
|
||||
gui:setAspectSize(1920, 1080)
|
||||
gui.aspect_ratio = true
|
||||
|
||||
loadLog:debug("Creating main background image")
|
||||
local bg = gui:newImageLabel("assets/images/background.png")
|
||||
bg:fullFrame()
|
||||
|
||||
loadLog:debug("Init menu module")
|
||||
menu.init(bg)
|
||||
|
||||
loadLog:debug("Displaying title menu")
|
||||
title:visible(true)
|
||||
end
|
||||
|
||||
@@ -54,3 +106,75 @@ function love.draw()
|
||||
gui.draw()
|
||||
end
|
||||
|
||||
-- custom shaders
|
||||
|
||||
gui.NewShader("background", [[
|
||||
extern float time;
|
||||
extern vec2 size;
|
||||
extern vec3 colA;
|
||||
extern vec3 colB;
|
||||
extern vec3 colC;
|
||||
|
||||
// Hash function (pseudo-random from 2D input)
|
||||
float hash(vec2 p) {
|
||||
p = fract(p * vec2(127.1, 311.7));
|
||||
p += dot(p, p + 19.19);
|
||||
return fract(p.x * p.y);
|
||||
}
|
||||
|
||||
// Smooth value noise
|
||||
float noise(vec2 p) {
|
||||
vec2 i = floor(p);
|
||||
vec2 f = fract(p);
|
||||
// Quintic smoothstep
|
||||
vec2 u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);
|
||||
|
||||
float a = hash(i);
|
||||
float b = hash(i + vec2(1.0, 0.0));
|
||||
float c = hash(i + vec2(0.0, 1.0));
|
||||
float d = hash(i + vec2(1.0, 1.0));
|
||||
|
||||
return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
|
||||
}
|
||||
|
||||
// Fractional Brownian Motion – layers of noise at different scales
|
||||
float fbm(vec2 p) {
|
||||
float value = 0.0;
|
||||
float amplitude = 0.5;
|
||||
float frequency = 1.0;
|
||||
for (int i = 0; i < 6; i++) {
|
||||
value += amplitude * noise(p * frequency);
|
||||
frequency *= 2.0;
|
||||
amplitude *= 0.5;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
vec4 effect(vec4 color, Image tex, vec2 texCoord, vec2 screenCoord) {
|
||||
// Normalized UV with aspect ratio correction
|
||||
vec2 uv = screenCoord / size;
|
||||
|
||||
// Slow, asymmetric time offsets per axis for lava-lamp feel
|
||||
float t1 = time * 0.008;
|
||||
float t2 = time * 0.005;
|
||||
|
||||
// Domain-warped FBM: feed FBM output back into itself
|
||||
// This creates the bulging, self-folding blob shapes.
|
||||
vec2 q = vec2(
|
||||
fbm(uv + vec2(0.0, 0.0) + t1),
|
||||
fbm(uv + vec2(5.2, 1.3) + t2)
|
||||
);
|
||||
|
||||
vec2 r = vec2(
|
||||
fbm(uv + 4.0 * q + vec2(1.7, 9.2) + t1 * 0.7),
|
||||
fbm(uv + 4.0 * q + vec2(8.3, 2.8) + t2 * 0.9)
|
||||
);
|
||||
|
||||
float n = fbm(uv + 4.0 * r + t1 * 0.4);
|
||||
|
||||
vec3 col = mix(colA, colB, clamp(n * 2.0, 0.0, 1.0));
|
||||
col = mix(col, colC, clamp(n * 2.0 - 0.6, 0.0, 1.0));
|
||||
|
||||
return vec4(col, 1.0);
|
||||
}
|
||||
]])
|
||||
+266
-122
@@ -1,11 +1,13 @@
|
||||
local gui = require("gui")
|
||||
local color = require("gui.core.color")
|
||||
local loader = require("loader")
|
||||
local loader = require("utils/loader")
|
||||
local theme = require("gui.core.theme")
|
||||
local fmt = require("fmt")
|
||||
local timer = require("utils")
|
||||
local fmt = require("utils/fmt")
|
||||
local timer = require("utils/utils")
|
||||
local multi, thread = require("multi"):init()
|
||||
local menu = require("gui.core.menus")
|
||||
local transition = require("gui.core.transitions")
|
||||
local logger = require("utils/logger")
|
||||
|
||||
local timesup = love.audio.newSource("assets/sounds/timesup.mp3", "static")
|
||||
local double = love.audio.newSource("assets/sounds/double.mp3", "static")
|
||||
@@ -18,31 +20,16 @@ local activePlayer
|
||||
local playerList = {}
|
||||
local playerStaticList = {}
|
||||
local scoreboard = {}
|
||||
local handler
|
||||
local handler_conn = boardUpdater:newConnection()
|
||||
local reference
|
||||
local multiply
|
||||
|
||||
-- Create a table to manage GUI elements
|
||||
local manage = {}
|
||||
local reset = boardUpdater:newConnection()
|
||||
|
||||
-- Function to resize fonts for all managed elements
|
||||
local function resizeFonts()
|
||||
-- Use multi-threading to improve performance
|
||||
multi:newThread(function()
|
||||
-- Introduce a small delay to avoid too many iterations at once
|
||||
thread.skip(2)
|
||||
-- Iterate over each element in the 'manage' table
|
||||
for i = 1, #manage do
|
||||
local elem = manage[i]
|
||||
local default_text = "Pick a Category"
|
||||
|
||||
-- Check if the current element has a centerFont property
|
||||
if elem.centerFont then
|
||||
-- Adjust font size and re-center the text
|
||||
elem:fitFont(nil, nil, {scale = 2/3})
|
||||
elem:centerFont()
|
||||
end
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
gui.Events.OnResized(resizeFonts)
|
||||
local boardLog = log:child("board")
|
||||
|
||||
local completed_questions = 0
|
||||
local min_questions = 0
|
||||
@@ -51,6 +38,28 @@ local dd_enabled = false
|
||||
local applied_dd = false
|
||||
local board, question
|
||||
|
||||
local function cleanUp(frameRef)
|
||||
boardLog:debug("Cleaning up state and returning to title screen")
|
||||
scoreboard:removeAllPlayers()
|
||||
activePlayer = nil
|
||||
handler_conn:Remove()
|
||||
playerList = {}
|
||||
playerStaticList = {}
|
||||
scoreboard = {}
|
||||
handler = nil
|
||||
reference = nil
|
||||
multiply = nil
|
||||
reset:Remove()
|
||||
default_text = "Pick a Category"
|
||||
completed_questions = 0
|
||||
min_questions = 0
|
||||
dd_enabled = false
|
||||
applied_dd = false
|
||||
board = nil
|
||||
question = nil
|
||||
frameRef:destroy()
|
||||
end
|
||||
|
||||
local function pickUniqueIndices(t, count)
|
||||
assert(#t >= count, "Not enough elements to pick " .. count .. " unique items")
|
||||
|
||||
@@ -87,6 +96,7 @@ end
|
||||
|
||||
function applyDD()
|
||||
if not applied_dd and completed_questions > min_questions then
|
||||
boardLog:debug("Creating double jeopardy questions: %d",dd_count)
|
||||
local dd = 0
|
||||
local dd_list = {}
|
||||
local dds = {pickFiltered(board.children, dd_count)}
|
||||
@@ -97,13 +107,24 @@ function applyDD()
|
||||
end
|
||||
end
|
||||
|
||||
local function setMultiplier(m)
|
||||
multiply = m
|
||||
end
|
||||
|
||||
local function useDefaultHandler(callback)
|
||||
handler.visible = true
|
||||
reference = handler_conn(callback)
|
||||
end
|
||||
|
||||
local templateLog = log:child("template")
|
||||
function LoadTemplate(name, path)
|
||||
boardLog:debug("Loading Template: %s", name)
|
||||
if love.filesystem.getInfo(path .."/templates/" .. name .. ".lua") then
|
||||
data = love.filesystem.read(path .."/templates/" .. name .. ".lua")
|
||||
elseif love.filesystem.getInfo("templates/" .. name .. ".lua") then
|
||||
data = love.filesystem.read("templates/" .. name .. ".lua")
|
||||
else
|
||||
print("Error Loading Template: " .. name, path)
|
||||
boardLog:error("Error Loading Template: %s", name)
|
||||
gui:newMessageBox({
|
||||
title = "Error!",
|
||||
message = "Unable to load template: " .. name,
|
||||
@@ -156,8 +177,11 @@ function LoadTemplate(name, path)
|
||||
theme = theme,
|
||||
gui = gui,
|
||||
timer = timer,
|
||||
useDefaultHandler = useDefaultHandler,
|
||||
setMultiplier = setMultiplier,
|
||||
-- love stuff
|
||||
newSource = love.audio.newSource
|
||||
newSource = love.audio.newSource,
|
||||
log = templateLog,
|
||||
}
|
||||
|
||||
env._G = env
|
||||
@@ -167,16 +191,24 @@ function LoadTemplate(name, path)
|
||||
end
|
||||
|
||||
local function manageCosmetics(frame, cosmetics)
|
||||
if cosmetics["bg-img"] then
|
||||
frame:setImage(cosmetics["bg-img"])
|
||||
else
|
||||
frame:setImage("assets/images/background.png")
|
||||
end
|
||||
boardLog:debug("Managing cosmetics")
|
||||
if type(cosmetics.colors) == "table" then
|
||||
for i,v in pairs(cosmetics.colors) do
|
||||
color.reindexColor((i:gsub("-","_")),v)
|
||||
end
|
||||
end
|
||||
if cosmetics["bg-img"] then
|
||||
frame:setImage(cosmetics["bg-img"])
|
||||
frame:setShader()
|
||||
else
|
||||
-- frame:setImage("assets/images/background.png")
|
||||
frame:setImage(nil)
|
||||
frame:setShader(gui.SHADERS.background,{
|
||||
colA = color.shaderColA,
|
||||
colB = color.shaderColB,
|
||||
colC = color.shaderColC
|
||||
})
|
||||
end
|
||||
end
|
||||
|
||||
function gui:cleanup()
|
||||
@@ -187,14 +219,11 @@ function gui:cleanup()
|
||||
completed_questions = completed_questions + 1
|
||||
end
|
||||
|
||||
local reset = boardUpdater:newConnection()
|
||||
|
||||
local default_text = "Pick a Category"
|
||||
|
||||
function Menu(frame, path)
|
||||
function Menu(frame, path, deb)
|
||||
local frameRef = frame:newImageLabel():fullFrame()
|
||||
frameRef.visibility = 0
|
||||
boardLog:info("Building board")
|
||||
if path:match(".zip") then
|
||||
-- local basename = path:match("([^/\\]+)$")
|
||||
print(path)
|
||||
local success = love.filesystem.mount(path, "quiz", true)
|
||||
if not success then
|
||||
gui:newMessageBox({
|
||||
@@ -214,40 +243,152 @@ function Menu(frame, path)
|
||||
path = "quiz"
|
||||
end
|
||||
|
||||
local scoreboard = ScoreBoard(frameRef, 0, 0, 0, 0, .06, .1, .170, .8)
|
||||
|
||||
local qframe = frameRef:newFrame(0, 0, 0, 0, .24, .1, .70, .8)
|
||||
|
||||
local dframe = frameRef:newTextLabel("",0, 0, 0, 0, .24, .1, .7, .8)
|
||||
dframe:scaleFont(.075)
|
||||
dframe:centerFont()
|
||||
dframe.align = gui.ALIGN_CENTER
|
||||
dframe.color = color.bg
|
||||
dframe.visible = false
|
||||
dframe:OnReleased(function(self)
|
||||
if self.click then
|
||||
boardUpdater:newThread(function()
|
||||
thread.skip(1)
|
||||
dframe.visible = false
|
||||
end)
|
||||
end
|
||||
end)
|
||||
|
||||
if deb then
|
||||
boardLog.level = logger.LEVELS.DEBUG
|
||||
templateLog.level = logger.LEVELS.DEBUG
|
||||
boardLog:debug("Debug mode is activated when quiz directory is in the save directory")
|
||||
local refresh = frameRef:newTextButton("Refresh", 0, -30, 140, 30, 0, 1)
|
||||
refresh:centerFont()
|
||||
refresh:scaleFont(.9)
|
||||
refresh.align = gui.ALIGN_CENTER
|
||||
refresh.color = color.green
|
||||
refresh:OnReleased(function()
|
||||
cleanUp(frameRef)
|
||||
menu.getMenu("title"):visible(true)
|
||||
menu.getMenu("board"):visible(frame, path, deb)
|
||||
end)
|
||||
end
|
||||
|
||||
-- Start the processors now
|
||||
boardLog:debug("Starting processors")
|
||||
boardUpdater.Start()
|
||||
boardLog:debug("Starting board-updater Started")
|
||||
qUpdater.Start()
|
||||
boardLog:debug("Starting question-updater Started")
|
||||
scoreUpdater.Start()
|
||||
boardLog:debug("Starting score-updater Started")
|
||||
|
||||
local scoreboard = ScoreBoard(frame, 0, 0, 0, 0, .06, .1, .170, .8)
|
||||
local glide = transition.glide()
|
||||
|
||||
local qframe = frame:newFrame(0, 0, 0, 0, .24, .1, .70, .8)
|
||||
local function displayAnswer(q)
|
||||
dframe.text = q.answer
|
||||
dframe.textColor = color.white
|
||||
|
||||
dframe.visible = true
|
||||
dframe.click = q["display-mode"] == "click"
|
||||
local sleep = 5
|
||||
local fade = 1
|
||||
if type(q["display-mode"]) == "number" then
|
||||
sleep = q["display-mode"]
|
||||
end
|
||||
if type(q["display-fade"]) == "number" and q["display-fade"] > 0 then
|
||||
fade = q["display-fade"]
|
||||
end
|
||||
if not dframe.click then
|
||||
boardUpdater:newThread(function()
|
||||
thread.sleep(sleep)
|
||||
local handle = glide(1,0,fade)
|
||||
handle:OnStep(function(p)
|
||||
dframe.textVisibility = p
|
||||
dframe.visibility = p
|
||||
end)
|
||||
handle:OnStop(function()
|
||||
dframe.visible = false
|
||||
dframe.textVisibility = 1
|
||||
dframe.visibility = 1
|
||||
handle.OnStep:Remove()
|
||||
handle.OnStop:Remove()
|
||||
end)
|
||||
end)
|
||||
end
|
||||
end
|
||||
|
||||
local label = frameRef:newTextLabel(default_text, 0, 10, 0, -20, .29, 0, .6, .1)
|
||||
handler = frameRef:newFrame(0, 10, 0, -20, .29, .9, .6, .1)
|
||||
handler.visible = false
|
||||
local correct = handler:newTextButton("Correct", 5,0,-10,0,0,.1,1/3,.8)
|
||||
correct.color = color.correct
|
||||
local skip = handler:newTextButton("Skip", 8,0,-15,0,1/3,.1,1/3,.8)
|
||||
skip.color = color.skip
|
||||
local wrong = handler:newTextButton("Wrong", 5,0,-10,0,2/3,.1,1/3,.8)
|
||||
wrong.color = color.wrong
|
||||
|
||||
gui.apply({
|
||||
setRoundness = {15,15,60},
|
||||
centerFont = {},
|
||||
scaleFont = {1/2},
|
||||
align = gui.ALIGN_CENTER,
|
||||
OnEnter = function(self)
|
||||
self:setShader(gui.SHADERS.glow)
|
||||
end,
|
||||
OnExit = function(self)
|
||||
self:setShader()
|
||||
end,
|
||||
shaderTime = {true},
|
||||
OnReleased=function(self)
|
||||
if self.text == "Skip" then
|
||||
handler_conn:Fire()
|
||||
reference:Unconnect()
|
||||
handler.visible = false
|
||||
return
|
||||
end
|
||||
local val = self.text == "Correct"
|
||||
handler_conn:Fire(val, multiply)
|
||||
if val then
|
||||
if reference then
|
||||
reference:Unconnect()
|
||||
end
|
||||
handler.visible = false
|
||||
end
|
||||
end,
|
||||
},correct,skip,wrong)
|
||||
|
||||
local label = frame:newTextLabel(default_text, 0, 10, 0, -20, .29, 0, .6, .1)
|
||||
label.visibility = .85
|
||||
label.drawBorder = false
|
||||
label.align = gui.ALIGN_CENTER
|
||||
label.color = color.bg
|
||||
label.textColor = color.status_font
|
||||
label:setRoundness(20,20,60)
|
||||
|
||||
boardUpdater:newThread(function()
|
||||
local test = function()
|
||||
return label.text ~= ""
|
||||
end
|
||||
while true do
|
||||
thread.hold(test)
|
||||
label:centerFont()
|
||||
label:fitFont(nil, nil, {scale = 2/3})
|
||||
end
|
||||
end)
|
||||
handler:setRoundness(20,20,60)
|
||||
handler.visibility = .9
|
||||
handler.color = color.bg
|
||||
label:scaleFont(2/3)
|
||||
label:centerFont()
|
||||
|
||||
local data = loader:new(path)
|
||||
board, question, dailydouble = qframe:newFrame(), qframe:newFrame(), qframe:newImageLabel("assets/images/double.jpg")
|
||||
index = data.index
|
||||
|
||||
local cosmetics = index.cosmetics or {}
|
||||
manageCosmetics(frame, cosmetics)
|
||||
cosmetics.colors = cosmetics.colors or {}
|
||||
|
||||
for i,v in pairs(color.listColors()) do
|
||||
if not cosmetics.colors[v] then
|
||||
cosmetics.colors[v] = color.rgbToHex(color[v])
|
||||
end
|
||||
end
|
||||
|
||||
frameRef:shaderTime()
|
||||
manageCosmetics(frameRef, cosmetics)
|
||||
|
||||
board:fullFrame()
|
||||
question:fullFrame()
|
||||
@@ -284,10 +425,13 @@ function Menu(frame, path)
|
||||
end
|
||||
end
|
||||
|
||||
reset(function()
|
||||
reset(function(q)
|
||||
question:cleanup()
|
||||
manageCosmetics(frame, cosmetics, true)
|
||||
manageCosmetics(frameRef, cosmetics)
|
||||
label.text = default_text
|
||||
if q["display-answer"] then
|
||||
displayAnswer(q)
|
||||
end
|
||||
end)
|
||||
|
||||
for cat,v in pairs(index.categories) do
|
||||
@@ -314,7 +458,8 @@ function Menu(frame, path)
|
||||
img:fullFrame()
|
||||
end
|
||||
|
||||
table.insert(manage,c)
|
||||
c:scaleFont(.25)
|
||||
c:centerFont()
|
||||
|
||||
for tier = 1,tiers do
|
||||
local t = board:newTextButton("$" .. start + inc*(tier-1),0,0,0,0,(1/#index.categories)*(cat-1),1/(tiers+1)*tier,(1/#index.categories),1/(tiers+1))
|
||||
@@ -324,27 +469,35 @@ function Menu(frame, path)
|
||||
t.category = v.name
|
||||
t.index = tier
|
||||
t.price = start + inc*(tier-1)
|
||||
t:OnEnter(function(self)
|
||||
self:setShader(gui.SHADERS.glow)
|
||||
end)
|
||||
t:OnExit(function(self)
|
||||
self:setShader()
|
||||
end)
|
||||
t:shaderTime(true)
|
||||
t:OnReleased(boardUpdater:newFunction(function(self)
|
||||
if self.text == "" or GetActivePlayer() == nil then return end
|
||||
if dd_enabled then
|
||||
applyDD() -- check and run DD if conditions meet
|
||||
end
|
||||
if index.categories[cat].questions == nil then fmt.Printf("Question not defined: File: %v Category: %v - %v\n",path,index.categories[cat].name,start + inc*(tier-1)) return end
|
||||
if index.categories[cat].questions == nil then boardLog:debug("Question not defined: File: %s Category: %s - %s",path,index.categories[cat].name,start + inc*(tier-1)) return end
|
||||
local globals = index.categories[cat].global
|
||||
if not globals then
|
||||
globals = {}
|
||||
end
|
||||
local q = index.categories[cat].questions[self.index]
|
||||
if not q then return end
|
||||
label.text = t.category .. ": " .. t.price
|
||||
label.text = t.category .. " - " .. t.price
|
||||
boardLog:debug("Displaying question for: %s - %s", t.category, t.price)
|
||||
local mt = debug.getmetatable(q)
|
||||
if mt then
|
||||
mt.__metatable = nil
|
||||
end
|
||||
setmetatable(q, {__index = globals})
|
||||
if q == nil then fmt.Printf("Question contains no data: File: %v Category: %v Tier: %v\n",path,index.categories[cat].name,start + inc*(tier-1)) return end
|
||||
if q == nil then boardLog:debug("Question contains no data: File: %s Category: %s Tier: %s",path,index.categories[cat].name,start + inc*(tier-1)) return end
|
||||
if q.cosmetics then
|
||||
manageCosmetics(frame, q.cosmetics)
|
||||
manageCosmetics(frameRef, q.cosmetics)
|
||||
end
|
||||
self.textVisibility = 0
|
||||
local template = LoadTemplate(q.template, path)
|
||||
@@ -352,7 +505,7 @@ function Menu(frame, path)
|
||||
local player = GetActivePlayer()
|
||||
local tm
|
||||
local stop
|
||||
fmt.Printf("--------------------\nQuestion: %v \nAnswer: %v\n--------------------\n",q["title"],q["answer"])
|
||||
boardLog:info("Question: '%s' Answer: '%s'",q["title"],q["answer"])
|
||||
local mul = 1
|
||||
boardUpdater:newThread(function()
|
||||
if self.isDouble then
|
||||
@@ -385,33 +538,30 @@ function Menu(frame, path)
|
||||
player:Add((self.price*mul)*m)
|
||||
finished = true
|
||||
question.visible = false
|
||||
reset:Fire()
|
||||
reset:Fire(q)
|
||||
elseif ans == false then
|
||||
player:Add(-self.price*mul)
|
||||
player = GetNextPlayer()
|
||||
else
|
||||
finished = true
|
||||
question.visible = false
|
||||
reset:Fire()
|
||||
reset:Fire(q)
|
||||
end -- nil is a valid option where you weren't right or wrong, you just skipped
|
||||
self.text = ""
|
||||
end)
|
||||
boardUpdater:newThread("QuestionUpdater",function()
|
||||
while true do
|
||||
template.update(dt)
|
||||
thread.yield()
|
||||
thread.sleep(.1)
|
||||
if self.text == "" then return end
|
||||
end
|
||||
end)
|
||||
end)
|
||||
end))
|
||||
table.insert(manage,t)
|
||||
t:centerFont()
|
||||
t:scaleFont(.5)
|
||||
end
|
||||
end
|
||||
|
||||
resizeFonts()
|
||||
resizeFonts()
|
||||
|
||||
return background
|
||||
end
|
||||
|
||||
@@ -450,19 +600,33 @@ end
|
||||
|
||||
function ScoreBoard(frame, x, y, w, h, sx, sy, sw, sh)
|
||||
-- Colors
|
||||
local C_BG_PANEL = color.new("#1a1a2e")
|
||||
local C_BG_HEADER = color.new("#16213e")
|
||||
local C_ACCENT = color.new("#e94560")
|
||||
local C_ROW_TOP = color.new("#1c2641")
|
||||
local C_ROW_NORM = color.new("#121226")
|
||||
local C_BORDER_TOP = color.new("#323c6e")
|
||||
local C_BORDER_NRM = color.new("#1c1c37")
|
||||
local C_BAR_EMPTY = color.new("#232341")
|
||||
local C_TEXT_MUTED = color.new("#786e96")
|
||||
local C_WHITE = color.new("#ffffff")
|
||||
local C_GOLD = color.new("#ffd700")
|
||||
local C_SILVER = color.new("#C0C0C0")
|
||||
local C_BRONZE = color.new("#cd7f32")
|
||||
color.indexColor("scoreboard_panel_bg", "#1a1a2e")
|
||||
color.indexColor("scoreboard_header_bg", "#16213e")
|
||||
color.indexColor("scoreboard_accent_color", "#e94560")
|
||||
color.indexColor("scoreboard_row_top_bg", "#1c2641")
|
||||
color.indexColor("scoreboard_row_norm_bg", "#121226")
|
||||
color.indexColor("scoreboard_border_top_color", "#323c6e")
|
||||
color.indexColor("scoreboard_border_nrm_color", "#1c1c37")
|
||||
color.indexColor("scoreboard_bar_empty_color", "#232341")
|
||||
color.indexColor("scoreboard_text_muted_color", "#786e96")
|
||||
color.indexColor("scoreboard_pure_white", "#ffffff")
|
||||
color.indexColor("scoreboard_precious_gold", "#ffd700")
|
||||
color.indexColor("scoreboard_precious_silver", "#C0C0C0")
|
||||
color.indexColor("scoreboard_precious_bronze", "#cd7f32")
|
||||
|
||||
local C_BG_PANEL = color.scoreboard_panel_bg
|
||||
local C_BG_HEADER = color.scoreboard_header_bg
|
||||
local C_ACCENT = color.scoreboard_accent_color
|
||||
local C_ROW_TOP = color.scoreboard_row_top_bg
|
||||
local C_ROW_NORM = color.scoreboard_row_norm_bg
|
||||
local C_BORDER_TOP = color.scoreboard_border_top_color
|
||||
local C_BORDER_NRM = color.scoreboard_border_nrm_color
|
||||
local C_BAR_EMPTY = color.scoreboard_bar_empty_color
|
||||
local C_TEXT_MUTED = color.scoreboard_text_muted_color
|
||||
local C_WHITE = color.scoreboard_pure_white
|
||||
local C_GOLD = color.scoreboard_precious_gold
|
||||
local C_SILVER = color.scoreboard_precious_silver
|
||||
local C_BRONZE = color.scoreboard_precious_bronze
|
||||
|
||||
-- Config stuff
|
||||
local LEADER_HEIGHT_SCALE = .06
|
||||
@@ -498,28 +662,11 @@ function ScoreBoard(frame, x, y, w, h, sx, sy, sw, sh)
|
||||
textColor = C_TEXT_MUTED,
|
||||
}, headernum, headerplayer, headerscore)
|
||||
|
||||
local updateList = {header, headernum, headerplayer, headerscore}
|
||||
local updateList = {headernum, headerplayer, headerscore, header}
|
||||
|
||||
local function ScoreResize()
|
||||
scoreUpdater:newThread(function()
|
||||
thread.skip(2)
|
||||
|
||||
for _,object in pairs(updateList) do
|
||||
object:fitFont(nil, nil, {scale = 5/6})
|
||||
object:centerFont()
|
||||
end
|
||||
|
||||
for _,object in pairs(playerList) do
|
||||
if type(object) == "table" and object.Ref then
|
||||
for i, player in pairs(object.Ref) do
|
||||
if player:hasType(gui.TYPE_TEXT) then
|
||||
player:fitFont(nil, nil, {scale = 5/6})
|
||||
player:centerFont()
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end)
|
||||
for _,object in pairs(updateList) do
|
||||
object:scaleFont(2/3)
|
||||
object:centerFont()
|
||||
end
|
||||
|
||||
function scoreboard:AddPlayer(name, score, icon)
|
||||
@@ -537,13 +684,11 @@ function ScoreBoard(frame, x, y, w, h, sx, sy, sw, sh)
|
||||
return tonumber(a.Score) > tonumber(b.Score)
|
||||
end)
|
||||
scoreboard:RenderPlayer(playerList)
|
||||
ScoreResize()
|
||||
end,
|
||||
}
|
||||
table.insert(playerList, player)
|
||||
table.insert(playerStaticList, player)
|
||||
scoreboard:RenderPlayer(playerList)
|
||||
ScoreResize()
|
||||
return player
|
||||
end
|
||||
|
||||
@@ -559,17 +704,12 @@ function ScoreBoard(frame, x, y, w, h, sx, sy, sw, sh)
|
||||
local add_player = leaderboard:newFrame(5,-5,-10,0,0,1-PLAYER_HEIGHT,1,PLAYER_HEIGHT)
|
||||
local edit_player = leaderboard:newFrame(5,-10,-10,0,0,1-2*PLAYER_HEIGHT,1,PLAYER_HEIGHT)
|
||||
local remove_player = leaderboard:newTextButton("Remove Selected",5,-15,-10,0,0,1-3*PLAYER_HEIGHT,1,PLAYER_HEIGHT)
|
||||
remove_player:setFont(20)
|
||||
remove_player.align = gui.ALIGN_CENTER
|
||||
local embededWatch = {remove_player}
|
||||
scoreUpdater:newThread(function()
|
||||
while true do
|
||||
thread.sleep(.01)
|
||||
for i,v in pairs(embededWatch) do
|
||||
v:centerFont()
|
||||
end
|
||||
end
|
||||
end)
|
||||
gui.apply({
|
||||
centerFont = {},
|
||||
scaleFont = {.5}
|
||||
},add_player,edit_player,remove_player)
|
||||
|
||||
local function embedTextEdit(reference, default, but_text, callback)
|
||||
reference.color = C_BORDER_NRM
|
||||
@@ -588,11 +728,10 @@ function ScoreBoard(frame, x, y, w, h, sx, sy, sw, sh)
|
||||
callback(textbox)
|
||||
end)
|
||||
gui.apply({
|
||||
setFont = {20},
|
||||
align = gui.ALIGN_CENTER
|
||||
scaleFont = {.5},
|
||||
align = gui.ALIGN_CENTER,
|
||||
centerFont = {},
|
||||
},textbox,button,reference)
|
||||
table.insert(embededWatch,textbox)
|
||||
table.insert(embededWatch,button)
|
||||
end
|
||||
|
||||
remove_player.color = color.new("#a13a3a")
|
||||
@@ -627,6 +766,11 @@ function ScoreBoard(frame, x, y, w, h, sx, sy, sw, sh)
|
||||
end
|
||||
end)
|
||||
|
||||
function scoreboard:removeAllPlayers()
|
||||
playerList = {}
|
||||
playerStaticList = {}
|
||||
end
|
||||
|
||||
function scoreboard:RenderPlayer(list)
|
||||
for index, player in ipairs(list) do
|
||||
if player.Ref then
|
||||
@@ -694,7 +838,9 @@ function ScoreBoard(frame, x, y, w, h, sx, sy, sw, sh)
|
||||
gui.apply({
|
||||
visibility = 0,
|
||||
drawBorder = false,
|
||||
textColor = MapColor(index)
|
||||
textColor = MapColor(index),
|
||||
scaleFont = {5/6},
|
||||
centerFont = {}
|
||||
},playernum, playerName, playerScore, playerIcon, playerLine)
|
||||
|
||||
player.Ref = {playerName, playerScore, playernum, playerIcon, playerLine, Frame = playerFrame}
|
||||
@@ -702,8 +848,6 @@ function ScoreBoard(frame, x, y, w, h, sx, sy, sw, sh)
|
||||
end
|
||||
end
|
||||
|
||||
gui.Events.OnResized(ScoreResize)
|
||||
ScoreResize()
|
||||
return scoreboard
|
||||
end
|
||||
|
||||
|
||||
+9
-2
@@ -4,6 +4,13 @@ local menu = require("gui.core.menus")
|
||||
-- local proc = gui:getProcessor():newProcessor("settings")
|
||||
|
||||
function Menu(frame)
|
||||
local background = frame:newImageLabel("assets/images/background.jpg")
|
||||
background:fullFrame()
|
||||
local background = frame:newFrame():fullFrame()
|
||||
background:setShader(gui.SHADERS.background,{
|
||||
colA = color.shaderColA,
|
||||
colB = color.shaderColB,
|
||||
colC = color.shaderColC
|
||||
})
|
||||
background:shaderTime()
|
||||
end
|
||||
|
||||
return menu.registerMenu("settings", Menu)
|
||||
+23
-20
@@ -5,7 +5,10 @@ local proc = gui:getProcessor():newProcessor("main-title")
|
||||
|
||||
local APP_VERSION = love.filesystem.read("version.txt")
|
||||
|
||||
local board = require("menus.board")
|
||||
local boardMenu = require("menus.board")
|
||||
local settingsMenu = require("menus.settings")
|
||||
|
||||
local titleLog = log:child("title")
|
||||
|
||||
function Menu(frame)
|
||||
local background = frame:newImageLabel("assets/images/background.jpg")
|
||||
@@ -13,6 +16,7 @@ function Menu(frame)
|
||||
local title = background:newTextLabel("Jeopardy",0,0,0,0,0,.1,1,.25)
|
||||
title:setFont("assets/fonts/gyparody.ttf",300)
|
||||
|
||||
titleLog:debug("Setting title shader")
|
||||
title:setShader(gui.SHADERS.vignette,{
|
||||
intensity = .5,
|
||||
smoothness = .8
|
||||
@@ -22,16 +26,9 @@ function Menu(frame)
|
||||
title.visibility = 0
|
||||
title.textColor = color.title_font
|
||||
title.drawBorder = false
|
||||
title:centerFont()
|
||||
|
||||
proc:newThread(function()
|
||||
local function enabled()
|
||||
return background.visible
|
||||
end
|
||||
while true do
|
||||
thread.hold(enabled)
|
||||
title:centerFont()
|
||||
end
|
||||
end)
|
||||
titleLog:debug("Creating font thread")
|
||||
|
||||
local items = 0
|
||||
local MenuOption = function(str)
|
||||
@@ -39,13 +36,10 @@ function Menu(frame)
|
||||
local text = item:newTextLabel(str)
|
||||
text:fullFrame()
|
||||
text.align = gui.ALIGN_CENTER
|
||||
thread:newThread(function()
|
||||
thread.skip(2)
|
||||
text:fitFont(nil,nil,{scale = 1/2})
|
||||
text:centerFont()
|
||||
text.visibility = 0
|
||||
text.textColor = color.new("#24269a")
|
||||
end)
|
||||
text:scaleFont(.4)
|
||||
text:centerFont()
|
||||
text.visibility = 0
|
||||
text.textColor = color.new("#24269a")
|
||||
items = items + 1
|
||||
return item, text
|
||||
end
|
||||
@@ -64,17 +58,26 @@ function Menu(frame)
|
||||
},play,settings,quit)
|
||||
|
||||
play:OnReleased(function()
|
||||
titleLog:debug("Play button pressed")
|
||||
if love.filesystem.getInfo("quiz") then
|
||||
menu.getMenu("board"):visible(true, "quiz")
|
||||
boardMenu:visible(true, "quiz", true)
|
||||
return
|
||||
else
|
||||
gui:newFilePicker("File picker test",nil, {".zip"}, function(file)
|
||||
menu.getMenu("board"):visible(true, file:gsub("\\","/"):gsub(love.filesystem.getSaveDirectory(),""):sub(2,-1))
|
||||
titleLog:info("File picked: %s", file)
|
||||
boardMenu:visible(true, file:gsub("\\","/"):gsub(love.filesystem.getSaveDirectory(),""):sub(2,-1))
|
||||
end)
|
||||
end
|
||||
end)
|
||||
|
||||
quit:OnReleased(function()
|
||||
settings:OnReleased(function()
|
||||
titleLog:debug("Settings button pressed")
|
||||
settingsMenu:visible(true)
|
||||
end)
|
||||
|
||||
quit:OnReleased(function(self, x, y)
|
||||
print("Quit Pressed",x,y,self:getAbsolutes())
|
||||
titleLog:debug("Quit button pressed")
|
||||
local f = frame:newFrame()
|
||||
f:fullFrame()
|
||||
f.visibility = .8
|
||||
|
||||
+1
-1
Submodule multi updated: 0796788fcb...8b5d10cbb6
+1
-1
@@ -5,7 +5,7 @@ for /f "usebackq delims=" %%i in ("version.txt") do (
|
||||
)
|
||||
|
||||
:done
|
||||
"C:\Program Files\7-Zip\7z.exe" a -tzip game.love templates version.txt assets multi\integration\loveManager multi\integration\sharedExtensions multi\init.lua gui menus conf.lua fmt.lua loader.lua main.lua utils.lua yaml.lua
|
||||
"C:\Program Files\7-Zip\7z.exe" a -tzip game.love templates version.txt assets multi\integration\loveManager multi\integration\sharedExtensions multi\init.lua utils gui menus conf.lua main.lua
|
||||
rd /s /q "bin\%userInput%"
|
||||
if not exist "bin\%userInput%" mkdir "bin\%userInput%"
|
||||
copy /b love\love.exe + game.love "bin\%userInput%\Jeopardy.exe"
|
||||
|
||||
+5
-20
@@ -10,7 +10,9 @@ local function index(window, q, callback)
|
||||
label.align = ALIGN_CENTER
|
||||
label.textColor = color.white
|
||||
label.color = color.new("#363ac8")
|
||||
label.borderColor = color.new("#363ac8")
|
||||
label.drawBorder = false
|
||||
label:scaleFont(.4)
|
||||
label:centerFont()
|
||||
|
||||
if not q.imageA or q.imageA == "" then
|
||||
error("Missing 'imageA' field for question!")
|
||||
@@ -37,32 +39,15 @@ local function index(window, q, callback)
|
||||
imageHolder2:setAspectSize(imageHolder2.imageWidth, imageHolder2.imageHeight)
|
||||
imageHolder2:setDualDim(0, 0, 0, 0, .6, 0, .4, 1)
|
||||
|
||||
local correct = window:newTextButton("Correct",0,-200,0,100,0,1,.5)
|
||||
correct.color = color.new("#52b11b")
|
||||
local wrong = window:newTextButton("Wrong",0,-200,0,100,.5,1,.5)
|
||||
wrong.color = color.new("#bd2626")
|
||||
local skip = window:newTextButton("Skip",0,-100,0,100,.25,1,.5)
|
||||
skip.color = color.new("#5d5d5d")
|
||||
|
||||
window.apply({
|
||||
centerY = {true},
|
||||
}, imageHolder, plusLabel, imageHolder2)
|
||||
|
||||
window.apply({
|
||||
fitFont={},
|
||||
align=window.ALIGN_CENTER,
|
||||
OnReleased=function(self)
|
||||
if self.text == "Skip" then
|
||||
callback()
|
||||
return
|
||||
end
|
||||
callback(self.text == "Correct")
|
||||
end,
|
||||
}, correct, wrong, skip)
|
||||
useDefaultHandler(callback)
|
||||
end
|
||||
|
||||
local function update(dt)
|
||||
label:fitFont()
|
||||
|
||||
end
|
||||
|
||||
return {
|
||||
|
||||
@@ -23,7 +23,11 @@ local function index(window, q, callback)
|
||||
label.textColor = color.white
|
||||
label.color = color.new("#363ac8")
|
||||
label:setFont(50)
|
||||
choices = window:newFrame(noOf(0,.3,1,.7))
|
||||
label:centerFont()
|
||||
label:scaleFont(2/3)
|
||||
label.drawBorder = false
|
||||
|
||||
local choices = window:newFrame(noOf(0,.3,1,.7))
|
||||
choices.color = color.new("#363ac8")
|
||||
|
||||
function choices:newChoice(choice, i)
|
||||
@@ -52,9 +56,8 @@ local function index(window, q, callback)
|
||||
choiceText.textColor = color.white
|
||||
-- choiceText.align = window.ALIGN_CENTER
|
||||
choiceText:setFont(40)
|
||||
table.insert(choiceList,choiceText)
|
||||
choiceText:centerFont()
|
||||
table.insert(allBoxes,box)
|
||||
|
||||
end
|
||||
|
||||
for i,choice in pairs(q.choices) do
|
||||
@@ -84,16 +87,7 @@ local function index(window, q, callback)
|
||||
end
|
||||
|
||||
local function update(dt) -- time in seconds that has passed since
|
||||
-- label:fitFont()
|
||||
label:centerFont()
|
||||
for _, obj in pairs(choiceList) do
|
||||
obj:centerFont()
|
||||
-- obj:fitFont(nil, nil, {scale = 2/3})
|
||||
end
|
||||
confirm:fitFont(nil, nil, {scale = 2/3})
|
||||
confirm:centerFont()
|
||||
-- print(box.parent:getAbsolutes())
|
||||
-- print(box:getAbsolutes())
|
||||
|
||||
end
|
||||
|
||||
return {
|
||||
|
||||
+6
-19
@@ -10,12 +10,15 @@ local label
|
||||
local imageHolder
|
||||
|
||||
local function index(window, q, callback)
|
||||
frame = window:newFrame(0,0,0,-200,0,.2,1,.8)
|
||||
frame = window:newFrame(0,0,0,0,0,.2,1,.8)
|
||||
frame.visibility = 0
|
||||
label = window:newTextLabel(" " ..q.title.. " ",0,0,0,0,0,0,1,.2)
|
||||
label.align = ALIGN_CENTER
|
||||
label.textColor = color.white
|
||||
label.color = color.new("#363ac8")
|
||||
label:scaleFont(.4)
|
||||
label:centerFont()
|
||||
label.drawBorder = false
|
||||
if not q.image or q.image == "" then
|
||||
error("Missing 'image' field for question!")
|
||||
end
|
||||
@@ -24,30 +27,14 @@ local function index(window, q, callback)
|
||||
imageHolder:centerX(true)
|
||||
imageHolder:centerY(true)
|
||||
imageHolder:setDualDim(0,0,imageHolder.imageWidth,imageHolder.imageHeight)
|
||||
local correct = window:newTextButton("Correct",0,-200,0,100,0,1,.5)
|
||||
correct.color = color.new("#52b11b")
|
||||
local wrong = window:newTextButton("Wrong",0,-200,0,100,.5,1,.5)
|
||||
wrong.color = color.new("#bd2626")
|
||||
local skip = window:newTextButton("Skip",0,-100,0,100,.25,1,.5)
|
||||
skip.color = color.new("#5d5d5d")
|
||||
window.apply({
|
||||
fitFont={},
|
||||
align=window.ALIGN_CENTER,
|
||||
OnReleased=function(self)
|
||||
if self.text == "Skip" then
|
||||
callback()
|
||||
return
|
||||
end
|
||||
callback(self.text == "Correct")
|
||||
end,
|
||||
},correct,wrong,skip)
|
||||
|
||||
useDefaultHandler(callback)
|
||||
end
|
||||
|
||||
local function update(dt) -- time in seconds that has passed since
|
||||
_,_,w,h = imageHolder.parent:getAbsolutes()
|
||||
local x,y,w,h = imageHolder:GetSizeAdjustedToAspectRatio(w,h)
|
||||
imageHolder:setDualDim(w,h,x,y)
|
||||
label:fitFont()
|
||||
end
|
||||
|
||||
return {
|
||||
|
||||
+6
-19
@@ -14,28 +14,15 @@ local function index(window, q, callback)
|
||||
label:fullFrame()
|
||||
label.textColor = color.white
|
||||
label.color = color.new("#363ac8")
|
||||
local correct = window:newTextButton("Correct",0,-200,0,100,0,1,.5)
|
||||
correct.color = color.new("#52b11b")
|
||||
local wrong = window:newTextButton("Wrong",0,-200,0,100,.5,1,.5)
|
||||
wrong.color = color.new("#bd2626")
|
||||
local skip = window:newTextButton("Skip",0,-100,0,100,.25,1,.5)
|
||||
skip.color = color.new("#5d5d5d")
|
||||
gui.apply({
|
||||
fitFont={},
|
||||
align=gui.ALIGN_CENTER,
|
||||
OnReleased=function(self)
|
||||
if self.text == "Skip" then
|
||||
callback()
|
||||
return
|
||||
end
|
||||
callback(self.text == "Correct")
|
||||
end,
|
||||
},correct,wrong,skip)
|
||||
label:setFont(60)
|
||||
label:centerFont()
|
||||
label:scaleFont(.075)
|
||||
label.drawBorder = false
|
||||
|
||||
useDefaultHandler(callback)
|
||||
end
|
||||
|
||||
local function update(dt) -- time in seconds that has passed since
|
||||
label:centerFont()
|
||||
|
||||
end
|
||||
|
||||
return {
|
||||
|
||||
+9
-22
@@ -15,13 +15,17 @@ local function index(window, q, callback)
|
||||
callback()
|
||||
return
|
||||
end
|
||||
frame = window:newFrame(0,0,0,-200,0,.2,1,.8)
|
||||
frame = window:newFrame(0,0,0,0,0,.2,1,.8)
|
||||
frame.visibility = 0
|
||||
label = window:newTextLabel(" " ..q.title.. " ",0,0,0,0,0,0,1,.2)
|
||||
label.align = ALIGN_CENTER
|
||||
label.textColor = color.white
|
||||
label.color = color.new("#363ac8")
|
||||
imageHolder = frame:newImageButton("assets/images/speaker.png",0,0,0,0,0,0,.3,.4)
|
||||
label:scaleFont(.4)
|
||||
label:centerFont()
|
||||
label.drawBorder = false
|
||||
imageHolder = frame:newImageButton("assets/images/speaker.png",0,0,0,0,0,0,.3,.3)
|
||||
imageHolder.scale = "h"
|
||||
imageHolder:setAspectSize(imageHolder.imageWidth,imageHolder.imageHeight)
|
||||
imageHolder:centerX(true)
|
||||
imageHolder:centerY(true)
|
||||
@@ -38,29 +42,12 @@ local function index(window, q, callback)
|
||||
sound:seek(0)
|
||||
end)
|
||||
end)
|
||||
local correct = window:newTextButton("Correct",0,-200,0,100,0,1,.5)
|
||||
correct.color = color.new("#52b11b")
|
||||
local wrong = window:newTextButton("Wrong",0,-200,0,100,.5,1,.5)
|
||||
wrong.color = color.new("#bd2626")
|
||||
local skip = window:newTextButton("Skip",0,-100,0,100,.25,1,.5)
|
||||
skip.color = color.new("#5d5d5d")
|
||||
window.apply({
|
||||
fitFont={},
|
||||
align=window.ALIGN_CENTER,
|
||||
OnReleased=function(self)
|
||||
sound:stop()
|
||||
if self.text == "Skip" then
|
||||
callback()
|
||||
return
|
||||
end
|
||||
callback(self.text == "Correct")
|
||||
end,
|
||||
},correct,wrong,skip)
|
||||
|
||||
useDefaultHandler(callback)
|
||||
end
|
||||
|
||||
local function update(dt) -- time in seconds that has passed since
|
||||
label:fitFont()
|
||||
label:centerFont()
|
||||
|
||||
end
|
||||
|
||||
return {
|
||||
|
||||
+6
-20
@@ -21,6 +21,9 @@ local function index(window, q, callback)
|
||||
label.align = ALIGN_CENTER
|
||||
label.textColor = color.white
|
||||
label.color = color.new("#363ac8")
|
||||
label:centerFont()
|
||||
label:scaleFont(.4)
|
||||
label.drawBorder = false
|
||||
local holder = frame:newFrame(-300, -200, 600, 400, .5, .5)
|
||||
holder:centerX(true)
|
||||
holder:centerY(true)
|
||||
@@ -31,29 +34,12 @@ local function index(window, q, callback)
|
||||
video:play()
|
||||
end)
|
||||
video.XButton.visible = false
|
||||
local correct = window:newTextButton("Correct",0,-200,0,100,0,1,.5)
|
||||
correct.color = color.new("#52b11b")
|
||||
local wrong = window:newTextButton("Wrong",0,-200,0,100,.5,1,.5)
|
||||
wrong.color = color.new("#bd2626")
|
||||
local skip = window:newTextButton("Skip",0,-100,0,100,.25,1,.5)
|
||||
skip.color = color.new("#5d5d5d")
|
||||
window.apply({
|
||||
fitFont={},
|
||||
align=window.ALIGN_CENTER,
|
||||
OnReleased=function(self)
|
||||
video:stop()
|
||||
if self.text == "Skip" then
|
||||
callback()
|
||||
return
|
||||
end
|
||||
callback(self.text == "Correct")
|
||||
end,
|
||||
},correct,wrong,skip)
|
||||
|
||||
useDefaultHandler(callback)
|
||||
end
|
||||
|
||||
local function update(dt) -- time in seconds that has passed since
|
||||
label:fitFont()
|
||||
label:centerFont()
|
||||
|
||||
end
|
||||
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
--[[ Constants
|
||||
* (all lua builtins that don't allow io/executing code)
|
||||
color (interface)
|
||||
gui (interface)
|
||||
multi (interface bound to a processor) no thread module
|
||||
|
||||
callback true/false correct/wrong
|
||||
]]
|
||||
local label
|
||||
local imageHolder
|
||||
|
||||
local function index(window, q, callback)
|
||||
frame = window:newFrame(0,0,0,0,0,.2,1,.8)
|
||||
frame.visibility = 0
|
||||
label = window:newTextLabel(" " ..q.title.. " ",0,0,0,0,0,0,1,.2)
|
||||
label.align = ALIGN_CENTER
|
||||
label.textColor = color.white
|
||||
label.color = color.new("#363ac8")
|
||||
label:scaleFont(.4)
|
||||
label:centerFont()
|
||||
label.drawBorder = false
|
||||
|
||||
local errors = {}
|
||||
|
||||
if type(q.zoom) ~= "string" and q.zoom ~= "" then
|
||||
table.insert(errors, "Missing 'zoom' fiels for queston! Should be a path to an image.")
|
||||
end
|
||||
|
||||
if type(q.minzoom) ~= "string" and q.minzoom ~= "" then
|
||||
table.insert(errors, "Missing 'minzoom' field for question! Should be a path to an image.")
|
||||
end
|
||||
|
||||
if type(q.fullimage) ~= "string" and q.fullimage ~= "" then
|
||||
table.insert(errors, "Missing 'fullimage' field for question! Should be a path to an image.")
|
||||
end
|
||||
|
||||
local zooms = {q.zoom, q.minzoom, q.fullimage}
|
||||
|
||||
local index = 1
|
||||
local mul = 1
|
||||
|
||||
imageHolder = frame:newImageLabel(q.zoom)
|
||||
imageHolder:setAspectSize(imageHolder.imageWidth,imageHolder.imageHeight)
|
||||
imageHolder:centerX(true)
|
||||
imageHolder:centerY(true)
|
||||
imageHolder:setDualDim(0,0,imageHolder.imageWidth,imageHolder.imageHeight)
|
||||
|
||||
imageHolder:OnEnter(function(self)
|
||||
self:setShader(gui.SHADERS.glow)
|
||||
end)
|
||||
|
||||
imageHolder:OnExit(function(self)
|
||||
self:setShader()
|
||||
end)
|
||||
|
||||
imageHolder:shaderTime(true)
|
||||
|
||||
imageHolder:OnReleased(function()
|
||||
index = index + 1
|
||||
if index == 2 then
|
||||
if q["zoom-deduct"] then
|
||||
mul = .5
|
||||
end
|
||||
elseif index == 3 then
|
||||
if q["zoom-deduct"] then
|
||||
mul = .25
|
||||
end
|
||||
else
|
||||
index = 3
|
||||
end
|
||||
imageHolder:setImage(zooms[index])
|
||||
setMultiplier(mul)
|
||||
end)
|
||||
|
||||
useDefaultHandler(callback)
|
||||
end
|
||||
|
||||
local function update(dt) -- time in seconds that has passed since
|
||||
_,_,w,h = imageHolder.parent:getAbsolutes()
|
||||
local x,y,w,h = imageHolder:GetSizeAdjustedToAspectRatio(w,h)
|
||||
imageHolder:setDualDim(w,h,x,y)
|
||||
end
|
||||
|
||||
return {
|
||||
index = index,
|
||||
update = update
|
||||
}
|
||||
@@ -1,245 +0,0 @@
|
||||
-- local gui = require("gui")
|
||||
-- local color = require("gui.core.color")
|
||||
-- local transition = require("gui.core.transitions")
|
||||
-- local multi = require("multi"):init()
|
||||
-- local timer = transition.glide(3.5,1.5,5)
|
||||
|
||||
-- local function startTimer(opt)
|
||||
-- local default = {
|
||||
-- duration = 30,
|
||||
-- autoText = true,
|
||||
-- autoColor = true,
|
||||
-- autoCleanup = true,
|
||||
-- startColor = color.green,
|
||||
-- textColor = color.black,
|
||||
-- warnColor = color.yellow,
|
||||
-- timeColor = color.red,
|
||||
-- finegrained = false,
|
||||
-- visibility = 1
|
||||
-- }
|
||||
|
||||
-- if type(opt) == "number" then
|
||||
-- local d = opt
|
||||
-- opt = default
|
||||
-- opt.duration = d
|
||||
-- elseif type(opt) ~= "table" then
|
||||
-- opt = default
|
||||
-- elseif type(opt) == "table" then
|
||||
-- for i,v in pairs(opt) do
|
||||
-- default[i] = v
|
||||
-- end
|
||||
-- opt = default
|
||||
-- end
|
||||
|
||||
-- local timeRemaining = opt.duration or 30
|
||||
|
||||
-- transition.glide:SetFPS(60)
|
||||
-- local handle = timer(3.5, 1.5, timeRemaining)
|
||||
-- local tpie = gui:newFrame():makeArc("pie",-200, 0, 100,1 ,0 ,0 ,1.5*math.pi, 3.5*math.pi, 360)
|
||||
-- local tlabel = tpie:newTextLabel("")
|
||||
-- tlabel.textColor = opt.textColor
|
||||
-- tlabel.align = gui.ALIGN_CENTER
|
||||
-- tlabel:fullFrame()
|
||||
-- tlabel.visibility = 0
|
||||
-- tpie.color = opt.startColor
|
||||
-- tpie.visibility = opt.visibility
|
||||
|
||||
-- local tm, num
|
||||
-- local func = function(p,t)
|
||||
-- if num ~= timeRemaining-math.floor(t) then
|
||||
-- num = timeRemaining-math.floor(t)
|
||||
-- end
|
||||
|
||||
-- if opt.autoColor then
|
||||
-- tpie.color = opt.startColor
|
||||
-- if num <= timeRemaining/3 then
|
||||
-- tpie.color = opt.timeColor
|
||||
-- elseif num <= timeRemaining/2 then
|
||||
-- tpie.color = opt.warnColor
|
||||
-- end
|
||||
-- end
|
||||
|
||||
-- tpie:makeArc("pie", -200, 0, 100, 1, 0, 0, 1.5 * math.pi, p * math.pi, 360)
|
||||
|
||||
-- if opt.autoText then
|
||||
-- tlabel.text = num
|
||||
-- tlabel:fitFont(nil, nil, {scale=1/2})
|
||||
-- tlabel:centerFont()
|
||||
-- end
|
||||
|
||||
-- if num == 0 then
|
||||
-- thread:newThread("Pie Timer",function()
|
||||
-- thread.yield()
|
||||
-- if opt.autoText then
|
||||
-- tlabel.text = "Time"
|
||||
-- tlabel:fitFont(nil, nil, {scale=1/2})
|
||||
-- tlabel:centerFont()
|
||||
-- end
|
||||
-- tpie:makeArc("pie", -200, 0, 100, 1, 0, 0, 1.5 * math.pi, 3.5 * math.pi, 360)
|
||||
-- tm.OnStop:Fire(tm)
|
||||
-- if opt.autoCleanup then
|
||||
-- tm:Cleanup()
|
||||
-- end
|
||||
-- tm.OnTime:Destroy()
|
||||
-- tm.OnStop:Destroy()
|
||||
-- end)
|
||||
-- end
|
||||
|
||||
-- return tm, num, t
|
||||
-- end
|
||||
|
||||
-- tm = {
|
||||
-- Duration = timeRemaining,
|
||||
-- Cleanup = function() handle:Kill() tpie:destroy() tm.Cleanup = function() end end,
|
||||
-- SetText = function(str) tlabel.text = str end,
|
||||
-- SetColor = function(c) tpie.color = c end,
|
||||
-- OnStop = multi:newConnection()
|
||||
-- }
|
||||
|
||||
-- if opt.finegrained then
|
||||
-- tm.OnTime = func % handle.OnStep
|
||||
-- else
|
||||
-- tm.OnTime = function(self, sec, t) return math.floor(t) == t, self, sec end / (func % handle.OnStep)
|
||||
-- end
|
||||
|
||||
-- return tm
|
||||
-- end
|
||||
|
||||
-- return {
|
||||
-- startTimer = startTimer
|
||||
-- }
|
||||
|
||||
local gui = require("gui")
|
||||
local color = require("gui.core.color")
|
||||
local multi, thread = require("multi"):init()
|
||||
|
||||
local function startTimer(opt)
|
||||
local default = {
|
||||
duration = 30,
|
||||
autoText = true,
|
||||
autoColor = true,
|
||||
autoCleanup = false,
|
||||
startColor = color.green,
|
||||
textColor = color.black,
|
||||
warnColor = color.yellow,
|
||||
timeColor = color.red,
|
||||
finegrained = false,
|
||||
visibility = 1
|
||||
}
|
||||
|
||||
if type(opt) == "number" then
|
||||
local d = opt
|
||||
opt = default
|
||||
opt.duration = d
|
||||
elseif type(opt) ~= "table" then
|
||||
opt = default
|
||||
else
|
||||
for i, v in pairs(opt) do
|
||||
default[i] = v
|
||||
end
|
||||
opt = default
|
||||
end
|
||||
|
||||
local timeRemaining = opt.duration or 30
|
||||
|
||||
local tpie = gui:newFrame():makeArc("pie", -200, 0, 100, 1, 0, 0, 1.5*math.pi, 3.5*math.pi, 360)
|
||||
local tlabel = tpie:newTextLabel("")
|
||||
tlabel.textColor = opt.textColor
|
||||
tlabel.align = gui.ALIGN_CENTER
|
||||
tlabel:fullFrame()
|
||||
tlabel.visibility = 0
|
||||
tpie.color = opt.startColor
|
||||
tpie.visibility = opt.visibility
|
||||
|
||||
local tm
|
||||
local stopped = false
|
||||
local onTimeConn = multi:newConnection()
|
||||
local onStopConn = multi:newConnection()
|
||||
|
||||
local function cleanup()
|
||||
if stopped then return end
|
||||
stopped = true
|
||||
if onTimeConn and not onTimeConn.destroyed then
|
||||
onTimeConn:Destroy()
|
||||
end
|
||||
if not tpie.destroyed then
|
||||
tpie:destroy()
|
||||
end
|
||||
end
|
||||
|
||||
local timerThread = thread:newThread("Pie Timer", function()
|
||||
local startTime = love.timer.getTime()
|
||||
local lastSecond = timeRemaining
|
||||
|
||||
while not stopped do
|
||||
thread.sleep(1/60)
|
||||
|
||||
local now = love.timer.getTime()
|
||||
local elapsed = now - startTime
|
||||
local t = math.min(elapsed, timeRemaining)
|
||||
local num = timeRemaining - math.floor(t)
|
||||
local p = 3.5 - (t / timeRemaining) * 2
|
||||
|
||||
if opt.autoColor then
|
||||
tpie.color = opt.startColor
|
||||
if num <= timeRemaining / 3 then
|
||||
tpie.color = opt.timeColor
|
||||
elseif num <= timeRemaining / 2 then
|
||||
tpie.color = opt.warnColor
|
||||
end
|
||||
end
|
||||
|
||||
tpie:makeArc("pie", -200, 0, 100, 1, 0, 0, 1.5*math.pi, p*math.pi, 360)
|
||||
|
||||
if opt.autoText then
|
||||
tlabel.text = num
|
||||
tlabel:fitFont(nil, nil, {scale=1/2})
|
||||
tlabel:centerFont()
|
||||
end
|
||||
|
||||
if opt.finegrained then
|
||||
onTimeConn:Fire(tm, num, t)
|
||||
elseif num < lastSecond then
|
||||
-- crossed a second boundary
|
||||
lastSecond = num
|
||||
onTimeConn:Fire(tm, num, t)
|
||||
end
|
||||
|
||||
if elapsed >= timeRemaining then
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
-- Timer finished
|
||||
if stopped then return end
|
||||
|
||||
if opt.autoText then
|
||||
tlabel.text = "Time"
|
||||
tlabel:fitFont(nil, nil, {scale=1/2})
|
||||
tlabel:centerFont()
|
||||
end
|
||||
tpie:makeArc("pie", -200, 0, 100, 1, 0, 0, 1.5*math.pi, 3.5*math.pi, 360)
|
||||
|
||||
local onStop = onStopConn
|
||||
cleanup()
|
||||
onStop:Fire(tm)
|
||||
end)
|
||||
|
||||
tm = {
|
||||
Duration = timeRemaining,
|
||||
OnTime = onTimeConn,
|
||||
OnStop = onStopConn,
|
||||
SetText = function(str) tlabel.text = str end,
|
||||
SetColor = function(c) tpie.color = c end,
|
||||
Cleanup = function()
|
||||
timerThread:Kill()
|
||||
cleanup()
|
||||
end,
|
||||
}
|
||||
|
||||
return tm
|
||||
end
|
||||
|
||||
return {
|
||||
startTimer = startTimer
|
||||
}
|
||||
@@ -1,20 +1,25 @@
|
||||
local yaml = require("yaml")
|
||||
local yaml = require("utils/yaml")
|
||||
local loader = {}
|
||||
loader.__index = loader
|
||||
|
||||
local loaderLog = log:child("loader")
|
||||
|
||||
function loader:new(path_or_file)
|
||||
local c = {}
|
||||
setmetatable(c, loader)
|
||||
c.source = path_or_file
|
||||
local file = love.filesystem.read(path_or_file .. "/index.yml")
|
||||
|
||||
if not file then
|
||||
error("Unable to load file: ".. path_or_file .."/index.yml")
|
||||
loaderLog:error("Unable to load file: %s/index.yml", path_or_file)
|
||||
end
|
||||
|
||||
c.index = yaml.parse(file)
|
||||
|
||||
for i,v in pairs(c.index.categories) do
|
||||
local link = love.filesystem.read(path_or_file .. "/" .. v.name .. ".yml")
|
||||
if not link then
|
||||
print("Error! Cannot find file: " .. path_or_file .."/" .. v.name .. ".yml")
|
||||
loaderLog:error("Error! Cannot find file: %s/%s.yml", path_or_file,v.name)
|
||||
else
|
||||
local category = yaml.parse(link)
|
||||
c.index.categories[i].questions = category.questions
|
||||
@@ -0,0 +1,300 @@
|
||||
--- logger.lua — A feature-rich logging library for Lua
|
||||
-- Supports log levels, multiple handlers, formatting, and filtering.
|
||||
--
|
||||
-- Usage:
|
||||
-- local Logger = require("logger")
|
||||
-- local log = Logger.new("MyApp")
|
||||
-- log:info("Server started on port %d", 8080)
|
||||
-- log:warn("Disk usage at %d%%", 92)
|
||||
-- log:error("Connection refused: %s", err)
|
||||
|
||||
local Logger = {}
|
||||
Logger.__index = Logger
|
||||
|
||||
-- ── Level definitions ──────────────────────────────────────────────────────
|
||||
|
||||
Logger.LEVELS = {
|
||||
TRACE = 1,
|
||||
DEBUG = 2,
|
||||
INFO = 3,
|
||||
WARN = 4,
|
||||
ERROR = 5,
|
||||
FATAL = 6,
|
||||
OFF = 7, -- disable all output
|
||||
}
|
||||
|
||||
-- Reverse map: number → name
|
||||
local LEVEL_NAMES = {}
|
||||
for name, val in pairs(Logger.LEVELS) do
|
||||
LEVEL_NAMES[val] = name
|
||||
end
|
||||
|
||||
-- ANSI colour codes (used by the ConsoleHandler when colours are enabled)
|
||||
local COLOURS = {
|
||||
[1] = "\27[36m", -- TRACE cyan
|
||||
[2] = "\27[34m", -- DEBUG blue
|
||||
[3] = "\27[32m", -- INFO green
|
||||
[4] = "\27[33m", -- WARN yellow
|
||||
[5] = "\27[31m", -- ERROR red
|
||||
[6] = "\27[35m", -- FATAL magenta
|
||||
RESET = "\27[0m",
|
||||
}
|
||||
|
||||
-- ── Utility helpers ────────────────────────────────────────────────────────
|
||||
|
||||
--- Returns an ISO-8601-style timestamp: "2025-06-08 14:32:01"
|
||||
local function timestamp()
|
||||
return os.date("%Y-%m-%d %H:%M:%S")
|
||||
end
|
||||
|
||||
--- Safe string formatting — falls back gracefully when fmt is not a string
|
||||
local function safe_format(fmt, ...)
|
||||
if select("#", ...) == 0 then
|
||||
return tostring(fmt)
|
||||
end
|
||||
local ok, result = pcall(string.format, tostring(fmt), ...)
|
||||
return ok and result or (tostring(fmt) .. " " .. table.concat({...}, " "))
|
||||
end
|
||||
|
||||
--- Pads or truncates a string to a fixed width
|
||||
local function pad(s, width)
|
||||
s = tostring(s)
|
||||
if #s >= width then return s:sub(1, width) end
|
||||
return s .. string.rep(" ", width - #s)
|
||||
end
|
||||
|
||||
-- ── Built-in Handlers ──────────────────────────────────────────────────────
|
||||
|
||||
--- ConsoleHandler — writes to stdout (or stderr for ERROR+)
|
||||
-- Options:
|
||||
-- colours (bool, default true) — enable ANSI colours
|
||||
-- stderr (bool, default false) — always write to stderr
|
||||
local function ConsoleHandler(opts)
|
||||
opts = opts or {}
|
||||
local use_colour = (opts.colours ~= false)
|
||||
local force_stderr = opts.stderr or false
|
||||
|
||||
return function(record)
|
||||
local line = record.formatted
|
||||
if use_colour then
|
||||
local c = COLOURS[record.level] or ""
|
||||
line = c .. line .. COLOURS.RESET
|
||||
end
|
||||
local dest = (force_stderr or record.level >= Logger.LEVELS.ERROR) and io.stderr or io.stdout
|
||||
dest:write(line .. "\n")
|
||||
dest:flush()
|
||||
end
|
||||
end
|
||||
|
||||
--- FileHandler — appends log records to a file
|
||||
-- Options:
|
||||
-- path (string, required) — path to the log file
|
||||
-- max_size (number, optional) — rotate when file exceeds this many bytes
|
||||
-- max_files(number, optional) — keep this many rotated files (default 5)
|
||||
local function FileHandler(opts)
|
||||
assert(opts and opts.path, "FileHandler requires opts.path")
|
||||
local path = opts.path
|
||||
local max_size = opts.max_size -- nil = never rotate
|
||||
local max_files = opts.max_files or 5
|
||||
local file
|
||||
|
||||
local function open_file()
|
||||
file = assert(io.open(path, "a"), "Cannot open log file: " .. path)
|
||||
end
|
||||
|
||||
local function rotate()
|
||||
if file then file:close(); file = nil end
|
||||
-- shift old files: .4 → .5, .3 → .4, …, .1 → .2, base → .1
|
||||
for i = max_files - 1, 1, -1 do
|
||||
os.rename(path .. "." .. i, path .. "." .. (i + 1))
|
||||
end
|
||||
os.rename(path, path .. ".1")
|
||||
open_file()
|
||||
end
|
||||
|
||||
open_file()
|
||||
|
||||
return function(record)
|
||||
if not file then open_file() end
|
||||
file:write(record.formatted .. "\n")
|
||||
file:flush()
|
||||
if max_size then
|
||||
local pos = file:seek("cur")
|
||||
if pos and pos >= max_size then rotate() end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- MemoryHandler — stores records in a Lua table (useful for testing)
|
||||
-- Returns handler, get_records() function
|
||||
local function MemoryHandler(opts)
|
||||
opts = opts or {}
|
||||
local limit = opts.limit or 10000
|
||||
local records = {}
|
||||
|
||||
local handler = function(record)
|
||||
if #records >= limit then table.remove(records, 1) end
|
||||
table.insert(records, record)
|
||||
end
|
||||
|
||||
local function get_records() return records end
|
||||
local function clear() records = {} end
|
||||
|
||||
return handler, get_records, clear
|
||||
end
|
||||
|
||||
-- Expose built-ins
|
||||
Logger.handlers = {
|
||||
ConsoleHandler = ConsoleHandler,
|
||||
FileHandler = FileHandler,
|
||||
MemoryHandler = MemoryHandler,
|
||||
}
|
||||
|
||||
-- ── Formatter ─────────────────────────────────────────────────────────────
|
||||
-- Tokens in the format string:
|
||||
-- {time} — timestamp
|
||||
-- {level} — padded level name (5 chars)
|
||||
-- {name} — logger name
|
||||
-- {message} — the log message
|
||||
|
||||
local DEFAULT_FORMAT = "[{time}] [{level}] [{name}] {message}"
|
||||
|
||||
local function escape_replacement(s)
|
||||
-- In Lua's gsub, '%' in the replacement string is special; escape it.
|
||||
return (s:gsub("%%", "%%%%"))
|
||||
end
|
||||
|
||||
local function apply_format(fmt, record)
|
||||
return (fmt
|
||||
:gsub("{time}", escape_replacement(record.time))
|
||||
:gsub("{level}", escape_replacement(pad(record.level_name, 5)))
|
||||
:gsub("{name}", escape_replacement(record.name))
|
||||
:gsub("{message}", escape_replacement(record.message)))
|
||||
end
|
||||
|
||||
-- ── Logger constructor ─────────────────────────────────────────────────────
|
||||
|
||||
--- Create a new logger instance.
|
||||
-- @param name string — logger name shown in output
|
||||
-- @param opts table — optional configuration:
|
||||
-- level (number) — minimum level, default INFO
|
||||
-- format (string) — format string, default DEFAULT_FORMAT
|
||||
-- handlers (table) — list of handler functions; defaults to ConsoleHandler
|
||||
function Logger.new(name, opts)
|
||||
opts = opts or {}
|
||||
local self = setmetatable({}, Logger)
|
||||
self.name = name or "root"
|
||||
self.level = opts.level or Logger.LEVELS.INFO
|
||||
self.format = opts.format or DEFAULT_FORMAT
|
||||
self._handlers = opts.handlers or { ConsoleHandler() }
|
||||
self._filters = {} -- list of predicate functions
|
||||
return self
|
||||
end
|
||||
|
||||
-- ── Configuration API ──────────────────────────────────────────────────────
|
||||
|
||||
--- Set the minimum log level (Logger.LEVELS.*)
|
||||
function Logger:set_level(level)
|
||||
assert(type(level) == "number", "level must be a number from Logger.LEVELS")
|
||||
self.level = level
|
||||
return self
|
||||
end
|
||||
|
||||
--- Add a handler function
|
||||
function Logger:add_handler(handler)
|
||||
table.insert(self._handlers, handler)
|
||||
return self
|
||||
end
|
||||
|
||||
--- Remove all handlers and replace with the given ones
|
||||
function Logger:set_handlers(handlers)
|
||||
self._handlers = handlers
|
||||
return self
|
||||
end
|
||||
|
||||
--- Add a filter predicate — a function(record) → bool
|
||||
-- If ANY filter returns false the record is dropped.
|
||||
function Logger:add_filter(fn)
|
||||
table.insert(self._filters, fn)
|
||||
return self
|
||||
end
|
||||
|
||||
--- Set the output format string
|
||||
function Logger:set_format(fmt)
|
||||
self.format = fmt
|
||||
return self
|
||||
end
|
||||
|
||||
-- ── Core emit logic ────────────────────────────────────────────────────────
|
||||
|
||||
function Logger:_emit(level, fmt, ...)
|
||||
if level < self.level then return end
|
||||
|
||||
local record = {
|
||||
time = timestamp(),
|
||||
level = level,
|
||||
level_name = LEVEL_NAMES[level] or ("LVL" .. level),
|
||||
name = self.name,
|
||||
message = safe_format(fmt, ...),
|
||||
}
|
||||
record.formatted = apply_format(self.format, record)
|
||||
|
||||
-- run filters
|
||||
for _, filter in ipairs(self._filters) do
|
||||
if not filter(record) then return end
|
||||
end
|
||||
|
||||
-- dispatch to handlers
|
||||
for _, handler in ipairs(self._handlers) do
|
||||
local ok, err = pcall(handler, record)
|
||||
if not ok then
|
||||
io.stderr:write("[logger] handler error: " .. tostring(err) .. "\n")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ── Convenience level methods ──────────────────────────────────────────────
|
||||
|
||||
function Logger:trace(fmt, ...) self:_emit(Logger.LEVELS.TRACE, fmt, ...) end
|
||||
function Logger:debug(fmt, ...) self:_emit(Logger.LEVELS.DEBUG, fmt, ...) end
|
||||
function Logger:info (fmt, ...) self:_emit(Logger.LEVELS.INFO, fmt, ...) end
|
||||
function Logger:warn (fmt, ...) self:_emit(Logger.LEVELS.WARN, fmt, ...) end
|
||||
function Logger:error(fmt, ...) self:_emit(Logger.LEVELS.ERROR, fmt, ...) end
|
||||
function Logger:fatal(fmt, ...) self:_emit(Logger.LEVELS.FATAL, fmt, ...) end
|
||||
|
||||
--- Log at a given numeric level
|
||||
function Logger:log(level, fmt, ...)
|
||||
self:_emit(level, fmt, ...)
|
||||
end
|
||||
|
||||
--- Returns true if the given level would be emitted
|
||||
function Logger:is_enabled(level)
|
||||
return level >= self.level
|
||||
end
|
||||
|
||||
-- ── Child loggers ──────────────────────────────────────────────────────────
|
||||
|
||||
--- Create a child logger that inherits handlers/format but has its own name.
|
||||
function Logger:child(name, opts)
|
||||
opts = opts or {}
|
||||
return Logger.new(self.name .. "." .. name, {
|
||||
level = opts.level or self.level,
|
||||
format = opts.format or self.format,
|
||||
handlers = opts.handlers or self._handlers,
|
||||
})
|
||||
end
|
||||
|
||||
-- ── Module-level root logger ───────────────────────────────────────────────
|
||||
|
||||
Logger._root = Logger.new("root")
|
||||
|
||||
--- Get / lazily create a named logger backed by the root's handlers.
|
||||
local _registry = {}
|
||||
function Logger.get(name)
|
||||
if not _registry[name] then
|
||||
_registry[name] = Logger._root:child(name)
|
||||
end
|
||||
return _registry[name]
|
||||
end
|
||||
|
||||
return Logger
|
||||
@@ -0,0 +1,222 @@
|
||||
--- love_file_handler.lua — LÖVE2D file handler for logger.lua
|
||||
--
|
||||
-- Uses love.filesystem to write logs into LÖVE's save directory, which works
|
||||
-- correctly on every platform LÖVE supports (Windows, macOS, Linux, Android).
|
||||
--
|
||||
-- Requires:
|
||||
-- logger.lua in the same directory (or on package.path)
|
||||
-- LÖVE2D 11.x+ (love.filesystem must be available)
|
||||
--
|
||||
-- Usage inside main.lua / conf.lua:
|
||||
--
|
||||
-- local Logger = require("logger")
|
||||
-- local LoveHandler = require("love_file_handler")
|
||||
--
|
||||
-- local log = Logger.new("game", {
|
||||
-- handlers = {
|
||||
-- Logger.handlers.ConsoleHandler(), -- print() fallback
|
||||
-- LoveHandler.new("logs/game.log"), -- love.filesystem
|
||||
-- },
|
||||
-- })
|
||||
--
|
||||
-- function love.load()
|
||||
-- log:info("Game started — LÖVE %s", love.getVersion())
|
||||
-- end
|
||||
|
||||
-- ── Sanity check ──────────────────────────────────────────────────────────
|
||||
|
||||
assert(love and love.filesystem,
|
||||
"love_file_handler requires the LÖVE2D runtime (love.filesystem)")
|
||||
|
||||
-- ── Module table ──────────────────────────────────────────────────────────
|
||||
|
||||
local LoveHandler = {}
|
||||
|
||||
-- ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
--- Ensure every directory component in `path` exists.
|
||||
-- love.filesystem.createDirectory is recursive on LÖVE 11+.
|
||||
local function ensure_dir(path)
|
||||
local dir = path:match("^(.*)/[^/]+$")
|
||||
if dir and dir ~= "" then
|
||||
love.filesystem.createDirectory(dir)
|
||||
end
|
||||
end
|
||||
|
||||
--- Return current file size in bytes, or 0 on error / missing file.
|
||||
local function file_size(path)
|
||||
local info = love.filesystem.getInfo(path)
|
||||
return info and info.size or 0
|
||||
end
|
||||
|
||||
--- Shift rotated files: .4→.5, .3→.4, …, base→.1
|
||||
local function rotate(path, max_files)
|
||||
for i = max_files - 1, 1, -1 do
|
||||
local src = path .. "." .. i
|
||||
local dest = path .. "." .. (i + 1)
|
||||
if love.filesystem.getInfo(src) then
|
||||
-- love.filesystem has no rename; copy + delete
|
||||
local data = love.filesystem.read(src)
|
||||
if data then
|
||||
love.filesystem.write(dest, data)
|
||||
love.filesystem.remove(src)
|
||||
end
|
||||
end
|
||||
end
|
||||
-- move base → .1
|
||||
if love.filesystem.getInfo(path) then
|
||||
local data = love.filesystem.read(path)
|
||||
if data then
|
||||
love.filesystem.write(path .. ".1", data)
|
||||
love.filesystem.remove(path)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ── Constructor ───────────────────────────────────────────────────────────
|
||||
|
||||
--- Create a new LÖVE2D file handler.
|
||||
--
|
||||
-- @param path string Path inside the LÖVE save directory.
|
||||
-- Subdirectories are created automatically.
|
||||
-- Default: "logs/game.log"
|
||||
--
|
||||
-- @param opts table Optional settings:
|
||||
-- max_size (number) Rotate when the log file reaches this many bytes.
|
||||
-- Default: 1 MB (1 048 576). Set to 0 to disable.
|
||||
-- max_files (number) How many rotated files to keep. Default: 5.
|
||||
-- buffered (bool) Accumulate lines in memory and flush in batches.
|
||||
-- Reduces I/O overhead on mobile / web exports.
|
||||
-- Default: false.
|
||||
-- flush_size (number) Lines to buffer before auto-flushing (buffered mode).
|
||||
-- Default: 20.
|
||||
-- on_error (func) Called with (err_string) on any I/O error.
|
||||
-- Default: prints a warning to love.graphics console.
|
||||
--
|
||||
-- @return handler, control_table
|
||||
-- handler — function accepted by Logger:add_handler()
|
||||
-- control — table with :flush(), :close(), :path(), :size() methods
|
||||
function LoveHandler.new(path, opts)
|
||||
path = path or "logs/game.log"
|
||||
opts = opts or {}
|
||||
|
||||
local max_size = (opts.max_size == nil) and (1024 * 1024) or opts.max_size
|
||||
local max_files = opts.max_files or 5
|
||||
local buffered = opts.buffered or false
|
||||
local flush_size = opts.flush_size or 20
|
||||
local on_error = opts.on_error or function(err)
|
||||
if love.graphics and love.graphics.print then
|
||||
print("[love_file_handler] I/O error: " .. tostring(err))
|
||||
end
|
||||
end
|
||||
|
||||
-- State
|
||||
local buffer = {} -- pending lines (buffered mode)
|
||||
local closed = false
|
||||
|
||||
ensure_dir(path)
|
||||
|
||||
-- ── Internal write ────────────────────────────────────────────────────
|
||||
|
||||
local function raw_write(lines)
|
||||
if #lines == 0 then return end
|
||||
local text = table.concat(lines, "\n") .. "\n"
|
||||
|
||||
-- Rotate if needed
|
||||
if max_size and max_size > 0 and file_size(path) + #text >= max_size then
|
||||
rotate(path, max_files)
|
||||
end
|
||||
|
||||
-- Append
|
||||
local ok, err = love.filesystem.append(path, text)
|
||||
if not ok then
|
||||
on_error(tostring(err))
|
||||
end
|
||||
end
|
||||
|
||||
-- ── Public control table ──────────────────────────────────────────────
|
||||
|
||||
local control = {}
|
||||
|
||||
--- Flush buffered lines to disk immediately.
|
||||
function control:flush()
|
||||
if #buffer > 0 then
|
||||
raw_write(buffer)
|
||||
buffer = {}
|
||||
end
|
||||
end
|
||||
|
||||
--- Close the handler (flushes first). After close() the handler is a no-op.
|
||||
function control:close()
|
||||
self:flush()
|
||||
closed = true
|
||||
end
|
||||
|
||||
--- Full path as seen by love.filesystem.
|
||||
function control:path()
|
||||
return path
|
||||
end
|
||||
|
||||
--- Real filesystem path to the save directory file (for external tools).
|
||||
function control:real_path()
|
||||
local save_dir = love.filesystem.getSaveDirectory()
|
||||
return save_dir .. "/" .. path
|
||||
end
|
||||
|
||||
--- Current log file size in bytes.
|
||||
function control:size()
|
||||
return file_size(path)
|
||||
end
|
||||
|
||||
--- List rotated files that exist (e.g. {"logs/game.log.1", ...})
|
||||
function control:rotated_files()
|
||||
local result = {}
|
||||
for i = 1, max_files do
|
||||
local p = path .. "." .. i
|
||||
if love.filesystem.getInfo(p) then
|
||||
table.insert(result, p)
|
||||
end
|
||||
end
|
||||
return result
|
||||
end
|
||||
|
||||
--- Read the entire current log file as a string (nil on error).
|
||||
function control:read()
|
||||
self:flush()
|
||||
return love.filesystem.read(path)
|
||||
end
|
||||
|
||||
-- ── Handler function ──────────────────────────────────────────────────
|
||||
|
||||
local function handler(record)
|
||||
if closed then return end
|
||||
|
||||
if buffered then
|
||||
table.insert(buffer, record.formatted)
|
||||
if #buffer >= flush_size then
|
||||
raw_write(buffer)
|
||||
buffer = {}
|
||||
end
|
||||
else
|
||||
raw_write({ record.formatted })
|
||||
end
|
||||
end
|
||||
|
||||
return handler, control
|
||||
end
|
||||
|
||||
-- ── Convenience: hook love.quit to flush ──────────────────────────────────
|
||||
|
||||
--- Wrap love.quit so a control table's flush() is called automatically.
|
||||
-- Call once per handler after Logger.new(); safe to call multiple times.
|
||||
--
|
||||
-- @param control The control table returned by LoveHandler.new()
|
||||
function LoveHandler.auto_flush_on_quit(control)
|
||||
local original_quit = love.quit or function() end
|
||||
love.quit = function()
|
||||
control:flush()
|
||||
return original_quit()
|
||||
end
|
||||
end
|
||||
|
||||
return LoveHandler
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
local gui = require("gui")
|
||||
local color = require("gui.core.color")
|
||||
local multi, thread = require("multi"):init()
|
||||
|
||||
local function startTimer(opt)
|
||||
local default = {
|
||||
duration = 30,
|
||||
autoText = true,
|
||||
autoColor = true,
|
||||
autoCleanup = false,
|
||||
startColor = color.green,
|
||||
textColor = color.black,
|
||||
warnColor = color.yellow,
|
||||
timeColor = color.red,
|
||||
finegrained = false,
|
||||
visibility = 1
|
||||
}
|
||||
|
||||
if type(opt) == "number" then
|
||||
local d = opt
|
||||
opt = default
|
||||
opt.duration = d
|
||||
elseif type(opt) ~= "table" then
|
||||
opt = default
|
||||
else
|
||||
for i, v in pairs(opt) do
|
||||
default[i] = v
|
||||
end
|
||||
opt = default
|
||||
end
|
||||
|
||||
local timeRemaining = opt.duration or 30
|
||||
|
||||
local tpie = gui:newFrame():makeArc("pie", -200, 0, 100, 1, 0, 0, 1.5*math.pi, 3.5*math.pi, 360)
|
||||
local tlabel = tpie:newTextLabel("")
|
||||
tlabel.textColor = opt.textColor
|
||||
tlabel.align = gui.ALIGN_CENTER
|
||||
tlabel:fullFrame()
|
||||
tlabel.visibility = 0
|
||||
tlabel:centerFont()
|
||||
tlabel:scaleFont(.5)
|
||||
tpie.color = opt.startColor
|
||||
tpie.visibility = opt.visibility
|
||||
|
||||
local tm
|
||||
local stopped = false
|
||||
local onTimeConn = multi:newConnection()
|
||||
local onStopConn = multi:newConnection()
|
||||
|
||||
local function cleanup()
|
||||
if stopped then return end
|
||||
stopped = true
|
||||
if onTimeConn and not onTimeConn.destroyed then
|
||||
onTimeConn:Destroy()
|
||||
end
|
||||
if not tpie.destroyed then
|
||||
tpie:destroy()
|
||||
end
|
||||
end
|
||||
|
||||
local timerThread = thread:newThread("Pie Timer", function()
|
||||
local startTime = love.timer.getTime()
|
||||
local lastSecond = timeRemaining
|
||||
|
||||
while not stopped do
|
||||
thread.sleep(1/60)
|
||||
|
||||
local now = love.timer.getTime()
|
||||
local elapsed = now - startTime
|
||||
local t = math.min(elapsed, timeRemaining)
|
||||
local num = timeRemaining - math.floor(t)
|
||||
local p = 3.5 - (t / timeRemaining) * 2
|
||||
|
||||
if opt.autoColor then
|
||||
tpie.color = opt.startColor
|
||||
if num <= timeRemaining / 3 then
|
||||
tpie.color = opt.timeColor
|
||||
elseif num <= timeRemaining / 2 then
|
||||
tpie.color = opt.warnColor
|
||||
end
|
||||
end
|
||||
|
||||
tpie:makeArc("pie", -200, 0, 100, 1, 0, 0, 1.5*math.pi, p*math.pi, 360)
|
||||
|
||||
if opt.autoText then
|
||||
tlabel.text = num
|
||||
end
|
||||
|
||||
if opt.finegrained then
|
||||
onTimeConn:Fire(tm, num, t)
|
||||
elseif num < lastSecond then
|
||||
-- crossed a second boundary
|
||||
lastSecond = num
|
||||
onTimeConn:Fire(tm, num, t)
|
||||
end
|
||||
|
||||
if elapsed >= timeRemaining then
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
-- Timer finished
|
||||
if stopped then return end
|
||||
|
||||
if opt.autoText then
|
||||
tlabel.text = "Time"
|
||||
tlabel:fitFont(nil, nil, {scale=1/2})
|
||||
tlabel:centerFont()
|
||||
end
|
||||
tpie:makeArc("pie", -200, 0, 100, 1, 0, 0, 1.5*math.pi, 3.5*math.pi, 360)
|
||||
|
||||
local onStop = onStopConn
|
||||
cleanup()
|
||||
onStop:Fire(tm)
|
||||
end)
|
||||
|
||||
tm = {
|
||||
Duration = timeRemaining,
|
||||
OnTime = onTimeConn,
|
||||
OnStop = onStopConn,
|
||||
SetText = function(str) tlabel.text = str end,
|
||||
SetColor = function(c) tpie.color = c end,
|
||||
Cleanup = function()
|
||||
timerThread:Kill()
|
||||
cleanup()
|
||||
end,
|
||||
}
|
||||
|
||||
return tm
|
||||
end
|
||||
|
||||
return {
|
||||
startTimer = startTimer
|
||||
}
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
--[[
|
||||
zip.lua — A zip writer module for LÖVE 2D
|
||||
==========================================
|
||||
Uses love.math.compress (zlib/DEFLATE) and a pure-Lua CRC-32 table.
|
||||
No external dependencies required.
|
||||
|
||||
Requires: LÖVE 11.0+
|
||||
|
||||
Usage:
|
||||
local Zip = require("zip")
|
||||
|
||||
local z = Zip.new()
|
||||
z:add("level1.lua", love.filesystem.read("level1.lua"))
|
||||
z:add("tiles/grass.png", love.filesystem.read("tiles/grass.png"))
|
||||
local data = z:build()
|
||||
love.filesystem.write("levels.zip", data)
|
||||
|
||||
API:
|
||||
Zip.new() → creates a new Zip writer
|
||||
zip:add(path, data) → adds a file entry (path uses forward slashes)
|
||||
zip:build() → returns the zip file as a string
|
||||
]]
|
||||
|
||||
local Zip = {}
|
||||
Zip.__index = Zip
|
||||
|
||||
-- ── helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
--- Pack bytes into a little-endian binary string.
|
||||
local function pack_u16(n)
|
||||
return string.char(n % 256, math.floor(n / 256) % 256)
|
||||
end
|
||||
|
||||
local function pack_u32(n)
|
||||
return string.char(
|
||||
n % 256,
|
||||
math.floor(n / 256) % 256,
|
||||
math.floor(n / 65536) % 256,
|
||||
math.floor(n / 16777216) % 256
|
||||
)
|
||||
end
|
||||
|
||||
-- LuaJIT (used by LOVE) provides the 'bit' library for bitwise operations.
|
||||
local bxor = bit.bxor
|
||||
local band = bit.band
|
||||
local rshift = bit.rshift
|
||||
|
||||
--- CRC-32 lookup table (standard IEEE 802.3 polynomial 0xEDB88320, reflected).
|
||||
local _crc_table = (function()
|
||||
local t = {}
|
||||
for i = 0, 255 do
|
||||
local c = i
|
||||
for _ = 1, 8 do
|
||||
if band(c, 1) == 1 then
|
||||
c = bxor(rshift(c, 1), 0xEDB88320)
|
||||
else
|
||||
c = rshift(c, 1)
|
||||
end
|
||||
end
|
||||
t[i] = c
|
||||
end
|
||||
return t
|
||||
end)()
|
||||
|
||||
--- Compute CRC-32 of a string (LuaJIT / LOVE compatible).
|
||||
local function crc32(data)
|
||||
local crc = 0xFFFFFFFF
|
||||
for i = 1, #data do
|
||||
local idx = band(bxor(crc, data:byte(i)), 0xFF)
|
||||
crc = bxor(rshift(crc, 8), _crc_table[idx])
|
||||
end
|
||||
return band(bxor(crc, 0xFFFFFFFF), 0xFFFFFFFF)
|
||||
end
|
||||
|
||||
--- Deflate-compress data using love.math.compress.
|
||||
--- Returns compressed_string, or nil if compression made it larger.
|
||||
local function deflate(data)
|
||||
-- "zlib" wraps DEFLATE with a 2-byte header and 4-byte Adler-32 checksum.
|
||||
-- For ZIP we need raw DEFLATE, which we get by stripping the zlib envelope.
|
||||
-- love.math.compress( rawstring, format, level )
|
||||
-- love.data.compress( container, format, rawstring, level )
|
||||
local zlib_data = love.data.compress("string", "zlib", data, 6) -- level 6 = default
|
||||
|
||||
-- Strip the 2-byte zlib header and 4-byte Adler-32 trailer
|
||||
local raw_deflate = zlib_data:sub(3, -5)
|
||||
|
||||
if #raw_deflate >= #data then
|
||||
return nil -- not worth compressing
|
||||
end
|
||||
return raw_deflate
|
||||
end
|
||||
|
||||
--- MS-DOS date/time encoding for the current time.
|
||||
local function dos_datetime()
|
||||
local t = os.date("*t")
|
||||
local date = ((t.year - 1980) * 512) + (t.month * 32) + t.day
|
||||
local time = (t.hour * 2048) + (t.min * 32) + math.floor(t.sec / 2)
|
||||
return pack_u16(time), pack_u16(date)
|
||||
end
|
||||
|
||||
-- ── Zip writer ────────────────────────────────────────────────────────────────
|
||||
|
||||
--- Create a new Zip writer instance.
|
||||
function Zip.new()
|
||||
return setmetatable({ _entries = {}, _offset = 0 }, Zip)
|
||||
end
|
||||
|
||||
--- Add a file to the zip.
|
||||
-- @param path string Archive path, e.g. "maps/level1.lua". Use '/' separators.
|
||||
-- @param data string Raw file contents.
|
||||
function Zip:add(path, data)
|
||||
assert(type(path) == "string", "path must be a string")
|
||||
assert(type(data) == "string", "data must be a string")
|
||||
assert(not path:match("^/"), "path must not start with '/'")
|
||||
|
||||
local crc = crc32(data)
|
||||
local original = #data
|
||||
local compressed, method
|
||||
|
||||
local deflated = deflate(data)
|
||||
if deflated then
|
||||
compressed = deflated
|
||||
method = 8 -- DEFLATE
|
||||
else
|
||||
compressed = data
|
||||
method = 0 -- Stored
|
||||
end
|
||||
|
||||
table.insert(self._entries, {
|
||||
path = path,
|
||||
data = data, -- uncompressed (kept for the central dir)
|
||||
compressed = compressed,
|
||||
method = method,
|
||||
crc = crc,
|
||||
size_orig = original,
|
||||
size_comp = #compressed,
|
||||
offset = self._offset,
|
||||
})
|
||||
|
||||
-- Local file header = 30 bytes + filename length + compressed data length
|
||||
self._offset = self._offset + 30 + #path + #compressed
|
||||
end
|
||||
|
||||
--- Build and return the full zip file as a binary string.
|
||||
function Zip:build()
|
||||
local parts = {}
|
||||
|
||||
-- ── Local file headers + data ────────────────────────────────────────────
|
||||
for _, e in ipairs(self._entries) do
|
||||
local dos_time, dos_date = dos_datetime()
|
||||
|
||||
-- Local file header signature
|
||||
parts[#parts+1] = "\x50\x4B\x03\x04" -- PK\3\4
|
||||
parts[#parts+1] = "\x14\x00" -- version needed: 2.0
|
||||
parts[#parts+1] = "\x00\x00" -- general purpose bit flag
|
||||
parts[#parts+1] = pack_u16(e.method)
|
||||
parts[#parts+1] = dos_time
|
||||
parts[#parts+1] = dos_date
|
||||
parts[#parts+1] = pack_u32(e.crc)
|
||||
parts[#parts+1] = pack_u32(e.size_comp)
|
||||
parts[#parts+1] = pack_u32(e.size_orig)
|
||||
parts[#parts+1] = pack_u16(#e.path) -- filename length
|
||||
parts[#parts+1] = "\x00\x00" -- extra field length
|
||||
parts[#parts+1] = e.path
|
||||
parts[#parts+1] = e.compressed
|
||||
end
|
||||
|
||||
local central_dir_offset = 0
|
||||
for _, p in ipairs(parts) do central_dir_offset = central_dir_offset + #p end
|
||||
|
||||
-- ── Central directory ────────────────────────────────────────────────────
|
||||
local central_parts = {}
|
||||
for _, e in ipairs(self._entries) do
|
||||
local dos_time, dos_date = dos_datetime()
|
||||
|
||||
central_parts[#central_parts+1] = "\x50\x4B\x01\x02" -- PK\1\2
|
||||
central_parts[#central_parts+1] = "\x14\x00" -- version made by: 2.0
|
||||
central_parts[#central_parts+1] = "\x14\x00" -- version needed: 2.0
|
||||
central_parts[#central_parts+1] = "\x00\x00" -- general purpose bit flag
|
||||
central_parts[#central_parts+1] = pack_u16(e.method)
|
||||
central_parts[#central_parts+1] = dos_time
|
||||
central_parts[#central_parts+1] = dos_date
|
||||
central_parts[#central_parts+1] = pack_u32(e.crc)
|
||||
central_parts[#central_parts+1] = pack_u32(e.size_comp)
|
||||
central_parts[#central_parts+1] = pack_u32(e.size_orig)
|
||||
central_parts[#central_parts+1] = pack_u16(#e.path) -- filename length
|
||||
central_parts[#central_parts+1] = "\x00\x00" -- extra field length
|
||||
central_parts[#central_parts+1] = "\x00\x00" -- file comment length
|
||||
central_parts[#central_parts+1] = "\x00\x00" -- disk number start
|
||||
central_parts[#central_parts+1] = "\x00\x00" -- internal attributes
|
||||
central_parts[#central_parts+1] = "\x00\x00\x00\x00" -- external attributes
|
||||
central_parts[#central_parts+1] = pack_u32(e.offset) -- offset of local header
|
||||
central_parts[#central_parts+1] = e.path
|
||||
end
|
||||
|
||||
local central_dir_size = 0
|
||||
for _, p in ipairs(central_parts) do central_dir_size = central_dir_size + #p end
|
||||
|
||||
-- ── End of central directory record ─────────────────────────────────────
|
||||
local num_entries = #self._entries
|
||||
local eocd = table.concat({
|
||||
"\x50\x4B\x05\x06", -- PK\5\6 (EOCD signature)
|
||||
"\x00\x00", -- disk number
|
||||
"\x00\x00", -- disk with central dir start
|
||||
pack_u16(num_entries), -- entries on this disk
|
||||
pack_u16(num_entries), -- total entries
|
||||
pack_u32(central_dir_size), -- central dir size
|
||||
pack_u32(central_dir_offset), -- central dir offset
|
||||
"\x00\x00", -- comment length
|
||||
})
|
||||
|
||||
return table.concat(parts)
|
||||
.. table.concat(central_parts)
|
||||
.. eocd
|
||||
end
|
||||
|
||||
return Zip
|
||||
+1
-1
@@ -1 +1 @@
|
||||
1.0.1
|
||||
1.0.4
|
||||
Reference in New Issue
Block a user