GIDNetwork > More OOP in Python
Register
« Linux on Dell Precision M90 - Part VII: Peripherals ChronoPay Payment Solutions now HACKER SAFE »

More OOP in Python

by: crystalattice - Jun 23, 2006

Here is another Python module I just finished. I'm learning how to use classes and other Object Oriented Programming (OOP) ideas vs. my old way of thinking using functions. At first it was extremely difficult to think in OO ways; the first time I tried to create a character-creator program I got about halfway before I got confused.

This time it went easier, most likely because I revised what was needed for a basic character and designed for that. Plus, I didn't just try to pull over my procedural-based modules and make it work; I rewrote the code in a more OO way and had many fewer errors this time.

(One of the benefits of coding in Python, whether it will be your final code or if you use it to "flesh-out" your ideas before you write it in C++, Java, etc., is that you don't have to wait for a code-compile-debug cycle. The largest parts of this module [attribute generation and skill selection] probably took me 3 hours each to code and troubleshoot. I don't know what the normal "turnaround" for you experienced programmers is, but that's quite an achievement for me. Especially considering I'm learning the language as I go.)

The code below is a complete module for creating a generic character; you just have to have a copy of my dice rolling program to make it work. It's an interactive console program (GUI version coming later) that will let you choose a name, gender and skills and will output your name, gender, age, attributes, hit points, chosen skills, and a generic equipment list.

Because I use the SPE IDE for my coding environment, some of the commented sections may not make sense. SPE uses these special comments to highlight sections, making it easier to mark off areas and jump to sections.

Python Code Example:

######################################################################
#BasicCharacter.py
#
#Purpose:  A revised version of the Marine character using classes.
#Author:  Cody Jackson
#Date:  6/16/06
#
#Copyright 2006 Cody Jackson
#This program is free software; you can redistribute it and/or modify it 
#under the terms of the GNU General Public License as published by the Free 
#Software Foundation; either version 2 of the License, or (at your option) 
#any later version.
#
#This program is distributed in the hope that it will be useful, but 
#WITHOUT ANY WARRANTY; without even the implied warranty of 
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
#General Public License for more details.
#
#You should have received a copy of the GNU General Public License 
#along with this program; if not, write to the Free Software Foundation, 
#Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#----------------------------------------------------------------------
#Version 0.1
#   Initial build
######################################################################

#TODO: make I/O operations (save to file)
from dice_roller import multiDie

class Character:
    def __init__(self):
        """Constructor to initialize each data member to zero."""
        
        #---Personal info
        self.name = ""
        self.gender = ""
        self.age = 0        
        
        #---Attribute info
        self.attrib = 0
        self.attrib_dict = {}
        self.setAttribute("str")
        self.setAttribute("intel")
        self.setAttribute("build")
        self.setAttribute("char")
        self.setAttribute("will")
        self.setAttribute("throw")
        self.setAttribute("mass")
        self.setAttribute("load")
        
        #---Hit point info
        self.hp_dict = {}
        self.body_part = 0
        self.setHitPoints("head")
        self.setHitPoints("torso")
        self.setHitPoints("rarm")
        self.setHitPoints("larm")
        self.setHitPoints("lleg")
        self.setHitPoints("rleg")
        
        #---Skills info
        self.chosenSkills = {}
        self.subskills = {}
        self.skillPoints = 0
        self.skillLevel = 0
        self.skillChoice = 0
        self.maximum = 0
        self.subskillChoices = []
        self.baseSkills = ["Armed Combat", "Unarmed Combat", "Throwing", "Small Arms", 
            "Heavy Weapons", "Vehicle Weapons", "Combat Engineer", "First Aid", 
            "Wheeled Vehicles", "Tracked Vehicles", "Aircraft", "Interrogation", 
            "Swimming", "Reconnaissance", "Mechanic", "Forward Observer", 
            "Indirect Fire", "Electronics", "Computers", "Gunsmith",
            "Supply", "Mountaineering", "Parachute", "Small Boats",
            "Harsh environments", "Xenomorphs", "Navigation", "Stealth",
            "Chemistry", "Biology"]
            
        #---Equipment list
        self.equipment = []
    
#---Get personal info---#008000#FFFFFF------------------------------------------
    def setName(self):
        """Get the name of the character."""
        
        self.name = raw_input("Please enter your character's name.\n")
    
    def setGender(self):
        """Get the gender of the character."""
        
        while 1:
            self.gender = raw_input("Select a gender:  1=Male, 2=Female: ")
            if int(self.gender) == 1:
                self.gender = "Male"
                break
            elif int(self.gender) == 2:
                self.gender = "Female"
                break
            else:
                print "Invalid choice.  Please choose 1 or 2."
                continue

    def setAge(self):
        """Calculate the age of character, between 18 and 45 years old."""
        
        self.age = 15 + multiDie(3,2) #3d10

#---Create attributes---#008000#FFFFFF------------------------------------------
    def setAttribute(self, attr):
        """Generate value for an attribute, between 2 and 20."""
        
        #---Get secondary attributes
        if attr == "throw":
           self.attrib_dict[attr] = self.attrib_dict["str"] * 2    #meters
        elif attr == "mass":
            self.attrib_dict[attr] = (self.attrib_dict["build"] * 5) + 15 #kg
        elif attr == "load":
            self.attrib_dict[attr] = (self.attrib_dict["str"] + 
                self.attrib_dict["build"]) #kg
        #---Get core attributes
        else:
            self.attrib_dict[attr] = multiDie(2, 2)   #2d10 
    
    def setHitPoints(self, body_part):    
        """Generate hit points for each body part, based on 'build' attribute."""
        
        if body_part == "head":
            self.hp_dict[body_part] = self.attrib_dict["build"]
        elif body_part == "torso":
            self.hp_dict[body_part] = self.attrib_dict["build"] * 4
        else:   #arms & legs
            self.hp_dict[body_part] = self.attrib_dict["build"] * 2

#---Choose skills---#008000#FFFFFF----------------------------------------------
    def printSkills(self):
        """Print list of skills available for a character."""
        
        print "Below is a list of available skills for your character."
        print "Some skills may have specializations and will be noted when chosen."
        for i in range(len(self.baseSkills)):
            print "     ", i, self.baseSkills[i],    #5 spaces between columns
            if i % 3 == 0:
                print "\n"

    def setSkills(self):
        """Calculate skill points and pick base skills and levels.
        
        Skill points are randomly determined by dice roll.
        Certain skills have specialty areas available and are chosen separately."""
        
        self.skillPoints = multiDie(2,2) * 10
        while self.skillPoints > 0:
            #---Choose skill
            self.printSkills()
            print "\n\nYou have", self.skillPoints, "skill level points available."
            self.skillChoice = int(raw_input("Please pick a skill: "))
            self.pick = self.baseSkills[self.skillChoice]   #Chosen skill
            print "\nYou chose", self.skillChoice, self.baseSkills[self.skillChoice], "."
            
            #---Determine maximum skill level
            if self.skillPoints > 98:
                self.maximum = 98
            else: self.maximum = self.skillPoints
            
            #---Choose skill level
            print "The maximum points you can use are", self.maximum, "."
            self.skillLevel = int(raw_input("What skill level would you like? "))
            if self.skillLevel > self.skillPoints:  #See if level chosen exceeds points available
                print "Sorry, you don't have that many points."
                continue
            self.chosenSkills[self.pick] = self.skillLevel  #Chosen skill level
            self.skillPoints -= self.skillLevel #Decrement skill points
            #print self.skillPoints, self.chosenSkills   #debug
            
            #---Pick specialty
            if self.skillLevel >= 20:   #Minimum level for a specialty
                self.pickSubSkill(self.pick)
    
    def pickSubSkill(self, skill):
        """If a base skill level is 20 or greater, a specialty may be available,
        depending on the skill.
        
        Chosen skill text string passed in as argument."""
        
        self.skill = skill
        
        #---Set speciality lists
        if self.skill == "Armed Combat":
            self.subskillChoices = ["Blunt Weapons", "Edged Weapons", "Chain Weapons"]
        elif self.skill == "Unarmed Combat":
            self.subskillChoices = ["Grappling", "Pummeling", "Throttling"]
        elif self.skill == "Throwing":
            self.subskillChoices = ["Aerodynamic", "Non-aerodynamic"]
        elif self.skill == "Small Arms":
            self.subskillChoices = ["Flamer", "Pulse Rifle", "Smartgun", "Sniper rifle", "Pistol"]
        elif self.skill == "Heavy Weapons":
            self.subskillChoices = ["PIG", "RPG", "SADAR", "HIMAT", "Remote Sentry"]
        elif self.skill == "Vehicle Weapons":
            self.subskillChoices = ["Aircraft", "Land Vehicles", "Water Vehicles"]
        elif self.skill == "Combat Engineer":
            self.subskillChoices = ["Underwater demolitions", "EOD", "Demolitions", "Land structures",
                "Vehicle use", "Bridges"]
        elif self.skill == "Aircraft":
            self.subskillChoices = ["Dropship", "Conventional", "Helicopter"]
        elif self.skill == "Swimming":
            self.subskillChoices = ["SCUBA", "Snorkel"]
        elif self.skill == "Mechanic":
            self.subskillChoices = ["Wheeled", "Tracked", "Aircraft"]
        elif self.skill == "Electronics":
            self.subskillChoices = ["Radio", "ECM"]
        elif self.skill == "Computers":
            self.subskillChoices = ["Hacking", "Programming"]
        elif self.skill == "Gunsmith":
            self.subskillChoices = ["Small Arms", "Heavy Weapons", "Vehicles"]
        elif self.skill == "Parachute":
            self.subskillChoices = ["HALO", "HAHO"]
        elif self.skill == "Harsh Environments":
            self.subskillChoices = ["No atmosphere", "Non-terra"]
        else:
            return
        
        self.statement(self.skill)
        for i in range(len(self.subskillChoices)):
            print i, self.subskillChoices[i]
        self.choice = int(raw_input())
        if self.choice == -1:   #Specialization not desired
            return
        else:   #Speciality chosen
            print "You chose the", self.subskillChoices[self.choice], "specialty.\n\
It has an initial skill level of 10."
            self.subskills[self.subskillChoices[self.choice]] = 10
        print self.subskills
        return

    def statement(self, skill):
        """Prints a generic statement for choosing a skill specialty."""
        
        self.skill = skill
        print "\n", self.skill, "has specializations.  If you desire to specialize in\
 a field,\nplease choose from the following list.  Enter -1 if you don't want a\n\
specialization.\n"

#---Equipment access methods---#008000#FFFFFF-----------------------------------
    def setEquipment(self, item):
        self.equipment.append(item)
    
    def getEquipment(self):
        print self.equipment
    
def test():
    person = Character()
    person.setName()
    person.setGender()
    person.setAge()
    person.setSkills()
    person.setEquipment("Rucksack")
    person.setEquipment("Knife")
    person.setEquipment("Flashlight")
    print "\nName = ", person.name
    print "Gender = ", person.gender
    print "Age = ", person.age
    for key in person.attrib_dict.keys():
        print key, person.attrib_dict[key]
    for key in person.hp_dict.keys():
        print key, person.hp_dict[key]    
    print person.chosenSkills
    print person.subskills
    person.getEquipment()
    
if __name__ == "__main__":
    test()
Would you like to comment? This story has been viewed 10,015 times.
« Linux on Dell Precision M90 - Part VII: Peripherals ChronoPay Payment Solutions now HACKER SAFE »

__top__

Copyright © GIDNetwork™ 2001 - 2017

Another website by J de Silva

Page generated in : 0.02673 sec.