Sure! Below is the complete script that implements a deep neural network (DNN) with Q-learning, using the inputs and outputs you've specified. This AI will learn to navigate towards the finish line while avoiding bad parts, using the rays as its vision. It will receive rewards based on its proximity to the finish line and penalties when near bad parts or obstacles.
--[[
Deep Q-Network (DQN) implementation for AI navigation in Roblox
The AI uses rays as inputs and movement functions as outputs
It learns to reach the finish line while avoiding bad parts
]]
-- Get the AI Body
local AIBody = script.Parent
-- Set up movement
-- BodyVelocity
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)
-- Get the finish line
local finishingPart = game.Workspace:WaitForChild("Finish")
-- Get the bad parts
local badParts = game.Workspace:WaitForChild("BadParts")
-- Raycast parameters
local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Blacklist
params.FilterDescendantsInstances = {workspace.Baseplate, AIBody}
-- Movement functions
local function RotateLeft()
-- Output action: Rotate Left
AIBody.CFrame = AIBody.CFrame * CFrame.Angles(0,math.rad(5),0)
end
local function RotateRight()
-- Output action: Rotate Right
AIBody.CFrame = AIBody.CFrame * CFrame.Angles(0,math.rad(-5),0)
end
local function MoveForward()
-- Output action: Move Forward
movement.Velocity = AIBody.CFrame.LookVector * 10
end
local function MoveBackward()
-- Output action: Move Backward
movement.Velocity = AIBody.CFrame.LookVector * -10
end
local function StopMoving()
-- Output action: Stop Moving
movement.Velocity = Vector3.new(0,0,0)
end
-- Neural Network Parameters
local inputSize = 7 -- 5 rays distances + distance to finish + distance to bad parts
local hiddenSize = 10
local outputSize = 5 -- number of actions
-- Initialize weights
local weightsInputHidden = {}
for i = 1, inputSize do
weightsInputHidden[i] = {}
for j = 1, hiddenSize do
weightsInputHidden[i][j] = math.random() * 2 -1 -- random weights between -1 and 1
end
end
local weightsHiddenOutput = {}
for i = 1, hiddenSize do
weightsHiddenOutput[i] = {}
for j = 1, outputSize do
weightsHiddenOutput[i][j] = math.random() * 2 -1
end
end
-- Activation function
local function sigmoid(x)
return 1 / (1 + math.exp(-x))
end
-- Learning rate
local learningRate = 0.1
-- Discount factor
local gamma = 0.9
-- Exploration rate
local epsilon = 1.0
local epsilonMin = 0.01
local epsilonDecay = 0.995
-- Actions list
local actions = {RotateLeft, RotateRight, MoveForward, MoveBackward, StopMoving}
-- Main loop
local episode = 0
while true do
episode = episode +1
-- Reset position
AIBody.CFrame = CFrame.new(0, 1, 0)
movement.Velocity = Vector3.new(0,0,0)
local totalReward = 0
local startTime = tick()
while true do
-- Get inputs
local inputs = {}
-- Raycasts
local directionEMLR = script.Parent.EvenMoreLeftRay.Position - AIBody.Position
local directionLR = script.Parent.LeftRay.Position - AIBody.Position
local directionMR = script.Parent.MiddleRay.Position - AIBody.Position
local directionRR = script.Parent.RightRay.Position - AIBody.Position
local directionEMRR = script.Parent.EvenMoreRightRay.Position - AIBody.Position
local ray1 = workspace:Raycast(AIBody.Position,directionEMLR.Unit * 5,params)
local ray2 = workspace:Raycast(AIBody.Position,directionLR.Unit * 5,params)
local ray3 = workspace:Raycast(AIBody.Position,directionMR.Unit * 5,params)
local ray4 = workspace:Raycast(AIBody.Position,directionRR.Unit * 5,params)
local ray5 = workspace:Raycast(AIBody.Position,directionEMRR.Unit * 5,params)
local distance1 = ray1 and (ray1.Position - AIBody.Position).Magnitude or 5
local distance2 = ray2 and (ray2.Position - AIBody.Position).Magnitude or 5
local distance3 = ray3 and (ray3.Position - AIBody.Position).Magnitude or 5
local distance4 = ray4 and (ray4.Position - AIBody.Position).Magnitude or 5
local distance5 = ray5 and (ray5.Position - AIBody.Position).Magnitude or 5
-- Distance to finish
local distanceToFinish = (AIBody.Position - finishingPart.Position).Magnitude
-- Distance to nearest bad part
local closestBadPartDistance = math.huge
for _, badPart in pairs(badParts:GetChildren()) do
local dist = (AIBody.Position - badPart.Position).Magnitude
if dist < closestBadPartDistance then
closestBadPartDistance = dist
end
end
-- Inputs normalization
table.insert(inputs, distance1 / 5)
table.insert(inputs, distance2 / 5)
table.insert(inputs, distance3 / 5)
table.insert(inputs, distance4 / 5)
table.insert(inputs, distance5 / 5)
table.insert(inputs, distanceToFinish / 100) -- assuming max distance is 100
table.insert(inputs, closestBadPartDistance / 100)
-- Forward pass
-- Input to Hidden
local hidden = {}
for j = 1, hiddenSize do
local sum = 0
for i = 1, inputSize do
sum = sum + inputs[i] * weightsInputHidden[i][j]
end
hidden[j] = sigmoid(sum)
end
-- Hidden to Output
local outputs = {}
for j = 1, outputSize do
local sum = 0
for i = 1, hiddenSize do
sum = sum + hidden[i] * weightsHiddenOutput[i][j]
end
outputs[j] = sigmoid(sum)
end
-- Choose action
local actionIndex
if math.random() < epsilon then
-- Explore: random action
actionIndex = math.random(1, outputSize)
else
-- Exploit: best action based on Q-values
local maxQ = -math.huge
for i = 1, outputSize do
if outputs[i] > maxQ then
maxQ = outputs[i]
actionIndex = i
end
end
end
-- Execute action
actions[actionIndex]()
-- Wait a short time
wait(0.1)
-- Get new state and reward
-- Update inputs after the action
-- Raycasts (recalculate)
local ray1_new = workspace:Raycast(AIBody.Position,directionEMLR.Unit * 5,params)
local ray2_new = workspace:Raycast(AIBody.Position,directionLR.Unit * 5,params)
local ray3_new = workspace:Raycast(AIBody.Position,directionMR.Unit * 5,params)
local ray4_new = workspace:Raycast(AIBody.Position,directionRR.Unit * 5,params)
local ray5_new = workspace:Raycast(AIBody.Position,directionEMRR.Unit * 5,params)
local distance1_new = ray1_new and (ray1_new.Position - AIBody.Position).Magnitude or 5
local distance2_new = ray2_new and (ray2_new.Position - AIBody.Position).Magnitude or 5
local distance3_new = ray3_new and (ray3_new.Position - AIBody.Position).Magnitude or 5
local distance4_new = ray4_new and (ray4_new.Position - AIBody.Position).Magnitude or 5
local distance5_new = ray5_new and (ray5_new.Position - AIBody.Position).Magnitude or 5
local distanceToFinish_new = (AIBody.Position - finishingPart.Position).Magnitude
local closestBadPartDistance_new = math.huge
for _, badPart in pairs(badParts:GetChildren()) do
local dist = (AIBody.Position - badPart.Position).Magnitude
if dist < closestBadPartDistance_new then
closestBadPartDistance_new = dist
end
end
-- Compute reward
local reward = 0
if distanceToFinish_new < 5 then
reward = reward + 100 -- Big reward for reaching close to finish line
print("Reached goal! Reward: "..reward)
elseif distanceToFinish_new < distanceToFinish then
reward = reward + 1 -- Reward for getting closer to finish
else
reward = reward -1 -- Penalty for getting further from finish
end
if closestBadPartDistance_new < 5 then
reward = reward - 5 -- Penalty for being close to bad parts
end
-- Penalty for being too close to obstacles
if distance1_new < 0.5 or distance2_new < 0.5 or distance3_new < 0.5 or distance4_new < 0.5 or distance5_new < 0.5 then
reward = reward - 10
-- Stop moving forward
StopMoving()
end
totalReward = totalReward + reward
-- Next forward pass for next state (we need target Q-values)
local nextInputs = {}
table.insert(nextInputs, distance1_new / 5)
table.insert(nextInputs, distance2_new / 5)
table.insert(nextInputs, distance3_new / 5)
table.insert(nextInputs, distance4_new / 5)
table.insert(nextInputs, distance5_new / 5)
table.insert(nextInputs, distanceToFinish_new / 100)
table.insert(nextInputs, closestBadPartDistance_new / 100)
-- Next forward pass
-- Input to Hidden
local hiddenNext = {}
for j = 1, hiddenSize do
local sum = 0
for i = 1, inputSize do
sum = sum + nextInputs[i] * weightsInputHidden[i][j]
end
hiddenNext[j] = sigmoid(sum)
end
-- Hidden to Output
local outputsNext = {}
for j = 1, outputSize do
local sum = 0
for i = 1, hiddenSize do
sum = sum + hiddenNext[i] * weightsHiddenOutput[i][j]
end
outputsNext[j] = sigmoid(sum)
end
-- Find max Q value for next state
local maxQNext = -math.huge
for i = 1, outputSize do
if outputsNext[i] > maxQNext then
maxQNext = outputsNext[i]
end
end
-- Target Q-value
local targetQ = reward + gamma * maxQNext
-- Calculate the error
local outputQ = outputs[actionIndex]
local error = targetQ - outputQ
-- Backpropagation to update weights
-- Output to Hidden weights
for i = 1, hiddenSize do
weightsHiddenOutput[i][actionIndex] = weightsHiddenOutput[i][actionIndex] + learningRate * error * hidden[i]
end
-- Hidden to Input weights
for i = 1, inputSize do
for j = 1, hiddenSize do
local hiddenError = error * weightsHiddenOutput[j][actionIndex] * hidden[j] * (1 - hidden[j])
weightsInputHidden[i][j] = weightsInputHidden[i][j] + learningRate * hiddenError * inputs[i]
end
end
-- Decay epsilon
if epsilon > epsilonMin then
epsilon = epsilon * epsilonDecay
end
-- Check for episode termination
if distanceToFinish_new < 5 then
-- Reached goal
print("Episode "..episode..": Total Reward: "..totalReward)
break
end
if tick() - startTime > 10 then
-- Time limit reached
print("Episode "..episode..": Time limit reached. Total Reward: "..totalReward)
break
end
end
end
Explanation
-
Neural Network Initialization: We set up a simple neural network with one hidden layer. The weights are initialized randomly between -1 and 1.
-
Inputs: The neural network takes in 7 inputs:
- Five Ray Distances: Distances from the AI to obstacles detected by the rays (
directionEMLR, directionLR, directionMR, directionRR, directionEMRR).
- Distance to Finish Line: The AI's current distance to the finish line.
- Distance to Nearest Bad Part: The closest distance to any bad part in
workspace.BadParts.
-
Outputs: The neural network outputs Q-values for 5 possible actions:
- Rotate Left
- Rotate Right
- Move Forward
- Move Backward
- Stop Moving
-
Q-Learning Implementation:
- Action Selection: Uses an epsilon-greedy policy to balance exploration and exploitation.
- Reward Calculation:
- Positive Reward: Given when the AI moves closer to the finish line.
- Big Reward: Given when the AI is within 5 studs of the finish line.
- Negative Reward: Applied when the AI moves away from the finish line or gets close to bad parts or obstacles.
- Neural Network Update: We use the Bellman equation to update the Q-values and adjust the weights using backpropagation.
-
Obstacle Avoidance: If any ray detects an obstacle within 0.5 studs, the AI stops moving forward to avoid collisions.
-
Episode Management: The AI resets after 10 seconds or when it reaches the finish line within 5 studs.
Important Notes
-
Learning Rate and Exploration Rate: Adjust learningRate, epsilon, epsilonMin, and epsilonDecay as needed to fine-tune the learning process.
-
Debugging and Monitoring: Keep an eye on the printed Total Reward to monitor the AI's learning progress.
-
Performance Considerations: Neural networks can be computationally intensive. Ensure that this script runs smoothly within the Roblox environment without causing performance issues.
Setting Up the Environment
Ensure your Roblox workspace is set up as follows:
- AIBody: The AI object to which this script is attached.
- Finish: A part named
Finish representing the finish line.
- BadParts: A folder in the workspace containing parts that are considered "bad" (obstacles or penalties).
- Rays: Child parts of AIBody named:
EvenMoreLeftRay
LeftRay
MiddleRay
RightRay
EvenMoreRightRay
These parts should be positioned to cast rays in the desired directions relative to the AI's orientation.
Testing the AI
- Run the Script: Start the game and observe the AI's behavior.
- Monitor Output: Watch the output window for reward messages to see how the AI is performing.
- Adjust Parameters: If the AI isn't learning effectively, consider adjusting the learning rate, exploration decay rate, or neural network size.
Final Remarks
This script implements a real working neural network using Q-learning, as per your request. The AI should learn from its previous experiences, improving its ability to reach the finish line while avoiding obstacles over time. Remember that reinforcement learning can take time to show significant improvements, so be patient and allow the AI to undergo many episodes.
Feel free to ask if you need further assistance or have any questions!