Ruin 是一个专为自动化、游戏开发和AI应用设计的现代脚本语言。提供强类型系统、完整的输入控制、计算机视觉、GPU加速和AI集成能力。
- 🎯 强类型系统 - 11种类型,泛型支持,编译时类型检查
- ⌨️ 全局输入控制 - 实时轮询 + 模拟输入,支持自动化操作
- 🔍 计算机视觉 - 集成 OpenCV,100+ CV函数(图像处理、DNN、人脸检测)
- 🤖 AI 集成 - Llama.cpp 支持,本地 LLM 推理
- 🎮 游戏开发 - GUI系统、输入系统、Canvas绘图
- 🚀 GPU 加速 - 34个 GPU 函数,支持矩阵运算
- ⚡ 异步编程 - ruin function 关键字,await 语法,future 类型
- 🌐 网络功能 - HTTP/HTTPS 客户端,JSON 支持
- 📸 屏幕捕获 - 跨平台截图(DXGI/X11)
- 📦 28个内置模块 - 开箱即用的标准库
// 必须显式声明类型
let number age = 25;
let string name = "Alice";
let boolean isActive = true;
let array<number> scores = [90, 85, 88];
let map<string, number> ages = {"Alice": 25, "Bob": 30};
import input from "input";
// 实时查询键盘鼠标状态(不需要事件监听)
if (input.isKeyDown("A")) {
console.log("A 键被按下");
}
let object mousePos = input.getMousePos();
console.log("鼠标位置: ", mousePos.x.toString(), ", ", mousePos.y.toString());
// 模拟键盘鼠标输入(自动化操作)
input.moveMouse(500, 300); // 移动鼠标
input.mouseClick(); // 左键单击
input.typeText("Hello World!"); // 输入文本(支持中文)
input.pressKey(input.KEY_ENTER); // 按回车
// 反作弊随机延迟(避免被检测为脚本)
input.setDelayRange(50, 150); // 设置随机延迟范围
input.pressKey("E"); // 使用随机延迟
// 组合键
input.pressKeyCombination(input.KEY_CTRL, 65); // Ctrl+A
import gui from "gui";
import director from "director";
// 创建窗口
let window win = gui.createWindow({
width: 800,
height: 600,
title: "我的应用"
});
// 创建组件
let label title = gui.createLabel("欢迎使用 Ruin", {
fontSize: 32
});
let button btn = gui.createButton("点击我", {
width: 150,
height: 50
});
// 添加事件
btn.on("click", () => {
console.log("按钮被点击!");
});
// 添加到场景
director.getScene().canvas.addChild(title);
director.getScene().canvas.addChild(btn);
win.show();
import llama from "llama";
import console from "console";
// 加载模型(GPU 配置)
let object model = llama.loadModel("models/TinyLlama-1.1B-Chat-v1.0.Q8_0.gguf", {
nGpuLayers: 0 // 0=CPU, 22=全GPU (TinyLlama 22层)
});
// 不同模型的层数配置:
// - TinyLlama 1.1B: 22 层 (nGpuLayers: 22)
// - Llama 2 7B: 32 层 (nGpuLayers: 32)
// - Llama 2 13B: 40 层 (nGpuLayers: 40)
let object ctx = llama.createContext(model, {
nCtx: 2048
});
let object sampler = llama.createSampler({
temperature: 0.7,
topK: 40,
topP: 0.9
});
// 启动聊天会话
llama.startChatSession(model, ctx, {
templateType: 4,
systemPrompt: "You are a helpful AI assistant.",
maxHistoryMessages: 10
});
// 多轮对话
console.log("User: Hello! What can you help me with?");
let string reply1 = llama.chatWithHistory(model, ctx, sampler, "Hello! What can you help me with?", {
maxTokens: 80
});
console.log("AI: " + reply1);
console.log("User: Tell me about programming");
let string reply2 = llama.chatWithHistory(model, ctx, sampler, "Tell me about programming", {
maxTokens: 100
});
console.log("AI: " + reply2);
// 查看历史
let object history = llama.getChatHistory(model);
console.log("Total messages: " + history.count().toString());
// 清理资源
llama.freeSampler(sampler);
llama.freeContext(ctx);
llama.freeModel(model);
- 不能混用:CUDA 和 Vulkan 库不能同时链接,会导致段错误!
- 选择后端:
- Vulkan:支持所有显卡(NVIDIA/AMD/Intel),通用性好
- CUDA:仅 NVIDIA 显卡,性能最佳(快 20-30%)
- 配置方法:
# 只使用 Vulkan mv lib/ggml-cuda.lib lib/ggml-cuda.lib.bak make clean && make # 只使用 CUDA mv lib/ggml-vulkan.lib lib/ggml-vulkan.lib.bak make clean && make
- 详细文档:GPU-ACCELERATION-GUIDE.md | LLAMA-GPU-SETUP.md
完整示例见: docs/examples/llama/chat-system-direct-api.ruin
import gpu from "gpu";
// 检查 GPU 是否可用
if (gpu.isAvailable()) {
// 矩阵乘法
let array<number> matrixA = [1.0, 2.0, 3.0, 4.0];
let array<number> matrixB = [5.0, 6.0, 7.0, 8.0];
let array<number> result = gpu.matrixMultiply(matrixA, matrixB, 2, 2, 2);
// 向量运算
let array<number> vec1 = [1.0, 2.0, 3.0];
let array<number> vec2 = [4.0, 5.0, 6.0];
let array<number> sum = gpu.vectorAdd(vec1, vec2);
}
import http from "http";
import json from "json";
ruin function fetchUserData = (string userId) => future<object> {
let object response = await http.get("https://api.example.com/users/" + userId);
let object data = json.parse(response.body);
return data;
};
// 使用
let object userData = await fetchUserData("12345");
console.log("用户名: " + userData.name);
import console from "console";
import json from "json";
// 基础 try-catch
try {
throw "Something went wrong";
} catch (error) {
console.log("Error: " + error.message);
console.log("Type: " + error.type);
console.log("Line: " + error.line);
}
// Try-catch-finally
try {
let object data = json.parseStrict("{\"name\": \"Alice\"}");
console.log("Parse successful");
} catch (error) {
console.log("Parse failed: " + error.message);
} finally {
console.log("Cleanup always runs");
}
// 函数中的错误处理
let function divide = (number a, number b) => number {
if (b == 0.0) {
throw "Division by zero";
}
return a / b;
};
try {
let number result = divide(10.0, 0.0);
} catch (error) {
console.log("Error: " + error.message);
}
从 Releases 下载最新版本,或克隆仓库:
git clone https://github.com/naichabaobao/ruin.git
cd ruin方式A: 直接使用编译好的可执行文件:
./dist/ruin.exe script.ruin方式B: 查看帮助:
./dist/ruin.exe --help创建文件 hello.ruin:
import console from "console";
console.log("Hello, Ruin!");
运行:
./ruin.exe hello.ruin创建文件 first-app.ruin:
import console from "console";
import gui from "gui";
import director from "director";
console.log("创建窗口...");
// 创建窗口
let window win = gui.createWindow({
width: 800,
height: 600,
title: "我的第一个应用",
center: true
});
// 创建标签
let label title = gui.createLabel("欢迎使用 Ruin", {
fontSize: 32,
color: {r: 1.0, g: 1.0, b: 1.0, a: 1.0}
});
title.x = 250.0;
title.y = 250.0;
// 添加到场景
director.getScene().canvas.addChild(title);
// 显示窗口
win.show();
运行:
./ruin.exe first-app.ruinRuin 提供了多个实战示例,从简单到复杂,展示了语言的各种特性。
文件: test/test-closure.ruin
展示闭包、高阶函数和异步编程的完整示例。
import console from "console";
// 闭包示例 - 创建计数器
let function createCounter = () => function {
let number count = 0;
return () => number {
count = count + 1;
return count;
};
};
let function counter = createCounter();
console.log(counter()); // 输出: 1
console.log(counter()); // 输出: 2
运行:
./dist/ruin.exe test/test-closure.ruin
# 测试闭包捕获和高阶函数涵盖知识点:
- 闭包捕获外部变量
- 高阶函数返回函数
- 异步回调支持
- 函数式编程
文件: test/test-convert.ruin
展示 Ruin 的类型转换系统和类型安全。
import console from "console";
import convert from "convert";
// 字符串转数字
let string numStr = "123";
let number num = parseInt(numStr);
console.log("解析的数字: " + num);
// 数字转字符串
let number value = 456;
let string valueStr = toString(value);
console.log("转换的字符串: " + valueStr);
运行:
./dist/ruin.exe test/test-convert.ruin
# 测试各种类型转换涵盖知识点:
- parseInt() 字符串转数字
- toString() 数字转字符串
- 类型安全的转换
文件: test/test-screen-basic.ruin
展示 ScreenCapture 模块的所有基础功能。
功能:
- ✅ 平台检测(Windows DXGI / Linux X11)
- ✅ 显示器信息获取(分辨率、刷新率、位置)
- ✅ 多显示器列表
- ✅ 光标位置追踪
- ✅ 全屏/区域截图保存
- ✅ 屏幕图像捕获(cv.Mat 类型)
运行:
./dist/ruin.exe test/test-screen-basic.ruin
# 生成截图文件到 test/results/涵盖知识点:
- ScreenCapture API
- 跨平台屏幕捕获
- 类型检查(type.Mat)
- 资源管理
文件: test/test-cv-channels.ruin
展示 OpenCV 的各种图像处理功能。
功能:
- ✅ 图像读取与保存
- ✅ 颜色空间转换(RGB、灰度)
- ✅ 图像滤波(高斯模糊)
- ✅ 边缘检测(Canny)
- ✅ 通道操作
运行:
./dist/ruin.exe test/test-cv-channels.ruin
# 测试 OpenCV 图像处理涵盖知识点:
- OpenCV 基础操作
- 图像滤波和增强
- 边缘检测算法
- 通道分离合并
| 示例 | 难度 | 模块 | 特点 | 运行时间 |
|---|---|---|---|---|
| test-closure | ⭐⭐ | console | 闭包和高阶函数 | < 0.1s |
| test-convert | ⭐ | convert | 类型转换 | < 0.1s |
| test-screen-basic | ⭐⭐ | screen | 屏幕捕获基础 | < 1s |
| test-cv-channels | ⭐⭐ | cv | OpenCV 图像处理 | < 1s |
import console from "console";
import input from "input";
import gui from "gui";
import director from "director";
// 创建窗口
let window win = gui.createWindow({
width: 800,
height: 600,
title: "简单游戏"
});
// 创建玩家
let sprite player = gui.createSprite({
width: 50,
height: 50,
backgroundColor: {r: 0.2, g: 0.8, b: 0.2, a: 1.0}
});
let number playerX = 400.0;
let number playerY = 300.0;
let number speed = 5.0;
let number score = 0;
// 分数显示
let label scoreLabel = gui.createLabel("Score: 0", {
fontSize: 24
});
scoreLabel.x = 10.0;
scoreLabel.y = 10.0;
// 游戏逻辑
player.update = (number delta) => {
// 移动
let number horizontal = input.getAxis("move_left", "move_right");
let number vertical = input.getAxis("move_up", "move_down");
playerX = playerX + (horizontal * speed);
playerY = playerY + (vertical * speed);
// 边界检测
if (playerX < 0.0) { playerX = 0.0; }
if (playerX > 750.0) { playerX = 750.0; }
if (playerY < 0.0) { playerY = 0.0; }
if (playerY > 550.0) { playerY = 550.0; }
player.x = playerX;
player.y = playerY;
// 空格增加分数
if (input.isActionJustPressed("jump")) {
score = score + 10;
scoreLabel.text = "Score: " + score;
}
};
director.getScene().canvas.addChild(player);
director.getScene().canvas.addChild(scoreLabel);
win.show();
import console from "console";
import json from "json";
// 带错误处理的 JSON 解析
let function safeJsonParse = (string jsonStr) => object {
try {
return json.parseStrict(jsonStr);
} catch (error) {
console.log("Parse failed: " + error.message);
return json.parseStrict("{}"); // 返回默认空对象
}
};
let object data = safeJsonParse(userInput);
// 带错误处理的除法
let function safeDivide = (number a, number b) => number {
if (b == 0.0) {
throw "Division by zero";
}
return a / b;
};
try {
let number result = safeDivide(10.0, 0.0);
} catch (error) {
console.log("Error: " + error.message);
console.log("At line: " + error.line);
}
📌 注意:
- ✅ 当前项目包含 56个 经过验证的测试文件
- ❌ 已删除 63个 失败的测试(详见 DEPRECATED-TESTS.md)
- 📋 完整测试清单请查看 TEST-FILES-INDEX.md
| 模块 | 功能 | 导入方式 |
|---|---|---|
console |
控制台输出 | import console from "console" |
math |
数学运算 | import math from "math" |
fs |
文件系统 | import fs from "fs" |
http |
HTTP/HTTPS 客户端 | import http from "http" |
gui |
GUI 图形界面 | import gui from "gui" |
input |
输入系统 | import input from "input" |
director |
场景管理 | import director from "director" |
gpu |
GPU 计算加速 | import gpu from "gpu" |
cv |
计算机视觉(OpenCV) ★新增 | import cv from "cv" |
screen |
屏幕捕获 ★新增 | import screen from "screen" |
llama |
Llama AI 模型 ★新增 | import llama from "llama" |
timer |
定时器 | import timer from "timer" |
json |
JSON 处理 | import json from "json" |
date |
日期时间 | import date from "date" |
path |
路径操作 | import path from "path" |
buffer |
二进制缓冲区 | import buffer from "buffer" |
system |
系统功能 | import system from "system" |
process |
进程管理 | import process from "process" |
详细 API 文档请查看 docs/BUILTIN-MODULES.md。
完整的文档系统位于 docs/ 目录:
- GUI 系统 - 窗口和组件系统
- Canvas 绘图 - 2D 绘图与渲染
- 输入系统 - 输入处理和动作映射
- 生命周期 - 组件生命周期管理
- 异步编程 - async/await 使用指南
- GPU 计算 - GPU 加速功能
- 计算机视觉 ★新增 - OpenCV 图像处理
- 屏幕捕获 ★新增 - 跨平台屏幕截图
- Llama AI ★新增 - AI 大语言模型
- 错误处理 ★ - Try-Catch-Finally 完整指南
- 错误处理集成 ★ - 与HTTP/JSON/Async集成
在浏览器中打开 docs/html/index.html 即可访问完整文档。
// 必须显式声明类型
let number x = 10;
let string name = "Ruin";
let boolean flag = true;
let array<number> numbers = [1, 2, 3];
let map<string, number> dict = {"key": 42};
// 普通函数
let function add = (number a, number b) => number {
return a + b;
};
// 单参数函数
let function square = (number x) => number {
return x * x;
};
// 异步函数
ruin function fetchData = (string url) => future<string> {
let object response = await http.get(url);
return response.body;
};
// 字符串拼接(自动转换)
let number score = 100;
let string message = "Score: " + score; // "Score: 100"
// 字符串转数字
let string input = "42";
let number num = parseInt(input); // 42
let number pi = parseFloat("3.14"); // 3.14
// if 语句
if (age >= 18) {
console.log("成年人");
} else {
console.log("未成年");
}
// while 循环
let number i = 0;
while (i < 10) {
console.log(i);
i = i + 1;
}
// try-catch-finally(新增)
try {
riskyOperation();
} catch (error) {
console.log("Error: " + error.message);
} finally {
cleanup();
}
let sprite enemy = gui.createSprite({...});
// 初始化
enemy.start = () => {
console.log("敌人生成!");
};
// 每帧更新
enemy.update = (number delta) => {
// 游戏逻辑
};
// 销毁时
enemy.onDestroy = () => {
console.log("敌人死亡!");
};
- UI:
ui_accept,ui_cancel,ui_touch,ui_select - 移动:
move_left,move_right,move_up,move_down - 动作:
jump,sprint,interact - 战斗:
attack,secondary_attack
详见 输入系统文档。
Ruin 内置 34 个 GPU 函数,支持:
- ✅ 矩阵运算(加、减、乘、转置、求逆)
- ✅ 向量运算(加、减、点积、归一化)
- ✅ 卷积和池化
- ✅ 激活函数(ReLU、Sigmoid、Tanh)
- ✅ 神经网络前向/反向传播
- ✅ 图像处理(滤波、边缘检测)
示例:
import gpu from "gpu";
if (gpu.isAvailable()) {
let array<number> result = gpu.matrixMultiply(matA, matB, m, n, p);
let array<number> sum = gpu.vectorAdd(vec1, vec2);
let array<number> activated = gpu.relu(data);
}
详见 GPU 文档。
import http from "http";
import json from "json";
// GET 请求
let object response = await http.get("https://api.example.com/data");
// POST 请求
let object postData = {
body: json.stringify({key: "value"}),
headers: {"Content-Type": "application/json"}
};
let object result = await http.post("https://api.example.com/data", postData);
console.log("状态码: " + result.status);
console.log("响应体: " + result.body);
ruin/
├── src/ # 源代码
│ ├── core/ # 核心功能(GUI、GPU 等)
│ ├── lang/ # 语言实现(词法、解析、解释器)
│ └── main/ # 主入口
├── docs/ # 文档
│ ├── html/ # HTML 文档系统
│ ├── api/ # API 模块文档
│ ├── examples/ # 示例代码(教学用)
│ ├── API-INDEX.md # API 索引
│ └── QUICK-REFERENCE.md # 快速参考
├── std/ # 标准库
│ ├── audio.ruin # 音频模块
│ ├── console.ruin # 控制台模块
│ ├── cv.ruin # 计算机视觉
│ ├── graphics.ruin # 图形系统
│ └── ... (28个模块)
├── test/ # 测试和示例 ✅ 56个测试
│ ├── test-*.ruin # 功能测试 (30个)
│ ├── syntax/ # 语法测试 (19个)
│ └── comprehensive/ # 综合测试 (7个)
├── TEST-FILES-INDEX.md # 测试文件索引 ⭐
├── DEPRECATED-TESTS.md # 已删除测试说明 ⭐
├── Makefile # 构建配置
└── README.md # 本文件
⭐ 重要文档:
- TEST-FILES-INDEX.md - 56个通过测试的完整清单
- DEPRECATED-TESTS.md - 63个已删除测试及替代方案
- TEST-CLEANUP-REPORT.md - 详细的清理报告
- C++17 或更高
- CUDA Toolkit(如果使用 GPU 功能)
- SDL2(用于 GUI)
- OpenSSL(用于 HTTPS)
make clean
make./ruin.exe test/test-window-show.ruin
./ruin.exe test/demo-textfield.ruin- ✅ Llama 聊天系统 - 完整的多轮对话支持
llama.startChatSession()- 启动聊天会话llama.chatWithHistory()- 带历史的对话llama.getChatHistory()/clearChatHistory()- 历史管理- 支持多种聊天模板(ChatML、Llama2、Alpaca、Vicuna、Simple)
- 自定义系统提示词和采样参数
- ✅ 控制Token过滤 - 自动过滤特殊控制字符,输出更干净
- ✅ GPU加速支持 - 支持 CUDA/Vulkan/Metal 后端(需重新编译库)
- ✅ 完整示例 - 4个不同场景的对话示例(通用助手、技术专家、创意写作、代码助手)
- ✅ 日志级别控制
- Debug 模式:只显示 ERROR(RUIN_LOG_LEVEL=3)
- Release 模式:完全禁用(RUIN_LOG_LEVEL=5)
- ✅ llama.cpp 日志过滤 - 自定义日志回调,只显示错误
- ✅ 输出更干净 - 减少200+行的详细日志输出
- ✅ OpenAL32.dll 自动拷贝 - 编译时自动拷贝到 dist/
- ✅ Release 模式优化 -
-O3优化,完全禁用日志 - ✅ 编译信息优化 - 清晰显示编译模式和日志级别
- ✅ GPU 加速指南 - docs/GPU-ACCELERATION-GUIDE.md
- ✅ 聊天示例说明 - docs/examples/llama/README-CHAT-EXAMPLES.md
- ✅ CPU 版本示例 - chat-system-cpu.ruin
- ✅ 对象字面量限制说明 - docs/OBJECT-LITERAL-LIMITATIONS.md
- ✅ Try-Catch-Finally - 完整的异常处理语法
- ✅ Throw - 抛出自定义错误
- ✅ Error 类型 - 专门的 error 类型
error.message- 错误消息error.type- 错误类型error.line- 错误行号error.column- 错误列号
- ✅ JSON 双模式API - 普通模式 + 严格模式(抛出异常)
json.parseStrict()- 抛出异常版本json.stringifyStrict()- 抛出异常版本
- ✅ 完全兼容 - HTTP、Async、JSON 全兼容
- ✅ 嵌套支持 - 多层嵌套错误处理
- ✅ 错误传播 - 通过调用栈自动传播
- ✅ 全局输入管理
- 动作映射(Action Mapping)
- 轴输入(Axis Input)
- 预定义 20+ 常用动作
- 支持键盘和鼠标输入
- ✅ Button 支持
on("click", callback)事件 - ✅ Sprite 支持
setImage(path)加载图片 - ✅ 改进的生命周期系统(start, update, onDestroy)
- ✅ 完整的 UTF-8 支持
- ✅ 全新的 HTML 文档系统
- ✅ 错误处理完整指南
- ✅ 10+ 完整的文档页面
- ✅ 响应式设计,支持移动端
- ✅ GPU 计算优化
- ✅ 改进的内存管理
- ✅ 更快的渲染性能
详见 CHANGELOG.md。
欢迎贡献代码、报告问题或提出建议!
- Fork 本仓库
- 创建特性分支 (
git checkout -b feature/AmazingFeature) - 提交更改 (
git commit -m 'Add some AmazingFeature') - 推送到分支 (
git push origin feature/AmazingFeature) - 开启 Pull Request
本项目采用 MIT 许可证 - 详见 LICENSE 文件。
- GitHub: https://github.com/naichabaobao/ruin
- 文档: docs/html/index.html
- 问题反馈: https://github.com/naichabaobao/ruin/issues
用 Ruin 开始你的创作之旅! 🚀
Made with ❤️ by naichabaobao