I am in the middle of hacking together a rogue-like game in OCaml for
fun and to get a better feel for the language, and I have come across a
stumbling block. Specifically I began to model items in the game as
objects deriving from a base item class. All well and good until I
tried to come up with a way to model a container (like a backpack, or
sack). The container itself was an item, that could hold other items -
including, possibly, other containers.
Some brief dabbling led me to the idea that I could store the items in
the container in a list using a variant type to differentiate the
specific types of items - but I can't for the life of me think how to
add containers to that type list without having defined containers
first. I've included the simple code below so that hopefully some smart
person can point out how dumb I'm being. ;)
-David
class virtual item =
object (self)
val mutable name = ""
method name = name
method set_name newname = name <- newname
end
;;
class weapon =
object (self)
inherit item
end
;;
class container =
object (self)
inherit item
val mutable items = []
method add newitem = items <- (newitem :: items)
method contents = items
method remove i = items <- List.filter (fun x -> x != i) items
method contents_to_string =
let print_item i =
match i with
| `Weapon w -> Printf.sprintf "%s (weapon)" w#name
| `Container c -> Printf.sprintf "%s (container) -
Containing:\n%s" c#name c#contents_to_string
in
List.map print_item items
end
;;