I’m working on a framework where NPC’s will try to mimic as real players. I’ve decided to do a full rewrite with my system using Composition due to the original one (If I recall correctly, uses inheritance and factory pattern) being all over the place.
The issue is that I don’t know how to implement composition. I’ve tried searching for tutorials going over composition but I’ve only found a handful that, in all honesty, confused me a bit. So I’m asking you on how to use composition for OOP NPC’s.
What I’m looking for is:
A basic overview of composition
An example of using composition general use
An example of using composition with NPC’s.
Sorry if I’m asking too much, but I really want to know how to do so.
Composition is very simply, a class having objects from other classes, instead of inheriting.
If you wanted to use composition for an NPC like thing, it would look something like this:
--// Flying Class
local Flying = {}
Flying.__index = Flying
function Flying.new(flySpeed)
local self = setmetatable({}, Flying)
self.FlySpeed = flySpeed
return self
end
function Flying:getSpeed()
return self.FlySpeed
end
--// NPC class
local NPC = {}
NPC.__index = NPC
function NPC.new()
local self = setmetatable({}, NPC)
self.Flying = Flying.new(100) --/ Composition, NPC has a Flying object instead of inheriting it
return self
end
Then you don’t run into inheritance issues and you could do this hundreds of times for however many modules you would want to create for your npcs.
I’m going to use classes for this one (A Builder and Fighter class respectively). Additionally, how would I handle on making the NPC function? (For example, the Builder class using a function inside of it to build and using a base function to move around.)
I’m a little confused as to what exactly you’re asking, however, if I understood correctly, you can just make the build and move functions as part of the Builder class & the base stuff in a base class. So like
local NPC = {}
NPC.__index = NPC
function NPC.Move()
...
end
function NPC.new()
...
end
...
local Builder = {}
Builder.__index = Builder
function Builder.Build()
...
end
function Builder.new()
return setmetatable({
NPC = NPC.new()
}, Builder)
end
And then something along the lines of
local builder = Builder.new()
...
builder.Build(wall)
builder.NPC.Move(target)
I haven’t dug too deep into oop, so excuse me if I haven’t mentioned a better way to do this.
And this is all just pseudocode anyway.