Sure! I'll help you create a deep neural network (DNN) using Q-learning in Roblox Lua, based on the script you provided. I'll integrate the neural network into your AI agent so that it learns to navigate towards the finish line while avoiding bad parts.
Below is the complete script with detailed comments explaining each part. I'll also provide explanations after the code to further clarify.
--[[
Deep Q-Network AI Agent in Roblox Lua
This script implements a DNN using Q-learning for an AI agent in Roblox.
The AI uses raycasts as inputs and movement functions as outputs.
It learns to navigate towards a finish line while avoiding bad parts.
]]
-- Services
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")
-- Constants
local INPUT_SIZE = 7 -- Number of inputs (5 rays + distance to finish + distance to bad part)
local HIDDEN_SIZE = 16 -- Size of hidden layer
local OUTPUT_SIZE = 5 -- Number of possible actions
local LEARNING_RATE = 0.01
local DISCOUNT_FACTOR = 0.9
local EPSILON = 0.1 -- Exploration rate
-- AI Agent
local AIBody = script.Parent
-- Movement
local movement = Instance.new("BodyVelocity")
movement.Parent = AIBody
movement.MaxForce = Vector3.new(math.huge, math.huge, math.huge)
movement.Velocity = Vector3.new(0, 0, 0)
-- Finish Line
local finishingPart = Workspace:WaitForChild("Finish")
-- Bad Parts (Obstacles)
local badParts = Workspace:WaitForChild("BadParts"):GetChildren()
-- Neural Network Parameters
local weights1 = {} -- Weights from input layer to hidden layer
local biases1 = {} -- Biases for hidden layer
local weights2 = {} -- Weights from hidden layer to output layer
local biases2 = {} -- Biases for output layer
-- Initialize Neural Network Parameters with small random values
local function initializeParameters()
math.randomseed(tick())
for i = 1, HIDDEN_SIZE do
biases1[i] = math.random() * 0.1
weights1[i] = {}
for j = 1, INPUT_SIZE do
weights1[i][j] = math.random() * 0.1
end
end
for i = 1, OUTPUT_SIZE do
biases2[i] = math.random() * 0.1
weights2[i] = {}
for j = 1, HIDDEN_SIZE do
weights2[i][j] = math.random() * 0.1
end
end
end
-- Activation Function (ReLU)
local function relu(x)
return math.max(0, x)
end
-- Forward Pass through Neural Network
local function forward(input)
local hidden = {}
for i = 1, HIDDEN_SIZE do
local sum = biases1[i]
for j = 1, INPUT_SIZE do
sum = sum + weights1[i][j] * input[j]
end
hidden[i] = relu(sum)
end
local output = {}
for i = 1, OUTPUT_SIZE do
local sum = biases2[i]
for j = 1, HIDDEN_SIZE do
sum = sum + weights2[i][j] * hidden[j]
end
output[i] = sum -- Output is linear, since we'll use Q-values
end
return output, hidden
end
-- Choose Action Based on Epsilon-Greedy Policy
local function chooseAction(qValues)
if math.random() < EPSILON then
-- Explore: choose a random action
return math.random(1, OUTPUT_SIZE)
else
-- Exploit: choose the action with highest Q-value
local maxQ = qValues[1]
local action = 1
for i = 2, OUTPUT_SIZE do
if qValues[i] > maxQ then
maxQ = qValues[i]
action = i
end
end
return action
end
end
-- Movement Functions (Actions)
local function RotateLeft()
AIBody.CFrame = AIBody.CFrame * CFrame.Angles(0, math.rad(5), 0)
end
local function RotateRight()
AIBody.CFrame = AIBody.CFrame * CFrame.Angles(0, math.rad(-5), 0)
end
local function MoveForward()
movement.Velocity = AIBody.CFrame.LookVector * 10
end
local function MoveBackward()
movement.Velocity = AIBody.CFrame.LookVector * -10
end
local function StopMoving()
movement.Velocity = Vector3.new(0, 0, 0)
end
local actions = {RotateLeft, RotateRight, MoveForward, MoveBackward, StopMoving}
-- Gather Inputs
local function getInputs()
local inputs = {}
-- Rays (Vision)
local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Blacklist
params.FilterDescendantsInstances = {Workspace.Baseplate, AIBody}
local directions = {
(AIBody.EvenMoreLeftRay.Position - AIBody.Position).Unit * 10,
(AIBody.LeftRay.Position - AIBody.Position).Unit * 10,
(AIBody.MiddleRay.Position - AIBody.Position).Unit * 10,
(AIBody.RightRay.Position - AIBody.Position).Unit * 10,
(AIBody.EvenMoreRightRay.Position - AIBody.Position).Unit * 10,
}
for i, direction in ipairs(directions) do
local ray = Workspace:Raycast(AIBody.Position, direction, params)
if ray then
inputs[i] = ray.Distance -- Distance to obstacle
else
inputs[i] = 10 -- Max distance (no obstacle detected within 10 studs)
end
end
-- Distance to Finish Line
local distanceToFinish = (AIBody.Position - finishingPart.Position).Magnitude
inputs[6] = distanceToFinish
-- Distance to Closest Bad Part
local minBadPartDistance = math.huge
for _, badPart in ipairs(badParts) do
local dist = (AIBody.Position - badPart.Position).Magnitude
if dist < minBadPartDistance then
minBadPartDistance = dist
end
end
inputs[7] = minBadPartDistance
return inputs
end
-- Main Training Loop
local totalReward = 0
local episodeReward = 0
local timeElapsed = 0
local maxEpisodeTime = 10 -- seconds
local initialized = false
initializeParameters()
local function resetEpisode()
-- Reset AI position to starting point
AIBody:SetPrimaryPartCFrame(Workspace.Start.CFrame)
movement.Velocity = Vector3.new(0, 0, 0)
episodeReward = 0
timeElapsed = 0
end
-- Q-Learning Update
local function updateQValues(state, action, reward, nextState)
-- Forward pass for current state
local qValues, hidden = forward(state)
local predictedQ = qValues[action]
-- Forward pass for next state
local nextQValues, _ = forward(nextState)
local maxNextQ = nextQValues[1]
for i = 2, OUTPUT_SIZE do
if nextQValues[i] > maxNextQ then
maxNextQ = nextQValues[i]
end
end
-- Calculate target Q-value
local targetQ = reward + DISCOUNT_FACTOR * maxNextQ
-- Calculate error
local error = targetQ - predictedQ
-- Backpropagate error and update weights (Gradient descent)
-- Update weights2 and biases2
for i = 1, OUTPUT_SIZE do
local gradient = (i == action) and error or 0
biases2[i] = biases2[i] + LEARNING_RATE * gradient
for j = 1, HIDDEN_SIZE do
weights2[i][j] = weights2[i][j] + LEARNING_RATE * gradient * hidden[j]
end
end
-- Update weights1 and biases1 (assuming ReLU derivative)
for i = 1, HIDDEN_SIZE do
local hiddenGradient = 0
if hidden[i] > 0 then -- ReLU derivative
for j = 1, OUTPUT_SIZE do
local gradient = (j == action) and error or 0
hiddenGradient = hiddenGradient + gradient * weights2[j][i]
end
biases1[i] = biases1[i] + LEARNING_RATE * hiddenGradient
for j = 1, INPUT_SIZE do
weights1[i][j] = weights1[i][j] + LEARNING_RATE * hiddenGradient * state[j]
end
end
end
end
-- Episode Reset
resetEpisode()
-- Main Loop
RunService.Stepped:Connect(function(deltaTime)
timeElapsed = timeElapsed + deltaTime
-- Get Current State
local state = getInputs()
-- Forward Pass to get Q-values
local qValues, _ = forward(state)
-- Choose Action
local actionIndex = chooseAction(qValues)
-- Perform Action
actions[actionIndex]()
-- Wait for a short duration to allow action effect
wait(0.1)
-- Get Next State
local nextState = getInputs()
-- Calculate Reward
local reward = 0
-- Reward for being closer to the finish line
local prevDistanceToFinish = state[6]
local currDistanceToFinish = nextState[6]
if currDistanceToFinish < prevDistanceToFinish then
reward = reward + 1 -- Positive reward for moving closer
else
reward = reward - 1 -- Negative reward for moving away
end
-- Additional reward if very close to the finish line
if currDistanceToFinish <= 5 then
reward = reward + 100 -- Big reward for reaching the goal
print("Reached the Finish Line! Total Episode Reward:", episodeReward + reward)
totalReward = totalReward + episodeReward + reward
print("Total Reward:", totalReward)
resetEpisode()
return
end
-- Penalty for being near bad parts
local distanceToBadPart = nextState[7]
if distanceToBadPart <= 5 then
reward = reward - 5 -- Penalty for being close to bad part
end
-- Penalty for being close to obstacles (rays less than 0.5 studs)
for i = 1, 5 do
if nextState[i] <= 0.5 then
reward = reward - 10 -- Penalty for being too close to obstacle
StopMoving()
break
end
end
-- Update Q-values (Train the Network)
updateQValues(state, actionIndex, reward, nextState)
-- Accumulate Rewards
episodeReward = episodeReward + reward
-- If time exceeds max episode time, reset episode
if timeElapsed >= maxEpisodeTime then
print("Episode Time Exceeded. Total Episode Reward:", episodeReward)
totalReward = totalReward + episodeReward
print("Total Reward:", totalReward)
resetEpisode()
end
-- Print out the current reward
print("Current Reward:", reward, "Episode Reward:", episodeReward)
end)
Explanation:
Notes:
Final Remarks:
This script provides a basic implementation of a Deep Q-Network in Roblox Lua. The AI agent uses reinforcement learning to navigate towards the finish line while avoiding obstacles. It learns from its experiences by updating its neural network based on the rewards it receives.
Remember to place this script inside the AI agent's model and ensure all referenced objects (like Finish, BadParts, and ray parts) exist and are correctly set up in your Roblox workspace.
Let me know if you have any questions or need further assistance!