I have written some code in Python for a tanks game and I need to write pseudocode for the Tank's move method and main game functions (battle and bonuses). What is bold and underline are what I need to do pseudocode for in the quoted text. I know what pseudocode is, just having trouble writing it out.

You need to show good evidence of planning – in one separate file (Word, PDF, text file), that includes pseudocode for the more advanced parts like the main game functions (battle, bonuses) and the Tank’s move method. It is not necessary to show planning for trivial methods like getters and setters.

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.armour < 1:
        print ":(", self.name, "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.name, self.name, "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()
from random import randint

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

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

    def getArmour(self):
        """Return armour value"""
        return self.armour

    def getFirepower(self):
        """Return firepower value"""
        return self.firepower

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

    def getName(self):
        """Return name"""
        return self.name

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

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

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

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

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

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

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

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

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

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

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

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


                        #############
                        ## Testing ##
                        #############

#Setting the variables for Tank class testing
name = "test"
armour = 20
firepower = 10
amount = 5
diceRoll = 4
gridmin = 2
gridmax = 10
move = 2
x = 3
y = 3

print "Testing __init__ .....",
testTank = Tank(name, armour, firepower)
print "Success"

print "Testing __str__ ....."
tankStr = testTank
print "Success"
print "printing tank info: "
print tankStr

print "Testing getArmour .....",
if testTank.getArmour() == armour: #We can test expected outcome
    print "Success"
else:
    print "Failed"

print "Testing getFirepower .....",
if testTank.getFirepower() == firepower:
    print "Success"
else:
    print "Failed"

print "Testing getLocation .....",
if testTank.getLocation() == (0,0):
    print "Success"
else:
    print "Failed"

print "Testing getName .....",
if testTank.getName() == name:
    print "Success"
else:
    print "Failed"

print "Testing getX .....",
if testTank.getX() == 0:
    print "Success"
else:
    print "Failed"

print "Testing getY .....",
if testTank.getY() == 0:
    print "Success"
else:
    print "Failed"

print "Testing increaseArmour .....",
testTank.increaseArmour(amount)
armour += amount #increase expected result
if testTank.getArmour() == armour:
    print "Success"
else:
    print "Failed"

print "Testing increaseFirepower .....",
testTank.increaseFirepower(amount)
firepower += amount #increase expected result
if testTank.getFirepower() == firepower:
    print "Success"
else:
    print "Failed"

print "Testing isAt .....",
if testTank.isAt((0,0)):
    print "Success"
else:
    print "Failed"

print "Testing move .....",
testTank.move("up", diceRoll, gridmin, gridmax)
if testTank.move == move:
    print "Success"
else:
    print "Failed"

print "Testing reduceArmour .....",
testTank.reduceArmour(amount)
armour -= amount
if testTank.getArmour() == armour:
    print "Success"
else:
    print "Failed"

print "Testing reduceFirepower .....",
testTank.reduceFirepower(amount)
firepower -= amount
if testTank.getFirepower() == firepower:
    print "Success"
else:
    print "Failed"

print "Testing setArmour .....",
testTank.setArmour(armour)
armour == armour
if testTank.getArmour() == armour:
    print "Success"
else:
    print "Failed"

print "Testing setX .....",
if testTank.getX() == x:
    print "Success"
else:
    print "Failed"

print "Testing setY .....",
if testTank.getY() == y:
    print "Success"
else:
    print "Failed"

Recommended Answers

All 6 Replies

You did not get rid of those un-Pythonic getters and setters.

some pseudo-code:

For each pixel on the screen do:
{
  x0 = x co-ordinate of pixel
  y0 = y co-ordinate of pixel

  x = 0
  y = 0

  iteration = 0
  max_iteration = 1000

  while ( x*x + y*y <= (2*2)  AND  iteration < max_iteration )
  {
    xtemp = x*x - y*y + x0
    y = 2*x*y + y0

    x = xtemp

    iteration = iteration + 1
  }

  if ( iteration == max_iteration )
  then
    color = black
  else
    color = iteration

  plot(x0,y0,color)
}

This is to generate Mandelbrot set.

You did not get rid of those un-Pythonic getters and setters.

Yea, it would be doing us a favor if you removed them. They are quite painful to my eyes.

That is how it has to be done, I asked yesterday and was told it had to be done that way. Unless you can help me then please don't post

That is how it has to be done, I asked yesterday and was told it had to be done that way. Unless you can help me then please don't post

I guess your teacher isn't a Pythonista, then.
Probably came from a Java background.
If I had a teacher like that, I'd write code like:

class AutoGetters(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __getattr__(self, name):
        if name.startswith("get"):
            name = name[3].lower() + name[4:]
            if hasattr(self, name):
                val = getattr(self, name)
                return lambda: val
            raise AttributeError("Value {0} not found.".format(name))
        raise AttributeError("Attribute {0} not found.".format(name))

a = AutoGetters(1,2)
print a.getX()  #returns 1
print a.getY()  #returns 2

...in order to defend the essential Python idioms and guiding principles.
(and also to brag a little bit :))


Anyways, I'll answer your question.
To write pseudocode, just translate the code you already written into something more English-like.

for_each i in range(len(tanks)) dothis
    additem theDice.roll() to diceRoll
    additem theDir.randomDir() to theDirection
    if theDirection[i] equals "up" do this
        set the y of tanks[i] to diceRoll[i]
    #.. and continue something like that

This is a terrible assignment from a naive teacher in my opinion. Python's code is normally readable enough to not need any pseudocode representation.

This particular subject actually used to be C++ and they changed it this year to Python on the basis that it was easier to learn and when transitioning from Python to say Java or C++ that it would be easier. There have being a lot of complaints about it, a good majority of the rest of the class wanted to know why C++, C# or C wasn't being taught. The problem with the lecturers is that they have to lecture multiple subjects, so they are above average at those subjects and not focusing on one subject where they really focus on it.

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.