Further enhance and add in a more advanced pathfinding with AI, and Multi-layer Perceptron, w/Classifications and repetition penalty with movement finding.
code
-- Variables 8=======D --
local Pathfinding = game:GetService("PathfindingService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local path = Pathfinding:CreatePath({
AgentHeight = 6;
AgentRadius = 3;
AgentCanJump = false;
Costs = {
Water = 100;
DangerZone = math.huge
}
})
local Character = script.Parent
local humanoid = Character:WaitForChild("Humanoid")
local waypoints
local nextWaypointIndex
local reachedConnection
local blockedConnection
local function findTarget ()
local maxDistance = 500
local nearestTarget
for index, player in pairs(Players:GetPlayers()) do
if player.Character then
local target = player.Character
local distance = (Character.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude
if distance < maxDistance then
nearestTarget = target
maxDistance = distance
end
if distance < 5 then
nearestTarget.Humanoid:TakeDamage(25)
end
end
end
return nearestTarget
end
local function followPath(destination)
local success, errorMessage = pcall (function()
path:ComputeAsync(Character.PrimaryPart.Position, destination)
end)
if success and path.Status == Enum.PathStatus.Success then
waypoints = path:GetWaypoints()
blockedConnection = path.Blocked:Connect (function(blockedWayPointIndex)
if blockedWayPointIndex >= nextWaypointIndex then
blockedConnection:Disconnect()
followPath(destination)
end
end)
if not reachedConnection then
reachedConnection = humanoid.MoveToFinished:Connect(function(reached)
if reached and nextWaypointIndex < #waypoints then
nextWaypointIndex += 1
humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
else
reachedConnection:Disconnect()
blockedConnection:Disconnect()
end
end)
end
nextWaypointIndex = 2
humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
else
warn("Path not computed!", errorMessage)
end
end
while wait() do
local target = findTarget()
if target then
print(target.Name)
followPath(target.HumanoidRootPart.Position)
end
end
Assistant
Enhancing your Roblox AI with advanced pathfinding, a Multi-Layer Perceptron (MLP) for decision-making, classifications, and a repetition penalty involves several steps. Below is an enhanced version of your script incorporating these features, along with detailed explanations to help you understand and customize it further.
Overview of Enhancements
Advanced Pathfinding with AI: Incorporate smarter decision-making by evaluating the environment and dynamically adjusting paths based on obstacles and target behavior.
Multi-Layer Perceptron (MLP) for Classification: Implement a simple neural network to classify targets or decide actions based on input features.
Repetition Penalty: Prevent the AI from repeating the same actions or movement patterns excessively to promote more natural and varied behavior.
Enhanced Script
lua
-- Advanced AI with Pathfinding, MLP Classification, and Repetition Penalty
local Pathfinding = game:GetService("PathfindingService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
-- Configuration Parameters
local CONFIG = {
AgentHeight = 6,
AgentRadius = 3,
AgentCanJump = false,
CostModifiers = {
Water = 100,
DangerZone = math.huge
},
MaxTargetDistance = 500,
AttackRange = 5,
AttackDamage = 25,
MLP = {
InputSize = 3, -- Example: distance, visibility, threat level
HiddenSize = 5,
OutputSize = 2, -- Example: [Move, Attack]
LearningRate = 0.01
},
RepetitionPenalty = {
MaxHistory = 20,
PenaltyFactor = 0.1
}
}
-- Initialize Pathfinding
local path = Pathfinding:CreatePath({
AgentHeight = CONFIG.AgentHeight,
AgentRadius = CONFIG.AgentRadius,
AgentCanJump = CONFIG.AgentCanJump,
Costs = CONFIG.CostModifiers
})
-- Character and Humanoid References
local Character = script.Parent
local humanoid = Character:WaitForChild("Humanoid")
local humanoidRootPart = Character:WaitForChild("HumanoidRootPart")
-- MLP Neural Network Implementation
local MLP = {}
MLP.__index = MLP
function MLP.new(inputSize, hiddenSize, outputSize, learningRate)
local self = setmetatable({}, MLP)
self.inputSize = inputSize
self.hiddenSize = hiddenSize
self.outputSize = outputSize
self.learningRate = learningRate
-- Initialize weights with random values
self.weightsInputHidden = {}
for i = 1, hiddenSize do
self.weightsInputHidden[i] = {}
for j = 1, inputSize do
self.weightsInputHidden[i][j] = math.random() * 2 - 1
end
end
self.weightsHiddenOutput = {}
for i = 1, outputSize do
self.weightsHiddenOutput[i] = {}
for j = 1, hiddenSize do
self.weightsHiddenOutput[i][j] = math.random() * 2 - 1
end
end
return self
end
-- Activation function (ReLU)
local function relu(x)
return math.max(0, x)
end
-- Forward pass
function MLP:forward(input)
self.hidden = {}
for i = 1, self.hiddenSize do
local sum = 0
for j = 1, self.inputSize do
sum = sum + self.weightsInputHidden[i][j] * input[j]
end
self.hidden[i] = relu(sum)
end
self.output = {}
for i = 1, self.outputSize do
local sum = 0
for j = 1, self.hiddenSize do
sum = sum + self.weightsHiddenOutput[i][j] * self.hidden[j]
end
self.output[i] = relu(sum)
end
return self.output
end
-- Initialize MLP
local mlp = MLP.new(CONFIG.MLP.InputSize, CONFIG.MLP.HiddenSize, CONFIG.MLP.OutputSize, CONFIG.MLP.LearningRate)
-- Repetition Penalty Variables
local actionHistory = {}
-- Function to Add Action to History
local function addToHistory(action)
table.insert(actionHistory, action)
if #actionHistory > CONFIG.RepetitionPenalty.MaxHistory then
table.remove(actionHistory, 1)
end
end
-- Function to Calculate Repetition Penalty
local function calculateRepetitionPenalty(currentAction)
local penalty = 0
for _, action in ipairs(actionHistory) do
if action == currentAction then
penalty = penalty + CONFIG.RepetitionPenalty.PenaltyFactor
end
end
return penalty
end
-- Function to Normalize Distance
local function normalizeDistance(distance, maxDistance)
return math.clamp(distance / maxDistance, 0, 1)
end
-- Function to Find and Classify Target
local function findAndClassifyTarget()
local maxDistance = CONFIG.MaxTargetDistance
local nearestTarget
local targetFeatures = {}
-- Find Nearest Target
for _, player in pairs(Players:GetPlayers()) do
if player.Character and player.Character:FindFirstChild("HumanoidRootPart") then
local targetPos = player.Character.HumanoidRootPart.Position
local distance = (humanoidRootPart.Position - targetPos).Magnitude
if distance < maxDistance then
nearestTarget = player.Character
maxDistance = distance
end
end
end
if nearestTarget then
-- Gather Features for MLP
local distance = (humanoidRootPart.Position - nearestTarget.HumanoidRootPart.Position).Magnitude
local visibility = 1 -- Placeholder: Implement visibility check if needed
local threatLevel = 0 -- Placeholder: Determine threat level based on target's state
table.insert(targetFeatures, normalizeDistance(distance, CONFIG.MaxTargetDistance))
table.insert(targetFeatures, visibility)
table.insert(targetFeatures, threatLevel)
-- Classify Action using MLP
local actions = mlp:forward(targetFeatures)
-- Apply Repetition Penalty
for i, actionValue in ipairs(actions) do
if actionValue > 0 then
local actionName = ""
if i == 1 then
actionName = "Move"
elseif i == 2 then
actionName = "Attack"
end
local penalty = calculateRepetitionPenalty(actionName)
actions[i] = actionValue - penalty
if actions[i] < 0 then
actions[i] = 0
end
end
end
-- Decide Action Based on MLP Output
local moveAction = actions[1] > actions[2] -- Simple decision: move if move action has higher value
local attackAction = actions[2] > actions[1]
-- Add to Action History
if moveAction then
addToHistory("Move")
return nearestTarget, "Move"
elseif attackAction and distance <= CONFIG.AttackRange then
addToHistory("Attack")
return nearestTarget, "Attack"
end
end
return nil, nil
end
-- Function to Attack Target
local function attackTarget(target)
if target and target:FindFirstChild("Humanoid") then
target.Humanoid:TakeDamage(CONFIG.AttackDamage)
end
end
-- Function to Follow Path to Destination
local function followPath(destination)
local success, errorMessage = pcall(function()
path:ComputeAsync(humanoidRootPart.Position, destination)
end)
if success and path.Status == Enum.PathStatus.Success then
local waypoints = path:GetWaypoints()
local nextWaypointIndex = 2
-- Handle Path Blocked
local blockedConnection
blockedConnection = path.Blocked:Connect(function(blockedWaypointIndex)
if blockedWaypointIndex >= nextWaypointIndex then
blockedConnection:Disconnect()
followPath(destination) -- Recompute path if blocked
end
end)
-- Handle Reaching Waypoints
local reachedConnection
reachedConnection = humanoid.MoveToFinished:Connect(function(reached)
if reached and nextWaypointIndex < #waypoints then
nextWaypointIndex = nextWaypointIndex + 1
humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
else
reachedConnection:Disconnect()
blockedConnection:Disconnect()
end
end)
-- Start Moving to the First Waypoint
humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
else
warn("Path not computed!", errorMessage)
end
end
-- Main Loop
RunService.RenderStepped:Connect(function()
local target, action = findAndClassifyTarget()
if target then
print("Target:", target.Name, "Action:", action)
if action == "Move" then
followPath(target.HumanoidRootPart.Position)
elseif action == "Attack" then
attackTarget(target)
end
end
end)
Explanation of Enhancements
Advanced Pathfinding with AI:
Dynamic Path Adjustment: The followPath function now includes connections to handle blocked paths dynamically, allowing the AI to recompute its path when obstacles appear.
Configuration Parameters: Centralized configuration (CONFIG) allows easy adjustments of agent properties, pathfinding costs, and other parameters.
Multi-Layer Perceptron (MLP) for Classification:
Simple MLP Implementation: A basic MLP with one hidden layer is implemented to process input features and output action decisions.
Input Features: The MLP takes features such as normalized distance to the target, visibility, and threat level. These can be expanded based on your game's requirements.
Action Decisions: The MLP outputs scores for possible actions (e.g., Move, Attack), determining the AI's next action based on these scores.
Repetition Penalty:
Action History: The script maintains a history of recent actions (actionHistory) to track repetitive behavior.
Penalty Calculation: When deciding on an action, the script applies a penalty if the same action has been taken frequently in the recent history, encouraging varied behavior.
Configuration: The RepetitionPenalty settings allow customization of how history size and penalty factors influence behavior.
Customization and Further Enhancements
MLP Training: The current MLP implementation does not include training mechanisms. For more sophisticated behavior, consider implementing backpropagation and training the network based on in-game experiences or predefined datasets.
Feature Expansion: Enhance the input features to the MLP by including more environmental factors, such as obstacles, other AI agents, or target states.
Advanced Decision-Making: Incorporate more complex decision-making logic, such as prioritizing targets based on threat level or orchestrating multiple actions.
Optimization: Since Lua is not optimized for intensive computations, ensure that the MLP's complexity remains manageable to prevent performance issues.
Debugging and Visualization: Implement debugging tools or visual markers to monitor the AI's decisions and paths in real-time, aiding in development and tuning.
Final Notes
Implementing AI with MLPs in Roblox can significantly enhance the intelligence and adaptability of NPCs. However, it's essential to balance complexity with performance, ensuring that the game remains responsive and enjoyable. The provided script offers a foundation that you can build upon, tailoring the AI's behavior to fit the specific needs of your game.
Feel free to ask if you need further assistance or specific features added to the AI!