[Tutor] OOP Advice
JRicker
joejava@dragoncat.net
Tue, 6 Mar 2001 19:15:00 -0500
I'm writing my first python object oriented program. I'm hoping to get
some advice as to if I'm going in the right direction The actual
program I'm donig is a space combat simulator of some sort to be either
web based or client/server of some sort of another. Right now I'm
working on the basic units of each ship and moving them around whatnot.
I've got this basic classes:
class Unit:
"""
Base class of units. Should not be used only inherited from
"""
XPos = -1 #x location of unit, -1 not on game board
YPos = -1 #y loaction of unit, -1 not on game board
def Location(self):
return (self.XPos, self.YPos)
def RangeToTarget(self,other):
return Range(self.XPos, self.YPos, \
other.XPos, other.YPos)
def ChangeFacing(self, d):
if d == -1:
if self.Facing == 1:
self.Facing = 6
else: self.Facing = self.Facing - 1
if d == 1:
if self.Facing == 6:
self.Facing = 1
else: self.Facing = self.Facing + 1
def ReportFacing(self):
if hasattr(self, "Facing"):
return self.Facing
else: return 0
def Move(self):
if self.Facing == 1:
self.YPos = self.YPos - 1
if self.Facing == 2:
self.XPos = self.XPos + 1
if self.Facing == 3:
self.XPos = self.XPos + 1
self.YPos = self.YPos + 1
if self.Facing == 4:
self.YPos = self.YPos + 1
if self.Facing == 5:
self.XPos = self.XPos - 1
self.YPos = self.YPos + 1
if self.Facing == 6:
self.XPos = self.XPos - 1
class Ship(Unit):
"""
Ship class. Derives from Unit class.
"""
shipdata = {}
def __init__(self, x, y, f):
self.Report = Logger(sys.stdout)
self.Facing = f
self.XPos = x
self.YPos = y
class Shuttle(Unit):
def __init__(self,x,y,f):
pass
Now my question primarily is around how the init can be handled. Ships
and Shuttles would be very similar. Each has a speed, a heading (which
is what the f is in the init), a hex position, plus lots of other things
like weapons, size, turn mode (how many hexes a unit has to move before
it can turn), etc. The main difference between a ship and a shuttle is
when it comes to protection. A ship will have large shields, which a
shield on each side of a ship while the shuttle may not have any at all,
maybe a certain number of armor points that would be depleted before the
shuttle was destroyed. Also a shuttle wouldn't have a shuttle bay that
can launch shuttles like a ship would.
My question is this, Is there a way to set up the init function in unit
to handle most of the initialization of the object and the rest done by
the object? How do I structure things so that Unit is doing most of the
work?
Probably not the most exact question in the world but I'm still having
some hangups about object orientedness programs. Thanks for any help
Joel