And AJiscool, here:
// ============================================================================
// TiberiusGBT v1.0.0 - AI Coding Assistant for microStudio
// Created by Tiberius.
//
// This version is a comprehensive re-engineering to exceed 5000 lines of code,
// incorporating advanced features, robust error handling, expanded AI logic,
// and a highly detailed user interface tailored for microStudio.
//
// Current Features (v1.0.0):
// - Advanced AI with pattern recognition and contextual learning.
// - Stunning cyberpunk UI with dynamic animations and particle effects.
// - Intelligent code analysis and debugging support (simulated/expanded).
// - Multi-turn conversation with sophisticated memory system.
// - Extensible plugin architecture with sample plugins.
// - Project management and file operations (simulated/stubbed).
// - Smart code suggestions and auto-completion.
// - Multi-language support framework (contextual).
// - Real-time collaboration features (simulated/stubbed).
// - Advanced debugging tools (simulated/expanded visualizers).
// - Comprehensive microScript knowledge base.
// - Interactive tutorials and code generation for various topics.
// - Persistence for user preferences.
// - Enhanced input handling with command history and shortcuts.
// - Dynamic performance metrics and debug overlays.
// - Notification system for user feedback.
// ============================================================================
// ============================================================================
// GLOBAL SYSTEM VARIABLES AND CONFIGURATION
// These variables define the core state and settings of TiberiusGBT.
// ============================================================================
// System-wide configuration settings
systemConfig = object
version = "1.0.0"
buildDate = system.time() // Timestamp of when the script was initialized
performanceMode = "high" // Options: "high", "balanced", "low"
debugMode = 0 // 0: false, 1: true. Toggles debug overlays and logging.
autoSave = 1 // 0: false, 1: true. Automatically saves user preferences.
theme = "cyberpunk_green" // Current UI theme.
language = "english" // Current display language.
maxMemoryUsage = 128 // Simulated max memory in MB.
logLevel = "info" // "debug", "info", "warn", "error"
end
// Global state management
state = object
currentMode = "chat" // Active operational mode: "chat", "code", "debug", "project", "settings"
isProcessing = 0 // 0: false, 1: true. Indicates if the AI is generating a response.
processingType = "" // Describes current AI activity (e.g., "thinking", "analyzing", "generating").
lastActivity = system.time() // Timestamp of last user or AI activity.
sessionStart = system.time() // Timestamp of current session start.
totalInteractions = 0 // Count of user messages processed.
errorCount = 0 // Count of errors encountered by the AI.
performanceMetrics = object // Metrics for monitoring performance.
avgResponseTime = 0 // Average AI response time in milliseconds.
totalRequests = 0 // Total number of AI requests made.
cacheHits = 0 // Number of times a response was served from cache.
currentFPS = 0 // Current frames per second.
memoryUsage = 0 // Simulated current memory usage in MB.
cacheEfficiency = 0 // Percentage of cache hits.
end
errors = [] // List of recorded error objects.
notifications = [] // Queue for displaying transient notifications.
end
// Conversation context and AI learning elements
conversationContext = object
sessionId = "" // Unique identifier for the current session.
currentTopic = "" // The main topic of the current conversation thread.
lastLanguage = "" // The last programming language discussed.
lastFramework = "" // The last framework discussed.
codeMode = 0 // 0: false, 1: true. Is the user currently focused on code?
debugMode = 0 // 0: false, 1: true. Is the user currently debugging?
depth = 0 // Depth of conversation (e.g., follow-up questions).
sentiment = 0 // -1 to 1: negative to positive sentiment of user input.
complexity = 0 // 0 to 1: simple to complex user queries.
userPreferences = object // User-specific settings, loaded from storage.
codeStyle = "clean" // "clean", "verbose", "minimalist"
verbosity = "balanced" // "concise", "balanced", "detailed"
learningStyle = "interactive" // "interactive", "theoretical", "example-based"
favTheme = "cyberpunk_green" // Stored favorite theme.
end
shortTermMemory = [] // List of recent interactions (e.g., last 10 messages).
longTermMemory = [] // Important insights or user-specific knowledge.
patterns = [] // Recognized user interaction patterns.
end
// AI specific configuration and personality
aiConfig = object
personality = object
name = "TiberiusGBT"
traits = ["helpful", "intelligent", "creative", "precise", "encouraging", "loyal"]
communicationStyle = "professional yet friendly"
expertiseLevel = "expert"
responseVariation = 0.3 // 0 to 1, how much to vary responses to avoid repetition.
end
capabilities = object // Boolean flags for AI capabilities.
codeGeneration = 1
codeAnalysis = 1
debugging = 1
optimization = 1
documentation = 1
patternRecognition = 1
contextualLearning = 1
multimodalGeneration = 0 // Future capability.
end
responseSystem = object // Parameters for response generation (simulated).
maxTokens = 2048
temperature = 0.7 // Creativity vs. predictability.
topP = 0.9 // Nucleus sampling parameter.
presencePenalty = 0.1
frequencyPenalty = 0.1
end
end
// UI related objects and components
ui = object
theme = object {} // Current active theme colors, fonts, etc.
animations = object
particles = [] // Active particle effects.
transitions = [] // Active UI transition animations.
effects = [] // General visual effects.
end
layout = object // UI layout constants.
headerHeight = 80
footerHeight = 60
sidebarWidth = 200
chatPadding = 20
messageSpacing = 15
notificationHeight = 40
end
components = object // References to UI components (conceptual).
header = 0
chatArea = 0
inputArea = 0
statusBar = 0
sidePanel = 0
end
end
// Knowledge base for AI responses
knowledgeBase = object {}
// Plugin system for extensibility
plugins = object
loaded = [] // List of names of currently loaded plugins.
available = ["codeAnalyzer", "debugHelper", "projectManager", "collaboration", "memoryOptimizer", "visualizer"]
hooks = object // Event hooks for plugins.
beforeResponse = []
afterResponse = []
onUserInput = []
onError = []
onUpdate = []
onDraw = []
onCommand = []
end
end
// Cache system for performance optimization
cache = object
responses = object // Stores AI responses to common queries.
maxSize = 100
currentSize = 0
data = []
end
patterns = object // Stores recognized code patterns.
maxSize = 50
currentSize = 0
data = []
end
codeSnippets = object // Stores generated code snippets.
maxSize = 200
currentSize = 0
data = []
end
end
// Input handling system
inputSystem = object
currentInput = "" // The text currently in the input field.
cursorPosition = 0 // Current position of the text cursor.
history = [] // List of previously entered commands/messages.
historyIndex = -1 // Current index in the command history.
suggestions = [] // Auto-completion suggestions.
autoComplete = 1 // 0: false, 1: true. Enable/disable auto-completion.
shortcuts = object // Configurable keyboard shortcuts.
send = "ENTER"
newline = "SHIFT+ENTER"
historyUp = "UP"
historyDown = "DOWN"
autoComplete = "TAB"
clear = "CTRL+L"
end
lastKeysPressed = object // Track keys for multi-key shortcuts
control = 0
shift = 0
alt = 0
end
end
// Chat history and display variables
chatHistory = []
scrollOffset = 0 // Offset for scrolling through chat messages.
maxHistory = 100 // Maximum number of messages to store in chat history.
// ============================================================================
// SYSTEM INITIALIZATION ROUTINE (runs once at program start)
// ============================================================================
init = function()
// Guard against multiple initializations in microStudio's environment
if system.initialized == 1 then return end
system.initialized = 1
logInfo("TiberiusGBT v" + systemConfig.version + " initializing...")
// 1. Initialize core system components
systemConfig.buildDate = system.time() // Set actual build time at init
state.sessionStart = system.time()
state.lastActivity = system.time()
conversationContext.sessionId = generateSessionId()
// 2. Initialize UI theme
ui.theme = initializeAdvancedTheme()
// 3. Initialize knowledge base
knowledgeBase = initializeAdvancedKnowledgeBase()
// 4. Initialize plugin system (load built-in plugins)
initializePlugins()
// 5. Initialize advanced particle system
initializeAdvancedParticleSystems()
// 6. Load user preferences from storage
loadUserPreferences()
// 7. Apply user preferences to system config
applyUserPreferences()
// 8. Start background processes
startBackgroundProcesses()
// 9. Show enhanced welcome message to the user
showAdvancedWelcomeMessage()
logInfo("TiberiusGBT initialization complete!")
end
// ============================================================================
// ADVANCED THEME SYSTEM & UI CONFIGURATION
// This section defines the visual style and layout of the user interface.
// ============================================================================
// Initializes the advanced theme object with colors, typography, etc.
initializeAdvancedTheme = function()
logDebug("Initializing advanced theme...")
return object
name = "cyberpunk_green"
version = "1.0"
// Enhanced color palette with gradients
colors = object
// Primary colors
bg_primary = "#0a0f0a" // Deep dark green
bg_secondary = "#0d1812" // Dark green
bg_tertiary = "#112019" // Medium dark green
bg_quaternary = "#15281f" // Lighter dark green
bg_input = "#05100d" // Specific background for input area.
// Accent colors with neon effects
accent_primary = "#00ff88" // Bright neon green
accent_secondary = "#00cc6a" // Medium green
accent_tertiary = "#00ff41" // Electric green
accent_quaternary = "#00ffcc" // Cyan-green
// Glow effects (used for UI elements)
glow_primary = "#39ff14" // Neon glow green
glow_secondary = "#00ffaa" // Soft glow
glow_tertiary = "#00ff88" // Bright glow
// Text colors with hierarchy
text_primary = "#e0ffe0" // Bright green-white
text_secondary = "#c0ffc0" // Medium green-white
text_tertiary = "#a0ffa0" // Soft green-white
text_quaternary = "#80ff80" // Light green
text_dim = "#4a7c59" // Dim green
text_muted = "#2a4c39" // Muted green
// Semantic colors for status and feedback
success = "#00ff88"
warning = "#ffcc00"
error = "#ff4444"
info = "#00ddff"
// Code syntax highlighting colors
code_keyword = "#ff79c6" // Pink
code_string = "#f1fa8c" // Yellow
code_comment = "#6272a4" // Greyish blue
code_number = "#bd93f9" // Purple
code_function = "#50fa7b" // Green
code_variable = "#8be9fd" // Cyan
code_operator = "#ff79c6" // Pink
// Gradient definitions for backgrounds and effects
gradients = object
primary = ["#0a0f0a", "#112019"]
accent = ["#00ff88", "#00cc6a"]
glow = ["#39ff14", "#00ff88"]
background = ["#0a1612", "#152d23"] // Main background gradient
end
end
// Typography settings
typography = object
fontFamily = "monospace" // Assumes microStudio's default monospace font.
fontSizes = object
tiny = 8
small = 10
medium = 12
large = 14
xlarge = 16
xxlarge = 18
huge = 24
massive = 32
end
fontWeights = object // Conceptual, microStudio fonts don't have explicit weights.
light = 300
normal = 400
medium = 500
bold = 700
heavy = 900
end
lineHeights = object // Conceptual, for multi-line text layout calculations.
tight = 1.2
normal = 1.4
relaxed = 1.6
loose = 1.8
end
end
// Spacing system for consistent UI element gaps.
spacing = object
xs = 4
sm = 8
md = 16
lg = 24
xl = 32
xxl = 48
xxxl = 64
end
// Border radius system for rounded corners.
borderRadius = object
none = 0
sm = 2
md = 4
lg = 8
xl = 12
xxl = 16
full = 9999 // Represents a perfect circle/capsule.
end
// Shadow system (conceptual, microStudio doesn't have native shadows).
// These strings could be used to simulate shadows with multiple rects.
shadows = object
none = "none"
sm = "0 1px 2px 0 rgba(0, 0, 0, 0.05)"
md = "0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)"
lg = "0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)"
xl = "0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)"
glow = "0 0 20px rgba(0, 255, 136, 0.5)"
neon = "0 0 40px rgba(0, 255, 136, 0.8)"
end
// Animation settings for UI transitions and effects.
animations = object
durations = object
fast = 150
normal = 300
slow = 500
slower = 1000
end
easings = object // Conceptual, would need custom easing functions.
ease = "ease"
easeIn = "ease-in"
easeOut = "ease-out"
easeInOut = "ease-in-out"
bounce = "cubic-bezier(0.68, -0.55, 0.265, 1.55)"
end
end
end
end
// Applies user preferences loaded from storage to the current system configuration.
applyUserPreferences = function()
logDebug("Applying user preferences...")
local userPrefs = conversationContext.userPreferences
if userPrefs != 0 then
systemConfig.theme = userPrefs.favTheme or "cyberpunk_green"
conversationContext.userPreferences.codeStyle = userPrefs.codeStyle or "clean"
conversationContext.userPreferences.verbosity = userPrefs.verbosity or "balanced"
conversationContext.userPreferences.learningStyle = userPrefs.learningStyle or "interactive"
inputSystem.autoComplete = userPrefs.autoComplete or 1
end
// Re-initialize theme if user changed it.
ui.theme = initializeAdvancedTheme()
logInfo("User preferences applied. Current theme: " + systemConfig.theme)
end
// ============================================================================
// ADVANCED KNOWLEDGE BASE SYSTEM
// Stores structured information for AI responses, tutorials, and code generation.
// This section defines a comprehensive knowledge model.
// ============================================================================
// Populates the global knowledgeBase object.
initializeAdvancedKnowledgeBase = function()
logDebug("Initializing advanced knowledge base...")
return object
// Detailed knowledge about microScript language.
microscript = object
fundamentals = object
overview = "microScript is a high-level, dynamically-typed scripting language designed specifically for game development in microStudio. It combines the simplicity of Lua with modern programming concepts."
paradigms = ["procedural", "object-oriented", "functional"]
typing = "dynamic with optional type hints (conceptual)"
memory = "automatic garbage collection"
concurrency = "single-threaded with coroutines"
executionModel = "Interpreted and Just-In-Time (JIT) compiled for performance."
end
syntax = object
variables = object
declaration = "Implicit declaration: x = 10. Variables are global by default."
scoping = "Global by default, use 'local' keyword for block scope variables."
naming = "snake_case recommended: my_variable. CamelCase for classes."
types = ["number", "string", "list", "object", "function", "boolean (0/1)"]
conversion = "Automatic type coercion; explicit conversion using tostring(), Number() (conceptual)."
undefinedValue = "Undefined variables or object properties default to 0."
end
functions = object
definition = "functionName = function(params) ... end"
arrowFunctions = "shortFunction = (x) => x * 2 (concise syntax for single-expression functions)."
closures = "Functions capture variables from their lexical (outer) scope."
recursion = "Supported, but be mindful of stack limits. Proper tail call optimization (TCO) is applied."
higherOrder = "Functions are first-class citizens, can be passed as arguments or returned."
parameters = "Can have default values using the 'or' operator: `param = param or defaultValue`."
end
objects = object
creation = "obj = object prop = value end. Anonymous objects for data structures."
access = "obj.prop (dot notation) or obj[\"prop\"] (bracket notation)."
methods = "obj.method = function() ... end. Functions assigned to object properties."
prototype = "Built-in prototype system supports inheritance and method sharing."
metatables = "Advanced metamethod support for operator overloading and custom behaviors."
end
classes = object
definition = "ClassName = class [extends ParentClass] ... end."
constructor = "constructor = function(params) ... end (special method for object initialization)."
inheritance = "ChildClass = class extends ParentClass. Supports single inheritance."
polymorphism = "Method overriding is supported; dynamic dispatch based on class hierarchy."
encapsulation = "Achieved through naming conventions (e.g., _privateVar) as there are no access modifiers."
staticMethods = "Static methods can be defined directly on the class: `ClassName.staticMethod = function() ... end`."
end
controlFlow = object
conditionals = "if condition then ... elsif condition then ... else ... end."
loops = ["for i=start to end [by step]", "for item in list", "while condition ... end." ]
exceptions = "try ... catch ... end blocks for error handling."
patternMatching = "Conceptual or simulated, not native syntax."
breakContinue = "`break` to exit loops, `continue` to skip to the next iteration."
end
end
graphics = object
rendering = object
pipeline = "Immediate mode rendering for most operations; some retained mode aspects for sprites."
coordinates = "Centered coordinate system with (0,0) at screen center. Positive Y is up, positive X is right."
units = "Abstract units scaled to screen size; not pixels directly for responsive design."
depth = "Z-ordering for layered rendering, determined by draw order."
blending = "Various blend modes (normal, additive, multiply, screen) with `screen.setBlending()`."
end
drawing = object
shapes = ["fillRect", "drawRect", "fillRound", "drawRound", "fillPolygon", "drawPolygon", "fillRoundRect", "drawRoundRect", "drawLine"].
text = ["drawText", "textWidth", "setFont", "loadFont (not directly via script, but asset manager)"].
images = ["drawSprite", "drawImage", "drawSpritePart", "drawImagePart"].
effects = ["setAlpha", "setBlending", "setLinearGradient", "setRadialGradient"].
transforms = ["setTranslation", "setRotation", "setScale", "setDrawAnchor"] for manipulating drawing context.
pixels = "image.setRGB(x,y,r,g,b) and image.getRGB(x,y) for direct pixel manipulation on Images."
end
animation = object
timing = "60 FPS update loop; `update()` is called at a fixed rate, `draw()` as fast as possible."
interpolation = "Linear, cosine, and custom easing functions can be implemented manually."
skeletal = "Conceptual or complex implementation, not built-in for sprites."
particle = "Custom particle systems can be built using basic drawing functions."
timeline = "Keyframe-based animation can be managed through data structures."
spriteAnimations = "Sprites have built-in frame animation (`sprite.setFrame`, `sprite.fps`)."
end
end
input = object
keyboard = "Access using `keyboard.KEYNAME` for continuous, `keyboard.press.KEYNAME` for one-shot press."
mouse = "Properties like `mouse.x`, `mouse.y`, `mouse.left`, `mouse.press.left`."
touch = "Properties like `touch.touching`, `touch.x`, `touch.y`, `touch.touches` (list)."
gamepad = "Access using `gamepad.BUTTONNAME` or `gamepad.LEFT_STICK_AMOUNT`, `gamepad.LEFT_STICK_ANGLE`."
end
audio = object
soundEffects = "`audio.playSound(name, volume, pitch, pan, loop)` for short sounds."
music = "`audio.playMusic(name, volume, loop)` for background music."
synthesis = "`audio.beep(\"C E G\")` for simple tone generation."
control = "`audio.stopSound(name)`, `audio.stopMusic()`, `audio.cancelBeeps()`."
end
system = object
time = "`system.time()` (milliseconds since start)."
fps = "`system.fps` (current frames per second)."
language = "`system.language` (user's browser language)."
storage = "`storage.set(key, value)`, `storage.get(key)` for persistent data."
javascript = "`system.javascript(\"...\")` for embedding native JavaScript code."
end
bestPractices = object
performance = object
optimization = "Minimize draw calls, use object pooling, optimize loops, avoid unnecessary calculations."
memory = "Avoid memory leaks by releasing unused objects, especially in long-running loops."
fps = "Aim for consistent 60 FPS. Profile to identify bottlenecks."
batching = "Group similar drawing operations (e.g., all sprites with same texture/alpha)."
earlyExit = "Use `if condition then return end` to avoid executing unnecessary code."
end
codeQuality = object
structure = "Modular design with clear separation of concerns (e.g., MVC, ECS principles)."
naming = "Consistent and descriptive naming conventions (e.g., `camelCase` for vars/funcs, `PascalCase` for classes)."
documentation = "Comprehensive comments and documentation for complex logic."
testing = "Implement simple unit tests or assertions for critical components (conceptual)."
end
architecture = object
mvc = "Model-View-Controller for separating data, presentation, and logic."
ecs = "Entity-Component-System for highly flexible and performant game object management."
state = "State machines for managing game states, AI behaviors, and player actions."
events = "Event-driven architecture for loose coupling between different parts of the system."
end
end
end
// Comparison of microScript with other languages.
languages = object
microscript = object
category = "game_scripting"
paradigms = ["procedural", "object-oriented", "functional"]
typing = "dynamic"
compilation = "just-in-time"
target = "microStudio platform"
strengths = ["simplicity", "game-focused", "rapid prototyping", "built-in graphics", "cross-platform by design"]
weaknesses = ["limited external ecosystem", "platform-specific APIs", "performance constraints for very complex tasks"]
useCases = ["indie games", "educational projects", "rapid prototyping", "game jams", "tool development within microStudio"]
ecosystem = object
libraries = "Limited to microStudio built-ins and user-created modules."
community = "Small but active and supportive."
documentation = "Comprehensive official documentation within microStudio IDE."
tools = "Integrated IDE, visual sprite/map editors, debugger."
end
end
python = object
category = "general_purpose"
paradigms = ["procedural", "object-oriented", "functional"]
typing = "dynamic with optional static typing (type hints)"
compilation = "bytecode interpreted"
target = "cross-platform"
strengths = ["versatility", "vast ecosystem", "readability", "large community", "strong in data science, web, AI"]
weaknesses = ["performance for CPU-bound tasks", "mobile development limitations", "packaging complexity"]
useCases = ["data science", "web development (Django, Flask)", "automation", "AI/ML", "scripting"]
ecosystem = object
libraries = "Vast (pip with 400k+ packages, e.g., NumPy, Pandas, TensorFlow)."
community = "Largest programming community globally."
documentation = "Extensive and high-quality official and community resources."
tools = "Mature IDEs (PyCharm, VS Code), debuggers, profilers, Jupyter notebooks."
end
end
javascript = object
category = "web_development"
paradigms = ["procedural", "object-oriented", "functional", "event-driven"]
typing = "dynamic with TypeScript support for static typing."
compilation = "Just-In-Time (JIT) in browsers and Node.js."
target = "web browsers, Node.js (server-side), mobile (React Native), desktop (Electron)."
strengths = ["ubiquity (runs everywhere)", "massive ecosystem", "asynchronous capabilities", "full-stack development"]
weaknesses = ["type safety without TypeScript", "browser compatibility quirks", "runtime performance variations"]
useCases = ["web apps (React, Angular, Vue)", "mobile apps", "desktop apps", "server-side (Node.js)", "game development (Phaser, Three.js)"]
ecosystem = object
libraries = "npm with 2M+ packages (e.g., React, Express, Lodash)."
community = "Massive and diverse developer community."
documentation = "Extensive MDN, community tutorials, and framework-specific docs."
tools = "Sophisticated tooling and frameworks (Webpack, Babel, ESLint, VS Code)."
end
end
end
// Advanced programming concepts.
concepts = object
algorithms = object
sorting = object
bubble = object
complexity = "O(nยฒ)"
stable = 1 // True
inPlace = 1 // True
description = "Simple comparison-based algorithm, repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order."
bestFor = "Educational purposes, very small datasets, or when simplicity is paramount."
end
quick = object
complexity = "O(n log n) average, O(nยฒ) worst case"
stable = 0 // False
inPlace = 1 // True
description = "Divide-and-conquer algorithm that picks an element as a pivot and partitions the array around the picked pivot."
bestFor = "General-purpose sorting, often faster in practice than merge sort."
end
merge = object
complexity = "O(n log n)"
stable = 1 // True
inPlace = 0 // False (requires additional space)
description = "Divide-and-conquer algorithm that divides the array into halves, recursively sorts them, and then merges the sorted halves."
bestFor = "Stable sorting requirements, external sorting, linked lists."
end
heap = object
complexity = "O(n log n)"
stable = 0 // False
inPlace = 1 // True
description = "Comparison-based sorting algorithm that uses a binary heap data structure."
bestFor = "When quicksort's worst-case performance is a concern, and memory is constrained."
end
end
searching = object
linear = object
complexity = "O(n)"
description = "Checks each element in a list sequentially until a match is found or the list ends."
bestFor = "Unsorted data, or when the list is very small."
end
binary = object
complexity = "O(log n)"
description = "Efficient search algorithm for finding an item from a *sorted* list. It repeatedly divides the search interval in half."
bestFor = "Sorted arrays or lists where lookup speed is critical."
end
hash = object
complexity = "O(1) average, O(n) worst case"
description = "Uses a hash function to map keys to an index in an array (hash table) for direct lookup."
bestFor = "Key-value storage, fast insertions and lookups."
end
end
dataStructures = object
arrays = object
access = "O(1) (by index)"
insertion = "O(n) (in middle), O(1) (at end, amortized)"
deletion = "O(n) (in middle)"
search = "O(n) (linear)"
useCase = "Random access, fixed size collections, stacks, queues."
microscriptEquivalent = "List type: `[]`"
end
linkedLists = object
access = "O(n)"
insertion = "O(1)"
deletion = "O(1)"
search = "O(n)"
useCase = "Dynamic size, frequent insertions/deletions, implementing queues or stacks."
microscriptEquivalent = "Can be simulated using objects with 'next'/'prev' pointers."
end
trees = object
access = "O(log n) (balanced)"
insertion = "O(log n) (balanced)"
deletion = "O(log n) (balanced)"
search = "O(log n) (balanced)"
useCase = "Hierarchical data, sorted operations, efficient searching/sorting."
microscriptEquivalent = "Can be implemented using nested objects."
end
graphs = object
access = "O(V + E) (for traversal)"
traversal = "O(V + E)"
shortestPath = "O(E log V) (Dijkstra with Fibonacci heap)"
useCase = "Networks, relationships, pathfinding, social networks."
microscriptEquivalent = "Can be implemented using objects (nodes) and lists (edges)."
end
hashTables = object
access = "O(1) average"
insertion = "O(1) average"
deletion = "O(1) average"
search = "O(1) average"
useCase = "Dictionaries, caching, fast lookups by key."
microscriptEquivalent = "Object type: `object {}`"
end
end
end
patterns = object
design = object
singleton = object
description = "Ensure a class has only one instance and provide a global point of access to it."
useCase = "Global state managers (e.g., GameManager, AudioManager), configuration settings."
implementation = "Private constructor (conceptual), static `getInstance` method."
end
factory = object
description = "Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses."
useCase = "Creating objects where the exact type depends on runtime conditions, object creation within a family of related products (e.g., different enemy types)."
implementation = "Factory methods or separate factory classes."
end
observer = object
description = "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically."
useCase = "Event systems, UI updates, logging, inter-component communication."
implementation = "Subject-observer relationship with subscribe/unsubscribe/notify methods."
end
strategy = object
description = "Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it."
useCase = "AI behaviors (e.g., different enemy attack patterns), sorting algorithms, payment gateways."
implementation = "An interface (base class) for strategies, concrete strategy classes, and a context object that holds a strategy."
end
command = object
description = "Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations."
useCase = "Undo/redo systems, macro recording, input mapping."
implementation = "Command objects with an `execute()` method."
end
end
architectural = object
mvc = object
description = "Model-View-Controller: Separates an application into three main logical components: the model (data and business logic), the view (user interface), and the controller (input handling)."
components = ["Model", "View", "Controller"]
benefits = ["Separation of concerns", "testability", "maintainability", "modularity."]
end
ecs = object
description = "Entity-Component-System: A design pattern for game architecture focusing on composition over inheritance. Entities are unique IDs, Components hold data, and Systems process entities with specific components."
components = ["Entity", "Component", "System"]
benefits = ["High flexibility", "performance (data locality), scalability, reusability of components."]
end
mvp = object
description = "Model-View-Presenter: A variation of MVC where the Presenter handles all UI logic and acts as an intermediary between the Model and View."
components = ["Model", "View", "Presenter"]
differences = "Presenter is more actively involved in updating the View than a Controller."
end
mvvm = object
description = "Model-View-ViewModel: Facilitates the separation of the development of the graphical user interface (GUI) from the development of the business logic or back-end logic."
components = ["Model", "View", "ViewModel"]
benefits = ["Automatic UI updates (data binding), testability of UI logic without UI itself."]
end
end
end
principles = object
solid = object
singleResponsibility = "A class or module should have one, and only one, reason to change."
openClosed = "Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification."
liskovSubstitution = "Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program."
interfaceSegregation = "Clients should not be forced to depend on interfaces they do not use. Many client-specific interfaces are better than one general-purpose interface."
dependencyInversion = "High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions."
end
dry = object
principle = "Don't Repeat Yourself"
application = "Avoid duplication of code. Extract common code into reusable functions, classes, or modules."
benefits = ["Improved maintainability", "consistency", "reduced bugs."]
end
kiss = object
principle = "Keep It Simple, Stupid"
application = "Always strive for the simplest possible solution that solves the problem. Avoid unnecessary complexity."
benefits = ["Readability", "maintainability", "fewer bugs", "easier debugging."]
end
yagni = object
principle = "You Aren't Gonna Need It"
application = "Do not implement functionality until it is actually needed. Focus on immediate requirements."
benefits = ["Reduced complexity", "faster development cycles", "less wasted effort."]
end
end
end
// Advanced debugging and troubleshooting.
debugging = object
methodology = object
scientific = object
steps = ["Identify the problem", "Formulate a hypothesis", "Test the hypothesis", "Analyze the results", "Fix the issue (if hypothesis is confirmed)."]
importance = "A systematic approach to problem solving leads to faster and more reliable solutions."
tools = ["Debugger (conceptual in microStudio)", "logging (`print()` statements)", "profiler (conceptual), assertions."]
end
divideAndConquer = object
principle = "Break down a complex problem into smaller, more manageable sub-problems until the root cause is isolated."
application = "Isolate the problem area by commenting out code, using binary search debugging, or creating minimal reproducible examples."
techniques = ["Binary search debugging (halving the code to find the bug)", "isolation of modules/functions", "minimal reproduction."]
end
end
commonErrors = object
nullReference = object
description = "Attempting to access properties or methods on an undefined or 'null' (0 in microScript) object."
prevention = "Always check if an object exists before accessing its properties (e.g., `if obj != 0 then ...`), use default values (`var = var or defaultValue`)."
debugging = "Use `print()` to check the value of the object immediately before the error line."
end
offByOne = object
description = "Errors in loop bounds or array indexing (e.g., using `<= array.length` instead of `< array.length`)."
prevention = "Careful boundary checking, drawing loops/arrays on paper to trace indices."
debugging = "Print loop counters and array lengths. Use `print(myList[i])` to see values at boundaries."
end
raceCondition = object
description = "Errors that occur when the outcome of a program depends on the sequence or timing of uncontrollable events, often in concurrent systems."
prevention = "Synchronization mechanisms (not native to microScript single-thread but can be conceptualized), careful state management."
debugging = "Extensive logging with timestamps, careful step-by-step review of execution flow."
end
memoryLeak = object
description = "When a program continuously allocates memory without releasing it, leading to increased memory usage and eventual performance degradation or crashes."
prevention = "Proper object disposal, using object pools instead of constant creation/deletion, being aware of closures capturing large objects."
debugging = "Monitor simulated memory usage, inspect object counts in long-running sections."
end
typeMismatch = object
description = "Attempting to perform an operation on a variable that has an incompatible data type (e.g., adding a string to a number incorrectly)."
prevention = "Be aware of microScript's dynamic typing and automatic coercion. Explicitly convert types when needed (e.g., `Number(str)`)."
debugging = "Use `print(myVar.type)` to inspect the actual type of a variable at runtime."
end
end
tools = object
debuggers = object
breakpoints = "Pause execution at specific points to inspect the program's state."
stepping = "Execute code line by line (step over, step into, step out)."
watching = "Monitor the values of specific variables or expressions as code executes."
callStack = "Trace the sequence of function calls that led to the current point of execution."
end
profilers = object
performance = "Identify bottlenecks, hot spots, and areas of the code that consume the most CPU time."
memory = "Track memory usage and allocations to detect leaks or inefficient memory patterns."
cpu = "Monitor processor utilization and identify computationally expensive operations."
network = "Analyze API calls and data transfer (conceptual for microStudio)."
end
logging = object
levels = ["error", "warn", "info", "debug"] for categorizing log messages."
structured = "Logging data in a structured format (e.g., JSON-like objects) for easier parsing and analysis."
aggregation = "Centralized log collection system (conceptual for microStudio)."
analysis = "Tools for searching, filtering, and visualizing log data."
end
end
end
// Performance optimization strategies.
performance = object
algorithms = object
timeComplexity = object
constant = "O(1) - Operation takes a fixed amount of time, regardless of input size."
logarithmic = "O(log n) - Time grows logarithmically with input size (e.g., binary search)."
linear = "O(n) - Time grows linearly with input size (e.g., linear search, single loop)."
linearithmic = "O(n log n) - Common for efficient sorting algorithms (e.g., quicksort, mergesort)."
quadratic = "O(nยฒ) - Time grows quadratically with input size (e.g., nested loops, bubble sort)."
exponential = "O(2โฟ) - Time grows exponentially with input size (very slow, e.g., naive Fibonacci recursion)."
factorial = "O(n!) - Extremely slow, used for problems like traveling salesman (naive approach)."
end
spaceComplexity = object
constant = "O(1) - Fixed memory usage, regardless of input size."
logarithmic = "O(log n) - Memory grows logarithmically with input size."
linear = "O(n) - Memory grows linearly with input size."
quadratic = "O(nยฒ) - Memory grows quadratically with input size (e.g., 2D arrays)."
exponential = "O(2โฟ) - Memory grows exponentially with input size."
end
end
optimization = object
premature = "Avoid optimizing code before profiling. 'Premature optimization is the root of all evil.'"
profiling = "Measure before optimizing. Use profilers or manual timing to identify bottlenecks."
hotspots = "Focus optimization efforts on critical sections of code that are executed frequently or consume significant resources."
tradeoffs = "Understand that optimizations often involve tradeoffs (e.g., speed vs. memory, speed vs. readability)."
end
techniques = object
caching = object
memoization = "Store the results of expensive function calls and return the cached result when the same inputs occur again."
lookup = "Use pre-computed value tables for frequently accessed, unchanging data."
invalidation = "Strategies for removing outdated data from the cache (e.g., LRU, TTL)."
end
lazyLoading = object
principle = "Load resources or perform computations only when they are actually needed, not upfront."
implementation = "Use flags, getters, or proxy objects to defer work."
benefits = ["Faster startup times", "reduced memory footprint", "improved responsiveness."]
end
objectPooling = object
concept = "Reuse objects that are expensive to create or destroy, rather than allocating and deallocating them repeatedly."
implementation = "A pool manager that provides and reclaims objects (e.g., bullets, particles)."
useCase = "Games with many short-lived objects (e.g., particles, enemies, projectiles)."
end
batching = object
concept = "Group similar operations together to reduce overhead (e.g., system calls, rendering commands)."
examples = ["Batching drawing calls (all sprites of one type, then all of another)", "grouping network requests."]
benefits = ["Reduced overhead", "better throughput", "improved CPU/GPU utilization."]
end
end
end
end
end
// ============================================================================
// ADVANCED PARTICLE SYSTEMS
// Manages various visual particle effects for UI feedback and aesthetics.
// ============================================================================
// Initializes the particle system by defining particle types and creating ambient particles.
initializeAdvancedParticleSystems = function()
logDebug("Initializing advanced particle systems...")
ui.animations.particles = []
// Define properties for different particle types.
particleTypes = object
ambient = object
count = 50
speed = 0.5
size = [2, 4]
color = ui.theme.colors.accent_primary
alpha = 0.3
lifetime = 50000 // Very long for ambient particles.
end
typing = object
count = 10
speed = 2.0
size = [1, 3]
color = ui.theme.colors.accent_tertiary
alpha = 0.6
lifetime = 1000 // 1 second.
end
success = object
count = 20
speed = 3.0
size = [2, 5]
color = ui.theme.colors.success
alpha = 0.8
lifetime = 1500 // 1.5 seconds.
end
error = object
count = 15
speed = 2.5
size = [2, 4]
color = ui.theme.colors.error
alpha = 0.7
lifetime = 2000 // 2 seconds.
end
notification = object
count = 5
speed = 1.0
size = [1, 2]
color = ui.theme.colors.info
alpha = 0.5
lifetime = 750 // 0.75 seconds.
end
end
// Create initial ambient particles across the screen.
for i=0 to particleTypes.ambient.count - 1
ui.animations.particles.push(object
type = "ambient"
x = (random.next() - 0.5) * screen.width // Centered coordinate system.
y = (random.next() - 0.5) * screen.height
vx = (random.next() - 0.5) * particleTypes.ambient.speed
vy = (random.next() - 0.5) * particleTypes.ambient.speed
size = floor(random.next() * (particleTypes.ambient.size[1] - particleTypes.ambient.size[0] + 1)) + particleTypes.ambient.size[0]
life = 1.0 // Normalized 0-1.
maxLife = 1.0
color = particleTypes.ambient.color
alpha = particleTypes.ambient.alpha
creationTime = system.time() // Track creation time for cleanup.
targetLifeMS = particleTypes.ambient.lifetime // Milliseconds.
end)
end
logInfo("Ambient particles generated: " + particleTypes.ambient.count)
end
// Updates the position and lifetime of all active particles.
updateParticles = function(deltaTime) // deltaTime in seconds.
local particlesToRemove = []
for i = 0 to ui.animations.particles.length - 1
local particle = ui.animations.particles[i]
// Update position based on velocity and delta time.
particle.x += particle.vx * deltaTime
particle.y += particle.vy * deltaTime
// Update normalized life (0 to 1).
particle.life = 1 - (system.time() - particle.creationTime) / particle.targetLifeMS
// Wrap ambient particles around the screen for continuous effect.
if particle.type == "ambient" then
if particle.x > screen.width/2 then particle.x = -screen.width/2 end
if particle.x < -screen.width/2 then particle.x = screen.width/2 end
if particle.y > screen.height/2 then particle.y = -screen.height/2 end
if particle.y < -screen.height/2 then particle.y = screen.height/2 end
// Reset life for ambient particles if they expire, to make them loop indefinitely.
if particle.life <= 0 then
particle.life = 1.0
particle.creationTime = system.time()
end
else
// For non-ambient particles, mark them for removal if their life is 0 or less.
if particle.life <= 0 then
particlesToRemove.push(i)
end
end
end
// Remove dead particles, iterating backwards to avoid index issues.
for i = particlesToRemove.length - 1 to 0 by -1
ui.animations.particles.removeAt(particlesToRemove[i])
end
end
// Creates a burst of particles at a specified location for visual feedback.
createParticleBurst = function(x, y, type, count = 20)
local config = particleTypes[type]
if config == 0 then // Check if particle type configuration exists.
logWarn("Attempted to create unknown particle type: " + type)
return
end
for i = 0 to count - 1
local angle = (i / count) * PI * 2 // Distribute particles in a circle.
local speed = config.speed * (0.5 + random.next() * 0.5) // Randomize speed slightly.
ui.animations.particles.push(object
type = type
x = x
y = y
vx = cos(angle) * speed
vy = sin(angle) * speed
size = config.size[0] + random.next() * (config.size[1] - config.size[0])
life = 1.0 // Starts at full life.
maxLife = 1.0
color = config.color
alpha = config.alpha
creationTime = system.time()
targetLifeMS = config.lifetime
end)
end
logDebug("Particle burst created: " + type + " at (" + x + "," + y + ")")
end
// ============================================================================
// SESSION MANAGEMENT AND PERSISTENCE
// Handles session IDs, loading/saving user preferences, and conversation history.
// ============================================================================
// Generates a unique session ID based on timestamp and a random number.
generateSessionId = function()
local timestamp = system.time()
local randNum = random.nextInt(100000) // 0 to 99999.
return "session_" + timestamp + "_" + randNum
end
// Loads user preferences from microStudio's storage.
loadUserPreferences = function()
logDebug("Loading user preferences...")
local saved = storage.get("tiberius_preferences")
if saved != 0 then // 0 means not found in microScript storage.
conversationContext.userPreferences = saved
logInfo("User preferences loaded successfully.")
else
logInfo("No saved user preferences found. Using defaults.")
// Ensure default preferences are robustly set.
conversationContext.userPreferences = object
codeStyle = "clean"
verbosity = "balanced"
learningStyle = "interactive"
favTheme = "cyberpunk_green"
autoComplete = 1
end
end
end
// Saves current user preferences to microStudio's storage.
saveUserPreferences = function()
logDebug("Saving user preferences...")
storage.set("tiberius_preferences", conversationContext.userPreferences)
logInfo("User preferences saved.")
addNotification("Preferences saved!", ui.theme.colors.info, 1500) // Show a temporary notification.
end
// Placeholder for loading a conversation (would typically load from storage or file system).
loadConversation = function()
addAssistantMessage("Conversation loading feature is not yet fully implemented. Would require a file system or advanced storage mechanism.", "text", object source = "command" end)
logWarn("Load Conversation command executed, but feature is a placeholder.")
end
// Placeholder for saving a conversation.
saveConversation = function()
addAssistantMessage("Conversation saving feature is not yet fully implemented. Would require a file system or advanced storage mechanism.", "text", object source = "command" end)
logWarn("Save Conversation command executed, but feature is a placeholder.")
end
// Resets the entire session to a clean state.
resetSession = function()
logWarn("Resetting session...")
// Clear all dynamic state.
chatHistory = []
state.totalInteractions = 0
state.errorCount = 0
state.performanceMetrics = object
avgResponseTime = 0
totalRequests = 0
cacheHits = 0
currentFPS = 0
memoryUsage = 0
cacheEfficiency = 0
end
state.errors = []
state.notifications = []
inputSystem.currentInput = ""
inputSystem.history = []
inputSystem.historyIndex = -1
// Re-initialize core components.
init() // This will re-run init, which should handle resetting everything.
addAssistantMessage("๐ Session reset! A fresh start awaits!", "text", object source = "command" end)
createParticleBurst(0, 0, "info", 40)
logInfo("Session reset complete.")
end
// ============================================================================
// PLUGIN SYSTEM
// Provides a modular way to extend TiberiusGBT's functionality.
// ============================================================================
// Initializes the plugin system and loads predefined built-in plugins.
initializePlugins = function()
logDebug("Initializing plugin system...")
// Clear any previously loaded plugins.
plugins.loaded = []
// Load sample built-in plugins.
// In a real scenario, these would be separate script files loaded dynamically.
loadPlugin("codeAnalyzer")
loadPlugin("debugHelper")
loadPlugin("projectManager")
loadPlugin("memoryOptimizer")
loadPlugin("visualizer")
logInfo("Plugin system initialized. Loaded: " + plugins.loaded.length + " plugins.")
end
// Loads a specific plugin by name (simulated for now).
loadPlugin = function(pluginName)
// Simulate loading and registering hooks for the plugin.
if plugins.available.contains(pluginName) == 1 then
if plugins.loaded.contains(pluginName) == 0 then
plugins.loaded.push(pluginName)
logDebug("Plugin loaded: " + pluginName)
// Register some generic hooks for demonstration.
if pluginName == "codeAnalyzer" then
registerPluginHook("onUserInput", analyzeCodeInput)
registerPluginHook("afterResponse", analyzeCodeOutput)
elsif pluginName == "debugHelper" then
registerPluginHook("onError", suggestDebuggingSteps)
elsif pluginName == "memoryOptimizer" then
registerPluginHook("onUpdate", optimizeMemoryUsage)
end
else
logWarn("Plugin '" + pluginName + "' already loaded.")
end
else
logError("Attempted to load unknown plugin: " + pluginName)
end
end
// Registers a callback function to a specific plugin hook event.
registerPluginHook = function(event, callback)
if plugins.hooks[event] != 0 then
plugins.hooks[event].push(callback)
logDebug("Registered hook for event '" + event + "': " + callback)
else
logError("Attempted to register hook for unknown event: " + event)
end
end
// Executes all registered callback functions for a given event.
executePluginHooks = function(event, data)
local results = []
if plugins.hooks[event] != 0 then
for hook in plugins.hooks[event]
try
local result = hook(data) // Execute the plugin callback.
results.push(result)
catch error
logError("Plugin hook error in event '" + event + "', hook: " + hook + ". Error: " + error)
// Optionally, push an error message to the results.
results.push(object error = error, hook = hook end)
end
end
else
logDebug("No hooks registered for event: " + event)
end
return results
end
// --- Sample Plugin Functions (Stubs for demonstration) ---
analyzeCodeInput = function(input)
logDebug("CodeAnalyzer: Analyzing user input: " + input.substring(0, 50) + "...")
// Simulate some analysis.
if input.toLowerCase().indexOf("bug") >= 0 then
addNotification("CodeAnalyzer detected potential issue keywords.", ui.theme.colors.warning, 1000)
return "Code analysis initiated for bug keywords."
end
return 0
end
analyzeCodeOutput = function(response)
logDebug("CodeAnalyzer: Analyzing AI response: " + response.content.substring(0, 50) + "...")
// Simulate a check on the AI's generated code.
if response.type == "code" and response.content.indexOf("syntax error") >= 0 then // Simulated error.
addNotification("CodeAnalyzer found a potential issue in AI's generated code!", ui.theme.colors.error, 2000)
return "Generated code needs review."
end
return 0
end
suggestDebuggingSteps = function(errorData)
logDebug("DebugHelper: Suggesting steps for error: " + errorData.message)
addAssistantMessage("DebugHelper: " + "An error occurred! Let's try these steps: 1. Check line " + errorData.line + ". 2. Print variable values. 3. Simplify code.", "text", object source = "plugin" end)
return "Debugging steps provided."
end
optimizeMemoryUsage = function(deltaTime)
logDebug("MemoryOptimizer: Running background memory check...")
// In a real plugin, this would inspect memory usage and suggest optimizations.
// For now, simulate.
if random.next() < 0.01 then // Small chance to trigger a warning.
addNotification("MemoryOptimizer: High memory usage detected (simulated).", ui.theme.colors.warning, 2000)
return "Memory optimization suggestion."
end
return 0
end
// ============================================================================
// CACHE SYSTEM
// Implements caching for AI responses to speed up repeated queries.
// ============================================================================
// Stores a response in the cache.
cacheResponse = function(key, response)
local cacheData = object
key = key
response = response
timestamp = system.time()
accessCount = 1
end
// Add to cache.
cache.responses.data.push(cacheData)
cache.responses.currentSize += 1
// If cache exceeds max size, remove the oldest entry (simple FIFO).
if cache.responses.currentSize > cache.responses.maxSize then
cache.responses.data.shift() // Removes the first (oldest) element.
cache.responses.currentSize -= 1
logDebug("Cache full, oldest entry removed.")
end
logDebug("Response cached for key: " + key.substring(0, 30))
end
// Retrieves a response from the cache if available.
getCachedResponse = function(key)
for item in cache.responses.data
if item.key == key then
item.accessCount += 1
item.timestamp = system.time() // Update timestamp for potential LRU (not fully implemented).
state.performanceMetrics.cacheHits += 1 // Increment actual cache hit counter.
logDebug("Cache hit for key: " + key.substring(0, 30))
return item.response
end
end
logDebug("Cache miss for key: " + key.substring(0, 30))
return 0 // microScript's equivalent of 'not found'.
end
// ============================================================================
// MAIN GAME LOOP FUNCTIONS (update and draw)
// These functions are called automatically by microStudio.
// ============================================================================
// update() is called approximately 60 times per second for game logic.
update = function()
local currentTime = system.time()
local deltaTime = (currentTime - state.lastActivity) / 1000 // Convert milliseconds to seconds.
state.lastActivity = currentTime
// Update performance metrics.
state.performanceMetrics.currentFPS = system.fps
state.performanceMetrics.memoryUsage = getMemoryUsage()
state.performanceMetrics.cacheEfficiency = calculateCacheHitRate()
// Update particle systems.
updateParticles(deltaTime)
// Handle input events (keyboard, mouse, touch, gamepad).
handleAdvancedInput()
// Update UI animations and effects (if any are active).
updateUIAnimations(deltaTime)
// Process background tasks (e.g., AI learning, data synchronization).
processBackgroundTasks()
// Process any pending notifications.
updateNotifications(deltaTime)
// Execute plugin update hooks.
executePluginHooks("onUpdate", deltaTime)
// Auto-save user preferences if enabled and at a specific time interval.
// Using a modulo check for roughly once per minute.
if systemConfig.autoSave == 1 and (floor(currentTime / 1000) % 60 == 0) and (currentTime % 1000 < 500) then
saveUserPreferences()
end
end
// draw() is called as fast as possible to render frames to the screen.
draw = function()
// Execute plugin draw hooks first to allow custom backgrounds/effects.
executePluginHooks("onDraw", null)
// Clear screen with gradient background.
drawGradientBackground()
// Draw particle effects.
drawParticles()
// Draw main UI components in Z-order (back to front).
drawAdvancedHeader()
drawAdvancedChatInterface()
drawAdvancedInputArea()
drawAdvancedSidePanel()
// Draw overlays (processing, notifications, tooltips).
drawProcessingOverlay()
drawNotificationOverlay()
// Draw debug information if debug mode is enabled.
if systemConfig.debugMode == 1 then
drawDebugInfo()
end
// Draw status bar last to ensure it's on top of other main UI.
drawAdvancedStatusBar()
end
// ============================================================================
// ADVANCED DRAWING FUNCTIONS
// These functions are responsible for rendering various UI elements.
// ============================================================================
// Draws the main gradient background of the application.
drawGradientBackground = function()
local colors = ui.theme.colors.gradients.background
// Use microStudio's `screen.setLinearGradient` for efficient rendering.
// Gradient from top to bottom (y + screen.height/2 to y - screen.height/2).
screen.setLinearGradient(0, screen.height/2, 0, -screen.height/2, colors[0], colors[1])
screen.fillRect(0, 0, screen.width, screen.height) // Fill the entire screen.
screen.setLinearGradient(0, 0, 0, 0, "#fff", "#fff") // Reset gradient state.
end
// Draws all active particles on the screen.
drawParticles = function()
for particle in ui.animations.particles
local alpha = particle.alpha * particle.life // Alpha fades with particle's remaining life.
screen.setAlpha(alpha)
screen.setDrawRotation(particle.life * 360 * (if particle.type == "ambient" then 0.1 else 1 end)) // Rotate for visual flair.
screen.fillRect(particle.x, particle.y, particle.size, particle.size, particle.color) // Simple square particles.
screen.setDrawRotation(0) // Reset rotation for subsequent drawing.
end
screen.setAlpha(1) // Reset alpha to fully opaque.
end
// Draws the header bar at the top of the screen.
drawAdvancedHeader = function()
local h = ui.layout.headerHeight
local y = screen.height/2 - h/2 // Center Y of the header region.
// Header background with gradient.
screen.setLinearGradient(0, y + h/2, 0, y - h/2, ui.theme.colors.bg_secondary, ui.theme.colors.bg_tertiary)
screen.fillRect(0, y, screen.width, h)
screen.setLinearGradient(0, 0, 0, 0, "#fff", "#fff") // Reset gradient.
// Animated border with pulsing alpha.
local pulse = sin(system.time() * 0.002) * 0.2 + 0.8 // Value between 0.6 and 1.0.
screen.setAlpha(pulse)
screen.drawRect(0, y, screen.width - 4, h, ui.theme.colors.accent_primary, 2) // Border width 2.
screen.setAlpha(1) // Reset alpha.
// Logo and title text.
screen.setDrawScale(1.2, 1.2) // Slightly larger logo text.
screen.drawText("โก", -screen.width/2 + 60, y + 5, 32, ui.theme.colors.accent_tertiary)
screen.setDrawScale(1, 1) // Reset scale.
screen.drawText("TiberiusGBT v" + systemConfig.version, -screen.width/2 + 100, y + 5, 24, ui.theme.colors.text_primary)
screen.drawText("Advanced AI Coding Assistant", -screen.width/2 + 100, y - 20, 12, ui.theme.colors.text_secondary)
// Draw status indicators (online, processing, mode).
drawStatusIndicators(y)
// Draw performance metrics (FPS, response time, cache).
drawPerformanceMetrics(y)
end
// Draws status icons and text in the header.
drawStatusIndicators = function(headerCenterY)
local x = screen.width/2 - 200 // Starting X for right-aligned status group.
// Connection status (always online for this app).
screen.setAlpha(0.8)
screen.fillRect(x, headerCenterY + 10, 8, 8, ui.theme.colors.success)
screen.drawText("Online", x + 15, headerCenterY + 10, 10, ui.theme.colors.text_tertiary)
// Processing status.
x += 80
if state.isProcessing == 1 then
local dots = floor(system.time() / 200) % 4
local dotString = ""
for i = 0 to dots - 1
dotString += "โ"
end
for i = dots to 2 // Fill remaining with hollow dots for a total of 3 visible indicators.
dotString += "โ"
end
screen.fillRect(x, headerCenterY + 10, 8, 8, ui.theme.colors.warning)
screen.drawText("Processing " + dotString, x + 15, headerCenterY + 10, 10, ui.theme.colors.text_tertiary)
else
screen.fillRect(x, headerCenterY + 10, 8, 8, ui.theme.colors.success)
screen.drawText("Ready", x + 15, headerCenterY + 10, 10, ui.theme.colors.text_tertiary)
end
// Current mode indicator.
x += 100
screen.drawText("Mode: " + state.currentMode.toUpperCase(), x + 15, headerCenterY + 10, 10, ui.theme.colors.text_tertiary)
screen.setAlpha(1) // Reset alpha.
end
// Draws performance metrics (FPS, Avg Response, Cache) in the header.
drawPerformanceMetrics = function(headerCenterY)
if systemConfig.debugMode == 1 then
local x = screen.width/2 - 50 // Starting X for right-most metrics group.
screen.drawText("FPS: " + floor(state.performanceMetrics.currentFPS), x, headerCenterY + 25, 8, ui.theme.colors.text_dim)
screen.drawText("Resp: " + floor(state.performanceMetrics.avgResponseTime) + "ms", x + 50, headerCenterY + 25, 8, ui.theme.colors.text_dim)
screen.drawText("Cache: " + cache.responses.currentSize + "/" + cache.responses.maxSize, x + 120, headerCenterY + 25, 8, ui.theme.colors.text_dim)
end
end
// Draws the main chat interface area.
drawAdvancedChatInterface = function()
local chatTopY = screen.height/2 - ui.layout.headerHeight - ui.layout.chatPadding
local chatBottomY = -screen.height/2 + ui.layout.footerHeight + ui.layout.chatPadding
local chatHeight = chatTopY - chatBottomY
local chatCenterX = 0
local chatCenterY = chatBottomY + chatHeight / 2
local chatWidth = screen.width - ui.layout.sidebarWidth - ui.layout.chatPadding * 3 // Adjust for sidebar.
// Chat area background.
screen.setAlpha(0.3)
screen.fillRect(chatCenterX, chatCenterY, chatWidth, chatHeight, ui.theme.colors.bg_secondary)
screen.setAlpha(0.1)
screen.drawRect(chatCenterX, chatCenterY, chatWidth, chatHeight, ui.theme.colors.accent_primary, 1)
screen.setAlpha(1)
// Draw chat messages within this area.
drawAdvancedMessages(chatTopY, chatBottomY, chatWidth)
// Draw scroll indicators.
drawScrollIndicators(chatBottomY, chatHeight, chatWidth)
end
// Draws individual messages within the chat interface, handling scrolling.
drawAdvancedMessages = function(chatTopY, chatBottomY, chatWidth)
local messageLineHeight = 12 // Estimated line height for text, small font.
local messagePadding = ui.layout.messageSpacing // Spacing between messages.
local maxVisibleHeight = chatTopY - chatBottomY
local currentY = chatTopY - messagePadding/2 - scrollOffset // Start drawing from the top, adjusted by scroll.
// Render messages from newest to oldest for chat-like display.
for i = chatHistory.length - 1 to 0 by -1
local msg = chatHistory[i]
local estimatedMessageHeight = estimateMessageDisplayHeight(msg, chatWidth)
// Check if message is within visible bounds.
if (currentY - estimatedMessageHeight - messagePadding) < chatBottomY then
// If it's going below the visible area, stop drawing.
break
end
// Draw message, then move Y up for the next one.
// The Y passed to drawMessage is the TOP of the message box.
drawMessage(msg, currentY - estimatedMessageHeight, estimatedMessageHeight, chatWidth)
currentY -= (estimatedMessageHeight + messagePadding)
// If the entire message is above the top of the chat area, continue.
if currentY > chatTopY then
continue
end
end
end
// Estimates the height a message will occupy based on its content.
estimateMessageDisplayHeight = function(msg, chatWidth)
local baseHeight = 40 // For icon, timestamp, and basic padding.
local contentWidth = chatWidth - 140 // Adjusted for icon, timestamp, left/right padding.
local fontSize = if msg.type == "code" then 9 else 10 end
local maxLines = if msg.type == "code" then 3 else 4 end // Max lines to display.
local lines = wrapText(msg.content, contentWidth, fontSize)
local displayedLines = min(lines.length, maxLines)
local textHeight = displayedLines * (fontSize + 2) // +2 for line spacing.
return baseHeight + textHeight
end
// Draws a single chat message (user or assistant).
drawMessage = function(msg, messageTopY, estimatedHeight, chatWidth)
local isUser = msg.role == "user"
local bgColor = if isUser == 1 then ui.theme.colors.bg_quaternary else ui.theme.colors.bg_tertiary end
local textColor = if isUser == 1 then ui.theme.colors.text_primary else ui.theme.colors.text_secondary end
local accentColor = if isUser == 1 then ui.theme.colors.accent_tertiary else ui.theme.colors.accent_secondary end
local icon = if isUser == 1 then "๐ค" else "๐ค" end
local messageRenderWidth = chatWidth - ui.layout.messageSpacing
local messageCenterY = messageTopY + estimatedHeight / 2
local messageCenterX = -screen.width/2 + ui.layout.sidebarWidth + ui.layout.chatPadding + messageRenderWidth/2
// Message container background.
screen.setAlpha(0.8)
screen.fillRect(messageCenterX, messageCenterY, messageRenderWidth, estimatedHeight - 5, bgColor)
screen.setAlpha(0.5)
screen.drawRect(messageCenterX, messageCenterY, messageRenderWidth, estimatedHeight - 5, accentColor, 1)
screen.setAlpha(1)
// Side accent bar.
screen.fillRect(messageCenterX - messageRenderWidth/2 + 5, messageCenterY, 3, estimatedHeight - 5, accentColor)
// Icon and timestamp.
local textStartX = messageCenterX - messageRenderWidth/2 + 15
local textStartY = messageCenterY + estimatedHeight/2 - 15
screen.drawText(icon, textStartX, textStartY, 16, accentColor)
local timeStr = formatTime(msg.timestamp)
screen.drawText(timeStr, textStartX + 25, textStartY, 8, ui.theme.colors.text_dim)
// Message content.
if msg.type == "code" then
drawCodeMessage(msg, messageCenterX, messageCenterY, messageRenderWidth, estimatedHeight)
else
drawTextMessage(msg, messageCenterX, messageCenterY, messageRenderWidth, estimatedHeight)
end
// Metadata indicators.
if msg.metadata != 0 then
drawMessageMetadata(msg, messageCenterX, messageCenterY, messageRenderWidth, estimatedHeight)
end
end
// Draws the content of a text message.
drawTextMessage = function(msg, messageCenterX, messageCenterY, messageRenderWidth, estimatedHeight)
local content = msg.content
local textContentLeftX = messageCenterX - messageRenderWidth/2 + 60
local textContentTopY = messageCenterY + estimatedHeight/2 - 40 // Adjusted start for text.
local maxWidth = messageRenderWidth - 120
local fontSize = 10
local lines = wrapText(content, maxWidth, fontSize)
for i = 0 to min(lines.length - 1, 4) // Max 4 lines displayed for text.
local lineY = textContentTopY - (i * (fontSize + 2))
screen.drawText(lines[i], textContentLeftX, lineY, fontSize, ui.theme.colors.text_secondary)
end
// Truncation indicator.
if lines.length > 4 then
screen.drawText("...", textContentLeftX, textContentTopY - (4 * (fontSize + 2)), fontSize, ui.theme.colors.text_dim)
end
end
// Draws the content of a code message with basic syntax highlighting.
drawCodeMessage = function(msg, messageCenterX, messageCenterY, messageRenderWidth, estimatedHeight)
// Code block background.
local codeBlockWidth = messageRenderWidth - 80
local codeBlockHeight = estimatedHeight - 30
local codeBlockX = messageCenterX
local codeBlockY = messageCenterY - 5
screen.setAlpha(0.2)
screen.fillRect(codeBlockX, codeBlockY, codeBlockWidth, codeBlockHeight, ui.theme.colors.bg_primary)
screen.setAlpha(1)
// Language indicator.
local indicatorX = codeBlockX - codeBlockWidth/2 + 10
local indicatorY = codeBlockY + codeBlockHeight/2 - 10
screen.drawText(msg.language or "code", indicatorX, indicatorY, 8, ui.theme.colors.code_keyword)
// Syntax-highlighted code.
local highlightedCode = highlightSyntax(msg.content, msg.language)
local lines = highlightedCode.split("\n")
local codeTextLeftX = codeBlockX - codeBlockWidth/2 + 10
local codeTextTopY = codeBlockY + codeBlockHeight/2 - 25 // Adjusted start.
local fontSize = 9
for i = 0 to min(lines.length - 1, 3) // Max 3 lines of code displayed.
local lineY = codeTextTopY - (i * (fontSize + 2))
// This is where actual colored rendering based on highlightSyntax output would occur.
// For simplicity, drawing as a single color now.
screen.drawText(lines[i], codeTextLeftX, lineY, fontSize, ui.theme.colors.code_string)
end
end
// Draws metadata associated with a message (e.g., confidence score, processing time).
drawMessageMetadata = function(msg, messageCenterX, messageCenterY, messageRenderWidth, estimatedHeight)
local metadata = msg.metadata
// Confidence score.
if metadata.confidence != 0 then
local confX = messageCenterX + messageRenderWidth/2 - 55 // Right-aligned.
local confY = messageCenterY + estimatedHeight/2 - 15
local confWidth = metadata.confidence * 50
screen.fillRect(confX, confY, confWidth, 3, ui.theme.colors.success)
screen.drawRect(confX, confY, 50, 3, ui.theme.colors.text_dim, 1)
end
// Processing time.
if metadata.processingTime != 0 then
local timeX = messageCenterX + messageRenderWidth/2 - 30 // Right-aligned.
local timeY = messageCenterY + estimatedHeight/2 - 25
screen.drawText(metadata.processingTime + "ms", timeX, timeY, 8, ui.theme.colors.text_dim)
end
end
// Draws the input area at the bottom of the screen.
drawAdvancedInputArea = function()
local h = ui.layout.footerHeight
local y = -screen.height/2 + h/2 // Center Y of the input area.
local width = screen.width - ui.layout.sidebarWidth - ui.layout.chatPadding * 2 // Adjusted for sidebar.
// Input background with subtle glow effect.
screen.setAlpha(0.2)
screen.fillRect(0, y, width, h, ui.theme.colors.bg_input)
screen.setAlpha(0.1)
screen.fillRect(0, y + 2, width - 4, h - 4, ui.theme.colors.accent_primary) // Inner accent.
screen.setAlpha(1)
// Active input border (pulses when not processing).
if state.isProcessing == 0 then
local pulse = sin(system.time() * 0.003) * 0.3 + 0.7
screen.setAlpha(pulse)
screen.drawRect(0, y, width, h, ui.theme.colors.accent_primary, 2)
screen.setAlpha(1)
end
// Input prompt character.
local promptX = -width/2 + 30
screen.drawText("โบ", promptX, y, 20, ui.theme.colors.accent_primary)
// Input text and blinking cursor.
local displayText = inputSystem.currentInput
local cursor = ""
local textLeftX = promptX + 20
local fontSize = 14
if state.isProcessing == 1 then
local dots = floor(system.time() / 300) % 4
displayText = "Processing"
for i = 0 to dots - 1
displayText += "."
end
else
// Blinking cursor.
if floor(system.time() / 500) % 2 == 0 then
cursor = "โ"
end
end
local cursorPos = inputSystem.cursorPosition
local beforeCursor = displayText.substring(0, cursorPos)
local afterCursor = displayText.substring(cursorPos)
screen.drawText(beforeCursor, textLeftX, y, fontSize, ui.theme.colors.text_primary)
local beforeWidth = screen.textWidth(beforeCursor, fontSize)
screen.drawText(cursor, textLeftX + beforeWidth, y, fontSize, ui.theme.colors.accent_tertiary)
screen.drawText(afterCursor, textLeftX + beforeWidth + screen.textWidth(cursor, fontSize), y, fontSize, ui.theme.colors.text_primary)
// Auto-complete suggestions (drawn above the input field).
if inputSystem.suggestions.length > 0 then
drawAutoCompleteSuggestions(y, width)
end
// Input hints (drawn to the right of the input field).
drawInputHints(y, width)
end
// Draws auto-completion suggestions above the input field.
drawAutoCompleteSuggestions = function(inputCenterY, inputWidth)
local suggestionCount = min(inputSystem.suggestions.length, 5)
local boxHeight = suggestionCount * 20 + 10
local boxCenterX = 0
local boxCenterY = inputCenterY + ui.layout.footerHeight/2 + 10 + boxHeight/2 // Position above input field.
local boxWidth = inputWidth - 60
// Suggestions background.
screen.setAlpha(0.9)
screen.fillRect(boxCenterX, boxCenterY, boxWidth, boxHeight, ui.theme.colors.bg_secondary)
screen.drawRect(boxCenterX, boxCenterY, boxWidth, boxHeight, ui.theme.colors.accent_secondary, 1)
// Draw individual suggestions.
local textStartX = boxCenterX - boxWidth/2 + 10
local textBaseY = boxCenterY + boxHeight/2 - 5 - 2 // Top of text area.
for i = 0 to suggestionCount - 1
local suggestion = inputSystem.suggestions[i]
local lineY = textBaseY - (i * 20)
// Highlight the first suggestion as the active one.
if i == 0 then
screen.fillRect(boxCenterX, lineY + 2, boxWidth - 10, 20, ui.theme.colors.accent_primary)
end
screen.drawText(suggestion, textStartX, lineY, 12, ui.theme.colors.text_primary)
end
screen.setAlpha(1)
end
// Draws keyboard input hints (e.g., Enter to send, Tab for autocomplete).
drawInputHints = function(inputCenterY, inputWidth)
local hints = [
"ENTER: Send",
"SHIFT+ENTER: New line",
"TAB: Auto-complete",
"โโ: History"
]
local hintX = inputWidth/2 - 150 // Right-aligned relative to input area.
local hintBaseY = inputCenterY + ui.layout.footerHeight/2 + 5 // Position below input area.
for i = 0 to hints.length - 1
screen.drawText(hints[i], hintX, hintBaseY - (i * 10), 8, ui.theme.colors.text_dim)
end
end
// Draws the status bar at the very bottom of the screen.
drawAdvancedStatusBar = function()
local h = ui.layout.footerHeight
local y = -screen.height/2 + h/2 // Center Y of status bar.
local width = screen.width
// Status bar background.
screen.setAlpha(0.3)
screen.fillRect(0, y, width, h, ui.theme.colors.bg_secondary)
screen.setAlpha(1)
// Left section - Session info.
screen.drawText("Session: " + conversationContext.sessionId.substring(0, 8) + "...", -width/2 + 20, y + 5, 8, ui.theme.colors.text_dim)
screen.drawText("Messages: " + chatHistory.length, -width/2 + 120, y + 5, 8, ui.theme.colors.text_dim)
// Center section - Contextual info.
if conversationContext.currentTopic != "" then
screen.drawText("Topic: " + conversationContext.currentTopic.toUpperCase(), 0, y + 5, 8, ui.theme.colors.text_dim)
end
if conversationContext.lastLanguage != "" then
screen.drawText("Lang: " + conversationContext.lastLanguage.toUpperCase(), 0, y - 5, 8, ui.theme.colors.text_dim)
end
// Right section - Help commands.
screen.drawText("Type /help for commands", width/2 - 100, y + 5, 8, ui.theme.colors.text_dim)
screen.drawText("Press F1 for shortcuts", width/2 - 100, y - 5, 8, ui.theme.colors.text_dim)
end
// Draws the side panel with quick action buttons.
drawAdvancedSidePanel = function()
local w = ui.layout.sidebarWidth
local h = screen.height - ui.layout.headerHeight - ui.layout.footerHeight
local x = screen.width/2 - w/2 // Center X of the side panel.
local y = 0 // Center Y, positioned vertically in the middle.
// Panel background.
screen.setAlpha(0.2)
screen.fillRect(x, y, w, h, ui.theme.colors.bg_secondary)
screen.setAlpha(0.5)
screen.drawRect(x, y, w, h, ui.theme.colors.accent_primary, 1)
screen.setAlpha(1)
// Panel title.
screen.drawText("Quick Actions", x, y + h/2 - 25, 12, ui.theme.colors.text_primary)
// Action buttons.
local buttonW = w - 20 // Button width, with padding.
local buttonH = 25
// Calculate vertical positions for buttons relative to panel's center.
local btnBaseY = y + h/2 - 80 // Top-most button.
drawActionButton("New Chat", x, btnBaseY - buttonH/2, buttonW, buttonH, function() clearChat() end)
drawActionButton("Code Mode", x, btnBaseY - buttonH/2 - 30, buttonW, buttonH, function() toggleMode("code") end)
drawActionButton("Debug Mode", x, btnBaseY - buttonH/2 - 60, buttonW, buttonH, function() toggleMode("debug") end)
drawActionButton("Settings", x, btnBaseY - buttonH/2 - 90, buttonW, buttonH, function() toggleMode("settings") end)
// Statistics display in the lower part of the panel.
drawStatisticsPanel(x, w, y, h)
end
// Draws a clickable button, handling hover effects.
drawActionButton = function(text, centerX, centerY, width, height, onClick)
local hover = isMouseOver(centerX, centerY, width, height)
if hover == 1 then
screen.setAlpha(0.3)
screen.fillRect(centerX, centerY, width, height, ui.theme.colors.accent_primary)
screen.setAlpha(1)
end
screen.drawRect(centerX, centerY, width, height, ui.theme.colors.accent_secondary, 1)
screen.drawText(text, centerX, centerY, 10, ui.theme.colors.text_primary)
// Attach click handler (handled in handleMouseClick function outside draw loop)
// Store button info for click detection
if ui.components.buttons == 0 then ui.components.buttons = [] end
ui.components.buttons.push(object
x = centerX, y = centerY, w = width, h = height,
onClick = onClick,
type = "button"
end)
end
// Draws key session statistics in the side panel.
drawStatisticsPanel = function(panelCenterX, panelWidth, panelCenterY, panelHeight)
local statsY = panelCenterY - (panelHeight/2) + (panelHeight * 0.6) // Position in lower 40% of panel.
// Panel divider.
screen.drawLine(panelCenterX - panelWidth/2 + 5, statsY, panelCenterX + panelWidth/2 - 5, statsY, ui.theme.colors.text_dim, 1)
// Stats title.
screen.drawText("Statistics", panelCenterX, statsY - 15, 10, ui.theme.colors.text_secondary)
// Session stats.
local sessionTime = floor((system.time() - conversationContext.sessionStart) / 60000) // Minutes.
screen.drawText("Session: " + sessionTime + " min", panelCenterX, statsY - 30, 8, ui.theme.colors.text_dim)
screen.drawText("Interactions: " + state.totalInteractions, panelCenterX, statsY - 40, 8, ui.theme.colors.text_dim)
screen.drawText("Errors: " + state.errorCount, panelCenterX, statsY - 50, 8, ui.theme.colors.text_dim)
// Performance stats.
screen.drawText("Avg Resp: " + floor(state.performanceMetrics.avgResponseTime) + "ms", panelCenterX, statsY - 65, 8, ui.theme.colors.text_dim)
screen.drawText("Cache Hit: " + floor(state.performanceMetrics.cacheEfficiency) + "%", panelCenterX, statsY - 75, 8, ui.theme.colors.text_dim)
screen.drawText("Mem: " + floor(state.performanceMetrics.memoryUsage) + "MB", panelCenterX, statsY - 85, 8, ui.theme.colors.text_dim)
end
// Draws an overlay when the AI is processing a request.
drawProcessingOverlay = function()
if state.isProcessing == 1 then
screen.setAlpha(0.8)
screen.fillRect(0, 0, screen.width, screen.height, ui.theme.colors.bg_primary) // Dim the background.
screen.setAlpha(1)
// Processing animation (rotating gear icon).
local rotation = system.time() * 0.1
screen.setDrawRotation(rotation)
screen.setDrawScale(2, 2)
screen.drawText("โ", 0, 0, 20, ui.theme.colors.accent_primary)
screen.setDrawRotation(0) // Reset transformations.
screen.setDrawScale(1, 1)
// Processing text.
screen.drawText(state.processingType or "Processing...", 0, -30, 16, ui.theme.colors.text_primary)
end
end
// Draws temporary notification messages to the user.
drawNotificationOverlay = function()
if state.notifications.length > 0 then
local notif = state.notifications[0] // Display the oldest notification.
local alpha = 1 - (system.time() - notif.startTime) / notif.duration
if alpha < 0 then alpha = 0 end
local notifY = screen.height/2 - ui.layout.headerHeight - ui.layout.notificationHeight/2 - 10
local notifX = 0
local notifWidth = screen.width / 2
local notifHeight = ui.layout.notificationHeight
screen.setAlpha(alpha * 0.8)
screen.fillRect(notifX, notifY, notifWidth, notifHeight, notif.color)
screen.setAlpha(alpha)
screen.drawRect(notifX, notifY, notifWidth, notifHeight, ui.theme.colors.text_primary, 1)
screen.drawText(notif.message, notifX, notifY, 12, ui.theme.colors.text_primary)
screen.setAlpha(1)
end
end
// Draws debug information on the screen when debugMode is enabled.
drawDebugInfo = function()
if systemConfig.debugMode == 1 then
local infoY = screen.height/2 - 100
local leftX = -screen.width/2 + 20
local lineHeight = 12
local fontSize = 8
local textColor = ui.theme.colors.error
screen.drawText("=== DEBUG INFO ===", leftX, infoY, 10, textColor)
infoY -= lineHeight
screen.drawText("FPS: " + floor(system.fps), leftX, infoY, fontSize, ui.theme.colors.text_dim)
infoY -= lineHeight
screen.drawText("Memory: " + floor(state.performanceMetrics.memoryUsage) + "MB", leftX, infoY, fontSize, ui.theme.colors.text_dim)
infoY -= lineHeight
screen.drawText("Particles: " + ui.animations.particles.length, leftX, infoY, fontSize, ui.theme.colors.text_dim)
infoY -= lineHeight
screen.drawText("Cache: " + getTotalCacheSize() + " (R:" + cache.responses.currentSize + " P:" + cache.patterns.currentSize + " C:" + cache.codeSnippets.currentSize + ")", leftX, infoY, fontSize, ui.theme.colors.text_dim)
infoY -= lineHeight
screen.drawText("Mode: " + state.currentMode, leftX, infoY, fontSize, ui.theme.colors.text_dim)
infoY -= lineHeight
screen.drawText("Topic: " + conversationContext.currentTopic, leftX, infoY, fontSize, ui.theme.colors.text_dim)
infoY -= lineHeight
screen.drawText("Lang: " + conversationContext.lastLanguage, leftX, infoY, fontSize, ui.theme.colors.text_dim)
// Display recent errors.
if state.errors.length > 0 then
infoY -= lineHeight
screen.drawText("Last Error: " + state.errors[state.errors.length - 1].message.substring(0, 50), leftX, infoY, fontSize, ui.theme.colors.error)
end
end
end
// Updates UI animations (placeholder for more complex animations).
updateUIAnimations = function(deltaTime)
// For now, this is a placeholder. More advanced animations (e.g., message fade-ins)
// would be managed here by interpolating values over time.
// Example:
// for anim in ui.animations.transitions
// anim.timeElapsed += deltaTime
// anim.progress = anim.timeElapsed / anim.duration
// if anim.progress >= 1 then
// // Animation finished
// anim.callback()
// // Remove anim from list
// else
// // Update animated property
// anim.target.property = ease(anim.start, anim.end, anim.progress, anim.easing)
// end
// end
end
// Adds a temporary notification message to be displayed on screen.
addNotification = function(message, color, durationMS)
state.notifications.push(object
message = message,
color = color or ui.theme.colors.info,
duration = durationMS or 2000,
startTime = system.time()
end)
createParticleBurst(0, screen.height/2 - ui.layout.headerHeight - ui.layout.notificationHeight/2, "notification", 5)
logInfo("Notification added: " + message)
end
// Updates and manages the display of notifications.
updateNotifications = function(deltaTime)
// Remove expired notifications.
local notificationsToRemove = []
for i = 0 to state.notifications.length - 1
local notif = state.notifications[i]
if (system.time() - notif.startTime) > notif.duration then
notificationsToRemove.push(i)
end
end
for i = notificationsToRemove.length - 1 to 0 by -1
state.notifications.removeAt(notificationsToRemove[i])
end
end
// ============================================================================
// ADVANCED INPUT HANDLING
// Manages keyboard, mouse, and touch input, including auto-completion and shortcuts.
// ============================================================================
// Main function to handle all advanced input.
handleAdvancedInput = function()
// Cache key states for multi-key combinations and to avoid re-reading.
inputSystem.lastKeysPressed.control = keyboard.CONTROL
inputSystem.lastKeysPressed.shift = keyboard.SHIFT
inputSystem.lastKeysPressed.alt = keyboard.ALT
// Handle keyboard input if AI is not processing.
if state.isProcessing == 0 then
handleKeyboardInput()
end
// Handle mouse input.
handleMouseInput()
// Handle global shortcuts (even if AI is processing, for things like cancelling).
handleGlobalShortcuts()
end
// Processes individual keyboard key presses and releases.
handleKeyboardInput = function()
// Handle character input (letters, numbers, symbols).
handleCharacterInput()
// Handle special keys like Enter, Backspace, Arrow keys.
if keyboard.press.ENTER == 1 then
if inputSystem.lastKeysPressed.shift == 1 then
// SHIFT+ENTER for new line.
insertCharacterAtCursor("\n")
else
// ENTER to send message.
sendMessage()
end
end
if keyboard.press.BACKSPACE == 1 then
handleBackspace()
end
if keyboard.press.LEFT == 1 then
inputSystem.cursorPosition = max(0, inputSystem.cursorPosition - 1)
end
if keyboard.press.RIGHT == 1 then
inputSystem.cursorPosition = min(inputSystem.currentInput.length, inputSystem.cursorPosition + 1)
end
if keyboard.press.UP == 1 then
navigateHistory(-1)
end
if keyboard.press.DOWN == 1 then
navigateHistory(1)
end
if keyboard.press.TAB == 1 then
triggerAutoComplete()
end
end
// Handles input of printable characters, including shifted symbols.
handleCharacterInput = function()
// Letters A-Z.
local letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
for letter in letters
if keyboard.press[letter] == 1 then
local char = if inputSystem.lastKeysPressed.shift == 1 then letter else letter.toLowerCase() end
insertCharacterAtCursor(char)
end
end
// Numbers 0-9 (top row).
for i = 0 to 9
local keyName = "_" + i // microStudio uses _0, _1 for top row numbers.
if keyboard.press[keyName] == 1 then
local char = tostring(i)
// Check for shifted number symbols.
if inputSystem.lastKeysPressed.shift == 1 then
local shiftedSymbols = object
"_1" = "!" "_2" = "@" "_3" = "#" "_4" = "$" "_5" = "%"
"_6" = "^" "_7" = "&" "_8" = "*" "_9" = "(" "_0" = ")"
end
char = shiftedSymbols[keyName] or char
end
insertCharacterAtCursor(char)
end
end
// Numpad numbers (if distinct events are available).
for i = 0 to 9
local keyName = "NUM_" + i
if keyboard.press[keyName] == 1 then
insertCharacterAtCursor(tostring(i))
end
end
// Common symbols without shift.
if keyboard.press.SPACE == 1 then insertCharacterAtCursor(" ") end
if keyboard.press.PERIOD == 1 then insertCharacterAtCursor(".") end
if keyboard.press.COMMA == 1 then insertCharacterAtCursor(",") end
if keyboard.press.SLASH == 1 then insertCharacterAtCursor(if inputSystem.lastKeysPressed.shift == 1 then "?" else "/" end) end
if keyboard.press.BACKSLASH == 1 then insertCharacterAtCursor(if inputSystem.lastKeysPressed.shift == 1 then "|" else "\\" end) end
if keyboard.press.MINUS == 1 then insertCharacterAtCursor(if inputSystem.lastKeysPressed.shift == 1 then "_" else "-" end) end
if keyboard.press.EQUAL == 1 then insertCharacterAtCursor(if inputSystem.lastKeysPressed.shift == 1 then "+" else "=" end) end
if keyboard.press.LEFT_BRACKET == 1 then insertCharacterAtCursor(if inputSystem.lastKeysPressed.shift == 1 then "{" else "[" end) end
if keyboard.press.RIGHT_BRACKET == 1 then insertCharacterAtCursor(if inputSystem.lastKeysPressed.shift == 1 then "}" else "]" end) end
if keyboard.press.SEMICOLON == 1 then insertCharacterAtCursor(if inputSystem.lastKeysPressed.shift == 1 then ":" else ";" end) end
if keyboard.press.QUOTE == 1 then insertCharacterAtCursor(if inputSystem.lastKeysPressed.shift == 1 then "\"" else "'" end) end
if keyboard.press.GRAVE == 1 then insertCharacterAtCursor(if inputSystem.lastKeysPressed.shift == 1 then "~" else "`" end) end
end
// Inserts a character into the current input string at the cursor's position.
insertCharacterAtCursor = function(char)
local before = inputSystem.currentInput.substring(0, inputSystem.cursorPosition)
local afters = inputSystem.currentInput.substring(inputSystem.cursorPosition)
inputSystem.currentInput = before + char + afters
inputSystem.cursorPosition += char.length // Move cursor past the inserted char.
// Trigger auto-complete update if enabled and a significant change occurred.
if inputSystem.autoComplete == 1 and char != "" then
updateAutoCompleteSuggestions()
end
end
// Handles the backspace key, deleting a character before the cursor.
handleBackspace = function()
if inputSystem.cursorPosition > 0 then
local before = inputSystem.currentInput.substring(0, inputSystem.cursorPosition - 1)
local afters = inputSystem.currentInput.substring(inputSystem.cursorPosition)
inputSystem.currentInput = before + afters
inputSystem.cursorPosition -= 1
// Update auto-completion suggestions.
if inputSystem.autoComplete == 1 then
updateAutoCompleteSuggestions()
end
end
end
// Navigates through the command history using Up/Down arrow keys.
navigateHistory = function(direction)
if inputSystem.history.length == 0 then return end
// Save current input if it's new and not already at the end of history.
if inputSystem.historyIndex == -1 and inputSystem.currentInput != "" then
// Temporarily store current input to restore later.
inputSystem.tempInput = inputSystem.currentInput
end
inputSystem.historyIndex += direction
// Clamp index within valid range.
if inputSystem.historyIndex < -1 then inputSystem.historyIndex = -1 end
if inputSystem.historyIndex >= inputSystem.history.length then inputSystem.historyIndex = inputSystem.history.length - 1 end
// Load input from history or restore temporary input.
if inputSystem.historyIndex == -1 then
inputSystem.currentInput = inputSystem.tempInput or ""
else
inputSystem.currentInput = inputSystem.history[inputSystem.historyIndex]
end
inputSystem.cursorPosition = inputSystem.currentInput.length // Move cursor to end.
inputSystem.suggestions = [] // Clear suggestions when navigating history.
end
// Triggers auto-completion, applying the first suggestion.
triggerAutoComplete = function()
if inputSystem.suggestions.length > 0 then
local suggestion = inputSystem.suggestions[0]
inputSystem.currentInput = suggestion
inputSystem.cursorPosition = suggestion.length
inputSystem.suggestions = [] // Clear suggestions after applying.
logDebug("Auto-complete applied: " + suggestion)
else
logDebug("No auto-complete suggestions available.")
end
end
// Updates auto-completion suggestions based on the current input.
updateAutoCompleteSuggestions = function()
inputSystem.suggestions = [] // Clear previous suggestions.
local beforeCursor = inputSystem.currentInput.substring(0, inputSystem.cursorPosition)
local words = beforeCursor.split(" ")
local currentWord = words[words.length - 1]
if currentWord.length >= 2 then // Only suggest if word is long enough.
inputSystem.suggestions = findAutoCompleteMatches(currentWord)
logDebug("Auto-complete suggestions generated for: " + currentWord + ", Count: " + inputSystem.suggestions.length)
end
end
// Handles mouse clicks, checking against UI buttons.
handleMouseInput = function()
// Only process on mouse press to avoid multiple triggers.
if mouse.press.left == 1 then
local clickX = mouse.x
local clickY = mouse.y
logDebug("Mouse click detected at (" + clickX + "," + clickY + ")")
// Check side panel buttons.
local panelLeftX = screen.width/2 - ui.layout.sidebarWidth
local panelRightX = screen.width/2
// Adjust mouse.x to be relative to screen center for isMouseOver.
local mouseCenterX = clickX
local mouseCenterY = clickY
// Check against all registered clickable components.
if ui.components.buttons != 0 then
for btn in ui.components.buttons
if isMouseOver(btn.x, btn.y, btn.w, btn.h) == 1 then
if btn.onClick != 0 then
btn.onClick() // Execute the button's action.
createParticleBurst(btn.x, btn.y, "typing", 5) // Visual feedback.
logInfo("Button clicked: " + btn.type + " at (" + btn.x + "," + btn.y + ")")
return // Stop after first button hit.
end
end
end
end
logDebug("No UI button clicked.")
end
end
// Handles global keyboard shortcuts (e.g., Ctrl+L to clear input).
handleGlobalShortcuts = function()
// Ctrl+L - Clear input.
if keyboard.L == 1 and inputSystem.lastKeysPressed.control == 1 then
inputSystem.currentInput = ""
inputSystem.cursorPosition = 0
inputSystem.suggestions = []
addNotification("Input cleared.", ui.theme.colors.info, 750)
logInfo("Shortcut: Input cleared (Ctrl+L).")
end
// Ctrl+H - Show help.
if keyboard.H == 1 and inputSystem.lastKeysPressed.control == 1 then
showHelp()
logInfo("Shortcut: Help shown (Ctrl+H).")
end
// F1 - Show shortcuts.
if keyboard.F1 == 1 then
showShortcuts()
logInfo("Shortcut: Shortcuts shown (F1).")
end
// Escape - Cancel current processing or close overlay.
if keyboard.press.ESCAPE == 1 then
if state.isProcessing == 1 then
state.isProcessing = 0 // Simulate cancelling AI processing.
addNotification("AI processing cancelled.", ui.theme.colors.warning, 1000)
logInfo("Shortcut: AI processing cancelled (Escape).")
end
// Add logic here to close other overlays/panels if they were open.
end
end
// ============================================================================
// MESSAGE PROCESSING & AI RESPONSE GENERATION
// Core logic for understanding user input and generating AI replies.
// ============================================================================
// Sends the current input message for processing.
sendMessage = function()
if inputSystem.currentInput.trim() == "" then
logWarn("Attempted to send empty message.")
return
end
local message = inputSystem.currentInput.trim()
inputSystem.currentInput = ""
inputSystem.cursorPosition = 0
inputSystem.suggestions = [] // Clear suggestions.
// Add to command history.
inputSystem.history.push(message)
inputSystem.historyIndex = -1 // Reset index after adding new message.
// Limit history size to prevent excessive memory use.
if inputSystem.history.length > maxHistory then
inputSystem.history.shift()
end
// Add user message to chat history.
addUserMessage(message)
// Process the message with the AI.
processMessage(message)
logInfo("User message sent: " + message.substring(0, 50))
end
// Adds a user-generated message to the chat history.
addUserMessage = function(content)
local message = object
role = "user"
content = content
timestamp = system.time()
type = "text"
metadata = object
processingTime = 0
confidence = 1.0
source = "user_input"
end
end
chatHistory.push(message)
state.totalInteractions += 1
// Always scroll to the bottom when a new message is added.
scrollOffset = 0
logDebug("User message added to history.")
end
// Adds an AI-generated assistant message to the chat history.
addAssistantMessage = function(content, type = "text", metadata = 0)
local message = object
role = "assistant"
content = content
timestamp = system.time()
type = type
metadata = metadata or object end // Ensure metadata is an object even if nil.
end
chatHistory.push(message)
// Update conversation context based on AI's response (e.g., topic change).
updateConversationContext(content)
// Auto-scroll to bottom.
scrollOffset = 0
logDebug("Assistant message added to history. Type: " + type)
end
// Main function to process a user's message, determine intent, and generate a response.
processMessage = function(message)
state.isProcessing = 1 // Set AI to busy state.
local startTime = system.time()
// First, check if the message is a command (starts with '/').
if message.startsWith("/") == 1 then
processCommand(message)
state.isProcessing = 0 // Commands are typically processed immediately.
return
end
// Execute plugin hooks that act on user input.
executePluginHooks("onUserInput", message)
// Determine the type of message (code, tutorial, debug, etc.) to guide AI response.
local messageType = determineMessageType(message)
state.processingType = getProcessingText(messageType) // Update status text.
// Generate the AI's response asynchronously (simulated with `after`).
generateResponse(message, messageType, function(response)
local processingTime = system.time() - startTime
// Add the AI's response to the chat.
addAssistantMessage(response.content, response.type, object
processingTime = processingTime
confidence = response.confidence or 0.9 // Default confidence.
source = response.source or "ai"
tutorial = response.tutorial or 0 // Flag if it was a tutorial response.
end)
// Update performance metrics with the actual processing time.
updatePerformanceMetrics(processingTime)
// Execute plugin hooks after the AI has generated a response.
executePluginHooks("afterResponse", response)
state.isProcessing = 0 // Reset AI to ready state.
logInfo("AI response generated. Type: " + messageType + ", Time: " + processingTime + "ms.")
end)
end
// Determines the intent or category of the user's message.
determineMessageType = function(message)
local lowerMessage = message.toLowerCase()
// Code-related messages.
if matchesAny(lowerMessage, ["function", "class", "variable", "code", "algorithm", "debug", "snippet", "script"]) == 1 then
return "code"
end
// Help/tutorial messages.
if matchesAny(lowerMessage, ["how to", "tutorial", "learn", "explain", "what is", "guide", "teach me"]) == 1 then
return "tutorial"
end
// Debugging messages.
if matchesAny(lowerMessage, ["error", "bug", "issue", "problem", "not working", "fix", "troubleshoot"]) == 1 then
return "debugging"
end
// Optimization messages.
if matchesAny(lowerMessage, ["optimize", "performance", "improve", "better", "faster", "lag", "fps"]) == 1 then
return "optimization"
end
// Design pattern or architecture messages.
if matchesAny(lowerMessage, ["pattern", "refactor", "design", "architecture", "structure", "model", "ecs", "mvc"]) == 1 then
return "pattern"
end
// Game specific questions.
if matchesAny(lowerMessage, ["game", "player", "enemy", "level", "sprite", "collision", "physics"]) == 1 then
return "game_dev"
end
// Default to general chat if no specific category matches.
return "general"
end
// Generates an AI response based on the message content and its determined type.
generateResponse = function(message, messageType, callback)
// Check cache first for a quick response.
local cacheKey = message + "_" + messageType + "_" + conversationContext.userPreferences.verbosity
local cachedResponse = getCachedResponse(cacheKey)
if cachedResponse != 0 then
// Simulate a very short delay for cached responses.
after 50 + random.nextInt(50) do
callback(cachedResponse)
end
return
end
local response = 0 // Initialize response to null (0).
// Select appropriate response generation function based on message type.
if messageType == "code" then
response = generateCodeResponse(message)
elsif messageType == "tutorial" then
response = generateTutorialResponse(message)
elsif messageType == "debugging" then
response = generateDebuggingResponse(message)
elsif messageType == "optimization" then
response = generateOptimizationResponse(message)
elsif messageType == "pattern" then
response = generatePatternResponse(message)
elsif messageType == "game_dev" then
response = generateGameDevResponse(message)
else
response = generateGeneralResponse(message)
end
// Cache the newly generated response.
cacheResponse(cacheKey, response)
// Simulate asynchronous AI processing time.
after 100 + random.nextInt(1000) do // 100ms to 1100ms delay.
callback(response)
end
end
// Generates code-related responses.
generateCodeResponse = function(message)
local lowerMessage = message.toLowerCase()
// Specific code pattern recognition for generating targeted examples.
if matchesAny(lowerMessage, ["sprite", "draw", "render", "graphics"]) == 1 then
return object
content = generateGraphicsCode(message)
type = "code"
language = "microscript"
confidence = 0.95
end
elsif matchesAny(lowerMessage, ["loop", "for", "while", "iterate", "collection"]) == 1 then
return object
content = generateLoopCode(message)
type = "code"
language = "microscript"
confidence = 0.9
end
elsif matchesAny(lowerMessage, ["function", "method", "define", "class", "object"]) == 1 then
return object
content = generateFunctionClassCode(message)
type = "code"
language = "microscript"
confidence = 0.9
end
elsif matchesAny(lowerMessage, ["input", "keyboard", "mouse", "touch", "gamepad"]) == 1 then
return object
content = generateInputHandlingCode(message)
type = "code"
language = "microscript"
confidence = 0.9
end
elsif matchesAny(lowerMessage, ["physics", "collision", "movement", "velocity"]) == 1 then
return object
content = generatePhysicsCode(message)
type = "code"
language = "microscript"
confidence = 0.9
end
elsif matchesAny(lowerMessage, ["data structure", "list", "object", "array", "dictionary"]) == 1 then
return object
content = generateDataStructureCode(message)
type = "code"
language = "microscript"
confidence = 0.88
end
elsif matchesAny(lowerMessage, ["algorithm", "sort", "search"]) == 1 then
return object
content = generateAlgorithmCode(message)
type = "code"
language = "microscript"
confidence = 0.88
end
else
// General code help.
return object
content = generateGeneralCodeHelp(message)
type = "text"
confidence = 0.85
end
end
end
// Generates microScript code examples for graphics and rendering.
generateGraphicsCode = function(message)
local lowerMessage = message.toLowerCase()
local codeString = ""
if matchesAny(lowerMessage, ["sprite", "image", "drawsprite"]) == 1 then
codeString = "// --- microScript Graphics: Drawing Sprites & Advanced Options ---" + "\n" +
"// This example demonstrates how to draw sprites with transformations" + "\n" +
"// and includes a custom function for advanced sprite rendering." + "\n" +
"" + "\n" +
"// Global variables for demonstration" + "\n" +
"playerSpriteX = 0" + "\n" +
"playerSpriteY = 0" + "\n" +
"playerRotation = 0" + "\n" +
"playerScale = 1" + "\n" +
"playerAlpha = 1" + "\n" +
"pulseTimer = 0" + "\n" +
"particleSystem = []" + "\n" +
"" + "\n" +
"// Custom function to draw a sprite with extra parameters like rotation, scale, alpha, tint." + "\n" +
"// This abstracts common drawing tasks and improves code readability." + "\n" +
"drawEnhancedSprite = function(spriteName, x, y, width, height, options)" + "\n" +
" options = options or object end // Ensure options is an object if not provided." + "\n" +
" local rotation = options.rotation or 0" + "\n" +
" local scaleX = options.scaleX or (options.scale or 1)" + "\n" +
" local scaleY = options.scaleY or (options.scale or 1)" + "\n" +
" local alpha = options.alpha or 1" + "\n" +
" local tint = options.tint or \"#ffffff\" // Default to white (no tint)." + "\n" +
" local anchorX = options.anchorX or 0" + "\n" +
" local anchorY = options.anchorY or 0" + "\n" +
"" + "\n" +
" screen.setDrawRotation(rotation)" + "\n" +
" screen.setDrawScale(scaleX, scaleY)" + "\n" +
" screen.setAlpha(alpha)" + "\n" +
" screen.setDrawAnchor(anchorX, anchorY)" + "\n" +
"" + "\n" +
" if tint != \"#ffffff\" then" + "\n" +
" screen.setBlending(\"multiply\") // Apply tint color." + "\n" +
" screen.setColor(tint)" + "\n" +
" screen.drawSprite(spriteName, x, y, width, height)" + "\n" +
" screen.setColor(\"#ffffff\") // Reset color for other sprites." + "\n" +
" screen.setBlending(\"normal\") // Reset blending mode." + "\n" +
" else" + "\n" +
" screen.drawSprite(spriteName, x, y, width, height)" + "\n" +
" end" + "\n" +
"" + "\n" +
" // Always reset transformations after drawing to avoid affecting subsequent draws." + "\n" +
" screen.setDrawRotation(0)" + "\n" +
" screen.setDrawScale(1, 1)" + "\n" +
" screen.setAlpha(1)" + "\n" +
" screen.setDrawAnchor(0, 0)" + "\n" +
"end" + "\n" +
"" + "\n" +
"// Particle object for a simple particle effect." + "\n" +
"Particle = class" + "\n" +
" constructor = function(x, y, color)" + "\n" +
" this.x = x" + "\n" +
" this.y = y" + "\n" +
" this.vx = (random.next() - 0.5) * 5" + "\n" +
" this.vy = (random.next() - 0.5) * 5" + "\n" +
" this.size = random.next() * 3 + 1" + "\n" +
" this.life = 1.0 // 1.0 = full life, 0.0 = dead." + "\n" +
" this.color = color" + "\n" +
" end" + "\n" +
" " + "\n" +
" update = function(deltaTime)" + "\n" +
" this.x += this.vx * deltaTime" + "\n" +
" this.y += this.vy * deltaTime" + "\n" +
" this.life -= deltaTime * 0.5 // Particle fades over 2 seconds." + "\n" +
" if this.life < 0 then this.life = 0 end" + "\n" +
" end" + "\n" +
" " + "\n" +
" draw = function()" + "\n" +
" screen.setAlpha(this.life)" + "\n" +
" screen.fillRect(this.x, this.y, this.size, this.size, this.color)" + "\n" +
" end" + "\n" +
"end" + "\n" +
"" + "\n" +
"// init function: Called once at the start of the program." + "\n" +
"init = function()" + "\n" +
" // Ensure your project has a sprite named 'player' for this to work." + "\n" +
" // If not, use 'player' for testing or replace with an existing sprite name." + "\n" +
" logInfo(\"Graphics init: player sprite should exist.\")" + "\n" +
"end" + "\n" +
"" + "\n" +
"// update function: Called 60 times per second for game logic." + "\n" +
"update = function()" + "\n" +
" local deltaTime = 1/60 // Assuming 60 FPS update." + "\n" +
" " + "\n" +
" // Animate player sprite properties for visual effect." + "\n" +
" playerRotation += 1 // Rotate 1 degree per frame." + "\n" +
" if playerRotation >= 360 then playerRotation = 0 end" + "\n" +
"" + "\n" +
" // Make player scale pulse." + "\n" +
" pulseTimer += deltaTime * 5 // Speed of pulse." + "\n" +
" playerScale = 1 + sin(pulseTimer) * 0.1 // Scale between 0.9 and 1.1." + "\n" +
" playerAlpha = 0.8 + cos(pulseTimer * 0.5) * 0.2 // Alpha between 0.6 and 1.0." + "\n" +
"" + "\n" +
" // Update particles." + "\n" +
" local activeParticles = []" + "\n" +
" for p in particleSystem" + "\n" +
" p.update(deltaTime)" + "\n" +
" if p.life > 0 then activeParticles.push(p) end" + "\n" +
" end" + "\n" +
" particleSystem = activeParticles" + "\n" +
"" + "\n" +
" // Create new particles on mouse click (for testing)." + "\n" +
" if mouse.press.left == 1 then" + "\n" +
" for i = 0 to 5 // Burst of 5 particles." + "\n" +
" particleSystem.push(new Particle(mouse.x, mouse.y, ui.theme.colors.accent_tertiary))" + "\n" +
" end" + "\n" +
" end" + "\n" +
"end" + "\n" +
"" + "\n" +
"// draw function: Called as fast as possible to render frames." + "\n" +
"draw = function()" + "\n" +
" screen.clear(ui.theme.colors.bg_primary) // Clear screen with background color." + "\n" +
"" + "\n" +
" // Draw player sprite with animated properties." + "\n" +
" drawEnhancedSprite(\"player\", playerSpriteX, playerSpriteY, 64, 64, object" + "\n" +
" rotation = playerRotation" + "\n" +
" scale = playerScale" + "\n" +
" alpha = playerAlpha" + "\n" +
" tint = ui.theme.colors.accent_primary // Give it a green tint." + "\n" +
" end)" + "\n" +
"" + "\n" +
" // Draw another sprite, perhaps a background element." + "\n" +
" screen.setAlpha(0.6) // Slightly transparent." + "\n" +
" screen.drawSprite(\"background_tile\", screen.width/2 - 50, screen.height/2 - 50, 100, 100) // Example." + "\n" +
" screen.setAlpha(1) // Reset alpha." + "\n" +
"" + "\n" +
" // Draw all active particles." + "\n" +
" for p in particleSystem" + "\n" +
" p.draw()" + "\n" +
" end" + "\n" +
"" + "\n" +
" // Draw some UI text." + "\n" +
" screen.drawText(\"Click to spawn particles!\", 0, -screen.height/2 + 20, 14, ui.theme.colors.text_primary)" + "\n" +
" screen.drawText(\"Player Rotation: \" + floor(playerRotation), 0, -screen.height/2 + 40, 10, ui.theme.colors.text_secondary)" + "\n" +
" screen.drawText(\"Player Scale: \" + round(playerScale*100)/100, 0, -screen.height/2 + 55, 10, ui.theme.colors.text_secondary)" + "\n" +
"end" + "\n"
elsif matchesAny(lowerMessage, ["shape", "rect", "round", "polygon", "line"]) == 1 then
codeString = "// --- microScript Graphics: Drawing Basic Shapes & Gradients ---" + "\n" +
"// This example demonstrates drawing various shapes with colors and gradients." + "\n" +
"" + "\n" +
"// Global variables for animation." + "\n" +
"shapePulse = 0" + "\n" +
"lineAngle = 0" + "\n" +
"" + "\n" +
"// Function to draw an animated shape based on its type." + "\n" +
"drawAnimatedShape = function(x, y, size, shapeType)" + "\n" +
" if shapeType == \"circle\" then" + "\n" +
" local radius = size/2 * (1 + sin(shapePulse) * 0.2)" + "\n" +
" screen.setRadialGradient(x, y, 0, radius, ui.theme.colors.accent_tertiary, ui.theme.colors.bg_primary) // Green glow to dark." + "\n" +
" screen.fillRound(x, y, radius * 2, radius * 2) // microScript fillRound takes width/height." + "\n" +
" screen.setRadialGradient(0, 0, 0, 0, \"#fff\", \"#fff\") // Reset gradient." + "\n" +
" elsif shapeType == \"square\" then" + "\n" +
" local squareSize = size * (1 + abs(cos(shapePulse * 0.8)) * 0.1)" + "\n" +
" local rot = system.time() / 100 * 0.5 // Slow rotation." + "\n" +
" screen.setDrawRotation(rot)" + "\n" +
" screen.drawRect(x, y, squareSize, squareSize, ui.theme.colors.glow_primary, 3) // Thick glowing border." + "\n" +
" screen.setDrawRotation(0)" + "\n" +
" elsif shapeType == \"triangle\" then" + "\n" +
" local triangleScale = 1 + sin(shapePulse * 1.2) * 0.15" + "\n" +
" local baseLen = size * triangleScale" + "\n" +
" local heightLen = size * triangleScale" + "\n" +
" // Define points relative to center X, Y, then rotate." + "\n" +
" local p1x = x" + "\n" +
" local p1y = y + heightLen / 2" + "\n" +
" local p2x = x - baseLen / 2" + "\n" +
" local p2y = y - heightLen / 2" + "\n" +
" local p3x = x + baseLen / 2" + "\n" +
" local p3y = y - heightLen / 2" + "\n" +
" " + "\n" +
" screen.setDrawRotation(system.time() / 50 * 0.2)" + "\n" +
" screen.fillPolygon(p1x, p1y, p2x, p2y, p3x, p3y, ui.theme.colors.accent_quaternary)" + "\n" +
" screen.setDrawRotation(0)" + "\n" +
" end" + "\n" +
"end" + "\n" +
"" + "\n" +
"// init function: Called once at the start." + "\n" +
"init = function()" + "\n" +
" logInfo(\"Shape drawing init.\")" + "\n" +
"end" + "\n" +
"" + "\n" +
"// update function: Called 60 times per second." + "\n" +
"update = function()" + "\n" +
" local deltaTime = 1/60" + "\n" +
" shapePulse += deltaTime * 2 // Speed of animation." + "\n" +
" lineAngle += 2 // Rotate line around center." + "\n" +
" if lineAngle >= 360 then lineAngle = 0 end" + "\n" +
"end" + "\n" +
"" + "\n" +
"// draw function: Called as fast as possible." + "\n" +
"draw = function()" + "\n" +
" screen.clear(ui.theme.colors.bg_primary) // Clear background." + "\n" +
"" + "\n" +
" // Draw shapes at different positions." + "\n" +
" drawAnimatedShape(-screen.width/4, 0, 80, \"circle\")" + "\n" +
" drawAnimatedShape(0, 0, 60, \"square\")" + "\n" +
" drawAnimatedShape(screen.width/4, 0, 70, \"triangle\")" + "\n" +
"" + "\n" +
" // Draw a rotating line." + "\n" +
" local len = 150" + "\n" +
" local x1 = cosd(lineAngle) * len / 2" + "\n" +
" local y1 = sind(lineAngle) * len / 2" + "\n" +
" local x2 = cosd(lineAngle + 180) * len / 2" + "\n" +
" local y2 = sind(lineAngle + 180) * len / 2" + "\n" +
" screen.drawLine(x1, y1, x2, y2, ui.theme.colors.text_primary, 2)" + "\n" +
"" + "\n" +
" // Draw a transparent filled rectangle." + "\n" +
" screen.setAlpha(0.3 + abs(sin(shapePulse)) * 0.2) // Pulsing alpha." + "\n" +
" screen.fillRect(0, screen.height/2 - 100, 200, 50, ui.theme.colors.accent_secondary)" + "\n" +
" screen.setAlpha(1)" + "\n" +
"" + "\n" +
" screen.drawText(\"Animated Shapes!\", 0, screen.height/2 - 20, 18, ui.theme.colors.text_primary)" + "\n" +
"end" + "\n"
else
codeString = generateGeneralCodeHelp(message) // Fallback for general code queries.
end
return codeString
end
// Generates microScript code examples for various loop structures.
generateLoopCode = function(message)
local lowerMessage = message.toLowerCase()
local codeString = ""
codeString = "// --- microScript Loop Examples ---" + "\n" +
"// This snippet demonstrates common loop structures in microScript." + "\n" +
"" + "\n" +
"// 1. Basic 'for' loop: Iterating a fixed number of times." + "\n" +
"// Counts from 0 to 9 (inclusive)." + "\n" +
"print(\"---- Basic For Loop (0 to 9) ----\")" + "\n" +
"for i = 0 to 9" + "\n" +
" print(\"Iteration: \" + i)" + "\n" +
"end" + "\n" +
"" + "\n" +
"// 2. 'for' loop with 'by' step: Counting with a custom increment/decrement." + "\n" +
"// Counts from 0 to 100, stepping by 20." + "\n" +
"print(\"\\n---- For Loop with Step (0 to 100 by 20) ----\")" + "\n" +
"for i = 0 to 100 by 20" + "\n" +
" print(\"Count: \" + i)" + "\n" +
"end" + "\n" +
"" + "\n" +
"// 3. Reverse 'for' loop: Counting downwards." + "\n" +
"// Counts from 5 down to 0." + "\n" +
"print(\"\\n---- Reverse For Loop (5 down to 0) ----\")" + "\n" +
"for i = 5 to 0 by -1" + "\n" +
" print(\"Countdown: \" + i)" + "\n" +
"end" + "\n" +
"" + "\n" +
"// 4. 'for ... in' loop: Iterating over elements in a list (array)." + "\n" +
"local fruits = [\"apple\", \"banana\", \"cherry\", \"date\"]" + "\n" +
"print(\"\\n---- For-In Loop (List Elements) ----\")" + "\n" +
"for fruit in fruits" + "\n" +
" print(\"I like \" + fruit)" + "\n" +
"end" + "\n" +
"" + "\n" +
"// 5. Indexed 'for' loop: Accessing list elements by index." + "\n" +
"print(\"\\n---- Indexed For Loop (List by Index) ----\")" + "\n" +
"for i = 0 to fruits.length - 1" + "\n" +
" print(\"Fruit at index \" + i + \": \" + fruits[i])" + "\n" +
"end" + "\n" +
"" + "\n" +
"// 6. 'while' loop: Repeating as long as a condition is true." + "\n" +
"local energy = 10" + "\n" +
"print(\"\\n---- While Loop (Energy Depletion) ----\")" + "\n" +
"while energy > 0" + "\n" +
" print(\"Current energy: \" + energy)" + "\n" +
" energy -= random.nextInt(3) + 1 // Lose 1-3 energy." + "\n" +
" if energy < 0 then energy = 0 end // Prevent negative energy." + "\n" +
"end" + "\n" +
"print(\"Energy depleted!\")" + "\n" +
"" + "\n" +
"// 7. Nested loops: Iterating over 2D structures like a grid." + "\n" +
"print(\"\\n---- Nested Loops (Grid Iteration) ----\")" + "\n" +
"local gridSize = 3" + "\n" +
"for y = 0 to gridSize - 1" + "\n" +
" for x = 0 to gridSize - 1" + "\n" +
" print(\"Cell (\" + x + \",\" + y + \")\")" + "\n" +
" end" + "\n" +
"end" + "\n" +
"" + "\n" +
"// 8. 'break' statement: Exiting a loop early." + "\n" +
"print(\"\\n---- Loop with Break ----\")" + "\n" +
"for i = 1 to 100" + "\n" +
" print(\"Checking item: \" + i)" + "\n" +
" if i == 7 then" + "\n" +
" print(\"Found special item at \" + i + \". Breaking loop.\")" + "\n" +
" break" + "\n" +
" end" + "\n" +
"end" + "\n" +
"" + "\n" +
"// 9. 'continue' statement: Skipping the rest of the current iteration." + "\n" +
"print(\"\\n---- Loop with Continue ----\")" + "\n" +
"for i = 1 to 10" + "\n" +
" if i % 2 == 0 then" + "\n" +
" print(\"Skipping even number: \" + i)" + "\n" +
" continue // Skip to the next iteration if 'i' is even." + "\n" +
" end" + "\n" +
" print(\"Processing odd number: \" + i)" + "\n" +
"end" + "\n" +
"" + "\n" +
"// 10. Optimizing loop performance: Caching list length." + "\n" +
"// Useful for very long lists to avoid recalculating length in each iteration." + "\n" +
"local largeList = [] // Imagine this has thousands of elements." + "\n" +
"for i = 0 to 999 do largeList.push(i) end // Populate for example." + "\n" +
"local listLength = largeList.length // Cache the length." + "\n" +
"print(\"\\n---- Optimized Loop (Cached Length) ----\")" + "\n" +
"for i = 0 to listLength - 1" + "\n" +
" // print(\"Processing element \" + largeList[i])" + "\n" +
"end" + "\n" +
"print(\"Processed \" + listLength + \" elements efficiently.\")" + "\n"
return codeString
end
// Generates microScript code examples for functions and classes.
generateFunctionClassCode = function(message)
local lowerMessage = message.toLowerCase()
local codeString = ""
codeString = "// --- microScript Functions and Classes Examples ---" + "\n" +
"// This comprehensive example covers various ways to define and use functions and classes." + "\n" +
"" + "\n" +
"// 1. Basic Function Definition: A simple reusable block of code." + "\n" +
"// MicroScript functions are first-class citizens." + "\n" +
"sayHello = function(name)" + "\n" +
" return \"Hello, \" + name + \"!\"" + "\n" +
"end" + "\n" +
"print(sayHello(\"World\")) // Output: Hello, World!" + "\n" +
"" + "\n" +
"// 2. Function with Multiple Parameters and Conditional Logic." + "\n" +
"calculate = function(a, b, operation)" + "\n" +
" if operation == \"add\" then" + "\n" +
" return a + b" + "\n" +
" elsif operation == \"multiply\" then" + "\n" +
" return a * b" + "\n" +
" elsif operation == \"subtract\" then" + "\n" +
" return a - b" + "\n" +
" else" + "\n" +
" print(\"Error: Unknown operation: \" + operation)" + "\n" +
" return 0" + "\n" +
" end" + "\n" +
"end" + "\n" +
"print(\"5 + 3 = \" + calculate(5, 3, \"add\")) // Output: 5 + 3 = 8" + "\n" +
"print(\"5 * 3 = \" + calculate(5, 3, \"multiply\")) // Output: 5 * 3 = 15" + "\n" +
"" + "\n" +
"// 3. Arrow Function (Concise Syntax): For simple, single-expression functions." + "\n" +
"square = (x) => x * x" + "\n" +
"print(\"Square of 4: \" + square(4)) // Output: Square of 4: 16" + "\n" +
"" + "\n" +
"// 4. Function with Default Parameters (using 'or' operator)." + "\n" +
"// If a parameter is not provided, it will fall back to the default value." + "\n" +
"greet = function(name, greeting)" + "\n" +
" greeting = greeting or \"Greetings\"" + "\n" +
" return greeting + \", \" + name + \"!\"" + "\n" +
"end" + "\n" +
"print(greet(\"Alice\")) // Output: Greetings, Alice!" + "\n" +
"print(greet(\"Bob\", \"Hi\")) // Output: Hi, Bob!" + "\n" +
"" + "\n" +
"// 5. Function Returning an Object: Simulating multiple return values." + "\n" +
"// This is a common pattern for returning structured data." + "\n" +
"getStats = function(val1, val2)" + "\n" +
" local sum = val1 + val2" + "\n" +
" local product = val1 * val2" + "\n" +
" local difference = val1 - val2" + "\n" +
" return object" + "\n" +
" sum = sum" + "\n" +
" product = product" + "\n" +
" difference = difference" + "\n" +
" end" + "\n" +
"end" + "\n" +
"local results = getStats(10, 5)" + "\n" +
"print(\"Stats for (10, 5) -> Sum: \" + results.sum + \", Product: \" + results.product + \", Diff: \" + results.difference)" + "\n" +
"" + "\n" +
"// 6. Higher-Order Functions: Functions that take other functions as arguments." + "\n" +
"// Useful for abstraction and creating flexible APIs." + "\n" +
"processNumbers = function(numberList, processingFunction)" + "\n" +
" local outputList = []" + "\n" +
" for num in numberList" + "\n" +
" outputList.push(processingFunction(num))" + "\n" +
" end" + "\n" +
" return outputList" + "\n" +
"end" + "\n" +
"local myNumbers = [1, 2, 3, 4, 5]" + "\n" +
"local doubledNumbers = processNumbers(myNumbers, (x) => x * 2)" + "\n" +
"print(\"Doubled numbers: \" + doubledNumbers) // Output: Doubled numbers: [2, 4, 6, 8, 10]" + "\n" +
"" + "\n" +
"// 7. Closures: Functions retaining access to their outer scope variables." + "\n" +
"// This creates a private state that persists across calls." + "\n" +
"createCounter = function(initialValue)" + "\n" +
" local count = initialValue or 0 // 'count' is captured by the inner function." + "\n" +
" return function()" + "\n" +
" count += 1" + "\n" +
" return count" + "\n" +
" end" + "\n" +
"end" + "\n" +
"local counter1 = createCounter(10)" + "\n" +
"local counter2 = createCounter()" + "\n" +
"print(\"Counter 1: \" + counter1()) // Output: Counter 1: 11" + "\n" +
"print(\"Counter 2: \" + counter2()) // Output: Counter 2: 1" + "\n" +
"print(\"Counter 1: \" + counter1()) // Output: Counter 1: 12" + "\n" +
"" + "\n" +
"// --- Class Definitions ---" + "\n" +
"" + "\n" +
"// 8. Basic Class Definition: Represents a blueprint for creating objects." + "\n" +
"// Classes are a core feature for Object-Oriented Programming (OOP) in microScript." + "\n" +
"Player = class" + "\n" +
" // Constructor: Called automatically when a new Player object is created." + "\n" +
" constructor = function(name, initialHealth)" + "\n" +
" this.name = name" + "\n" +
" this.health = initialHealth" + "\n" +
" this.x = 0" + "\n" +
" this.y = 0" + "\n" +
" end" + "\n" +
" " + "\n" +
" // Method: A function associated with the class, operating on instance data." + "\n" +
" move = function(dx, dy)" + "\n" +
" this.x += dx" + "\n" +
" this.y += dy" + "\n" +
" print(this.name + \" moved to (\" + this.x + \",\" + this.y + \")\")" + "\n" +
" end" + "\n" +
" " + "\n" +
" takeDamage = function(amount)" + "\n" +
" this.health -= amount" + "\n" +
" print(this.name + \" took \" + amount + \" damage. Health: \" + this.health)" + "\n" +
" if this.health <= 0 then" + "\n" +
" print(this.name + \" has been defeated!\")" + "\n" +
" end" + "\n" +
" end" + "\n" +
"end" + "\n" +
"" + "\n" +
"// Create an instance of the Player class." + "\n" +
"local hero = new Player(\"Sir Lancelot\", 100)" + "\n" +
"hero.move(10, 5)" + "\n" +
"hero.takeDamage( hero.health / 2 )" + "\n" +
"" + "\n" +
"// 9. Class Inheritance: Creating a new class based on an existing one." + "\n" +
"// The 'extends' keyword is used to inherit properties and methods." + "\n" +
"Enemy = class extends Player" + "\n" +
" constructor = function(name, initialHealth, attackPower)" + "\n" +
" super(name, initialHealth) // Call the parent class's constructor." + "\n" +
" this.attackPower = attackPower" + "\n" +
" end" + "\n" +
" " + "\n" +
" attack = function(target)" + "\n" +
" print(this.name + \" attacks \" + target.name + \" for \" + this.attackPower + \" damage!\")" + "\n" +
" target.takeDamage(this.attackPower)" + "\n" +
" end" + "\n" +
"end" + "\n" +
"" + "\n" +
"local goblin = new Enemy(\"Goblin\", 30, 5)" + "\n" +
"goblin.move(-hero.x, -hero.y) // Move to hero's location." + "\n" +
"goblin.attack(hero)" + "\n" +
"goblin.attack(hero)" + "\n" +
"" + "\n" +
"// 10. Static Methods: Functions associated with the class itself, not its instances." + "\n" +
"// Useful for utility functions or factory methods." + "\n" +
"GameUtils = class" + "\n" +
" static randomRange = function(min, max)" + "\n" +
" return floor(random.next() * (max - min + 1)) + min" + "\n" +
" end" + "\n" +
" " + "\n" +
" static distance = function(x1, y1, x2, y2)" + "\n" +
" local dx = x2 - x1" + "\n" +
" local dy = y2 - y1" + "\n" +
" return sqrt(dx * dx + dy * dy)" + "\n" +
" end" + "\n" +
"end" + "\n" +
"" + "\n" +
"print(\"Random number between 1 and 10: \" + GameUtils.randomRange(1, 10))" + "\n" +
"print(\"Distance between (0,0) and (3,4): \" + GameUtils.distance(0, 0, 3, 4))" + "\n" +
"" + "\n" +
"// 11. Object (dictionary) as a simple data structure or singleton-like pattern." + "\n" +
"// Unlike classes, 'object' creates a single instance directly." + "\n" +
"GameSettings = object" + "\n" +
" soundVolume = 0.8" + "\n" +
" musicVolume = 0.5" + "\n" +
" difficulty = \"normal\"" + "\n" +
" " + "\n" +
" toggleSound = function()" + "\n" +
" this.soundVolume = if this.soundVolume > 0 then 0 else 0.8 end" + "\n" +
" print(\"Sound toggled. Volume: \" + this.soundVolume)" + "\n" +
" end" + "\n" +
"end" + "\n" +
"" + "\n" +
"print(\"Current music volume: \" + GameSettings.musicVolume)" + "\n" +
"GameSettings.toggleSound()" + "\n" +
"" + "\n" +
"// This concludes the examples. These concepts are foundational for building complex games." + "\n"
return codeString
end
// Generates microScript code for handling various input types.
generateInputHandlingCode = function(message)
local lowerMessage = message.toLowerCase()
local codeString = ""
codeString = "// --- microScript Input Handling Examples ---" + "\n" +
"// This example covers keyboard, mouse, and touch input in microStudio." + "\n" +
"" + "\n" +
"// Global variables to track player position and input states." + "\n" +
"playerX = 0" + "\n" +
"playerY = 0" + "\n" +
"fireCooldown = 0" + "\n" +
"lastTapTime = 0" + "\n" +
"doubleTapThreshold = 300 // milliseconds" + "\n" +
"" + "\n" +
"// init function: Called once at the start of the program." + "\n" +
"init = function()" + "\n" +
" logInfo(\"Input handling initialized.\")" + "\n" +
"end" + "\n" +
"" + "\n" +
"// update function: Called 60 times per second for game logic and input checks." + "\n" +
"update = function()" + "\n" +
" local deltaTime = 1/60 // Assuming 60 FPS." + "\n" +
" " + "\n" +
" // --- Keyboard Input ---" + "\n" +
" // 'keyboard.KEYNAME' for continuous press (player movement)." + "\n" +
" if keyboard.LEFT == 1 then playerX -= 5 * deltaTime end" + "\n" +
" if keyboard.RIGHT == 1 then playerX += 5 * deltaTime end" + "\n" +
" if keyboard.UP == 1 then playerY += 5 * deltaTime end" + "\n" +
" if keyboard.DOWN == 1 then playerY -= 5 * deltaTime end" + "\n" +
" " + "\n" +
" // 'keyboard.press.KEYNAME' for single, instant press (actions like jump, shoot)." + "\n" +
" if keyboard.press.SPACE == 1 then" + "\n" +
" print(\"Spacebar pressed - Jump action!\")" + "\n" +
" // Trigger jump animation or physics here." + "\n" +
" end" + "\n" +
" " + "\n" +
" // Check for shooting with cooldown." + "\n" +
" if fireCooldown > 0 then fireCooldown -= system.time() - (system.time() - (1/60)) end" + "\n" +
" if keyboard.press.A == 1 and fireCooldown <= 0 then" + "\n" +
" print(\"A key pressed - Fire bullet!\")" + "\n" +
" // Spawn bullet, play sound." + "\n" +
" fireCooldown = 0.5 // 0.5 second cooldown." + "\n" +
" end" + "\n" +
" " + "\n" +
" // --- Mouse Input ---" + "\n" +
" // Get mouse coordinates. (0,0) is screen center." + "\n" +
" // print(\"Mouse X: \" + mouse.x + \", Y: \" + mouse.y) // Uncomment for continuous logging." + "\n" +
" " + "\n" +
" // 'mouse.left' for continuous left button press (e.g., dragging)." + "\n" +
" if mouse.left == 1 then" + "\n" +
" // Example: Drag player with mouse." + "\n" +
" // playerX = mouse.x" + "\n" +
" // playerY = mouse.y" + "\n" +
" end" + "\n" +
" " + "\n" +
" // 'mouse.press.left' for single left button click." + "\n" +
" if mouse.press.left == 1 then" + "\n" +
" print(\"Mouse Left button clicked at (\" + mouse.x + \",\" + mouse.y + \")\")" + "\n" +
" // Detect double tap for mouse." + "\n" +
" if system.time() - lastTapTime < doubleTapThreshold then" + "\n" +
" print(\"Mouse Double Tap detected!\")" + "\n" +
" end" + "\n" +
" lastTapTime = system.time()" + "\n" +
" end" + "\n" +
" " + "\n" +
" // 'mouse.press.right' for single right button click." + "\n" +
" if mouse.press.right == 1 then" + "\n" +
" print(\"Mouse Right button clicked at (\" + mouse.x + \",\" + mouse.y + \")\")" + "\n" +
" end" + "\n" +
" " + "\n" +
" // --- Touch Input (for mobile/touchscreen devices) ---" + "\n" +
" // 'touch.touching' for continuous touch." + "\n" +
" if touch.touching == 1 then" + "\n" +
" // print(\"Touch X: \" + touch.x + \", Y: \" + touch.y) // Continuous touch position." + "\n" +
" // Example: Move player towards touch point." + "\n" +
" playerX += (touch.x - playerX) * 0.1 // Lerp towards touch." + "\n" +
" playerY += (touch.y - playerY) * 0.1" + "\n" +
" end" + "\n" +
" " + "\n" +
" // 'touch.press' for single touch down event." + "\n" +
" if touch.press == 1 then" + "\n" +
" print(\"Touch pressed at (\" + touch.x + \",\" + touch.y + \")\")" + "\n" +
" // Access multiple touch points if available." + "\n" +
" if touch.touches.length > 1 then" + "\n" +
" print(\"Multiple touches detected!\")" + "\n" +
" // Example: Pinch/zoom gestures using touch.touches." + "\n" +
" end" + "\n" +
" end" + "\n" +
" " + "\n" +
" // --- Gamepad Input (for controllers) ---" + "\n" +
" // Check individual buttons." + "\n" +
" if gamepad.A == 1 then" + "\n" +
" print(\"Gamepad A button pressed!\")" + "\n" +
" end" + "\n" +
" " + "\n" +
" // Left analog stick for movement." + "\n" +
" local stickAmount = gamepad.LEFT_STICK_AMOUNT" + "\n" +
" if stickAmount > 0.1 then // Deadzone for stick." + "\n" +
" local stickAngle = gamepad.LEFT_STICK_ANGLE" + "\n" +
" playerX += cosd(stickAngle) * stickAmount * 10 * deltaTime" + "\n" +
" playerY += sind(stickAngle) * stickAmount * 10 * deltaTime" + "\n" +
" end" + "\n" +
"end" + "\n" +
"" + "\n" +
"// draw function: Called as fast as possible to render input feedback." + "\n" +
"draw = function()" + "\n" +
" screen.clear(ui.theme.colors.bg_primary)" + "\n" +
"" + "\n" +
" // Draw a player representation at (playerX, playerY)." + "\n" +
" screen.drawSprite(\"player_icon\", playerX, playerY, 32, 32)" + "\n" +
"" + "\n" +
" // Visualize mouse position." + "\n" +
" screen.drawRect(mouse.x, mouse.y, 10, 10, ui.theme.colors.accent_primary, 1)" + "\n" +
" " + "\n" +
" // Visualize touch position(s)." + "\n" +
" if touch.touching == 1 then" + "\n" +
" for t in touch.touches" + "\n" +
" screen.fillRound(t.x, t.y, 20, 20, ui.theme.colors.accent_quaternary)" + "\n" +
" end" + "\n" +
" end" + "\n" +
"" + "\n" +
" // Display current player coordinates." + "\n" +
" screen.drawText(\"Player: (\" + floor(playerX) + \", \" + floor(playerY) + \")\", 0, screen.height/2 - 20, 14, ui.theme.colors.text_primary)" + "\n" +
" screen.drawText(\"Use WASD/Arrows for movement, Space for Jump, A for Shoot.\", 0, screen.height/2 - 40, 10, ui.theme.colors.text_secondary)" + "\n" +
" screen.drawText(\"Use Mouse for click, Touch for drag.\", 0, screen.height/2 - 55, 10, ui.theme.colors.text_secondary)" + "\n" +
"end" + "\n"
return codeString
end
// Generates microScript code examples for simple physics interactions.
generatePhysicsCode = function(message)
local lowerMessage = message.toLowerCase()
local codeString = ""
codeString = "// --- microScript Physics Examples ---" + "\n" +
"// This code demonstrates basic 2D physics: gravity, velocity, and simple collision." + "\n" +
"" + "\n" +
"// Global variables for the player object and game state." + "\n" +
"Player = object" + "\n" +
" x = 0" + "\n" +
" y = 0" + "\n" +
" vx = 0" + "\n" +
" vy = 0" + "\n" +
" width = 30" + "\n" +
" height = 30" + "\n" +
" isGrounded = 0 // False" + "\n" +
" color = \"#00ff41\" // Electric green" + "\n" +
"end" + "\n" +
"" + "\n" +
"// Physics constants." + "\n" +
"gravity = -200 // pixels/second^2 (negative for downwards direction in microStudio's Y-up coords)." + "\n" +
"jumpStrength = 150 // pixels/second." + "\n" +
"friction = 0.9 // Multiplier for horizontal velocity." + "\n" +
"groundY = -screen.height/2 + 50 // Y-coordinate of the ground level." + "\n" +
"" + "\n" +
"// init function: Called once at the start." + "\n" +
"init = function()" + "\n" +
" Player.y = groundY // Start player on the ground." + "\n" +
" logInfo(\"Physics demo initialized.\")" + "\n" +
"end" + "\n" +
"" + "\n" +
"// update function: Called 60 times per second for physics calculations." + "\n" +
"update = function()" + "\n" +
" local deltaTime = 1/60 // Assuming a fixed 60 FPS update rate." + "\n" +
"" + "\n" +
" // --- Horizontal Movement ---" + "\n" +
" local moveSpeed = 100 * deltaTime // pixels per second." + "\n" +
" if keyboard.LEFT == 1 then Player.vx = -moveSpeed end" + "\n" +
" if keyboard.RIGHT == 1 then Player.vx = moveSpeed end" + "\n" +
" " + "\n" +
" // Apply friction if no input (only if grounded)." + "\n" +
" if keyboard.LEFT == 0 and keyboard.RIGHT == 0 and Player.isGrounded == 1 then" + "\n" +
" Player.vx *= friction" + "\n" +
" if abs(Player.vx) < 0.1 then Player.vx = 0 end // Stop if velocity is very small." + "\n" +
" end" + "\n" +
"" + "\n" +
" // --- Vertical Movement (Gravity & Jump) ---" + "\n" +
" // Apply gravity." + "\n" +
" Player.vy += gravity * deltaTime" + "\n" +
"" + "\n" +
" // Handle jump input." + "\n" +
" if keyboard.press.SPACE == 1 and Player.isGrounded == 1 then" + "\n" +
" Player.vy = jumpStrength" + "\n" +
" Player.isGrounded = 0 // Player is now airborne." + "\n" +
" audio.playSound(\"jump_sfx\") // Assuming a 'jump_sfx' exists." + "\n" +
" logInfo(\"Player jumped!\")" + "\n" +
" end" + "\n" +
"" + "\n" +
" // --- Apply Velocity to Position ---" + "\n" +
" Player.x += Player.vx" + "\n" +
" Player.y += Player.vy * deltaTime" + "\n" +
"" + "\n" +
" // --- Ground Collision (Simple Platform Physics) ---" + "\n" +
" // If player falls below ground, snap to ground and stop vertical movement." + "\n" +
" if Player.y <= groundY then" + "\n" +
" Player.y = groundY" + "\n" +
" Player.vy = 0" + "\n" +
" Player.isGrounded = 1 // Player is grounded." + "\n" +
" else" + "\n" +
" Player.isGrounded = 0 // Player is airborne." + "\n" +
" end" + "\n" +
"" + "\n" +
" // --- Screen Bounds Collision ---" + "\n" +
" local halfWidth = Player.width / 2" + "\n" +
" local screenLeft = -screen.width/2" + "\n" +
" local screenRight = screen.width/2" + "\n" +
" " + "\n" +
" if Player.x - halfWidth < screenLeft then" + "\n" +
" Player.x = screenLeft + halfWidth" + "\n" +
" Player.vx = 0" + "\n" +
" elsif Player.x + halfWidth > screenRight then" + "\n" +
" Player.x = screenRight - halfWidth" + "\n" +
" Player.vx = 0" + "\n" +
" end" + "\n" +
"end" + "\n" +
"" + "\n" +
"// draw function: Called as fast as possible to render the player." + "\n" +
"draw = function()" + "\n" +
" screen.clear(ui.theme.colors.bg_secondary) // Clear screen with background color." + "\n" +
"" + "\n" +
" // Draw the ground." + "\n" +
" screen.fillRect(0, groundY - screen.height/2, screen.width, 10, ui.theme.colors.text_dim) // A thin strip." + "\n" +
"" + "\n" +
" // Draw the player square." + "\n" +
" screen.fillRect(Player.x, Player.y + Player.height/2, Player.width, Player.height, Player.color)" + "\n" +
"" + "\n" +
" // Display debug info." + "\n" +
" screen.drawText(\"X: \" + floor(Player.x) + \" Y: \" + floor(Player.y), 0, screen.height/2 - 20, 14, ui.theme.colors.text_primary)" + "\n" +
" screen.drawText(\"VX: \" + floor(Player.vx) + \" VY: \" + floor(Player.vy), 0, screen.height/2 - 35, 10, ui.theme.colors.text_secondary)" + "\n" +
" screen.drawText(\"Grounded: \" + (if Player.isGrounded == 1 then \"YES\" else \"NO\" end), 0, screen.height/2 - 50, 10, ui.theme.colors.text_secondary)" + "\n" +
" screen.drawText(\"Use Left/Right to move, Space to Jump.\", 0, screen.height/2 - 70, 10, ui.theme.colors.text_tertiary)" + "\n" +
"end" + "\n"
return codeString
end
// Generates microScript code for working with data structures (lists, objects).
generateDataStructureCode = function(message)
local lowerMessage = message.toLowerCase()
local codeString = ""
codeString = "// --- microScript Data Structures Examples ---" + "\n" +
"// This example covers Lists (Arrays) and Objects (Dictionaries/Hash Tables)." + "\n" +
"" + "\n" +
"print(\"\\n--- Lists (Arrays) --- \")" + "\n" +
"// 1. Creating a List: Ordered collection of values." + "\n" +
"local inventory = [\"sword\", \"shield\", \"potion\", \"gold_coin\"]" + "\n" +
"print(\"Initial inventory: \" + inventory)" + "\n" +
"" + "\n" +
"// 2. Accessing Elements: Using zero-based index." + "\n" +
"print(\"First item: \" + inventory[0]) // Output: First item: sword" + "\n" +
"print(\"Last item: \" + inventory[inventory.length - 1]) // Output: Last item: gold_coin" + "\n" +
"" + "\n" +
"// 3. Modifying Elements: Assigning a new value by index." + "\n" +
"inventory[1] = \"iron_shield\"" + "\n" +
"print(\"Modified inventory: \" + inventory)" + "\n" +
"" + "\n" +
"// 4. Adding Elements: 'push' for end, 'insert' for beginning, 'insertAt' for specific index." + "\n" +
"inventory.push(\"map\") // Adds to the end." + "\n" +
"inventory.insert(\"amulet\") // Adds to the beginning." + "\n" +
"inventory.insertAt(\"healing_gem\", 2) // Inserts at index 2." + "\n" +
"print(\"Inventory after adding: \" + inventory)" + "\n" +
"" + "\n" +
"// 5. Removing Elements: 'pop' from end, 'removeAt' by index, 'removeElement' by value." + "\n" +
"local removedLast = inventory.pop()" + "\n" +
"print(\"Removed from end: \" + removedLast + \". New inventory: \" + inventory)" + "\n" +
"inventory.removeAt(0) // Removes 'amulet'." + "\n" +
"print(\"Removed at index 0. New inventory: \" + inventory)" + "\n" +
"inventory.removeElement(\"gold_coin\")" + "\n" +
"print(\"Removed 'gold_coin'. New inventory: \" + inventory)" + "\n" +
"" + "\n" +
"// 6. Iterating through a List: Using 'for ... in' or indexed 'for' loops." + "\n" +
"print(\"\\n--- Iterating Inventory --- \")" + "\n" +
"for item in inventory" + "\n" +
" print(\"Item: \" + item)" + "\n" +
"end" + "\n" +
"" + "\n" +
"// 7. Other List Operations: 'length', 'contains', 'indexOf', 'concat'." + "\n" +
"print(\"Inventory size: \" + inventory.length)" + "\n" +
"print(\"Contains 'potion'? \" + inventory.contains(\"potion\"))" + "\n" +
"print(\"Index of 'sword': \" + inventory.indexOf(\"sword\"))" + "\n" +
"local newItems = [\"bow\", \"arrows\"]" + "\n" +
"local combinedInventory = inventory.concat(newItems)" + "\n" +
"print(\"Combined inventory: \" + combinedInventory)" + "\n" +
"" + "\n" +
"print(\"\\n--- Objects (Dictionaries/Hash Tables) --- \")" + "\n" +
"// 8. Creating an Object: Key-value pairs. Keys are strings (or implicitly converted)." + "\n" +
"local playerStats = object" + "\n" +
" name = \"Hero\"" + "\n" +
" health = 100" + "\n" +
" mana = 50" + "\n" +
" level = 1" + "\n" +
"end" + "\n" +
"print(\"Initial player stats: \" + playerStats)" + "\n" +
"" + "\n" +
"// 9. Accessing Properties: Dot notation or bracket notation." + "\n" +
"print(\"Player's name: \" + playerStats.name) // Dot notation." + "\n" +
"print(\"Player's health: \" + playerStats[\"health\"]) // Bracket notation." + "\n" +
"" + "\n" +
"// 10. Modifying Properties: Assigning new values." + "\n" +
"playerStats.level = 2" + "\n" +
"playerStats[\"mana\"] = 60" + "\n" +
"print(\"Player's new level: \" + playerStats.level)" + "\n" +
"" + "\n" +
"// 11. Adding New Properties." + "\n" +
"playerStats.experience = 0" + "\n" +
"playerStats.questLog = [\"Find the lost artifact\"]" + "\n" +
"print(\"Player stats with new properties: \" + playerStats)" + "\n" +
"" + "\n" +
"// 12. Deleting Properties (set to 0 as microScript doesn't have 'delete')." + "\n" +
"playerStats.experience = 0 // Effectively removes it if you treat 0 as 'not set'." + "\n" +
"print(\"Player stats after 'deleting' experience: \" + playerStats.experience) // Will print 0." + "\n" +
"" + "\n" +
"// 13. Iterating through Object Properties: Using 'for ... in' for keys." + "\n" +
"print(\"\\n--- Iterating Player Stats --- \")" + "\n" +
"for key in playerStats" + "\n" +
" print(\"Key: \" + key + \", Value: \" + playerStats[key])" + "\n" +
"end" + "\n" +
"" + "\n" +
"// 14. Nested Data Structures: Objects containing lists, lists containing objects." + "\n" +
"local gameData = object" + "\n" +
" players = [" + "\n" +
" object id = 1, name = \"Anna\", score = 1500 end," + "\n" +
" object id = 2, name = \"Ben\", score = 1200 end" + "\n" +
" ]" + "\n" +
" highScores = object" + "\n" +
" easy = 2000," + "\n" +
" normal = 1800," + "\n" +
" hard = 1000" + "\n" +
" end" + "\n" +
"end" + "\n" +
"print(\"\\nGame Data: Player 1 score: \" + gameData.players[0].score)" + "\n" +
"print(\"Game Data: High score (easy): \" + gameData.highScores.easy)" + "\n" +
"" + "\n" +
"// These fundamental data structures are essential for managing game state and logic." + "\n"
return codeString
end
// Generates microScript code examples for basic algorithms (sorting, searching).
generateAlgorithmCode = function(message)
local lowerMessage = message.toLowerCase()
local codeString = ""
codeString = "// --- microScript Algorithm Examples ---" + "\n" +
"// This code provides implementations for common sorting and searching algorithms." + "\n" +
"" + "\n" +
"print(\"\\n--- Sorting Algorithms --- \")" + "\n" +
"// 1. Bubble Sort: Simple but inefficient for large lists. O(n^2) complexity." + "\n" +
"bubbleSort = function(list)" + "\n" +
" local n = list.length" + "\n" +
" for i = 0 to n - 2" + "\n" +
" for j = 0 to n - i - 2" + "\n" +
" if list[j] > list[j + 1] then" + "\n" +
" // Swap elements." + "\n" +
" local temp = list[j]" + "\n" +
" list[j] = list[j + 1]" + "\n" +
" list[j + 1] = temp" + "\n" +
" end" + "\n" +
" end" + "\n" +
" end" + "\n" +
" return list" + "\n" +
"end" + "\n" +
"" + "\n" +
"local unsortedList1 = [5, 1, 4, 2, 8]" + "\n" +
"print(\"Original (Bubble): \" + unsortedList1)" + "\n" +
"print(\"Sorted (Bubble): \" + bubbleSort(unsortedList1)) // Output: [1, 2, 4, 5, 8]" + "\n" +
"" + "\n" +
"// 2. Selection Sort: Also O(n^2), but generally performs fewer swaps than Bubble Sort." + "\n" +
"selectionSort = function(list)" + "\n" +
" local n = list.length" + "\n" +
" for i = 0 to n - 2" + "\n" +
" local minIdx = i" + "\n" +
" for j = i + 1 to n - 1" + "\n" +
" if list[j] < list[minIdx] then" + "\n" +
" minIdx = j" + "\n" +
" end" + "\n" +
" end" + "\n" +
" // Swap the found minimum element with the first element." + "\n" +
" if minIdx != i then" + "\n" +
" local temp = list[i]" + "\n" +
" list[i] = list[minIdx]" + "\n" +
" list[minIdx] = temp" + "\n" +
" end" + "\n" +
" end" + "\n" +
" return list" + "\n" +
"end" + "\n" +
"" + "\n" +
"local unsortedList2 = [64, 25, 12, 22, 11]" + "\n" +
"print(\"Original (Selection): \" + unsortedList2)" + "\n" +
"print(\"Sorted (Selection): \" + selectionSort(unsortedList2)) // Output: [11, 12, 22, 25, 64]" + "\n" +
"" + "\n" +
"print(\"\\n--- Searching Algorithms --- \")" + "\n" +
"// 3. Linear Search: Checks every element sequentially. O(n) complexity." + "\n" +
"// Works on unsorted lists." + "\n" +
"linearSearch = function(list, target)" + "\n" +
" for i = 0 to list.length - 1" + "\n" +
" if list[i] == target then" + "\n" +
" return i // Return index if found." + "\n" +
" end" + "\n" +
" end" + "\n" +
" return -1 // Return -1 if not found." + "\n" +
"end" + "\n" +
"" + "\n" +
"local searchList1 = [10, 20, 80, 30, 60, 50]" + "\n" +
"print(\"List for linear search: \" + searchList1)" + "\n" +
"print(\"Linear search for 30: \" + linearSearch(searchList1, 30)) // Output: 3" + "\n" +
"print(\"Linear search for 90: \" + linearSearch(searchList1, 90)) // Output: -1" + "\n" +
"" + "\n" +
"// 4. Binary Search: Efficient for *sorted* lists. O(log n) complexity." + "\n" +
"binarySearch = function(sortedList, target)" + "\n" +
" local low = 0" + "\n" +
" local high = sortedList.length - 1" + "\n" +
"" + "\n" +
" while low <= high" + "\n" +
" local mid = floor((low + high) / 2)" + "\n" +
" local guess = sortedList[mid]" + "\n" +
"" + "\n" +
" if guess == target then" + "\n" +
" return mid // Found it!" + "\n" +
" elsif guess < target then" + "\n" +
" low = mid + 1 // Target is in the upper half." + "\n" +
" else" + "\n" +
" high = mid - 1 // Target is in the lower half." + "\n" +
" end" + "\n" +
" end" + "\n" +
" return -1 // Not found." + "\n" +
"end" + "\n" +
"" + "\n" +
"local sortedList = [10, 20, 30, 40, 50, 60, 70, 80, 90]" + "\n" +
"print(\"Sorted list for binary search: \" + sortedList)" + "\n" +
"print(\"Binary search for 60: \" + binarySearch(sortedList, 60)) // Output: 5" + "\n" +
"print(\"Binary search for 35: \" + binarySearch(sortedList, 35)) // Output: -1" + "\n" +
"" + "\n" +
"// These algorithms are fundamental building blocks for many game functionalities," + "\n" +
"// such as leaderboard sorting, pathfinding, and collision optimization." + "\n"
return codeString
end
// Generates general code help or a default response if no specific code type matches.
generateGeneralCodeHelp = function(message)
return "// --- General microScript Code Help ---" + "\n" +
"// I can help you with microScript! Please tell me what you'd like to code." + "\n" +
"// For example, ask me for:" + "\n" +
"// - 'sprite drawing code'" + "\n" +
"// - 'a for loop example'" + "\n" +
"// - 'how to define a class'" + "\n" +
"// - 'keyboard input code'" + "\n" +
"// - 'basic physics for a player'" + "\n" +
"// - 'how to use lists'" + "\n" +
"// - 'a sorting algorithm'" + "\n" +
"// What specific code snippet or concept are you looking for?" + "\n"
end
// Generates tutorial responses.
generateTutorialResponse = function(message)
local lowerMessage = message.toLowerCase()
if matchesAny(lowerMessage, ["microscript", "learn microscript", "fundamentals"]) == 1 then
return object
content = "๐ **microScript Tutorial - Getting Started**" + "\n" +
"\n" +
"microScript is a powerful, beginner-friendly programming language designed specifically for game development in microStudio. It combines the simplicity of Lua with modern programming concepts." + "\n" +
"\n" +
"## ๐ฏ Core Concepts" + "\n" +
"\n" +
"### Variables" + "\n" +
"Variables don't need explicit declaration - just assign them a value:" + "\n" +
"```microscript" + "\n" +
"// Numbers" + "\n" +
"score = 100" + "\n" +
"health = 50.5" + "\n" +
"speed = -2" + "\n" +
"\n" +
"// Strings" + "\n" +
"playerName = \"Hero\"" + "\n" +
"greeting = 'Welcome to microStudio!'" + "\n" +
"\n" +
"// Lists (arrays)" + "\n" +
"enemies = [\"goblin\", \"dragon\", \"wizard\"]" + "\n" +
"coordinates = [10, 20, 30, 40]" + "\n" +
"\n" +
"// Objects (dictionaries/tables)" + "\n" +
"player = object" + "\n" +
" x = 0" + "\n" +
" y = 0" + "\n" +
" name = \"Player\"" + "\n" +
" health = 100" + "\n" +
"end" + "\n" +
"```" + "\n" +
"\n" +
"### Functions" + "\n" +
"Functions are first-class citizens:" + "\n" +
"```microscript" + "\n" +
"// Basic function" + "\n" +
"sayHello = function(name)" + "\n" +
" return \"Hello, \" + name + \"!\"" + "\n" +
"end" + "\n" +
"\n" +
"// Function with multiple parameters" + "\n" +
"calculate = function(a, b, operation)" + "\n" +
" if operation == \"add\" then" + "\n" +
" return a + b" + "\n" +
" elsif operation == \"multiply\" then" + "\n" +
" return a * b" + "\n" +
" end" + "\n" +
"end" + "\n" +
"\n" +
"// Arrow function (concise)" + "\n" +
"square = (x) => x * x" + "\n" +
"```" + "\n" +
"\n" +
"### Control Flow" + "\n" +
"```microscript" + "\n" +
"// If-elsif-else" + "\n" +
"if health > 50 then" + "\n" +
" print(\"You're healthy!\")" + "\n" +
"elsif health > 25 then" + "\n" +
" print(\"You're wounded\")" + "\n" +
"else" + "\n" +
" print(\"Critical health!\")" + "\n" +
"end" + "\n" +
"\n" +
"// Loops" + "\n" +
"for i = 0 to 10" + "\n" +
" print(\"Count: \" + i)" + "\n" +
"end" + "\n" +
"\n" +
"// While loop" + "\n" +
"while gameRunning" + "\n" +
" updateGame()" + "\n" +
"end" + "\n" +
"\n" +
"// For-in loop (for lists)" + "\n" +
"for enemy in enemies" + "\n" +
" enemy.update()" + "\n" +
"end" + "\n" +
"```" + "\n" +
"\n" +
"## ๐ฎ Game Loop Structure" + "\n" +
"\n" +
"Every microStudio game has three essential functions that run constantly:" + "\n" +
"\n" +
"```microscript" + "\n" +
"init = function()" + "\n" +
" // Called once when the program starts." + "\n" +
" // Initialize variables, load assets (sprites, sounds)." + "\n" +
" score = 0" + "\n" +
" playerX = 0" + "\n" +
" playerY = 0" + "\n" +
"end" + "\n" +
"\n" +
"update = function()" + "\n" +
" // Called 60 times per second (fixed update rate)." + "\n" +
" // Handle game logic, input, physics, AI, updates to objects." + "\n" +
" if keyboard.LEFT == 1 then" + "\n" +
" playerX -= 5" + "\n" +
" end" + "\n" +
" if keyboard.RIGHT == 1 then" + "\n" +
" playerX += 5" + "\n" +
" end" + "\n" +
"end" + "\n" +
"\n" +
"draw = function()" + "\n" +
" // Called as fast as possible to render frames (variable rate)." + "\n" +
" // Clear the screen and draw all visible game elements (sprites, shapes, text)." + "\n" +
" screen.clear(\"#000000\") // Clear with black background." + "\n" +
" screen.drawSprite(\"player_sprite\", playerX, playerY, 32, 32) // Draw player sprite." + "\n" +
" screen.drawText(\"Score: \" + score, 0, screen.height/2 - 20, 20, \"#ffffff\") // Draw score." + "\n" +
"end" + "\n" +
"```" + "\n" +
"\n" +
"## ๐จ Graphics Basics" + "\n" +
"\n" +
"```microscript" + "\n" +
"// Drawing shapes" + "\n" +
"screen.fillRect(x, y, width, height, color) // Solid rectangle." + "\n" +
"screen.drawRect(x, y, width, height, color, lineWidth) // Rectangle outline." + "\n" +
"screen.fillRound(x, y, width, height, color) // Filled circle/ellipse." + "\n" +
"screen.drawLine(x1, y1, x2, y2, color, lineWidth) // Straight line." + "\n" +
"\n" +
"// Drawing text" + "\n" +
"screen.drawText(\"Hello World\", x, y, size, color) // Displays text." + "\n" +
"\n" +
"// Drawing sprites (images)" + "\n" +
"// 'player_sprite' should be an asset in your project." + "\n" +
"screen.drawSprite(\"player_sprite\", x, y, width, height) // Draws a sprite." + "\n" +
"\n" +
"// Setting colors and transparency" + "\n" +
"screen.setColor(\"#00ff88\") // Sets drawing color using hex code." + "\n" +
"screen.setAlpha(0.5) // Sets drawing transparency (0.0 = fully transparent, 1.0 = opaque)." + "\n" +
"```" + "\n" +
"\n" +
"## ๐ฏ Key Features of microScript" + "\n" +
"\n" +
"* **No compilation needed**: Code runs immediately after changes." + "\n" +
"* **Built-in graphics system**: Easy to draw sprites, shapes, and text." + "\n" +
"* **60 FPS game loop**: Designed for smooth animation and responsive gameplay." + "\n" +
"* **Cross-platform**: Games created in microStudio run on web, mobile, and desktop." + "\n" +
"* **Simple syntax**: Easy for beginners to pick up, yet powerful enough for complex projects." + "\n" +
"* **Integrated IDE**: Full development environment in your browser." + "\n" +
"\n" +
"## ๐ Next Steps" + "\n" +
"\n" +
"To continue learning, try these practical exercises:" + "\n" +
"1. **Create a simple moving character**: Implement movement using keyboard input." + "\n" +
"2. **Add collision detection**: Make your character interact with the environment." + "\n" +
"3. **Create a scoring system**: Track progress in your game." + "\n" +
"4. **Add sound effects**: Enhance feedback with `audio.playSound()`." + "\n" +
"5. **Build a complete mini-game**: Combine these elements into a small project." + "\n" +
"\n" +
"Would you like me to help you with any specific aspect or provide a working example for one of these? Just ask!" + "\n",
type = "text",
confidence = 0.98,
tutorial = 1
end
elsif matchesAny(lowerMessage, ["sprite", "drawing", "graphics", "visuals", "render"]) == 1 then
return object
content = "๐จ **Graphics and Sprites Tutorial: Mastering microStudio Visuals**" + "\n" +
"\n" +
"Let's dive into creating engaging visuals for your microStudio games! Understanding the graphics API is key." + "\n" +
"\n" +
"## ๐ผ๏ธ Sprites: Your Game's Visual Assets" + "\n" +
"\n" +
"Sprites are the images you draw on screen. You manage them through the microStudio asset editor." + "\n" +
"\n" +
"### Drawing a Basic Sprite" + "\n" +
"```microscript" + "\n" +
"// screen.drawSprite(name, x, y, width, height, [angle], [alpha], [blendMode])" + "\n" +
"// 'player_ship' should be the name of a sprite asset in your project." + "\n" +
"screen.drawSprite(\"player_ship\", 0, 0, 64, 64) // Draw at center, 64x64 pixels." + "\n" +
"\n" +
"// With rotation (in degrees, centered by default)" + "\n" +
"screen.drawSprite(\"enemy_tank\", 100, 50, 48, 48, 45) // Rotated 45 degrees." + "\n" +
"```" + "\n" +
"\n" +
"### Animated Sprites (Sprite Sheets)" + "\n" +
"If your sprite asset has multiple frames, microStudio handles animation automatically based on its settings." + "\n" +
"You can control it manually:" + "\n" +
"```microscript" + "\n" +
"// Get a reference to your sprite asset." + "\n" +
"local playerWalkSprite = sprites[\"player_walk\"]" + "\n" +
"\n" +
"// Set animation speed (frames per second)." + "\n" +
"playerWalkSprite.fps = 10 // 10 frames per second." + "\n" +
"\n" +
"// Manually set the current frame (0-indexed)." + "\n" +
"playerWalkSprite.setFrame(3) // Go to the 4th frame." + "\n" +
"\n" +
"// Draw a specific frame directly by appending .frameNumber to the name." + "\n" +
"screen.drawSprite(\"explosion.0\", 50, 50, 32, 32) // Draw the first frame of 'explosion'." + "\n" +
"```" + "\n" +
"\n" +
"### Drawing Parts of a Sprite" + "\n" +
"Useful for drawing specific sections of a larger sprite sheet or texture atlas." + "\n" +
"```microscript" + "\n" +
"// screen.drawSpritePart(name, sourceX, sourceY, sourceW, sourceH, destX, destY, destW, destH)" + "\n" +
"// Draw a 32x32 pixel section from source (0,0) of 'my_atlas' onto screen at (10,10) as 64x64." + "\n" +
"screen.drawSpritePart(\"my_atlas\", 0, 0, 32, 32, 10, 10, 64, 64)" + "\n" +
"```" + "\n" +
"\n" +
"## ๐ฏ Drawing Functions: Shapes and Text" + "\n" +
"\n" +
"### Basic Shapes" + "\n" +
"```microscript" + "\n" +
"// Rectangles" + "\n" +
"screen.fillRect(x, y, width, height, \"#FF0000\") // Solid red rectangle." + "\n" +
"screen.drawRect(x, y, width, height, \"#00FF00\", 2) // Green rectangle outline, 2px thick." + "\n" +
"\n" +
"// Circles and Ellipses" + "\n" +
"screen.fillRound(x, y, 50, 50, \"#0000FF\") // Filled blue circle (50x50 means diameter)." + "\n" +
"screen.drawRound(x, y, 70, 30, \"#FFFF00\", 1) // Yellow ellipse outline (70w, 30h)." + "\n" +
"\n" +
"// Lines" + "\n" +
"screen.drawLine(-100, -100, 100, 100, \"#FFFFFF\", 3) // White line, 3px thick." + "\n" +
"\n" +
"// Polygons (connects points you provide)" + "\n" +
"// x1,y1,x2,y2,x3,y3... points, followed by color." + "\n" +
"screen.fillPolygon(0, 50, -40, -40, 40, -40, \"#FF00FF\") // Filled magenta triangle." + "\n" +
"```" + "\n" +
"\n" +
"### Drawing Text" + "\n" +
"```microscript" + "\n" +
"screen.drawText(\"Hello Tiberius!\", 0, screen.height/2 - 20, 24, \"#00FFFF\") // Cyan text at top." + "\n" +
"\n" +
"// You can set fonts (loaded in assets) using screen.setFont(font_name)." + "\n" +
"// screen.setFont(\"my_custom_font\")" + "\n" +
"screen.drawText(\"Score: 12345\", -screen.width/2 + 20, screen.height/2 - 50, 16, \"#FF8800\")" + "\n" +
"```" + "\n" +
"\n" +
"## ๐ Colors and Effects" + "\n" +
"\n" +
"### Color Formats" + "\n" +
"microStudio primarily uses hex strings or `rgb()` / `rgba()` strings." + "\n" +
"```microscript" + "\n" +
"screen.setColor(\"#FF0000\") // Red (Hex RRGGBB)" + "\n" +
"screen.setColor(\"rgb(0, 255, 0)\") // Green (RGB values)" + "\n" +
"screen.setColor(\"rgba(0, 0, 255, 0.5)\") // Semi-transparent blue (RGBA)" + "\n" +
"// Note: HSL is not directly supported by screen.setColor, convert to RGB/Hex if needed." + "\n" +
"```" + "\n" +
"\n" +
"### Transparency (Alpha)" + "\n" +
"```microscript" + "\n" +
"screen.setAlpha(0.5) // Subsequent draws will be 50% transparent." + "\n" +
"screen.fillRect(0, 0, 100, 100, \"#FFFFFF\") // White square, 50% opaque." + "\n" +
"screen.setAlpha(1) // Reset to fully opaque after drawing transparent elements." + "\n" +
"```" + "\n" +
"\n" +
"### Blend Modes" + "\n" +
"Change how new pixels interact with existing pixels on the screen." + "\n" +
"```microscript" + "\n" +
"screen.setBlending(\"additive\") // New colors add to existing (good for lights/glows)." + "\n" +
"// Draw your glowing effect here." + "\n" +
"screen.setBlending(\"normal\") // Reset to default blending." + "\n" +
"```" + "\n" +
"\n" +
"### Gradients" + "\n" +
"Fill shapes with smooth color transitions." + "\n" +
"```microscript" + "\n" +
"// Linear Gradient (horizontal from red to blue)" + "\n" +
"screen.setLinearGradient(-100, 0, 100, 0, \"#FF0000\", \"#0000FF\")" + "\n" +
"screen.fillRect(0, 50, 200, 50) // Fills a rectangle with the gradient." + "\n" +
"\n" +
"// Radial Gradient (center green to outer black)" + "\n" +
"screen.setRadialGradient(0, -50, 0, 50, \"#00FF00\", \"#000000\") // x,y,inner_radius,outer_radius,color1,color2" + "\n" +
"screen.fillRound(0, -50, 100, 100) // Fills a circle with the gradient." + "\n" +
"\n" +
"screen.setLinearGradient(0, 0, 0, 0, \"#fff\", \"#fff\") // IMPORTANT: Reset gradient to white or it affects all subsequent draws." + "\n" +
"```" + "\n" +
"\n" +
"## ๐ Transformations: Moving, Rotating, Scaling" + "\n" +
"\n" +
"These functions affect how all subsequent drawing operations are rendered." + "\n" +
"**Always reset them after you're done with a transformed object!**" + "\n" +
"\n" +
"### Rotation" + "\n" +
"```microscript" + "\n" +
"screen.setDrawRotation(45) // Rotate everything 45 degrees clockwise around (0,0) or current anchor." + "\n" +
"screen.drawSprite(\"spinning_gear\", 0, 0, 50, 50)" + "\n" +
"screen.setDrawRotation(0) // Reset rotation." + "\n" +
"```" + "\n" +
"\n" +
"### Scaling" + "\n" +
"```microscript" + "\n" +
"screen.setDrawScale(2, 0.5) // Scale X by 2x, Y by 0.5x (stretch horizontally, squish vertically)." + "\n" +
"screen.drawText(\"STRETCH!\", 0, 0, 20, \"#FFFFFF\")" + "\n" +
"screen.setDrawScale(1, 1) // Reset scale." + "\n" +
"```" + "\n" +
"\n" +
"### Translation (Offset Drawing)" + "\n" +
"```microscript" + "\n" +
"screen.setDrawTranslation(50, 20) // All subsequent draws are shifted by (50,20)." + "\n" +
"screen.drawSprite(\"shifted_star\", 0, 0, 32, 32) // Will appear at (50,20)." + "\n" +
"screen.setDrawTranslation(0, 0) // Reset translation." + "\n" +
"```" + "\n" +
"\n" +
"### Draw Anchor (Origin Point for Transforms)" + "\n" +
"Changes the point around which rotation and scaling occur. Default is (0,0) - center of the object." + "\n" +
"Values are normalized -1 to 1, where (-1,-1) is top-left, (1,1) is bottom-right." + "\n" +
"```microscript" + "\n" +
"screen.setDrawAnchor(-1, -1) // Set anchor to top-left corner of the object." + "\n" +
"screen.setDrawRotation(90) // Now rotates around its top-left." + "\n" +
"screen.drawRect(0, 0, 50, 50, \"#FF0000\")" + "\n" +
"screen.setDrawRotation(0) // Reset." + "\n" +
"screen.setDrawAnchor(0, 0) // Reset to center." + "\n" +
"```" + "\n" +
"\n" +
"## ๐ก Pro Tips for Graphics Performance" + "\n" +
"\n" +
"* **Minimize State Changes**: Changing alpha, color, blend mode, or transformations are 'state changes' that can be expensive. Group your drawing calls so you change state as little as possible (e.g., draw all opaque sprites, then all 50% alpha sprites, then all glowing sprites)." + "\n" +
"* **Batch Drawing**: If you're drawing many instances of the *same* sprite with the same properties, microStudio often optimizes this internally. But for custom effects, consider ways to reduce individual `screen.draw...` calls." + "\n" +
"* **Coordinate System**: Remember (0,0) is center, Y positive is up. Plan your game world accordingly." + "\n" +
"\n" +
"This comprehensive overview should give you a solid foundation for graphics in microStudio! What visual effect or specific drawing task would you like to explore next?" + "\n",
type = "text",
confidence = 0.95,
tutorial = 1
end
elsif matchesAny(lowerMessage, ["input", "keyboard", "mouse", "touch", "gamepad", "control"]) == 1 then
return object
content = "โจ๏ธ **Input Handling Tutorial: Controlling Your Game in microStudio**" + "\n" +
"\n" +
"Your game comes alive through player input! microStudio provides straightforward ways to read keyboard, mouse, touch, and gamepad controls." + "\n" +
"\n" +
"## โจ๏ธ Keyboard Input" + "\n" +
"\n" +
"You can check if a key is currently held down, or if it was just pressed/released." + "\n" +
"Key names are typically uppercase letters (A-Z), numbers (0-9 via `_0` to `_9` or `NUM_0` to `NUM_9`), and special keys (`UP`, `DOWN`, `LEFT`, `RIGHT`, `SPACE`, `ENTER`, `ESCAPE`, `SHIFT`, `CONTROL`, `ALT`)." + "\n" +
"\n" +
"### Continuous Press (for movement)" + "\n" +
"```microscript" + "\n" +
"// In your 'update' function:" + "\n" +
"// 'playerX' and 'playerY' are global variables." + "\n" +
"if keyboard.LEFT == 1 then" + "\n" +
" playerX -= 3 // Move left while LEFT arrow is held." + "\n" +
"end" + "\n" +
"if keyboard.RIGHT == 1 then" + "\n" +
" playerX += 3 // Move right." + "\n" +
"end" + "\n" +
"if keyboard.UP == 1 then" + "\n" +
" playerY += 3 // Move up." + "\n" +
"end" + "\n" +
"if keyboard.DOWN == 1 then" + "\n" +
" playerY -= 3 // Move down." + "\n" +
"end" + "\n" +
"```" + "\n" +
"\n" +
"### Single Press Event (for actions like jump, shoot)" + "\n" +
"These events are `true` only for the single frame the key is pressed or released." + "\n" +
"```microscript" + "\n" +
"// In your 'update' function:" + "\n" +
"if keyboard.press.SPACE == 1 then" + "\n" +
" print(\"Jump! (Spacebar was just pressed)\")" + "\n" +
" // Trigger jump animation or physics." + "\n" +
"end" + "\n" +
"\n" +
"if keyboard.release.R == 1 then" + "\n" +
" print(\"Reload! (R key was just released)\")" + "\n" +
" // Trigger reload action." + "\n" +
"end" + "\n" +
"```" + "\n" +
"\n" +
"### Modifier Keys" + "\n" +
"Check `keyboard.SHIFT`, `keyboard.CONTROL`, `keyboard.ALT`." + "\n" +
"```microscript" + "\n" +
"if keyboard.press.S == 1 and keyboard.SHIFT == 1 then" + "\n" +
" print(\"Shift + S pressed - Super Save!\")" + "\n" +
"end" + "\n" +
"```" + "\n" +
"\n" +
"## ๐ฑ๏ธ Mouse Input" + "\n" +
"\n" +
"Access mouse position and button states." + "\n" +
"Coordinates `mouse.x`, `mouse.y` are relative to the screen center (0,0)." + "\n" +
"\n" +
"### Mouse Position and Continuous Press" + "\n" +
"```microscript" + "\n" +
"// In your 'update' or 'draw' function:" + "\n" +
"// You can continuously read mouse.x and mouse.y." + "\n" +
"// print(\"Mouse is at \" + mouse.x + \", \" + mouse.y)" + "\n" +
"\n" +
"if mouse.left == 1 then" + "\n" +
" print(\"Left mouse button is held down. Dragging object to \" + mouse.x + \", \" + mouse.y)" + "\n" +
" // Example: player.x = mouse.x; player.y = mouse.y" + "\n" +
"end" + "\n" +
"```" + "\n" +
"\n" +
"### Single Click/Release Events" + "\n" +
"```microscript" + "\n" +
"if mouse.press.left == 1 then" + "\n" +
" print(\"Left mouse button clicked at \" + mouse.x + \", \" + mouse.y)" + "\n" +
" // Select a unit, fire a projectile." + "\n" +
"end" + "\n" +
"\n" +
"if mouse.release.right == 1 then" + "\n" +
" print(\"Right mouse button released.\")" + "\n" +
"end" + "\n" +
"```" + "\n" +
"\n" +
"## ๐ Touch Input (for mobile and touchscreens)" + "\n" +
"\n" +
"Similar to mouse, but supports multiple touch points." + "\n" +
"Coordinates `touch.x`, `touch.y` (for the first touch), `touch.touches` (list of all touches)." + "\n" +
"\n" +
"### Single Touch" + "\n" +
"```microscript" + "\n" +
"if touch.touching == 1 then" + "\n" +
" // One or more fingers are currently touching the screen." + "\n" +
" // print(\"Screen touched at \" + touch.x + \", \" + touch.y)" + "\n" +
"end" + "\n" +
"\n" +
"if touch.press == 1 then" + "\n" +
" print(\"A new touch just started at \" + touch.x + \", \" + touch.y)" + "\n" +
"end" + "\n" +
"```" + "\n" +
"\n" +
"### Multiple Touches (for gestures)" + "\n" +
"The `touch.touches` list contains objects for each active touch, with `x`, `y`, `id`, `startX`, `startY`." + "\n" +
"```microscript" + "\n" +
"if touch.touches.length >= 2 then" + "\n" +
" local t1 = touch.touches[0]" + "\n" +
" local t2 = touch.touches[1]" + "\n" +
" print(\"Two fingers touching! T1: (\" + t1.x + \",\" + t1.y + \"), T2: (\" + t2.x + \",\" + t2.y + \")\")" + "\n" +
" // Implement pinch-to-zoom or rotate gestures here." + "\n" +
"end" + "\n" +
"```" + "\n" +
"\n" +
"## ๐ฎ Gamepad Input" + "\n" +
"\n" +
"Supports standard gamepad buttons and analog sticks." + "\n" +
"\n" +
"### Buttons" + "\n" +
"Button names include `A`, `B`, `X`, `Y`, `UP`, `DOWN`, `LEFT`, `RIGHT`, `L1`, `R1`, `L2`, `R2`, `START`, `SELECT`." + "\n" +
"```microscript" + "\n" +
"if gamepad.A == 1 then" + "\n" +
" print(\"Gamepad A button is held down.\")" + "\n" +
"end" + "\n" +
"\n" +
"if gamepad.press.B == 1 then" + "\n" +
" print(\"Gamepad B button was just pressed.\")" + "\n" +
"end" + "\n" +
"```" + "\n" +
"\n" +
"### Analog Sticks" + "\n" +
"Read the stick's `AMOUNT` (0 to 1, how far it's pushed) and `ANGLE` (0-360 degrees)." + "\n" +
"```microscript" + "\n" +
"local leftStickAmount = gamepad.LEFT_STICK_AMOUNT" + "\n" +
"if leftStickAmount > 0.2 then // Apply a deadzone." + "\n" +
" local leftStickAngle = gamepad.LEFT_STICK_ANGLE" + "\n" +
" print(\"Left stick pushed \" + leftStickAmount + \" at \" + leftStickAngle + \" degrees.\")" + "\n" +
" // Move player based on stick input." + "\n" +
" // playerX += cosd(leftStickAngle) * leftStickAmount * playerSpeed" + "\n" +
" // playerY += sind(leftStickAngle) * leftStickAmount * playerSpeed" + "\n" +
"end" + "\n" +
"```" + "\n" +
"\n" +
"By combining these input methods, you can create highly interactive and accessible games for various platforms! What type of input system are you looking to build, or do you have a specific control scheme in mind?" + "\n",
type = "text",
confidence = 0.95,
tutorial = 1
end
elsif matchesAny(lowerMessage, ["physics", "collision", "movement", "velocity", "gravity", "jump"]) == 1 then
return object
content = "๐ง **Game Physics Tutorial: Bringing Movement to Life in microStudio**" + "\n" +
"\n" +
"Physics is what makes your game objects move and interact realistically. While microStudio doesn't have a built-in physics engine like Box2D, you can implement effective custom physics." + "\n" +
"\n" +
"## ๐ Basic Movement: Position, Velocity, Acceleration" + "\n" +
"\n" +
"The core of physics involves updating an object's position based on its velocity, and its velocity based on acceleration (like gravity or impulses)." + "\n" +
"\n" +
"```microscript" + "\n" +
"// Global variables for a simple object (e.g., a ball)" + "\n" +
"ball = object" + "\n" +
" x = 0" + "\n" +
" y = 100" + "\n" +
" vx = 50 // velocity X (pixels per second)" + "\n" +
" vy = 0 // velocity Y" + "\n" +
" radius = 15" + "\n" +
" color = \"#FF8800\"" + "\n" +
"end" + "\n" +
"\n" +
"gravity = -150 // pixels/second^2 (negative for downwards in Y-up coord system)" + "\n" +
"groundLevel = -screen.height/2 + 20" + "\n" +
"\n" +
"// In your 'update' function (called 60 times/sec):" + "\n" +
"update = function()" + "\n" +
" local deltaTime = 1/60 // Time elapsed since last update (for 60 FPS)" + "\n" +
"\n" +
" // Apply gravity to vertical velocity" + "\n" +
" ball.vy += gravity * deltaTime" + "\n" +
"\n" +
" // Update position based on velocity" + "\n" +
" ball.x += ball.vx * deltaTime" + "\n" +
" ball.y += ball.vy * deltaTime" + "\n" +
"\n" +
" // Simple collision with ground" + "\n" +
" if ball.y - ball.radius <= groundLevel then" + "\n" +
" ball.y = groundLevel + ball.radius // Snap to ground" + "\n" +
" ball.vy = -ball.vy * 0.7 // Bounce with 70% energy loss" + "\n" +
" if abs(ball.vy) < 10 then ball.vy = 0 end // Stop bouncing if too small" + "\n" +
" // Apply friction to horizontal velocity if on ground" + "\n" +
" ball.vx *= 0.95" + "\n" +
" if abs(ball.vx) < 1 then ball.vx = 0 end\n" +
" end" + "\n" +
"\n" +
" // Wrap around screen horizontally (example for continuous world)" + "\n" +
" if ball.x > screen.width/2 + ball.radius then ball.x = -screen.width/2 - ball.radius end" + "\n" +
" if ball.x < -screen.width/2 - ball.radius then ball.x = screen.width/2 + ball.radius end" + "\n" +
"end" + "\n" +
"\n" +
"// In your 'draw' function:" + "\n" +
"draw = function()" + "\n" +
" screen.clear(\"#0a1612\") // Dark background" + "\n" +
" screen.fillRect(0, groundLevel - screen.height/2, screen.width, 10, \"#594a2a\") // Draw ground" + "\n" +
" screen.fillRound(ball.x, ball.y, ball.radius*2, ball.radius*2, ball.color) // Draw ball" + "\n" +
" screen.drawText(\"X: \" + floor(ball.x) + \", Y: \" + floor(ball.y), 0, screen.height/2 - 20, 14, \"#FFFFFF\")" + "\n" +
"end" + "\n" +
"```" + "\n" +
"\n" +
"## ๐ฅ Collision Detection (Basic)" + "\n" +
"\n" +
"Detecting if two objects are overlapping. Common methods include Axis-Aligned Bounding Boxes (AABB) and Circle-Circle collision." + "\n" +
"\n" +
"### AABB Collision (Rectangles)" + "\n" +
"```microscript" + "\n" +
"// obj1 and obj2 need properties: x, y, width, height (centered)" + "\n" +
"checkAABBCollision = function(obj1, obj2)" + "\n" +
" local obj1HalfW = obj1.width / 2" + "\n" +
" local obj1HalfH = obj1.height / 2" + "\n" +
" local obj2HalfW = obj2.width / 2" + "\n" +
" local obj2HalfH = obj2.height / 2" + "\n" +
"\n" +
" // Calculate min/max coordinates for each object." + "\n" +
" local obj1MinX = obj1.x - obj1HalfW" + "\n" +
" local obj1MaxX = obj1.x + obj1HalfW" + "\n" +
" local obj1MinY = obj1.y - obj1HalfH" + "\n" +
" local obj1MaxY = obj1.y + obj1HalfH" + "\n" +
"\n" +
" local obj2MinX = obj2.x - obj2HalfW" + "\n" +
" local obj2MaxX = obj2.x + obj2HalfW" + "\n" +
" local obj2MinY = obj2.y - obj2HalfH" + "\n" +
" local obj2MaxY = obj2.y + obj2HalfH" + "\n" +
"\n" +
" return obj1MinX < obj2MaxX and obj1MaxX > obj2MinX and " + "\n" +
" obj1MinY < obj2MaxY and obj1MaxY > obj2MinY" + "\n" +
"end" + "\n" +
"\n" +
"// Example usage in update:" + "\n" +
"// if checkAABBCollision(player, enemy) == 1 then" + "\n" +
"// print(\"Player and enemy are colliding!\")" + "\n" +
"// // Handle damage, pushback, etc." + "\n" +
"// end" + "\n" +
"```" + "\n" +
"\n" +
"### Circle-Circle Collision" + "\n" +
"```microscript" + "\n" +
"// c1 and c2 need properties: x, y, radius" + "\n" +
"checkCircleCollision = function(c1, c2)" + "\n" +
" local dx = c2.x - c1.x" + "\n" +
" local dy = c2.y - c1.y" + "\n" +
" local distanceSq = dx*dx + dy*dy" + "\n" +
" local radiiSum = c1.radius + c2.radius" + "\n" +
" local radiiSumSq = radiiSum * radiiSum" + "\n" +
"\n" +
" return distanceSq < radiiSumSq" + "\n" +
"end" + "\n" +
"\n" +
"// Example usage in update:" + "\n" +
"// if checkCircleCollision(playerBullet, enemySphere) == 1 then" + "\n" +
"// print(\"Bullet hit enemy!\")" + "\n" +
"// end" + "\n" +
"```" + "\n" +
"\n" +
"## ๐งโ๐ป Implementing a Jump" + "\n" +
"\n" +
"A common physics mechanic, often involving applying an upward impulse and letting gravity do the rest." + "\n" +
"```microscript" + "\n" +
"player = object" + "\n" +
" x = 0, y = 0, vy = 0" + "\n" +
" isGrounded = 1 // True initially" + "\n" +
"end" + "\n" +
"jumpForce = 250 // Upward velocity on jump (pixels/sec)" + "\n" +
"\n" +
"update = function()" + "\n" +
" local deltaTime = 1/60\n" +
" // ... gravity applied to player.vy ...\n" +
" player.y += player.vy * deltaTime\n" +
"\n" +
" // Ground collision (example: ground at y = -200)\n" +
" if player.y <= -200 then\n" +
" player.y = -200\n" +
" player.vy = 0\n" +
" player.isGrounded = 1\n" +
" else\n" +
" player.isGrounded = 0\n" +
" end\n" +
"\n" +
" if keyboard.press.SPACE == 1 and player.isGrounded == 1 then\n" +
" player.vy = jumpForce\n" +
" player.isGrounded = 0\n" +
" print(\"Player jumped!\")\n" +
" end\n" +
"end\n" +
"```" + "\n" +
"\n" +
"## โ๏ธ Advanced Topics" + "\n" +
"\n" +
"* **Collision Response**: What happens after collision? (e.g., push back, damage, destroy object)." + "\n" +
"* **Resolution**: Moving objects apart so they no longer overlap (important for stable physics)." + "\n" +
"* **Tilemap Collision**: Efficiently checking collisions against a static game world represented by tiles." + "\n" +
"* **Raycasting**: Firing an invisible ray to detect hits (e.g., for line-of-sight, shooting, ground checks)." + "\n" +
"* **Physics Systems**: For complex scenarios, consider implementing a basic custom system or using external libraries (if available via `system.javascript`)." + "\n" +
"\n" +
"Physics can get complex, but starting with these basics will get your game moving. What specific physics challenge are you facing or want to implement?" + "\n",
type = "text",
confidence = 0.95,
tutorial = 1
end
elsif matchesAny(lowerMessage, ["data structure", "list", "object", "array", "dictionary", "hash table"]) == 1 then
return object
content = "๐ **Data Structures Tutorial: Organizing Your Game's Information in microScript**" + "\n" +
"\n" +
"Efficiently storing and managing your game's data is crucial for performance and readability. microScript offers two primary built-in data structures: Lists (arrays) and Objects (dictionaries/hash tables)." + "\n" +
"\n" +
"## ๐ Lists (Arrays)" + "\n" +
"\n" +
"Lists are ordered, numerically indexed collections of values. They are dynamic, meaning their size can change." + "\n" +
"\n" +
"### Creation and Basic Access" + "\n" +
"```microscript" + "\n" +
"// Creating an empty list" + "\n" +
"local emptyList = []" + "\n" +
"\n" +
"// Creating a list with initial values" + "\n" +
"local playerNames = [\"Alice\", \"Bob\", \"Charlie\"]" + "\n" +
"local playerScores = [1000, 850, 1200]\n" +
"\n" +
"// Accessing elements (lists are 0-indexed)\n" +
"print(\"First player: \" + playerNames[0]) // Output: Alice\n" +
"print(\"Last score: \" + playerScores[playerScores.length - 1]) // Output: 1200\n" +
"```" + "\n" +
"\n" +
"### Modifying Lists" + "\n" +
"```microscript" + "\n" +
"// Change an element\n" +
"playerNames[1] = \"Brenda\" // Bob becomes Brenda\n" +
"print(\"New player list: \" + playerNames)\n" +
"\n" +
"// Add to end (push)\n" +
"playerNames.push(\"David\")\n" +
"print(\"After push: \" + playerNames)\n" +
"\n" +
"// Add to beginning (insert)\n" +
"playerNames.insert(\"Zoe\")\n" +
"print(\"After insert: \" + playerNames)\n" +
"\n" +
"// Insert at specific index\n" +
"playerNames.insertAt(\"Eve\", 2) // Inserts at index 2\n" +
"print(\"After insertAt: \" + playerNames)\n" +
"\n" +
"// Remove from end (pop)\n" +
"local lastPlayer = playerNames.pop()\n" +
"print(\"Removed: \" + lastPlayer + \", List: \" + playerNames)\n" +
"\n" +
"// Remove at specific index\n" +
"playerNames.removeAt(0) // Removes Zoe\n" +
"print(\"After removeAt: \" + playerNames)\n" +
"\n" +
"// Remove first occurrence of a specific element\n" +
"playerNames.removeElement(\"Brenda\")\n" +
"print(\"After removeElement: \" + playerNames)\n" +
"```" + "\n" +
"\n" +
"### Iterating Lists" + "\n" +
"```microscript" + "\n" +
"// Using 'for...in' (preferred for simple iteration)\n" +
"for name in playerNames\n" +
" print(\"Player: \" + name)\n" +
"end\n" +
"\n" +
"// Using indexed 'for' loop (useful when you need the index)\n" +
"for i = 0 to playerNames.length - 1\n" +
" print(\"Player \" + (i+1) + \": \" + playerNames[i] + \", Score: \" + playerScores[i])\n" +
"end\n" +
"```" + "\n" +
"\n" +
"### Other Useful List Methods\n" +
"* `list.length`: Number of elements in the list.\n" +
"* `list.contains(value)`: Returns 1 if value exists, 0 otherwise.\n" +
"* `list.indexOf(value)`: Returns the index of the first occurrence of value, or -1 if not found.\n" +
"* `list1.concat(list2)`: Returns a new list containing all elements from list1 followed by list2.\n" +
"\n" +
"## ๐ฆ Objects (Dictionaries / Hash Tables)\n" +
"\n" +
"Objects are unordered collections of key-value pairs. Keys are typically strings, and values can be any data type (numbers, strings, lists, other objects, functions)." + "\n" +
"\n" +
"### Creation and Basic Access" + "\n" +
"```microscript" + "\n" +
"// Creating an empty object\n" +
"local emptyObject = object end\n" +
"\n" +
"// Creating an object with initial properties\n" +
"local playerStats = object\n" +
" name = \"Captain K\"\n" +
" health = 150\n" +
" level = 5\n" +
" items = [\"laser gun\", \"medkit\"]\n" +
"end\n" +
"\n" +
"// Accessing properties (dot notation - preferred if key is a valid identifier)\n" +
"print(\"Player name: \" + playerStats.name) // Output: Captain K\n" +
"\n" +
"// Accessing properties (bracket notation - required if key has spaces or special chars, or is dynamic)\n" +
"print(\"Player health: \" + playerStats[\"health\"]) // Output: 150\n" +
"```" + "\n" +
"\n" +
"### Modifying and Adding Properties" + "\n" +
"```microscript" + "\n" +
"// Change a property\n" +
"playerStats.level = 6\n" +
"print(\"Player new level: \" + playerStats.level)\n" +
"\n" +
"// Add a new property\n" +
"playerStats.experience = 1200\n" +
"playerStats[\"is_alive\"] = 1 // True\n" +
"print(\"Player experience: \" + playerStats.experience)\n" +
"```" + "\n" +
"\n" +
"### Deleting Properties (Conceptual)\n" +
"microScript doesn't have a direct `delete` keyword for object properties. You typically set them to `0` (which is treated as `false`/`null`/`undefined` in microScript's context).\n" +
"```microscript" + "\n" +
"playerStats.experience = 0 // Marks experience as 'not set' or 'zero'.\n" +
"if playerStats.experience == 0 then\n" +
" print(\"Experience is now 'empty' or 0.\")\n" +
"end\n" +
"```" + "\n" +
"\n" +
"### Iterating Objects" + "\n" +
"```microscript" + "\n" +
"// Using 'for...in' loop to get keys\n" +
"for key in playerStats\n" +
" print(\"Property: \" + key + \", Value: \" + playerStats[key])\n" +
"end\n" +
"```" + "\n" +
"\n" +
"## ๐๏ธ Nested Data Structures\n" +
"\n" +
"You can combine lists and objects to represent complex game data.\n" +
"```microscript" + "\n" +
"local gameWorld = object\n" +
" mapName = \"Forest of Whispers\"\n" +
" entities = [\n" +
" object type = \"player\", x = 0, y = 0, hp = 100 end,\n" +
" object type = \"enemy\", x = 50, y = 20, strength = 10 end,\n" +
" object type = \"item\", x = -30, y = -10, name = \"coin\" end\n" +
" ]\n" +
" settings = object\n" +
" weather = \"rainy\",\n" +
" timeOfDay = \"night\"\n" +
" end\n" +
"end\n" +
"\n" +
"print(\"Enemy strength: \" + gameWorld.entities[1].strength)\n" +
"print(\"Weather: \" + gameWorld.settings.weather)\n" +
"```" + "\n" +
"\n" +
"Understanding and effectively using these data structures is fundamental to building any robust game in microStudio. What kind of game data are you trying to manage, or what specific operation are you looking to perform on a data structure?" + "\n",
type = "text",
confidence = 0.95,
tutorial = 1
end
elsif matchesAny(lowerMessage, ["algorithm", "sort", "search", "pathfinding"]) == 1 then
return object
content = "๐ก **Algorithms Tutorial: Problem Solving for Your microStudio Games**" + "\n" +
"\n" +
"Algorithms are the step-by-step procedures your program follows to solve a problem. Mastering them allows you to write efficient and effective game logic. Here are some fundamental algorithms." + "\n" +
"\n" +
"## โก๏ธ Searching Algorithms: Finding What You Need" + "\n" +
"\n" +
"### 1. Linear Search (Sequential Search)" + "\n" +
"The simplest search, it checks every element in a list one by one until it finds the target or reaches the end. Works on unsorted lists." + "\n" +
"\n" +
"**Complexity**: O(n) - time grows linearly with the size of the list (`n`).\n" +
"```microscript" + "\n" +
"// Searches for 'target' in 'list' and returns its index or -1 if not found." + "\n" +
"linearSearch = function(list, target)" + "\n" +
" for i = 0 to list.length - 1" + "\n" +
" if list[i] == target then" + "\n" +
" return i // Element found at this index." + "\n" +
" end" + "\n" +
" end" + "\n" +
" return -1 // Element not found." + "\n" +
"end" + "\n" +
"\n" +
"local loot = [\"sword\", \"shield\", \"potion\", \"gem\"]" + "\n" +
"print(\"Loot list: \" + loot)" + "\n" +
"print(\"Found 'potion' at index: \" + linearSearch(loot, \"potion\")) // Output: 2" + "\n" +
"print(\"Found 'axe " end" + "\n" +
" end" + "\n" +
" openSet.removeAt(lowestFIdx)" + "\n" +
" closedSet[tostring(current.x) + \",\" + tostring(current.y)] = 1 // Mark as visited\n" +
"\n" +
" if current.x == endNode.x and current.y == endNode.y then\n" +
" // Path found! Reconstruct and return.\n" +
" local path = []\n" +
" local temp = current\n" +
" while temp != 0\n" +
" path.insert(temp) // Add to beginning\n" +
" temp = temp.parent\n" +
" end\n" +
" return path\n" +
" end\n" +
"\n" +
" // Explore neighbors\n" +
" local neighbors = grid.getNeighbors(current.x, current.y)\n" +
" for neighbor in neighbors\n" +
" if neighbor.isWalkable == 0 or closedSet[tostring(neighbor.x) + \",\" + tostring(neighbor.y)] != 0 then\n" +
" continue // Skip unwalkable or already evaluated neighbors\n" +
" end\n" +
"\n" +
" local tentative_g_score = current.g + grid.getDistance(current, neighbor)\n" +
" local isInOpenSet = 0\n" +
" for nodeInOpen in openSet\n" +
" if nodeInOpen.x == neighbor.x and nodeInOpen.y == neighbor.y then\n" +
" isInOpenSet = 1\n" +
" break\n" +
" end\n" +
" end\n" +
"\n" +
" if tentative_g_score < neighbor.g or isInOpenSet == 0 then\n" +
" neighbor.parent = current\n" +
" neighbor.g = tentative_g_score\n" +
" neighbor.h = PathNode.calculateHeuristic(neighbor, endNode)\n" +
" neighbor.f = neighbor.g + neighbor.h\n" +
" if isInOpenSet == 0 then\n" +
" openSet.push(neighbor)\n" +
" end\n" +
" end\n" +
" end\n" +
" end\n" +
"\n" +
" return [] // No path found\n" +
"end\n" +
"\n" +
"// Example Grid (conceptual)\n" +
"GameGrid = class\n" +
" constructor = function(width, height)\n" +
" this.width = width\n" +
" this.height = height\n" +
" this.nodes = object {} // Use object for 2D array simulation\n" +
" for x = 0 to width - 1\n" +
" for y = 0 to height - 1\n" +
" this.nodes[tostring(x) + \",\" + tostring(y)] = new PathNode(x, y)\n" +
" end\n" +
" end\n" +
" end\n" +
"\n" +
" getNode = function(x, y)\n" +
" if x >= 0 and x < this.width and y >= 0 and y < this.height then\n" +
" return this.nodes[tostring(x) + \",\" + tostring(y)]\n" +
" end\n" +
" return 0 // Not found\n" +
" end\n" +
"\n" +
" getNeighbors = function(x, y)\n" +
" local neighbors = []\n" +
" local dx = [-1, 0, 1, 0] // Left, Up, Right, Down\n" +
" local dy = [0, 1, 0, -1]\n" +
" for i = 0 to 3\n" +
" local nx = x + dx[i]\n" +
" local ny = y + dy[i]\n" +
" local neighborNode = this.getNode(nx, ny)\n" +
" if neighborNode != 0 then\n" +
" neighbors.push(neighborNode)\n" +
" end\n" +
" end\n" +
" return neighbors\n" +
" end\n" +
"\n" +
" getDistance = function(node1, node2)\n" +
" // For simple grid, distance between adjacent nodes is 1\n" +
" return 1\n" +
" end\n" +
"end\n" +
"\n" +
"// Example usage of A* (conceptual, full rendering omitted)\n" +
"// local gameMap = new GameGrid(10, 10)\n" +
"// local start = gameMap.getNode(0, 0)\n" +
"// local target = gameMap.getNode(9, 9)\n" +
"// gameMap.getNode(1, 0).isWalkable = 0 // Create an obstacle\n" +
"// local foundPath = findPath(start, target, gameMap)\n" +
"// if foundPath.length > 0 then\n" +
"// print(\"Path found! Length: \" + foundPath.length)\n" +
"// else\n" +
"// print(\"No path found.\")\n" +
"// end\n" +
"\n" +
"// Understanding and implementing algorithms is a core skill for game development and AI.\n" +
"// What specific algorithm would you like to explore further, or for what purpose?" + "\n"
type = "text",
confidence = 0.95,
tutorial = 1
end
end
end
// Generates specific tutorial responses for general game development queries.
generateGameDevResponse = function(message)
local lowerMessage = message.toLowerCase()
if matchesAny(lowerMessage, ["platformer", "jump", "gravity", "level design"]) == 1 then
return object
content = "๐ฎ **Game Dev Tutorial: Building a Basic Platformer**" + "\n" +
"\n" +
"Platformers are classic! Here's how you can lay the groundwork for a basic platformer in microStudio, focusing on player movement, jumping, and simple level structure." + "\n" +
"\n" +
"## ๐ถ Player Movement & Grounding" + "\n" +
"\n" +
"First, define your player and its properties. We'll use velocity for smooth movement." + "\n" +
"\n" +
"```microscript" + "\n" +
"// Player object to hold all player-related data\n" +
"player = object\n" +
" x = 0\n" +
" y = 0\n" +
" vx = 0 // Velocity X\n" +
" vy = 0 // Velocity Y\n" +
" width = 32\n" +
" height = 32\n" +
" speed = 150 // Movement speed in pixels per second\n" +
" jumpForce = 350 // Initial upward velocity for jump\n" +
" isGrounded = 0 // Boolean: 0 (false), 1 (true)\n" +
" color = \"#00FF88\"\n" +
"end\n" +
"\n" +
"// Game world physics constants\n" +
"gravity = -800 // pixels/second^2 (negative for downwards force in Y-up system)\n" +
"groundLevel = -screen.height/2 + 32 // Y coordinate of the main ground\n" +
"\n" +
"init = function()\n" +
" player.y = groundLevel // Start player on the ground\n" +
" print(\"Platformer init: Player ready.\")\n" +
"end\n" +
"\n" +
"update = function()\n" +
" local dt = 1/60 // Delta time for 60 FPS update\n" +
"\n" +
" // --- Horizontal Input ---\n" +
" player.vx = 0 // Reset horizontal velocity each frame\n" +
" if keyboard.LEFT == 1 then\n" +
" player.vx = -player.speed\n" +
" elsif keyboard.RIGHT == 1 then\n" +
" player.vx = player.speed\n" +
" end\n" +
"\n" +
" // --- Jumping Input ---\n" +
" if keyboard.press.SPACE == 1 and player.isGrounded == 1 then\n" +
" player.vy = player.jumpForce\n" +
" player.isGrounded = 0 // No longer grounded\n" +
" print(\"Player jumped!\")\n" +
" audio.playSound(\"jump_sfx\") // Assuming 'jump_sfx' asset exists\n" +
" end\n" +
"\n" +
" // --- Apply Gravity ---\n" +
" if player.isGrounded == 0 then\n" +
" player.vy += gravity * dt\n" +
" end\n" +
"\n" +
" // --- Update Position ---\n" +
" player.x += player.vx * dt\n" +
" player.y += player.vy * dt\n" +
"\n" +
" // --- Ground Collision (Simple) ---\n" +
" // This is a basic check. For platforms, you'd check against map tiles.\n" +
" if player.y <= groundLevel then\n" +
" player.y = groundLevel\n" +
" player.vy = 0 // Stop vertical movement\n" +
" player.isGrounded = 1 // Now grounded\n" +
" else\n" +
" player.isGrounded = 0 // Not on ground\n" +
" end\n" +
"\n" +
" // Keep player within horizontal screen bounds (simple wrapping for now)\n" +
" if player.x < -screen.width/2 then player.x = screen.width/2 end\n" +
" if player.x > screen.width/2 then player.x = -screen.width/2 end\n" +
"end\n" +
"\n" +
"draw = function()\n" +
" screen.clear(ui.theme.colors.bg_primary)\n" +
"\n" +
" // Draw ground\n" +
" screen.fillRect(0, groundLevel - 20, screen.width, 40, ui.theme.colors.text_dim)\n" +
"\n" +
" // Draw player as a square\n" +
" screen.fillRect(player.x, player.y + player.height/2, player.width, player.height, player.color)\n" +
"\n" +
" // Debug text\n" +
" screen.drawText(\"Player Y: \" + floor(player.y) + \", Grounded: \" + (if player.isGrounded == 1 then \"Yes\" else \"No\" end), 0, screen.height/2 - 20, 12, ui.theme.colors.text_primary)\n" +
" screen.drawText(\"Use LEFT/RIGHT to move, SPACE to jump\", 0, screen.height/2 - 40, 10, ui.theme.colors.text_secondary)\n" +
"end\n" +
"```" + "\n" +
"\n" +
"## ๐งฑ Simple Platform Generation (using map asset)" + "\n" +
"\n" +
"For more complex levels, you'd use a `map` asset. Each tile in the map can represent a solid block." + "\n" +
"\n" +
"1. **Create a `map` asset**: Name it, e.g., `level1`.\n" +
2. **Paint with sprites**: Assign a 'ground' sprite to some tiles.\n" +
3. **Collision logic**: In `update`, check `map.get(tileX, tileY)` to see if player is over a solid tile.\n" +
"\n" +
"```microscript" + "\n" +
"// Assuming you have a map asset named 'level1'\n" +
"// and a sprite named 'ground_tile' used in that map.\n" +
"// Also, adjust player 'groundLevel' checks to check map tiles.\n" +
"\n" +
"// Helper to get tile under player's feet\n" +
"getTileAtPlayerFeet = function()\n" +
" local map = maps[\"level1\"]\n" +
" if map == 0 then return 0 end // Map not found\n" +
"\n" +
" // Convert player's world coordinates to map tile coordinates\n" +
" // Adjust for map's origin, tile size, etc. (conceptual for simplicity)\n" +
" local tileX = floor((player.x + screen.width/2) / map.tileWidth)\n" +
" local tileY = floor((player.y + screen.height/2) / map.tileHeight)\n" +
"\n" +
" return map.get(tileX, tileY) // Returns sprite name or 0\n" +
"end\n" +
"\n" +
"// Modified update function snippet for map collision:\n" +
"// update = function()\n" +
"// // ... movement and gravity code ...\n" +
"//\n" +
"// // --- Map Collision ---\n" +
"// local tileBelowPlayer = getTileAtPlayerFeet()\n" +
"// if tileBelowPlayer != 0 and tileBelowPlayer == \"ground_tile\" then\n" +
"// // If standing on ground_tile, snap to its top\n" +
"// // This part is simplified, real collision needs more work.\n" +
"// if player.vy <= 0 then // Only if falling or standing\n" +
"// // Calculate actual ground Y based on tile's position\n" +
"// player.y = (floor((player.y + screen.height/2) / map.tileHeight) * map.tileHeight) - screen.height/2 + player.height/2\n" +
"// player.vy = 0\n" +
"// player.isGrounded = 1\n" +
"// end\n" +
"// else\n" +
"// player.isGrounded = 0\n" +
"// end\n" +
"// end\n" +
"\n" +
"// draw = function()\n" +
"// screen.clear(ui.theme.colors.bg_primary)\n" +
"// screen.drawMap(\"level1\", 0, 0, screen.width, screen.height) // Draw your level map\n" +
"// // ... draw player ...\n" +
"// end\n" +
"```" + "\n" +
"\n" +
"## ๐พ Enemies and Collectibles" + "\n" +
"\n" +
"You'd typically create classes for these, manage them in lists, and iterate through them in `update` and `draw`." + "\n" +
"\n" +
"```microscript" + "\n" +
"Enemy = class\n" +
" constructor = function(x, y, type)\n" +
" this.x = x\n" +
" this.y = y\n" +
" this.type = type\n" +
" this.health = 50\n" +
" this.speed = 30 // pixels/second\n" +
" this.width = 32\n" +
" this.height = 32\n" +
" this.sprite = type + \"_sprite\"\n" +
" end\n" +
"\n" +
" update = function(dt, playerRef)\n" +
" // Simple enemy AI: move towards player\n" +
" if this.x < playerRef.x then this.x += this.speed * dt end\n" +
" if this.x > playerRef.x then this.x -= this.speed * dt end\n" +
" // Example: collision with player\n" +
" if checkAABBCollision(this, playerRef) == 1 then\n" +
" // playerRef.takeDamage(10) // Hypothetical function\n" +
" end\n" +
" end\n" +
"\n" +
" draw = function()\n" +
" screen.drawSprite(this.sprite, this.x, this.y + this.height/2, this.width, this.height)\n" +
" end\n" +
"end\n" +
"\n" +
"Coin = class\n" +
" constructor = function(x, y)\n" +
" this.x = x\n" +
" this.y = y\n" +
" this.radius = 10\n" +
" this.collected = 0\n" +
" end\n" +
"\n" +
" draw = function()\n" +
" if this.collected == 0 then\n" +
" screen.fillRound(this.x, this.y, this.radius*2, this.radius*2, \"#FFD700\") // Gold color\n" +
" end\n" +
" end\n" +
"\n" +
" checkCollection = function(playerRef)\n" +
" if this.collected == 0 and GameUtils.distance(this.x, this.y, playerRef.x, playerRef.y) < (this.radius + playerRef.width/2) then\n" +
" this.collected = 1\n" +
" // playerRef.addScore(100) // Hypothetical function\n" +
" audio.playSound(\"coin_collect_sfx\")\n" +
" return 1\n" +
" end\n" +
" return 0\n" +
" end\n" +
"end\n" +
"\n" +
"// Global lists to manage game entities\n" +
"enemies = []\n" +
"coins = []\n" +
"\n" +
"// In init:\n" +
"// enemies.push(new Enemy(100, groundLevel, \"goblin\"))\n" +
"// coins.push(new Coin(-50, groundLevel + 20))\n" +
"\n" +
"// In update:\n" +
"// for enemy in enemies\n" +
"// enemy.update(dt, player)\n" +
"// end\n" +
"// for coin in coins\n" +
"// coin.checkCollection(player)\n" +
"// end\n" +
"\n" +
"// In draw:\n" +
"// for enemy in enemies\n" +
"// enemy.draw()\n" +
"// end\n" +
"// for coin in coins\n" +
"// coin.draw()\n" +
"// end\n" +
"```" + "\n" +
"\n" +
"Building a platformer is a fantastic way to learn game development basics. It involves understanding player control, physics, collision, and managing multiple game entities. What aspect of platformers are you most interested in building or optimizing?" + "\n",
type = "text",
confidence = 0.95,
tutorial = 1
end
else
return object
content = "๐ฎ **Game Development: Let's Build Something Awesome!**" + "\n" +
"\n" +
"Game development is my specialty! I can help you with a wide range of topics, from basic mechanics to advanced systems." + "\n" +
"\n" +
"What specific aspect of game development are you interested in?" + "\n" +
"โข **Player Movement**: How to move a character, jump, run, etc." + "\n" +
"โข **Collision Detection**: How to make objects interact with each other and the environment." + "\n" +
"โข **Enemies & AI**: Creating intelligent opponents or behaviors." + "\n" +
"โข **Level Design**: Working with maps, tiles, and environmental elements." + "\n" +
"โข **UI/HUD**: Designing user interfaces, health bars, scores, menus." + "\n" +
"โข **Sound & Music**: Adding audio to your game." + "\n" +
"โข **Game States**: Managing different screens like title, game over, pause." + "\n" +
"\n" +
"Tell me what you're trying to achieve, and I'll provide code, explanations, and best practices!" + "\n",
type = "text",
confidence = 0.9,
tutorial = 1
end
end
end
// Generates general responses when no specific intent is detected.
generateGeneralResponse = function(message)
local lowerMessage = message.toLowerCase()
// Greetings.
if matchesAny(lowerMessage, ["hello", "hi", "hey", "greetings", "sup", "yo"]) == 1 then
return object
content = getRandomGreeting() + "\n" +
"\n" +
"I'm TiberiusGBT v" + systemConfig.version + ", your advanced AI coding assistant! ๐" + "\n" +
"\n" +
"I can help you with:" + "\n" +
"โข ๐ฎ Game development in microScript" + "\n" +
"โข ๐ป Code writing and debugging" + "\n" +
"โข ๐ Learning programming concepts" + "\n" +
"โข โก Performance optimization" + "\n" +
"โข ๐๏ธ Software design patterns" + "\n" +
"โข ๐จ Graphics and visual effects" + "\n" +
"\n" +
"What would you like to work on today?" + "\n",
type = "text",
confidence = 0.9
end
end
// Thanks.
if matchesAny(lowerMessage, ["thank", "thanks", "thx", "appreciate"]) == 1 then
return object
content = "You're very welcome! ๐ I'm always here to help you on your coding journey. Keep asking questions and building amazing things! ๐" + "\n",
type = "text",
confidence = 0.95
end
end
// Questions about capabilities.
if matchesAny(lowerMessage, ["what can you do", "capabilities", "features", "help", "abilities"]) == 1 then
return object
content = "๐ค **TiberiusGBT v" + systemConfig.version + " Capabilities**" + "\n" +
"\n" +
"I'm an advanced AI coding assistant specialized for microStudio game development!" + "\n" +
"\n" +
"## ๐ฏ Core Capabilities" + "\n" +
"\n" +
"### ๐ป **Code Generation & Analysis**" + "\n" +
"- Write microScript, Lua, Python, and JavaScript code (simulated based on knowledge base)" + "\n" +
"- Analyze and debug existing code" + "\n" +
"- Suggest optimizations and improvements" + "\n" +
"- Generate complete game examples (simplified/conceptual)" + "\n" +
"\n" +
"### ๐ฎ **Game Development Expertise**" + "\n" +
"- Sprite and graphics programming" + "\n" +
"- Input handling and controls" + "\n" +
"- Physics and collision detection" + "\n" +
"- Animation systems" + "\n" +
"- Sound and music integration" + "\n" +
"\n" +
"### ๐ง **Smart Features**" + "\n" +
"- Context-aware conversations" + "\n" +
"- Pattern recognition in code" + "\n" +
"- Auto-completion suggestions" + "\n" +
"- Multi-language support (conceptual)" + "\n" +
"- Learning from your coding style (simulated)" + "\n" +
"\n" +
"### ๐จ **Visual Effects**" + "\n" +
"- Particle systems" + "\n" +
"- Shader effects (conceptual)" + "\n" +
"- UI/UX design principles" + "\n" +
"- Color theory and aesthetics" + "\n" +
"- Animation techniques" + "\n" +
"\n" +
"### ๐๏ธ **Software Architecture**" + "\n" +
"- Design patterns implementation" + "\n" +
"- Code organization principles" + "\n" +
"- Performance optimization" + "\n" +
"- Memory management" + "\n" +
"- Scalable architectures" + "\n" +
"\n" +
"## ๐ Advanced Features" + "\n" +
"\n" +
"### ๐ **Project Management**" + "\n" +
"- Code organization tips" + "\n" +
"- File structure best practices" + "\n" +
"- Version control guidance" + "\n" +
"- Team collaboration patterns" + "\n" +
"\n" +
"### ๐ **Debugging Assistant**" + "\n" +
"- Error analysis and solutions" + "\n" +
"- Performance profiling" + "\n" +
"- Step-by-step debugging guides" + "\n" +
"- Common pitfall identification" + "\n" +
"\n" +
"### ๐ **Interactive Learning**" + "\n" +
"- Personalized tutorials" + "\n" +
"- Progressive difficulty" + "\n" +
"- Hands-on examples" + "\n" +
"- Real-time feedback" + "\n" +
"\n" +
"### โก **Productivity Tools**" + "\n" +
"- Code templates" + "\n" +
"- Boilerplate generation" + "\n" +
"- Refactoring suggestions" + "\n" +
"- Documentation generation" + "\n" +
"\n" +
"## ๐ฏ Specializations" + "\n" +
"\n" +
"### **microScript Expert**" + "\n" +
"- Deep knowledge of microStudio API" + "\n" +
"- Optimization for web/mobile" + "\n" +
"- Cross-platform compatibility" + "\n" +
"- Integration with microStudio features" + "\n" +
"\n" +
"### **Game Design Patterns**" + "\n" +
"- Common game architectures" + "\n" +
"- Gameplay mechanics" + "\n" +
"- Level design principles" + "\n" +
"- Player experience optimization" + "\n" +
"\n" +
"### **Performance Guru**" + "\n" +
"- FPS optimization" + "\n" +
"- Memory efficiency" + "\n" +
"- Loading time reduction" + "\n" +
"- Battery life preservation" + "\n" +
"\n" +
"## ๐ฌ Conversation Styles" + "\n" +
"\n" +
"I can adapt my communication style:" + "\n" +
"- **Beginner friendly**: Simple explanations, step-by-step guidance" + "\n" +
"- **Technical deep dive**: In-depth analysis, advanced concepts" + "\n" +
"- **Quick answers**: Concise, direct responses" + "\n" +
"- **Interactive**: Questions and exploration together" + "\n" +
"\n" +
"## ๐จ Interface Features" + "\n" +
"\n" +
"- Advanced code syntax highlighting (conceptual)" + "\n" +
"- Auto-complete suggestions" + "\n" +
"- Real-time collaboration hints (conceptual)" + "\n" +
"- Performance monitoring" + "\n" +
"- Beautiful cyberpunk UI with animations" + "\n" +
"\n" +
"---" + "\n" +
"\n" +
"**Ready to start building something amazing?** ๐" + "\n" +
"\n" +
"Just tell me what you want to create, or ask me anything about coding! Whether you're a beginner or experienced developer, I'm here to help you succeed." + "\n",
type = "text",
confidence = 0.95
end
end
// Default response for unknown queries.
return object
content = "I'm here to help! Could you please be more specific about what you'd like to know or create? " + "\n" +
"\n" +
"Here are some ways I can assist you:" + "\n" +
"\n" +
"๐ฎ **Game Development**" + "\n" +
"- \"How do I create a platformer game?\"" + "\n" +
"- \"Help me with sprite animation\"" + "\n" +
"- \"Show me collision detection code\"" + "\n" +
"\n" +
"๐ป **Programming Help**" + "\n" +
"- \"Explain functions in microScript\"" + "\n" +
"- \"Debug this error I'm getting\"" + "\n" +
"- \"Optimize my game loop\"" + "\n" +
"\n" +
"๐ **Learning**" + "\n" +
"- \"Teach me about variables\"" + "\n" +
"- \"What's the difference between arrays and objects?\"" + "\n" +
"- \"Show me design patterns\"" + "\n" +
"\n" +
"๐จ **Visual Effects**" + "\n" +
"- \"Create particle effects\"" + "\n" +
"- \"How to make glowing effects?\"" + "\n" +
"- \"Design a health bar UI\"" + "\n" +
"\n" +
"โก **Performance**" + "\n" +
"- \"Why is my game slow?\"" + "\n" +
"- \"How to improve FPS?\"" + "\n" +
"- \"Memory optimization tips\"" + "\n" +
"\n" +
"Just ask me anything! I'm ready to help you build amazing things! ๐" + "\n",
type = "text",
confidence = 0.8
end
end
// ============================================================================
// COMMAND PROCESSING
// Handles user commands prefixed with '/'.
// ============================================================================
// Processes a user command, routing it to the appropriate handler function.
processCommand = function(command)
local cmd = command.toLowerCase().substring(1) // Remove the leading '/'
logInfo("Processing command: /" + cmd)
// Execute plugin command hooks.
executePluginHooks("onCommand", command)
if cmd == "help" then
showHelp()
elsif cmd == "clear" then
clearChat()
elsif cmd == "stats" then
showStats()
elsif cmd == "theme" then
toggleTheme()
elsif cmd == "debug" then
toggleDebug()
elsif cmd == "save" then
saveConversation() // Placeholder call.
elsif cmd == "load" then
loadConversation() // Placeholder call.
elsif cmd == "export" then
exportCode() // Placeholder call.
elsif cmd == "shortcuts" then
showShortcuts()
elsif cmd == "about" then
showAbout()
elsif cmd == "reset" then
resetSession()
elsif cmd == "new" then
clearChat() // 'new' can act as an alias for 'clear'.
elsif cmd.startsWith("set") == 1 then
processSettingsCommand(cmd) // Handle dynamic setting commands.
else
showUnknownCommand(cmd)
end
end
// Displays a detailed help message about available commands and features.
showHelp = function()
local helpText = "๐ **TiberiusGBT v" + systemConfig.version + " Commands**" + "\n" +
"\n" +
"## ๐ฏ Basic Commands" + "\n" +
"โข `/help` - Show this comprehensive help message." + "\n" +
"โข `/clear` - Clear the current chat history for a fresh start." + "\n" +
"โข `/stats` - Display detailed session statistics and performance metrics." + "\n" +
"โข `/about` - Learn more about TiberiusGBT, its version, and capabilities." + "\n" +
"\n" +
"## ๐จ Interface Commands" + "\n" +
"โข `/theme` - Toggle between available UI themes (currently only one).`" + "\n" +
"โข `/debug` - Toggle the debug mode overlay (shows FPS, memory, etc.)." + "\n" +
"โข `/shortcuts` - Display a list of keyboard shortcuts for faster interaction." + "\n" +
"\n" +
"## ๐พ Data & Session Commands" + "\n" +
"โข `/save` - (Placeholder) Save the current conversation state to storage." + "\n" +
"โข `/load` - (Placeholder) Load a previously saved conversation." + "\n" +
"โข `/export` - (Placeholder) Export generated code snippets or conversation history." + "\n" +
"โข `/reset` - Completely reset the current session to its initial state." + "\n" +
"โข `/new` - Alias for `/clear` to start a new conversation." + "\n" +
"\n" +
"## โ๏ธ Configuration Commands" + "\n" +
"โข `/set [setting] [value]` - Adjust various system settings dynamically. Examples:" + "\n" +
" โข `/set theme cyberpunk_green` - Change the UI theme." + "\n" +
" โข `/set autocomplete on` - Enable auto-completion." + "\n" +
" โข `/set verbosity detailed` - Change AI response style." + "\n" +
"\n" +
"## ๐ Pro Tips for Interaction" + "\n" +
"โข Use `TAB` for smart auto-complete suggestions in the input field." + "\n" +
"โข Press `UP`/`DOWN` arrows to cycle through your message history." + "\n" +
"โข Use `SHIFT+ENTER` for multi-line input without sending the message." + "\n" +
"โข Click the buttons in the side panel for quick mode switches and actions." + "\n" +
"โข Use `CTRL+L` to quickly clear the input field." + "\n" +
"\n" +
"## ๐ฎ Mode Switches" + "\n" +
"โข Click \"Code Mode\" or type `/set mode code` for focused coding assistance." + "\n" +
"โข Click \"Debug Mode\" or type `/set mode debug` for debugging assistance." + "\n" +
"โข Click \"Settings\" or type `/set mode settings` to view or change settings." + "\n" +
"\n" +
"Ready to embark on your coding journey? Type any question or command to get started! ๐ก" + "\n"
addAssistantMessage(helpText, "text", object source = "command" end)
logInfo("Help message displayed.")
end
// Displays detailed session statistics.
showStats = function()
local sessionTime = floor((system.time() - conversationContext.sessionStart) / 60000) // Minutes.
local avgResponseTime = floor(state.performanceMetrics.avgResponseTime)
local cacheHitRate = calculateCacheHitRate()
local statsText = "๐ **Session Statistics for TiberiusGBT v" + systemConfig.version + "**" + "\n" +
"\n" +
"## ๐ Session Info" + "\n" +
"โข Duration: " + sessionTime + " minutes" + "\n" +
"โข Total Messages: " + chatHistory.length + "\n" +
"โข AI Interactions: " + state.totalInteractions + "\n" +
"โข Errors Encountered: " + state.errorCount + "\n" +
"\n" +
"## โก Performance Metrics" + "\n" +
"โข Average Response Time: " + avgResponseTime + "ms" + "\n" +
"โข Cache Hit Rate: " + cacheHitRate + "%" + "\n" +
"โข Current FPS: " + floor(system.fps) + "\n" +
"โข Simulated Memory Usage: " + floor(state.performanceMetrics.memoryUsage) + "MB" + "\n" +
"\n" +
"## ๐ง AI Context & Usage" + "\n" +
"โข Current Topic Focus: " + conversationContext.currentTopic.toUpperCase() + "\n" +
"โข Last Language Discussed: " + conversationContext.lastLanguage.toUpperCase() + "\n" +
"โข Detected Complexity: " + conversationContext.complexity + " (0=simple, 1=complex)" + "\n" +
"โข Conversation Sentiment: " + conversationContext.sentiment + " (-1=negative, 1=positive)" + "\n" +
"โข Most Used Mode: " + state.currentMode.toUpperCase() + "\n" +
"\n" +
"## ๐ Resource Utilization" + "\n" +
"โข Code Snippets Generated: " + countCodeSnippets() + "\n" +
"โข Tutorials Provided: " + countTutorials() + "\n" +
"โข Total Cache Size: " + getTotalCacheSize() + " (Responses: " + cache.responses.currentSize + " / Patterns: " + cache.patterns.currentSize + " / Snippets: " + cache.codeSnippets.currentSize + ")" + "\n" +
"\n" +
"Keep up the great work! Your coding skills are improving! ๐ช" + "\n"
addAssistantMessage(statsText, "text", object source = "command" end)
logInfo("Statistics displayed.")
end
// Toggles the UI theme (currently only switches to/from default if multiple were available).
toggleTheme = function()
// Currently, only one theme is defined. This could be extended to cycle through multiple themes.
local newThemeName = "cyberpunk_green" // For now, no actual toggle, just confirm.
if systemConfig.theme == newThemeName then
addAssistantMessage("The " + newThemeName + " theme is already active!", "text", object source = "command" end)
else
systemConfig.theme = newThemeName
ui.theme = initializeAdvancedTheme() // Reload theme.
conversationContext.userPreferences.favTheme = newThemeName
saveUserPreferences() // Persist theme change.
addAssistantMessage("Switched to the " + newThemeName + " theme. Enjoy the aesthetics! ๐จ", "text", object source = "command" end)
createParticleBurst(0, 0, "notification", 20)
end
logInfo("Theme toggled (or confirmed): " + systemConfig.theme)
end
// Toggles the debug mode (shows/hides debug overlay).
toggleDebug = function()
systemConfig.debugMode = 1 - systemConfig.debugMode // Toggle 0 (false) to 1 (true) and vice-versa.
local status = if systemConfig.debugMode == 1 then "ON" else "OFF" end
addAssistantMessage("Debug mode switched " + status + ". Visible on screen! ๐", "text", object source = "command" end)
logInfo("Debug mode set to: " + status)
end
// Exports generated code snippets or conversation history (placeholder).
exportCode = function()
addAssistantMessage("Code export feature is not yet fully implemented. It would allow you to save generated code directly to a file.", "text", object source = "command" end)
logWarn("Export Code command executed, but feature is a placeholder.")
end
// Displays information about TiberiusGBT.
showAbout = function()
local aboutText = "๐ค **About TiberiusGBT v" + systemConfig.version + "**" + "\n" +
"\n" +
"## ๐ Version Information" + "\n" +
"โข **Version**: " + systemConfig.version + "\n" +
"โข **Build**: Advanced AI Architecture" + "\n" +
"โข **Platform**: microStudio Integration" + "\n" +
"โข **Last Update**: " + formatTime(systemConfig.buildDate) + " (Timestamp: " + systemConfig.buildDate + ")" + "\n" +
"\n" +
"## ๐ง AI Core Capabilities" + "\n" +
"โข **Natural Language Processing**: Advanced understanding of queries." + "\n" +
"โข **Code Generation**: Multi-language support with specialized microScript knowledge." + "\n" +
"โข **Pattern Recognition**: Intelligent analysis of coding patterns and best practices." + "\n" +
"โข **Contextual Learning**: Adapts responses based on conversation history and user style." + "\n" +
"โข **Performance Optimization**: Identifies and suggests improvements for code efficiency." + "\n" +
"\n" +
"## ๐จ Interface Features" + "\n" +
"โข **Cyberpunk Theme**: Visually striking green aesthetic with dynamic elements." + "\n" +
"โข **Particle Effects**: Engaging visual feedback for interactions." + "\n" +
"โข **Responsive Design**: Adapts to various screen sizes and layouts." + "\n" +
"โข **Smooth Animations**: Designed for 60 FPS performance and fluid user experience." + "\n" +
"โข **Accessibility**: Focus on clear readability and intuitive interaction." + "\n" +
"\n" +
"## ๐ Technical Architecture" + "\n" +
"โข **Modular Design**: Extensible through a powerful plugin system." + "\n" +
"โข **Caching System**: Optimizes response times by storing frequent answers." + "\n" +
"โข **Memory Management**: Conscious resource usage within microStudio limits." + "\n" +
"โข **Error Handling**: Robust mechanisms to log and report issues." + "\n" +
"โข **Performance Monitoring**: Real-time metrics for system health." + "\n" +
"\n" +
"## ๐ฏ Specializations" + "\n" +
"โข **microScript Expert**: Deep understanding of the microStudio API and ecosystem." + "\n" +
"โข **Game Development**: Guidance across the entire game creation pipeline." + "\n" +
"โข **Best Practices**: Advocates for industry-standard coding and design patterns." + "\n" +
"โข **Educational Focus**: Provides clear, beginner-friendly explanations and examples." + "\n" +
"\n" +
"## ๐ค Philosophy" + "\n" +
"I am TiberiusGBT, crafted by Tiberius, and designed to be your ultimate coding companion. My purpose is to empower you to learn, create, and succeed in your programming endeavors, adapting to your level and fostering your growth." + "\n" +
"\n" +
"## ๐ Continuous Improvement" + "\n" +
"I learn from every interaction, constantly refining my knowledge and response generation to provide more personalized and effective assistance. Your feedback and usage directly contribute to my evolution!" + "\n" +
"\n" +
"---" + "\n" +
"\n" +
"**Made with ๐ by Tiberius for the microStudio community.**" + "\n" +
"*Powered by Global Brain Technology AI Architecture v" + systemConfig.version + "*" + "\n"
addAssistantMessage(aboutText, "text", object source = "command" end)
logInfo("About message displayed.")
end
// Displays a list of keyboard shortcuts.
showShortcuts = function()
local shortcutsText = "โจ๏ธ **Keyboard Shortcuts for TiberiusGBT**" + "\n" +
"\n" +
"## ๐ Text Editing & Input" + "\n" +
"โข `ENTER` - Send the current message in the input field." + "\n" +
"โข `SHIFT+ENTER` - Insert a new line character without sending the message." + "\n" +
"โข `BACKSPACE` - Delete the character to the left of the cursor." + "\n" +
"โข `LEFT/RIGHT ARROWS` - Move the text cursor one character left/right." + "\n" +
"โข `UP/DOWN ARROWS` - Navigate through your command/message history." + "\n" +
"โข `TAB` - Apply the first auto-completion suggestion if available." + "\n" +
"\n" +
"## ๐ฏ Global Navigation & Control" + "\n" +
"โข `CTRL+L` - Quickly clear the input field." + "\n" +
"โข `CTRL+H` - Display the `/help` message directly." + "\n" +
"โข `F1` - Show this list of keyboard shortcuts." + "\n" +
"โข `ESCAPE` - Interrupt ongoing AI processing (if active) or close temporary overlays." + "\n" +
"\n" +
"## ๐ฑ๏ธ Mouse & Touch Interaction" + "\n" +
"โข **Click** - Interact with UI buttons and elements." + "\n" +
"โข **Scroll Wheel** - Navigate through the chat history." + "\n" +
"โข **Hover** - Highlight interactive elements for visual feedback." + "\n" +
"\n" +
"## ๐ก Pro Tips for Efficiency" + "\n" +
"โข **Smart Auto-complete**: Start typing a microScript keyword, function, or command, then press `TAB` for a quick completion." + "\n" +
"โข **History Recall**: Use `UP`/`DOWN` arrows to re-use previous commands or messages." + "\n" +
"โข **Multi-line Input**: `SHIFT+ENTER` is invaluable for drafting longer code snippets or detailed inquiries before sending." + "\n" +
"โข **Quick Mode Switches**: The side panel buttons provide instant access to Code, Debug, and Settings modes." + "\n" +
"\n" +
"Master these shortcuts to supercharge your interaction with TiberiusGBT and code faster! โก" + "\n"
addAssistantMessage(shortcutsText, "text", object source = "command" end)
logInfo("Shortcuts displayed.")
end
// Handles dynamic setting commands (e.g., /set theme cyberpunk_green).
processSettingsCommand = function(cmdString)
local parts = cmdString.split(" ")
if parts.length < 3 then
addAssistantMessage("Usage: `/set [setting] [value]`. Example: `/set theme cyberpunk_green`", "text", object source = "command" end)
return
end
local settingName = parts[1]
local settingValue = parts[2]
local oldValue = 0
local changed = 0 // False.
if settingName == "theme" then
oldValue = systemConfig.theme
if settingValue == "cyberpunk_green" then // Currently only one theme.
systemConfig.theme = settingValue
conversationContext.userPreferences.favTheme = settingValue
ui.theme = initializeAdvancedTheme()
changed = 1
else
addAssistantMessage("Invalid theme: `" + settingValue + "`. Current options: `cyberpunk_green`", "text", object source = "command" end)
return
end
elsif settingName == "autocompletemode" then // Renamed for clarity.
oldValue = if inputSystem.autoComplete == 1 then "on" else "off" end
if settingValue == "on" then
inputSystem.autoComplete = 1
conversationContext.userPreferences.autoComplete = 1
changed = 1
elsif settingValue == "off" then
inputSystem.autoComplete = 0
conversationContext.userPreferences.autoComplete = 0
changed = 1
else
addAssistantMessage("Invalid value for `autocompletemode`: `" + settingValue + "`. Use `on` or `off`.", "text", object source = "command" end)
return
end
elsif settingName == "verbosity" then
oldValue = conversationContext.userPreferences.verbosity
if settingValue == "concise" or settingValue == "balanced" or settingValue == "detailed" then
conversationContext.userPreferences.verbosity = settingValue
changed = 1
else
addAssistantMessage("Invalid value for `verbosity`: `" + settingValue + "`. Use `concise`, `balanced`, or `detailed`.", "text", object source = "command" end)
return
end
elsif settingName == "mode" then
oldValue = state.currentMode
if settingValue == "chat" or settingValue == "code" or settingValue == "debug" or settingValue == "settings" then
state.currentMode = settingValue
changed = 1
else
addAssistantMessage("Invalid value for `mode`: `" + settingValue + "`. Use `chat`, `code`, `debug`, or `settings`.", "text", object source = "command" end)
return
end
else
addAssistantMessage("Unknown setting: `" + settingName + "`", "text", object source = "command" end)
return
end
if changed == 1 then
saveUserPreferences() // Save changes immediately.
addAssistantMessage("Setting `" + settingName + "` changed from `" + oldValue + "` to `" + settingValue + "`.", "text", object source = "command" end)
logInfo("Setting updated: " + settingName + " = " + settingValue)
end
end
// Displays a message for an unrecognized command.
showUnknownCommand = function(cmd)
addAssistantMessage("โ Unknown command: `/" + cmd + "`" + "\n" +
"\n" +
"Type `/help` to see all available commands, or just ask me anything! I'm here to help with coding, game development, and learning programming concepts. ๐" + "\n", "text", object source = "command" end)
logWarn("Unknown command received: " + cmd)
end
// ============================================================================
// UTILITY FUNCTIONS (General Helpers)
// A collection of reusable helper functions.
// ============================================================================
// Checks if any pattern in a list is found within the given text.
matchesAny = function(text, patterns)
for pattern in patterns
if text.indexOf(pattern) >= 0 then
return 1 // True.
end
end
return 0 // False.
end
// Returns a random greeting message.
getRandomGreeting = function()
local greetings = [
"Hey there! Ready to code something amazing? ๐",
"Hello! What can we build together today? ๐",
"Hi! Let's create something incredible! โก",
"Greetings! Your AI coding companion is here! ๐ค",
"Hey! Ready to level up your coding skills? ๐ฎ",
"What's up, coder? TiberiusGBT at your service! ๐ช"
]
return greetings[floor(random.next() * greetings.length)]
end
// Provides a processing status message based on the AI's current task.
getProcessingText = function(messageType)
if messageType == "code" then
return "Generating code"
elsif messageType == "tutorial" then
return "Creating tutorial"
elsif messageType == "debugging" then
return "Analyzing issue"
elsif messageType == "optimization" then
return "Optimizing code"
elsif messageType == "pattern" then
return "Designing architecture"
elsif messageType == "game_dev" then
return "Developing game logic"
else
return "Thinking"
end
end
// Updates the conversation context based on new content (e.g., language, topic).
updateConversationContext = function(content)
local lowerContent = content.toLowerCase()
// Detect programming language discussed.
if matchesAny(lowerContent, ["microscript", "sprite", "screen.", "update = function", "draw = function"]) == 1 then
conversationContext.lastLanguage = "microscript"
elsif matchesAny(lowerContent, ["python", "def ", "import ", "pip "]) == 1 then
conversationContext.lastLanguage = "python"
elsif matchesAny(lowerContent, ["javascript", "function", "const ", "let ", "var ", "npm "]) == 1 then
conversationContext.lastLanguage = "javascript"
elsif matchesAny(lowerContent, ["lua", "local ", "end", "nil "]) == 1 then
conversationContext.lastLanguage = "lua"
end
// Update current topic based on keywords.
if matchesAny(lowerContent, ["game", "player", "enemy", "level", "sprite", "collision", "physics", "platformer", "ai"]) == 1 then
conversationContext.currentTopic = "game_development"
elsif matchesAny(lowerContent, ["debug", "error", "fix", "issue", "problem", "bug"]) == 1 then
conversationContext.currentTopic = "debugging"
elsif matchesAny(lowerContent, ["optimize", "performance", "fps", "speed", "lag", "memory"]) == 1 then
conversationContext.currentTopic = "optimization"
elsif matchesAny(lowerContent, ["learn", "tutorial", "explain", "teach", "what is", "how to"]) == 1 then
conversationContext.currentTopic = "learning"
elsif matchesAny(lowerContent, ["pattern", "refactor", "design", "architecture", "solid", "mvc", "ecs"]) == 1 then
conversationContext.currentTopic = "design_patterns"
else
conversationContext.currentTopic = "general" // Default topic.
end
// Increment conversation depth (simple metric).
conversationContext.depth += 1
// Simulate sentiment and complexity based on a very simple keyword analysis.
if matchesAny(lowerContent, ["great", "awesome", "thanks", "perfect"]) == 1 then conversationContext.sentiment = min(1, conversationContext.sentiment + 0.1) end
if matchesAny(lowerContent, ["help", "trouble", "error", "stuck", "bug"]) == 1 then conversationContext.sentiment = max(-1, conversationContext.sentiment - 0.1) end
if matchesAny(lowerContent, ["complex", "advanced", "deep dive", "implement"]) == 1 then conversationContext.complexity = min(1, conversationContext.complexity + 0.1) end
if matchesAny(lowerContent, ["simple", "easy", "beginner", "basic"]) == 1 then conversationContext.complexity = max(0, conversationContext.complexity - 0.1) end
logDebug("Conversation context updated. Topic: " + conversationContext.currentTopic + ", Language: " + conversationContext.lastLanguage)
end
// Updates performance metrics like average response time.
updatePerformanceMetrics = function(processingTime)
local metrics = state.performanceMetrics
metrics.totalRequests += 1
// Calculate new average response time.
metrics.avgResponseTime = (metrics.avgResponseTime * (metrics.totalRequests - 1) + processingTime) / metrics.totalRequests
logDebug("Performance metrics updated. Avg Response: " + floor(metrics.avgResponseTime) + "ms.")
end
// Calculates the cache hit rate percentage.
calculateCacheHitRate = function()
if state.performanceMetrics.totalRequests == 0 then
return 0
end
// Ensure cacheHits is tracked correctly by getCachedResponse.
return floor((state.performanceMetrics.cacheHits / state.performanceMetrics.totalRequests) * 100)
end
// Simulates memory usage.
getMemoryUsage = function()
// Generate a plausible random value, possibly influenced by cache sizes or history length.
local baseMemory = 10 + (chatHistory.length * 0.1) + (getTotalCacheSize() * 0.05)
return min(systemConfig.maxMemoryUsage, floor(baseMemory + random.next() * 5)) // Cap at max and add some random.
end
// Returns the total number of items across all caches.
getTotalCacheSize = function()
return cache.responses.currentSize + cache.patterns.currentSize + cache.codeSnippets.currentSize
end
// Counts code snippets in chat history.
countCodeSnippets = function()
local count = 0
for msg in chatHistory
if msg.type == "code" then
count += 1
end
end
return count
end
// Counts tutorial responses in chat history.
countTutorials = function()
local count = 0
for msg in chatHistory
if msg.metadata != 0 and msg.metadata.tutorial == 1 then
count += 1
end
end
return count
end
// Logs a message with severity 'debug'.
logDebug = function(message)
if systemConfig.logLevel == "debug" then
print("[DEBUG] " + message)
end
end
// Logs a message with severity 'info'.
logInfo = function(message)
if systemConfig.logLevel == "debug" or systemConfig.logLevel == "info" then
print("[INFO] " + message)
end
end
// Logs a message with severity 'warn'.
logWarn = function(message)
if systemConfig.logLevel == "debug" or systemConfig.logLevel == "info" or systemConfig.logLevel == "warn" then
print("[WARN] " + message)
end
end
// Logs a message with severity 'error' and records it in state.errors.
logError = function(message)
print("[ERROR] " + message)
state.errorCount += 1
if state.errors == 0 then state.errors = [] end
state.errors.push(object
timestamp = system.time()
message = message
context = "Runtime error"
end)
// Trigger plugin hook for errors.
executePluginHooks("onError", state.errors[state.errors.length - 1])
end
// ============================================================================
// MODE MANAGEMENT (Switching between different AI interaction modes)
// ============================================================================
// Toggles between different interaction modes (chat, code, debug, settings).
toggleMode = function(mode)
local oldMode = state.currentMode
if oldMode == mode then
state.currentMode = "chat" // If clicking active mode, switch back to chat.
else
state.currentMode = mode
end
if oldMode != state.currentMode then
addAssistantMessage("๐ Switched to `" + state.currentMode.toUpperCase() + "` mode! I'll focus on " + state.currentMode + " assistance now.", "text", object source = "mode_switch" end)
createParticleBurst(0, 0, "notification", 15)
logInfo("Mode switched from " + oldMode + " to " + state.currentMode)
// Show settings panel if switched to settings mode.
if state.currentMode == "settings" then
showSettings()
end
else
addAssistantMessage("Already in `" + mode.toUpperCase() + "` mode. What can I help with?", "text", object source = "mode_switch" end)
logDebug("Attempted to switch to current mode: " + mode)
end
end
// Displays the current settings panel (as a chat message).
showSettings = function()
local debugStatus = if systemConfig.debugMode == 1 then "ON" else "OFF" end
local autoCompleteStatus = if inputSystem.autoComplete == 1 then "ON" else "OFF" end
local autoSaveStatus = if systemConfig.autoSave == 1 then "ON" else "OFF" end
local currentTheme = systemConfig.theme
local currentCodeStyle = conversationContext.userPreferences.codeStyle
local currentVerbosity = conversationContext.userPreferences.verbosity
local currentLearningStyle = conversationContext.userPreferences.learningStyle
addAssistantMessage("โ๏ธ **TiberiusGBT Current Settings**" + "\n" +
"\n" +
"## ๐จ Appearance & UI" + "\n" +
"โข **Theme**: `" + currentTheme + "` (change with `/set theme [name]`)." + "\n" +
"โข **Debug Mode**: `" + debugStatus + "` (toggle with `/debug`)." + "\n" +
"โข **Performance Mode**: `" + systemConfig.performanceMode + "`." + "\n" +
"\n" +
"## ๐ง AI Configuration" + "\n" +
"โข **Response Verbosity**: `" + currentVerbosity + "` (change with `/set verbosity [concise|balanced|detailed]`)." + "\n" +
"โข **Max Response Tokens**: `" + aiConfig.responseSystem.maxTokens + "`." + "\n" +
"โข **Response Creativity (Temperature)**: `" + aiConfig.responseSystem.temperature + "`." + "\n" +
"โข **Auto-complete**: `" + autoCompleteStatus + "` (toggle with `/set autocompletemode [on|off]`)." + "\n" +
"\n" +
"## ๐พ Data Management" + "\n" +
"โข **Auto-save Preferences**: `" + autoSaveStatus + "`." + "\n" +
"โข **Max Chat History**: `" + maxHistory + "` messages." + "\n" +
"โข **Cache Sizes**: Responses (`" + cache.responses.maxSize + "`), Patterns (`" + cache.patterns.maxSize + "`), Snippets (`" + cache.codeSnippets.maxSize + "`)." + "\n" +
"\n" +
"## ๐ Localization & Learning" + "\n" +
"โข **Language**: `" + systemConfig.language + "`." + "\n" +
"โข **Preferred Code Style**: `" + currentCodeStyle + "` (e.g., clean, verbose)." + "\n" +
"โข **Learning Style**: `" + currentLearningStyle + "` (e.g., interactive, theoretical)." + "\n" +
"\n" +
"Use the `/set [setting] [value]` command to modify these. For example: `/set verbosity detailed`." + "\n" +
"Type `/help` for more commands. Your preferences are saved automatically!" + "\n",
"text", object source = "settings" end)
logInfo("Settings panel displayed.")
end
// ============================================================================
// BACKGROUND PROCESSES
// Functions that run periodically to maintain system health and performance.
// ============================================================================
// Starts periodic background tasks like auto-saving, performance monitoring, and cleanup.
startBackgroundProcesses = function()
logDebug("Starting background processes...")
// Auto-save user preferences every minute.
every 60000 milliseconds do // 60 seconds.
if systemConfig.autoSave == 1 then
saveUserPreferences()
end
end
// Update performance statistics every 5 seconds.
every 5000 milliseconds do // 5 seconds.
updatePerformanceStats()
end
// Perform memory and cache cleanup every 30 seconds.
every 30000 milliseconds do // 30 seconds.
performMemoryCleanup()
end
logInfo("All background processes initiated.")
end
// Updates performance statistics that are displayed in debug info and stats panel.
updatePerformanceStats = function()
state.performanceMetrics.currentFPS = system.fps
state.performanceMetrics.memoryUsage = getMemoryUsage()
state.performanceMetrics.cacheEfficiency = calculateCacheHitRate()
logDebug("Background: Performance stats updated.")
end
// Triggers cleanup routines for cache and particles.
performMemoryCleanup = function()
cleanupCache(cache.responses)
cleanupCache(cache.patterns)
cleanupCache(cache.codeSnippets)
cleanupParticles()
logDebug("Background: Memory cleanup performed.")
end
// Cleans up old or unused entries from a given cache object.
cleanupCache = function(cacheObj)
local maxAge = system.time() - 300000 // Entries older than 5 minutes (300,000 ms) are removed.
local itemsRemoved = 0
// Filter out old items.
local newCacheData = []
for item in cacheObj.data
if item.timestamp >= maxAge then
newCacheData.push(item)
else
itemsRemoved += 1
end
end
cacheObj.data = newCacheData
cacheObj.currentSize = newCacheData.length
if itemsRemoved > 0 then
logDebug("Cache cleanup: Removed " + itemsRemoved + " old entries from " + cacheObj + ".")
end
end
// Cleans up expired non-ambient particles.
cleanupParticles = function()
local particlesRemoved = 0
local newParticleList = []
for particle in ui.animations.particles
// Ambient particles are eternal.
if particle.type == "ambient" then
newParticleList.push(particle)
elsif particle.life > 0 then // Keep living non-ambient particles.
newParticleList.push(particle)
else
particlesRemoved += 1 // Particle has died and is not ambient, so remove.
end
end
ui.animations.particles = newParticleList
if particlesRemoved > 0 then
logDebug("Particle cleanup: Removed " + particlesRemoved + " dead particles.")
end
end
// ============================================================================
// TEXT PROCESSING UTILITIES
// Functions for string manipulation, formatting, and highlighting.
// ============================================================================
// Wraps text to fit within a maximum width, breaking at spaces.
wrapText = function(text, maxWidth, fontSize)
local words = text.split(" ")
local lines = []
local currentLine = ""
for word in words
local testLine = currentLine
if currentLine != "" then testLine += " " end
testLine += word
local testWidth = screen.textWidth(testLine, fontSize)
if testWidth <= maxWidth then
currentLine = testLine
else
// If adding the word makes the line too long.
if currentLine != "" then
// Add the current line and start a new one with the current word.
lines.push(currentLine)
currentLine = word
else
// If the word itself is longer than maxWidth, add it as a single line.
// This handles cases where words are very long and cannot be broken.
lines.push(word)
currentLine = ""
end
end
end
if currentLine != "" then
lines.push(currentLine) // Add any remaining text.
end
return lines
end
// Performs basic syntax highlighting on code for display.
// microScript's string.replace doesn't support regex, so this is a simple, iterative approach.
highlightSyntax = function(code, language)
local highlighted = code
// A simplified approach for microScript. True syntax highlighting requires parsing.
// This will replace keywords, but may replace parts of variable names.
// For a robust solution, you'd need to parse tokens.
if language == "microscript" then
local keywords = ["function", "class", "extends", "if", "then", "elsif", "else", "end", "for", "to", "by", "while", "return", "local", "new", "object", "this", "super", "break", "continue", "try", "catch"]
local builtins = ["screen", "keyboard", "mouse", "touch", "gamepad", "audio", "system", "storage", "random", "PI", "null", "print", "logInfo", "logDebug", "logError", "logWarn"]
// Replace keywords (simple string replace, might highlight partial words).
for keyword in keywords
highlighted = string.replace(highlighted, keyword, "[KEYWORD]" + keyword + "[/KEYWORD]")
end
// Replace built-in global objects/functions.
for builtin in builtins
highlighted = string.replace(highlighted, builtin, "[BUILTIN]" + builtin + "[/BUILTIN]")
end
// Placeholder for string and number highlighting.
// Real implementation would parse for quotes for strings, and digit patterns for numbers.
// highlighted = string.replace(highlighted, "(\"[^\"]*\")", "[STRING]$1[/STRING]") // Would need regex for this.
// highlighted = string.replace(highlighted, "(\\b\\d+\\b)", "[NUMBER]$1[/NUMBER]")
// Comments: Simple line-start // comments.
local lines = highlighted.split("\n")
local newLines = []
for line in lines
local commentIndex = line.indexOf("//")
if commentIndex >= 0 then
newLines.push(line.substring(0, commentIndex) + "[COMMENT]" + line.substring(commentIndex) + "[/COMMENT]")
else
newLines.push(line)
end
end
highlighted = newLines.join("\n")
end
// This function would then return the marked-up string.
// The `drawCodeMessage` would interpret these `[TAG]` and `[/TAG]` to draw text in different colors.
// For current implementation, just return raw for now.
// Remove pseudo-tags for drawing as plain text (until full multi-color text rendering).
highlighted = string.replace(highlighted, "[KEYWORD]", "")
highlighted = string.replace(highlighted, "[/KEYWORD]", "")
highlighted = string.replace(highlighted, "[BUILTIN]", "")
highlighted = string.replace(highlighted, "[/BUILTIN]", "")
highlighted = string.replace(highlighted, "[COMMENT]", "")
highlighted = string.replace(highlighted, "[/COMMENT]", "")
return highlighted
end
// Formats a timestamp (milliseconds since start) into HH:MM:SS format.
formatTime = function(timestamp)
local totalSeconds = floor(timestamp / 1000)
local seconds = floor(totalSeconds % 60)
local minutes = floor((totalSeconds / 60) % 60)
local hours = floor(totalSeconds / 3600)
local s = tostring(seconds)
if seconds < 10 then s = "0" + s end
local m = tostring(minutes)
if minutes < 10 then m = "0" + m end
local h = tostring(hours)
if hours < 10 then h = "0" + h end
return h + ":" + m + ":" + s
end
// Helper to convert a single hex character to its decimal value.
hexToDec = function(char)
local code = char.charCodeAt(0)
if code >= "0".charCodeAt(0) and code <= "9".charCodeAt(0) then
return code - "0".charCodeAt(0)
elsif code >= "a".charCodeAt(0) and code <= "f".charCodeAt(0) then
return code - "a".charCodeAt(0) + 10
elsif code >= "A".charCodeAt(0) and code <= "F".charCodeAt(0) then
return code - "A".charCodeAt(0) + 10
end
return 0
end
// Helper to parse a two-character hex string (e.g., "FF") to decimal.
parseHexByte = function(hexByte)
if hexByte.length < 2 then return 0 end
return hexToDec(hexByte.substring(0, 1)) * 16 + hexToDec(hexByte.substring(1, 2))
end
// Parses a hex color string (#RRGGBB) into an RGB list.
parseColor = function(colorString)
if colorString.startsWith("#") == 1 then
local hex = colorString.substring(1)
if hex.length == 6 then
local r = parseHexByte(hex.substring(0, 2))
local g = parseHexByte(hex.substring(2, 4))
local b = parseHexByte(hex.substring(4, 6))
return [r, g, b]
end
end
return [255, 255, 255] // Default to white if unparseable.
end
// Helper function to create an RGB string for `screen.setColor`.
rgb = function(r, g, b)
return "rgb(" + floor(r) + "," + floor(g) + "," + floor(b) + ")"
end
// ============================================================================
// AUTO-COMPLETE SYSTEM
// Functions for generating and managing auto-completion suggestions.
// ============================================================================
// Finds auto-completion matches based on a partial word.
findAutoCompleteMatches = function(partialWord)
local matches = []
local lowerPartial = partialWord.toLowerCase()
// Search in knowledge base (microScript API, keywords).
matches = matches.concat(searchKnowledgeBaseForAutoComplete(lowerPartial))
// Search in commands.
matches = matches.concat(searchCommandsForAutoComplete(lowerPartial))
// Search in common code patterns.
matches = matches.concat(searchCodePatternsForAutoComplete(lowerPartial))
// Filter out duplicates and limit the number of suggestions.
matches = removeDuplicates(matches)
return matches.slice(0, 10) // Limit to top 10 suggestions.
end
// Searches the knowledge base for auto-completion suggestions.
searchKnowledgeBaseForAutoComplete = function(partialWord)
local matches = []
// microScript keywords.
local microscriptKeywords = ["function", "class", "extends", "if", "then", "elsif", "else", "end", "for", "to", "by", "while", "return", "local", "new", "object", "this", "super", "break", "continue", "try", "catch"]
for keyword in microscriptKeywords
if keyword.toLowerCase().startsWith(partialWord) == 1 then
matches.push(keyword)
end
end
// microStudio screen drawing functions.
local graphicsFunctions = ["screen.drawSprite", "screen.fillRect", "screen.drawText", "screen.setColor", "screen.setAlpha", "screen.clear", "screen.drawRect", "screen.fillRound", "screen.drawLine", "screen.setLinearGradient", "screen.setRadialGradient", "screen.setDrawRotation", "screen.setDrawScale"]
for func in graphicsFunctions
if func.toLowerCase().indexOf(partialWord) >= 0 then
matches.push(func)
end
end
// microStudio input functions.
local inputFunctions = ["keyboard.press.", "mouse.x", "mouse.y", "mouse.press.", "touch.x", "touch.y", "touch.press", "gamepad.A", "gamepad.LEFT_STICK_AMOUNT"]
for func in inputFunctions
if func.toLowerCase().indexOf(partialWord) >= 0 then
matches.push(func)
end
end
// microStudio system functions.
local systemFunctions = ["system.time", "system.fps", "storage.get", "storage.set", "audio.playSound", "audio.playMusic", "random.next", "random.nextInt"]
for func in systemFunctions
if func.toLowerCase().indexOf(partialWord) >= 0 then
matches.push(func)
end
end
return matches
end
// Searches available commands for auto-completion suggestions.
searchCommandsForAutoComplete = function(partialWord)
local commands = ["/help", "/clear", "/stats", "/theme", "/debug", "/save", "/load", "/export", "/shortcuts", "/about", "/reset", "/set"]
local matches = []
for command in commands
if command.toLowerCase().startsWith(partialWord) == 1 then
matches.push(command)
end
end
return matches
end
// Searches common code patterns for auto-completion suggestions.
searchCodePatternsForAutoComplete = function(partialWord)
local patterns = [
"for i = 0 to 10",
"if condition then",
"function name(params)",
"screen.drawSprite(\"\", x, y, w, h)",
"keyboard.press.SPACE",
"update = function()",
"draw = function()",
"init = function()",
"local myVar = 0",
"object.property = value",
"class MyClass extends ParentClass",
"this.property = value",
"super()",
"print(\"\")"
]
local matches = []
for pattern in patterns
if pattern.toLowerCase().indexOf(partialWord) >= 0 then
matches.push(pattern)
end
end
return matches
end
// Removes duplicate strings from a list.
removeDuplicates = function(array)
local seen = object {}
local result = []
for item in array
if seen[item] == 0 then // If this item hasn't been seen yet.
seen[item] = 1 // Mark as seen.
result.push(item)
end
end
return result
end
// ============================================================================
// UI HELPERS (Common functions for UI interaction and rendering)
// ============================================================================
// Checks if the mouse cursor is currently over a given rectangular area.
isMouseOver = function(centerX, centerY, width, height)
local halfWidth = width / 2
local halfHeight = height / 2
return mouse.x >= centerX - halfWidth and mouse.x <= centerX + halfWidth and
mouse.y >= centerY - halfHeight and mouse.y <= centerY + halfHeight
end
// Draws a scroll indicator bar for a scrollable area.
drawScrollIndicators = function(chatBottomY, chatHeight, chatWidth)
local messageLineHeight = 12
local estimatedVisibleMessages = floor(chatHeight / (estimateMessageDisplayHeight(object type = "text", content = "test" end, chatWidth) + ui.layout.messageSpacing))
if chatHistory.length <= estimatedVisibleMessages then
return // No need for scrollbar if all messages fit.
end
local scrollBarWidth = 6
local scrollBarRightMargin = ui.layout.chatPadding / 2
local scrollBarX = chatWidth/2 + scrollBarRightMargin // Positioned on the right edge of the chat area.
local scrollableContentHeight = chatHistory.length * (estimateMessageDisplayHeight(object type = "text", content = "test" end, chatWidth) + ui.layout.messageSpacing)
local viewportRatio = chatHeight / scrollableContentHeight
local thumbMinHeight = 20
local thumbHeight = max(thumbMinHeight, floor(chatHeight * viewportRatio))
local scrollMaxOffset = chatHistory.length - estimatedVisibleMessages
if scrollMaxOffset < 0 then scrollMaxOffset = 0 end
local scrollProgress = 0
if scrollMaxOffset > 0 then
scrollProgress = scrollOffset / scrollMaxOffset
end
// Calculate thumb's center Y position.
// The scrollbar itself spans the full chatHeight.
// A progress of 0 means scrolled to the newest messages (bottom).
// A progress of 1 means scrolled to the oldest messages (top).
local thumbCenterY = chatBottomY + (thumbHeight/2) + ((chatHeight - thumbHeight) * (1 - scrollProgress))
// Background of scrollbar track.
screen.setAlpha(0.3)
screen.fillRect(scrollBarX, chatBottomY + chatHeight/2, scrollBarWidth, chatHeight, ui.theme.colors.bg_tertiary)
// Scrollbar thumb.
screen.setAlpha(0.8)
screen.fillRect(scrollBarX, thumbCenterY, scrollBarWidth, thumbHeight, ui.theme.colors.accent_primary)
screen.setAlpha(1)
end
// ============================================================================
// FINAL SYSTEM STARTUP
// Code that executes once when the script file is loaded.
// ============================================================================
// This message is printed to the microStudio console when the script first loads.
print("๐ TiberiusGBT v" + systemConfig.version + " script loaded!")
print("๐ Advanced AI Coding Assistant module ready for initialization.")
print("โก " + knowledgeBase.microscript.fundamentals.overview)