Help with rat race game

This is the place for queries that don't fit in any of the other categories.

Help with rat race game

Postby SkyKnifer79 » Wed Apr 24, 2013 1:58 pm

How would I make a function that:
Moves the rat unless there is a wall
If there is a brussels sprout eat it and:
Increase the rat's num_sprouts_eaten variable by one
Decrease the maze's num_sprouts_left variable by one
Change the SPROUT to a HALL
Thanks for helping! Here's the code:


Code: Select all
# Constants for the contents of the maze.

# The visual representation of a wall.
WALL = '#'

# The visual representation of a hallway.
HALL = '.'

# The visual representation of a brussels sprout.
SPROUT = '@'

# Constants for the directions. Use these to make Rats move.

# The left direction.
LEFT = -1

# The right direction.
RIGHT = 1

# No change in direction.
NO_CHANGE = 0

# The up direction.
UP = -1

# The down direction.
DOWN = 1

# The letters for rat_1 and rat_2 in the maze.
RAT_1_CHAR = 'J'
RAT_2_CHAR = 'P'


class Rat:
    """ A rat caught in a maze. """

    def __init__(self, symbol, row, col):
        ''' (Rat, str, int, int) -> NoneType

        A rat with symbol, row, column, and number of Brussel Sprouts eaten.
        '''

        self.symbol = symbol
        self.row = row
        self.col = col
        self.num_sprouts_eaten = 0

    def set_location(self, row, col):
        ''' (Rat, int, int) -> NoneType

        Set the rat's row and col instance variables to the given row and column

        >>> rat = Rat('k', 3, 1)
        >>> Rat.set_location(rat, 2, 4)
        >>> rat.row
        2
        >>> rat.col
        4
        '''

        self.row = row
        self.col = col
       
    def eat_sprout(self):
        ''' (Rat) -> NoneType

        Add one to the rats instance variable num_sprouts_eaten.

        >>> r = Rat('k', 4, 5)
        >>> r.num_sprouts_eaten
        0
        >>> Rat.eat_sprout(r)
        >>> r.num_sprouts_eaten
        1
        '''

        self.num_sprouts_eaten = self.num_sprouts_eaten + 1

    def __str__(self):
        ''' (Rat) -> str

        Return a string representation of the rat, in this format: symbol at (row, col) ate num_sprouts_eaten sprouts.

        >>> r = Rat('j', 4, 3)
        >>> str(r)
        'j at (4, 3) ate 0 sprouts.'
        '''
         
        return "{self.symbol} at ({self.row}, {self.col}) ate {self.num_sprouts_eaten} sprouts.".format(self=self)
       
   

class Maze:
    """ A 2D maze. """

    def __init__(self, maze, rat_1, rat_2):
        ''' (Maze, list of list of str, Rat, Rat)

        A rat maze with Brussel Sprouts.
        '''
        self.maze = maze
        self.rat_1 = rat_1
        self.rat_2 = rat_2
        num_sprouts_left = 0
        for lst in maze[:]:
            for ch in lst:
                if ch == SPROUT:
                    num_sprouts_left = num_sprouts_left + 1
        self.num_sprouts_left = num_sprouts_left
   
    def is_wall(self, row, col):
        ''' (Maze, int, int) -> bool

        Check to see if there is a wall at given coordinates.

        >>> maze = Maze([['#', '#', '#', '#', '#', '#', '#'], \
            ['#', '.', '.', '.', '.', '.', '#'], \
            ['#', '.', '#', '#', '#', '.', '#'], \
            ['#', '.', '.', '@', '#', '.', '#'], \
            ['#', '@', '#', '.', '@', '.', '#'], \
            ['#', '#', '#', '#', '#', '#', '#']], \
            Rat('J', 1, 1), \
            Rat('P', 1, 4))
        >>> Maze.is_wall(maze, 0, 0)
        True
        >>> Maze.is_wall(maze, 3, 2)
        False
        '''
        return self.maze[row][col] == WALL

    def get_character(self, row, col):
        ''' (Maze, int, int) -> str

        Return the character in the maze at the given row and column. If there is a rat at that location, then its character is returned.

        >>> maze = Maze([['#', '#', '#', '#', '#', '#', '#'], \
            ['#', '.', '.', '.', '.', '.', '#'], \
            ['#', '.', '#', '#', '#', '.', '#'], \
            ['#', '.', '.', '@', '#', '.', '#'], \
            ['#', '@', '#', '.', '@', '.', '#'], \
            ['#', '#', '#', '#', '#', '#', '#']], \
            Rat('J', 1, 1), \
            Rat('P', 1, 4))
        >>> Maze.get_character(maze, 4, 5)
        'HALL'
        >>> Maze.get_character(maze, 3, 4)
        'WALL'
        >>> Maze.get_character(maze, 3, 3)
        'SPROUT'
        '''

        if self.maze[row][col] == self.rat_1.symbol:
            return self.rat_1.symbol
        elif self.maze[row][col] == self.rat_2.symbol:
            return self.rat_2.symbol
        elif self.maze[row][col] == '.':
            return 'HALL'
        elif self.maze[row][col] == '#':
            return 'WALL'
        elif self.maze[row][col] == '@':
            return 'SPROUT'

    def move(self, rat, ver, hor):
        ''' (Maze, Rat, int, int) -> bool
        Move the rat in the given direction unless, there was a wall in the way.

        >>> maze = Maze([['#', '#', '#', '#', '#', '#', '#'], \
            ['#', '.', '.', '.', '.', '.', '#'], \
            ['#', '.', '#', '#', '#', '.', '#'], \
            ['#', '.', '.', '@', '#', '.', '#'], \
            ['#', '@', '#', '.', '@', '.', '#'], \
            ['#', '#', '#', '#', '#', '#', '#']], \
            Rat('J', 1, 1), \
            Rat('P', 1, 4))
        >>> Maze.move(maze, maze.rat_1, 0, RIGHT)
        True
        >>> Maze.move(maze, maze.rat_2, 0, 0)
        True
        >>> maze.rat_2.num_sprouts_eaten
        1
        >>> maze.num_sprouts_left
        2
        >>>
        '''
        #insert the move code here :)
 
       
                       
                   
           


    def __str__(self):
        """ (Maze) -> str

        Return a string representation of the maze.
        """
       
        return '{self.maze}  {self.rat_1} {self.rat_2}'.format(self=self)
Last edited by SkyKnifer79 on Thu Apr 25, 2013 11:13 am, edited 3 times in total.
SkyKnifer79
 
Posts: 4
Joined: Wed Apr 24, 2013 1:56 pm

Re: Help with rat race game

Postby hansn » Wed Apr 24, 2013 2:59 pm

Isn't that what the move method of the maze class does?
hansn
 
Posts: 87
Joined: Thu Feb 21, 2013 8:46 pm

Re: Help with rat race game

Postby SkyKnifer79 » Wed Apr 24, 2013 6:35 pm

hansn wrote:Isn't that what the move method of the maze class does?

That doesn't work, forgot to remove it
SkyKnifer79
 
Posts: 4
Joined: Wed Apr 24, 2013 1:56 pm

Re: Help with rat race game

Postby hansn » Thu Apr 25, 2013 7:08 am

Why did it not work? Did you get an error you can show us?
hansn
 
Posts: 87
Joined: Thu Feb 21, 2013 8:46 pm

Re: Help with rat race game

Postby Kebap » Thu Apr 25, 2013 9:55 am

SkyKnifer79 wrote:How would I make a function that:
Thanks for helping! Here's the code:

This is a very broad question. Please try and pinpoint to the exact problems you are facing right now, so we can help you there. It would be really good if you can produce some code to demonstrate the problems which does not exceed 10 lines.
Learn: How To Ask Questions The Smart Way
Join the #python-forum IRC channel on irc.freenode.net and chat with uns directly!
Kebap
 
Posts: 403
Joined: Thu Apr 04, 2013 1:17 pm
Location: Germany, Europe

Re: Help with rat race game

Postby Mekire » Thu Apr 25, 2013 10:03 am

Kebap wrote:This is a very broad question

Yeah. It's also a question that I have so far found cut and pasted identically in three different python forums yet he swears it isn't homework.
SkyKnifer79 from Dream in Code wrote:I do not have a teacher, this is a simple game that I am designing myself as a starter.

-Mek
User avatar
Mekire
 
Posts: 1158
Joined: Thu Feb 07, 2013 11:33 pm
Location: Asakusa, Japan

Re: Help with rat race game

Postby metulburr » Thu Apr 25, 2013 10:14 am

Quoting for reference
SkyKnifer79 wrote:Wed Apr 24, 2013 8:58 am

How would I make a function that:
Moves the rat unless there is a wall
If there is a brussels sprout eat it and:
Increase the rat's num_sprouts_eaten variable by one
Decrease the maze's num_sprouts_left variable by one
Change the SPROUT to a HALL
Thanks for helping! Here's the code:


Code: Select all
# Constants for the contents of the maze.

# The visual representation of a wall.
WALL = '#'

# The visual representation of a hallway.
HALL = '.'

# The visual representation of a brussels sprout.
SPROUT = '@'

# Constants for the directions. Use these to make Rats move.

# The left direction.
LEFT = -1

# The right direction.
RIGHT = 1

# No change in direction.
NO_CHANGE = 0

# The up direction.
UP = -1

# The down direction.
DOWN = 1

# The letters for rat_1 and rat_2 in the maze.
RAT_1_CHAR = 'J'
RAT_2_CHAR = 'P'


class Rat:
    """ A rat caught in a maze. """

    def __init__(self, symbol, row, col):
        ''' (Rat, str, int, int) -> NoneType

        A rat with symbol, row, column, and number of Brussel Sprouts eaten.
        '''

        self.symbol = symbol
        self.row = row
        self.col = col
        self.num_sprouts_eaten = 0

    def set_location(self, row, col):
        ''' (Rat, int, int) -> NoneType

        Set the rat's row and col instance variables to the given row and column

        >>> rat = Rat('k', 3, 1)
        >>> Rat.set_location(rat, 2, 4)
        >>> rat.row
        2
        >>> rat.col
        4
        '''

        self.row = row
        self.col = col
       
    def eat_sprout(self):
        ''' (Rat) -> NoneType

        Add one to the rats instance variable num_sprouts_eaten.

        >>> r = Rat('k', 4, 5)
        >>> r.num_sprouts_eaten
        0
        >>> Rat.eat_sprout(r)
        >>> r.num_sprouts_eaten
        1
        '''

        self.num_sprouts_eaten = self.num_sprouts_eaten + 1

    def __str__(self):
        ''' (Rat) -> str

        Return a string representation of the rat, in this format: symbol at (row, col) ate num_sprouts_eaten sprouts.

        >>> r = Rat('j', 4, 3)
        >>> str(r)
        'j at (4, 3) ate 0 sprouts.'
        '''
         
        return "{self.symbol} at ({self.row}, {self.col}) ate {self.num_sprouts_eaten} sprouts.".format(self=self)
       
    # Write your Rat methods here.

class Maze:
    """ A 2D maze. """

    def __init__(self, maze, rat_1, rat_2):
        ''' (Maze, list of list of str, Rat, Rat)

        A rat maze with Brussel Sprouts.
        '''
        self.maze = maze
        self.rat_1 = rat_1
        self.rat_2 = rat_2
        num_sprouts_left = 0
        for lst in maze[:]:
            for ch in lst:
                if ch == SPROUT:
                    num_sprouts_left = num_sprouts_left + 1
        self.num_sprouts_left = num_sprouts_left
   
    def is_wall(self, row, col):
        ''' (Maze, int, int) -> bool

        Check to see if there is a wall at given coordinates.

        >>> maze = Maze([['#', '#', '#', '#', '#', '#', '#'], \
            ['#', '.', '.', '.', '.', '.', '#'], \
            ['#', '.', '#', '#', '#', '.', '#'], \
            ['#', '.', '.', '@', '#', '.', '#'], \
            ['#', '@', '#', '.', '@', '.', '#'], \
            ['#', '#', '#', '#', '#', '#', '#']], \
            Rat('J', 1, 1), \
            Rat('P', 1, 4))
        >>> Maze.is_wall(maze, 0, 0)
        True
        >>> Maze.is_wall(maze, 3, 2)
        False
        '''
        return self.maze[row][col] == WALL

    def get_character(self, row, col):
        ''' (Maze, int, int) -> str

        Return the character in the maze at the given row and column. If there is a rat at that location, then its character is returned.

        >>> maze = Maze([['#', '#', '#', '#', '#', '#', '#'], \
            ['#', '.', '.', '.', '.', '.', '#'], \
            ['#', '.', '#', '#', '#', '.', '#'], \
            ['#', '.', '.', '@', '#', '.', '#'], \
            ['#', '@', '#', '.', '@', '.', '#'], \
            ['#', '#', '#', '#', '#', '#', '#']], \
            Rat('J', 1, 1), \
            Rat('P', 1, 4))
        >>> Maze.get_character(maze, 4, 5)
        'HALL'
        >>> Maze.get_character(maze, 3, 4)
        'WALL'
        >>> Maze.get_character(maze, 3, 3)
        'SPROUT'
        '''

        if self.maze[row][col] == self.rat_1.symbol:
            return self.rat_1.symbol
        elif self.maze[row][col] == self.rat_2.symbol:
            return self.rat_2.symbol
        elif self.maze[row][col] == '.':
            return 'HALL'
        elif self.maze[row][col] == '#':
            return 'WALL'
        elif self.maze[row][col] == '@':
            return 'SPROUT'

    def move(self, rat, ver, hor):
        ''' (Maze, Rat, int, int) -> bool
        Move the rat in the given direction unless, there was a wall in the way.

        >>> maze = Maze([['#', '#', '#', '#', '#', '#', '#'], \
            ['#', '.', '.', '.', '.', '.', '#'], \
            ['#', '.', '#', '#', '#', '.', '#'], \
            ['#', '.', '.', '@', '#', '.', '#'], \
            ['#', '@', '#', '.', '@', '.', '#'], \
            ['#', '#', '#', '#', '#', '#', '#']], \
            Rat('J', 1, 1), \
            Rat('P', 1, 4))
        >>> Maze.move(maze, maze.rat_1, 0, RIGHT)
        True
        >>> Maze.move(maze, maze.rat_2, 0, 0)
        True
        >>> maze.rat_2.num_sprouts_eaten
        1
        >>> maze.num_sprouts_left
        2
        >>>
        '''
        #insert the move code here :)
 
       
                       
                   
           


    def __str__(self):
        """ (Maze) -> str

        Return a string representation of the maze.
        """
       
        return '{self.maze}  {self.rat_1} {self.rat_2}'.format(self=self)
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1576
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Help with rat race game

Postby SkyKnifer79 » Thu Apr 25, 2013 11:10 am

Here's my code so far...
Code: Select all
def move(self, row, col):

if ver == 0 or hor == 0:
            if Maze.is_wall(self, rat.row, rat.col) == False:
                return True
                Rat.set_location(rat, rat.row + ver, rat.col + hor)
                if get_character(self, rat_temp.row, rat_temp.col) == SPROUT: #This is the only part that works properly so far,
                    self.maze[rat.row][rat.col] == 'HALL' # and this
                    self.rat.num_sprouts_eaten += 1     
                    self.num_sprouts_left -= 1

And btw, this isn't homework, but the I do post on other forums so I can get an answer faster.
Thanks for helping!

EDIT: FORGOT TO INDENT THE IF, NOT LIKE THAT IN REAL CODE
SkyKnifer79
 
Posts: 4
Joined: Wed Apr 24, 2013 1:56 pm

Re: Help with rat race game

Postby Mekire » Thu Apr 25, 2013 1:53 pm

When you post code that doesn't work here you need to explain why it didn't work, or how it differed from what you expected. If you are actually getting an error post the traceback. If you can show just a bit more effort then you will get a lot more help (I've already written up a fully working version just to give you a clue). Honestly no one really cares if it is homework as long as we see effort to actually learn. It is the appearance of what looks like an assignment template combined with your lack of effort that is making people not want to offer assistance. Where is the template originally from?

-Mek
User avatar
Mekire
 
Posts: 1158
Joined: Thu Feb 07, 2013 11:33 pm
Location: Asakusa, Japan

Re: Help with rat race game

Postby SkyKnifer79 » Thu Apr 25, 2013 2:15 pm

Mekire wrote:When you post code that doesn't work here you need to explain why it didn't work, or how it differed from what you expected. If you are actually getting an error post the traceback. If you can show just a bit more effort then you will get a lot more help (I've already written up a fully working version just to give you a clue). Honestly no one really cares if it is homework as long as we see effort to actually learn. It is the appearance of what looks like an assignment template combined with your lack of effort that is making people not want to offer assistance. Where is the template originally from?

-Mek




Code: Select all
def move(self, rat, ver, hor):
        ''' (Maze, Rat, int, int) -> bool
        Move the rat in the given direction unless, there was a wall in the way.
        Precondition: ver == -1, 0, or 1, hor == -1, 0, 1
       
        >>> maze = Maze([['#', '#', '#', '#', '#', '#', '#'], \
            ['#', '.', '.', '.', '.', '.', '#'], \
            ['#', '.', '#', '#', '#', '.', '#'], \
            ['#', '.', '.', '@', '#', '.', '#'], \
            ['#', '@', '#', '.', '@', '.', '#'], \
            ['#', '#', '#', '#', '#', '#', '#']], \
            Rat('J', 1, 1), \
            Rat('P', 1, 4))
        >>> Maze.move(maze, maze.rat_1, 0, RIGHT)
        True
        >>> maze.rat_1.row
        1
        >>> maze.rat_1.col
        2
        >>> Maze.move(maze, maze.rat_2, 0, 0)
        True
        >>> maze.rat_2.num_sprouts_eaten
        1
        >>> maze.num_sprouts_left
        2
        >>> maze.maze[maze.rat_2.row][maze.rat_2.col]
        '.'
        '''
        # Variables
       
        # Check if moving is possible
        if ver == 0 or hor == 0:
            if Maze.is_wall(self, rat.row, rat.col) == False:
        # How to make the rat move
                return True
                Rat.set_location(rat, rat.row + ver, rat.col + hor)
        # Change SPROUT to HALL
                if get_character(self, rat_temp.row, rat_temp.col) == SPROUT:
                    self.maze[rat.row][rat.col] == 'HALL'
        # Increase the value of num_sprouts_eaten
                    self.rat.num_sprouts_eaten += 1     
        # Decrease the value of num_sprouts_left
                    self.num_sprouts_left -= 1


OK, I'm using doctest. (BTW I wrote all the comments to make it easier for me)
This is what doctest returns:
Code: Select all
**********************************************************************
File "C:\Python33\a2.py", line 180, in __main__.Maze.move
Failed example:
    maze.rat_1.col
Expected:
    2
Got:
    1
**********************************************************************
File "C:\Python33\a2.py", line 184, in __main__.Maze.move
Failed example:
    maze.rat_2.num_sprouts_eaten
Expected:
    1
Got:
    0
**********************************************************************
File "C:\Python33\a2.py", line 186, in __main__.Maze.move
Failed example:
    maze.num_sprouts_left
Expected:
    2
Got:
    3
**********************************************************************
1 items had failures:
   3 of   8 in __main__.Maze.move
***Test Failed*** 3 failures.


And, I also fixed my get_character method:

Code: Select all
def get_character(self, row, col):
        ''' (Maze, int, int) -> str

        Return the character in the maze at the given row and column. If there is a rat at that location, then its character is returned.

        >>> maze = Maze([['#', '#', '#', '#', '#', '#', '#'], \
            ['#', '.', '.', '.', '.', '.', '#'], \
            ['#', '.', '#', '#', '#', '.', '#'], \
            ['#', '.', '.', '@', '#', '.', '#'], \
            ['#', '@', '#', '.', '@', '.', '#'], \
            ['#', '#', '#', '#', '#', '#', '#']], \
            Rat('J', 1, 1), \
            Rat('P', 1, 4))
        >>> Maze.get_character(maze, 4, 3)
        '.'
        >>> Maze.get_character(maze, 3, 4)
        '#'
        >>> Maze.get_character(maze, 3, 3)
        '@'
        >>> Maze.get_character(maze, 1, 1)
        'J'
        '''

        #Old code: if self.maze[self.rat_1.row][self.rat_1.col] == self.maze[row][col]:
        if self.rat_1.row == row and self.rat_1.col == col:
            return self.rat_1.symbol
        elif self.rat_2.row == row and self.rat_2.col == col:
            return self.rat_2.symbol
        elif self.maze[row][col] == HALL:
            return HALL
        elif self.maze[row][col] == WALL:
            return WALL
        elif self.maze[row][col] == SPROUT:
            return SPROUT


The rat won't actually move, and the sprout isn't eaten, AND the num_sprouts_left variable won't decrease.
I have actually put a lot of effort into this. I have been working on the code for about three weeks, 10 hours a week. I would really like help with this. Here is the original template:

Code: Select all

# Constants for the contents of the maze.

# The visual representation of a wall.
WALL = '#'

# The visual representation of a hallway.
HALL = '.'

# The visual representation of a brussels sprout.
SPROUT = '@'

# Constants for the directions. Use these to make Rats move.

# The left direction.
LEFT = -1

# The right direction.
RIGHT = 1

# No change in direction.
NO_CHANGE = 0

# The up direction.
UP = -1

# The down direction.
DOWN = 1

# The letters for rat_1 and rat_2 in the maze.
RAT_1_CHAR = 'J'
RAT_2_CHAR = 'P'


class Rat:
    """ A rat caught in a maze. """

    # Write your Rat methods here.

class Maze:
    """ A 2D maze. """

    # Write your Maze methods here.
SkyKnifer79
 
Posts: 4
Joined: Wed Apr 24, 2013 1:56 pm

Re: Help with rat race game

Postby Mekire » Fri Apr 26, 2013 2:56 pm

Well go ahead and take a look. No guarantees on quality here. I am sure I would probably do quite a bit differently but I was trying to at least in part preserve your framework.

(code below uses raw_input. Replace all occurrences of it with input if using python 3.)
Code: Select all
from copy import deepcopy

DIRECTDICT = {"LEFT"  : ( 0,-1),
              "RIGHT" : ( 0, 1),
              "UP"    : (-1, 0),
              "DOWN"  : ( 1, 0)}

MAPKEY = {"WALL"  :'#',
          "HALL"  :'.',
          "SPROUT":'@'}

class Rat:
    def __init__(self, symbol,location):
        self.symbol = symbol
        self.loc = list(location)
        self.num_sprouts_eaten = 0
    def eat_sprout(self,Maze):
        self.num_sprouts_eaten += 1
        Maze.num_sprouts_left -= 1
        Maze.maze[self.loc[0]][self.loc[1]] = '.'
    def __str__(self):
        return "Labrat-{self.symbol} at {self.loc} has eaten {self.num_sprouts_eaten} sprouts.".format(self=self)
    def __repr__(self):
        return self.__str__()

class Maze:
    def __init__(self, maze,*rats):
        self.maze = maze
        self.rats = rats
        self.num_sprouts_left = 0
        for row in maze:
            for col in row:
                if col == MAPKEY["SPROUT"]:
                    self.num_sprouts_left += 1
        print(self)

    def is_wall(self, row, col):
        return self.maze[row][col] == MAPKEY["WALL"]
    def is_rat(self,row,col):
        for rat in self.rats:
            if rat.loc == [row,col]:
                return True
        return False

    def move(self,rat,direct):
        for vermin in self.rats:
            if rat == vermin.symbol:
                rat = vermin
                break
        next_loc = [rat.loc[0]+DIRECTDICT[direct][0],rat.loc[1]+DIRECTDICT[direct][1]]
        if not (self.is_wall(*next_loc) or self.is_rat(*next_loc)):
            rat.loc = next_loc
            if self.maze[rat.loc[0]][rat.loc[1]] == MAPKEY["SPROUT"]:
                rat.eat_sprout(self)
        print(self)

    def __str__(self):
        show_maze = deepcopy(self.maze)
        for rat in self.rats:
            show_maze[rat.loc[0]][rat.loc[1]] = rat.symbol
        maze_str = '\n'.join("".join(char for char in row) for row in show_maze)
        rat_str = '\n'.join(r.__str__() for r in self.rats)
        return "{}\n\n{}".format(maze_str,rat_str)
    def __repr__(self):
        return self.__str__()

###
def runit(Maze):
    #A function to make the user experience a little less painful.
    prompts = ["Please select from the list of active rats.",
               "\nRats in maze: {}",
               "Please choose a rat to move: "]
    accepts = [r.symbol for r in Maze.rats]
    rat = repeat_input(prompts,accepts)
    if not rat:
        return 0,0
    prompts = ["Please select a valid direction.",
               "Choose from: {}",
               "Please choose direction: "]
    accepts = [key.upper() for key in DIRECTDICT]
    direc = repeat_input(prompts,accepts)
    print('')
    return rat,direc

def repeat_input(prompt,accepts):
    result = ""
    while result not in accepts:
        if result:
            print(prompt[0])
        print(prompt[1].format(accepts))
        result = raw_input(prompt[2]).upper()
        if not result:
            return 0
    return result

###
if __name__ == "__main__":
    MyMaze = Maze([['#', '#', '#', '#', '#', '#', '#'],
                   ['#', '.', '.', '.', '.', '.', '#'],
                   ['#', '.', '#', '#', '#', '.', '#'],
                   ['#', '.', '.', '@', '#', '.', '#'],
                   ['#', '@', '#', '.', '@', '.', '#'],
                   ['#', '#', '#', '#', '#', '#', '#']],
                   Rat('J', [1,1]),
                   Rat('P', [1,4]),
                   Rat('Q', [4,5]))
    while 1:
        rat,direc = runit(MyMaze)
        if not (rat and direc):
            print("See you next rat race.")
            break
        MyMaze.move(rat,direc)
Giving an empty input at anytime will end the program.
-Mek
User avatar
Mekire
 
Posts: 1158
Joined: Thu Feb 07, 2013 11:33 pm
Location: Asakusa, Japan

Re: Help with rat race game

Postby sf_pythonista » Sat Apr 27, 2013 9:28 pm

This is Assignment #2 from the coursera.org Crafting Quality Code class :). Anyway, thank you Mekire as I was having trouble with this assignment and found your code helpful.
sf_pythonista
 
Posts: 1
Joined: Sat Apr 27, 2013 9:22 pm

Re: Help with rat race game

Postby Kebap » Mon Apr 29, 2013 10:43 am

Thanks for the info sf_pythonista!
sf_pythonista wrote:This is Assignment #2 from the coursera.org Crafting Quality Code class :). Anyway, thank you Mekire as I was having trouble with this assignment and found your code helpful.

Quoted for reference:
SkyKnifer79 wrote:Here's my code so far...
Code: Select all
def move(self, row, col):

if ver == 0 or hor == 0:
            if Maze.is_wall(self, rat.row, rat.col) == False:
                return True
                Rat.set_location(rat, rat.row + ver, rat.col + hor)
                if get_character(self, rat_temp.row, rat_temp.col) == SPROUT: #This is the only part that works properly so far,
                    self.maze[rat.row][rat.col] == 'HALL' # and this
                    self.rat.num_sprouts_eaten += 1     
                    self.num_sprouts_left -= 1

And btw, this isn't homework, but the I do post on other forums so I can get an answer faster.
Thanks for helping!

EDIT: FORGOT TO INDENT THE IF, NOT LIKE THAT IN REAL CODE

SkyKnifer79 wrote:
Mekire wrote:When you post code that doesn't work here you need to explain why it didn't work, or how it differed from what you expected. If you are actually getting an error post the traceback. If you can show just a bit more effort then you will get a lot more help (I've already written up a fully working version just to give you a clue). Honestly no one really cares if it is homework as long as we see effort to actually learn. It is the appearance of what looks like an assignment template combined with your lack of effort that is making people not want to offer assistance. Where is the template originally from?

-Mek




Code: Select all
def move(self, rat, ver, hor):
        ''' (Maze, Rat, int, int) -> bool
        Move the rat in the given direction unless, there was a wall in the way.
        Precondition: ver == -1, 0, or 1, hor == -1, 0, 1
       
        >>> maze = Maze([['#', '#', '#', '#', '#', '#', '#'], \
            ['#', '.', '.', '.', '.', '.', '#'], \
            ['#', '.', '#', '#', '#', '.', '#'], \
            ['#', '.', '.', '@', '#', '.', '#'], \
            ['#', '@', '#', '.', '@', '.', '#'], \
            ['#', '#', '#', '#', '#', '#', '#']], \
            Rat('J', 1, 1), \
            Rat('P', 1, 4))
        >>> Maze.move(maze, maze.rat_1, 0, RIGHT)
        True
        >>> maze.rat_1.row
        1
        >>> maze.rat_1.col
        2
        >>> Maze.move(maze, maze.rat_2, 0, 0)
        True
        >>> maze.rat_2.num_sprouts_eaten
        1
        >>> maze.num_sprouts_left
        2
        >>> maze.maze[maze.rat_2.row][maze.rat_2.col]
        '.'
        '''
        # Variables
       
        # Check if moving is possible
        if ver == 0 or hor == 0:
            if Maze.is_wall(self, rat.row, rat.col) == False:
        # How to make the rat move
                return True
                Rat.set_location(rat, rat.row + ver, rat.col + hor)
        # Change SPROUT to HALL
                if get_character(self, rat_temp.row, rat_temp.col) == SPROUT:
                    self.maze[rat.row][rat.col] == 'HALL'
        # Increase the value of num_sprouts_eaten
                    self.rat.num_sprouts_eaten += 1     
        # Decrease the value of num_sprouts_left
                    self.num_sprouts_left -= 1


OK, I'm using doctest. (BTW I wrote all the comments to make it easier for me)
This is what doctest returns:
Code: Select all
**********************************************************************
File "C:\Python33\a2.py", line 180, in __main__.Maze.move
Failed example:
    maze.rat_1.col
Expected:
    2
Got:
    1
**********************************************************************
File "C:\Python33\a2.py", line 184, in __main__.Maze.move
Failed example:
    maze.rat_2.num_sprouts_eaten
Expected:
    1
Got:
    0
**********************************************************************
File "C:\Python33\a2.py", line 186, in __main__.Maze.move
Failed example:
    maze.num_sprouts_left
Expected:
    2
Got:
    3
**********************************************************************
1 items had failures:
   3 of   8 in __main__.Maze.move
***Test Failed*** 3 failures.


And, I also fixed my get_character method:

Code: Select all
def get_character(self, row, col):
        ''' (Maze, int, int) -> str

        Return the character in the maze at the given row and column. If there is a rat at that location, then its character is returned.

        >>> maze = Maze([['#', '#', '#', '#', '#', '#', '#'], \
            ['#', '.', '.', '.', '.', '.', '#'], \
            ['#', '.', '#', '#', '#', '.', '#'], \
            ['#', '.', '.', '@', '#', '.', '#'], \
            ['#', '@', '#', '.', '@', '.', '#'], \
            ['#', '#', '#', '#', '#', '#', '#']], \
            Rat('J', 1, 1), \
            Rat('P', 1, 4))
        >>> Maze.get_character(maze, 4, 3)
        '.'
        >>> Maze.get_character(maze, 3, 4)
        '#'
        >>> Maze.get_character(maze, 3, 3)
        '@'
        >>> Maze.get_character(maze, 1, 1)
        'J'
        '''

        #Old code: if self.maze[self.rat_1.row][self.rat_1.col] == self.maze[row][col]:
        if self.rat_1.row == row and self.rat_1.col == col:
            return self.rat_1.symbol
        elif self.rat_2.row == row and self.rat_2.col == col:
            return self.rat_2.symbol
        elif self.maze[row][col] == HALL:
            return HALL
        elif self.maze[row][col] == WALL:
            return WALL
        elif self.maze[row][col] == SPROUT:
            return SPROUT


The rat won't actually move, and the sprout isn't eaten, AND the num_sprouts_left variable won't decrease.
I have actually put a lot of effort into this. I have been working on the code for about three weeks, 10 hours a week. I would really like help with this. Here is the original template:

Code: Select all

# Constants for the contents of the maze.

# The visual representation of a wall.
WALL = '#'

# The visual representation of a hallway.
HALL = '.'

# The visual representation of a brussels sprout.
SPROUT = '@'

# Constants for the directions. Use these to make Rats move.

# The left direction.
LEFT = -1

# The right direction.
RIGHT = 1

# No change in direction.
NO_CHANGE = 0

# The up direction.
UP = -1

# The down direction.
DOWN = 1

# The letters for rat_1 and rat_2 in the maze.
RAT_1_CHAR = 'J'
RAT_2_CHAR = 'P'


class Rat:
    """ A rat caught in a maze. """

    # Write your Rat methods here.

class Maze:
    """ A 2D maze. """

    # Write your Maze methods here.
Learn: How To Ask Questions The Smart Way
Join the #python-forum IRC channel on irc.freenode.net and chat with uns directly!
Kebap
 
Posts: 403
Joined: Thu Apr 04, 2013 1:17 pm
Location: Germany, Europe


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests