Skip to content

97. A little note on classes

July 23, 2013

A recent forum post saw a simple explanation of class “inheritance” and “polymorphism” (which sound like something out of biology class). I thought I’d preserve it before it got buried by more posts. Thanks to XanDDemoX for this.

(These are comments on someone’s code).

Viewing in the editor some code appears partly duplicated in places.

Consider, a computer player can do everything a human player can do just the difference is the computer does these things automatically. This is where classes are really useful you could create 3 like so:

Player base class. – has all the common functionality between players like shooting etc.

Player=class()

function Player:init()
end

function Player:setup()
-- get notification of new game
end

function Player:place(ship)
end

function Player:fireat(player,square)
end

function Player:moveStarted()
-- get notification of turn
end
function Player:moveFinished()
-- notify turn finished
end

function Player:touched(touch)
end

HumanPlayer – has all the common functions from Player and uses them with the touched method and would use setup and moveStarted to know when to accept ship placements or moves.

HumanPlayer = class(Player)
function HumanPlayer:init()
    Player.init(self)
end

function HumanPlayer:touched(touch)
     self:place(ship)
     self:fireat(opponent,touchedSquare)
     self:moveFinished()
end

Computer player – still has all the common functions from Player but uses them differently. Ignores touch input, places ships in the setup function and makes moves in the moveStarted function

ComputerPlayer = class(Player)
function ComputerPlayer:init()
     Player.init(self)
end
function ComputerPlayer:setup()
-- choose strategy 
-- place ships
end
function ComputerPlayer:moveStarted()
-- calculate move / best move
--  do move 
self:MoveFinished()
end

This is called inheritance and polymorphism, which you have probably seen mentioned in your extensive reading It allows you to share functionality between different objects by it being “inherited” but also have it do things differently (polymorphism) where needed without having to rewrite potentially lots of code.

Advertisements

From → Programming

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: