Make an advanced B-Variation of a Q-Learning Sword Bot AI In roblox, with advanced reinforcement B learning. Into one Lua file
REFERENCE FILES:
Control.Lua:
code
local util = require(script.Parent.util)
local Control = {}
Control.__index = Control
function Control.new(model, epsilon, alpha, gamma, q_values)
local self = setmetatable({
model = model;
humanoid = model.Humanoid;
epsilon = epsilon;
alpha = alpha;
gamma = gamma;
q_values = q_values;
q = nil;
x = nil;
hp = model.Humanoid.Health;
t_hp = nil;
reward = -1;
dead = false;
q_next = nil;
}, Control)
model.Humanoid.HealthChanged:Connect(function(hp)
if hp == 0 then
self.dead = true
self.reward = -100
else
self.reward = self.reward - self.hp + hp
end
self.hp = hp
end)
return self
end
function Control:setTarget(target)
self.target = target
self.t_hp = target.model.Humanoid.Health
target.model.Humanoid.HealthChanged:Connect(function(hp)
if hp == 0 then
self.reward = 100
else
self.reward = self.reward + self.t_hp - hp
end
self.t_hp = hp
end)
end
function Control:update()
local targ = self.target
local selfCF = self.model:GetPrimaryPartCFrame()
local targCF = targ.model:GetPrimaryPartCFrame()
local q = selfCF:ToObjectSpace(targCF)
self.x = util.paramsToState(
util.saturateMag(math.sqrt(q.X^2 + q.Z^2)),
util.saturateAng(math.atan2(q.X, q.Z)),
util.saturateAng(math.atan2(q.LookVector.X, q.LookVector.Z))
)
end
function Control:step()
local method
if math.random() < self.epsilon then
-- Exploit current knowledge
if self.q_next then
self.q = self.q_next
return
end
method = util.bestQ
else
-- Explore new methods
method = util.rndQ
end
self.q = method(self.q_values, self.x)
end
function Control:process()
local move, turn = util.qToAction(self.q)
self.humanoid:Move(util.DIR[move], true)
local cf = self.model:GetPrimaryPartCFrame()
if turn == 1 then
cf = cf * CFrame.Angles(0, math.pi/32, 0)
elseif turn == 2 then
cf = cf * CFrame.Angles(0, -math.pi/32, 0)
end
self.model:SetPrimaryPartCFrame(cf)
end
function Control:learn()
local reward = self.reward
local mag = (self.model.PrimaryPart.Position - self.target.model.PrimaryPart.Position).Magnitude
if mag > 30 then
reward = reward - 1000
elseif mag > 15 then
reward = reward - (mag - 15) ^ 2
end
self.q_next = util.bestQ(self.q_values, self.x)
local v = self.q_values[self.q]
local update = reward + self.gamma * self.q_values[self.q_next] - v
self.q_values[self.q] = v + self.alpha * update
self.reward = -1
return mag
end
return Control
Assistant
Combat.Lua:
code
local Control = require(script.Control)
local util = require(script.util)
local storage = game:GetService('ServerStorage')
local ai = storage.AI:Clone()
local epsilon = 1
local alpha = 0.1
local gamma = 0.9
local function makeBot(pos)
local bot = ai:Clone()
bot.Parent = workspace
bot:MoveTo(pos)
bot.PrimaryPart = bot.HumanoidRootPart
return bot
end
local q_values = util.loadQ()
local bots = {}
local function makePair(i)
local x_o = i % 10 * 150 - 750
local y_o = (i - i % 10) * 15 - 750
local r1 = Control.new(
makeBot(Vector3.new(x_o, 0, y_o + 10)),
epsilon, alpha, gamma,
q_values
)
local r2 = Control.new(
makeBot(Vector3.new(x_o + 10, 0, y_o)),
epsilon, alpha, gamma,
q_values
)
r1:setTarget(r2)
r2:setTarget(r1)
return {r1, r2}
end
local function movePair(p, i)
local x_o = i % 10 * 150 - 750
local y_o = (i - i % 10) * 15 - 750
p[1].model:SetPrimaryPartCFrame(CFrame.new(x_o, 0, y_o + 10))
p[2].model:SetPrimaryPartCFrame(CFrame.new(x_o + 10, 0, y_o))
end
local function makeWallX(x)
local wall = Instance.new 'Part'
wall.Position = Vector3.new(x, -5, 0)
wall.Size = Vector3.new(1, 10, 2048)
wall.Transparency = 0.5
wall.Anchored = true
wall.Parent = workspace
end
local function makeWallY(y)
local wall = Instance.new 'Part'
wall.Position = Vector3.new(0, -5, y)
wall.Size = Vector3.new(2048, 10, 1)
wall.Transparency = 0.5
wall.Anchored = true
wall.Parent = workspace
end
for i = -1024 + 75, 1024, 150 do
makeWallX(i)
makeWallY(i)
end
for i = 1, 100 do
bots[i] = makePair(i)
end
for i, pair in ipairs(bots) do
pair[1]:update()
pair[2]:update()
end
local showDebugUI = true
local screen = Instance.new('ScreenGui')
local radius = 20
local l = math.sin(math.pi / util.N_ANG) * 2
local gui = {}
if showDebugUI then
for d = 0, util.N_ANG - 1 do
gui[d] = {}
local theta = util.toTheta(d) + math.pi/2
local sine = math.sin(theta)
local cosine = math.cos(theta)
for m = 0, util.N_MAG - 1 do
local f = Instance.new('TextLabel')
f.Size = UDim2.new(0, radius * m * l, 0, 20)
f.Rotation = math.deg(theta) + 90
f.Position = UDim2.new(0.5, radius * m * cosine, 0.5, radius * m * sine)
f.AnchorPoint = Vector2.new(0.5, 0.5)
f.Parent = screen
gui[d][m] = f
end
end
screen.Parent = game.StarterGui
end
game['Run Service'].Heartbeat:Connect(function()
if showDebugUI then
for m = 0, util.N_MAG - 1 do
for d = 0, util.N_ANG - 1 do
local mv = -math.huge
local mx = 0
for o = 0, util.N_ANG - 1 do
local x = util.paramsToState(m, d, o)
local v = q_values[util.bestQ(q_values, x)]
if v > mv then
mv = v
mx = x
end
end
gui[d][m].Text = tostring(math.floor(mv + 0.5))
end
end
end
for i, pair in ipairs(bots) do
pair[1]:step()
pair[2]:step()
end
for i, pair in ipairs(bots) do
pair[1]:process()
pair[2]:process()
end
for i, pair in ipairs(bots) do
pair[1]:update()
pair[2]:update()
end
local m = 0
local d = 0
local y = 0
for i, pair in ipairs(bots) do
local n = pair[1]:learn()
m = m + n
pair[2]:learn()
if pair[1].dead or pair[2].dead then
d = d + 1
pair[1].model:Destroy()
pair[2].model:Destroy()
pair = makePair(i)
pair[1]:update()
pair[2]:update()
bots[i] = pair
elseif n > 30 then
y = y + 1
movePair(pair, i)
end
end
print(d, y, m / #bots)
end)
Certainly! Below is an advanced B-variation of a Q-Learning Sword Bot AI for Roblox, consolidated into a single Lua script. This implementation enhances the basic Q-Learning approach by incorporating Double Q-Learning to reduce overestimation bias and improve learning stability. Additionally, it includes better state representation, improved exploration strategies, and more robust reward shaping.
Advanced Sword Bot AI with Double Q-Learning
lua
-- Single Lua File: AdvancedSwordBotAI.lua
-- Advanced Sword Bot AI using Double Q-Learning in Roblox
-- Ensure this script is placed in ServerScriptService or an appropriate server-side location
local RunService = game:GetService("RunService")
local ServerStorage = game:GetService("ServerStorage")
-- ======= Configuration Parameters =======
local CONFIG = {
NUM_BOTS = 50, -- Number of bot pairs
BOT_START_POS_X = 750, -- Starting X position offset
BOT_START_POS_Y = 750, -- Starting Y position offset
WALL_INTERVAL = 150, -- Interval between walls
EPSILON_START = 1, -- Initial exploration rate
EPSILON_MIN = 0.1, -- Minimum exploration rate
EPSILON_DECAY = 1e-5, -- Exploration decay per step
ALPHA = 0.1, -- Learning rate
GAMMA = 0.95, -- Discount factor
STATE_BINS_MAG = 30, -- Number of bins for magnitude
STATE_BINS_ANG = 12, -- Number of bins for angle
ACTIONS = {"MoveForward", "MoveBackward", "TurnLeft", "TurnRight", "Attack"},
DEBUG_UI = true, -- Toggle debug UI
}
-- ======= Utility Functions =======
local Util = {}
-- Saturate magnitude to a maximum value
function Util.saturateMag(mag, maxMag)
maxMag = maxMag or 30
return math.clamp(mag, 0, maxMag)
end
-- Saturate angle between 0 and 2*pi
function Util.saturateAng(angle)
angle = angle % (2 * math.pi)
return angle
end
-- Convert continuous parameters to discrete state
function Util.paramsToState(mag, ang, lookAng)
local magBin = math.floor((mag / CONFIG.STATE_BINS_MAG) * CONFIG.STATE_BINS_MAG) + 1
local angBin = math.floor((ang / (2 * math.pi)) * CONFIG.STATE_BINS_ANG) + 1
local lookBin = math.floor((lookAng / (2 * math.pi)) * CONFIG.STATE_BINS_ANG) + 1
return (magBin - 1) * CONFIG.STATE_BINS_ANG * CONFIG.STATE_BINS_ANG +
(angBin - 1) * CONFIG.STATE_BINS_ANG +
lookBin
end
-- Initialize Q-tables
function Util.initializeQTables(numStates, numActions)
local Q1 = {}
local Q2 = {}
for state = 1, numStates do
Q1[state] = {}
Q2[state] = {}
for action = 1, numActions do
Q1[state][action] = 0
Q2[state][action] = 0
end
end
return Q1, Q2
end
-- Choose action using epsilon-greedy policy
function Util.chooseAction(Q1, Q2, state, epsilon)
if math.random() < epsilon then
return math.random(1, #CONFIG.ACTIONS)
else
-- Double Q-Learning: Use Q1 to select action, Q2 for evaluation
local maxQ = -math.huge
local bestAction = 1
for action, _ in ipairs(Q1[state]) do
local qValue = Q1[state][action] + Q2[state][action]
if qValue > maxQ then
maxQ = qValue
bestAction = action
end
end
return bestAction
end
end
-- Best action based on summed Q1 and Q2
function Util.bestAction(Q1, Q2, state)
local maxQ = -math.huge
local bestAction = 1
for action, _ in ipairs(Q1[state]) do
local qValue = Q1[state][action] + Q2[state][action]
if qValue > maxQ then
maxQ = qValue
bestAction = action
end
end
return bestAction
end
-- Load Q-tables from disk (placeholder if persistent storage is implemented)
function Util.loadQT()
-- For simplicity, initializing Q-tables randomly
local numStates = CONFIG.STATE_BINS_MAG * CONFIG.STATE_BINS_ANG * CONFIG.STATE_BINS_ANG
local Q1, Q2 = Util.initializeQTables(numStates, #CONFIG.ACTIONS)
return Q1, Q2
end
-- Save Q-tables to disk (placeholder if persistent storage is needed)
function Util.saveQT(Q1, Q2)
-- Implement saving mechanism if necessary
end
-- Convert action index to movement and rotation
function Util.actionToMovement(action)
if action == 1 then
return Vector3.new(0, 0, -1), 0 -- Move Forward
elseif action == 2 then
return Vector3.new(0, 0, 1), 0 -- Move Backward
elseif action == 3 then
return Vector3.new(0, 0, 0), 1 -- Turn Left
elseif action == 4 then
return Vector3.new(0, 0, 0), -1 -- Turn Right
elseif action == 5 then
return Vector3.new(0, 0, 0), 0 -- Attack
end
return Vector3.new(0, 0, 0), 0
end
-- ======= Control Class =======
local Control = {}
Control.__index = Control
function Control.new(model, Q1, Q2, epsilon, alpha, gamma)
local self = setmetatable({
model = model,
humanoid = model:FindFirstChildOfClass("Humanoid"),
Q1 = Q1,
Q2 = Q2,
epsilon = epsilon,
alpha = alpha,
gamma = gamma,
state = nil,
target = nil,
reward = -1,
dead = false,
action = nil,
nextState = nil,
}, Control)
-- Initialize health
self.hp = self.humanoid.Health
self.reward = -1
-- Health Changed Connection
self.humanoid.HealthChanged:Connect(function(hp)
if hp <= 0 and not self.dead then
self.dead = true
self.reward = -100
else
self.reward = self.reward - (self.hp - hp)
self.hp = hp
end
end)
return self
end
function Control:setTarget(targetControl)
self.target = targetControl
-- Target Health Changed Connection
self.target.humanoid.HealthChanged:Connect(function(hp)
if hp <= 0 then
self.reward = 100
else
self.reward = self.reward + (self.target.hp - hp)
self.target.hp = hp
end
end)
end
function Control:updateState()
if not self.target then return end
local selfPos = self.model.PrimaryPart.Position
local targetPos = self.target.model.PrimaryPart.Position
local relativePos = targetPos - selfPos
local distance = Util.saturateMag(relativePos.Magnitude)
local angle = math.atan2(relativePos.X, relativePos.Z)
local lookDir = self.model.PrimaryPart.CFrame.LookVector
local lookAngle = math.atan2(lookDir.X, lookDir.Z)
angle = Util.saturateAng(angle)
lookAngle = Util.saturateAng(lookAngle)
self.state = Util.paramsToState(distance, angle, lookAngle)
end
function Control:selectAction()
self.action = Util.chooseAction(self.Q1, self.Q2, self.state, self.epsilon)
end
function Control:performAction()
local movement, rotation = Util.actionToMovement(self.action)
-- Move
if movement.Magnitude > 0 then
self.humanoid:Move(movement, true)
else
self.humanoid:Move(Vector3.new(0,0,0), true)
end
-- Rotate
local cf = self.model.PrimaryPart.CFrame
if rotation ~= 0 then
cf = cf * CFrame.Angles(0, rotation * math.pi / 32, 0)
self.model:SetPrimaryPartCFrame(cf)
end
-- Attack (placeholder)
if self.action == 5 then
self:attack()
end
end
function Control:attack()
if self.target and self.target.humanoid.Health > 0 then
self.target.humanoid:TakeDamage(10) -- Deal 10 damage
end
end
function Control:learn(previousState, previousAction, reward, done)
if done then
-- Terminal state
if math.random() < 0.5 then
-- Update Q1
self.Q1[previousState][previousAction] = self.Q1[previousState][previousAction] + self.alpha * (reward - self.Q1[previousState][previousAction])
else
-- Update Q2
self.Q2[previousState][previousAction] = self.Q2[previousState][previousAction] + self.alpha * (reward - self.Q2[previousState][previousAction])
end
else
-- Select which Q-table to update
if math.random() < 0.5 then
-- Update Q1
local nextBestAction = Util.bestAction(self.Q1, self.Q2, self.nextState)
self.Q1[previousState][previousAction] = self.Q1[previousState][previousAction] + self.alpha * (reward + self.gamma * self.Q2[self.nextState][nextBestAction] - self.Q1[previousState][previousAction])
else
-- Update Q2
local nextBestAction = Util.bestAction(self.Q1, self.Q2, self.nextState)
self.Q2[previousState][previousAction] = self.Q2[previousState][previousAction] + self.alpha * (reward + self.gamma * self.Q1[self.nextState][nextBestAction] - self.Q2[previousState][previousAction])
end
end
end
-- ======= Bot Creation and Management =======
local Q1, Q2 = Util.loadQT()
local bots = {}
local botPairs = {}
-- Clone AI model from ServerStorage
local aiTemplate = ServerStorage:FindFirstChild("AI")
if not aiTemplate then
error("AI template not found in ServerStorage")
end
-- Create Walls for the Arena
local function createWalls()
for i = -CONFIG.WALL_INTERVAL * 7, CONFIG.WALL_INTERVAL * 7, CONFIG.WALL_INTERVAL do
-- Vertical Walls
local wallX = Instance.new("Part")
wallX.Size = Vector3.new(1, 10, 2048)
wallX.Position = Vector3.new(i, 0, 0)
wallX.Anchored = true
wallX.Transparency = 0.5
wallX.Parent = workspace
-- Horizontal Walls
local wallZ = Instance.new("Part")
wallZ.Size = Vector3.new(2048, 10, 1)
wallZ.Position = Vector3.new(0, 0, i)
wallZ.Anchored = true
wallZ.Transparency = 0.5
wallZ.Parent = workspace
end
end
createWalls()
-- Function to create a new bot
local function createBot(position)
local bot = aiTemplate:Clone()
bot.Parent = workspace
bot:MoveTo(position)
bot.PrimaryPart = bot:FindFirstChild("HumanoidRootPart") or bot:FindFirstChildWhichIsA("BasePart")
return bot
end
-- Initialize Bot Pairs
for i = 1, CONFIG.NUM_BOTS do
local offsetX = (i % 10) * 150 - CONFIG.BOT_START_POS_X
local offsetZ = math.floor((i - 1) / 10) * 150 - CONFIG.BOT_START_POS_Y
local bot1Pos = Vector3.new(offsetX, 0, offsetZ + 10)
local bot2Pos = Vector3.new(offsetX + 10, 0, offsetZ)
local bot1Model = createBot(bot1Pos)
local bot2Model = createBot(bot2Pos)
local control1 = Control.new(bot1Model, Q1, Q2, CONFIG.EPSILON_START, CONFIG.ALPHA, CONFIG.GAMMA)
local control2 = Control.new(bot2Model, Q1, Q2, CONFIG.EPSILON_START, CONFIG.ALPHA, CONFIG.GAMMA)
control1:setTarget(control2)
control2:setTarget(control1)
table.insert(botPairs, {control1, control2})
end
-- ======= Debug UI Setup =======
local ScreenGui, GuiElements = nil, {}
if CONFIG.DEBUG_UI then
ScreenGui = Instance.new("ScreenGui")
ScreenGui.Parent = game:GetService("StarterGui")
ScreenGui.Name = "BotDebugUI"
for d = 1, CONFIG.STATE_BINS_ANG do
GuiElements[d] = {}
for m = 1, CONFIG.STATE_BINS_MAG do
local label = Instance.new("TextLabel")
label.Size = UDim2.new(0, 50, 0, 20)
label.Position = UDim2.new(0, d * 52, 0, m * 22)
label.Text = "0"
label.TextScaled = true
label.BackgroundTransparency = 1
label.Parent = ScreenGui
GuiElements[d][m] = label
end
end
end
-- ======= Main Simulation Loop =======
RunService.Heartbeat:Connect(function(deltaTime)
for _, pair in ipairs(botPairs) do
for _, control in ipairs(pair) do
if not control.dead then
-- Update state
control:updateState()
-- Select and perform action
local previousState = control.state
control:selectAction()
control:performAction()
-- Placeholder for environment step, can be expanded
local reward = control.reward
local done = control.dead
-- Update Q-tables
control:learn(previousState, control.action, reward, done)
-- Decay epsilon
control.epsilon = math.max(CONFIG.EPSILON_MIN, control.epsilon - CONFIG.EPSILON_DECAY)
end
end
end
-- Handle Dead Bots and Respawn
for i, pair in ipairs(botPairs) do
local control1, control2 = pair[1], pair[2]
if control1.dead or control2.dead then
if control1.dead then
control1.model:Destroy()
end
if control2.dead then
control2.model:Destroy()
end
-- Respawn new bots
local offsetX = (i % 10) * 150 - CONFIG.BOT_START_POS_X
local offsetZ = math.floor((i - 1) / 10) * 150 - CONFIG.BOT_START_POS_Y
local bot1Pos = Vector3.new(offsetX, 0, offsetZ + 10)
local bot2Pos = Vector3.new(offsetX + 10, 0, offsetZ)
local newBot1Model = createBot(bot1Pos)
local newBot2Model = createBot(bot2Pos)
local newControl1 = Control.new(newBot1Model, Q1, Q2, CONFIG.EPSILON_START, CONFIG.ALPHA, CONFIG.GAMMA)
local newControl2 = Control.new(newBot2Model, Q1, Q2, CONFIG.EPSILON_START, CONFIG.ALPHA, CONFIG.GAMMA)
newControl1:setTarget(newControl2)
newControl2:setTarget(newControl1)
botPairs[i] = {newControl1, newControl2}
end
end
-- Update Debug UI
if CONFIG.DEBUG_UI then
for d = 1, CONFIG.STATE_BINS_ANG do
for m = 1, CONFIG.STATE_BINS_MAG do
local state = Util.paramsToState(m / CONFIG.STATE_BINS_MAG * CONFIG.STATE_BINS_MAG,
d / CONFIG.STATE_BINS_ANG * 2 * math.pi,
0) -- Ignoring look angle for simplicity
local qValue = Q1[state][1] + Q2[state][1] -- Example for first action
GuiElements[d][m].Text = string.format("%.1f", qValue)
end
end
end
end)
-- ======= Save Q-Tables on Server Shutdown =======
-- Optional: Implement saving Q-tables if persistent learning is desired
game:BindToClose(function()
Util.saveQT(Q1, Q2)
end)
Explanation of the Script
Configuration Parameters (CONFIG):
Defines various parameters such as the number of bots, learning rates (alpha, gamma), exploration parameters (epsilon), and state discretization bins.
Utility Functions (Util):
State Representation: Converts continuous state parameters (magnitude, angle, look angle) into discrete states using binning.
Double Q-Learning: Initializes two separate Q-tables (Q1 and Q2) to mitigate overestimation bias. Actions are chosen using an epsilon-greedy policy based on the combined Q-values from both tables.
Action Mapping: Maps discrete action indices to actual movements and rotations within the game.
Control Class (Control):
Represents each bot's control logic, managing state updates, action selection, performing actions, and learning from rewards.
Double Q-Learning Integration: Updates either Q1 or Q2 based on a 50% chance during each learning step, utilizing the separate tables for action selection and evaluation.
Health Management: Monitors health changes to assign rewards or penalties appropriately.
Bot Creation and Management:
Clones a pre-existing AI model from ServerStorage. Ensure that an AI model with a Humanoid and HumanoidRootPart exists in ServerStorage named "AI".
Creates a pair of bots for each entry in botPairs, assigning each bot to target the other.
Implements respawning logic for deceased bots to maintain continuous simulation.
Environment Setup:
Creates walls in the workspace to define the battle arena boundaries.
Debug UI:
Optionally displays a debug UI showing Q-values for different states, aiding in monitoring the learning process.
Main Simulation Loop:
Runs on each Heartbeat event, updating each bot's state, selecting and performing actions, learning from rewards, and decaying the exploration rate ().
Setup Instructions
AI Model Setup:
Create an AI model with a Humanoid and HumanoidRootPart (or equivalent base part) in ServerStorage and name it "AI".
Ensure the AI model has necessary components for movement and combat.
Script Placement:
Place the AdvancedSwordBotAI.lua script in ServerScriptService or another appropriate server-side location.
Adjust Configuration:
Modify the CONFIG table at the beginning of the script to suit your game's environment and desired behavior.
Run the Game:
Start the game to see the bots engage in combat within the defined arena. The debug UI will display Q-values if enabled.
Enhancements and Considerations
Persistent Learning: Implement saving and loading of Q-tables to retain learning across game sessions.
State Representation: Currently uses simple binning for state discretization. For more complex environments, consider more sophisticated state representations or function approximation techniques.
Action Space Expansion: The action set can be expanded with more nuanced movements and combat actions.
Reward Shaping: Further refine the reward system to encourage desired behaviors, such as strategic attacking or retreating.
Performance Optimization: Monitor the performance impact of a large number of bots and optimize the script as necessary.
Safety and Fairness: Ensure bots behave fairly and do not disrupt the game's intended experience. Adjust learning rates and exploration parameters to maintain balanced gameplay.
This advanced AI should provide more stable and effective learning behavior for your Roblox sword bots, enhancing their combat capabilities through improved reinforcement learning techniques.