I am working on a program with classes and a main function. This game involves tanks moving around a grid of defined size, and shooting at each other. Each tank has a name, armour and firepower. On the grid, there are randomly generated squares that contain extra armour or firepower. The user inputs how many squares and how much extra they want them to contain at the start of the game. The tanks move according to random direction with a dice roll each round. So whatever random number is generated is how many spaces the tank will move in a random direction. If the grid size is 10 for example, and a tank is at (8,1) and is told to move 3 steps to the right, it must bounce back so that it end up at (9,1). If two tanks land on the same square, then each will have their armour decreased by the others firewpower. When a tank has no armour left, it dies. When there is only 1 tank remaining, the game is over.
For this I have created a grid and tank class. I am unsure how to write the main program. This is what I have done so far:

Grid class:

from random import randint


class Grid(object):
    """ Grid is a playing field for tanks. It stores the size and the special squares """

    def __init__(self, maxx = 4, bonusA = 2, bonusF = 4, bonusAmt = 5):
        """ Constructor - set size and special squares """
        self.max = maxx

        # set special squares
        self.bonusSquares = []
        tempLocations = []
        
        # set bonus armour squares
        if bonusA:
            for x in xrange(bonusA):
                loc = randint(-self.max, self.max), randint(-self.max, self.max)
                while loc in tempLocations:
                    loc = randint(-self.max, self.max), randint(-self.max, self.max)
                square = loc, "A", bonusAmt
                self.bonusSquares.append(square)
                tempLocations.append(loc)
                
        # set bonus firepower squares
        if bonusF:
            for x in xrange(bonusF):
                loc = randint(-self.max, self.max), randint(-self.max, self.max)
                while loc in tempLocations:
                    loc = randint(-self.max, self.max), randint(-self.max, self.max)
                square = loc, "F", bonusAmt
                self.bonusSquares.append(square)
                tempLocations.append(loc)

    def __str__(self):
        squaresInfo = ""
        for square in self.bonusSquares:
            squaresInfo += "+" + str(square[2])
            if square[1] == "F":
                squaresInfo += " firepower at "
            else:
                squaresInfo += " armour at "
            squaresInfo += str(square[0]) + ", "
        string = "Maximum dimension: " + str(self.max) + " (width & height are " + str(self.max * 2) \
               + ")\nBonus Squares: " + squaresInfo
        return string[:-2]

    def getMax(self):
        return self.max

    def getSquare(self, loc):
        """ return a single square item given its location """
        if self.getLocation == loc:
            return bonusA, bonusF, bonusAmt

    def landOnBonus(self, loc):
        """ Bonus has been landed on so remove it from list, checked by location """
        for square in self.bonusSquares:
            if square[0] == loc:
                self.bonusSquares.remove(square)

    def getBonusLocations(self):
        """ Return a list of just the locations of the bonus squares """
        locations = []
        for square in self.bonusSquares:
            locations.append(square[0])
        return locations

Tank class:

from random import randint

class Tank(object):
    """Tank stores all the mathods to modify the properties of the tanks"""
    
    def __init__(self, n="", a=10, f=5):
        """Constructor- sets default values for properties"""
        self.x = 0
        self.y = 0
        self.a = a
        self.f = f
        self.n = n

    #Print the tanks properties                                                           
    def __str__(self):
        return "xpos: " + self.x + "ypos: " + self.y + "armour: " + self.a + "firepower: " + self._f

    #Return armour value
    def getArmour(self):
        return self.a

    #Return firepower value
    def getFirepower(self):
        return self.f

    #Return the location as a tuple
    def getLocation(self):
        return self.x, self.y

    #Return name
    def getName(self):
        return self.n

    #Return the X coordinate
    def getX(self):
        return self.x

    #Return the Y coordinate
    def getY(self):
        return self.y

    #Increase the armour value by the amount
    def increaseArmour(self, amount):
        self.a += amount

    #Increase the firepower value by the amount
    def increaseFirepower(self, amount):
        self.f += amount

    #Check if tank is at location loc, return True or False accordingly
    def isAt(self, loc):
        return self.getLocation == loc

    #Moves tanks keeping it inside the grid maximum passed in
    def move(self, direction, amount, gridmax):
        diceRoll = random.randint(1,7)
        directionNumber = random.randrange(1,5)
        directions = {1:"up", 2: "down", 3: "left", 4: "right"}
        theDirection = directions[directionNumber]
        return diceRoll
        return theDirection

    #Decrease the armour value by the amount 
    def reduceArmour(self, amount):
        self.a -= amount
        if self.a < 1:
            print ":(", self.n, "is gone :("

    #Decrease the firepower value by the amount
    def reduceFirepower(self, amount):
        self.firepower -= amount

    #Set armour value            
    def setArmour(self, a):
        self.a = a

    #Set firepower value        
    def setFirepower(self, f):
        self.f = f

    #Set x coordinate        
    def setX(self, x):
        self.x = x

    #Set y coordinate
    def setY(self, y):
        self.y = y

What I have done of the main function (just don't really know what to do):

from grid import Grid
from tank import Tank
import random


t1 = Tank("Meanie", 12, 7)
t2 = Tank("CP1200", 80, 5)
t3 = Tank("Wimpy", 1, 2)
tanks = [t1, t2, t3]


playingDimensions = input("Max dimension for playing field: ")
noBonusArmourSquares = input("Number of bonus armour squares: ")
noBonusFirepowerSquares = input("Number of bonus firepower squares: ")
amountBonus = input("Amount of bonus: ")
widthHeight = playingDimensions * 2 + 1
print "The setup:"
print "Maximum dimension:", playingDimensions, "(width and height are " + str(widthHeight) + ")"
print "Bonus squares:", "+" + str(amountBonus) + " armour at", 
print "+" + str(amountBonus) + " firepower at"
print "Let's ""Play..."""


#Grid.getBonusLocations()

def deadOrAlive(self):
    if self.a < 1:
        print ":(", self.n, "is gone :("
        tanks.remove(self)

def moveTanks():
    for i in range(len(tanks)):
        diceRoll.append(theDice.roll())
        theDirection.append(theDir.randomDir())
        if theDirection[i] == "up":
            tanks[i].set_y(diceRoll[i])
        elif theDirection[i] == "down":
            tanks[i].set._y(-diceRoll[i])
        elif theDirection[i] == "right":
            tanks[i].set_x(diceRoll[i])
        elif theDirection[i] == "left":
            tanks[i].set_x(-diceRoll[i])

def determineCoords():
    for i in range(len(tanks)):
        if tanks[i].getx() > gridSize:
            tanks[i].x = 2 * gridSize - tanks[i].x
        elif tanks[i].getx() < -gridSize:
            tanks[i].x = -2 * gridSize - tanks[i].x
        elif tanks[i].getY() > gridSize:
            tanks[i].y = 2 * gridSize - tanks[i].y
        elif tanks[i].getY() < - gridSize:
            tanks[i].y = -2 * gridSize - tanks[i].y

def doSpecials():
    for i in range(len(tanks)):
        if tanks[i].getx() == Grid.bonusSquares() and tanks[i].get.y() == Grid.bonusSquares():
            tanks[i].set_a(10)

        if tanks[i].getx() == Grid.bonusSquares() and tanks[i].get.y() == Grid.bonusSquares():
            tanks[i].set.f

def doBattle():
    isBattle = 0
    theCoords = []
    for i in range(len(tanks)):
        theCoords.append([tanks[i].x, tanks[i].y])
        i = 0
        x = 0
        battleLocation = []
        tanksInvolved = []
        for tank in tanks:
            pos = i
            theCoords[pos] = ""
            i += 1
            for coord in theCoords:
                if tank.Coords() == coord:
                    battleLocation.append(tank.Coords())
                    Tank.setArmour(-tanks[x].f)
                    
                x += 1
                if x == len(tanks):
                    x = 0
                    theCoords[pos] = tank.Coords()
                    break
        #Remove duplicates from battle location list
        fighting = []
        while battleLocation != []:
            item = battleLocation.pop(0)
            if item not in fighting:
                fighting.append(item)
        for cord in fighting:
            print "- Battle! -", self.n, self.n, "are fighting"
        return isBattle


def gameOver():
    if len(tanks) <= 1:
        print "After", rounds, "rounds, and", noBattles, "battles, the winner is...\n", tanks

def main():

    noBattles = 0
    #diceRoll = Die()
    #theDirections = Direction()

    while len(tanks) >= 2:
        moveTanks()
        determineCoords()
        doSpecials()
        doBattle()
        battle = theBattle()
        noBattles += 1
        deadCheck()
        gameOver()

gridSize = playingDimensions

main(

Thank you

In python there is not main program, but the code in highest indention level is executed when code is loaded. To stop modules main code to run you can put if __name__ == 'main': in beginning of that code.

For object oriented program main program would generally be used to create the objects, take in the input from user, handle the exit from program (in case of text based program, gui application calls qui mainloop).

You can also include there testing code if your code is module for other programs. See for example turtle.py from library.

It is an object oriented main program I am trying to do, however, I'm just not sure how to go about it, and how to acctually construct the program using the classes.

Generally you would save the following three code files in the same directory:
class Tank as tank.py
class Grid as grid.py
your main code as tank_game.py
then run tank_game

Note that filenames for modules tank and grid are case sensitive!

if __name__ == "__main__":
      noBattles = 0
      #diceRoll = Die()
      #theDirections = Direction()
      moveTanks()
      determineCoords()
      doSpecials()
      doBattle()
      battle = theBattle()
      noBattles += 1
      deadCheck()
      while len(tanks) < 2:
            gameOver()
            sys.exit()

I hope this can help you

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.