Skip to content

Page362

Procedural and Object-Oriented Languages

Procedural languages (also called procedure-oriented languages) use subroutines, procedures, and functions. Examples include Basic, C, Fortran, and Pascal. Object-oriented languages attempt to model the real world through the use of objects that combine methods and data. Examples include C++, Ruby, and Python; see the “Object-Oriented Design and Programming” section below for more information. A procedural language function is the equivalent of an object-oriented method.

The following code shows the beginning “ram()” function, written in C (a procedural language), from the BSD text-based game Trek.

void 
ram(ix, iy)
int ix, iy;
{
    int i;
    char c;
    printf("\07RED ALERT\07: collision imminent\n");
    c = Sect[ix][iy];
    switch (c)
    {
    case KLINGON:
        printf("%s rams Klingon at %d,%d\n", Ship.shipname, ix, iy);
        killk(ix, iy);
        break;
    case STAR:
    case INHABIT:
        printf("Yeoman Rand: Captain, isn't it getting hot in here?\n");
        sleep(2);
        printf("Spock: Hull temperature approaching 550 Degrees Kelvin.\n");
        lose(L_STAR);
        case BASE:
            printf("You ran into the starbase at %d,%d\n", ix, iy);
            killb(Ship.quadx, Ship.quady);
            /* don't penalize the captain if it wasn't his fault */[2]
    }
}

This ram() function also calls other functions, including killk(), killb(), and lose().

Next is an example of object-oriented Ruby (see http://ruby-lang.org) code for a text adventure game that creates a class called “Verb,” and then creates multiple Verb objects. As we will learn in the “Object-Oriented Design and Programming” section below, an object inherits features from its parent class.

class Verb
    attr_accessor :name, :description
    def initialize(params)
        @name = params[:name]
        @description = params[:description]
    end
end
# Create verbs
north = Verb.new(:name => "Move north", :description => "Player moves to the north")
east = Verb.new(:name => "Move east", :description => "Player moves to the east")
west = Verb.new(:name => "Move west", :description => "Player moves to the west")
south = Verb.new(:name => "Move south", :description => "Player moves to the south")
xyzzy = Verb.new(:name => "Magic word", :description => "Player teleports to another location in the cave")[3]

Note that coding itself is not testable; these examples are given for illustrative purposes.