0

Hello,everyone.Im doing the same project as Slash12
source:http://www.daniweb.com/forums/thread331507.html

I thought the data structure I constructed is correct but I don't know how to test it until my search function works.
The errors i have now are:
TypeError:__init__() takes exactly 3 arguements(1 given)

for i in range(len(board)) has no len()
TypeError:object of type "NoneType"

Im not sure about line 37 def enqueue(element, queue)
line 203
and the search function

Any advice or feedback is greatly appreciated

from interface import *
import engine


"""
The player module is called by the engine to conduct game play.  You should
not modify the signatures for the init(), shortest_path(), move() 
and last_move() functions.  You are free to implement any other routines or modules.

Author: 
"""

# public routines
class EmptyListNode(object):
    __slots__ = ()

class ListNode(object):
    __slots__ = ( "data","next" )    # the only valid attributes for node

    def __init__(self, dataVal, nextVal=EmptyListNode()):
        """Initialize the node"""
        self.data = dataVal            # the node's element
        self.next = nextVal            # the node's next 

    def __str__(self):
        """Return a string representation of the node"""
        return "Node val: "+ str(self.data)

class Queue(object):
    __slots__ = ( "up", "down","left","right" )
    
    def __init__(self):
        self.up = EmptyListNode()    # The front node in the queue
        self.down = EmptyListNode()        # The back node in the queue
        self.left= EmptyListNode() 
        self.right= EmptyListNode() 
def enqueue(element, queue):
    """Insert an element into the back of the queue"""
    newnode = ListNode(element)
    if empty(queue):
        queue.up = newnode
    elif empty(queue):
        queue.down = newnode
    elif empty(queue):
        queue.left = newnode
    else:
        queue.right = newnode
    
def dequeue(queue):
    """Remove the front element from the queue (returns None)"""
    if empty(queue):
        raise IndexError("dequeue on empty queue") 
    queue.front = queue.front.next
    if empty(queue):
        queue.back = EmptyListNode()
    
def up(queue):
    """Access and return the first element in the queue without removing it"""
    if empty(queue):
        raise IndexError("up on empty queue") 
    return queue.up.data
    
def down(queue):
    """Access and return the last element in the queue without removing it"""
    if empty(queue):
        raise IndexError("down on empty queue") 
    return queue.down.data
def left(queue):
    """Access and return the first element in the queue without removing it"""
    if empty(queue):
        raise IndexError("left on empty queue") 
    return queue.left.data
def right(queue):
    """Access and return the first element in the queue without removing it"""
    if empty(queue):
        raise IndexError("right on empty queue") 
    return queue.right.data
def empty(queue):
    """Is the queue empty?"""
    return isinstance(queue.up, EmptyListNode)



class square(object):
    ___slots___ = ('row', 'column', 'neighbors')
    def __init__(self,row,column,neighbors):
        self.row= row
        self.column= column
        self.neighbors= neighbors
    def __str__(self):
        lst = "(" + str(self.row) + "," + str(self.column) + ") neighbors:" 
        for i in self.neighbors:
            lst = lst + "(" + str(i.row) + "," + str(i.column) + ") "
        print lst
                
class direction(object):
    ___slots___=("up","down","left","right")
    def __init__(self, up,down,left,right):
        self.up=up
        self.down=down
        self.left=left
        self.right=right
        
def findNode(row,column,board):
    ''' returns the node from the graph with the given name. '''
    for n in range(len(board)):
        if board[n].row== board[n].column:
            return board[n] 
class board(object):
    __slots__=('edgeLength','squareList')
    
    def __init__(self,edgeLength,squareList):
        self.edgeLength = edgeLength
        self.squareList = []
        for i in range(0,edgeLength):
            for j in range(0,edgeLength):
                self.squareList.append(square(i,j,[]))
        for current in self.squareList:
            i = current.row
            j = current.column
            if current.row != 0:
                neighbor = self.squareList[(((i-1)*9)+j)]
                current.neighbors.append(neighbor)
            if current.row < (edgeLength-1):
                neighbor = self.squareList[(((i+1)*9)+j)]
                current.neighbors.append(neighbor)
            if current.column != 0:
                neighbor = self.squareList[(i*9 + (j-1))]
                current.neighbors.append(neighbor)
            if current.column < (edgeLength-1 ):
                neighbor = self.squareList[(i*9 + (j+1))]
                current.neighbors.append(neighbor)       

    def loadboard(gameFile):
        for line in open(gameFile):
            contents = line.split()
            row1 = int(contents[0])
            column1 = int(contents[1])
            row2 = int(contents[2])
            column2 = int(contents[3])
        
        
            if column1 == column2:
                #vertical wall
                leftSquare = findNode(row1,column1 - 1,board)
                rightSquare = findNode(row1,column1,board)
                lowleft = findNode(row2 - 1,column2-1,board)
                lowright = findNode(row2 - 1,column2,board)
                for i in range(len(lSquare.neighbors)):
                    if leftSquare.neighbors[i] == rightSquare:
                        leftSquare.neighbors.remove[i]
                        
                for i in range(len(rightSquare.neighbors)):
                    if rightSquare.neighbors[i] == lSquare:
                        rightSquare.neighbors.remove[i]
                    
                for i in range(len(lowleft.neighbors)):
                    if lowleft.neighbors[i] == lowright:
                        lowleft.neighbors.remove[i]
                        
                for i in range(len(lowright.neighbors)):
                    if lowright.neighbors[i] == lowleft:
                        lowright.neighbors.remove[i]
            elif row1 == row2:
                #horizontal wall
                leftUpper = findNode(row1 - 1,column1,board)
                leftLower = findNode(row1,column1,board)
                rightUpper = findNode(row2 - 1,column2 - 1,board)
                rightLower = findNode(row2,column2 - 1,board)
                for i in range(len(leftUpper.neighbors)):
                    if leftUpper.neighbors[i] == leftLower:
                        leftUpper.neighbors.remove[i]
                for i in range(len(leftLower.neighbors)):
                    if leftLower.neighbors[i] == leftUpper:
                        leftLower.neighbors.remove[i]
                        
                for i in range(len(rightUpper.neighbors)):
                    if rightUpper.neighbors[i] == rightLower:
                        rightUpper.neighbors.remove[i]
                for i in range(len(rightLower.neighbors)):
                    if rightLower.neighbors[i] == rightUpper:
                        rightLower.neighbors.remove[i]
                    
        return board
    

def init(gameFile, playerId, numPlayers, playerHomes, wallsRemaining):
    """
    For all parts the engine calls this method so the player can initialize their data.
        gameFile - a string which is the file containing the initial board state.
        playerId - the numeric Id of the player (0-4).
        numPlayers - the number of players (2 or 4).
        playerHomes - a list of coordinates for each players starting cell (PO-P4).
        wallsRemaining - the number of walls remaining (same for all players at start).
    """

    # log any message string to standard output and the current log file
    engine.log_msg("player.init called for player " + str(playerId) + " File=" + gameFile +
                   ', playerId=' + str(playerId) + ', numPlayers=' + str(numPlayers) + ', playerHomes=' +
                   str(playerHomes) + ', wallsRemaining=' + str(wallsRemaining))
   
    playerData=board()
    playerData.loadGrah(gameFile,playerId, numPlayers, playerHomes, wallsRemaining)
    


    # initialize your data structure here, and then return it.  It will be
    # passed back to you as 'playerData' in the shortest_path function.

    return playerData

def shortest_path(playerData, source, dest):
    """Returns a list of coordinates representing the shortest path on the
    board between the start and finish coordinates.
        playerData - The player's data
        source - the start coordinate
        dest - the end coordinate
    """
    
    engine.log_msg("player.shortest_path called.  Source: " + str(source) + 
                   ", Dest: " + str(dest))
    source=findNode(source[0],source[1],playerData)
    dest=findNode(dest[0],dest[1],playerData)
    open=Queue()
    closed=Queue()
    open.enqueue(source)
    path = []
    while not empty(que):
        current = front(que)
        dequeue(que)
        if current == dest:
            break
        for neighbor in current.neighbors:
            if neighbor not in visited:
                neigbhor.previous = current
                visited.append(neighbor)
                enqueue(neighbor,que)
        return constructPath(visited, source, destination)

            
    def constructPath(visited, source, destination):
        if destination in visted:
            temp = destination
        while temp!= source:
            path.insert(0,temp)
            tmp = tmp.previous
        path.insert(0,source)

    return path

Edited by newbieha: n/a

3
Contributors
5
Replies
6
Views
6 Years
Discussion Span
Last Post by richieking
0

is it okay that i make a loadBoard function inside class and call it ?

playerData=board()
playerData.loadBoard(gameFile,playerId, numPlayers, playerHomes, wallsRemaining)

0

we can use everything. can anyone test my data structure. i dont know what wrong with it

0

Better first to use standard tested data structure. Your class is strange as it has no methods but is used only as structure by module functions. Also I do not understand where comes value of que. And open is poor variable name.

Edited by pyTony: n/a

0

#
def enqueue(element, queue):

"""Insert an element into the back of the queue"""

newnode = ListNode(element)

if empty(queue):

queue.up = newnode

elif empty(queue):

queue.down = newnode

elif empty(queue):

queue.left = newnode

else:

queue.right = newnode

What is the logic here? Very redundant method i see.
Besides you do not have a proper class grip hence data are not called and sync'ed well. Please break your codes into parts and repost them one after other as i like running away from 50 lines of code at one go.
;)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.