MtnMCG

ndisk chatai

Sep 6th, 2024 (edited)
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 27.83 KB | None | 0 0
  1. local modem = peripheral.find("modem") or error("No modem found")
  2. modem.open(1) -- Open channel 1 for communication
  3.  
  4. local nodes = {}
  5. local chunkMap = {}
  6.  
  7. -- Function to load node IDs
  8. local function loadNodeIds()
  9. nodes = {}
  10. if fs.exists("ids.txt") then
  11. local file = fs.open("ids.txt", "r")
  12. for line in file.readLine do
  13. local nodeId, hierarchicalNum = line:match("(%d+)%s+(%d+)")
  14. if nodeId and hierarchicalNum then
  15. nodes[tonumber(hierarchicalNum)] = tonumber(nodeId)
  16. end
  17. end
  18. file.close()
  19. end
  20. end
  21.  
  22. -- Function to load chunk map
  23. local function loadChunkMap()
  24. chunkMap = {}
  25. if fs.exists("chunklocation.txt") then
  26. local file = fs.open("chunklocation.txt", "r")
  27. for line in file.readLine do
  28. local filename, chunk, nodeId = line:match("(%S+)%s+(%S+)%s+(%S+)")
  29. if filename and chunk and nodeId then
  30. chunkMap[filename] = chunkMap[filename] or {}
  31. local chunkNum = tonumber(chunk:match("chunk(%d+)"))
  32. chunkMap[filename][chunkNum] = tonumber(nodeId)
  33. end
  34. end
  35. file.close()
  36. end
  37. end
  38.  
  39. loadNodeIds()
  40. local nodeCount = 0
  41. for _ in pairs(nodes) do nodeCount = nodeCount + 1 end
  42. if nodeCount == 0 then
  43. error("No storage nodes found. Make sure the storage nodes are running and connected.")
  44. end
  45. print("Found " .. nodeCount .. " storage node(s)")
  46. loadChunkMap()
  47.  
  48.  
  49.  
  50. -- Function to send a request to a node
  51. local function sendRequest(nodeId, request)
  52. request.targetNode = nodeId
  53. modem.transmit(1, 1, request)
  54. local timer = os.startTimer(5)
  55. while true do
  56. local event, param1, param2, param3, param4, param5 = os.pullEvent()
  57. if event == "modem_message" and param4.id == request.id then
  58. return param4.response
  59. elseif event == "timer" and param1 == timer then
  60. error("Request timed out for node: " .. nodeId)
  61. end
  62. end
  63. end
  64.  
  65. -- Advanced Dynamic Language Model with Enhanced Spatial AI and Pathfinding for CC: Tweaked
  66.  
  67. local model = {
  68. wordTransitions = {},
  69. layers = {},
  70. complexIdeas = {},
  71. selfImprovement = {
  72. learningRate = 0.1,
  73. adaptationRate = 0.01
  74. },
  75. spatialMemory = {},
  76. position = {x = 0, y = 0, z = 0},
  77. orientation = 0, -- 0: north, 1: east, 2: south, 3: west
  78. locations = {}
  79. }
  80. local wordList = {}
  81. local memory = {}
  82. local SAVE_FILE = "language_model.dat"
  83. local TRAINING_FILE = "trainingdata.txt"
  84. local exploring = false
  85.  
  86. local function sendRequest(nodeId, request)
  87. request.targetNode = nodeId
  88. modem.transmit(1, 1, request)
  89. local timer = os.startTimer(5)
  90. while true do
  91. local event, param1, param2, param3, param4, param5 = os.pullEvent()
  92. if event == "modem_message" and param4.id == request.id then
  93. return param4.response
  94. elseif event == "timer" and param1 == timer then
  95. error("Request timed out for node: " .. nodeId)
  96. end
  97. end
  98. end
  99.  
  100. -- Function to load the model from ndisk
  101. local function loadModel()
  102. if chunkMap[SAVE_FILE] then
  103. local content = {}
  104. for chunkNum, nodeId in pairs(chunkMap[SAVE_FILE]) do
  105. local response = sendRequest(nodeId, {
  106. id = os.getComputerID() .. "_" .. os.clock(),
  107. action = "read",
  108. path = SAVE_FILE,
  109. chunk = chunkNum
  110. })
  111. if response.success then
  112. content[chunkNum] = response.content
  113. else
  114. error("Failed to read chunk " .. chunkNum .. " from node " .. nodeId)
  115. end
  116. end
  117. local data = table.concat(content)
  118. local loaded = textutils.unserialize(data)
  119. model.wordTransitions = loaded.wordTransitions or {}
  120. model.layers = loaded.layers or {}
  121. model.complexIdeas = loaded.complexIdeas or {}
  122. model.selfImprovement = loaded.selfImprovement or {learningRate = 0.1, adaptationRate = 0.01}
  123. model.spatialMemory = loaded.spatialMemory or {}
  124. model.position = loaded.position or {x = 0, y = 0, z = 0}
  125. model.orientation = tonumber(loaded.orientation) or 0
  126. model.locations = loaded.locations or {}
  127. wordList = loaded.wordList or {}
  128. memory = loaded.memory or {}
  129. print("Model loaded from ndisk.")
  130. else
  131. print("No existing model found on ndisk. Starting fresh.")
  132. wordList = {"the", "be", "to", "of", "and", "a", "in", "that", "have", "I"}
  133. end
  134. end
  135.  
  136. -- Function to save the model to ndisk
  137. local function saveModel()
  138. print("Saving model to ndisk...")
  139. local data = textutils.serialize({
  140. wordTransitions = model.wordTransitions,
  141. layers = model.layers,
  142. complexIdeas = model.complexIdeas,
  143. selfImprovement = model.selfImprovement,
  144. spatialMemory = model.spatialMemory,
  145. position = model.position,
  146. orientation = model.orientation,
  147. locations = model.locations,
  148. wordList = wordList,
  149. memory = memory
  150. })
  151.  
  152. local nodeCount = 0
  153. for _ in pairs(nodes) do nodeCount = nodeCount + 1 end
  154. local chunkSize = math.ceil(#data / nodeCount)
  155. chunkMap[SAVE_FILE] = {}
  156. local chunkNum = 1
  157. for hierarchicalNum, nodeId in pairs(nodes) do
  158. local start = (chunkNum - 1) * chunkSize + 1
  159. local chunk = data:sub(start, math.min(start + chunkSize - 1, #data))
  160. local response = sendRequest(nodeId, {
  161. id = os.getComputerID() .. "_" .. os.clock(),
  162. action = "write",
  163. path = SAVE_FILE,
  164. chunk = chunkNum,
  165. content = chunk
  166. })
  167. if not response.success then
  168. error("Failed to write chunk " .. chunkNum .. " to node " .. nodeId)
  169. end
  170. chunkMap[SAVE_FILE][chunkNum] = nodeId
  171. chunkNum = chunkNum + 1
  172. end
  173.  
  174. -- Save updated chunk map
  175. local file = fs.open("chunklocation.txt", "w")
  176. for filename, chunks in pairs(chunkMap) do
  177. for chunkNum, nodeId in pairs(chunks) do
  178. file.writeLine(filename .. " chunk" .. chunkNum .. " " .. nodeId)
  179. end
  180. end
  181. file.close()
  182.  
  183. print("Model saved to ndisk.")
  184. end
  185.  
  186. -- Function to tokenize input
  187. local function tokenize(input)
  188. if type(input) ~= "string" then
  189. return {}
  190. end
  191. local words = {}
  192. for word in input:gmatch("%w+") do
  193. table.insert(words, word:lower())
  194. end
  195. return words
  196. end
  197.  
  198. -- Function to update the model
  199. local function updateModel(words, modelTable)
  200. if type(words) ~= "table" or #words == 0 then
  201. return
  202. end
  203. for i = 1, #words - 1 do
  204. local currentWord = words[i]
  205. local nextWord = words[i + 1]
  206.  
  207. if not modelTable.wordTransitions[currentWord] then
  208. modelTable.wordTransitions[currentWord] = {}
  209. end
  210. modelTable.wordTransitions[currentWord][nextWord] = (modelTable.wordTransitions[currentWord][nextWord] or 0) + 1
  211.  
  212. -- Add new words to wordList
  213. if not table.concat(wordList, " "):find(currentWord) then
  214. table.insert(wordList, currentWord)
  215. end
  216. if not table.concat(wordList, " "):find(nextWord) then
  217. table.insert(wordList, nextWord)
  218. end
  219. end
  220. end
  221.  
  222. -- Function to generate a response with improved coherence and reduced hallucinations
  223. local function generateResponse(input, modelTable)
  224. local words = tokenize(input)
  225. local response = {}
  226. local currentWord = words[#words] or wordList[math.random(#wordList)]
  227.  
  228. local maxWords = math.random(1, 15) -- Changed minimum to 1
  229. local context = {} -- Keep track of recent words for context
  230.  
  231. for i = 1, maxWords do
  232. if modelTable.wordTransitions[currentWord] then
  233. local totalWeight = 0
  234. local weightedWords = {}
  235. for word, count in pairs(modelTable.wordTransitions[currentWord]) do
  236. totalWeight = totalWeight + (count or 0)
  237. table.insert(weightedWords, {word = word, weight = count or 0})
  238. end
  239.  
  240. if totalWeight > 0 then
  241. -- Use context to influence word selection
  242. local contextInfluence = 0.3 -- Adjust this value to change the influence of context
  243. local randomWeight = math.random() * (totalWeight + (#context * contextInfluence))
  244. local cumulativeWeight = 0
  245. for _, wordData in ipairs(weightedWords) do
  246. cumulativeWeight = cumulativeWeight + wordData.weight
  247. if context[wordData.word] then
  248. cumulativeWeight = cumulativeWeight + contextInfluence
  249. end
  250. if cumulativeWeight >= randomWeight then
  251. currentWord = wordData.word
  252. break
  253. end
  254. end
  255. else
  256. currentWord = wordList[math.random(#wordList)]
  257. end
  258. table.insert(response, currentWord)
  259.  
  260. -- Update context
  261. context[currentWord] = (context[currentWord] or 0) + 1
  262. if #response > 5 then -- Keep last 5 words in context
  263. local oldWord = response[#response - 5]
  264. context[oldWord] = (context[oldWord] or 1) - 1
  265. if context[oldWord] <= 0 then
  266. context[oldWord] = nil
  267. end
  268. end
  269. else
  270. currentWord = wordList[math.random(#wordList)]
  271. table.insert(response, currentWord)
  272. end
  273. end
  274.  
  275. return table.concat(response, " ")
  276. end
  277.  
  278. -- Function to analyze patterns and predict improvements
  279. local function analyzePatterns(modelTable)
  280. local patterns = {}
  281. for word, transitions in pairs(modelTable.wordTransitions) do
  282. local sortedTransitions = {}
  283. for nextWord, weight in pairs(transitions) do
  284. table.insert(sortedTransitions, {word = nextWord, weight = weight})
  285. end
  286. table.sort(sortedTransitions, function(a, b) return a.weight > b.weight end)
  287.  
  288. if #sortedTransitions >= 3 then
  289. patterns[word] = {
  290. sortedTransitions[1].word,
  291. sortedTransitions[2].word,
  292. sortedTransitions[3].word
  293. }
  294. end
  295. end
  296.  
  297. modelTable.predictedPatterns = patterns
  298. end
  299. -- Function to delete a saved location
  300. local function deleteLocation(name)
  301. if model.locations[name] then
  302. model.locations[name] = nil
  303. saveModel() -- Save the model to persist the change
  304. print("Location '" .. name .. "' has been deleted.")
  305. else
  306. print("Location '" .. name .. "' not found.")
  307. end
  308. end
  309.  
  310. -- Function for self-improvement with pattern analysis
  311. local function selfImprove()
  312. model.selfImprovement.learningRate = model.selfImprovement.learningRate * (1 + model.selfImprovement.adaptationRate)
  313. analyzePatterns(model)
  314.  
  315. -- Use predicted patterns to reinforce likely transitions
  316. for word, likelyNext in pairs(model.predictedPatterns) do
  317. for _, nextWord in ipairs(likelyNext) do
  318. if model.wordTransitions[word] and model.wordTransitions[word][nextWord] then
  319. model.wordTransitions[word][nextWord] = model.wordTransitions[word][nextWord] * 1.1 -- Increase weight by 10%
  320. end
  321. end
  322. end
  323. end
  324.  
  325. -- Function to get coordinates in front of the turtle
  326. local function getFrontCoords()
  327. local x, y, z = model.position.x, model.position.y, model.position.z
  328. if model.orientation == 0 then -- North
  329. z = z - 1
  330. elseif model.orientation == 1 then -- East
  331. x = x + 1
  332. elseif model.orientation == 2 then -- South
  333. z = z + 1
  334. else -- West
  335. x = x - 1
  336. end
  337. return x, y, z
  338. end
  339.  
  340. -- Function to move the turtle and update its position
  341. local function moveTurtle(direction)
  342. local success = false
  343. if direction == "forward" then
  344. success = turtle.forward()
  345. if success then
  346. local x, y, z = getFrontCoords()
  347. model.position.x, model.position.y, model.position.z = x, y, z
  348. end
  349. elseif direction == "back" then
  350. success = turtle.back()
  351. if success then
  352. local x, y, z = getFrontCoords()
  353. model.position.x, model.position.y, model.position.z = x, y, z
  354. end
  355. elseif direction == "up" then
  356. success = turtle.up()
  357. if success then
  358. model.position.y = model.position.y + 1
  359. end
  360. elseif direction == "down" then
  361. success = turtle.down()
  362. if success then
  363. model.position.y = model.position.y - 1
  364. end
  365. elseif direction == "left" then
  366. turtle.turnLeft()
  367. model.orientation = (model.orientation - 1) % 4
  368. success = true
  369. elseif direction == "right" then
  370. turtle.turnRight()
  371. model.orientation = (model.orientation + 1) % 4
  372. success = true
  373. end
  374.  
  375. return success
  376. end
  377.  
  378. -- Function to detect blocks and update spatial memory
  379. local function detectBlocks()
  380. local success, data = turtle.inspect()
  381. if success then
  382. local x, y, z = getFrontCoords()
  383. local key = x .. "," .. y .. "," .. z
  384. model.spatialMemory[key] = {
  385. name = data.name,
  386. metadata = data.metadata,
  387. explored = true
  388. }
  389. end
  390. end
  391.  
  392. -- Function to create a new layer in the model
  393. local function createNewLayer(layerName, words, modelTable)
  394. if not modelTable.layers[layerName] then
  395. modelTable.layers[layerName] = {}
  396. end
  397.  
  398. for i = 1, #words - 1 do
  399. local currentWord = words[i]
  400. local nextWord = words[i + 1]
  401.  
  402. if not modelTable.layers[layerName][currentWord] then
  403. modelTable.layers[layerName][currentWord] = {}
  404. end
  405. modelTable.layers[layerName][currentWord][nextWord] = (modelTable.layers[layerName][currentWord][nextWord] or 0) + 1
  406. end
  407. end
  408.  
  409. -- Function to remember spatial context
  410. local function rememberSpatialContext()
  411. local context = {}
  412. for pos, data in pairs(model.spatialMemory) do
  413. table.insert(context, pos .. ": " .. data.name)
  414. end
  415. return table.concat(context, "\n")
  416. end
  417.  
  418. -- Function to relate spatial memory to language model
  419. local function relateSpatialToLanguage()
  420. for pos, data in pairs(model.spatialMemory) do
  421. local words = tokenize(data.name)
  422. updateModel(words, model)
  423. createNewLayer("spatial_" .. pos, words, model)
  424. end
  425. print("Spatial data integrated into language model.")
  426. end
  427.  
  428. -- Function to find unexplored directions
  429. local function findUnexploredDirections()
  430. local unexplored = {}
  431. local directions = {"forward", "left", "right", "up", "down"}
  432. for _, dir in ipairs(directions) do
  433. local x, y, z
  434. if dir == "forward" then
  435. x, y, z = getFrontCoords()
  436. elseif dir == "up" then
  437. x, y, z = model.position.x, model.position.y + 1, model.position.z
  438. elseif dir == "down" then
  439. x, y, z = model.position.x, model.position.y - 1, model.position.z
  440. else
  441. local tempOrientation = dir == "left" and (model.orientation - 1) % 4 or (model.orientation + 1) % 4
  442. if tempOrientation == 0 then -- North
  443. x, y, z = model.position.x, model.position.y, model.position.z - 1
  444. elseif tempOrientation == 1 then -- East
  445. x, y, z = model.position.x + 1, model.position.y, model.position.z
  446. elseif tempOrientation == 2 then -- South
  447. x, y, z = model.position.x, model.position.y, model.position.z + 1
  448. else -- West
  449. x, y, z = model.position.x - 1, model.position.y, model.position.z
  450. end
  451. end
  452. local key = x .. "," .. y .. "," .. z
  453. if not model.spatialMemory[key] or not model.spatialMemory[key].explored then
  454. table.insert(unexplored, dir)
  455. end
  456. end
  457. return unexplored
  458. end
  459.  
  460. -- A* Pathfinding Algorithm
  461. local function aStarPath(start, goal)
  462. local function heuristic(a, b)
  463. return math.abs(a.x - b.x) + math.abs(a.y - b.y) + math.abs(a.z - b.z)
  464. end
  465.  
  466. local openSet = {}
  467. local closedSet = {}
  468. local cameFrom = {}
  469. local gScore = {[start] = 0}
  470. local fScore = {[start] = heuristic(start, goal)}
  471.  
  472. table.insert(openSet, start)
  473.  
  474. while #openSet > 0 do
  475. local current = openSet[1]
  476. for i = 2, #openSet do
  477. if fScore[openSet[i]] < fScore[current] then
  478. current = openSet[i]
  479. end
  480. end
  481.  
  482. if current.x == goal.x and current.y == goal.y and current.z == goal.z then
  483. local path = {}
  484. while current do
  485. table.insert(path, 1, current)
  486. current = cameFrom[current]
  487. end
  488. return path
  489. end
  490.  
  491. for i, v in ipairs(openSet) do
  492. if v == current then
  493. table.remove(openSet, i)
  494. break
  495. end
  496. end
  497. table.insert(closedSet, current)
  498.  
  499. local neighbors = {
  500. {x = current.x + 1, y = current.y, z = current.z},
  501. {x = current.x - 1, y = current.y, z = current.z},
  502. {x = current.x, y = current.y + 1, z = current.z},
  503. {x = current.x, y = current.y - 1, z = current.z},
  504. {x = current.x, y = current.y, z = current.z + 1},
  505. {x = current.x, y = current.y, z = current.z - 1}
  506. }
  507.  
  508. for _, neighbor in ipairs(neighbors) do
  509. local inClosedSet = false
  510. for _, v in ipairs(closedSet) do
  511. if v.x == neighbor.x and v.y == neighbor.y and v.z == neighbor.z then
  512. inClosedSet = true
  513. break
  514. end
  515. end
  516.  
  517. if not inClosedSet then
  518. local tentative_gScore = gScore[current] + 1
  519.  
  520. local inOpenSet = false
  521. for _, v in ipairs(openSet) do
  522. if v.x == neighbor.x and v.y == neighbor.y and v.z == neighbor.z then
  523. inOpenSet = true
  524. break
  525. end
  526. end
  527.  
  528. if not inOpenSet then
  529. table.insert(openSet, neighbor)
  530. elseif tentative_gScore >= (gScore[neighbor] or math.huge) then
  531. goto continue
  532. end
  533.  
  534. cameFrom[neighbor] = current
  535. gScore[neighbor] = tentative_gScore
  536. fScore[neighbor] = gScore[neighbor] + heuristic(neighbor, goal)
  537.  
  538. ::continue::
  539. end
  540. end
  541. end
  542.  
  543. return nil -- No path found
  544. end
  545.  
  546. -- Function to save a location
  547. local function saveLocation(name)
  548. model.locations[name] = {x = model.position.x, y = model.position.y, z = model.position.z}
  549. saveModel() -- Save the model immediately after adding a new location
  550. print("Location '" .. name .. "' saved.")
  551. end
  552.  
  553. -- Function to go to a saved location
  554. local function gotoLocation(name)
  555. local coords = model.locations[name]
  556. if not coords then
  557. print("Location '" .. name .. "' not found.")
  558. return
  559. end
  560.  
  561. local path = aStarPath(model.position, coords)
  562. if not path then
  563. print("No path found to '" .. name .. "'.")
  564. return
  565. end
  566.  
  567. print("Path found. Moving to '" .. name .. "'...")
  568. for i, step in ipairs(path) do
  569. local dx = step.x - model.position.x
  570. local dy = step.y - model.position.y
  571. local dz = step.z - model.position.z
  572.  
  573. -- Determine direction and move
  574. if dx ~= 0 then
  575. if dx > 0 then
  576. while model.orientation ~= 1 do -- Face East
  577. moveTurtle("right")
  578. end
  579. else
  580. while model.orientation ~= 3 do -- Face West
  581. moveTurtle("right")
  582. end
  583. end
  584. moveTurtle("forward")
  585. elseif dz ~= 0 then
  586. if dz > 0 then
  587. while model.orientation ~= 2 do -- Face South
  588. moveTurtle("right")
  589. end
  590. else
  591. while model.orientation ~= 0 do -- Face North
  592. moveTurtle("right")
  593. end
  594. end
  595. moveTurtle("forward")
  596. elseif dy ~= 0 then
  597. if dy > 0 then
  598. moveTurtle("up")
  599. else
  600. moveTurtle("down")
  601. end
  602. end
  603.  
  604. print("Step " .. i .. " of " .. #path .. " completed.")
  605. end
  606.  
  607. print("Arrived at '" .. name .. "'.")
  608. end
  609.  
  610. -- Function to load training data
  611. local function loadTrainingData()
  612. if fs.exists(TRAINING_FILE) then
  613. local f = fs.open(TRAINING_FILE, "r")
  614. local data = f.readAll()
  615. f.close()
  616. if data and data ~= "" then
  617. local lines = {}
  618. for line in data:gmatch("[^\r\n]+") do
  619. table.insert(lines, line)
  620. end
  621. for i = 1, #lines, 2 do
  622. local prompt = lines[i]
  623. local response = lines[i + 1]
  624. if prompt and response then
  625. local promptWords = tokenize(prompt)
  626. local responseWords = tokenize(response)
  627. updateModel(promptWords, model)
  628. updateModel(responseWords, model)
  629. createNewLayer("prompt_" .. i, promptWords, model)
  630. createNewLayer("response_" .. i, responseWords, model)
  631. end
  632. end
  633. end
  634. end
  635. end
  636.  
  637.  
  638. -- Function to remember context
  639. local function rememberContext(input)
  640. table.insert(memory, input)
  641. if #memory > 10 then
  642. table.remove(memory, 1)
  643. end
  644. end
  645.  
  646. -- Function to handle complex ideas (placeholder implementation)
  647. local function handleComplexIdea(idea, modelTable)
  648. modelTable.complexIdeas = modelTable.complexIdeas or {}
  649. modelTable.complexIdeas[idea] = (modelTable.complexIdeas[idea] or 0) + 1
  650. end
  651.  
  652. -- Function for reinforcement learning
  653. local function reinforcementLearning(rating, modelTable)
  654. local learningRate = model.selfImprovement.learningRate
  655. for i = 1, #memory do
  656. local words = tokenize(memory[i])
  657. for j = 1, #words - 1 do
  658. local currentWord = words[j]
  659. local nextWord = words[j + 1]
  660. if modelTable.wordTransitions[currentWord] and modelTable.wordTransitions[currentWord][nextWord] then
  661. modelTable.wordTransitions[currentWord][nextWord] =
  662. modelTable.wordTransitions[currentWord][nextWord] * (1 + learningRate * (rating / 10 - 0.5))
  663. end
  664. end
  665. end
  666. end
  667.  
  668. -- Function to handle math expressions
  669. local function handleMath(input)
  670. local func, err = load("return " .. input)
  671. if func then
  672. local success, result = pcall(func)
  673. if success then
  674. return tostring(result)
  675. end
  676. end
  677. return "Error: Invalid math expression."
  678. end
  679.  
  680. -- Main loop
  681. print("Advanced Dynamic Language Model with Enhanced Spatial AI and Pathfinding")
  682. print("Type 'exit' to quit, 'save' to save the model")
  683.  
  684. loadNodeIds()
  685. local nodeCount = 0
  686. for _ in pairs(nodes) do nodeCount = nodeCount + 1 end
  687. if nodeCount == 0 then
  688. error("No storage nodes found. Make sure the storage nodes are running and connected.")
  689. end
  690. print("Found " .. nodeCount .. " storage node(s)")
  691. loadChunkMap()
  692. loadModel()
  693. loadTrainingData()
  694.  
  695. local function explorationTask()
  696. while true do
  697. if exploring then
  698. local unexploredDirections = findUnexploredDirections()
  699. if #unexploredDirections > 0 then
  700. local direction = unexploredDirections[math.random(#unexploredDirections)]
  701. if moveTurtle(direction) then
  702. detectBlocks()
  703. end
  704. else
  705. -- If surrounded by explored blocks, move randomly
  706. local directions = {"forward", "left", "right", "up", "down"}
  707. local direction = directions[math.random(#directions)]
  708. if moveTurtle(direction) then
  709. detectBlocks()
  710. end
  711. end
  712.  
  713. -- Allow other processes to run
  714. os.sleep(0.1)
  715.  
  716. if turtle.getFuelLevel() == 0 then
  717. print("Out of fuel. Exploration stopped.")
  718. exploring = false
  719. end
  720. else
  721. os.sleep(0.1)
  722. end
  723. end
  724. end
  725. -- Function to list saved locations
  726. local function listLocations()
  727. if not model.locations or next(model.locations) == nil then
  728. print("No locations saved.")
  729. return
  730. end
  731.  
  732. print("Saved locations:")
  733. local index = 1
  734. for name, coords in pairs(model.locations) do
  735. print(index .. ". " .. name .. " (" .. coords.x .. ", " .. coords.y .. ", " .. coords.z .. ")")
  736. index = index + 1
  737. end
  738. end
  739.  
  740. local function mainLoop()
  741. while true do
  742. write("> ")
  743. local input = read()
  744.  
  745. if input:lower() == "exit" then
  746. saveModel()
  747. print("Goodbye!")
  748. break
  749. elseif input:lower() == "save" then
  750. saveModel()
  751. elseif input:lower() == "explore" then
  752. exploring = true
  753. print("Starting exploration. Type 'stop' to end.")
  754. elseif input:lower() == "stop" then
  755. exploring = false
  756. print("Exploration will stop after the current move.")
  757. elseif input:lower() == "list locations" then
  758. listLocations()
  759. elseif input:match("^save%s+(.+)$") then
  760. local name = input:match("^save%s+(.+)$")
  761. saveLocation(name)
  762. elseif input:match("^goto%s+(.+)$") then
  763. local name = input:match("^goto%s+(.+)$")
  764. gotoLocation(name)
  765. elseif input:match("^delete%s+(.+)$") then
  766. local name = input:match("^delete%s+(.+)$")
  767. deleteLocation(name)
  768. elseif input:match("^rate%s+(%d+)$") then
  769. local rating = tonumber(input:match("^rate%s+(%d+)$"))
  770. if rating and rating >= 1 and rating <= 10 then
  771. reinforcementLearning(rating, model)
  772. print("Thank you for your rating!")
  773. else
  774. print("Invalid rating. Please use a number between 1 and 10.")
  775. end
  776. elseif input:match("^%d+[%+%-%*/%^]%d+$") then
  777. local result = handleMath(input)
  778. print("Math: " .. result)
  779. elseif input:match("^move%s+(%w+)$") then
  780. local direction = input:match("^move%s+(%w+)$")
  781. if moveTurtle(direction) then
  782. print("Moved " .. direction)
  783. detectBlocks()
  784. else
  785. print("Failed to move " .. direction)
  786. end
  787. elseif input:match("^inspect$") then
  788. detectBlocks()
  789. print("Inspected block at current position.")
  790. elseif input:match("^remember%s+spatial$") then
  791. local context = rememberSpatialContext()
  792. print("Spatial Memory:\n" .. context)
  793. else
  794. local words = tokenize(input)
  795. updateModel(words, model)
  796. rememberContext(input)
  797. handleComplexIdea(input, model)
  798. local response = generateResponse(input, model)
  799. print("Model: " .. response)
  800. selfImprove()
  801. end
  802. end
  803. end
  804.  
  805. parallel.waitForAny(explorationTask, mainLoop)
  806.  
  807.  
Add Comment
Please, Sign In to add comment