Untitled conversation
- User
local gamePath = arg[1] if not gamePath then printError("Obsi error: No path specified!") printError("Usage: obsi <path>") return end gamePath = fs.combine(shell.dir(), gamePath) if not fs.exists(gamePath) then printError("Obsi error: Path does not exist!") printError(("Path being: %s"):format(gamePath)) printError("Please make sure that your path is correct!") return elseif not fs.isDir(gamePath) then printError("Obsi error: Path is not a folder!") printError(("Path being: %s"):format(gamePath)) printError("Please make sure that your path is correct!") return end ---@class obsi obsi = {} ---@type function obsi.config = nil local config = { maxfps = 20, mintps = 60, multiUpdate = true, renderingAPI = "parea" } local r = require "cc.require" local env = setmetatable({obsi = obsi}, { __index = _G }) env.require, env.package = r.make(env, gamePath) if fs.exists(fs.combine(gamePath, "config.lua")) then local chunk, err = loadfile(fs.combine(gamePath, "config.lua"), "bt", env) if not chunk then printError(("obsi: config.lua file is found but can't be executed!")) printError(err) return end chunk() if obsi.config then obsi.config(config) end -- if config.maxfps > config.mintps then -- config.maxfps = config.mintps -- end end ---@type parea.Canvas|pixelbox.box local canvas ---@type Window local winh local soundLoop, mouseDown, mouseMove, mouseUp local emptyFunc = function(...) end obsi.system = require("system") obsi.graphics, canvas, winh = require("graphics")(gamePath, config.renderingAPI) obsi.time = require("time") obsi.keyboard = require("keyboard") obsi.mouse, mouseDown, mouseUp, mouseMove = require("mouse")() obsi.audio, soundLoop = require("audio")(gamePath) obsi.state = require("state") obsi.debug = false obsi.version = "1.4.1" -- obsi.debugger = peripheral.find("debugger") or (periphemu and periphemu.create("right", "debugger") and peripheral.find("debugger")) local chunk, err = loadfile(fs.combine(gamePath, "main.lua"), "bt", env) if not chunk then printError(("obsi: %s not found!"):format(fs.combine(gamePath, "main.lua"))) printError(err) return end obsi.load = emptyFunc obsi.update = emptyFunc obsi.draw = emptyFunc obsi.mousePressed = emptyFunc obsi.mouseReleased = emptyFunc obsi.mouseMoved = emptyFunc obsi.keyPressed = emptyFunc obsi.keyReleased = emptyFunc obsi.windowFlush = emptyFunc -- sends a window object as a first argument, which you can mutate if you wish. obsi.resize = emptyFunc -- sends width and height of the window in characters, not pixels. obsi.onEvent = emptyFunc -- for any events that aren't caught! Runs last so that you won't mutate it. obsi.quit = emptyFunc -- called when Obsi recieves "terminate" event. chunk() local function clock() return periphemu and os.epoch(("nano")--[[@as "local"]])/10^9 or os.clock() end ---@param time number local function sleepRaw(time) local timerID = os.startTimer(time) while true do local _, tID = os.pullEventRaw("timer") if tID == timerID then break end end end local t = clock() local dt = 1/config.maxfps local drawTime = t local updateTime = t local frameTime = t local function gameLoop() obsi.load() while true do local startTime = clock() if config.multiUpdate then local updated = false for _ = 1, dt/(1/config.mintps) do obsi.update(1/config.mintps) updated = true end if not updated then obsi.update(dt) end else obsi.update(dt) end updateTime = clock() - startTime startTime = clock() obsi.draw(dt) drawTime = clock() - startTime obsi.graphics.setCanvas() soundLoop(dt) if obsi.debug then local bg, fg = obsi.graphics.bgColor, obsi.graphics.fgColor obsi.graphics.bgColor, obsi.graphics.fgColor = colors.black, colors.white obsi.graphics.write("Obsi "..obsi.version, 1, 1) obsi.graphics.write(obsi.system.getHost(), 1, 2) obsi.graphics.write(("rendering: %s [%sx%s]"):format(obsi.graphics.getRenderer(), obsi.graphics.getPixelSize()), 1, 3) obsi.graphics.write(("%.2f fps"):format(1/dt), 1, 4) obsi.graphics.write(("%0.2fms update"):format(updateTime*1000), 1, 5) obsi.graphics.write(("%0.2fms draw"):format(drawTime*1000), 1, 6) obsi.graphics.write(("%0.2fms frame"):format(frameTime*1000), 1, 7) obsi.graphics.bgColor, obsi.graphics.fgColor = bg, fg end obsi.graphics.flushAll() obsi.windowFlush(winh) obsi.graphics.show() frameTime = clock() - startTime repeat sleepRaw((1/config.maxfps)/20) until (clock()-t >= 1/config.maxfps) obsi.graphics.clear() obsi.graphics.bgColor, obsi.graphics.fgColor = colors.black, colors.white obsi.graphics.resetOrigin() dt = clock()-t t = clock() end end local function eventLoop() while true do local eventData = {os.pullEventRaw()} if eventData[1] == "mouse_click" then mouseDown(eventData[3], eventData[4], eventData[2]) obsi.mousePressed(eventData[3], eventData[4], eventData[2]) elseif eventData[1] == "mouse_up" then mouseUp(eventData[3], eventData[4], eventData[2]) obsi.mouseReleased(eventData[3], eventData[4], eventData[2]) elseif eventData[1] == "mouse_move" then -- apparently the second index is only there for compatibility? Alright. mouseMove(eventData[3], eventData[4]) obsi.mouseMoved(eventData[3], eventData[4]) elseif eventData[1] == "mouse_drag" then mouseMove(eventData[3], eventData[4]) obsi.mouseMoved(eventData[3], eventData[4]) elseif eventData[1] == "term_resize" then local w, h = term.getSize() winh.reposition(1, 1, w, h) canvas:resize(w, h) obsi.graphics.pixelWidth, obsi.graphics.pixelHeight = canvas.width, canvas.height obsi.graphics.width, obsi.graphics.height = w, h obsi.resize(w, h) elseif eventData[1] == "key" and not eventData[3] then obsi.keyboard.keys[keys.getName(eventData[2])] = true obsi.keyboard.scancodes[eventData[2]] = true obsi.keyPressed(eventData[2]) -- --the code below is only for testing! if eventData[2] == keys.l then local rentab = { ["pixelbox"] = "parea", ["parea"] = "hmon", ["hmon"] = "pixelbox", } obsi.graphics.setRenderer(rentab[obsi.graphics.getRenderer()] or "parea") elseif eventData[2] == keys.p then obsi.debug = not obsi.debug end elseif eventData[1] == "key_up" then obsi.keyboard.keys[keys.getName(eventData[2])] = false obsi.keyboard.scancodes[eventData[2]] = false obsi.keyReleased(eventData[2]) elseif eventData[1] == "terminate" then obsi.quit() obsi.graphics.clearPalette() term.setBackgroundColor(colors.black) term.clear() term.setCursorPos(1, 1) return end obsi.onEvent(eventData) end end local function catch(err) obsi.graphics.clearPalette() term.setBackgroundColor(colors.black) term.clear() term.setCursorPos(1, 1) printError(debug.traceback(err, 2)) end parallel.waitForAny(function() xpcall(gameLoop, catch) end, function() xpcall(eventLoop, catch) end)Read the source code of the
obsi.luafile (the core of 2D game engine called Obsi) and tell me what are your thoughts about the structure of this game engine. - Assistant
The
obsi.luafile outlines a 2D game engine for ComputerCraft, a mod for Minecraft that introduces programmable computers and peripherals into the game. The script is quite comprehensive, showcasing a well-thought-out structure aimed at providing a robust framework for creating games or graphical applications within the ComputerCraft environment. Here are some detailed thoughts on its structure and components:Modular Design
- The engine is modular, with clear separations between different functionalities like graphics, audio, input handling (keyboard and mouse), and system utilities. This design facilitates easier maintenance and potential expansion of the engine.
- Dependencies are managed through a custom
requirefunction, which allows for dynamic loading of modules relative to the game path. This is a clever use of Lua's flexibility to adapt to the ComputerCraft filesystem.
Configuration and Flexibility
- The engine supports external configuration via a
config.luafile, allowing developers to adjust settings like FPS, TPS (ticks per second), and the rendering API. This flexibility is crucial for tailoring the engine to different games' needs and performance profiles. - There's a provision for multi-rendering APIs, with a default setup for
parea. It indicates an intention to support different rendering backends, which is excellent for performance optimization and compatibility across various ComputerCraft versions or hardware.
Event-driven Architecture
- The engine operates on an event-driven architecture, with a main loop that handles drawing, updates, and input events. This approach is well-suited to the event-based nature of ComputerCraft's API and Minecraft's game loop.
- Custom event handling functions (
mousePressed,mouseReleased,mouseMoved,keyPressed,keyReleased, etc.) are defined but set to empty implementations, allowing developers to override them as needed. This flexibility is excellent for creating interactive applications.
Debugging and Development Features
- There's a debugging mode toggleable by pressing a specific key (
p), which displays performance metrics and engine version information. This feature is invaluable during development for monitoring performance and identifying bottlenecks. - Commented out code and placeholders for future features (e.g., debugger peripheral integration) suggest ongoing development and consideration for advanced debugging tools.
Error Handling and Robustness
- The script employs
xpcalland custom error handling to catch and report errors gracefully. This approach enhances the robustness of games developed with the engine, providing clear feedback to developers when issues arise. - Comprehensive error checking at the start (for path validity and directory checks) prevents common setup mistakes and guides the developer with clear error messages.
Performance Considerations
- The engine includes mechanisms to control frame rates and update rates, crucial for creating smooth and responsive games. The
multiUpdatefeature, which can adjust update frequency based on performance, shows a nuanced approach to managing game loop timing.
Conclusion
Overall, the
obsi.luascript presents a solid foundation for a 2D game engine within the ComputerCraft environment. Its modular design, flexibility, and thoughtful inclusion of development and debugging tools reflect well on its potential to support a wide range of games and applications. Future improvements could include more detailed documentation within the code, expanded support for different rendering APIs, and further optimization of the game loop for performance.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.